Microsoft Foundation Classes and Templates

The Microsoft Foundation Classes and Templates (MFC&T) provide tools to create small, lightweight controls, database applications, and full-featured, Windows desktop applications. All three libraries also provide support for COM.
Microsoft Foundation Class Library (MFC)
Active Template Library (ATL)
OLE DB Templates

Interesting home pages
Visual C++ Home The entire Visual C++ product.
Samples Sample programs from Visual C++ and the SDKs.


Microsoft Foundation Class Library

The MFC documentation includes a reference to the classes, global functions, global variables, and macros that make up the library, plus a collection of technical notes written by the MFC development team.
MFC Reference
MFC Technical Notes
MFC Sample Programs
Hierarchy chart
Hierarchy chart categories
About the MFC classes

Interesting home pages
Visual C++ Home
Adding User-Interface Features
Adding Program Functionality
Active Template Library (ATL)
OLE DB Templates


Class Library Reference

The Class Library Reference covers the classes, global functions, global variables, and macros that make up the Microsoft® Foundation Class Library, version 6.0. The class hierarchy chart details the class relationships in the class library.

The Class Library Overview lists the classes in helpful categories. Use these lists to help locate a class that contains the functionality you are interested in. Visual C++ Programmer's Guide explains how to use the class library to program for Microsoft Windows NT®, Microsoft Windows® 95, and other Win32® platforms. Practical examples and techniques are supplied in the tutorials in Visual C++/MFC Tutorials.

The remainder of the Class Library Reference consists of an alphabetical listing of the classes and an MFC Macros and Globals section that explains the global functions, global variables, and macros used with the class library.

The individual hierarchy charts included with each class are useful for locating base classes. The Class Library Reference usually does not describe inherited member functions, inherited operators, and overridden virtual member functions. For information on these functions, refer to the base classes depicted in the hierarchy diagrams.

In the alphabetical listing section, each class description includes a member summary by category, followed by alphabetical listings of member functions, overloaded operators, and data members.

Public and protected class members are documented only when they are normally used in application programs or derived classes. Occasionally, private members are listed because they override a public or protected member in the base class. See the class header files for a complete listing of class members.

Some C-language structures defined by Windows are so widely applicable that their descriptions have been reproduced completely in a section following the alphabetical reference.

Please note that the “See Also” sections refer to Win32 API functions by prefacing them with the scope resolution operator (::), for example, ::EqualRect. More information on these functions can be found in the Win32 SDK documentation.


Hierarchy Chart

See Also Hierarchy Chart Categories, About the Microsoft Foundation Classes


Hierarchy Chart Categories

See the Hierarchy Chart to view the classes in each category listed above.


Class Library Overview

This overview categorizes and describes the classes in the Microsoft Foundation Class Library (MFC) version 6.0. The classes in MFC, taken together, constitute an “application framework” — the framework of an application written for the Windows API. Your programming task is to fill in the code that is specific to your application.


About the Microsoft Foundation Classes

The library’s classes are presented here in the following categories:

  • Root Class: CObject

  • MFC Application Architecture Classes
    • Application and Thread Support Classes

    • Command Routing Classes

    • Document Classes

    • View Classes (Architecture)

    • Frame Window Classes (Architecture)

    • Document-Template Classes
  • Window, Dialog, and Control Classes
    • Frame Window Classes (Windows)

    • View Classes (Windows)

    • Dialog Box Classes

    • Control Classes

    • Control Bar Classes
  • Drawing and Printing Classes
    • Output (Device Context) Classes

    • Drawing Tool Classes
  • Simple Data Type Classes

  • Array, List, and Map Classes
    • Template Classes for Arrays, Lists, and Maps

    • Ready-to-Use Array Classes

    • Ready-to-Use List Classes

    • Ready-to-Use Map Classes
  • File and Database Classes
    • File I/O Classes

    • DAO Classes

    • ODBC Classes
  • Internet and Networking Classes
    • ISAPI Classes

    • Windows Sockets Classes

    • Win32 Internet Classes
  • OLE Classes
    • OLE Container Classes

    • OLE Server Classes

    • OLE Drag-and-Drop and Data Transfer Classes

    • OLE Common Dialog Classes

    • OLE Automation Classes

    • OLE Control Classes

    • Active Document Classes

    • OLE-Related Classes
  • Debugging and Exception Classes
    • Debugging Support Classes

    • Exception Classes

The section General Class Design Philosophy explains how the Microsoft Foundation Class Library was designed.

The framework is explained in detail in the Visual C++ Programmer's Guide. (See Using the Classes to Write Applications for Windows, for an overview.) Some of the classes listed above are general-purpose classes that can be used outside of the framework.and provide useful abstractions such as collections, exceptions, files, and strings.

To see the inheritance of a class, use the Class Hierarchy Chart.

In addition to the classes listed in this overview, the Microsoft Foundation Class Library contains a number of global functions, global variables, and macros. There is an overview and detailed listing of these in the section MFC Macros and Globals, which follows the alphabetical reference to the MFC classes.


General Class Design Philosophy

Microsoft Windows was designed long before the C++ language became popular. Because thousands of applications use the C-language Windows application programming interface (API), that interface will be maintained for the foreseeable future. Any C++ Windows interface must therefore be built on top of the procedural C-language API. This guarantees that C++ applications will be able to coexist with C applications.

The Microsoft Foundation Class Library is an object-oriented interface to Windows that meets the following design goals:

  • Significant reduction in the effort to write an application for Windows.

  • Execution speed comparable to that of the C-language API.

  • Minimum code size overhead.

  • Ability to call any Windows C function directly.

  • Easier conversion of existing C applications to C++.

  • Ability to leverage from the existing base of C-language Windows programming experience.

  • Easier use of the Windows API with C++ than with C.

  • Easier-to-use yet powerful abstractions of complicated features such as ActiveX, database support, printing, toolbars, and status bars.

  • True Windows API for C++ that effectively uses C++ language features.


The Application Framework

The core of the Microsoft Foundation Class Library is an encapsulation of a large portion of the Windows API in C++ form. Library classes represent windows, dialog boxes, device contexts, common GDI objects such as brushes and pens, controls, and other standard Windows items. These classes provide a convenient C++ member function interface to the structures in Windows that they encapsulate. For more about using these classes, see Window Object Topics in the Visual C++ Programmer's Guide.

But the Microsoft Foundation Class Library also supplies a layer of additional application functionality built on the C++ encapsulation of the Windows API. This layer is a working application framework for Windows that provides most of the common user interface expected of programs for Windows, including toolbars, status bars, printing, print preview, database support, and ActiveX support. Using the Classes to Write Applications for Windows in Visual C++ Programmer's Guide explains the framework in detail, and Visual C++Tutorials provides the Scribble tutorial, which teaches application-framework programming.


Relationship to the C-Language API

The single characteristic that sets the Microsoft Foundation Class Library apart from other class libraries for Windows is the very close mapping to the Windows API written in the C language. Further, you can generally mix calls to the class library freely with direct calls to the Windows API. This direct access does not, however, imply that the classes are a complete replacement for that API. Developers must still occasionally make direct calls to some Windows functions — SetCursor and GetSystemMetrics, for example. A Windows function is wrapped by a class member function only when there is a clear advantage to doing so.

Because you sometimes need to make native Windows function calls, you should have access to the C-language Windows API documentation. This documentation is included with Microsoft Visual C++™. Two useful books are Advanced Windows, by Jeffrey Richter, and Programming Windows 95, by Charles Petzold. Both are published by Microsoft Press®. Many of those books’ examples can be easily converted to the Microsoft Foundation classes. For examples and additional information about programming with the Microsoft Foundation Class Library, see Inside Visual C++ by David J. Kruglinski, also published by Microsoft Press.

Note For an overview of how the Microsoft Foundation Class Library framework operates, see Using the Classes to Write Applications for Windows in Visual C++ Programmer's Guide. The overview material is no longer located in the Class Library Reference.


Class Summary by Category

The following is a brief summary of the classes in the Microsoft Foundation Class Library, divided by category to help you locate what you need. In some cases, a class is listed in more than one category. To see the inheritance of a class, use the Class Hierarchy Chart.


Root Class: CObject

Most of the classes in the Microsoft Foundation Class Library are derived from a single base class at the root of the class hierarchy. CObject provides a number of useful capabilities to all classes derived from it, with very low overhead. For more information about CObject and its capabilities, see CObject Class Topics in Visual C++ Programmer's Guide.

CObject

The ultimate base class of most MFC classes. Supports serializing data and obtaining run-time information about a class.

CRuntimeClass

Structure used to determine the exact class of an object at run time.


MFC Application Architecture Classes

Classes in this category contribute to the architecture of a framework application. They supply functionality common to most applications. You fill in the framework to add application-specific functionality. Typically, you do so by deriving new classes from the architecture classes, then adding new members and/or overriding existing member functions.

AppWizard generates several types of applications, all of which use the application framework in differing ways. SDI (single document interface) and MDI (multiple document interface) applications make full use of a part of the framework called document/view architecture. Other types of applications, such as dialog-based applications, form-based applications, and DLLs, use only some of document/view architecture features.

Document/view applications contain one or more sets of documents, views, and frame windows. A document-template object associates the classes for each document/view/frame set.

Although you do not have to use document/view architecture in your MFC application, there are a number of advantages to doing so. MFC’s OLE container and server support is based on document/view architecture, as is support for printing and print preview.

All MFC applications have at least two objects: an application object derived from CWinApp, and some sort of main window object, derived (often indirectly) from CWnd. (Most often, the main window is derived from CFrameWnd, CMDIFrameWnd, or CDialog, all of which are derived from CWnd.)

Applications that use document/view architecture contain additional objects. The principal objects are as follows:

  • An application object derived from class CWinApp, as mentioned before.

  • One or more document class objects derived from class CDocument. Document class objects are responsible for the internal representation of the data manipulated in the view. They may be associated with a data file.

  • One or more view objects derived from class CView. Each view is a window that is attached to a document and associated with a frame window. Views display and manipulate the data contained in a document class object.

Document/view applications also contain frame windows (derived from CFrameWnd) and document templates (derived from CDocTemplate).


Application and Thread Support Classes

Each application has one and only one application object; this object coordinates other objects in the running program and is derived from CWinApp.

The Microsoft Foundation Class Library supports multiple threads of execution within an application. All applications must have at least one thread; the thread used by your CWinApp object is this “primary” thread.

CWinThread encapsulates a portion of the operating system’s threading capabilities. To make using multiple threads easier, MFC also provides synchronization object classes to provide a C++ interface to Win32 synchronization objects.

Application and Thread Classes

CWinApp

Encapsulates the code to initialize, run, and terminate the application. You will derive your application object from this class.

CWinThread

The base class for all threads. Use directly, or derive a class from CWinThread if your thread performs user-interface functions. CWinApp is derived from CWinThread.

ISAPI Application Classes

CHttpFilter

Filters selected HTTP requests sent to an ISAPI server.

CHttpServer

Extends the functionality of an ISAPI server by processing client requests.

Synchronization Object Classes

CSyncObject

Base class of the synchronization object classes.

CCriticalSection

A synchronization class that allows only one thread within a single process to access an object.

CSemaphore

A synchronization class that allows between one and a specified maximum number of simultaneous accesses to an object.

CMutex

A synchronization class that allows only one thread within any number of processes to access an object.

CEvent

A synchronization class that notifies an application when an event has occurred.

CSingleLock

Used in member functions of thread-safe classes to lock on one synchronization object.

CMultiLock

Used in member functions of thread-safe classes to lock on one or more synchronization objects from an array of synchronization objects.

Related Classes

CCommandLineInfo

Parses the command line with which your program was started.

CWaitCursor

Puts a wait cursor on the screen. Used during lengthy operations.

CDockState

Handles persistent storage of docking state data for control bars.

CRecentFileList

Maintains the most recently used (MRU) file list.


Command Routing Classes

As the user interacts with the application by choosing menus or control-bar buttons with the mouse, the application sends messages from the affected user-interface object to an appropriate command-target object. Command-target classes derived from CCmdTarget include CWinApp, CWnd, CDocTemplate, CDocument, CView, and the classes derived from them. The framework supports automatic command routing so that commands can be handled by the most appropriate object currently active in the application.

An object of class CCmdUI is passed to your command targets’ update command UI (ON_UPDATE_COMMAND_UI) handlers to allow you to update the state of the user interface for a particular command (for instance, to check or remove the check from menu items). You call member functions of the CCmdUI object to update the state of the UI object. This process is the same whether the UI object associated with a particular command is a menu item or a button or both.

CCmdTarget

Serves as the base class for all classes of objects that can receive and respond to messages.

CCmdUI

Provides a programmatic interface for updating user-interface objects such as menu items or control-bar buttons. The command target object enables, disables, checks, and/or clears the user-interface object via this object.


Document Classes

Document class objects, created by document-template objects, manage the application’s data. You will derive a class for your documents from one of these classes.

Document class objects interact with view objects. View objects represent the client area of a window, display a document’s data, and allow users to interact with it. Documents and views are created by a document-template object.

CDocument

The base class for application-specific documents. Derive your document class(es) from CDocument.

COleDocument

Used for compound document implementation, as well as basic container support. Serves as a container for classes derived from CDocItem. This class can be used as the base class for container documents and is the base class for COleServerDoc.

COleLinkingDoc

A class derived from COleDocument that provides the infrastructure for linking. You should derive the document classes for your container applications from this class instead of from COleDocument if you want them to support links to embedded objects.

CRichEditDoc

Maintains the list of OLE client items that are in the rich edit control. Used with CRichEditView and CRichEditCntrItem.

COleServerDoc

Used as the base class for server-application document classes. COleServerDoc objects provide the bulk of server support through interactions with COleServerItem objects. Visual editing capability is provided using the class library’s document/view architecture.

Related Classes

Document class objects can be persistent — in other words, they can write their state to a storage medium and read it back. MFC provides the CArchive class to facilitate transferring the document’s data to a storage medium.

CArchive

Cooperates with a CFile object to implement persistent storage for objects through serialization (see CObject::Serialize).

Documents can also contain OLE objects. CDocItem is the base class of the server and client items.

CDocItem

Abstract base class of COleClientItem and COleServerItem. Objects of classes derived from CDocItem represent parts of documents.


View Classes (Architecture)

CView and its derived classes are child windows that represent the client area of a frame window. Views show data and accept input for a document.

A view class is associated with a document class and a frame window class using a document-template object.

CView

The base class for application-specific views of a document’s data. Views display data and accept user input to edit or select the data. Derive your view class(es) from CView.

CScrollView

The base class for views with scrolling capabilities. Derive your view class from CScrollView for automatic scrolling.

Form and Record Views

Form views are also scrolling views. They are based on a dialog box template.

Record views are derived from form views. In addition to the dialog box template, they also have a connection to a database.

CFormView

A scroll view whose layout is defined in a dialog box template. Derive a class from CFormView to implement a user interface based on a dialog box template.

CDaoRecordView

Provides a form view directly connected to a Data Access Object (DAO) recordset object. Like all form views, a CDaoRecordView is based on a dialog box template.

CRecordView

Provides a form view directly connected to an Open Database Connectivity (ODBC) recordset object. Like all form views, a CRecordView is based on a dialog box template.

Control Views

Control views display a control as their view.

CCtrlView

The base class for all views associated with Windows controls. The views based on controls are described below.

CEditView

A view that contains a Windows standard edit control (see CEdit). Edit controls support text-editing, searching, replacing, and scrolling capabilities.

CRichEditView

A view that contains a Windows rich edit control (see CRichEditCtrl). In addition to the capabilities of an edit control, rich edit controls support fonts, colors, paragraph formatting, and embedded OLE objects.

CListView

A view that contains a Windows list control (see CListCtrl). A list control displays icons and strings in a manner similar to the right-hand pane of the Windows 95 Explorer.

CTreeView

A view that contains a Windows tree control (see CTreeCtrl). A tree control displays icons and strings arranged in a hierarchy in a manner similar to the left-hand pane of the Windows 95 Explorer.


Frame Window Classes (Architecture)

In document/view architecture, frame windows are windows that contain a view window. They also support having control bars attached to them.

In multiple document interface (MDI) applications, the main window is derived from CMDIFrameWnd. It indirectly contains the documents’ frames, which are CMDIChildWnd objects. The CMDIChildWnd objects, in turn, contain the documents’ views.

In single document interface (SDI) applications, the main window, derived from CFrameWnd, contains the view of the current document.

CFrameWnd

The base class for an SDI application’s main frame window. Also the base class for all other frame window classes.

CMDIFrameWnd

The base class for an MDI application’s main frame window.

CMDIChildWnd

The base class for an MDI application’s document frame windows.

COleIPFrameWnd

Provides the frame window for a view when a server document is being edited in place.


Document-Template Classes

Document-template objects coordinate the creation of document, view, and frame window objects when a new document and/or view is created.

CDocTemplate

The base class for document templates. You will never use this class directly; instead, you’ll use one of the other document-template classes derived from this class.

CMultiDocTemplate

A template for documents in the multiple document interface (MDI). MDI applications can have multiple documents open at a time.

CSingleDocTemplate

A template for documents in the single document interface (SDI). SDI applications have only one document open at a time.

Related Class

CCreateContext

A structure passed by a document template to window-creation functions to coordinate the creation of document, view, and frame-window objects.


Window, Dialog, and Control Classes

Class CWnd and its derived classes encapsulate an HWND, a handle to a Windows window. CWnd can be used by itself or as a base for deriving new classes. The derived classes supplied by the class library represent various kinds of windows.

CWnd

The base class for all windows. You can use one of the classes derived from CWnd or derive your own classes directly from it.


Frame Window Classes (Windows)

Frame windows are windows that frame an application or a part of an application. Frame windows usually contain other windows, such as views, tool bars, and status bars. In the case of CMDIFrameWnd, they may contain CMDIChildWnd objects indirectly.

CFrameWnd

The base class for an SDI application’s main frame window. Also the base class for all other frame window classes.

CMDIFrameWnd

The base class for an MDI application’s main frame window.

CMDIChildWnd

The base class for an MDI application’s document frame windows.

CMiniFrameWnd

A half-height frame window typically seen around floating toolbars.

COleIPFrameWnd

Provides the frame window for a view when a server document is being edited in place.

Related Class

Class CMenu provides an interface through which to access your application’s menus. It is useful for manipulating menus dynamically at run time; for example, when adding or deleting menu items according to context. Although menus are most often used with frame windows, they can also be used with dialog boxes and other nonchild windows.

CMenu

Encapsulates an HMENU handle to the application’s menu bar and pop-up menus.


View Classes (Windows)

CView and its derived classes are child windows that represent the client area of a frame window. Views show data and accept input for a document.

A view class is associated with a document class and a frame window class using a document-template object.

CView

The base class for application-specific views of a document’s data. Views display data and accept user input to edit or select the data. Derive your view class(es) from CView.

CScrollView

The base class for views with scrolling capabilities. Derive your view class from CScrollView for automatic scrolling.

Form and Record Views

Form views are also scrolling views. They are based on a dialog box template.

Record views are derived from form views. In addition to the dialog box template, they also have a connection to a database.

CFormView

A scroll view whose layout is defined in a dialog box template. Derive a class from CFormView to implement a user interface based on a dialog box template.

CDaoRecordView

Provides a form view directly connected to a Data Access Object (DAO) recordset object. Like all form views, a CDaoRecordView is based on a dialog box template.

CRecordView

Provides a form view directly connected to an Open Database Connectivity (ODBC) recordset object. Like all form views, a CRecordView is based on a dialog box template.

Control Views

Control views display a control as their view.

CCtrlView

The base class for all views associated with Windows controls. The views based on controls are described below.

CEditView

A view that contains a Windows standard edit control (see CEdit). Edit controls support text-editing, searching, replacing, and scrolling capabilities.

CRichEditView

A view that contains a Windows rich edit control (see CRichEditCtrl). In addition to the capabilities of an edit control, rich edit controls support fonts, colors, paragraph formatting, and embedded OLE objects.

CListView

A view that contains a Windows list control (see CListCtrl). A list control displays a collection of items, each consisting of an icon and a label, in a manner similar to the right-hand pane of the Windows 95 Explorer.

CTreeView

A view that contains a Windows tree control (see CTreeCtrl). A tree control displays a hierarchical list of icons and labels arranged in a manner similar to the left-hand pane of the Windows 95 Explorer.

Related Classes

CSplitterWnd allows you to have multiple views within a single frame window. CPrintDialog and CPrintInfo support the print and print preview ability of views. CRichEditDoc and CRichEditCntrItem are used with CRichEditView to implement OLE container capabilities.

CSplitterWnd

A window that the user can split into multiple panes. These panes can be resizable by the user or fixed size.

CPrintDialog

Provides a standard dialog box for printing a file.

CPrintInfo

A structure containing information about a print or print preview job. Used by CView’s printing architecture.

CRichEditDoc

Maintains the list of OLE client items that are in a CRichEditView.

CRichEditCntrItem

Provides client-side access to an OLE item stored in a CRichEditView.


Dialog Box Classes

Class CDialog and its derived classes encapsulate dialog-box functionality. Since a dialog box is a special kind of window, CDialog is derived from CWnd. Derive your dialog classes from CDialog or use one of the common dialog classes for standard dialog boxes, such as opening or saving a file, printing, selecting a font or color, initiating a search-and-replace operation, or performing various OLE-related operations.

CDialog

The base class for all dialog boxes — both modal and modeless.

CDataExchange

Supplies data exchange and validation information for dialog boxes.

Common Dialogs

These dialog box classes encapsulate the Windows common dialog boxes. They provide easy-to-use implementations of complicated dialog boxes.

CCommonDialog

This is the base class for all common dialog boxes.

CFileDialog

Provides a standard dialog box for opening or saving a file.

CColorDialog

Provides a standard dialog box for selecting a color.

CFontDialog

Provides a standard dialog box for selecting a font.

CFindReplaceDialog

Provides a standard dialog box for a search-and-replace operation.

CPrintDialog

Provides a standard dialog box for printing a file.

CPageSetupDialog

Encapsulates the services provided by the Windows common Page Setup dialog box with additional support for setting and modifying print margins.

OLE Common Dialogs

OLE adds several common dialog boxes to Windows. These classes encapsulate the OLE common dialog boxes.

COleDialog

Used by the framework to contain common implementations for all OLE dialog boxes. All dialog box classes in the user-interface category are derived from this base class. COleDialog cannot be used directly.

COleInsertDialog

Displays the Insert Object dialog box, the standard user interface for inserting new OLE linked or embedded items.

COlePasteSpecialDialog

Displays the Paste Special dialog box, the standard user interface for implementing the Edit Paste Special command.

COleLinksDialog

Displays the Edit Links dialog box, the standard user interface for modifying information about linked items.

COleChangeIconDialog

Displays the Change Icon dialog box, the standard user interface for changing the icon associated with an OLE embedded or linked item.

COleConvertDialog

Displays the Convert dialog box, the standard user interface for converting OLE items from one type to another.

COlePropertiesDialog

Encapsulates the Windows common OLE Properties dialog box. Common OLE Properties dialog boxes provide an easy way to display and modify the properties of an OLE document item in a manner consistent with Windows standards.

COleUpdateDialog

Displays the Update dialog box, the standard user interface for updating all links in a document. The dialog box contains a progress indicator to indicate how close the update procedure is to completion.

COleChangeSourceDialog

Displays the Change Source dialog box, the standard user interface for changing the destination or source of a link.

COleBusyDialog

Displays the Server Busy and Server Not Responding dialog boxes, the standard user interface for handling calls to busy applications. Usually displayed automatically by the COleMessageFilter implementation.

Property Sheet Classes

The property sheet classes allow your applications to use property sheets, also known as “tabbed dialogs.” Property sheets are an efficient way to organize a large number of controls in a single dialog box.

CPropertyPage

Provides the individual pages within a property sheet. Derive a class from CPropertyPage for each page to be added to your property sheet.

CPropertySheet

Provides the frame for multiple property pages. Derive your property sheet class from CPropertySheet to implement your property sheets quickly.

COlePropertyPage

Displays the properties of an OLE control in a graphical interface, similar to a dialog box.

Related Classes

These classes are not dialog boxes per se, but they use dialog box templates and have much of the behavior of dialog boxes.

CDialogBar

A control bar that is based on a dialog box template.

CFormView

A scroll view whose layout is defined in a dialog box template. Derive a class from CFormView to implement a user interface based on a dialog box template.

CDaoRecordView

Provides a form view directly connected to a Data Access Object (DAO) recordset object. Like all form views, a CDaoRecordView is based on a dialog box template.

CRecordView

Provides a form view directly connected to an Open Database Connectivity (ODBC) recordset object. Like all form views, a CRecordView is based on a dialog box template.

CPrintInfo

A structure containing information about a print or print preview job. Used by the printing architecture of CView.


Control Classes

Control classes encapsulate a wide variety of standard Windows controls ranging from static text controls to tree controls. In addition, MFC provides some new controls, including buttons with bitmaps and control bars.

The controls whose class names end in “Ctrl” are new in Windows 95 and Windows NT version 3.51.

Static Display Controls

CStatic

A static-display window. Static controls are used to label, box, or separate other controls in a dialog box or window. They may also display graphical images rather than text or a box.

Text Controls

CEdit

An editable-text control window. Edit controls are used to accept textual input from the user.

CRichEditCtrl

A control in which the user can enter and edit text. Unlike the control encapsulated in CEdit, a rich edit control supports character and paragraph formatting and OLE objects.

Controls Which Represent Numbers

CSliderCtrl

A control containing a slider, which the user moves to select a value or set of values.

CSpinButtonCtrl

A pair of arrow buttons the user can click to increment or decrement a value.

CProgressCtrl

Displays a rectangle that is gradually filled from left to right to indicate the progress of an operation.

CScrollBar

A scroll-bar control window. The class provides the functionality of a scroll bar, for use as a control in a dialog box or window, through which the user can specify a position within a range.

Buttons

CButton

A button control window. The class provides a programmatic interface for a pushbutton, check box, or radio button in a dialog box or window.

CBitmapButton

A button with a bitmap rather than a text caption.

Lists

CListBox

A list-box control window. A list box displays a list of items that the user can view and select.

CDragListBox

Provides the functionality of a Windows list box; allows the user to move list box items, such as filenames and string literals, within the list box. List boxes with this capability are useful for an item list in an order other than alphabetical, such as include pathnames or files in a project.

CComboBox

A combo-box control window. A combo box consists of an edit control plus a list box.

CCheckListBox

Displays a list of items with check boxes, which the user can check or clear, next to each item.

CListCtrl

Displays a collection of items, each consisting of an icon and a label, in a manner similar to the right-hand pane of the Windows 95 Explorer.

CTreeCtrl

Displays a hierarchical list of icons and labels arranged in a manner similar to the left-hand pane of the Windows 95 Explorer.

Toolbars and Status Bars

CToolBarCtrl

Provides the functionality of the Windows toolbar common control. Most MFC programs use CToolBar instead of this class.

CStatusBarCtrl

A horizontal window, usually divided into panes, in which an application can display status information. Most MFC programs use CStatusBar instead of this class.

Miscellaneous Controls

CAnimateCtrl

Displays a simple video clip.

CToolTipCtrl

A small pop-up window that displays a single line of text describing the purpose of a tool in an application.

CHeaderCtrl

Displays titles or labels for columns.

CTabCtrl

A control with tabs on which the user can click, analogous to the dividers in a notebook.

CHotKeyCtrl

Enables the user to create a “hot key” combination, which the user can press to perform an action quickly.

Related Classes

CImageList

Provides the functionality of the Windows image list. Image lists are used with list controls and tree controls. They can also be used to store and archive a set of same-sized bitmaps.

CCtrlView

The base class for all views associated with Windows controls. The views based on controls are described below.

CEditView

A view that contains a Windows standard edit control.

CRichEditView

A view that contains a Windows rich edit control.

CListView

A view that contains a Windows list control.

CTreeView

A view that contains a Windows tree control.


Control Bar Classes

Control bars are attached to a frame window. They contain buttons, status panes, or a dialog template. Free-floating control bars, also called tool palettes, are implemented by attaching them to a CMiniFrameWnd object.

Framework Control Bars

These control bars are an integral part of the MFC framework. They are easier to use and more powerful than the Windows control bars because they’re integrated with the framework. Most MFC applications use these control bars rather than the Windows control bars.

CControlBar

The base class for MFC control bars listed in this section. A control bar is a window aligned to the edge of a frame window. The control bar contains either HWND-based child controls or controls not based on an HWND, such as toolbar buttons.

CToolBar

Toolbar control windows that contain bitmap command buttons not based on an HWND. Most MFC applications use this class rather than CToolBarCtrl.

CStatusBar

The base class for status-bar control windows. Most MFC applications use this class rather than CStatusBarCtrl.

CDialogBar

A control bar that is based on a dialog box template.

Windows Control Bars

These control bars are thin wrappers for the corresponding Windows controls. Since they’re not integrated with the framework, they’re harder to use than the control bars listed above. Most MFC applications use the control bars listed above.

CStatusBarCtrl

A horizontal window, usually divided into panes, in which an application can display status information.

CToolBarCtrl

Provides the functionality of the Windows toolbar common control.

Related Classes

CToolTipCtrl

A small pop-up window that displays a single line of text describing the purpose of a tool in an application.

CDockState

Handles persistent storage of docking state data for control bars.


Drawing and Printing Classes

In Windows, all graphical output is drawn on a virtual drawing area called a device context (or DC). MFC provides classes to encapsulate the various types of DCs, as well as encapsulations for Windows drawing tools such as bitmaps, brushes, palettes, and pens.


Output (Device Context) Classes

These classes encapsulate the different types of device contexts available in Windows.

Most of the following classes encapsulate a handle to a Windows device context. A device context is a Windows object that contains information about the drawing attributes of a device such as a display or a printer. All drawing calls are made through a device-context object. Additional classes derived from CDC encapsulate specialized device-context functionality, including support for Windows metafiles.

CDC

The base class for device contexts. Used directly for accessing the whole display and for accessing nondisplay contexts such as printers.

CPaintDC

A display context used in OnPaint member functions of windows. Automatically calls BeginPaint on construction and EndPaint on destruction.

CClientDC

A display context for client areas of windows. Used, for example, to draw in an immediate response to mouse events.

CWindowDC

A display context for entire windows, including both the client and nonclient areas.

CMetaFileDC

A device context for Windows metafiles. A Windows metafile contains a sequence of graphics device interface (GDI) commands that can be replayed to create an image. Calls made to the member functions of a CMetaFileDC are recorded in a metafile.

Related Classes

CPoint

Holds coordinate (x, y) pairs.

CSize

Holds distance, relative positions, or paired values.

CRect

Holds coordinates of rectangular areas.

CRgn

Encapsulates a GDI region for manipulating an elliptical, polygonal, or irregular area within a window. Used in conjunction with the clipping member functions in class CDC.

CRectTracker

Displays and handles the user interface for resizing and moving rectangular objects.

CColorDialog

Provides a standard dialog box for selecting a color.

CFontDialog

Provides a standard dialog box for selecting a font.

CPrintDialog

Provides a standard dialog box for printing a file.


Drawing Tool Classes

These classes encapsulate drawing tools that are used to draw on a device context.

CGdiObject

The base class for GDI drawing tools.

CBrush

Encapsulates a GDI brush that can be selected as the current brush in a device context. Brushes are used for filling interiors of objects being drawn.

CPen

Encapsulates a GDI pen that can be selected as the current pen in a device context. Pens are used for drawing the border lines of objects.

CFont

Encapsulates a GDI font that can be selected as the current font in a device context.

CBitmap

Encapsulates a GDI bitmap, providing an interface for manipulating bitmaps.

CPalette

Encapsulates a GDI color palette for use as an interface between the application and a color output device such as a display.

CRectTracker

Displays and handles the user interface for resizing and moving rectangular objects.


Simple Data Type Classes

The following classes encapsulate drawing coordinates, character strings, and time and date information, allowing convenient use of C++ syntax. These objects are used widely as parameters to the member functions of Windows classes in the class library. Because CPoint, CSize, and CRect correspond to the POINT, SIZE, and RECT structures, respectively, in the Win32 SDK, you can use objects of these C++ classes wherever you can use these C-language structures. The classes provide useful interfaces through their member functions. CString provides very flexible dynamic character strings. CTime, COleDateTime, CTimeSpan, and COleTimeSpan represent time and date values. For more information about these classes, see the article Date and Time in Visual C++ Programmer's Guide.

The classes that begin with “COle” are encapsulations of data types provided by OLE. These data types can be used in Windows programs regardless of whether other OLE features are used.

CString

Holds character strings.

CTime

Holds absolute time and date values.

COleDateTime

Wrapper for the OLE automation type DATE. Represents date and time values.

CTimeSpan

Holds relative time and date values.

COleDateTimeSpan

Holds relative COleDateTime values, such as the difference between two COleDateTime values.

CPoint

Holds coordinate (x, y) pairs.

CSize

Holds distance, relative positions, or paired values.

CRect

Holds coordinates of rectangular areas.

CImageList

Provides the functionality of the Windows image list. Image lists are used with list controls and tree controls. They can also be used to store and archive a set of same-sized bitmaps.

COleVariant

Wrapper for the OLE automation type VARIANT. Data in VARIANTs can be stored in many formats.

COleCurrency

Wrapper for the OLE automation type CURRENCY, a fixed-point arithmetic type, with 15 digits before the decimal point and 4 digits after.


Array, List, and Map Classes

For handling aggregates of data, the class library provides a group of collection classes — arrays, lists, and “maps” — that can hold a variety of object and predefined types. The collections are dynamically sized. These classes can be used in any program, whether written for Windows or not. However, they are most useful for implementing the data structures that define your document classes in the application framework. You can readily derive specialized collection classes from these, or you can create them based on the template classes. For more information about these approaches, see the article Collections in Visual C++ Programmer's Guide and Template Classes for Arrays, Lists, and Maps in this overview for a list of the template collection classes.

Arrays are one-dimensional data structures that are stored contiguously in memory. They support very fast random access since the memory address of any given element can be calculated by multiplying the index of the element by the size of an element and adding the result to the base address of the array. But arrays are very expensive if you have to insert elements into the array, since the entire array past the element inserted has to be moved to make room for the element to be inserted. Arrays can grow and shrink as necessary.

Lists are similar to arrays but are stored very differently. Each element in a list also includes a pointer to the previous and next elements, making it a doubly-linked list. It’s very fast to add or delete items because doing so only involves changing a few pointers. However, searching a list can be expensive since all searches need to start at one of the list’s ends.

Maps relate a key value to a data value. For instance, the key of a map could be a string and the data a pointer into a list. You would ask the map to give you the pointer associated with a particular string. Map lookups are fast because maps use hash tables for key lookups. Adding and deleting items is also fast. Maps are often used with other data structures as auxiliary indices. MFC uses a special kind of map called a “ message map” to map Windows messages to a pointer to the handler function for that message.


Template Classes for Arrays, Lists, and Maps

These collection classes are templates whose parameters determine the types of the objects stored in the aggregates. The CArray, CMap, and CList classes use global helper functions that must usually be customized. For more information about these helper functions, see Collection Class Helpers in the “Macros and Globals” section. The typed pointer classes are “wrappers” for other classes in the class library. By using these wrappers, you enlist the compiler’s type-checking to help you avoid errors. For more information on using these classes, see the article Collections in Visual C++ Programmer's Guide.

These classes provide templates you can use to create arrays, lists, and maps using any type you like.

CArray

Template class for making arrays of arbitrary types.

CList

Template class for making lists of arbitrary types.

CMap

Template class for making maps with arbitrary key and value types.

CTypedPtrArray

Template class for type-safe arrays of pointers.

CTypedPtrList

Template class for type-safe lists of pointers.

CTypedPtrMap

Template class for type-safe maps with pointers.


Ready-to-Use Array Classes

CByteArray

Stores elements of type BYTE in an array.

CDWordArray

Stores elements of type DWORD in an array.

CObArray

Stores pointers to objects of class CObject or to objects of classes derived from CObject in an array.

CPtrArray

Stores pointers to void (generic pointers) in an array.

CUIntArray

Stores elements of type UINT in an array.

CWordArray

Stores elements of type WORD in an array.

CStringArray

Stores CString objects in an array.


Ready-to-Use List Classes

CObList

Stores pointers to objects of class CObject or to objects of classes derived from CObject in a linked list.

CPtrList

Stores pointers to void (generic pointers) in a linked list.

CStringList

Stores CString objects in a linked list.


Ready-to-Use Map Classes

CMapPtrToPtr

Uses void pointers as keys for finding other void pointers.

CMapPtrToWord

Uses void pointers as keys for finding data of type WORD.

CMapStringToOb

Uses CString objects as keys for finding CObject pointers.

CMapStringToPtr

Uses CString objects as keys for finding void pointers.

CMapStringToString

Uses CString objects as keys for finding other CString objects.

CMapWordToOb

Uses data of type WORD to find CObject pointers.

CMapWordToPtr

Uses data of type WORD to find void pointers.


File and Database Classes

These classes allow you to store information to a database or a disk file. There are two sets of database classes — DAO and ODBC — which provide similar functionality. The DAO group is implemented using the Data Access Object, while the ODBC group is implemented using Open Database Connectivity. There are also a set of classes for manipulating standard files, Active streams, and HTML streams.

The following categories of classes support data persistence.

  • File I/O Classes

  • DAO Classes

  • ODBC Classes


File I/O Classes

These classes provide an interface to traditional disk files, in-memory files, Active streams, and Windows sockets. All of the classes derived from CFile can be used with a CArchive object to perform serialization.

Use the following classes, particularly CArchive and CFile, if you write your own input/output processing. Normally you don’t need to derive from these classes. If you use the application framework, the default implementations of the Open and Save commands on the File menu will handle file I/O (using class CArchive), as long as you override your document’s Serialize function to supply details about how a document “serializes” its contents. For more information about the file classes and serialization, see the article Files in MFC and the article Serialization (Object Persistence) in Visual C++ Programmer's Guide.

CFile

Provides a file interface to binary disk files.

CStdioFile

Provides a CFile interface to buffered stream disk files, usually in text mode.

CMemFile

Provides a CFile interface to in-memory files.

CSharedFile

Provides a CFile interface to shared in-memory files.

COleStreamFile

Uses the COM IStream interface to provide CFile access to compound files.

CSocketFile

Provides a CFile interface to a Windows Socket.

Related Classes

CArchive

Cooperates with a CFile object to implement persistent storage for objects through serialization (see CObject::Serialize).

CArchiveException

An archive exception.

CFileException

A file-oriented exception.

CFileDialog

Provides a standard dialog box for opening or saving a file.

CHtmlStream

Handles caching HTML output. Functionally similar to CMemFile.

CRecentFileList

Maintains the most recently used (MRU) file list.


DAO Classes

These classes work with the other application framework classes to give easy access to DAO (Data Access Object) databases, which use the same database engine as Microsoft Visual Basic® and Microsoft Access. The DAO classes can also access a wide variety of databases for which Open Database Connectivity (ODBC) drivers are available.

Programs that use DAO databases will have at least a CDaoDatabase object and a CDaoRecordset object.

CDaoWorkspace

Manages a named, password-protected database session from login to logoff. Most programs use the default workspace.

CDaoDatabase

A connection to a database through which you can operate on the data.

CDaoRecordset

Represents a set of records selected from a data source.

CDaoRecordView

A view that displays database records in controls.

CDaoQueryDef

Represents a query definition, usually one saved in a database.

CDaoTableDef

Represents the stored definition of a base table or an attached table.

CDaoException

Represents an exception condition arising from the DAO classes.

CDaoFieldExchange

Supports the DAO record field exchange (DFX) routines used by the DAO database classes. You will normally not directly use this class.

Related Classes

CLongBinary

Encapsulates a handle to storage for a binary large object (or BLOB), such as a bitmap. CLongBinary objects are used to manage large data objects stored in database tables.

COleCurrency

Wrapper for the OLE automation type CURRENCY, a fixed-point arithmetic type, with 15 digits before the decimal point and 4 digits after.

COleDateTime

Wrapper for the OLE automation type DATE. Represents date and time values.

COleVariant

Wrapper for the OLE automation type VARIANT. Data in VARIANTs can be stored in many formats.


ODBC Classes

These classes work with the other application framework classes to give easy access to a wide variety of databases for which Open Database Connectivity (ODBC) drivers are available.

Programs that use ODBC databases will have at least a CDatabase object and a CRecordset object.

CDatabase

Encapsulates a connection to a data source, through which you can operate on the data source.

CRecordset

Encapsulates a set of records selected from a data source. Recordsets enable scrolling from record to record, updating records (adding, editing, and deleting records), qualifying the selection with a filter, sorting the selection, and parameterizing the selection with information obtained or calculated at run time.

CRecordView

Provides a form view directly connected to a recordset object. The dialog data exchange (DDX) mechanism exchanges data between the recordset and the controls of the record view. Like all form views, a record view is based on a dialog template resource. Record views also support moving from record to record in the recordset, updating records, and closing the associated recordset when the record view closes.

CDBException

An exception resulting from failures in data access processing. This class serves the same purpose as other exception classes in the exception-handling mechanism of the class library.

CFieldExchange

Supplies context information to support record field exchange (RFX), which exchanges data between the field data members and parameter data members of a recordset object and the corresponding table columns on the data source. Analogous to class CDataExchange, which is used similarly for dialog data exchange (DDX).

Related Classes

CLongBinary

Encapsulates a handle to storage for a binary large object (or BLOB), such as a bitmap. CLongBinary objects are used to manage large data objects stored in database tables.

CDBVariant

Allows you to store a value without worrying about the value’s data type. CDBVariant tracks the data type of the current value, which is stored in a union.


Internet and Networking Classes

These classes allow you to exchange information with another computer using ISAPI or a Windows Socket. There are also a set of classes for creating ISAPI extension DLLs and a set of classes for manipulating Windows Sockets.

The following categories of classes support connectivity.

  • ISAPI Classes

  • Windows Sockets Classes

  • Win32 Internet Classes


ISAPI Classes

ISAPI describes an interface for Internet servers. An example of an ISAPI server is Windows NT Server running Microsoft Internet Information Server (IIS).

HTTP filters handle server requests. They can be used to handle the following types of applications:

  • Custom authentication schemes

  • Data compression

  • Encryption

  • Logging

Filter Classes

CHttpFilter

Filters selected HTTP requests sent to an ISAPI server.

CHttpFilterContext

Manages the context for an HTTP filter. This is a helper class to handle multiple, concurrent requests of a CHttpFilter object.

Server Classes

ISAPI server extensions process server requests. MFC ISAPI classes will not process requests from a Common Gateway Interface (CGI).

CHttpServer

Extends the functionality of an ISAPI server by processing client requests.

CHttpServerContext

Manages the context for an ISAPI server extension. This is a helper class to handle multiple, concurrent requests of a CHttpServer object.

Related Classes

CHtmlStream

Handles caching HTML output. Functionally similar to CMemFile.


Windows Sockets Classes

Windows Sockets provide a network protocol-independent way to communicate between two computers. These sockets can be synchronous (your program waits until the communication is done) or asynchronous (your program continues running while the communication is going on).

CAsyncSocket

Encapsulates the Windows Sockets API in a thin wrapper.

CSocket

Higher-level abstraction derived from CAsyncSocket. It operates synchronously.

CSocketFile

Provides a CFile interface to a Windows Socket.


Win32 Internet Classes

MFC wraps the Win32 Internet (WinInet) and ActiveX technology to make Internet programming easier.

CInternetSession

Creates and initializes one Internet session or several simultaneous Internet sessions and, if necessary, describes the connection to a proxy server.

CInternetConnection

Manages your connection to an Internet server.

CInternetFile

This class and its derived classes allow access to files on remote systems that use Internet protocols.

CHttpConnection

Manages your connection to an HTTP server.

CHttpFile

Provides the functionality to find and read files on an HTTP server.

CGopherFile

Provides the functionality to find and read files on a gopher server.

CFtpConnection

Manages your connection to an FTP server.

CGopherConnection

Manages your connection to a gopher server.

CFileFind

Performs local and Internet file searches.

CFtpFileFind

Aids in Internet file searches of FTP servers.

CGopherFileFind

Aids in Internet file searches of gopher servers.

CGopherLocator

Gets a gopher "locator" from a gopher server, determines the locator's type, and makes the locator available to CGopherFileFind.

CInternetException

Represents an exception condition related to an Internet operation.


OLE Classes

The OLE classes work with the other application framework classes to provide easy access to the ActiveX API, giving your programs an easy way to provide the power of ActiveX to your users. Using ActiveX, you can:

  • Create compound documents, which allow users to create and edit documents containing data created by multiple applications, including text, graphics, spreadsheets, sound, or other types of data.

  • Create OLE objects that can be embedded in compound documents.

  • Use OLE drag and drop to copy data between applications.

  • Use Automation to control one program with another.

  • Create ActiveX controls and ActiveX control containers (formerly called OLE controls and OLE control containers, respectively).

The following categories of classes support ActiveX:

  • OLE Container Classes

  • OLE Server Classes

  • OLE Drag-and-Drop and Data Transfer Classes

  • OLE Common Dialog Classes

  • OLE Automation Classes

  • OLE Control Classes

  • Active Document Classes

  • OLE-Related Classes

To see the inheritance of a class, use the Class Hierarchy Chart.


OLE Container Classes

These classes are used by container applications. Both COleLinkingDoc and COleDocument manage collections of COleClientItem objects. Rather than deriving your document class from CDocument, you’ll derive it from COleLinkingDoc or COleDocument, depending on whether or not you want support for links to objects embedded in your document.

Use a COleClientItem object to represent each OLE item in your document that is embedded from another document or is a link to another document.

COleDocument

Used for compound document implementation, as well as basic container support. Serves as a container for classes derived from CDocItem. This class can be used as the base class for container documents and is the base class for COleServerDoc.

COleLinkingDoc

A class derived from COleDocument that provides the infrastructure for linking. You should derive the document classes for your container applications from this class instead of from COleDocument if you want them to support links to embedded objects.

CRichEditDoc

Maintains the list of OLE client items that are in the rich edit control. Used with CRichEditView and CRichEditCntrItem.

CDocItem

Abstract base class of COleClientItem and COleServerItem. Objects of classes derived from CDocItem represent parts of documents.

COleClientItem

A client item class that represents the client’s side of the connection to an embedded or linked OLE item. Derive your client items from this class.

CRichEditCntrItem

Provides client-side access to an OLE item stored in a rich edit control when used with CRichEditView and CRichEditDoc.

COleException

An exception resulting from a failure in OLE processing. This class is used by both containers and servers.


OLE Server Classes

These classes are used by server applications. Server documents are derived from COleServerDoc rather than CDocument. Note that since COleServerDoc is derived from COleLinkingDoc, server documents can also be containers that support linking.

The COleServerItem class represents a document or portion of a document that can be embedded in another document or linked to.

COleIPFrameWnd and COleResizeBar support in-place editing while the object is in a container, and COleTemplateServer supports creation of document/view pairs so OLE objects from other applications can be edited.

COleServerDoc

Used as the base class for server-application document classes. COleServerDoc objects provide the bulk of server support through interactions with COleServerItem objects. Visual editing capability is provided using the class library’s document/view architecture.

CDocItem

Abstract base class of COleClientItem and COleServerItem. Objects of classes derived from CDocItem represent parts of documents.

COleServerItem

Used to represent the OLE interface to COleServerDoc items. There is usually one COleServerDoc object, which represents the embedded part of a document. In servers that support links to parts of documents, there can be many COleServerItem objects, each of which represents a link to a portion of the document.

COleIPFrameWnd

Provides the frame window for a view when a server document is being edited in place.

COleResizeBar

Provides the standard user interface for in-place resizing. Objects of this class are always used in conjunction with COleIPFrameWnd objects.

COleTemplateServer

Used to create documents using the framework’s document/view architecture. A COleTemplateServer object delegates most of its work to an associated CDocTemplate object.

COleException

An exception resulting from a failure in OLE processing. This class is used by both containers and servers.


OLE Drag-and-Drop and Data Transfer Classes

These classes are used in OLE data transfers. They allow data to be transferred between applications by using the Clipboard or through drag and drop.

COleDropSource

Controls the drag-and-drop operation from start to finish. This class determines when the drag operation starts and when it ends. It also displays cursor feedback during the drag-and-drop operation.

COleDataSource

Used when an application provides data for a data transfer. COleDataSource could be viewed as an object-oriented Clipboard object.

COleDropTarget

Represents the target of a drag-and-drop operation. A COleDropTarget object corresponds to a window on screen. It determines whether to accept any data dropped onto it and implements the actual drop operation.

COleDataObject

Used as the receiver side to COleDataSource. COleDataObject objects provide access to the data stored by a COleDataSource object.


OLE Common Dialog Classes

These classes handle common OLE tasks by implementing a number of standard OLE dialog boxes. They also provide a consistent user interface for OLE functionality.

COleDialog

Used by the framework to contain common implementations for all OLE dialog boxes. All dialog box classes in the user-interface category are derived from this base class. COleDialog cannot be used directly.

COleInsertDialog

Displays the Insert Object dialog box, the standard user interface for inserting new OLE linked or embedded items.

COlePasteSpecialDialog

Displays the Paste Special dialog box, the standard user interface for implementing the Edit Paste Special command.

COleLinksDialog

Displays the Edit Links dialog box, the standard user interface for modifying information about linked items.

COleChangeIconDialog

Displays the Change Icon dialog box, the standard user interface for changing the icon associated with an OLE embedded or linked item.

COleConvertDialog

Displays the Convert dialog box, the standard user interface for converting OLE items from one type to another.

COlePropertiesDialog

Encapsulates the Windows common OLE Properties dialog box. Common OLE Properties dialog boxes provide an easy way to display and modify the properties of an OLE document item in a manner consistent with Windows standards.

COleUpdateDialog

Displays the Update dialog box, the standard user interface for updating all links in a document. The dialog box contains a progress indicator to indicate how close the update procedure is to completion.

COleChangeSourceDialog

Displays the Change Source dialog box, the standard user interface for changing the destination or source of a link.

COleBusyDialog

Displays the Server Busy and Server Not Responding dialog boxes, the standard user interface for handling calls to busy applications. Usually displayed automatically by the COleMessageFilter implementation.


OLE Automation Classes

These classes support automation clients (applications that control other applications). Automation servers (applications that can be controlled by other applications) are supported through dispatch maps.

COleDispatchDriver

Used to call automation servers from your automation client. ClassWizard uses this class to create type-safe classes for automation servers that provide a type library.

COleDispatchException

An exception resulting from an error during OLE automation. Automation exceptions are thrown by automation servers and caught by automation clients.


OLE Control Classes

These are the primary classes you’ll use when writing OLE controls. The COleControlModule class in an OLE control module is like the CWinApp class in an application. Each module implements one or more OLE controls; these controls are represented by COleControl objects. These controls communicate with their containers using CConnectionPoint objects.

The CPictureHolder and CFontHolder classes encapsulate COM interfaces for pictures and fonts, while the COlePropertyPage and CPropExchange classes help you implement property pages and property persistence for your control.

COleControlModule

Replaces the CWinApp class for your OLE control module. Derive from the COleControlModule class to develop an OLE control module object. It provides member functions for initializing your OLE control’s module.

COleControl

Derive from the COleControl class to develop an OLE control. Derived from CWnd, this class inherits all the functionality of a Windows window object plus additional OLE-specific functionality, such as event firing and the ability to support methods and properties.

CConnectionPoint

The CConnectionPoint class defines a special type of interface used to communicate with other OLE objects, called a “connection point.” A connection point implements an outgoing interface that is able to initiate actions on other objects, such as firing events and change notifications.

CPictureHolder

Encapsulates the functionality of a Windows picture object and the IPicture COM interface; used to implement the custom Picture property of an OLE control.

CFontHolder

Encapsulates the functionality of a Windows font object and the IFont COM interface; used to implement the stock Font property of an OLE control.

COlePropertyPage

Displays the properties of an OLE control in a graphical interface, similar to a dialog box.

CPropExchange

Supports the implementation of property persistence for your OLE controls. Analogous to CDataExchange for dialog boxes.

CMonikerFile

Takes a moniker, or a string representation that it can make into a moniker, and binds it synchronously to the stream for which the moniker is a name.

CAsyncMonikerFile

Works similarly to CMonikerFile; however, it binds the moniker asynchronously to the stream for which the moniker is a name.

CDataPathProperty

Implements an OLE control property that can be loaded asynchronously.

CCachedDataPathProperty

Implements an OLE control property transferred asynchronously and cached in a memory file.

COleCmdUI

Allows an Active document to receive commands that originate in its container's user interface (such as FileNew, Open, Print, and so on), and allows a container to receive commands that originate in the Active document's user interface.

COleSafeArray

Works with arrays of arbitrary type and dimension.


Active Document Classes

Active documents can be displayed either in the entire client window of a Web browser, such as Internet Explorer 3.0, or in an Active container—such as the Microsoft Office Binder—that supports Active documents.

CDocObjectServer

Maps the Active document interfaces, and initializes and activates an Active document object.

CDocObjectServerItem

Implements OLE server verbs specifically for Active document servers.

COleDocObjectItem

Implements Active document containment.


OLE-Related Classes

These classes provide a number of different services, ranging from exceptions to file input and output.

COleObjectFactory

Used to create items when requested from other containers. This class serves as the base class for more specific types of factories, including COleTemplateServer.

COleMessageFilter

Used to manage concurrency with OLE Lightweight Remote Procedure Calls (LRPC).

COleStreamFile

Uses the COM IStream interface to provide CFile access to compound files. This class (derived from CFile) enables MFC serialization to use OLE structured storage.

CRectTracker

Used to allow moving, resizing, and reorientation of in-place items.


Debugging and Exception Classes

These classes provide support for debugging dynamic memory allocation and for passing exception information from the function where the exception is thrown to the function where it's caught.

Use classes CDumpContext and CMemoryState during development to assist with debugging, as described in MFC Debugging Support. Use CRuntimeClass to determine the class of any object at run time, as described in the article CObject Class: Accessing Run-Time Class Information. Both articles are in Visual C++ Programmer's Guide. The framework uses CRuntimeClass to create objects of a particular class dynamically.


Debugging Support Classes

MFC provides the following classes to help you debug dynamic memory allocation problems.

CDumpContext

Provides a destination for diagnostic dumps.

CMemoryState

Structure that provides snapshots of memory use. Also used to compare earlier and later memory snapshots.


Exception Classes

The class library provides an exception-handling mechanism based on class CException. The application framework uses exceptions in its code; you can also use them in yours. For more information, see the article Exceptions in Visual C++ Programmer's Guide. You can derive your own exception types from CException.

MFC provides an exception class from which you can derive your own exception as well as exception classes for all of the exceptions it supports.

CException

The base class for exceptions.

CArchiveException

An archive exception.

CDaoException

An exception resulting from a failure in a DAO database operation.

CDBException

An exception resulting from a failure in ODBC database processing.

CFileException

A file-oriented exception.

CMemoryException

An out-of-memory exception.

CNotSupportedException

An exception resulting from using an unsupported feature.

COleException

An exception resulting from a failure in OLE processing. This class is used by both containers and servers.

COleDispatchException

An exception resulting from an error during automation. Automation exceptions are thrown by automation servers and caught by automation clients.

CResourceException

An exception resulting from a failure to load a Windows resource.

CUserException

An exception used to stop a user-initiated operation. Typically the user has been notified of the problem before this exception is thrown.


CAnimateCtrl

The CAnimateCtrl class provides the functionality of the Windows common animation control. This control (and therefore the CAnimateCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

An animation control is a rectangular window that displays a clip in AVI (Audio Video Interleaved) format— the standard Windows video/audio format. An AVI clip is a series of bitmap frames, like a movie.

Animation controls can play only simple AVI clips. Specifically, the clips to be played by an animation control must meet the following requirements:

  • There must be exactly one video stream and it must have at least one frame.

  • There can be at most two streams in the file (typically the other stream, if present, is an audio stream, although the animation control ignores audio information).

  • The clip must either be uncompressed or compressed with RLE8 compression.

  • No palette changes are allowed in the video stream.

You can add the AVI clip to your application as an AVI resource, or it can accompany your application as a separate AVI file.

Since your thread continues executing while the AVI clip is displayed, one common use for an animation control is to indicate system activity during a lengthy operation. For example, the Find dialog box of the Windows 95 Explorer displays a moving magnifying glass as the system searches for a file.

If you create a CAnimateCtrl object within a dialog box or from a dialog resource using the dialog editor, it will be automatically destroyed when the user closes the dialog box.

If you create a CAnimateCtrl object within a window, you may need to destroy it. If you create the CAnimateCtrl object on the stack, it is destroyed automatically. If you create the CAnimateCtrl object on the heap by using the new function, you must call delete on the object to destroy it. If you derive a new class from CAnimateCtrl and allocate any memory in that class, override the CAnimateCtrl destructor to dispose of the allocations.

For more information on using CAnimateCtrl, see Control Topics and Using CAnimateCtrl in the Visual C++ Programmer's Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CMNCTRL1 | MFC Sample MFCIE

See Also Animation Control Styles in CAnimateCtrl::Create, ON_CONTROL


CAnimateCtrl Class Members

Construction

CAnimateCtrl Constructs a CAnimateCtrl object.

Initialization

Create Creates an animation control and attaches it to a CAnimateCtrl object.

Operations

Open | Opens an AVI clip from a file or resource and displays the first frame.
Play | Plays the AVI clip without sound.
Seek | Displays a selected single frame of the AVI clip.
Stop | Stops playing the AVI clip.
Close | Closes the AVI clip that was previously opened.


Member Functions


CAnimateCtrl::CAnimateCtrl

CAnimateCtrl( );

Remarks

Constructs a CAnimateCtrl object. You must call the Create member function before you can perform any other operations on the object you create.

CAnimateCtrl Overview | Class Members | Hierarchy Chart

See Also CAnimateCtrl::Create


CAnimateCtrl::Close

BOOL Close( );

Return Value

Nonzero if successful; otherwise zero.

Remarks

Use the Close member function to close the AVI clip that was previously opened in the animation control (if any) and remove it from memory.

CAnimateCtrl Overview | Class Members | Hierarchy Chart

See Also CAnimateCtrl::Open


CAnimateCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise zero.

Parameters

dwStyle

Specifies the animation control’s style. Apply any combination of the window and animation control styles described under Remarks to the control.

rect

Specifies the animation control’s position and size. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the animation control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the animation control’s ID.

Remarks

You construct a CAnimateCtrl in two steps. First call the constructor, then call Create, which creates the animation control and attaches it to the CAnimateCtrl object.

Apply the following window styles to an animation control.

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

In addition to the window styles listed above, you may want to apply one or more of the following animation control styles to an animation control:

  • ACS_CENTER Centers the AVI clip in the animation control’s window and leaves the animation control’s size and position unchanged when the AVI clip is opened. If this style is not specified, the control will be resized when the AVI clip is opened to the size of the images in the AVI clip.

  • ACS_TRANSPARENT Causes the AVI clip to be drawn using a transparent background rather than the background color specified in the AVI clip.

  • ACS_AUTOPLAY Causes the AVI clip to start playing as soon as it is opened. When the clip is done playing, it will automatically be repeated.

CAnimateCtrl Overview | Class Members | Hierarchy Chart

See Also CAnimateCtrl::CAnimateCtrl, CAnimateCtrl::Open, CAnimateCtrl::Play, CAnimateCtrl::Seek


CAnimateCtrl::Open

BOOL Open( LPCTSTR lpszFileName );

BOOL Open( UINT nID );

Return Value

Nonzero if successful; otherwise zero.

Parameters

lpszFileName

A CString object or a pointer to a null-terminated string that contains either the name of the AVI file or the name of an AVI resource. If this parameter is NULL, the system closes the AVI clip that was previously opened for the animation control, if any.

nID

The AVI resource identifier. If this parameter is NULL, the system closes the AVI clip that was previously opened for the animation control, if any.

Remarks

Call this function to open an AVI clip and display its first frame.

If the animation control has the ACS_AUTOPLAY style, the animation control will automatically start playing the clip immediately after it opens it. It will continue to play the clip in the background while your thread continues executing. When the clip is done playing, it will automatically be repeated.

If the animation control has the ACS_CENTER style, the AVI clip will be centered in the control and the size of the control will not change. If the animation control does not have the ACS_CENTER style, the control will be resized when the AVI clip is opened to the size of the images in the AVI clip. The position of the top left corner of the control will not change, only the size of the control.

If the animation control has the ACS_TRANSPARENT style, the first frame will be drawn using a transparent background rather than the background color specified in the animation clip.

CAnimateCtrl Overview | Class Members | Hierarchy Chart

See Also CAnimateCtrl::Close, CAnimateCtrl::Create


CAnimateCtrl::Play

BOOL Play( UINT nFrom, UINT nTo, UINT nRep );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nFrom

Zero-based index of the frame where playing begins. Value must be less than 65,536. A value of 0 means begin with the first frame in the AVI clip.

nTo

Zero-based index of the frame where playing ends. Value must be less than 65,536. A value of – 1 means end with the last frame in the AVI clip.

nRep

Number of times to replay the AVI clip. A value of – 1 means replay the file indefinitely.

Remarks

Call this function to play an AVI clip in an animation control. The animation control will play the clip in the background while your thread continues executing. If the animation control has ACS_TRANSPARENT style, the AVI clip will be played using a transparent background rather than the background color specified in the animation clip.

CAnimateCtrl Overview | Class Members | Hierarchy Chart

See Also CAnimateCtrl::Open, CAnimateCtrl::Stop, CAnimateCtrl::Seek, CAnimateCtrl::Create


CAnimateCtrl::Seek

BOOL Seek( UINT nTo );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nTo

Zero-based index of the frame to display. Value must be less than 65,536. A value of 0 means display the first frame in the AVI clip. A value of – 1 means display the last frame in the AVI clip.

Remarks

Call this function to statically display a single frame of your AVI clip. If the animation control has ACS_TRANSPARENT style, the AVI clip will be drawn using a transparent background rather than the background color specified in the animation clip.

CAnimateCtrl Overview | Class Members | Hierarchy Chart

See Also CAnimateCtrl::Open, CAnimateCtrl::Play, CAnimateCtrl::Create


CAnimateCtrl::Stop

BOOL Stop( );

Return Value

Nonzero if successful; otherwise zero.

Remarks

Call this function to stop playing an AVI clip in an animation control.

CAnimateCtrl Overview | Class Members | Hierarchy Chart

See Also CAnimateCtrl::Play


CArchive

CArchive does not have a base class.

The CArchive class allows you to save a complex network of objects in a permanent binary form (usually disk storage) that persists after those objects are deleted. Later you can load the objects from persistent storage, reconstituting them in memory. This process of making data persistent is called “serialization.”

You can think of an archive object as a kind of binary stream. Like an input/output stream, an archive is associated with a file and permits the buffered writing and reading of data to and from storage. An input/output stream processes sequences of ASCII characters, but an archive processes binary object data in an efficient, nonredundant format.

You must create a CFile object before you can create a CArchive object. In addition, you must ensure that the archive’s load/store status is compatible with the file’s open mode. You are limited to one active archive per file.

When you construct a CArchive object, you attach it to an object of class CFile (or a derived class) that represents an open file. You also specify whether the archive will be used for loading or storing. A CArchive object can process not only primitive types but also objects of CObject-derived classes designed for serialization. A serializable class usually has a Serialize member function, and it usually uses the DECLARE_SERIAL and IMPLEMENT_SERIAL macros, as described under class CObject.

The overloaded extraction (>>) and insertion (<<) operators are convenient archive programming interfaces that support both primitive types and CObject-derived classes.

CArchive also supports programming with the MFC Windows Sockets classes CSocket and CSocketFile. The IsBufferEmpty member function supports that usage.

For more information on CArchive, see the articles Serialization (Object Persistence) and Windows Sockets: Using Sockets with Archives in Visual C++ Programmer's Guide.

#include <afx.h>

Class Members | Hierarchy Chart

Sample MFC Sample MULTIPAD

See Also CFile, CObject, CSocket, CSocketFile


CArchive Class Members

Data Members

m_pDocument Points to the CDocument object being serialized.

Construction

CArchive | Creates a CArchive object.
Abort | Closes an archive without throwing an exception.
Close | Flushes unwritten data and disconnects from the CFile.

Basic Input/Output

Flush | Flushes unwritten data from the archive buffer.
operator >> | Loads objects and primitive types from the archive.
operator << | Stores objects and primitive types to the archive.
Read | Reads raw bytes.
Write | Writes raw bytes.
WriteString | Writes a single line of text.
ReadString | Reads a single line of text.

Status

GetFile | Gets the CFile object pointer for this archive.
GetObjectSchema | Called from the Serialize function to determine the version of the object that is being deserialized.
SetObjectSchema | Sets the object schema stored in the archive object.
IsLoading | Determines whether the archive is loading.
IsStoring | Determines whether the archive is storing.
IsBufferEmpty | Determines whether the buffer has been emptied during a Windows Sockets receive process.

Object Input/Output

ReadObject | Calls an object’s Serialize function for loading.
WriteObject | Calls an object’s Serialize function for storing.
MapObject | Places objects in the map that are not serialized to the file, but that are available for subobjects to reference.
SetStoreParams | Sets the hash table size and the block size of the map used to identify unique objects during the serialization process.
SetLoadParams | Sets the size to which the load array grows. Must be called before any object is loaded or before MapObject or ReadObject is called.
ReadClass | Reads a class reference previously stored with WriteClass.
WriteClass | Writes a reference to the CRuntimeClass to the CArchive.
SerializeClass | Reads or writes the class reference to the CArchive object depending on the direction of the CArchive.


CArchive::Abort

void Abort ( );

Remarks

Call this function to close the archive without throwing an exception. The CArchive destructor will normally call Close, which will flush any data that has not been saved to the associated CFile object. This can cause exceptions.

When catching these exceptions, it is a good idea to use Abort, so that destructing the CArchive object doesn't cause further exceptions. When handling exceptions, CArchive::Abort will not throw an exception on failures because, unlike CArchive::Close, Abort ignores failures.

If you used new to allocate the CArchive object on the heap, then you must delete it after closing the file.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::Close, CFile::Close


CArchive::CArchive

CArchive( CFile* pFile, UINT nMode, int nBufSize = 4096, void* lpBuf = NULL );
throw( CMemoryException, CArchiveException, CFileException );

Parameters

pFile

A pointer to the CFile object that is the ultimate source or destination of the persistent data.

nMode

A flag that specifies whether objects will be loaded from or stored to the archive. The nMode parameter must have one of the following values:

  • CArchive::load Loads data from the archive. Requires only CFile read permission.

  • CArchive::store Saves data to the archive. Requires CFile write permission.

  • CArchive::bNoFlushOnDelete Prevents the archive from automatically calling Flush when the archive destructor is called. If you set this flag, you are responsible for explicitly calling Close before the destructor is called. If you do not, your data will be corrupted.

nBufSize

An integer that specifies the size of the internal file buffer, in bytes. Note that the default buffer size is 4096 bytes. If you routinely archive large objects, you will improve performance if you use a larger buffer size that is a multiple of the file buffer size.

lpBuf

An optional pointer to a user-supplied buffer of size nBufSize. If you do not specify this parameter, the archive allocates a buffer from the local heap and frees it when the object is destroyed. The archive does not free a user-supplied buffer.

Remarks

Constructs a CArchive object and specifies whether it will be used for loading or storing objects. You cannot change this specification after you have created the archive.

You may not use CFile operations to alter the state of the file until you have closed the archive. Any such operation will damage the integrity of the archive. You may access the position of the file pointer at any time during serialization by obtaining the archive’s file object from the GetFile member function and then using the CFile::GetPosition function. You should call CArchive::Flush before obtaining the position of the file pointer.

Example

extern char* pFileName;
CFile f;
char buf[512];
if( !f.Open( pFileName, CFile::modeCreate | CFile::modeWrite ) ) {
   #ifdef _DEBUG
      afxDump << "Unable to open file" << "\n";
      exit( 1 );
   #endif
}
CArchive ar( &f, CArchive::store, 512, buf );

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::Close, CArchive::Flush, CFile::Close


CArchive::Close

void Close( );
throw( CArchiveException, CFileException );

Remarks

Flushes any data remaining in the buffer, closes the archive, and disconnects the archive from the file. No further operations on the archive are permitted. After you close an archive, you can create another archive for the same file or you can close the file.

The member function Close ensures that all data is transferred from the archive to the file, and it makes the archive unavailable. To complete the transfer from the file to the storage medium, you must first use CFile::Close and then destroy the CFile object.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::Flush, CArchive::Abort


CArchive::Flush

void Flush( );
throw( CFileException );

Remarks

Forces any data remaining in the archive buffer to be written to the file.

The member function Flush ensures that all data is transferred from the archive to the file. You must call CFile::Close to complete the transfer from the file to the storage medium.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::Close, CFile::Flush, CFile::Close


CArchive::GetFile

CFile* GetFile( ) const;

Return Value

A constant pointer to the CFile object in use.

Remarks

Gets the CFile object pointer for this archive. You must flush the archive before using GetFile.

Example

extern CArchive ar;
const CFile* fp = ar.GetFile();

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::Flush


CArchive::GetObjectSchema

UINT GetObjectSchema( );

Return Value

During deserialization, the version of the object being read.

Remarks

Call this function from the Serialize function to determine the version of the object that is currently being deserialized. Calling this function is only valid when the CArchive object is being loaded (CArchive::IsLoading returns nonzero). It should be the first call in the Serialize function and called only once. A return value of (UINT)–1 indicates that the version number is unknown).

A CObject-derived class may use VERSIONABLE_SCHEMA combined (using bitwise OR) with the schema version itself (in the IMPLEMENT_SERIAL macro) to create a “versionable object,” that is, an object whose Serialize member function can read multiple versions. The default framework functionality (without VERSIONABLE_SCHEMA) is to throw an exception when the version is mismatched.

Example

IMPLEMENT_SERIAL(CMyObject, CObject, VERSIONABLE_SCHEMA|1)

void CMyObject::Serialize(CArchive& ar)
{
   if (ar.IsLoading())
   {
      int nVersion = ar.GetObjectSchema();

      switch(nVersion)
      {
      case 0:
         // read in previous version of
         // this object
         break;
      case 1:
         // read in current version of
         // this object
         break;
      default:
         // report unknown version of
         // this object
         break;
      }
   }
   else
   {
      // Normal storing code goes here
   }
}

CArchive Overview | Class Members | Hierarchy Chart

See Also CObject::Serialize, CObject::IsSerializable, IMPLEMENT_SERIAL, DECLARE_SERIAL, CArchive::IsLoading


CArchive::IsBufferEmpty

BOOL IsBufferEmpty( ) const;

Return Value

Nonzero if the archive’s buffer is empty; otherwise 0.

Remarks

Call this member function to determine whether the archive object’s internal buffer is empty. This function is supplied to support programming with the MFC Windows Sockets class CSocketFile. You do not need to use it for an archive associated with a CFile object.

The reason for using IsBufferEmpty with an archive associated with a CSocketFile object is that the archive’s buffer might contain more than one message or record. After receiving one message, you should use IsBufferEmpty to control a loop that continues receiving data until the buffer is empty. For more information, see the Receive member function of class CAsyncSocket and the MFC Advanced Concepts sample CHATSRVR, which shows how to use IsBufferEmpty.

For more information, see the article Windows Sockets: Using Sockets with Archives in Visual C++ Programmer's Guide.

CArchive Overview | Class Members | Hierarchy Chart

See Also CSocketFile, CAsyncSocket::Receive


CArchive::IsLoading

BOOL IsLoading( ) const;

Return Value

Nonzero if the archive is currently being used for loading; otherwise 0.

Remarks

Determines whether the archive is loading data. This member function is called by the Serialize functions of the archived classes.

Example

int i;
extern CArchive ar;
if( ar.IsLoading() )
  ar >> i;
else
  ar << i;

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::IsStoring


CArchive::IsStoring

BOOL IsStoring( ) const;

Return Value

Nonzero if the archive is currently being used for storing; otherwise 0.

Remarks

Determines whether the archive is storing data. This member function is called by the Serialize functions of the archived classes.

If the IsStoring status of an archive is nonzero, then its IsLoading status is 0, and vice versa.

Example

int i;
extern CArchive ar;
if( ar.IsStoring() )
  ar << i;
else
  ar >> i;

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::IsLoading


CArchive::MapObject

void MapObject( const CObject* pOb );

Parameters

pOb

A constant pointer to the object being stored.

Remarks

Call this member function to place objects in the map that are not really serialized to the file, but that are available for subobjects to reference. For example, you might not serialize a document, but you would serialize the items that are part of the document. By calling MapObject, you allow those items, or subobjects, to reference the document. Also, serialized subitems can serialize their m_pDocument back pointer.

You can call MapObject when you store to and load from the CArchive object. MapObject adds the specified object to the internal data structures maintained by the CArchive object during serialization and deserialization, but unlike ReadObject and WriteObject , it does not call serialize on the object.

Example

// MyDoc.h
// Document should have DECLARE_SERIAL and IMPLEMENT_SERIAL

class CMyDocument : public CDocument
{
   CObList m_listOfSubItems;
    ...
   DECLARE_SERIAL(CMyDocument)
};

// MyDoc.cpp
...
IMPLEMENT_SERIAL(CMyDocument, CObject, 1)
...
void CMyDocument::Serialize(CArchive& ar)
{
   if (ar.IsStoring())
   {
      // TODO: add storing code here
   }
   else
   {
      // TODO: add loading code here
   }

   ar.MapObject(this);
   //serialize the subitems in the document;
   //they will be able to serialize their m_pDoc
   //back pointer
   m_listOfSubItems.Serialize(ar);

}

//SubItem.h
class CSubItem : public CObject
{
public:
   CSubItem(CMyDocument * pDoc)
      { m_pDoc = pDoc; }

   // back pointer to owning document
   CMyDocument* m_pDoc;
   WORD m_i; // other item data

   virtual void Serialize(CArchive& ar);
};

//SubItem.cpp
void CSubItem::Serialize(CArchive& ar)
{
   if (ar.IsStoring())
   {
      // will serialize a reference
      //to the "mapped" document pointer
      ar << m_pDoc;
      ar << m_i;
   }
   else
   {
      // will load a reference to
      //the "mapped" document pointer
      ar >> m_pDoc;
      ar >> m_i;
   }
}

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::ReadObject, CArchive::WriteObject


CArchive::Read

UINT Read( void* lpBuf, UINT nMax );
throw( CFileException );

Return Value

An unsigned integer containing the number of bytes actually read. If the return value is less than the number requested, the end of file has been reached. No exception is thrown on the end-of-file condition.

Parameters

lpBuf

A pointer to a user-supplied buffer that is to receive the data read from the archive.

nMax

An unsigned integer specifying the number of bytes to be read from the archive.

Remarks

Reads a specified number of bytes from the archive. The archive does not interpret the bytes.

You can use the Read member function within your Serialize function for reading ordinary structures that are contained in your objects.

Example

extern CArchive ar;
char pb[100];
UINT nr = ar.Read( pb, 100 );


CArchive::ReadClass

CRuntimeClass* ReadClass( const CRuntimeClass* pClassRefRequested = NULL, UINT* pSchema = NULL, DWORD* obTag = NULL );
Throw CArchiveException;
Throw CNotSupportedException;

Return Value

A pointer to the CRuntimeClass structure.

Parameters

pClassRefRequested

A pointer to the CRuntimeClass structure that corresponds to the class reference requested. Can be NULL.

pSchema

A pointer to a schema of the run-time class previously stored.

obTag

A number that refers to an object’s unique tag. Used internally by the implementation of ReadObject. Exposed for advanced programming only; obTag normally should be NULL.

Remarks

Call this member function to read a reference to a class previously stored with WriteClass.

If pClassRefRequested is not NULL, ReadClass verifies that the archived class information is compatible with your runtime class. If it is not compatible, ReadClass will throw a CArchiveException.

Your runtime class must use DECLARE_SERIAL and IMPLEMENT_SERIAL; otherwise, ReadClass will throw a CNotSupportedException.

If pSchema is NULL, the schema of the stored class can be retrieved by calling CArchive::GetObjectSchema; otherwise, *pSchema will contain the schema of the run-time class that was previously stored.

You can use SerializeClass instead of ReadClass, which handles both reading and writing of the class reference.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::WriteClass, CArchive::GetObjectSchema, CArchive::SetObjectSchema, CArchiveException, CNotSupportedException, CArchive::SerializeClass


CArchive::ReadObject

CObject* ReadObject( const CRuntimeClass* pClass );
throw( CFileException, CArchiveException, CMemoryException );

Return Value

A CObject pointer that must be safely cast to the correct derived class by using CObject::IsKindOf.

Parameters

pClass

A constant pointer to the CRuntimeClass structure that corresponds to the object you expect to read.

Remarks

Reads object data from the archive and constructs an object of the appropriate type.

This function is normally called by the CArchive extraction (>>) operator overloaded for a CObject pointer. ReadObject, in turn, calls the Serialize function of the archived class.

If you supply a nonzero pClass parameter, which is obtained by the RUNTIME_CLASS macro, then the function verifies the run-time class of the archived object. This assumes you have used the IMPLEMENT_SERIAL macro in the implementation of the class.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::WriteObject, CObject::IsKindOf


CArchive::ReadString

Bool ReadString(CString& rString );

LPTSTR ReadString( LPTSTR lpsz, UINT nMax );
throw( CArchiveException );

Return Value

In the version that returns Bool, TRUE if successful; FALSE otherwise.

In the version that returns an LPTSTR, a pointer to the buffer containing the text data; NULL if end-of-file was reached.

Parameters

rString

A reference to a CString that will contain the resultant string after it is read from the file associated with the CArchive object.

lpsz

Specifies a pointer to a user-supplied buffer that will receive a null-terminated text string.

nMax

Specifies the maximum number of characters to read. Should be one less than the size of the lpsz buffer.

Remarks

Call this member function to read text data into a buffer from the file associated with the CArchive object. In the version of the member function with the nMax parameter, the buffer will hold up to a limit of nMax - 1 characters. Reading is stopped by a carriage return-linefeed pair. Trailing newline characters are always removed. A null character ('\0') is appended in either case.

CArchive::Read is also available for text-mode input, but it does not terminate on a carriage return-linefeed pair.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::Read, CArchive::Write, CArchive::WriteString, CArchiveException


CArchive::SerializeClass

void SerializeClass( const CRuntimeClass* pRuntimeClass );

Parameters

pRuntimeClass

A pointer to a run-time class object for the base class.

Remarks

Call this member function when you want to store and load the version information of a base class. SerializeClass reads or writes the reference to a class to the CArchive object, depending on the direction of the CArchive. Use SerializeClass in place of ReadClass and WriteClass as a convenient way to serialize base-class objects; SerializeClass requires less code and fewer parameters.

Like ReadClass, SerializeClass verifies that the archived class information is compatible with your runtime class. If it is not compatible, SerializeClass will throw a CArchiveException.

Your runtime class must use DECLARE_SERIAL and IMPLEMENT_SERIAL; otherwise, SerializeClass will throw a CNotSupportedException.

Use the RUNTIME_CLASS macro to retrieve the value for the pRuntimeClass parameter. The base class must have used the IMPLEMENT_SERIAL macro.

Example

class CBaseClass : public CObject { ... };
class CDerivedClass : public CBaseClass { ... };
void CDerivedClass::Serialize(CArchive& ar)
{
   if (ar.IsStoring())
   {
      //normal code for storing contents
      //of this object
   }
   else
   {
      //normal code for reading contents
      //of this object
   }

   //allow the base class to serialize along
   //with its version information
   ar.SerializeClass(RUNTIME_CLASS(CBaseClass));
   CBaseClass::Serialize(ar);
}

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::ReadClass, CArchive::WriteClass, CArchive::GetObjectSchema, CArchive::SetObjectSchema, CArchiveException, CNotSupportedException


CArchive::SetLoadParams

void SetLoadParams( UINT nGrowBy = 1024 );

Parameters

nGrowBy

The minimum number of element slots to allocate if a size increase is necessary.

Remarks

Call SetLoadParams when you are going to read a large number of CObject-derived objects from an archive. CArchive uses a load array to resolve references to objects stored in the archive. SetLoadParams allows you to set the size to which the load array grows.

You must not call SetLoadParams after any object is loaded, or after MapObject or ReadObject is called.

Example

class CMyLargeDocument : public CDocument { ... };
void CMyLargeDocument::Serialize(CArchive& ar)
{
   if (ar.IsStoring())
      ar.SetStoreParams();  // use large defaults
   else
      ar.SetLoadParams();

   if (ar.IsStoring())
   {
      // code for storing CMyLargeDocument
   }
   else
   {
      // code for loading CMyLargeDocument
   }
}

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::SetStoreParams


CArchive::SetObjectSchema

void SetObjectSchema( UINT nSchema );

Parameters

nSchema

Specifies the object’s schema.

Remarks

Call this member function to set the object schema stored in the archive object to nSchema. The next call to GetObjectSchema will return the value stored in nSchema.

Use SetObjectSchema for advanced versioning; for example, when you want to force a particular version to be read in a Serialize function of a derived class.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::GetObjectSchema


CArchive::SetStoreParams

void SetStoreParams( UINT nHashSize = 2053, UINT nBlockSize = 128 );

Parameters

nHashSize

The size of the hash table for interface pointer maps. Should be a prime number.

nBlockSize

Specifies the memory-allocation granularity for extending the parameters. Should be a power of 2 for the best performance.

Remarks

Use SetStoreParams when storing a large number of CObject-derived objects in an archive.

SetStoreParams allows you to set the hash table size and the block size of the map used to identify unique objects during the serialization process.

You must not call SetStoreParams after any objects are stored, or after MapObject or WriteObject is called.

Example

class CMyLargeDocument : public CDocument { ... };
void CMyLargeDocument::Serialize(CArchive& ar)
{
   if (ar.IsStoring())
      ar.SetStoreParams();  // use large defaults
   else
      ar.SetLoadParams();

   if (ar.IsStoring())
   {
      // code for storing CMyLargeDocument
   }
   else
   {
      // code for loading CMyLargeDocument
   }
}

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::SetLoadParams


CArchive::Write

void Write( const void* lpBuf, UINT nMax );
throw( CFileException );

Parameters

lpBuf

A pointer to a user-supplied buffer that contains the data to be written to the archive.

nMax

An integer that specifies the number of bytes to be written to the archive.

Remarks

Writes a specified number of bytes to the archive. The archive does not format the bytes.

You can use the Write member function within your Serialize function to write ordinary structures that are contained in your objects.

Example

extern CArchive ar;
char pb[100];
ar.Write( pb, 100 );

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::Read


CArchive::WriteClass

void WriteClass( const CRuntimeClass* pClassRef );

Parameters

pClassRef

A pointer to the CRuntimeClass structure that corresponds to the class reference requested.

Remarks

Use WriteClass to store the version and class information of a base class during serialization of the derived class. WriteClass writes a reference to the CRuntimeClass for the base class to the CArchive. Use CArchive::ReadClass to retrieve the reference.

WriteClass verifies that the archived class information is compatible with your runtime class. If it is not compatible, WriteClass will throw a CArchiveException.

Your runtime class must use DECLARE_SERIAL and IMPLEMENT_SERIAL; otherwise, WriteClass will throw a CNotSupportedException.

You can use SerializeClass instead of WriteClass, which handles both reading and writing of the class reference.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::ReadClass, CArchive::GetObjectSchema, CArchive::SetObjectSchema, CArchive::SerializeClass, CArchiveException, CNotSupportedException.


CArchive::WriteObject

void WriteObject( const CObject* pOb );
throw( CFileException, CArchiveException );

Parameters

pOb

A constant pointer to the object being stored.

Remarks

Stores the specified CObject to the archive.

This function is normally called by the CArchive insertion (<<) operator overloaded for CObject. WriteObject, in turn, calls the Serialize function of the archived class.

You must use the IMPLEMENT_SERIAL macro to enable archiving. WriteObject writes the ASCII class name to the archive. This class name is validated later during the load process. A special encoding scheme prevents unnecessary duplication of the class name for multiple objects of the class. This scheme also prevents redundant storage of objects that are targets of more than one pointer.

The exact object encoding method (including the presence of the ASCII class name) is an implementation detail and could change in future versions of the library.

Note Finish creating, deleting, and updating all your objects before you begin to archive them. Your archive will be corrupted if you mix archiving with object modification.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::ReadObject


CArchive::WriteString

void WriteString( LPCTSTR lpsz );
throw( CFileException );

Parameters

lpsz

Specifies a pointer to a buffer containing a null-terminated text string.

Remarks

Use this member function to write data from a buffer to the file associated with the CArchive object. The terminating null character ('\0') is not written to the file; nor is a newline automatically written.

WriteString throws an exception in response to several conditions, including the disk-full condition.

Write is also available, but rather than terminating on a null character, it writes the requested number of bytes to the file.

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::Write, CArchive::Read, CArchive::ReadString, CFileException


Operators


CArchive::operator <<

friend CArchive& operator <<( CArchive& ar, const CObject* pOb );
throw( CArchiveException, CFileException );

CArchive& operator <<( BYTE by );
throw( CArchiveException, CFileException );

CArchive& operator <<( WORD w );
throw( CArchiveException, CFileException );

CArchive& operator <<( int i );
throw( CArchiveException, CFileException );

CArchive& operator <<( LONG l );
throw( CArchiveException, CFileException );

CArchive& operator <<( DWORD dw );
throw( CArchiveException, CFileException );

CArchive& operator <<( float f );
throw( CArchiveException, CFileException );

CArchive& operator <<( double d );
throw( CArchiveException, CFileException );

Return Value

A CArchive reference that enables multiple extraction operators on a single line.

Remarks

Stores the indicated object or primitive type to the archive.

If you used the IMPLEMENT_SERIAL macro in your class implementation, then the insertion operator overloaded for CObject calls the protected WriteObject. This function, in turn, calls the Serialize function of the class.

Example

long l;
int i;
extern CArchive ar;
if( ar.IsStoring() )
  ar << l << i;

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::WriteObject, CObject::Serialize


CArchive::operator >>

friend CArchive& operator >>( CArchive& ar, CObject *& pOb );
throw( CArchiveException, CFileException, CMemoryException );

friend CArchive& operator >>( CArchive& ar, const CObject *& pOb );
throw( CArchiveException, CFileException, CMemoryException );

CArchive& operator >>( BYTE& by );
throw( CArchiveException, CFileException );

CArchive& operator >>( WORD& w );
throw( CArchiveException, CFileException );

CArchive& operator >>( int& i );
throw( CArchiveException, CFileException );

CArchive& operator >>( LONG& l );
throw( CArchiveException, CFileException );

CArchive& operator >>( DWORD& dw );
throw( CArchiveException, CFileException );

CArchive& operator >>( float& f );
throw( CArchiveException, CFileException );

CArchive& operator >>( double& d );
throw( CArchiveException, CFileException );

Return Value

A CArchive reference that enables multiple insertion operators on a single line.

Remarks

Loads the indicated object or primitive type from the archive.

If you used the IMPLEMENT_SERIAL macro in your class implementation, then the extraction operators overloaded for CObject call the protected ReadObject function (with a nonzero run-time class pointer). This function, in turn, calls the Serialize function of the class.

Example

int i;
extern CArchive ar;
if( ar.IsLoading() )
  ar >> i;

CArchive Overview | Class Members | Hierarchy Chart

See Also CArchive::ReadObject, CObject::Serialize


Data Members


CArchive::m_pDocument

Remarks

Set to NULL by default, this pointer to a CDocument can be set to anything the user of the CArchive instance wants. A common usage of this pointer is to convey additional information about the serialization process to all objects being serialized. This is achieved by initializing the pointer with the document (a CDocument-derived class) that is being serialized, in such a way that objects within the document can access the document if necessary. This pointer is also used by COleClientItem objects during serialization.

The framework sets m_pDocument to the document being serialized when a user issues a File Open or Save command. If you serialize an Object Linking and Embedding (OLE) container document for reasons other than File Open or Save, you must explicitly set m_pDocument. For example, you would do this when serializing a container document to the Clipboard.

CArchive Overview | Class Members | Hierarchy Chart

See Also CDocument, COleClientItem


CArchiveException

A CArchiveException object represents a serialization exception condition. The CArchiveException class includes a public data member that indicates the cause of the exception.

CArchiveException objects are constructed and thrown inside CArchive member functions. You can access these objects within the scope of a CATCH expression. The cause code is independent of the operating system. For more information about exception processing, see the article Exceptions in Visual C++ Programmer's Guide.

#include <afx.h>

Class Members | Base Class | Hierarchy Chart

See Also CArchive, AfxThrowArchiveException,Exception Processing


CArchiveException Class Members

Data Members

m_cause Indicates the exception cause.

Construction

CArchiveException Constructs a CArchiveException object.


CArchiveException::CArchiveException

CArchiveException( int cause = CArchiveException::none );

Parameters

cause

An enumerated type variable that indicates the reason for the exception. For a list of the enumerators, see the m_cause data member.

Remarks

Constructs a CArchiveException object, storing the value of cause in the object. You can create a CArchiveException object on the heap and throw it yourself or let the global function AfxThrowArchiveException handle it for you.

Do not use this constructor directly; instead, call the global function AfxThrowArchiveException.


CArchiveException::m_cause

Remarks

Specifies the cause of the exception. This data member is a public variable of type int. Its values are defined by a CArchiveException enumerated type. The enumerators and their meanings are as follows:

  • CArchiveException::none No error occurred.

  • CArchiveException::generic Unspecified error.

  • CArchiveException::readOnly Tried to write into an archive opened for loading.

  • CArchiveException::endOfFile Reached end of file while reading an object.

  • CArchiveException::writeOnly Tried to read from an archive opened for storing.

  • CArchiveException::badIndex Invalid file format.

  • CArchiveException::badClass Tried to read an object into an object of the wrong type.

  • CArchiveException::badSchema Tried to read an object with a different version of the class.

Note These CArchiveException cause enumerators are distinct from the CFileException cause enumerators.


CArray

template< class TYPE, class ARG_TYPE > class CArray : public CObject

Parameters

TYPE

Template parameter specifying the type of objects stored in the array. TYPE is a parameter that is returned by CArray.

ARG_TYPE

Template parameter specifying the argument type used to access objects stored in the array. Often a reference to TYPE. ARG_TYPE is a parameter that is passed to CArray.

Remarks

The CArray class supports arrays that are are similar to C arrays, but can dynamically shrink and grow as necessary.

Array indexes always start at position 0. You can decide whether to fix the upper bound or allow the array to expand when you add elements past the current bound. Memory is allocated contiguously to the upper bound, even if some elements are null.

As with a C array, the access time for a CArray indexed element is constant and is independent of the array size.

Tip Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

If you need a dump of individual elements in an array, you must set the depth of the CDumpContext object to 1 or greater.

Certain member functions of this class call global helper functions that must be customized for most uses of the CArray class. See the topic Collection Class Helpers in the Macros and Globals section.

When elements are removed from a CArray object, the helper function DestructElements is called. When elements are added, the helper function ConstructElements is called.

Array class derivation is similar to list derivation.

For more information on using CArray, see the article Collections in Visual C++ Programmer's Guide.

#include <afxtempl.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample COLLECT

See Also CObArray, DestructElements, ConstructElements, Collection Class Helpers


CArray Class Members

Construction

CArray Constructs an empty array.

Attributes

GetSize | Gets the number of elements in this array.
GetUpperBound | Returns the largest valid index.
SetSize | Sets the number of elements to be contained in this array.

Operations

FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.

Element Access

GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; array not allowed to grow.
ElementAt | Returns a temporary reference to the element pointer within the array.
GetData | Allows access to elements in the array. Can be NULL.

Growing the Array

SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds an element to the end of the array; grows the array if necessary.
Append | Appends another array to the array; grows the array if necessary
Copy | Copies another array to the array; grows the array if necessary.

Insertion/Removal

InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.

Operators

operator [] Sets or gets the element at the specified index.


CArray::Add

int Add( ARG_TYPE newElement );
throw( CMemoryException );

Return Value

The index of the added element.

Parameters

ARG_TYPE

Template parameter specifying the type of arguments referencing elements in this array.

newElement

The element to be added to this array.

Remarks

Adds a new element to the end of an array, growing the array by 1. If SetSize has been used with an nGrowBy value greater than 1, then extra memory may be allocated. However, the upper bound will increase by only 1.

Example

// example for CArray::Add
CArray<CPoint,CPoint> ptArray;

CPoint pt(10,20);
ptArray.Add(pt);             // Element 0
ptArray.Add(CPoint(30,40));  // Element 1

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::SetAt, CArray::SetAtGrow, CArray::InsertAt, CArray::operator []


CArray::Append

int Append( const CArray& src );

Return Value

The index of the first appended element.

Parameters

src

Source of the elements to be appended to an array.

Remarks

Call this member function to add the contents of one array to the end of another. The arrays must be of the same type.

If necessary, Append may allocate extra memory to accommodate the elements appended to the array.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::Copy


CArray::CArray

CArray( );

Remarks

Constructs an empty array. The array grows one element at a time.

CArray Overview | Class Members | Hierarchy Chart

See Also CObArray::CObArray


CArray::Copy

void Copy( const CArray& src );

Parameters

src

Source of the elements to be copied to an array.

Remarks

Use this member function to copy the elements of one array to another.

Call this member function to overwrite the elements of one array with the elements of another array.

Copy does not free memory; however, if necessary, Copy may allocate extra memory to accommodate the elements copied to the array.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::Append


CArray::ElementAt

TYPE& ElementAt( int nIndex );

Return Value

A reference to an array element.

Parameters

TYPE

Template parameter specifying the type of elements in the array.

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

Remarks

Returns a temporary reference to the specified element within the array. It is used to implement the left-side assignment operator for arrays.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::operator []


CArray::FreeExtra

void FreeExtra( );

Remarks

Frees any extra memory that was allocated while the array was grown. This function has no effect on the size or upper bound of the array.


CArray::GetAt

TYPE GetAt( int nIndex ) const;

Return Value

The array element currently at this index.

Parameters

TYPE

Template parameter specifying the type of the array elements.

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

Remarks

Returns the array element at the specified index.

Note Passing a negative value or a value greater than the value returned by GetUpperBound will result in a failed assertion.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::SetAt, CArray::operator [], ConstructElements


CArray::GetData

const TYPE* GetData( ) const;

TYPE* GetData( );

Return Value

A pointer to an array element.

Parameters

TYPE

Template parameter specifying the type of the array elements.

Remarks

Use this member function to gain direct access to the elements in an array. If no elements are available, GetData returns a null value.

While direct access to the elements of an array can help you work more quickly, use caution when calling GetData; any errors you make directly affect the elements of your array.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::GetAt, CArray::SetAt, CArray::ElementAt


CArray::GetSize

int GetSize( ) const;

Remarks

Returns the size of the array. Since indexes are zero-based, the size is 1 greater than the largest index.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::GetUpperBound, CArray::SetSize


CArray::GetUpperBound

int GetUpperBound( ) const;

Remarks

Returns the current upper bound of this array. Because array indexes are zero-based, this function returns a value 1 less than GetSize.

The condition GetUpperBound( ) = –1 indicates that the array contains no elements.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::GetSize, CArray::SetSize


CArray::InsertAt

void InsertAt( int nIndex, ARG_TYPE newElement, int nCount = 1 );
throw( CMemoryException );

void InsertAt( int nStartIndex, CArray* pNewArray );
throw( CMemoryException );

Parameters

nIndex

An integer index that may be greater than the value returned by GetUpperBound.

ARG_TYPE

Template parameter specifying the type of elements in this array.

newElement

The element to be placed in this array.

nCount

The number of times this element should be inserted (defaults to 1).

nStartIndex

An integer index that may be greater than the value returned by GetUpperBound.

pNewArray

Another array that contains elements to be added to this array.

Remarks

The first version of InsertAt inserts one element (or multiple copies of an element) at a specified index in an array. In the process, it shifts up (by incrementing the index) the existing element at this index, and it shifts up all the elements above it.

The second version inserts all the elements from another CArray collection, starting at the nStartIndex position.

The SetAt function, in contrast, replaces one specified array element and does not shift any elements.

Example

// example for CArray::InsertAt

CArray<CPoint,CPoint> ptArray;

ptArray.Add(CPoint(10,20));   // Element 0
ptArray.Add(CPoint(30,40));   // Element 1 (will become element 2)
ptArray.InsertAt(1, CPoint(50,60));   // New element 1

CArray Overview | Class Members | Hierarchy Chart

See Also GetUpperBound, CArray::SetAt, CArray::RemoveAt


CArray::RemoveAll

void RemoveAll( );

Remarks

Removes all the elements from this array. If the array is already empty, the function still works.


CArray::RemoveAt

void RemoveAt( int nIndex, int nCount = 1 );

Parameters

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

nCount

The number of elements to remove.

Remarks

Removes one or more elements starting at a specified index in an array. In the process, it shifts down all the elements above the removed element(s). It decrements the upper bound of the array but does not free memory.

If you try to remove more elements than are contained in the array above the removal point, then the Debug version of the library asserts.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::SetAt, CArray::SetAtGrow, CArray::InsertAt


CArray::SetAt

void SetAt( int nIndex, ARG_TYPE newElement );

Parameters

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

ARG_TYPE

Template parameter specifying the type of arguments used for referencing array elements.

newElement

The new element value to be stored at the specified position.

Remarks

Sets the array element at the specified index. SetAt will not cause the array to grow. Use SetAtGrow if you want the array to grow automatically.

You must ensure that your index value represents a valid position in the array. If it is out of bounds, then the Debug version of the library asserts.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::GetAt, CArray::SetAtGrow, CArray::ElementAt, CArray::operator []


CArray::SetAtGrow

void SetAtGrow( int nIndex, ARG_TYPE newElement );
throw( CMemoryException );

Parameters

nIndex

An integer index that is greater than or equal to 0.

ARG_TYPE

Template parameter specifying the type of elements in the array.

newElement

The element to be added to this array. A NULL value is allowed.

Remarks

Sets the array element at the specified index. The array grows automatically if necessary (that is, the upper bound is adjusted to accommodate the new element).

Example

// example for CArray::SetAtGrow
CArray<CPoint,CPoint> ptArray;

ptArray.Add(CPoint(10,20));   // Element 0
ptArray.Add(CPoint(30,40));   // Element 1
                     // Element 2 deliberately skipped
ptArray.SetAtGrow(3, CPoint(50,60));   // Element 3

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::GetAt, CArray::SetAt, CArray::ElementAt, CArray::operator []


CArray::SetSize

void SetSize( int nNewSize, int nGrowBy = -1 );
throw( CMemoryException );

Parameters

nNewSize

The new array size (number of elements). Must be greater than or equal to 0.

nGrowBy

The minimum number of element slots to allocate if a size increase is necessary.

Remarks

Establishes the size of an empty or existing array; allocates memory if necessary.

If the new size is smaller than the old size, then the array is truncated and all unused memory is released.

Use this function to set the size of your array before you begin using the array. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

The nGrowBy parameter affects internal memory allocation while the array is growing. Its use never affects the array size as reported by GetSize and GetUpperBound. If the default value is used, MFC allocates memory in a way calculated to avoid memory fragmentation and optimize efficiency for most cases.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::GetUpperBound, CArray::GetSize


CArray::operator [ ]

TYPE& operator []( int nIndex );

TYPE operator []( int nIndex ) const;

Parameters

TYPE

Template parameter specifying the type of elements in this array.

nIndex

Index of the element to be accessed.

Remarks

These subscript operators are a convenient substitute for the SetAt and GetAt functions.

The first operator, called for arrays that are not const, may be used on either the right (r-value) or the left (l-value) of an assignment statement. The second, called for const arrays, may be used only on the right.

The Debug version of the library asserts if the subscript (either on the left or right side of an assignment statement) is out of bounds.

CArray Overview | Class Members | Hierarchy Chart

See Also CArray::GetAt, CArray::SetAt, CArray::ElementAt


CAsyncMonikerFile

CAsyncMonikerFile provides functionality for the use of asynchronous monikers in ActiveX controls (formerly OLE controls). Derived from CMonikerFile, which in turn is derived from COleStreamFile, CAsyncMonikerFile uses the IMoniker interface to access any data stream asynchronously, including loading files asynchronously from a URL. The files can be datapath properties of ActiveX controls.

Asynchronous monikers are used primarily in Internet-enabled applications and ActiveX controls to provide a responsive user-interface during file transfers. A prime example of this is the use of CDataPathProperty to provide asynchronous properties for ActiveX controls. The CDataPathProperty object will repeatedly get a callback to indicate availability of new data during a lengthy property exchange process.

For more information about how to use asynchronous monikers and ActiveX controls in Internet applications, see the following articles in Visual C++ Programmer's Guide:

  • Internet First Steps: Asynchronous Monikers

  • Internet First Steps: ActiveX Controls

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

See Also CMonikerFile, CDataPathProperty, Asynchronous Versus Synchronous Monikers in the OLE Programmer's Reference in the Win32 SDK


CAsyncMonikerFile Class Members

Construction

CAsyncMonikerFile Constructs a CAsyncMonikerFile object.

Operations

GetBinding | Retrieves a pointer to the asynchronous transfer binding.
GetFormatEtc | Retrieves the format of the data in the stream.

Overridables

Close | Closes and releases all resources.
CreateBindStatusCallback | Creates a COM object that implements IBindStatusCallback.
GetBindInfo | Called by the OLE system library to request information on the type of bind to be created.
GetPriority | Called by the OLE system library to get the priority of the binding.
OnDataAvailable | Called to provide data as it becomes available to the client during asynchronous bind operations.
OnLowResource | Called when resources are low.
OnProgress | Called to indicate progress on the data downloading process.
OnStartBinding | Called when binding is starting up.
OnStopBinding | Called when asynchronous transfer is stopped.
Open | Opens a file asynchronously.


CAsyncMonikerFile::CAsyncMonikerFile

CAsyncMonikerFile( );

Remarks

Constructs a CAsyncMonikerFile object. It does not create the IBindHost interface. IBindHost is used only if you provide it in the Open member function.

For a description of the IBindHost interface, see the ActiveX SDK.

CAsyncMonikerFile Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty, CAsyncMonikerFile::Open


CAsyncMonikerFile::Close

virtual void Close( );

Remarks

Call this function to close and release all resources. Can be called on unopened or already closed files.

CAsyncMonikerFile Overview | Class Members | Hierarchy Chart

See Also CAsyncMonikerFile::Open


CAsyncMonikerFile::CreateBindStatusCallback

virtual IUnknown* CreateBindStatusCallback( IUnknown* pUnkControlling );

Return Value

If pUnkControlling is not NULL, the function returns a pointer to the inner IUnknown on a new COM object supporting IBindStatusCallback. If pUnkControlling is NULL, the function returns a pointer to an IUnknown on a new COM object supporting IBindStatusCallback.

Parameters

pUnkControlling

A pointer to the controlling unknown (the outer IUnknown) or NULL if aggregation is not being used.

Remarks

CAsyncMonikerFile requires a COM object that implements IBindStatusCallback. MFC implements such an object, and it is aggregatable. You can override CreateBindStatusCallback to return your own COM object. Your COM object can aggregate MFC’s implementation by calling CreateBindStatusCallback with the controlling unknown of your COM object. COM objects implemented using CCmdTarget's COM support can retrieve the controlling unknown using CCmdTarget::GetControllingUnknown.

Alternately, your COM object can delegate to MFC's implementation by calling CreateBindStatusCallback( NULL ).

Open calls CreateBindStatusCallback.

For details about the IBindStatusCallback interface, described in the Platform SDK. For more about asynchronous binding, see How Asynchronous Binding and Storage Work in the Platform SDK. For a discussion of aggregation, see Aggregation in the Platform SDK.


CAsyncMonikerFile::GetBindInfo

virtual DWORD GetBindInfo( ) const;

Return Value

Retrieves the settings for IBindStatusCallBack. For a description of the IBindStatusCallback interface, see the ActiveX SDK.

Remarks

Called from the client of an asynchronous moniker to tell the asynchronous moniker how it wants to bind. The default implementation sets the binding to be asynchronous, to use a storage medium (a stream), and to use the data-push model. Override this function if you want to change the behavior of the binding.

One reason for doing this would be to bind using the data-pull model instead of the data-push model. In a data-pull model, the client drives the bind operation, and the moniker only provides data to the client when it is read. In a data-push model, the moniker drives the asynchronous bind operation and continuously notifies the client whenever new data is available.


CAsyncMonikerFile::GetBinding

IBinding* GetBinding( ) const;

Return Value

A pointer to the IBinding interface provided when asynchronous transfer begins. Returns NULL if for any reason the transfer cannot be made asynchronously.

Remarks

Call this function to retrieve a pointer to the asynchronous transfer binding. This allows you to control the data transfer process through the IBinding interface, for example, with IBinding::Abort, IBinding::Pause, and IBinding::Resume.

For a description of the IBinding interface, see the ActiveX SDK.


CAsyncMonikerFile::GetFormatEtc

FORMATETC* GetFormatEtc( ) const;

Return Value

A pointer to the Windows structure FORMATETC for the currently opened stream. Returns NULL if the moniker has not been bound, if it is not asynchronous, or if the asynchronous operation has not begun.

Remarks

Call this function to retrieve the format of the data in the stream.


CAsyncMonikerFile::GetPriority

virtual long GetPriority( ) const;

Return Value

The priority at which the asynchronous transfer will take place. One of the standard thread priority flags: THREAD_PRIORITY_ABOVE_NORMAL, THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL, and THREAD_PRIORITY_TIME_CRITICAL. See the Windows function SetThreadPriority for a description of these values.

Remarks

Called from the client of an asynchronous moniker as the binding process starts to receive the priority given to the thread for the binding operation. GetPriority should not be called directly. THREAD_PRIORITY_NORMAL is returned by the default implementation.


CAsyncMonikerFile::OnDataAvailable

virtual void OnDataAvailable( DWORD dwsize, DWORD bscfFlag );

Parameters

dwsize

The cumulative amount (in bytes) of data available since the beginning of the binding. Can be zero, indicating that the amount of data is not relevant to the operation, or that no specific amount became available.

bscfFlag

A BSCF enumeration value. Can be one or more of the following values:

  • BSCF_FIRSTDATANOTIFICATION Identifies the first call to OnDataAvailable for a given bind operation.

  • BSCF_INTERMEDIATEDATANOTIFICATION Identifies an intermediary call to OnDataAvailable for a bind operation.

  • BSCF_LASTDATANOTIFICATION Identifies the last call to OnDataAvailable for a bind operation.

Remarks

An asynchronous moniker calls OnDataAvailable to provide data to the client as it becomes available, during asynchronous bind operations. The default implementation of this function does nothing. See the following example for a sample implementation.

Example

// refer to CDataPathProperty.
void CAsyncMyTextProperty::OnDataAvailable(DWORD dwSize, DWORD bscfFlag)
{
   if ((bscfFlag & BSCF_FIRSTDATANOTIFICATION) != 0)
   {
      m_dwReadBefore = 0;
      m_strText.Empty();
   }

   DWORD dwArriving = dwSize - m_dwReadBefore;

   if (dwArriving > 0)
   {
      int nLen = m_strText.GetLength();
      ASSERT(nLen == m_dwReadBefore);
      LPTSTR psz = m_strText.GetBuffer(nLen + dwArriving);
      Read(psz + nLen, dwArriving);
      m_strText.ReleaseBuffer(nLen + dwArriving);
      m_dwReadBefore = dwSize;
      GetControl()->Invalidate();
   }
}

CAsyncMonikerFile Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty


CAsyncMonikerFile::OnLowResource

virtual void OnLowResource( );

Remarks

Called by the moniker when resources are low. The default implementation calls GetBinding( )-> Abort( ).


CAsyncMonikerFile::OnProgress

virtual void OnProgress( ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCTSTR szStatusText );

Parameters

ulProgress

Indicates the current progress of the bind operation relative to the expected maximum indicated in ulProgressMax.

ulProgressMax

Indicates the expected maximum value of ulProgress for the duration of calls to OnProgress for this operation.

ulStatusCode

Provides additional information regarding the progress of the bind operation. Valid values are taken from the BINDSTATUS enumeration. See Remarks for possible values.

szStatusText

Information about the current progress, depending on the value of ulStatusCode. See Remarks for possible values.

Remarks

Called by the moniker repeatedly to indicate the current progress of this bind operation, typically at reasonable intervals during a lengthy operation.

Possible values for ulStatusCode (and the szStatusText for each value) are:

BINDSTATUS_FINDINGRESOURCE

The bind operation is finding the resource that holds the object or storage being bound to. The szStatusText provides the display name of the resource being searched for (for example, “www.microsoft.com”).

BINDSTATUS_CONNECTING

The bind operation is connecting to the resource that holds the object or storage being bound to. The szStatusText provides the display name of the resource being connected to (for example, an IP address).

BINDSTATUS_SENDINGREQUEST

The bind operation is requesting the object or storage being bound to. The szStatusText provides the display name of the object (for example, a file name).

BINDSTATUS_REDIRECTING

The bind operation has been redirected to a different data location. The szStatusText provides the display name of the new data location.

BINDSTATUS_USINGCACHEDCOPY

The bind operation is retrieving the requested object or storage from a cached copy. The szStatusText is NULL.

BINDSTATUS_BEGINDOWNLOADDATA

The bind operation has begun receiving the object or storage being bound to. The szStatusText provides the display name of the data location.

BINDSTATUS_DOWNLOADINGDATA

The bind operation continues to receive the object or storage being bound to. The szStatusText provides the display name of the data location.

BINDSTATUS_ENDDOWNLOADDATA

The bind operation has finished receiving the object or storage being bound to. The szStatusText provides the display name of the data location.

BINDSTATUS_CLASSIDAVAILABLE

An instance of the object being bound to is just about to be created. The szStatusText provides the CLSID of the new object in string format, allowing the client an opportunity to cancel the bind operation, if desired.


CAsyncMonikerFile::OnStartBinding

virtual void OnStartBinding( );

Remarks

Override this function in your derived classes to perform actions when binding is starting up. This function is called back by the moniker. The default implementation does nothing.

CAsyncMonikerFile Overview | Class Members | Hierarchy Chart

See Also CAsyncMonikerFile::OnStopBinding


CAsyncMonikerFile::OnStopBinding

virtual void OnStopBinding( HRESULT hresult, LPCTSTR szError );

Parameters

hresult

An HRESULT that is the error or warning value.

szErrort

A character string describing the error.

Remarks

Called by the moniker at the end of the bind operation. Override this function to perform actions when the transfer is stopped. By default, the function releases IBinding.

For a description of the IBinding interface, see the ActiveX SDK.

CAsyncMonikerFile Overview | Class Members | Hierarchy Chart

See Also CAsyncMonikerFile::OnStartBinding


CAsyncMonikerFile::Open

virtual BOOL Open( LPCTSTR lpszURL, CFileException* pError = NULL );

virtual BOOL Open( IMoniker* pMoniker, CFileException* pError = NULL );

virtual BOOL Open( LPCTSTR lpszURL, IBindHost* pBindHost, CFileException* pError = NULL );

virtual BOOL Open( IMoniker* pMoniker, IBindHost* pBindHost, CFileException* pError = NULL );

virtual BOOL Open( LPCTSTR lpszURL, IServiceProvider* pServiceProvider, CFileException* pError = NULL );

virtual BOOL Open( IMoniker* pMoniker, IServiceProvider* pServiceProvider, CFileException* pError = NULL );

virtual BOOL Open( LPCTSTR lpszURL, IUnknown* pUnknown, CFileException* pError = NULL );

virtual BOOL Open( IMoniker* pMoniker, IUnknown* pUnknown, CFileException* pError = NULL );

Return Value

Nonzero if the file is opened successfully; otherwise 0.

Parameters

lpszURL

A pointer to file to be opened asynchronously. The file can be any valid URL or filename.

pError

A pointer to the file exceptions. In the event of an error, it will be set to the cause.

pMoniker

A pointer to the asynchronous moniker interface IMoniker, a precise moniker that is the combination of the document’s own moniker, which you can retrieve with 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 the control should save.

pBindHost A pointer to the IBindHost interface that will be used to create the moniker from a potentially relative pathname. If the bind host is invalid or does not provide a moniker, the call defaults to Open( lpszFileName, pError ). For a description of the IBindHost interface, see the ActiveX SDK.

pServiceProvider

A pointer to the IServiceProvider interface. If the service provider is invalid or fails to provide the service for IBindHost, the call defaults to Open( lpszFileName, pError ).

pUnknown

A pointer to the IUnknown interface. If IServiceProvider is found, the function queries for IBindHost. If the service provider is invalid or fails to provide the service for IBindHost, the call defaults to Open( lpszFileName, pError ).

Remarks

Call this member function to open a file asynchronously. This call initiates the binding process.

You can use a URL or a filename for the lpszURL parameter. For example:

CMyAsyncMonFile  mamf;
mamf.Open(_T("http://www.microsoft.com"));

– or –

CMyAsyncMonFile  mamf;
mamf.Open(_T("file:c:\mydata.dat"));

CAsyncMonikerFile Overview | Class Members | Hierarchy Chart

See Also CAsyncMonikerFile::CAsyncMonikerFile


CAsyncSocket

A CAsyncSocket object represents a Windows Socket — an endpoint of network communication. Class CAsyncSocket encapsulates the Windows Sockets API, providing an object-oriented abstraction for programmers who want to use Windows Sockets in conjunction with MFC.

This class is based on the assumption that you understand network communications. You are responsible for handling blocking, byte-order differences, and conversions between Unicode and multibyte character set (MBCS) strings. If you want a more convenient interface that manages these issues for you, see class CSocket.

To use a CAsyncSocket object, call its constructor, then call the Create function to create the underlying socket handle (type SOCKET), except on accepted sockets. For a server socket call the Listen member function, and for a client socket call the Connect member function. The server socket should call the Accept function upon receiving a connection request. Use the remaining CAsyncSocket functions to carry out communications between sockets. Upon completion, destroy the CAsyncSocket object if it was created on the heap; the destructor automatically calls the Close function. The SOCKET data type is described in the article Windows Sockets: Background in Visual C++ Programmer's Guide.

For more information, see Windows Sockets: Using Class CAsyncSocket and related articles in Visual C++ Programmer's Guide, as well as Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

#include <afxsock.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CHATSRVR | MFC Sample HTTPSVR

See Also CSocket, CSocketFile


CAsyncSocket Class Members

Construction

CAsyncSocket | Constructs a CAsyncSocket object.
Create | Creates a socket.

Attributes

Attach | Attaches a socket handle to a CAsyncSocket object.
Detach | Detaches a socket handle from a CAsyncSocket object.
FromHandle | Returns a pointer to a CAsyncSocket object, given a socket handle.
GetLastError | Gets the error status for the last operation that failed.
GetPeerName | Gets the address of the peer socket to which the socket is connected.
GetSockName | Gets the local name for a socket.
GetSockOpt | Retrieves a socket option.
SetSockOpt | Sets a socket option.

Operations

Accept | Accepts a connection on the socket.
AsyncSelect | Requests event notification for the socket.
Bind | Associates a local address with the socket.
Close | Closes the socket.
Connect | Establishes a connection to a peer socket.
IOCtl | Controls the mode of the socket.
Listen | Establishes a socket to listen for incoming connection requests.
Receive | Receives data from the socket.
ReceiveFrom | Receives a datagram and stores the source address.
Send | Sends data to a connected socket.
SendTo | Sends data to a specific destination.
ShutDown | Disables Send and/or Receive calls on the socket.

Overridable Notification Functions

OnAccept | Notifies a listening socket that it can accept pending connection requests by calling Accept.
OnClose | Notifies a socket that the socket connected to it has closed.
OnConnect | Notifies a connecting socket that the connection attempt is complete, whether successfully or in error.
OnOutOfBandData | Notifies a receiving socket that there is out-of-band data to be read on the socket, usually an urgent message.
OnReceive | Notifies a listening socket that there is data to be retrieved by calling Receive.
OnSend | Notifies a socket that it can send data by calling Send.

Data Members

m_hSocket Indicates the SOCKET handle attached to this CAsyncSocket object.


CAsyncSocket::Accept

virtual BOOL Accept( CAsyncSocket& rConnectedSocket, SOCKADDR* lpSockAddr = NULL, int* lpSockAddrLen = NULL );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEFAULT The lpSockAddrLen argument is too small (less than the size of a SOCKADDR structure).

  • WSAEINPROGRESS A blocking Windows Sockets call is in progress.

  • WSAEINVAL Listen was not invoked prior to accept.

  • WSAEMFILE The queue is empty upon entry to accept and there are no descriptors available.

  • WSAENOBUFS No buffer space is available.

  • WSAENOTSOCK The descriptor is not a socket.

  • WSAEOPNOTSUPP The referenced socket is not a type that supports connection-oriented service.

  • WSAEWOULDBLOCK The socket is marked as nonblocking and no connections are present to be accepted.

Parameters

rConnectedSocket

A reference identifying a new socket that is available for connection.

lpSockAddr

A pointer to a SOCKADDR structure that receives the address of the connecting socket, as known on the network. The exact format of the lpSockAddr argument is determined by the address family established when the socket was created. If lpSockAddr and/or lpSockAddrLen are equal to NULL, then no information about the remote address of the accepted socket is returned.

lpSockAddrLen

A pointer to the length of the address in lpSockAddr in bytes. The lpSockAddrLen is a value-result parameter: it should initially contain the amount of space pointed to by lpSockAddr; on return it will contain the actual length (in bytes) of the address returned.

Remarks

Call this member function to accept a connection on a socket. This routine extracts the first connection in the queue of pending connections, creates a new socket with the same properties as this socket, and attaches it to rConnectedSocket. If no pending connections are present on the queue, Accept returns zero and GetLastError returns an error. The accepted socket (rConnectedSocket) cannot be used to accept more connections. The original socket remains open and listening.

The argument lpSockAddr is a result parameter that is filled in with the address of the connecting socket, as known to the communications layer. Accept is used with connection-based socket types such as SOCK_STREAM.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Bind, CAsyncSocket::Connect, CAsyncSocket::Listen, CAsyncSocket::Create, ::WSAAsyncSelect


CAsyncSocket::AsyncSelect

BOOL AsyncSelect( long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEINVAL Indicates that one of the specified parameters was invalid.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

Parameters

lEvent

A bitmask which specifies a combination of network events in which the application is interested.

  • FD_READ Want to receive notification of readiness for reading.

  • FD_WRITE Want to receive notification when data is available to be read.

  • FD_OOB Want to receive notification of the arrival of out-of-band data.

  • FD_ACCEPT Want to receive notification of incoming connections.

  • FD_CONNECT Want to receive notification of connection results.

  • FD_CLOSE Want to receive notification when a socket has been closed by a peer.

Remarks

Call this member function to request event notification for a socket. This function is used to specify which MFC callback notification functions will be called for the socket. AsyncSelect automatically sets this socket to nonblocking mode. For more information, see the article Windows Sockets: Socket Notifications in Visual C++ Programmer's Guide and Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::GetLastError, ::WSAAsyncSelect


CAsyncSocket::Attach

BOOL Attach( SOCKET hSocket, long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE );

Return Value

Nonzero if the function is successful.

Parameters

hSocket

Contains a handle to a socket.

lEvent

A bitmask which specifies a combination of network events in which the application is interested.

  • FD_READ Want to receive notification of readiness for reading.

  • FD_WRITE Want to receive notification when data is available to be read.

  • FD_OOB Want to receive notification of the arrival of out-of-band data.

  • FD_ACCEPT Want to receive notification of incoming connections.

  • FD_CONNECT Want to receive notification of connection results.

  • FD_CLOSE Want to receive notification when a socket has been closed by a peer.

Remarks

Call this member function to attach the hSocket handle to an CAsyncSocket object. The SOCKET handle is stored in the object’s m_hSocket data member.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Detach


CAsyncSocket::Bind

BOOL Bind( UINT nSocketPort, LPCTSTR lpszSocketAddress = NULL );

BOOL Bind ( const SOCKADDR* lpSockAddr, int nSockAddrLen );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEADDRINUSE The specified address is already in use. (See the SO_REUSEADDR socket option under SetSockOpt.)

  • WSAEFAULT The nSockAddrLen argument is too small (less than the size of a SOCKADDR structure).

  • WSAEINPROGRESS A blocking Windows Sockets call is in progress.

  • WSAEAFNOSUPPORT The specified address family is not supported by this port.

  • WSAEINVAL The socket is already bound to an address.

  • WSAENOBUFS Not enough buffers available, too many connections.

  • WSAENOTSOCK The descriptor is not a socket.

Parameters

nSocketPort

The port identifying the socket application.

lpszSocketAddress

The network address, a dotted number such as “128.56.22.8”.

lpSockAddr

A pointer to a SOCKADDR structure that contains the address to assign to this socket.

nSockAddrLen

The length of the address in lpSockAddr in bytes.

Remarks

Call this member function to associate a local address with the socket. This routine is used on an unconnected datagram or stream socket, before subsequent Connect or Listen calls. Before it can accept connection requests, a listening server socket must select a port number and make it known to Windows Sockets by calling Bind. Bind establishes the local association (host address/port number) of the socket by assigning a local name to an unnamed socket.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Connect, CAsyncSocket::Listen, CAsyncSocket::GetSockName, CAsyncSocket::SetSockOpt, CAsyncSocket::Create


CAsyncSocket::CAsyncSocket

CAsyncSocket( );

Remarks

Constructs a blank socket object. After constructing the object, you must call its Create member function to create the SOCKET data structure and bind its address. (On the server side of a Windows Sockets communication, when the listening socket creates a socket to use in the Accept call, you do not call Create for that socket.)

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Create


CAsyncSocket::Close

virtual void Close( );

Remarks

This function closes the socket. More precisely, it releases the socket descriptor, so that further references to it will fail with the error WSAENOTSOCK. If this is the last reference to the underlying socket, the associated naming information and queued data are discarded. The socket object’s destructor calls Close for you.

For CAsyncSocket, but not for CSocket, the semantics of Close are affected by the socket options SO_LINGER and SO_DONTLINGER. For further information, see member function GetSockOpt and Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Accept, CAsyncSocket::CAsyncSocket, CAsyncSocket::IOCtl, CAsyncSocket::GetSockOpt, CAsyncSocket::SetSockOpt, CAsyncSocket::AsyncSelect


CAsyncSocket::Connect

BOOL Connect( LPCTSTR lpszHostAddress, UINT nHostPort );

BOOL Connect( const SOCKADDR* lpSockAddr, int nSockAddrLen );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. If this indicates an error code of WSAEWOULDBLOCK, and your application is using the overridable callbacks, your application will receive an OnConnect message when the connect operation is complete. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEADDRINUSE The specified address is already in use.

  • WSAEINPROGRESS A blocking Windows Sockets call is in progress.

  • WSAEADDRNOTAVAIL The specified address is not available from the local machine.

  • WSAEAFNOSUPPORT Addresses in the specified family cannot be used with this socket.

  • WSAECONNREFUSED The attempt to connect was rejected.

  • WSAEDESTADDRREQ A destination address is required.

  • WSAEFAULT The nSockAddrLen argument is incorrect.

  • WSAEINVAL Invalid host address.

  • WSAEISCONN The socket is already connected.

  • WSAEMFILE No more file descriptors are available.

  • WSAENETUNREACH The network cannot be reached from this host at this time.

  • WSAENOBUFS No buffer space is available. The socket cannot be connected.

  • WSAENOTSOCK The descriptor is not a socket.

  • WSAETIMEDOUT Attempt to connect timed out without establishing a connection.

  • WSAEWOULDBLOCK The socket is marked as nonblocking and the connection cannot be completed immediately.

Parameters

lpszHostAddress

The network address of the socket to which this object is connected: a machine name such as “ftp.microsoft.com”, or a dotted number such as “128.56.22.8”.

nHostPort

The port identifying the socket application.

lpSockAddr

A pointer to a SOCKADDR structure that contains the address of the connected socket.

nSockAddrLen

The length of the address in lpSockAddr in bytes.

Remarks

Call this member function to establish a connection to an unconnected stream or datagram socket. If the socket is unbound, unique values are assigned to the local association by the system, and the socket is marked as bound. Note that if the address field of the name structure is all zeroes, Connect will return zero. To get extended error information, call the GetLastError member function.

For stream sockets (type SOCK_STREAM), an active connection is initiated to the foreign host. When the socket call completes successfully, the socket is ready to send/receive data.

For a datagram socket (type SOCK_DGRAM), a default destination is set, which will be used on subsequent Send and Receive calls.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Accept, CAsyncSocket::Bind, CAsyncSocket::GetSockName, CAsyncSocket::Create, CAsyncSocket::AsyncSelect


CAsyncSocket::Create

BOOL Create( UINT nSocketPort = 0, int nSocketType = SOCK_STREAM, long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, LPCTSTR lpszSocketAddress = NULL );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEAFNOSUPPORT The specified address family is not supported.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAEMFILE No more file descriptors are available.

  • WSAENOBUFS No buffer space is available. The socket cannot be created.

  • WSAEPROTONOSUPPORT The specified port is not supported.

  • WSAEPROTOTYPE The specified port is the wrong type for this socket.

  • WSAESOCKTNOSUPPORT The specified socket type is not supported in this address family.

Parameters

nSocketPort

A well-known port to be used with the socket, or 0 if you want Windows Sockets to select a port.

nSocketType

SOCK_STREAM or SOCK_DGRAM.

lEvent

A bitmask which specifies a combination of network events in which the application is interested.

  • FD_READ Want to receive notification of readiness for reading.

  • FD_WRITE Want to receive notification of readiness for writing.

  • FD_OOB Want to receive notification of the arrival of out-of-band data.

  • FD_ACCEPT Want to receive notification of incoming connections.

  • FD_CONNECT Want to receive notification of completed connection.

  • FD_CLOSE Want to receive notification of socket closure.

lpszSockAddress

A pointer to a string containing the network address of the connected socket, a dotted number such as "128.56.22.8".

Remarks

Call the Create member function after constructing a socket object to create the Windows socket and attach it. Create then calls Bind to bind the socket to the specified address. The following socket types are supported:

  • SOCK_STREAM Provides sequenced, reliable, full-duplex, connection-based byte streams. Uses the Transmission Control Protocol (TCP) for the Internet address family.

  • SOCK_DGRAM Supports datagrams, which are connectionless, unreliable packets of a fixed (typically small) maximum length. Uses the User Datagram Protocol (UDP) for the Internet address family.

    Note The Accept member function takes a reference to a new, empty CSocket object as its parameter. You must construct this object before you call Accept. Keep in mind that if this socket object goes out of scope, the connection closes. Do not call Create for this new socket object.

For more information about stream and datagram sockets, see the articles Windows Sockets: Background and Windows Sockets: Ports and Socket Addresses in Visual C++ Programmer's Guide and Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Accept, CAsyncSocket::Bind, CAsyncSocket::Connect, CAsyncSocket::GetSockName,CAsyncSocket::IOCtl, CAsyncSocket::Listen, CAsyncSocket::Receive, CAsyncSocket::Send, CAsyncSocket::ShutDown


CAsyncSocket::Detach

SOCKET Detach( );

Remarks

Call this member function to detach the SOCKET handle in the m_hSocket data member from the CAsyncSocket object and set m_hSocket to NULL.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Attach


CAsyncSocket::FromHandle

static CAsyncSocket* PASCAL FromHandle( SOCKET hSocket );

Return Value

A pointer to an CAsyncSocket object, or NULL if there is no CAsyncSocket object attached to hSocket.

Parameters

hSocket

Contains a handle to a socket.

Remarks

Returns a pointer to a CAsyncSocket object. When given a SOCKET handle, if a CAsyncSocket object is not attached to the handle, the member function returns NULL.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CSocket::FromHandle, CAsyncSocket::Attach, CAsyncSocket::Detach


CAsyncSocket::GetLastError

static int GetLastError( );

Return Value

The return value indicates the error code for the last Windows Sockets API routine performed by this thread.

Remarks

Call this member function to get the error status for the last operation that failed. When a particular member function indicates that an error has occurred, GetLastError should be called to retrieve the appropriate error code. See the individual member function descriptions for a list of applicable error codes.

For more information about the error codes, see Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also ::WSASetLastError


CAsyncSocket::GetPeerName

BOOL GetPeerName( CString& rPeerAddress, UINT& rPeerPort );

BOOL GetPeerName( SOCKADDR* lpSockAddr, int* lpSockAddrLen );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEFAULT The lpSockAddrLen argument is not large enough.

  • WSAEINPROGRESS A blocking Windows Sockets call is in progress.

  • WSAENOTCONN The socket is not connected.

  • WSAENOTSOCK The descriptor is not a socket.

Parameters

rPeerAddress

Reference to a CString object that receives a dotted number IP address.

rPeerPort

Reference to a UINT that stores a port.

lpSockAddr

A pointer to the SOCKADDR structure that receives the name of the peer socket.

lpSockAddrLen

A pointer to the length of the address in lpSockAddr in bytes. On return, the lpSockAddrLen argument contains the actual size of lpSockAddr returned in bytes.

Remarks

Call this member function to get the address of the peer socket to which this socket is connected.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Bind, CAsyncSocket::Connect, CAsyncSocket::Create, CAsyncSocket::GetSockName


CAsyncSocket::GetSockName

BOOL GetSockName( CString& rSocketAddress, UINT& rSocketPort );

BOOL GetSockName( SOCKADDR* lpSockAddr, int* lpSockAddrLen );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEFAULT The lpSockAddrLen argument is not large enough.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAENOTSOCK The descriptor is not a socket.

  • WSAEINVAL The socket has not been bound to an address with Bind.

Parameters

rSocketAddress

Reference to a CString object that receives a dotted number IP address.

rSocketPort

Reference to a UINT that stores a port.

lpSockAddr

A pointer to a SOCKADDR structure that receives the address of the socket.

lpSockAddrLen

A pointer to the length of the address in lpSockAddr in bytes.

Remarks

Call this member function to get the local name for a socket. This call is especially useful when a Connect call has been made without doing a Bind first; this call provides the only means by which you can determine the local association which has been set by the system. For more information, see Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Bind, CAsyncSocket::Create, CAsyncSocket::GetPeerName


CAsyncSocket::GetSockOpt

BOOL GetSockOpt( int nOptionName, void* lpOptionValue, int* lpOptionLen, int nLevel = SOL_SOCKET );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. If an option was never set with SetSockOpt, then GetSockOpt returns the default value for the option. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEFAULT The lpOptionLen argument was invalid.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAENOPROTOOPT The option is unknown or unsupported. In particular, SO_BROADCAST is not supported on sockets of type SOCK_STREAM, while SO_ACCEPTCONN, SO_DONTLINGER, SO_KEEPALIVE, SO_LINGER, and SO_OOBINLINE are not supported on sockets of type SOCK_DGRAM.

  • WSAENOTSOCK The descriptor is not a socket.

Parameters

nOptionName

The socket option for which the value is to be retrieved.

lpOptionValue

A pointer to the buffer in which the value for the requested option is to be returned. The value associated with the selected option is returned in the buffer lpOptionValue. The integer pointed to by lpOptionLen should originally contain the size of this buffer in bytes; and on return, it will be set to the size of the value returned. For SO_LINGER, this will be the size of a LINGER structure; for all other options it will be the size of a BOOL or an int, depending on the option. See the list of options and their sizes in the Remarks section.

lpOptionLen

A pointer to the size of the lpOptionValue buffer in bytes.

nLevel

The level at which the option is defined; the only supported levels are SOL_SOCKET and IPPROTO_TCP.

Remarks

Call this member function to retrieve a socket option. GetSockOpt retrieves the current value for a socket option associated with a socket of any type, in any state, and stores the result in lpOptionValue. Options affect socket operations, such as the routing of packets, out-of-band data transfer, and so on.

The following options are supported for GetSockOpt. The Type identifies the type of data addressed by lpOptionValue. The TCP_NODELAY option uses level IPPROTO_TCP; all other options use level SOL_SOCKET.

Value | Type | Meaning
SO_ACCEPTCONN | BOOL | Socket is listening.
SO_BROADCAST | BOOL | Socket is configured for the transmission of broadcast messages.
SO_DEBUG | BOOL | Debugging is enabled.
SO_DONTLINGER | BOOL | If true, the SO_LINGER option is disabled.
SO_DONTROUTE | BOOL | Routing is disabled.
SO_ERROR | int | Retrieve error status and clear.
SO_KEEPALIVE | BOOL | Keep-alives are being sent.
SO_LINGER | struct LINGER | Returns the current linger options.
SO_OOBINLINE | BOOL | Out-of-band data is being received in the normal data stream.
SO_RCVBUF | int | Buffer size for receives.
SO_REUSEADDR | BOOL | The socket can be bound to an address which is already in use.
SO_SNDBUF | int | Buffer size for sends.
SO_TYPE | int | The type of the socket (for example, SOCK_STREAM).
TCP_NODELAY | BOOL | Disables the Nagle algorithm for send coalescing.

Berkeley Software Distribution (BSD) options not supported for GetSockOpt are:

Value | Type | Meaning
SO_RCVLOWAT | int | Receive low water mark.
SO_RCVTIMEO | int | Receive timeout.
SO_SNDLOWAT | int | Send low water mark.
SO_SNDTIMEO | int | Send timeout.
IP_OPTIONS |  | Get options in IP header.
TCP_MAXSEG | int | Get TCP maximum segment size.

Calling GetSockOpt with an unsupported option will result in an error code of WSAENOPROTOOPT being returned from GetLastError.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::SetSockOpt


CAsyncSocket::IOCtl

BOOL IOCtl( long lCommand, DWORD* lpArgument );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEINVAL lCommand is not a valid command, or lpArgument is not an acceptable parameter for lCommand, or the command is not applicable to the type of socket supplied.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAENOTSOCK The descriptor is not a socket.

Parameters

lCommand

The command to perform on the socket.

lpArgument

A pointer to a parameter for lCommand.

Remarks

Call this member function to control the mode of a socket. This routine can be used on any socket in any state. It is used to get or retrieve operating parameters associated with the socket, independent of the protocol and communications subsystem. The following commands are supported:

  • FIONBIO Enable or disable nonblocking mode on the socket. The lpArgument parameter points at a DWORD, which is nonzero if nonblocking mode is to be enabled and zero if it is to be disabled. If AsyncSelect has been issued on a socket, then any attempt to use IOCtl to set the socket back to blocking mode will fail with WSAEINVAL. To set the socket back to blocking mode and prevent the WSAEINVAL error, an application must first disable AsyncSelect by calling AsyncSelect with the lEvent parameter equal to 0, then call IOCtl.

  • FIONREAD Determine the maximum number of bytes that can be read with one Receive call from this socket. The lpArgument parameter points at a DWORD in which IOCtl stores the result. If this socket is of type SOCK_STREAM, FIONREAD returns the total amount of data which can be read in a single Receive; this is normally the same as the total amount of data queued on the socket. If this socket is of type SOCK_DGRAM, FIONREAD returns the size of the first datagram queued on the socket.

  • SIOCATMARK Determine whether all out-of-band data has been read. This applies only to a socket of type SOCK_STREAM which has been configured for in-line reception of any out-of-band data (SO_OOBINLINE). If no out-of-band data is waiting to be read, the operation returns nonzero. Otherwise it returns 0, and the next Receive or ReceiveFrom performed on the socket will retrieve some or all of the data preceding the “mark”; the application should use the SIOCATMARK operation to determine whether any data remains. If there is any normal data preceding the “urgent” (out-of-band) data, it will be received in order. (Note that a Receive or ReceiveFrom will never mix out-of-band and normal data in the same call.) The lpArgument parameter points at a DWORD in which IOCtl stores the result.

This function is a subset of ioctl() as used in Berkeley sockets. In particular, there is no command which is equivalent to FIOASYNC, while SIOCATMARK is the only socket-level command which is supported.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::AsyncSelect, CAsyncSocket::Create, CAsyncSocket::GetSockOpt, CAsyncSocket::SetSockOpt


CAsyncSocket::Listen

BOOL Listen( int nConnectionBacklog = 5 );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEADDRINUSE An attempt has been made to listen on an address in use.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAEINVAL The socket has not been bound with Bind or is already connected.

  • WSAEISCONN The socket is already connected.

  • WSAEMFILE No more file descriptors are available.

  • WSAENOBUFS No buffer space is available.

  • WSAENOTSOCK The descriptor is not a socket.

  • WSAEOPNOTSUPP The referenced socket is not of a type that supports the Listen operation.

Parameters

nConnectionBacklog

The maximum length to which the queue of pending connections can grow. Valid range is from 1 to 5.

Remarks

Call this member function to listen for incoming connection requests. To accept connections, the socket is first created with Create, a backlog for incoming connections is specified with Listen, and then the connections are accepted with Accept. Listen applies only to sockets that support connections, that is, those of type SOCK_STREAM. This socket is put into “passive” mode where incoming connections are acknowledged and queued pending acceptance by the process.

This function is typically used by servers (or any application that wants to accept connections) that could have more than one connection request at a time: if a connection request arrives with the queue full, the client will receive an error with an indication of WSAECONNREFUSED.

Listen attempts to continue to function rationally when there are no available ports (descriptors). It will accept connections until the queue is emptied. If ports become available, a later call to Listen or Accept will refill the queue to the current or most recent “backlog,” if possible, and resume listening for incoming connections.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Accept, CAsyncSocket::Connect, CAsyncSocket::Create


CAsyncSocket::OnAccept

virtual void OnAccept( int nErrorCode );

Parameters

nErrorCode

The most recent error on a socket. The following error codes applies to the OnAccept member function:

  • 0 The function executed successfully.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

Remarks

Called by the framework to notify a listening socket that it can accept pending connection requests by calling the Accept member function. For more information, see the article Windows Sockets: Socket Notifications in Visual C++ Programmer's Guide.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Accept, CAsyncSocket::GetLastError, CAsyncSocket::OnClose, CAsyncSocket::OnConnect, CAsyncSocket::OnOutOfBandData, CAsyncSocket::OnReceive, CAsyncSocket::OnSend


CAsyncSocket::OnClose

virtual void OnClose( int nErrorCode );

Parameters

nErrorCode

The most recent error on a socket. The following error codes apply to the OnClose member function:

  • 0 The function executed successfully.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAECONNRESET The connection was reset by the remote side.

  • WSAECONNABORTED The connection was aborted due to timeout or other failure.

Remarks

Called by the framework to notify this socket that the connected socket is closed by its process. For more information, see the article Windows Sockets: Socket Notifications in Visual C++ Programmer's Guide.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Close, CAsyncSocket::GetLastError, CAsyncSocket::OnAccept, CAsyncSocket::OnConnect, CAsyncSocket::OnOutOfBandData, CAsyncSocket::OnReceive, CAsyncSocket::OnSend


CAsyncSocket::OnConnect

virtual void OnConnect( int nErrorCode );

Parameters

nErrorCode

The most recent error on a socket. The following error codes apply to the OnConnect member function:

  • 0 The function executed successfully.

  • WSAEADDRINUSE The specified address is already in use.

  • WSAEADDRNOTAVAIL The specified address is not available from the local machine.

  • WSAEAFNOSUPPORT Addresses in the specified family cannot be used with this socket.

  • WSAECONNREFUSED The attempt to connect was forcefully rejected.

  • WSAEDESTADDRREQ A destination address is required.

  • WSAEFAULT The lpSockAddrLen argument is incorrect.

  • WSAEINVAL The socket is already bound to an address.

  • WSAEISCONN The socket is already connected.

  • WSAEMFILE No more file descriptors are available.

  • WSAENETUNREACH The network cannot be reached from this host at this time.

  • WSAENOBUFS No buffer space is available. The socket cannot be connected.

  • WSAENOTCONN The socket is not connected.

  • WSAENOTSOCK The descriptor is a file, not a socket.

  • WSAETIMEDOUT The attempt to connect timed out without establishing a connection.

Remarks

Called by the framework to notify this connecting socket that its connection attempt is completed, whether successfully or in error.

Important In CSocket, the OnConnect notification function is never called.

For connections, you simply call Connect, which will return when the connection is completed (either successfully or in error). How connection notifications are handled is an MFC implementation detail.

For more information, see the article Windows Sockets: Socket Notifications in Visual C++ Programmer's Guide.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Connect, CAsyncSocket::GetLastError, CAsyncSocket::OnAccept, CAsyncSocket::OnClose, CAsyncSocket::OnOutOfBandData, CAsyncSocket::OnReceive, CAsyncSocket::OnSend


CAsyncSocket::OnOutOfBandData

virtual void OnOutOfBandData( int nErrorCode );

Parameters

nErrorCode

The most recent error on a socket. The following error codes apply to the OnOutOfBandData member function:

  • 0 The function executed successfully.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

Remarks

Called by the framework to notify the receiving socket that the sending socket has out-of-band data to send. Out-of-band data is a logically independent channel that is associated with each pair of connected sockets of type SOCK_STREAM. The channel is generally used to send urgent data.

MFC supports out-of-band data, but users of class CAsyncSocket are discouraged from using it. The easier way is to create a second socket for passing such data. For more information about out-of-band data, see the article Windows Sockets: Socket Notifications in Visual C++ Programmer's Guide and Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::GetLastError, CAsyncSocket::OnAccept, CAsyncSocket::OnClose, CAsyncSocket::OnConnect, CAsyncSocket::OnReceive, CAsyncSocket::OnSend


CAsyncSocket::OnReceive

virtual void OnReceive( int nErrorCode );

Parameters

nErrorCode

The most recent error on a socket. The following error codes apply to the OnReceive member function:

  • 0 The function executed successfully.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

Remarks

Called by the framework to notify this socket that there is data in the buffer that can be retrieved by calling the Receive member function. For more information, see the article Windows Sockets: Socket Notifications in Visual C++ Programmer's Guide.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::GetLastError, CAsyncSocket::OnAccept, CAsyncSocket::OnClose, CAsyncSocket::OnConnect, CAsyncSocket::OnOutOfBandData, CAsyncSocket::OnSend, CAsyncSocket::Receive


CAsyncSocket::OnSend

virtual void OnSend( int nErrorCode );

Parameters

nErrorCode

The most recent error on a socket. The following error codes apply to the OnSend member function:

  • 0 The function executed successfully.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

Remarks

Called by the framework to notify the socket that it can now send data by calling the Send member function.

For more information, see the article Windows Sockets: Socket Notifications in Visual C++ Programmer's Guide.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::GetLastError, CAsyncSocket::OnAccept, CAsyncSocket::OnClose, CAsyncSocket::OnConnect, CAsyncSocket::OnOutOfBandData, CAsyncSocket::OnReceive, CAsyncSocket::Send


CAsyncSocket::Receive

virtual int Receive( void* lpBuf, int nBufLen, int nFlags = 0 );

Return Value

If no error occurs, Receive returns the number of bytes received. If the connection has been closed, it returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAENOTCONN The socket is not connected.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAENOTSOCK The descriptor is not a socket.

  • WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not of type SOCK_STREAM.

  • WSAESHUTDOWN The socket has been shut down; it is not possible to call Receive on a socket after ShutDown has been invoked with nHow set to 0 or 2.

  • WSAEWOULDBLOCK The socket is marked as nonblocking and the Receive operation would block.

  • WSAEMSGSIZE The datagram was too large to fit into the specified buffer and was truncated.

  • WSAEINVAL The socket has not been bound with Bind.

  • WSAECONNABORTED The virtual circuit was aborted due to timeout or other failure.

  • WSAECONNRESET The virtual circuit was reset by the remote side.

Parameters

lpBuf

A buffer for the incoming data.

nBufLen

The length of lpBuf in bytes.

nFlags

Specifies the way in which the call is made. The semantics of this function are determined by the socket options and the nFlags parameter. The latter is constructed by combining any of the following values with the C++ OR operator:

  • MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not removed from the input queue.

  • MSG_OOB Process out-of-band data (see Windows Sockets Programming Considerations in the Win32 SDK documentation for a discussion of this topic).

Remarks

Call this member function to receive data from a socket. This function is used for connected stream or datagram sockets and is used to read incoming data.

For sockets of type SOCK_STREAM, as much information as is currently available up to the size of the buffer supplied is returned. If the socket has been configured for in-line reception of out-of-band data (socket option SO_OOBINLINE) and out-of-band data is unread, only out-of-band data will be returned. The application can use the IOCtl SIOCATMARK option or OnOutOfBandData to determine whether any more out-of-band data remains to be read.

For datagram sockets, data is extracted from the first enqueued datagram, up to the size of the buffer supplied. If the datagram is larger than the buffer supplied, the buffer is filled with the first part of the datagram, the excess data is lost, and Receive returns a value of SOCKET_ERROR with the error code set to WSAEMSGSIZE. If no incoming data is available at the socket, a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The OnReceive callback function can be used to determine when more data arrives.

If the socket is of type SOCK_STREAM and the remote side has shut down the connection gracefully, a Receive will complete immediately with 0 bytes received. If the connection has been reset, a Receive will fail with the error WSAECONNRESET.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::AsyncSelect, CAsyncSocket::Create, CAsyncSocket::ReceiveFrom, CAsyncSocket::Send


CAsyncSocket::ReceiveFrom

int ReceiveFrom( void* lpBuf, int nBufLen, CString& rSocketAddress, UINT& rSocketPort, int nFlags = 0 );

int ReceiveFrom( void* lpBuf, int nBufLen, SOCKADDR* lpSockAddr, int* lpSockAddrLen, int nFlags = 0 );

Return Value

If no error occurs, ReceiveFrom returns the number of bytes received. If the connection has been closed, it returns 0. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEFAULT The lpSockAddrLen argument was invalid: the lpSockAddr buffer was too small to accommodate the peer address.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAEINVAL The socket has not been bound with Bind.

  • WSAENOTCONN The socket is not connected (SOCK_STREAM only).

  • WSAENOTSOCK The descriptor is not a socket.

  • WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not of type SOCK_STREAM.

  • WSAESHUTDOWN The socket has been shut down; it is not possible to call ReceiveFrom on a socket after ShutDown has been invoked with nHow set to 0 or 2.

  • WSAEWOULDBLOCK The socket is marked as nonblocking and the ReceiveFrom operation would block.

  • WSAEMSGSIZE The datagram was too large to fit into the specified buffer and was truncated.

  • WSAECONNABORTED The virtual circuit was aborted due to timeout or other failure.

  • WSAECONNRESET The virtual circuit was reset by the remote side.

Parameters

lpBuf

A buffer for the incoming data.

nBufLen

The length of lpBuf in bytes.

rSocketAddress

Reference to a CString object that receives a dotted number IP address.

rSocketPort

Reference to a UINT that stores a port.

lpSockAddr

A pointer to a SOCKADDR structure that holds the source address upon return.

lpSockAddrLen

A pointer to the length of the source address in lpSockAddr in bytes.

nFlags

Specifies the way in which the call is made. The semantics of this function are determined by the socket options and the nFlags parameter. The latter is constructed by combining any of the following values with the C++ OR operator:

  • MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not removed from the input queue.

  • MSG_OOB Process out-of-band data (see Windows Sockets Programming Considerations in the Win32 SDK documentation for a discussion of this topic).

Remarks

Call this member function to receive a datagram and store the source address in the SOCKADDR structure or in rSocketAddress. This function is used to read incoming data on a (possibly connected) socket and capture the address from which the data was sent.

For sockets of type SOCK_STREAM, as much information as is currently available up to the size of the buffer supplied is returned. If the socket has been configured for in-line reception of out-of-band data (socket option SO_OOBINLINE) and out-of-band data is unread, only out-of-band data will be returned. The application can use the IOCtl SIOCATMARK option or OnOutOfBandData to determine whether any more out-of-band data remains to be read. The lpSockAddr and lpSockAddrLen parameters are ignored for SOCK_STREAM sockets.

For datagram sockets, data is extracted from the first enqueued datagram, up to the size of the buffer supplied. If the datagram is larger than the buffer supplied, the buffer is filled with the first part of the message, the excess data is lost, and ReceiveFrom returns a value of SOCKET_ERROR with the error code set to WSAEMSGSIZE.

If lpSockAddr is nonzero, and the socket is of type SOCK_DGRAM, the network address of the socket which sent the data is copied to the corresponding SOCKADDR structure. The value pointed to by lpSockAddrLen is initialized to the size of this structure, and is modified on return to indicate the actual size of the address stored there. If no incoming data is available at the socket, the ReceiveFrom call waits for data to arrive unless the socket is nonblocking. In this case, a value of SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The OnReceive callback can be used to determine when more data arrives.

If the socket is of type SOCK_STREAM and the remote side has shut down the connection gracefully, a ReceiveFrom will complete immediately with 0 bytes received.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::AsyncSelect, CAsyncSocket::Create, CAsyncSocket::Receive, CAsyncSocket::Send


CAsyncSocket::Send

virtual int Send( const void* lpBuf, int nBufLen, int nFlags = 0 );

Return Value

If no error occurs, Send returns the total number of characters sent. (Note that this can be less than the number indicated by nBufLen.) Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEACCES The requested address is a broadcast address, but the appropriate flag was not set.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAEFAULT The lpBuf argument is not in a valid part of the user address space.

  • WSAENETRESET The connection must be reset because the Windows Sockets implementation dropped it.

  • WSAENOBUFS The Windows Sockets implementation reports a buffer deadlock.

  • WSAENOTCONN The socket is not connected.

  • WSAENOTSOCK The descriptor is not a socket.

  • WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not of type SOCK_STREAM.

  • WSAESHUTDOWN The socket has been shut down; it is not possible to call Send on a socket after ShutDown has been invoked with nHow set to 1 or 2.

  • WSAEWOULDBLOCK The socket is marked as nonblocking and the requested operation would block.

  • WSAEMSGSIZE The socket is of type SOCK_DGRAM, and the datagram is larger than the maximum supported by the Windows Sockets implementation.

  • WSAEINVAL The socket has not been bound with Bind.

  • WSAECONNABORTED The virtual circuit was aborted due to timeout or other failure.

  • WSAECONNRESET The virtual circuit was reset by the remote side.

Parameters

lpBuf

A buffer containing the data to be transmitted.

nBufLen

The length of the data in lpBuf in bytes.

nFlags

Specifies the way in which the call is made. The semantics of this function are determined by the socket options and the nFlags parameter. The latter is constructed by combining any of the following values with the C++ OR operator:

  • MSG_DONTROUTE Specifies that the data should not be subject to routing. A Windows Sockets supplier can choose to ignore this flag; see also the discussion of the SO_DONTROUTE option in Windows Sockets Programming Considerations in the Win32 SDK documentation.

  • MSG_OOB Send out-of-band data (SOCK_STREAM only).

Remarks

Call this member function to send data on a connected socket. Send is used to write outgoing data on connected stream or datagram sockets. For datagram sockets, care must be taken not to exceed the maximum IP packet size of the underlying subnets, which is given by the iMaxUdpDg element in the WSADATA structure returned by AfxSocketInit. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned via GetLastError, and no data is transmitted.

Note that for a datagram socket the successful completion of a Send does not indicate that the data was successfully delivered.

On CAsyncSocket objects of type SOCK_STREAM, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both the local and foreign hosts.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Create, CAsyncSocket::Receive, CAsyncSocket::ReceiveFrom, CAsyncSocket::SendTo


CAsyncSocket::SendTo

int SendTo( const void* lpBuf, int nBufLen, UINT nHostPort, LPCTSTR lpszHostAddress = NULL, int nFlags = 0 );

int SendTo( const void* lpBuf, int nBufLen, const SOCKADDR* lpSockAddr, int nSockAddrLen, int nFlags = 0 );

Return Value

If no error occurs, SendTo returns the total number of characters sent. (Note that this can be less than the number indicated by nBufLen.) Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEACCES The requested address is a broadcast address, but the appropriate flag was not set.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAEFAULT The lpBuf or lpSockAddr parameters are not part of the user address space, or the lpSockAddr argument is too small (less than the size of a SOCKADDR structure).

  • WSAEINVAL The host name is invalid.

  • WSAENETRESET The connection must be reset because the Windows Sockets implementation dropped it.

  • WSAENOBUFS The Windows Sockets implementation reports a buffer deadlock.

  • WSAENOTCONN The socket is not connected (SOCK_STREAM only).

  • WSAENOTSOCK The descriptor is not a socket.

  • WSAEOPNOTSUPP MSG_OOB was specified, but the socket is not of type SOCK_STREAM.

  • WSAESHUTDOWN The socket has been shut down; it is not possible to call SendTo on a socket after ShutDown has been invoked with nHow set to 1 or 2.

  • WSAEWOULDBLOCK The socket is marked as nonblocking and the requested operation would block.

  • WSAEMSGSIZE The socket is of type SOCK_DGRAM, and the datagram is larger than the maximum supported by the Windows Sockets implementation.

  • WSAECONNABORTED The virtual circuit was aborted due to timeout or other failure.

  • WSAECONNRESET The virtual circuit was reset by the remote side.

  • WSAEADDRNOTAVAIL The specified address is not available from the local machine.

  • WSAEAFNOSUPPORT Addresses in the specified family cannot be used with this socket.

  • WSAEDESTADDRREQ A destination address is required.

  • WSAENETUNREACH The network cannot be reached from this host at this time.

Parameters

lpBuf

A buffer containing the data to be transmitted.

nBufLen

The length of the data in lpBuf in bytes.

nHostPort

The port identifying the socket application.

lpszHostAddress

The network address of the socket to which this object is connected: a machine name such as “ftp.microsoft.com,” or a dotted number such as “128.56.22.8”.

nFlags

Specifies the way in which the call is made. The semantics of this function are determined by the socket options and the nFlags parameter. The latter is constructed by combining any of the following values with the C++ OR operator:

  • MSG_DONTROUTE Specifies that the data should not be subject to routing. A Windows Sockets supplier can choose to ignore this flag; see also the discussion of the SO_DONTROUTE option in Windows Sockets Programming Considerations in the Win32 SDK documentation.

  • MSG_OOB Send out-of-band data (SOCK_STREAM only).

lpSockAddr

A pointer to a SOCKADDR structure that contains the address of the target socket.

nSockAddrLen

The length of the address in lpSockAddr in bytes.

Remarks

Call this member function to send data to a specific destination. SendTo is used on datagram or stream sockets and is used to write outgoing data on a socket. For datagram sockets, care must be taken not to exceed the maximum IP packet size of the underlying subnets, which is given by the iMaxUdpDg element in the WSADATA structure filled out by AfxSocketInit. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned, and no data is transmitted.

Note that the successful completion of a SendTo does not indicate that the data was successfully delivered.

SendTo is only used on a SOCK_DGRAM socket to send a datagram to a specific socket identified by the lpSockAddr parameter.

To send a broadcast (on a SOCK_DGRAM only), the address in the lpSockAddr parameter should be constructed using the special IP address INADDR_BROADCAST (defined in the Windows Sockets header file WINSOCK.H) together with the intended port number. Or, if the lpszHostAddress parameter is NULL, the socket is configured for broadcast. It is generally inadvisable for a broadcast datagram to exceed the size at which fragmentation can occur, which implies that the data portion of the datagram (excluding headers) should not exceed 512 bytes.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Create, CAsyncSocket::Receive, CAsyncSocket::ReceiveFrom, CAsyncSocket::Send


CAsyncSocket::SetSockOpt

BOOL SetSockOpt( int nOptionName, const void* lpOptionValue, int nOptionLen, int nLevel = SOL_SOCKET );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEFAULT lpOptionValue is not in a valid part of the process address space.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAEINVAL nLevel is not valid, or the information in lpOptionValue is not valid.

  • WSAENETRESET Connection has timed out when SO_KEEPALIVE is set.

  • WSAENOPROTOOPT The option is unknown or unsupported. In particular, SO_BROADCAST is not supported on sockets of type SOCK_STREAM, while SO_DONTLINGER, SO_KEEPALIVE, SO_LINGER, and SO_OOBINLINE are not supported on sockets of type SOCK_DGRAM.

  • WSAENOTCONN Connection has been reset when SO_KEEPALIVE is set.

  • WSAENOTSOCK The descriptor is not a socket.

Parameters

nOptionName

The socket option for which the value is to be set.

lpOptionValue

A pointer to the buffer in which the value for the requested option is supplied.

nOptionLen

The size of the lpOptionValue buffer in bytes.

nLevel

The level at which the option is defined; the only supported levels are SOL_SOCKET and IPPROTO_TCP.

Remarks

Call this member function to set a socket option. SetSockOpt sets the current value for a socket option associated with a socket of any type, in any state. Although options can exist at multiple protocol levels, this specification only defines options that exist at the uppermost “socket” level. Options affect socket operations, such as whether expedited data is received in the normal data stream, whether broadcast messages can be sent on the socket, and so on.

There are two types of socket options: Boolean options that enable or disable a feature or behavior, and options which require an integer value or structure. To enable a Boolean option, lpOptionValue points to a nonzero integer. To disable the option lpOptionValue points to an integer equal to zero. nOptionLen should be equal to sizeof(BOOL) for Boolean options. For other options, lpOptionValue points to the integer or structure that contains the desired value for the option, and nOptionLen is the length of the integer or structure.

SO_LINGER controls the action taken when unsent data is queued on a socket and the Close function is called to close the socket. For more information, see Windows Sockets Programming Considerations in the Win32 SDK documentation.

By default, a socket cannot be bound (see Bind) to a local address which is already in use. On occasion, however, it may be desirable to “reuse” an address in this way. Since every connection is uniquely identified by the combination of local and remote addresses, there is no problem with having two sockets bound to the same local address as long as the remote addresses are different.

To inform the Windows Sockets implementation that a Bind call on a socket should not be disallowed because the desired address is already in use by another socket, the application should set the SO_REUSEADDR socket option for the socket before issuing the Bind call. Note that the option is interpreted only at the time of the Bind call: it is therefore unnecessary (but harmless) to set the option on a socket which is not to be bound to an existing address, and setting or resetting the option after the Bind call has no effect on this or any other socket.

An application can request that the Windows Sockets implementation enable the use of “keep-alive” packets on Transmission Control Protocol (TCP) connections by turning on the SO_KEEPALIVE socket option. (For information about “keep-alive” packets, see Windows Sockets Programming Considerations in the Win32 SDK documentation.) A Windows Sockets implementation need not support the use of keep-alives: if it does, the precise semantics are implementation-specific but should conform to section 4.2.3.6 of RFC 1122: “Requirements for Internet Hosts — Communication Layers.” If a connection is dropped as the result of “keep-alives” the error code WSAENETRESET is returned to any calls in progress on the socket, and any subsequent calls will fail with WSAENOTCONN.

The TCP_NODELAY option disables the Nagle algorithm. The Nagle algorithm is used to reduce the number of small packets sent by a host by buffering unacknowledged send data until a full-size packet can be sent. However, for some applications this algorithm can impede performance, and TCP_NODELAY can be used to turn it off. Application writers should not set TCP_NODELAY unless the impact of doing so is well-understood and desired, since setting TCP_NODELAY can have a significant negative impact on network performance. TCP_NODELAY is the only supported socket option which uses level IPPROTO_TCP; all other options use level SOL_SOCKET.

Some implementations of Windows Sockets supply output debug information if the SO_DEBUG option is set by an application.

The following options are supported for SetSockOpt. The Type identifies the type of data addressed by lpOptionValue.

Value | Type | Meaning
SO_BROADCAST | BOOL | Allow transmission of broadcast messages on the socket.
SO_DEBUG | BOOL | Record debugging information.
SO_DONTLINGER | BOOL | Don't block Close waiting for unsent data to be sent. Setting this option is equivalent to setting SO_LINGER with l_onoff set to zero.
SO_DONTROUTE | BOOL | Don't route: send directly to interface.
SO_KEEPALIVE | BOOL | Send keep-alives.
SO_LINGER | struct LINGER | Linger on Close if unsent data is present.
SO_OOBINLINE | BOOL | Receive out-of-band data in the normal data stream.
SO_RCVBUF | int | Specify buffer size for receives.
SO_REUSEADDR | BOOL | Allow the socket to be bound to an address which is already in use. (See Bind.)
SO_SNDBUF | int | Specify buffer size for sends.
TCP_NODELAY | BOOL | Disables the Nagle algorithm for send coalescing.

Berkeley Software Distribution (BSD) options not supported for SetSockOpt are:

Value | Type | Meaning
SO_ACCEPTCONN | BOOL | Socket is listening
SO_ERROR | int | Get error status and clear.
SO_RCVLOWAT | int | Receive low water mark.
SO_RCVTIMEO | int | Receive timeout
SO_SNDLOWAT | int | Send low water mark.
SO_SNDTIMEO | int | Send timeout.
SO_TYPE | int | Type of the socket.
IP_OPTIONS |  | Set options field in IP header.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::AsyncSelect, CAsyncSocket::Bind, CAsyncSocket::Create, CAsyncSocket::GetSockOpt, CAsyncSocket::IOCtl


CAsyncSocket::ShutDown

BOOL ShutDown( int nHow = sends );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError. The following errors apply to this member function:

  • WSANOTINITIALISED A successful AfxSocketInit must occur before using this API.

  • WSAENETDOWN The Windows Sockets implementation detected that the network subsystem failed.

  • WSAEINVAL nHow is not valid.

  • WSAEINPROGRESS A blocking Windows Sockets operation is in progress.

  • WSAENOTCONN The socket is not connected (SOCK_STREAM only).

  • WSAENOTSOCK The descriptor is not a socket.

Parameters

nHow

A flag that describes what types of operation will no longer be allowed, using the following enumerated values:

  • receives = 0

  • sends = 1

  • both = 2

Remarks

Call this member function to disable sends and/or receives on the socket. ShutDown is used on all types of sockets to disable reception, transmission, or both. If nHow is 0, subsequent receives on the socket will be disallowed. This has no effect on the lower protocol layers.

For Transmission Control Protocol (TCP), the TCP window is not changed and incoming data will be accepted (but not acknowledged) until the window is exhausted. For User Datagram Protocol (UDP), incoming datagrams are accepted and queued. In no case will an ICMP error packet be generated. If nHow is 1, subsequent sends are disallowed. For TCP sockets, a FIN will be sent. Setting nHow to 2 disables both sends and receives as described above.

Note that ShutDown does not close the socket, and resources attached to the socket will not be freed until Close is called. An application should not rely on being able to reuse a socket after it has been shut down. In particular, a Windows Sockets implementation is not required to support the use of Connect on such a socket.

CAsyncSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Connect, CAsyncSocket::Create


CAsyncSocket::m_hSocket

Remarks

Contains the SOCKET handle for the socket encapsulated by this CAsyncSocket object.


CBitmap

The CBitmap class encapsulates a Windows graphics device interface (GDI) bitmap and provides member functions to manipulate the bitmap. To use a CBitmap object, construct the object, attach a bitmap handle to it with one of the initialization member functions, and then call the object’s member functions.

For more information on using graphic objects like CBitmap, see Graphic Objects in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MDI


CBitmap Class Members

Construction

CBitmap Constructs a CBitmap object.

Initialization

LoadBitmap | Initializes the object by loading a named bitmap resource from the application’s executable file and attaching the bitmap to the object.
LoadOEMBitmap | Initializes the object by loading a predefined Windows bitmap and attaching the bitmap to the object.
LoadMappedBitmap | Loads a bitmap and maps colors to current system colors.
CreateBitmap | Initializes the object with a device-dependent memory bitmap that has a specified width, height, and bit pattern.
CreateBitmapIndirect | Initializes the object with a bitmap with the width, height, and bit pattern (if one is specified) given in a BITMAP structure.
CreateCompatibleBitmap | Initializes the object with a bitmap so that it is compatible with a specified device.
CreateDiscardableBitmap | Initializes the object with a discardable bitmap that is compatible with a specified device.

Attributes

GetBitmap | Fills a BITMAP structure with information about the bitmap.
operator HBITMAP | Returns the Windows handle attached to the CBitmap object.

Operations

FromHandle | Returns a pointer to a CBitmap object when given a handle to a Windows HBITMAP bitmap.
SetBitmapBits | Sets the bits of a bitmap to the specified bit values.
GetBitmapBits | Copies the bits of the specified bitmap into the specified buffer.
SetBitmapDimension | Assigns a width and height to a bitmap in 0.1-millimeter units.
GetBitmapDimension | Returns the width and height of the bitmap. The height and width are assumed to have been set previously by the SetBitmapDimension member function.


CBitmap::CBitmap

CBitmap( );

Remarks

Constructs a CBitmap object. The resulting object must be initialized with one of the initialization member functions.

CBitmap Overview | Class Members | Hierarchy Chart

See Also CBitmap::LoadBitmap, CBitmap::LoadOEMBitmap, CBitmap::CreateBitmap, CBitmap::CreateBitmapIndirect, CBitmap::CreateCompatibleBitmap, CBitmap::CreateDiscardableBitmap


CBitmap::CreateBitmap

BOOL CreateBitmap( int nWidth, int nHeight, UINT nPlanes, UINT nBitcount, const void* lpBits );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nWidth

Specifies the width (in pixels) of the bitmap.

nHeight

Specifies the height (in pixels) of the bitmap.

nPlanes

Specifies the number of color planes in the bitmap.

nBitcount

Specifies the number of color bits per display pixel.

lpBits

Points to a short-integer array that contains the initial bitmap bit values. If it is NULL, the new bitmap is left uninitialized.

Remarks

Initializes a device-dependent memory bitmap that has the specified width, height, and bit pattern.

For a color bitmap, either the nPlanes or nBitcount parameter should be set to 1. If both of these parameters are set to 1, CreateBitmap creates a monochrome bitmap.

Although a bitmap cannot be directly selected for a display device, it can be selected as the current bitmap for a “memory device context” by using CDC::SelectObject and copied to any compatible device context by using the CDC::BitBlt function.

When you finish with the CBitmap object created by the CreateBitmap function, first select the bitmap out of the device context, then delete the CBitmap object.

For more information, see the description of the bmBits field in the BITMAP structure. The BITMAP structure is described under the CBitmap::CreateBitmapIndirect member function.

CBitmap Overview | Class Members | Hierarchy Chart

See Also CDC::SelectObject, CGdiObject::DeleteObject, CDC::BitBlt, ::CreateBitmap


CBitmap::CreateBitmapIndirect

BOOL CreateBitmapIndirect( LPBITMAP lpBitmap );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpBitmap

Points to a BITMAP structure that contains information about the bitmap.

Remarks

Initializes a bitmap that has the width, height, and bit pattern (if one is specified) given in the structure pointed to by lpBitmap. Although a bitmap cannot be directly selected for a display device, it can be selected as the current bitmap for a memory device context by using CDC::SelectObject and copied to any compatible device context by using the CDC::BitBlt or CDC::StretchBlt function. (The CDC::PatBlt function can copy the bitmap for the current brush directly to the display device context.)

If the BITMAP structure pointed to by the lpBitmap parameter has been filled in by using the GetObject function, the bits of the bitmap are not specified and the bitmap is uninitialized. To initialize the bitmap, an application can use a function such as CDC::BitBlt or ::SetDIBits to copy the bits from the bitmap identified by the first parameter of CGdiObject::GetObject to the bitmap created by CreateBitmapIndirect.

When you finish with the CBitmap object created with CreateBitmapIndirect function, first select the bitmap out of the device context, then delete the CBitmap object.

CBitmap Overview | Class Members | Hierarchy Chart

See Also CDC::SelectObject, CDC::BitBlt, CGdiObject::DeleteObject, CGdiObject::GetObject, ::CreateBitmapIndirect


CBitmap::CreateCompatibleBitmap

BOOL CreateCompatibleBitmap( CDC* pDC, int nWidth, int nHeight );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDC

Specifies the device context.

nWidth

Specifies the width (in pixels) of the bitmap.

nHeight

Specifies the height (in pixels) of the bitmap.

Remarks

Initializes a bitmap that is compatible with the device specified by pDC. The bitmap has the same number of color planes or the same bits-per-pixel format as the specified device context. It can be selected as the current bitmap for any memory device that is compatible with the one specified by pDC.

If pDC is a memory device context, the bitmap returned has the same format as the currently selected bitmap in that device context. A “memory device context” is a block of memory that represents a display surface. It can be used to prepare images in memory before copying them to the actual display surface of the compatible device.

When a memory device context is created, GDI automatically selects a monochrome stock bitmap for it.

Since a color memory device context can have either color or monochrome bitmaps selected, the format of the bitmap returned by the CreateCompatibleBitmap function is not always the same; however, the format of a compatible bitmap for a nonmemory device context is always in the format of the device.

When you finish with the CBitmap object created with the CreateCompatibleBitmap function, first select the bitmap out of the device context, then delete the CBitmap object.

CBitmap Overview | Class Members | Hierarchy Chart

See Also ::CreateCompatibleBitmap, CGdiObject::DeleteObject


CBitmap::CreateDiscardableBitmap

BOOL CreateDiscardableBitmap( CDC* pDC, int nWidth, int nHeight );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDC

Specifies a device context.

nWidth

Specifies the width (in bits) of the bitmap.

nHeight

Specifies the height (in bits) of the bitmap.

Remarks

Initializes a discardable bitmap that is compatible with the device context identified by pDC. The bitmap has the same number of color planes or the same bits-per-pixel format as the specified device context. An application can select this bitmap as the current bitmap for a memory device that is compatible with the one specified by pDC.

Windows can discard a bitmap created by this function only if an application has not selected it into a display context. If Windows discards the bitmap when it is not selected and the application later attempts to select it, the CDC::SelectObject function will return NULL.

When you finish with the CBitmap object created with the CreateDiscardableBitmap function, first select the bitmap out of the device context, then delete the CBitmap object.

CBitmap Overview | Class Members | Hierarchy Chart

See Also ::CreateDiscardableBitmap, CGdiObject::DeleteObject


CBitmap::FromHandle

static CBitmap* PASCAL FromHandle( HBITMAP hBitmap );

Return Value

A pointer to a CBitmap object if successful; otherwise NULL.

Parameters

hBitmap

Specifies a Windows GDI bitmap.

Remarks

Returns a pointer to a CBitmap object when given a handle to a Windows GDI bitmap. If a CBitmap object is not already attached to the handle, a temporary CBitmap object is created and attached. This temporary CBitmap object is valid only until the next time the application has idle time in its event loop, at which time all temporary graphic objects are deleted. Another way of saying this is that the temporary object is only valid during the processing of one window message.


CBitmap::GetBitmap

int GetBitmap( BITMAP* pBitMap );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pBitMap

Pointer to a BITMAP structure. Must not be NULL.

Remarks

Call this member function to retrieve information about a CBitmap object. This information is returned in the BITMAP structure referred to by pBitmap.

CBitmap Overview | Class Members | Hierarchy Chart

See Also BITMAP


CBitmap::GetBitmapBits

DWORD GetBitmapBits( DWORD dwCount, LPVOID lpBits ) const;

Return Value

The actual number of bytes in the bitmap, or 0 if there is an error.

Parameters

dwCount

Specifies the number of bytes to be copied.

lpBits

Points to the buffer that is to receive the bitmap. The bitmap is an array of bytes. The bitmap byte array conforms to a structure where horizontal scan lines are multiples of 16 bits.

Remarks

Copies the bit pattern of the CBitmap object into the buffer that is pointed to by lpBits. The dwCount parameter specifies the number of bytes to be copied to the buffer. Use CGdiObject::GetObject to determine the correct dwCount value for the given bitmap.

CBitmap Overview | Class Members | Hierarchy Chart

See Also CGdiObject::GetObject, ::GetBitmapBits


CBitmap::GetBitmapDimension

CSize GetBitmapDimension( ) const;

Return Value

The width and height of the bitmap, measured in 0.1-millimeter units. The height is in the cy member of the CSize object, and the width is in the cx member. If the bitmap width and height have not been set by using SetBitmapDimension, the return value is 0.

Remarks

Returns the width and height of the bitmap. The height and width are assumed to have been set previously by using the SetBitmapDimension member function.

CBitmap Overview | Class Members | Hierarchy Chart

See Also CBitmap::SetBitmapDimension


CBitmap::LoadBitmap

BOOL LoadBitmap( LPCTSTR lpszResourceName );

BOOL LoadBitmap( UINT nIDResource );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszResourceName

Points to a null-terminated string that contains the name of the bitmap resource.

nIDResource

Specifies the resource ID number of the bitmap resource.

Remarks

Loads the bitmap resource named by lpszResourceName or identified by the ID number in nIDResource from the application’s executable file. The loaded bitmap is attached to the CBitmap object.

If the bitmap identified by lpszResourceName does not exist or if there is insufficient memory to load the bitmap, the function returns 0.

You can use the CGdiObject::DeleteObject function to delete bitmap loaded by the LoadBitmap function, or the CBitmap destructor will delete the object for you.

! WARNING Before you delete the object, make sure it is not selected into a device context.

The following bitmaps were added to Windows versions 3.1 and later:

OBM_UPARRROWI
OBM_DNARROWI
OBM_RGARROWI
OBM_LFARROWI

These bitmaps are not found in device drivers for Windows versions 3.0 and earlier. For a complete list of bitmaps and a display of their appearance, see the Win32 Programmer’s Reference.

CBitmap Overview | Class Members | Hierarchy Chart

See Also CBitmap::LoadOEMBitmap, ::LoadBitmap, CGdiObject::DeleteObject


CBitmap::LoadMappedBitmap

BOOL LoadMappedBitmap( UINT nIDBitmap, UINT nFlags = 0, LPCOLORMAP lpColorMap = NULL, int nMapSize = 0 );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nIDBitmap

The ID of the bitmap resource.

nFlags

A flag for a bitmap. Can be zero or CMB_MASKED.

lpColorMap

A pointer to a COLORMAP structure that contains the color information needed to map the bitmaps. If this parameter is NULL, the function uses the default color map.

nMapSize

The number of color maps pointed to by lpColorMap.

Remarks

Call this member function to load a bitmap and map the colors to the current system colors. By default, LoadMappedBitmap will map colors commonly used in button glyphs.

For information about creating a mapped bitmap, see the Windows function ::CreateMappedBitmap and the COLORMAP structure in the Win32 Programmer’s Reference.

CBitmap Overview | Class Members | Hierarchy Chart

See Also ::LoadBitmap, ::CreateMappedBitmap


CBitmap::LoadOEMBitmap

BOOL LoadOEMBitmap( UINT nIDBitmap );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nIDBitmap

ID number of the predefined Windows bitmap. The possible values are listed below from WINDOWS.H:

OBM_BTNCORNERS | OBM_OLD_RESTORE
OBM_BTSIZE | OBM_OLD_RGARROW
OBM_CHECK | OBM_OLD_UPARROW
OBM_CHECKBOXES | OBM_OLD_ZOOM
OBM_CLOSE | OBM_REDUCE
OBM_COMBO | OBM_REDUCED
OBM_DNARROW | OBM_RESTORE
OBM_DNARROWD | OBM_RESTORED
OBM_DNARROWI | OBM_RGARROW
OBM_LFARROW | OBM_RGARROWD
OBM_LFARROWD | OBM_RGARROWI
OBM_LFARROWI | OBM_SIZE
OBM_MNARROW | OBM_UPARROW
OBM_OLD_CLOSE | OBM_UPARROWD
OBM_OLD_DNARROW | OBM_UPARROW
OBM_OLD_LFARROW | OBM_ZOOM
OBM_OLD_REDUCE | OBM_ZOOMD

Remarks

Loads a predefined bitmap used by Windows.

Bitmap names that begin with OBM_OLD represent bitmaps used by Windows versions prior to 3.0.

Note that the constant OEMRESOURCE must be defined before including WINDOWS.H in order to use any of the OBM_ constants.

CBitmap Overview | Class Members | Hierarchy Chart

See Also CBitmap::LoadBitmap, ::LoadBitmap


CBitmap::operator HBITMAP

operator HBITMAP( ) const;

Return Value

If successful, a handle to the Windows GDI object represented by the CBitmap object; otherwise NULL.

Remarks

Use this operator to get the attached Windows GDI handle of the CBitmap object. This operator is a casting operator, which supports direct use of an HBITMAP object.

For more information about using graphic objects, see Graphic Objects in the Win32 Programmer’s Reference.


CBitmap::SetBitmapBits

DWORD SetBitmapBits( DWORD dwCount, const void* lpBits );

Return Value

The number of bytes used in setting the bitmap bits; 0 if the function fails.

Parameters

dwCount

Specifies the number of bytes pointed to by lpBits.

lpBits

Points to the BYTE array that contains the bit values to be copied to the CBitmap object.

Remarks

Sets the bits of a bitmap to the bit values given by lpBits.

CBitmap Overview | Class Members | Hierarchy Chart

See Also ::SetBitmapBits


CBitmap::SetBitmapDimension

CSize SetBitmapDimension( int nWidth, int nHeight );

Return Value

The previous bitmap dimensions. Height is in the cy member variable of the CSize object, and width is in the cx member variable.

Parameters

nWidth

Specifies the width of the bitmap (in 0.1-millimeter units).

nHeight

Specifies the height of the bitmap (in 0.1-millimeter units).

Remarks

Assigns a width and height to a bitmap in 0.1-millimeter units. The GDI does not use these values except to return them when an application calls the GetBitmapDimension member function.

CBitmap Overview | Class Members | Hierarchy Chart

See Also CBitmap::GetBitmapDimension


CBitmapButton

Use the CBitmapButton class to create pushbutton controls labeled with bitmapped images instead of text. CBitmapButton objects contain up to four bitmaps, which contain images for the different states a button can assume: up (or normal), down (or selected), focused, and disabled. Only the first bitmap is required; the others are optional.

Bitmap-button images include the border around the image as well as the image itself. The border typically plays a part in showing the state of the button. For example, the bitmap for the focused state usually is like the one for the up state but with a dashed rectangle inset from the border or a thick solid line at the border. The bitmap for the disabled state usually resembles the one for the up state but has lower contrast (like a dimmed or grayed menu selection).

These bitmaps can be of any size, but all are treated as if they were the same size as the bitmap for the up state.

Various applications demand different combinations of bitmap images:

Up | Down | Focused | Disabled | Application
× |  |  |  | Bitmap
× | × |  |  | Button without WS_TABSTOP style
× | × | × | × | Dialog button with all states
× | × | × |  | Dialog button with WS_TABSTOP style

When creating a bitmap-button control, set the BS_OWNERDRAW style to specify that the button is owner-drawn. This causes Windows to send the WM_MEASUREITEM and WM_DRAWITEM messages for the button; the framework handles these messages and manages the appearance of the button for you.

To create a bitmap-button control in a window’s client area, follow these steps:

  1. Create one to four bitmap images for the button.

  2. Construct the CBitmapButton object.

  3. Call the Create function to create the Windows button control and attach it to the CBitmapButton object.

  4. Call the LoadBitmaps member function to load the bitmap resources after the bitmap button is constructed.

To include a bitmap-button control in a dialog box, follow these steps:

  5. Create one to four bitmap images for the button.

  6. Create a dialog template with an owner-draw button positioned where you want the bitmap button. The size of the button in the template does not matter.

  7. Set the button’s caption to a value such as “MYIMAGE” and define a symbol for the button such as IDC_MYIMAGE.

  8. In your application’s resource script, give each of the images created for the button an ID constructed by appending one of the letters “U,” “D,” “F,” or “X” (for up, down, focused, and disabled) to the string used for the button caption in step 3. For the button caption “MYIMAGE,” for example, the IDs would be “MYIMAGEU,” “MYIMAGED,” “MYIMAGEF,” and “MYIMAGEX.” You must specify the ID of your bitmaps within double quotes. Otherwise the resource editor will assign an integer to the resource and MFC will fail when loading the image.

  9. In your application’s dialog class (derived from CDialog), add a CBitmapButton member object.

  10. In the CDialog object’s OnInitDialog routine, call the CBitmapButton object’s AutoLoad function, using as parameters the button’s control ID and the CDialog object’s this pointer.

If you want to handle Windows notification messages, such as BN_CLICKED, sent by a bitmap-button control to its parent (usually a class derived from CDialog), add to the CDialog-derived object a message-map entry and message-handler member function for each message. The notifications sent by a CBitmapButton object are the same as those sent by a CButton object.

The class CToolBar takes a different approach to bitmap buttons.

For more information on CBitmapButton, see Control Topics in Visual C++ Programmer's Guide.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CTRLTEST


CBitmapButton Class Members

Construction

CBitmapButton | Constructs a CBitmapButton object.
LoadBitmaps | Initializes the object by loading one or more named bitmap resources from the application’s resource file and attaching the bitmaps to the object.
AutoLoad | Associates a button in a dialog box with an object of the CBitmapButton class, loads the bitmap(s) by name, and sizes the button to fit the bitmap.

Operations

SizeToContent Sizes the button to accommodate the bitmap.


CBitmapButton::AutoLoad

BOOL AutoLoad( UINT nID, CWnd* pParent );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nID

The button’s control ID.

pParent

Pointer to the object that owns the button.

Remarks

Associates a button in a dialog box with an object of the CBitmapButton class, loads the bitmap(s) by name, and sizes the button to fit the bitmap.

Use the AutoLoad function to initialize an owner-draw button in a dialog box as a bitmap button. Instructions for using this function are in the remarks for the CBitmapButton class.

CBitmapButton Overview | Class Members | Hierarchy Chart

See Also CBitmapButton::LoadBitmaps, CBitmapButton::SizeToContent


CBitmapButton::CBitmapButton

CBitmapButton( );

Remarks

Creates a CBitmapButton object.

After creating the C++ CBitmapButton object, call CButton::Create to create the Windows button control and attach it to the CBitmapButton object.

CBitmapButton Overview | Class Members | Hierarchy Chart

See Also CBitmapButton::LoadBitmaps, CBitmapButton::AutoLoad, CBitmapButton::SizeToContent, CButton::Create


CBitmapButton::LoadBitmaps

BOOL LoadBitmaps( LPCTSTR lpszBitmapResource, LPCTSTR lpszBitmapResourceSel = NULL, LPCTSTR lpszBitmapResourceFocus = NULL, LPCTSTR lpszBitmapResourceDisabled = NULL );

BOOL LoadBitmaps( UINT nIDBitmapResource, UINT nIDBitmapResourceSel = 0, UINT nIDBitmapResourceFocus = 0, UINT nIDBitmapResourceDisabled = 0 );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszBitmapResource

Points to the null-terminated string that contains the name of the bitmap for a bitmap button’s normal or “up” state. Required.

lpszBitmapResourceSel

Points to the null-terminated string that contains the name of the bitmap for a bitmap button’s selected or “down” state. May be NULL.

lpszBitmapResourceFocus

Points to the null-terminated string that contains the name of the bitmap for a bitmap button’s focused state. May be NULL.

lpszBitmapResourceDisabled

Points to the null-terminated string that contains the name of the bitmap for a bitmap button’s disabled state. May be NULL.

nIDBitmapResource

Specifies the resource ID number of the bitmap resource for a bitmap button’s normal or “up” state. Required.

nIDBitmapResourceSel

Specifies the resource ID number of the bitmap resource for a bitmap button’s selected or “down” state. May be 0.

nIDBitmapResourceFocus

Specifies the resource ID number of the bitmap resource for a bitmap button’s focused state. May be 0.

nIDBitmapResourceDisabled

Specifies the resource ID number of the bitmap resource for a bitmap button’s disabled state. May be 0.

Remarks

Use this function when you want to load bitmap images identified by their resource names or ID numbers, or when you cannot use the AutoLoad function because, for example, you are creating a bitmap button that is not part of a dialog box.

CBitmapButton Overview | Class Members | Hierarchy Chart

See Also CBitmapButton::AutoLoad, CBitmapButton::SizeToContent, CButton::Create, CBitmap::LoadBitmap


CBitmapButton::SizeToContent

void SizeToContent( );

Remarks

Call this function to resize a bitmap button to the size of the bitmap.

CBitmapButton Overview | Class Members | Hierarchy Chart

See Also CBitmapButton::LoadBitmaps, CBitmapButton::AutoLoad


CBrush

The CBrush class encapsulates a Windows graphics device interface (GDI) brush. To use a CBrush object, construct a CBrush object and pass it to any CDC member function that requires a brush.

Brushes can be solid, hatched, or patterned.

For more information on CBrush, see Graphic Objects in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample PROPDLG

See Also CBitmap, CDC


CBrush Class Members

Construction

CBrush Constructs a CBrush object.

Initialization

CreateSolidBrush | Initializes a brush with the specified solid color.
CreateHatchBrush | Initializes a brush with the specified hatched pattern and color.
CreateBrushIndirect | Initializes a brush with the style, color, and pattern specified in a LOGBRUSH structure.
CreatePatternBrush | Initializes a brush with a pattern specified by a bitmap.
CreateDIBPatternBrush | Initializes a brush with a pattern specified by a device-independent bitmap (DIB).
CreateSysColorBrush | Creates a brush that is the default system color.

Operations

FromHandle Returns a pointer to a CBrush object when given a handle to a Windows HBRUSH object.

Attributes

GetLogBrush | Gets a LOGBRUSH structure.
operator HBRUSH | Returns the Windows handle attached to the CBrush object.


CBrush::CBrush

CBrush( );

CBrush( COLORREF crColor );
throw( CResourceException );

CBrush( int nIndex, COLORREF crColor );
throw( CResourceException );

CBrush( CBitmap* pBitmap );
throw( CResourceException );

Parameters

crColor

Specifies the foreground color of the brush as an RGB color. If the brush is hatched, this parameter specifies the color of the hatching.

nIndex

Specifies the hatch style of the brush. It can be any one of the following values:

  • HS_BDIAGONAL Downward hatch (left to right) at 45 degrees

  • HS_CROSS Horizontal and vertical crosshatch

  • HS_DIAGCROSS Crosshatch at 45 degrees

  • HS_FDIAGONAL Upward hatch (left to right) at 45 degrees

  • HS_HORIZONTAL Horizontal hatch

  • HS_VERTICAL Vertical hatch

pBitmap

Points to a CBitmap object that specifies a bitmap with which the brush paints.

Remarks

Has four overloaded constructors. The constructor with no arguments constructs an uninitialized CBrush object that must be initialized before it can be used.

If you use the constructor with no arguments, you must initialize the resulting CBrush object with CreateSolidBrush, CreateHatchBrush, CreateBrushIndirect, CreatePatternBrush, or CreateDIBPatternBrush. If you use one of the constructors that takes arguments, then no further initialization is necessary. The constructors with arguments can throw an exception if errors are encountered, while the constructor with no arguments will always succeed.

The constructor with a single COLORREF parameter constructs a solid brush with the specified color. The color specifies an RGB value and can be constructed with the RGB macro in WINDOWS.H.

The constructor with two parameters constructs a hatch brush. The nIndex parameter specifies the index of a hatched pattern. The crColor parameter specifies the color.

The constructor with a CBitmap parameter constructs a patterned brush. The parameter identifies a bitmap. The bitmap is assumed to have been created by using CBitmap::CreateBitmap, CBitmap::CreateBitmapIndirect, CBitmap::LoadBitmap, or CBitmap::CreateCompatibleBitmap. The minimum size for a bitmap to be used in a fill pattern is 8 pixels by 8 pixels.

CBrush Overview | Class Members | Hierarchy Chart

See Also CBrush::CreateSolidBrush, CBrush::CreateHatchBrush, CBrush::CreateBrushIndirect, CBrush::CreatePatternBrush, CBrush::CreateDIBPatternBrush, CGdiObject::CreateStockObject


CBrush::CreateBrushIndirect

BOOL CreateBrushIndirect( const LOGBRUSH* lpLogBrush );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpLogBrush

Points to a LOGBRUSH structure that contains information about the brush.

Remarks

Initializes a brush with a style, color, and pattern specified in a LOGBRUSH structure. The brush can subsequently be selected as the current brush for any device context.

A brush created using a monochrome (1 plane, 1 bit per pixel) bitmap is drawn using the current text and background colors. Pixels represented by a bit set to 0 will be drawn with the current text color. Pixels represented by a bit set to 1 will be drawn with the current background color.

CBrush Overview | Class Members | Hierarchy Chart

See Also CBrush::CreateDIBPatternBrush, CBrush::CreatePatternBrush, CBrush::CreateSolidBrush, CBrush::CreateHatchBrush, CGdiObject::CreateStockObject, CGdiObject::DeleteObject, ::CreateBrushIndirect


CBrush::CreateDIBPatternBrush

BOOL CreateDIBPatternBrush( HGLOBAL hPackedDIB, UINT nUsage );

BOOL CreateDIBPatternBrush( const void* lpPackedDIB, UINT nUsage );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hPackedDIB

Identifies a global-memory object containing a packed device-independent bitmap (DIB).

nUsage

Specifies whether the bmiColors[] fields of the BITMAPINFO data structure (a part of the “packed DIB”) contain explicit RGB values or indices into the currently realized logical palette. The parameter must be one of the following values:

  • DIB_PAL_COLORS The color table consists of an array of 16-bit indexes.

  • DIB_RGB_COLORS The color table contains literal RGB values.

    The following value is available only in the second version of this member function:

  • DIB_PAL_INDICES No color table is provided. The bitmap itself contains indices into the logical palette of the device context into which the brush is to be selected.

lpPackedDIB

Points to a packed DIB consisting of a BITMAPINFO structure immediately followed by an array of bytes defining the pixels of the bitmap.

Remarks

Initializes a brush with the pattern specified by a device-independent bitmap (DIB). The brush can subsequently be selected for any device context that supports raster operations.

The two versions differ in the way you handle the DIB:

  • In the first version, to obtain a handle to the DIB you call the Windows ::GlobalAlloc function to allocate a block of global memory and then fill the memory with the packed DIB.

  • In the second version, it is not necessary to call ::GlobalAlloc to allocate memory for the packed DIB.

A packed DIB consists of a BITMAPINFO data structure immediately followed by the array of bytes that defines the pixels of the bitmap. Bitmaps used as fill patterns should be 8 pixels by 8 pixels. If the bitmap is larger, Windows creates a fill pattern using only the bits corresponding to the first 8 rows and 8 columns of pixels in the upper-left corner of the bitmap.

When an application selects a two-color DIB pattern brush into a monochrome device context, Windows ignores the colors specified in the DIB and instead displays the pattern brush using the current text and background colors of the device context. Pixels mapped to the first color (at offset 0 in the DIB color table) of the DIB are displayed using the text color. Pixels mapped to the second color (at offset 1 in the color table) are displayed using the background color.

For information about using the following Windows functions, see the Win32 SDK Programmer’s Reference:

  • ::CreateDIBPatternBrush (This function is provided only for compatibility with applications written for versions of Windows earlier than 3.0; use the ::CreateDIBPatternBrushPt function.)

  • ::CreateDIBPatternBrushPt (This function should be used for Win32-based applications.)

  • ::GlobalAlloc

CBrush Overview | Class Members | Hierarchy Chart

See Also CBrush::CreatePatternBrush, CBrush::CreateBrushIndirect, CBrush::CreateSolidBrush, CBrush::CreateHatchBrush, CGdiObject::CreateStockObject, CDC::SelectObject, CGdiObject::DeleteObject, CDC::GetBrushOrg, CDC::SetBrushOrg


CBrush::CreateHatchBrush

BOOL CreateHatchBrush( int nIndex, COLORREF crColor );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nIndex

Specifies the hatch style of the brush. It can be any one of the following values:

  • HS_BDIAGONAL Downward hatch (left to right) at 45 degrees

  • HS_CROSS Horizontal and vertical crosshatch

  • HS_DIAGCROSS Crosshatch at 45 degrees

  • HS_FDIAGONAL Upward hatch (left to right) at 45 degrees

  • HS_HORIZONTAL Horizontal hatch

  • HS_VERTICAL Vertical hatch

crColor

Specifies the foreground color of the brush as an RGB color (the color of the hatches). See COLORREF in the Win32 SDK documentation for more information.

Remarks

Initializes a brush with the specified hatched pattern and color. The brush can subsequently be selected as the current brush for any device context.

CBrush Overview | Class Members | Hierarchy Chart

See Also CBrush::CreateBrushIndirect, CBrush::CreateDIBPatternBrush, CBrush::CreatePatternBrush, CBrush::CreateSolidBrush, CGdiObject::CreateStockObject, ::CreateHatchBrush


CBrush::CreatePatternBrush

BOOL CreatePatternBrush( CBitmap* pBitmap );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pBitmap

Identifies a bitmap.

Remarks

Initializes a brush with a pattern specified by a bitmap. The brush can subsequently be selected for any device context that supports raster operations. The bitmap identified by pBitmap is typically initialized by using the CBitmap::CreateBitmap, CBitmap::CreateBitmapIndirect, CBitmap::LoadBitmap, or CBitmap::CreateCompatibleBitmap function.

Bitmaps used as fill patterns should be 8 pixels by 8 pixels. If the bitmap is larger, Windows will only use the bits corresponding to the first 8 rows and columns of pixels in the upper-left corner of the bitmap.

A pattern brush can be deleted without affecting the associated bitmap. This means the bitmap can be used to create any number of pattern brushes.

A brush created using a monochrome bitmap (1 color plane, 1 bit per pixel) is drawn using the current text and background colors. Pixels represented by a bit set to 0 are drawn with the current text color. Pixels represented by a bit set to 1 are drawn with the current background color.

For information about using ::CreatePatternBrush, a Windows function, see the Win32 SDK Programmer’s Reference.

CBrush Overview | Class Members | Hierarchy Chart

See Also CBitmap, CBrush::CreateBrushIndirect, CBrush::CreateDIBPatternBrush, CBrush::CreateHatchBrush, CBrush::CreateSolidBrush, CGdiObject::CreateStockObject


CBrush::CreateSolidBrush

BOOL CreateSolidBrush( COLORREF crColor );

Return Value

Nonzero if successful; otherwise 0.

Parameters

crColor

A COLORREF structure that specifies the color of the brush. The color specifies an RGB value and can be constructed with the RGB macro in WINDOWS.H.

Remarks

Initializes a brush with a specified solid color. The brush can subsequently be selected as the current brush for any device context.

When an application has finished using the brush created by CreateSolidBrush, it should select the brush out of the device context.

CBrush Overview | Class Members | Hierarchy Chart

See Also CBrush::CreateBrushIndirect, CBrush::CreateDIBPatternBrush, CBrush::CreateHatchBrush, CBrush::CreatePatternBrush, ::CreateSolidBrush, CGdiObject::DeleteObject


CBrush::CreateSysColorBrush

BOOL CreateSysColorBrush( int nIndex );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nIndex

Specifies the hatch style of the brush. It can be any one of the following values:

  • HS_BDIAGONAL Downward hatch (left to right) at 45 degrees

  • HS_CROSS Horizontal and vertical crosshatch

  • HS_DIAGCROSS Crosshatch at 45 degrees

  • HS_FDIAGONAL Upward hatch (left to right) at 45 degrees

  • HS_HORIZONTAL Horizontal hatch

  • HS_VERTICAL Vertical hatch

Remarks

Initializes a brush color. The brush can subsequently be selected as the current brush for any device context.

When an application has finished using the brush created by CreateSysColorBrush, it should select the brush out of the device context.

CBrush Overview | Class Members | Hierarchy Chart

See Also CBrush::CreateBrushIndirect, CBrush::CreateDIBPatternBrush, CBrush::CreateHatchBrush, CBrush::CreatePatternBrush, ::CreateSolidBrush, CBrush::CreateSolidBrush, ::GetSysColorBrush, CGdiObject::DeleteObject


CBrush::FromHandle

static CBrush* PASCAL FromHandle( HBRUSH hBrush );

Return Value

A pointer to a CBrush object if successful; otherwise NULL.

Parameters

hBrush

HANDLE to a Windows GDI brush.

Remarks

Returns a pointer to a CBrush object when given a handle to a Windows HBRUSH object. If a CBrush object is not already attached to the handle, a temporary CBrush object is created and attached. This temporary CBrush object is valid only until the next time the application has idle time in its event loop. At this time, all temporary graphic objects are deleted. In other words, the temporary object is valid only during the processing of one window message.

For more information about using graphic objects, see Graphic Objects in the Win32 SDK Programmer’s Reference.


CBrush::GetLogBrush

int GetLogBrush( LOGBRUSH* pLogBrush );

Return Value

If the function succeeds, and pLogBrush is a valid pointer, the return value is the number of bytes stored into the buffer.

If the function succeeds, and pLogBrush is NULL, the return value is the number of bytes required to hold the information the function would store into the buffer.

If the function fails, the return value is 0.

Parameters

pLogBrush

Points to a LOGBRUSH structure that contains information about the brush.

Remarks

Call this member function to retrieve the LOGBRUSH structure. The LOGBRUSH structure defines the style, color, and pattern of a brush.

For example, call GetLogBrush to match the particular color or pattern of a bitmap.

Example

LOGBRUSH logbrush;
brushExisting.GetLogBrush( &logbrush );
CBrush brushOther( logbrush.lbColor);

CBrush Overview | Class Members | Hierarchy Chart

See Also LOGBRUSH, ::GetObject


CBrush::operator HBRUSH

operator HBRUSH( ) const;

Return Value

If successful, a handle to the Windows GDI object represented by the CBrush object; otherwise NULL.

Remarks

Use this operator to get the attached Windows GDI handle of the CBrush object. This operator is a casting operator, which supports direct use of an HBRUSH object.

For more information about using graphic objects, see Graphic Objects in the Win32 SDK Programmer’s Reference.


CButton

The CButton class provides the functionality of Windows button controls. A button control is a small, rectangular child window that can be clicked on and off. Buttons can be used alone or in groups and can either be labeled or appear without text. A button typically changes appearance when the user clicks it.

Typical buttons are the check box, radio button, and pushbutton. A CButton object can become any of these, according to the button style specified at its initialization by the Create member function.

In addition, the CBitmapButton class derived from CButton supports creation of button controls labeled with bitmap images instead of text. A CBitmapButton can have separate bitmaps for a button's up, down, focused, and disabled states.

You can create a button control either from a dialog template or directly in your code. In both cases, first call the constructor CButton to construct the CButton object; then call the Create member function to create the Windows button control and attach it to the CButton object.

Construction can be a one-step process in a class derived from CButton. Write a constructor for the derived class and call Create from within the constructor.

If you want to handle Windows notification messages sent by a button control to its parent (usually a class derived from CDialog), add a message-map entry and message-handler member function to the parent class for each message.

Each message-map entry takes the following form:

ON_Notification( id, memberFxn )

where id specifies the child window ID of the control sending the notification and memberFxn is the name of the parent member function you have written to handle the notification.

The parent’s function prototype is as follows:

afx_msg void memberFxn( );

Potential message-map entries are as follows:

Map entry | Sent to parent when...
ON_BN_CLICKED | The user clicks a button.
ON_BN_DOUBLECLICKED | The user double-clicks a button.

If you create a CButton object from a dialog resource, the CButton object is automatically destroyed when the user closes the dialog box.

If you create a CButton object within a window, you may need to destroy it. If you create the CButton object on the heap by using the new function, you must call delete on the object to destroy it when the user closes the Windows button control. If you create the CButton object on the stack, or it is embedded in the parent dialog object, it is destroyed automatically.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CWnd, CComboBox, CEdit, CListBox, CScrollBar, CStatic, CBitmapButton, CDialog


CButton Class Members

Construction

CButton Constructs a CButton object.

Initialization

Create Creates the Windows button control and attaches it to the CButton object.

Operations

GetState | Retrieves the check state, highlight state, and focus state of a button control.
SetState | Sets the highlighting state of a button control.
GetCheck | Retrieves the check state of a button control.
SetCheck | Sets the check state of a button control.
GetButtonStyle | Retrieves information about the button control style.
SetButtonStyle | Changes the style of a button.
GetIcon | Retrieves the handle of the icon previously set with SetIcon.
SetIcon | Specifies an icon to be displayed on the button.
GetBitmap | Retrieves the handle of the bitmap previously set with SetBitmap.
SetBitmap | Specifies a bitmap to be displayed on the button.
GetCursor | Retrieves the handle of the cursor image previously set with SetCursor.
SetCursor | Specifies a cursor image to be displayed on the button.

Overridables

DrawItem Override to draw an owner-drawn CButton object.


CButton::CButton

CButton( );

Remarks

Constructs a CButton object.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::Create


CButton::Create

BOOL Create( LPCTSTR lpszCaption, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszCaption

Specifies the button control’s text.

dwStyle

Specifies the button control’s style. Apply any combination of button styles to the button.

rect

Specifies the button control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the button control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the button control’s ID.

Remarks

You construct a CButton object in two steps. First call the constructor, then call Create, which creates the Windows button control and attaches it to the CButton object.

If the WS_VISIBLE style is given, Windows sends the button control all the messages required to activate and show the button.

Apply the following window styles to a button control:

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

  • WS_GROUP To group controls

  • WS_TABSTOP To include the button in the tabbing order

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::CButton


CButton::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A long pointer to a DRAWITEMSTRUCT structure. The structure contains information about the item to be drawn and the type of drawing required.

Remarks

Called by the framework when a visual aspect of an owner-drawn button has changed. An owner-drawn button has the BS_OWNERDRAW style set. Override this member function to implement drawing for an owner-drawn CButton object. The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before the member function terminates.

Also see the BS_ style values.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::SetButtonStyle, WM_DRAWITEM


CButton::GetBitmap

HBITMAP GetBitmap( ) const;

Return Value

A handle to a bitmap. NULL if no bitmap is previously specified.

Remarks

Call this member function to get the handle of a bitmap, previously set with SetBitmap, that is associated with a button.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::SetBitmap, CBitmapButton::LoadBitmaps, Bitmaps


CButton::GetButtonStyle

UINT GetButtonStyle( ) const;

Return Value

Returns the button styles for this CButton object.

Remarks

This function returns only the BS_ style values, not any of the other window styles.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::SetButtonStyle, ::GetWindowLong


CButton::GetCheck

int GetCheck( ) const;

Return Value

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

Value | Meaning
0 | Button state is unchecked.
1 | Button state is checked.
2 | Button state is indeterminate (applies only if the button has the BS_3STATE or BS_AUTO3STATE style).

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

Remarks

Retrieves the check state of a radio button or check box.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::GetState, CButton::SetState, CButton::SetCheck, BM_GETCHECK


CButton::GetCursor

HCURSOR GetCursor( );

Return Value

A handle to a cursor image. NULL if no cursor is previously specified.

Remarks

Call this member function to get the handle of a cursor, previously set with SetCursor, that is associated with a button.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::SetCursor, CBitmapButton::LoadBitmaps, Bitmaps


CButton::GetIcon

HICON GetIcon( ) const;

Return Value

A handle to an icon. NULL if no icon is previously specified.

Remarks

Call this member function to get the handle of an icon, previously set with SetIcon, that is associated with a button.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::SetIcon, CBitmapButton::LoadBitmaps, Bitmaps


CButton::GetState

UINT GetState( ) const;

Return Value

Specifies the current state of the button control. You can use the following masks against the return value to extract information about the state:

Mask | Meaning
0x0003 | Specifies the check state (radio buttons and check boxes only). A 0 indicates the button is unchecked. A 1 indicates the button is checked. A radio button is checked when it contains a bullet (). A check box is checked when it contains an X. A 2 indicates the check state is indeterminate (three-state check boxes only). The state of a three-state check box is indeterminate when it contains a halftone pattern.
0x0004 | Specifies the highlight state. A nonzero value indicates that the button is highlighted. A button is highlighted when the user clicks and holds the left mouse button. The highlighting is removed when the user releases the mouse button.
0x0008 | Specifies the focus state. A nonzero value indicates that the button has the focus.

Remarks

Retrieves the state of a radio button or check box.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::GetCheck, CButton::SetCheck, CButton::SetState, BM_GETSTATE


CButton::SetBitmap

HBITMAP SetBitmap( HBITMAP hBitmap );

Return Value

The handle of a bitmap previously associated with the button.

Parameters

hBitmap

The handle of a bitmap.

Remarks

Call this member function to associate a new bitmap with the button.

The bitmap will be automatically placed on the face of the button, centered by default. If the bitmap is too large for the button, it will be clipped on either side. You can choose other alignment options, including the following:

  • BS_TOP

  • BS_LEFT

  • BS_RIGHT

  • BS_CENTER

  • BS_BOTTOM

  • BS_VCENTER

Unlike CBitmapButton, which uses four bitmaps per button, SetBitmap uses only one bitmap per the button. When the button is pressed, the bitmap appears to shift down and to the right.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::GetBitmap, CBitmapButton, CBitmapButton::LoadBitmaps, Bitmaps


CButton::SetButtonStyle

void SetButtonStyle( UINT nStyle, BOOL bRedraw = TRUE );

Parameters

nStyle

Specifies the button style.

bRedraw

Specifies whether the button is to be redrawn. A nonzero value redraws the button. A 0 value does not redraw the button. The button is redrawn by default.

Remarks

Changes the style of a button.

Use the GetButtonStyle member function to retrieve the button style. The low-order word of the complete button style is the button-specific style.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::GetButtonStyle, BM_SETSTYLE


CButton::SetCheck

void SetCheck( int nCheck );

Parameters

nCheck

Specifies the check state. This parameter can be one of the following:

Value | Meaning
0 | Set the button state to unchecked.
1 | Set the button state to checked.
2 | Set the button state to indeterminate. This value can be used only if the button has the BS_3STATE or BS_AUTO3STATE style.

Remarks

Sets or resets the check state of a radio button or check box. This member function has no effect on a pushbutton.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::GetCheck, CButton::GetState, CButton::SetState, BM_SETCHECK


CButton::SetCursor

HCURSOR SetCursor( HCURSOR hCursor );

Return Value

The handle of a cursor previously associated with the button.

Parameters

hCursor

The handle of a cursor.

Remarks

Call this member function to associate a new cursor with the button.

The cursor will be automatically placed on the face of the button, centered by default. If the cursor is too large for the button, it will be clipped on either side. You can choose other alignment options, including the following:

  • BS_TOP

  • BS_LEFT

  • BS_RIGHT

  • BS_CENTER

  • BS_BOTTOM

  • BS_VCENTER

Unlike CBitmapButton, which uses four bitmaps per button, SetCursor uses only one cursor per the button. When the button is pressed, the cursor appears to shift down and to the right.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::GetCursor, CBitmapButton::LoadBitmaps, Bitmaps


CButton::SetIcon

HICON SetIcon( HICON hIcon );

Return Value

The handle of an icon previously associated with the button.

Parameters

hIcon

The handle of an icon.

Remarks

Call this member function to associate a new icon with the button.

The icon will be automatically placed on the face of the button, centered by default. If the icon is too large for the button, it will be clipped on either side. You can choose other alignment options, including the following:

  • BS_TOP

  • BS_LEFT

  • BS_RIGHT

  • BS_CENTER

  • BS_BOTTOM

  • BS_VCENTER

Unlike CBitmapButton, which uses four bitmaps per button, SetIcon uses only one icon per the button. When the button is pressed, the icon appears to shift down and to the right.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::GetIcon, CBitmapButton::LoadBitmaps, Bitmaps


CButton::SetState

void SetState( BOOL bHighlight );

Parameters

bHighlight

Specifies whether the button is to be highlighted. A nonzero value highlights the button; a 0 value removes any highlighting.

Remarks

Sets the highlighting state of a button control.

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

A button control is automatically highlighted when the user clicks and holds the left mouse button. The highlighting is removed when the user releases the mouse button.

CButton Overview | Class Members | Hierarchy Chart

See Also CButton::GetState, CButton::SetCheck, CButton::GetCheck, BM_SETSTATE


CByteArray

The CByteArray class supports dynamic arrays of bytes.

The member functions of CByteArray are similar to the member functions of class CObArray. Because of this similarity, you can use the CObArray reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a BYTE.

CObject* CObArray::GetAt( int <nIndex> ) const;

for example, translates to

BYTE CByteArray::GetAt( int <nIndex> ) const;

CByteArray incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. If an array of bytes is stored to an archive, either with the overloaded insertion (<<) operator or with the Serialize member function, each element is, in turn, serialized.

Note Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

If you need debug output from individual elements in the array, you must set the depth of the CDumpContext object to 1 or greater.

For more information on using CByteArray, see the article Collections in Visual C++ Programmer's Guide.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

See Also CObArray


CByteArray Class Members

Construction

CByteArray Constructs an empty array for bytes.

Bounds

GetSize | Gets the number of elements in this array.
GetUpperBound | Returns the largest valid index.
SetSize | Sets the number of elements to be contained in this array.

Operations

FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.

Element Access

GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; array not allowed to grow.
ElementAt | Returns a temporary reference to the byte within the array.
GetData | Allows access to elements in the array. Can be NULL.

Growing the Array

SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds an element to the end of the array; grows the array if necessary.
Append | Appends another array to the array; grows the array if necessary.
Copy | Copies another array to the array; grows the array if necessary.

Insertion/Removal

InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.

Operators

operator [] Sets or gets the element at the specified index.


CCachedDataPathProperty

Class CCachedDataPathProperty implements an OLE control property transferred asynchronously and cached in a memory file. A memory file is stored in RAM rather than on disk and is useful for fast temporary transfers.

Along with CAysncMonikerFile and CDataPathProperty, CCachedDataPathProperty provides functionality for the use of asynchronous monikers in OLE controls. With CCachedDataPathProperty objects, you to transfer data asynchronously from a URL or file source and store it in a memory file via the m_Cache public variable. All the data is stored in the memory file, and there is no need to override OnDataAvailable unless you want to watch for notifications and respond. For example, if you are transferring a large .GIF file and want to notify your control that more data has arrived and it should redraw itself, override OnDataAvailable to make the notification.

The class CCachedDataPathProperty is derived from CDataPathProperty.

For more information about how to use asynchronous monikers and ActiveX controls in Internet applications, see the following topics in Visual C++ Programmer's Guide:

  • Internet First Steps: ActiveX Controls

  • Internet First Steps: Asynchronous Monikers

#include <afxctl.h>

Class Members | Base Class | Hierarchy Chart

See Also CDataPathProperty


CCachedDataPathProperty Class Members

Data Members

m_Cache CMemFile object in which to cache data.


CCachedDataPathProperty::m_Cache

CMemFile m_Cache;

Remarks

Contains the class name of the memory file into which data is cached. A memory file is stored in RAM rather than on disk.

CCachedDataPathProperty Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty


CCheckListBox

The CCheckListBox class provides the functionality of a Windows checklist box. A “checklist box” displays a list of items, such as filenames. Each item in the list has a check box next to it that the user can check or clear.

CCheckListBox is only for owner-drawn controls because the list contains more than text strings. At its simplest, a checklist box contains text strings and check boxes, but you do not need to have text at all. For example, you could have a list of small bitmaps with a check box next to each item.

To create your own checklist box, you must derive your own class from CCheckListBox. To derive your own class, write a constructor for the derived class, then call Create.

If your checklist box is a default checklist box (a list of strings with the default-sized checkboxes to the left of each), you can use the default CCheckListBox::DrawItem to draw the checklist box. Otherwise, you must override the CListBox::CompareItem function and the CCheckListBox::DrawItem and CCheckListBox::MeasureItem functions.

You can create a checklist box either from a dialog template or directly in your code.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample TSTCON

See Also CListBox


CCheckListBox Class Members

Construction

CCheckListBox | Constructs a CCheckListBox object.
Create | Creates the Windows checklist box and attaches it to the CCheckListBox object.

Attributes

SetCheckStyle | Sets the style of the control’s check boxes.
GetCheckStyle | Gets the style of the control’s check boxes.
SetCheck | Sets the state of an item’s check box.
GetCheck | Gets the state of an item’s check box.
Enable | Enables or disables a checklist box item.
IsEnabled | Determines whether an item is enabled.
OnGetCheckPosition | Called by the framework to get the position of an item’s check box.

Overridables

DrawItem | Called by the framework when a visual aspect of an owner-draw list box changes.
MeasureItem | Called by the framework when a list box with an owner-draw style is created.


CCheckListBox::CCheckListBox

CCheckListBox( );

Remarks

Constructs a CCheckListBox object.

You construct a CCheckListBox object in two steps. First define a class derived from CCheckListBox, then call Create, which initializes the Windows checklist box and attaches it to the CCheckListBox object. For example:

class CMyCheckListBox : public CCheckListBox
{
   DECLARE_DYNAMIC(CMyCheckListBox)

// Constructors
public:
   CMyCheckListBox();
   BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID);
...

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::Create


CCheckListBox::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise 0.

Parameters

dwStyle

Specifies the style of the checklist box. The style must be either LBS_OWNERDRAWFIXED (all items in the list are the same height) or LBS_OWNERDRAWVARIABLE (items in the list are of varying heights). This style can be combined with other list-box styles.

rect

Specifies the checklist-box size and position. Can be either a CRect object or a RECT structure.

pParentWnd

Specifies the checklist box’s parent window (usually a CDialog object). It must not be NULL.

nID

Specifies the checklist box’s control ID.

Remarks

You construct a CCheckListBox object in two steps. First define a class derived from CCheckListBox, then call Create, which initializes the Windows checklist box and attaches it to the CCheckListBox. See CCheckListBox::CCheckListBox for a sample.

When Create executes, Windows sends the WM_NCCREATE, WM_CREATE, WM_NCCALCSIZE, and WM_GETMINMAXINFO messages to the checklist-box control.

These messages are handled by default by the OnNcCreate, OnCreate, OnNcCalcSize, and OnGetMinMaxInfo member functions in the CWnd base class. To extend the default message handling, add a message map to the your derived class and override the preceding message-handler member functions. Override OnCreate, for example, to perform needed initialization for a new class.

Apply the following window styles to a checklist-box control:

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

  • WS_VSCROLL To add a vertical scroll bar

  • WS_HSCROLL To add a horizontal scroll bar

  • WS_GROUP To group controls

  • WS_TABSTOP To allow tabbing to this control

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::CCheckListBox


CCheckListBox::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A long pointer to a DRAWITEMSTRUCT structure that contains information about the type of drawing required.

Remarks

Called by the framework when a visual aspect of an owner-drawn checklist box changes. The itemAction and itemState members of the DRAWITEMSTRUCT structure define the drawing action that is to be performed.

By default, this function draws a default checkbox list, consisting of a list of strings each with a default-sized checkbox to the left. The checkbox list size is the one specified in Create.

Override this member function to implement drawing of owner-draw checklist boxes that are not the default, such as checklist boxes with lists that aren't strings, with variable-height items, or with checkboxes that aren't on the left. The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before the termination of this member function.

If checklist box items are not all the same height, the checklist box style (specified in Create) must be LBS_OWNERVARIABLE, and you must override the MeasureItem function.

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::Create, CCheckListBox::MeasureItem


CCheckListBox::Enable

void Enable( int nIndex, BOOL bEnabled = TRUE );

Parameters

nIndex

Index of the checklist box item to be enabled.

bEnabled

Specifies whether the item is enabled or disabled.

Remarks

Call this function to enable or disable a checklist box item.

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::IsEnabled


CCheckListBox::GetCheck

int GetCheck( int nIndex );

Return Value

Zero if the item is not checked, 1 if it is checked, and 2 if it is indeterminate.

Parameters

nIndex

Index of the item whose check status is to be retrieved.

Remarks

Call this function to determine the check state of an item.

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::OnGetCheckPosition, CCheckListBox::SetCheck, CCheckListBox::SetCheckStyle, CCheckListBox::GetCheckStyle


CCheckListBox::GetCheckStyle

UINT GetCheckStyle( );

Return Value

The style of the control’s check boxes.

Remarks

Call this function to get the checklist box’s style. For information on possible styles, see SetCheckStyle.

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::OnGetCheckPosition, CCheckListBox::SetCheck, CCheckListBox::SetCheckStyle, CCheckListBox::GetCheck


CCheckListBox::IsEnabled

BOOL IsEnabled( int nIndex );

Return Value

Nonzero if the item is enabled; otherwise 0.

Parameters

nIndex

Index of the item.

Remarks

Call this function to determine whether an item is enabled.

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::Enable


CCheckListBox::MeasureItem

virtual void MeasureItem( LPMEASUREITEMSTRUCT lpMeasureItemStruct );

Parameters

lpMeasureItemStruct

A long pointer to a MEASUREITEMSTRUCT structure.

Remarks

Called by the framework when a checklist box with anon-default style is created.

By default, this member function does nothing. Override this member function and fill in the MEASUREITEMSTRUCT structure to inform Windows of the dimensions of checklist-box items. If the checklist box is created with the LBS_OWNERDRAWVARIABLE style, the framework calls this member function for each item in the list box. Otherwise, this member is called only once.

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::Create, CCheckListBox::DrawItem


CCheckListBox::OnGetCheckPosition

virtual CRect OnGetCheckPosition( CRect rectItem, CRect rectCheckBox );

Return Value

The position and size of an item's check box.

Parameters

rectItem

The position and size of the list item.

rectCheckBox

The default position and size of an item's check box.

Remarks

The framework calls this function to get the position and size of the check box in an item.

The default implementation only returns the default position and size of the check box (rectCheckBox). By default, a check box is aligned in the upper-left corner of an item and is the standard check box size. There may be cases where you want the check boxes on the right, or want a larger or smaller check box. In these cases, override OnGetCheckPosition to change the check box position and size within the item.

For example, the following function overrides the default and puts the check box on the right of the item, makes it the same height as the item (minus a pixel offset at the top and bottom), and makes it the standard check box width:

CRect CMyCheckListBox::OnGetCheckPosition(CRect rectItem, CRect rectCheckBox)
{
   CRect rectMyCheckBox;
   rectMyCheckBox.top = rectItem.top -1;
   rectMyCheckBox.bottom = rectItem.bottom -1;
   rectMyCheckBox.right = rectItem.right -1;
   rectMyCheckBox.left = rectItem.right -1 - rectCheckBox.Width();
   return rectMyCheckBox;
}

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::SetCheck, CCheckListBox::SetCheckStyle, CCheckListBox::GetCheck, CCheckListBox::GetCheckStyle


CCheckListBox::SetCheck

void SetCheck( int nIndex, int nCheck );

Parameters

nIndex

Index of the item whose check box is to be set.

nCheck

State of the check box: 0 for clear, 1 for checked, and 2 for indeterminate.

Remarks

Call this function to set the check box of the item specified by nIndex.

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::SetCheckStyle, CCheckListBox::GetCheck, CCheckListBox::GetCheckStyle


CCheckListBox::SetCheckStyle

void SetCheckStyle( UINT nStyle );

Parameters

nStyle

Determines the style of check boxes in the checklist box.

Remarks

Call this function to set the style of check boxes in the checklist box. Valid styles are:

  • BS_CHECKBOX

  • BS_AUTOCHECKBOX

  • BS_AUTO3STATE

  • BS_3STATE

For information on these styles, see Button Styles.

CCheckListBox Overview | Class Members | Hierarchy Chart

See Also CCheckListBox::SetCheck, CCheckListBox::GetCheck, CCheckListBox::GetCheckStyle


CClientDC

The CClientDC class is derived from CDC and takes care of calling the Windows functions GetDC at construction time and ReleaseDC at destruction time. This means that the device context associated with a CClientDC object is the client area of a window.

For more information on CClientDC, see Device Contexts in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MDI

See Also CDC


CClientDC Class Members

Construction

CClientDC Constructs a CClientDC object connected to the CWnd.

Data Members

m_hWnd The HWND of the window for which this CClientDC is valid.


CClientDC::CClientDC

CClientDC( CWnd* pWnd );
throw( CResourceException );

Parameters

pWnd

The window whose client area the device context object will access.

Remarks

Constructs a CClientDC object that accesses the client area of the CWnd pointed to by pWnd. The constructor calls the Windows function GetDC.

An exception (of type CResourceException) is thrown if the Windows GetDC call fails. A device context may not be available if Windows has already allocated all of its available device contexts. Your application competes for the five common display contexts available at any given time under Windows.


CClientDC::m_hWnd

Remarks

The HWND of the CWnd pointer used to construct the CClientDC object. m_hWnd is a protected variable.


CCmdTarget

CCmdTarget is the base class for the Microsoft Foundation Class Library message-map architecture. A message map routes commands or messages to the member functions you write to handle them. (A command is a message from a menu item, command button, or accelerator key.)

Key framework classes derived from CCmdTarget include CView, CWinApp, CDocument, CWnd, and CFrameWnd. If you intend for a new class to handle messages, derive the class from one of these CCmdTarget-derived classes. You will rarely derive a class from CCmdTarget directly.

For an overview of command targets and OnCmdMsg routing, see Command Targets, Command Routing, and Mapping Messages in Visual C++ Programmer's Guide.

CCmdTarget includes member functions that handle the display of an hourglass cursor. Display the hourglass cursor when you expect a command to take a noticeable time interval to execute.

Dispatch maps, similar to message maps, are used to expose OLE automation IDispatch functionality. By exposing this interface, other applications (such as Visual Basic) can call into your application. For more information on the IDispatch interfaces, see Creating the IDispatch Interface and Dispatch Interface and API Functions in the Win32 SDK OLE Programmer's Reference.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample ACDUAL

See Also CCmdUI, CDocument, CDocTemplate, CWinApp, CWnd, CView, CFrameWnd, COleDispatchDriver


CCmdTarget Class Members

Attributes

FromIDispatch | Returns a pointer to the CCmdTarget object associated with the IDispatch pointer.
GetIDispatch | Returns a pointer to the IDispatch object associated with the CCmdTarget object.
IsResultExpected | Returns nonzero if an automation function should return a value.

Operations

BeginWaitCursor | Displays the cursor as an hourglass cursor.
EnableAutomation | Allows OLE automation for the CCmdTarget object.
EndWaitCursor | Returns to the previous cursor.
RestoreWaitCursor | Restores the hourglass cursor.

Overridables

OnCmdMsg | Routes and dispatches command messages.
OnFinalRelease | Cleans up after the last OLE reference is released.


CCmdTarget::BeginWaitCursor

void BeginWaitCursor( );

Remarks

Call this function to display the cursor as an hourglass when you expect a command to take a noticeable time interval to execute. The framework calls this function to show the user that it is busy, such as when a CDocument object loads or saves itself to a file.

The actions of BeginWaitCursor are not always effective outside of a single message handler as other actions, such as OnSetCursor handling, could change the cursor.

Call EndWaitCursor to restore the previous cursor.

Example

// The following example illustrates the most common case
// of displaying the hourglass cursor during some lengthy
// processing of a command handler implemented in some
// CCmdTarget-derived class, such as a document or view.

void CMyView::OnSomeCommand()
{
   BeginWaitCursor(); // display the hourglass cursor

   // do some lengthy processing

   EndWaitCursor(); // remove the hourglass cursor
}

// The next example illustrates RestoreWaitCursor.
void CMyView::OnSomeCommand()
{
   BeginWaitCursor(); // display the hourglass cursor

   // do some lengthy processing

   // The dialog box will normally change the cursor to
   // the standard arrow cursor, and leave the cursor in
   // as the standard arrow cursor when the dialog box is
   // closed.
   CMyDialog dlg;
   dlg.DoModal();

   // It is necessary to call RestoreWaitCursor here in order
   // to change the cursor back to the hourglass cursor.
   RestoreWaitCursor();

   // do some more lengthy processing

   EndWaitCursor(); // remove the hourglass cursor
}

// In the above example, the dialog was clearly invoked between
// the pair of calls to BeginWaitCursor and EndWaitCursor.
// Sometimes it may not be clear whether the dialog is invoked
// in between a pair of calls to BeginWaitCursor and EndWaitCursor.
// It is permissable to call RestoreWaitCursor, even if
// BeginWaitCursor was not previously called.  This case is
// illustrated below, where CMyView::AnotherFunction does not
// need to know whether it was called in the context of an
// hourglass cursor.
void CMyView::AnotherFunction()
{
   // some processing ...

   CMyDialog dlg;
   dlg.DoModal();
   RestoreWaitCursor();

   // some more processing ...
}

// If the dialog is invoked from a member function of
// some non-CCmdTarget, then you can call CWinApp::DoWaitCursor
// with a 0 parameter value to restore the hourglass cursor.
void CMyObject::AnotherFunction()
{
   CMyDialog dlg;
   dlg.DoModal();
   AfxGetApp()->DoWaitCursor(0); // same as CCmdTarget::RestoreWaitCursor
}

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also CWaitCursor, CCmdTarget::EndWaitCursor, CCmdTarget::RestoreWaitCursor, CWinApp::DoWaitCursor


CCmdTarget::EnableAutomation

void EnableAutomation( );

Remarks

Call this function to enable OLE automation for an object. This function is typically called from the constructor of your object and should only be called if a dispatch map has been declared for the class. For more information on automation see the articles Automation Clients and Automation Servers in Visual C++ Programmer's Guide.

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also DECLARE_DISPATCH_MAP, DECLARE_OLECREATE


CCmdTarget::EndWaitCursor

void EndWaitCursor( );

Remarks

Call this function after you have called the BeginWaitCursor member function to return from the hourglass cursor to the previous cursor. The framework also calls this member function after it has called the hourglass cursor.

Example

// The following example illustrates the most common case
// of displaying the hourglass cursor during some lengthy
// processing of a command handler implemented in some
// CCmdTarget-derived class, such as a document or view.

void CMyView::OnSomeCommand()
{
   BeginWaitCursor(); // display the hourglass cursor

   // do some lengthy processing

   EndWaitCursor(); // remove the hourglass cursor
}

// The next example illustrates RestoreWaitCursor.
void CMyView::OnSomeCommand()
{
   BeginWaitCursor(); // display the hourglass cursor

   // do some lengthy processing

   // The dialog box will normally change the cursor to
   // the standard arrow cursor, and leave the cursor in
   // as the standard arrow cursor when the dialog box is
   // closed.
   CMyDialog dlg;
   dlg.DoModal();

   // It is necessary to call RestoreWaitCursor here in order
   // to change the cursor back to the hourglass cursor.
   RestoreWaitCursor();

   // do some more lengthy processing

   EndWaitCursor(); // remove the hourglass cursor
}

// In the above example, the dialog was clearly invoked between
// the pair of calls to BeginWaitCursor and EndWaitCursor.
// Sometimes it may not be clear whether the dialog is invoked
// in between a pair of calls to BeginWaitCursor and EndWaitCursor.
// It is permissable to call RestoreWaitCursor, even if
// BeginWaitCursor was not previously called.  This case is
// illustrated below, where CMyView::AnotherFunction does not
// need to know whether it was called in the context of an
// hourglass cursor.
void CMyView::AnotherFunction()
{
   // some processing ...

   CMyDialog dlg;
   dlg.DoModal();
   RestoreWaitCursor();

   // some more processing ...
}

// If the dialog is invoked from a member function of
// some non-CCmdTarget, then you can call CWinApp::DoWaitCursor
// with a 0 parameter value to restore the hourglass cursor.
void CMyObject::AnotherFunction()
{
   CMyDialog dlg;
   dlg.DoModal();
   AfxGetApp()->DoWaitCursor(0); // same as CCmdTarget::RestoreWaitCursor
}

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also CWaitCursor, CCmdTarget::BeginWaitCursor, CCmdTarget::RestoreWaitCursor, CWinApp::DoWaitCursor


CCmdTarget::FromIDispatch

static CCmdTarget* FromIDispatch( LPDISPATCH lpDispatch );

Return Value

A pointer to the CCmdTarget object associated with lpDispatch. This function returns NULL if the IDispatch object is not recognized as a Microsoft Foundation Class IDispatch object.

Parameters

lpDispatch

A pointer to an IDispatch object.

Remarks

Call this function to map an IDispatch pointer, received from automation member functions of a class, into the CCmdTarget object that implements the interfaces of the IDispatch object.

The result of this function is the inverse of a call to the member function GetIDispatch.

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also CCmdTarget::GetIDispatch, COleDispatchDriver


CCmdTarget::GetIDispatch

LPDISPATCH GetIDispatch( BOOL bAddRef );

Return Value

The IDispatch pointer associated with the object.

Parameters

bAddRef

Specifies whether to increment the reference count for the object.

Remarks

Call this member function to retrieve the IDispatch pointer from an automation method that either returns an IDispatch pointer or takes an IDispatch pointer by reference.

For objects that call EnableAutomation in their constructors, making them automation enabled, this function returns a pointer to the Foundation Class implementation of IDispatch that is used by clients who communicate via the IDispatch interface. Calling this function automatically adds a reference to the pointer, so it is not necessary to make a call to IUnknown::AddRef.

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also CCmdTarget::EnableAutomation, COleDispatchDriver, IUnknown::Release


CCmdTarget::IsResultExpected

BOOL IsResultExpected( );

Return Value

Nonzero if an automation function should return a value; otherwise 0.

Remarks

Use IsResultExpected to ascertain whether a client expects a return value from its call to an automation function. The OLE interface supplies information to MFC about whether the client is using or ignoring the result of a function call, and MFC in turn uses this information to determine the result of a call to IsResultExpected. If production of a return value is time- or resource-intensive, you can increase efficiency by calling this function before computing the return value.

This function returns 0 only once so that you will get valid return values from other automation functions if you call them from the automation function that the client has called.

IsResultExpected returns a nonzero value if called when an automation function call is not in progress.

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also CCmdTarget::GetIDispatch, CCmdTarget::EnableAutomation


CCmdTarget::OnCmdMsg

virtual BOOL OnCmdMsg( UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo );

Return Value

Nonzero if the message is handled; otherwise 0.

Parameters

nID

Contains the command ID.

nCode

Identifies the command notification code.

pExtra

Used according to the value of nCode.

pHandlerInfo

If not NULL, OnCmdMsg fills in the pTarget and pmf members of the pHandlerInfo structure instead of dispatching the command. Typically, this parameter should be NULL.

Remarks

Called by the framework to route and dispatch command messages and to handle the update of command user-interface objects. This is the main implementation routine of the framework command architecture.

At run time, OnCmdMsg dispatches a command to other objects or handles the command itself by calling the root class CCmdTarget::OnCmdMsg, which does the actual message-map lookup. For a complete description of the default command routing, see Message Handling and Mapping Topics in Visual C++ Programmer's Guide.

On rare occasions, you may want to override this member function to extend the framework’s standard command routing. Refer to Technical Note 21 for advanced details of the command-routing architecture.

Example

// This example illustrates extending the framework's standard command
// route from the view to objects managed by the view.  This example
// is from an object-oriented drawing application, similar to the
// DRAWCLI sample application, which draws and edits "shapes".

BOOL CMyView::OnCmdMsg(UINT nID, int nCode, void* pExtra,
      AFX_CMDHANDLERINFO* pHandlerInfo)
{
   // Extend the framework's command route from the view to
   // the application-specific CMyShape that is currently selected
   // in the view. m_pActiveShape is NULL if no shape object
   // is currently selected in the view.
   if ((m_pActiveShape != NULL)
      && m_pActiveShape->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
      return TRUE;

   // If the object(s) in the extended command route don't handle
   // the command, then let the base class OnCmdMsg handle it.
   return CView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}

// The command handler for ID_SHAPE_COLOR (menu command to change
// the color of the currently selected shape) was added to
// the message map of CMyShape (note, not CMyView) using ClassWizard.

// The menu item will be automatically enabled or disabled, depending
// on whether a CMyShape is currently selected in the view, that is,
// depending on whether CMyView::m_pActiveView is NULL.  It is not
// necessary to implement an ON_UPDATE_COMMAND_UI handler to enable
// or disable the menu item.

BEGIN_MESSAGE_MAP(CMyShape, CCmdTarget)
   //{{AFX_MSG_MAP(CMyShape)
   ON_COMMAND(ID_SHAPE_COLOR, OnShapeColor)
   //}}AFX_MSG_MAP
END_MESSAGE_MAP()

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also CCmdUI


CCmdTarget::OnFinalRelease

virtual void OnFinalRelease( );

Remarks

Called by the framework when the last OLE reference to or from the object is released. Override this function to provide special handling for this situation. The default implementation deletes the object.

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also COleServerItem


CCmdTarget::RestoreWaitCursor

void RestoreWaitCursor( );

Remarks

Call this function to restore the appropriate hourglass cursor after the system cursor has changed (for example, after a message box has opened and then closed while in the middle of a lengthy operation).

Example

// The following example illustrates the most common case
// of displaying the hourglass cursor during some lengthy
// processing of a command handler implemented in some
// CCmdTarget-derived class, such as a document or view.

void CMyView::OnSomeCommand()
{
   BeginWaitCursor(); // display the hourglass cursor

   // do some lengthy processing

   EndWaitCursor(); // remove the hourglass cursor
}

// The next example illustrates RestoreWaitCursor.
void CMyView::OnSomeCommand()
{
   BeginWaitCursor(); // display the hourglass cursor

   // do some lengthy processing

   // The dialog box will normally change the cursor to
   // the standard arrow cursor, and leave the cursor in
   // as the standard arrow cursor when the dialog box is
   // closed.
   CMyDialog dlg;
   dlg.DoModal();

   // It is necessary to call RestoreWaitCursor here in order
   // to change the cursor back to the hourglass cursor.
   RestoreWaitCursor();

   // do some more lengthy processing

   EndWaitCursor(); // remove the hourglass cursor
}

// In the above example, the dialog was clearly invoked between
// the pair of calls to BeginWaitCursor and EndWaitCursor.
// Sometimes it may not be clear whether the dialog is invoked
// in between a pair of calls to BeginWaitCursor and EndWaitCursor.
// It is permissable to call RestoreWaitCursor, even if
// BeginWaitCursor was not previously called.  This case is
// illustrated below, where CMyView::AnotherFunction does not
// need to know whether it was called in the context of an
// hourglass cursor.
void CMyView::AnotherFunction()
{
   // some processing ...

   CMyDialog dlg;
   dlg.DoModal();
   RestoreWaitCursor();

   // some more processing ...
}

// If the dialog is invoked from a member function of
// some non-CCmdTarget, then you can call CWinApp::DoWaitCursor
// with a 0 parameter value to restore the hourglass cursor.
void CMyObject::AnotherFunction()
{
   CMyDialog dlg;
   dlg.DoModal();
   AfxGetApp()->DoWaitCursor(0); // same as CCmdTarget::RestoreWaitCursor
}

CCmdTarget Overview | Class Members | Hierarchy Chart

See Also CWaitCursor, CCmdTarget::EndWaitCursor, CCmdTarget::BeginWaitCursor, CWinApp::DoWaitCursor


CCmdUI

CCmdUI does not have a base class.

The CCmdUI class is used only within an ON_UPDATE_COMMAND_UI handler in a CCmdTarget-derived class.

When a user of your application pulls down a menu, each menu item needs to know whether it should be displayed as enabled or disabled. The target of a menu command provides this information by implementing an ON_UPDATE_COMMAND_UI handler. Use ClassWizard to browse the command user-interface objects in your application and create a message-map entry and function prototype for each handler.

When the menu is pulled down, the framework searches for and calls each ON_UPDATE_COMMAND_UI handler, each handler calls CCmdUI member functions such as Enable and Check, and the framework then appropriately displays each menu item.

A menu item can be replaced with a control-bar button or other command user-interface object without changing the code within the ON_UPDATE_COMMAND_UI handler.

The following table summarizes the effect CCmdUI’s member functions have on various command user-interface items.

User-Interface Item | Enable | SetCheck | SetRadio | SetText
Menu item | Enables or disables | Checks (×) or unchecks | Checks using dot () | Sets item text
Toolbar button | Enables or disables | Selects, unselects, or indeterminate | Same as SetCheck | (Not applicable)
Status-bar pane | Makes text visible or invisible | Sets pop-out or normal border | Same as SetCheck | Sets pane text
Normal button in CDialogBar | Enables or disables | Checks or unchecks check box | Same as SetCheck | Sets button text
Normal control in CDialogBar | Enables or disables | (Not applicable) | (Not applicable) | Sets window text

For more on the use of this class, see Constructing the User Interface in Visual C++ Tutorials and How to Update User-Interface Objects in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Hierarchy Chart

Sample MFC Sample MDI

See Also CCmdTarget


CCmdUI Class Members

Data Members

m_nID | The ID of the user-interface object.
m_nIndex | The index of the user-interface object.
m_pMenu | Points to the menu represented by the CCmdUI object.
m_pSubMenu | Points to the contained sub-menu represented by the CCmdUI object.
m_pOther | Points to the window object that sent the notification.

Operations

Enable | Enables or disables the user-interface item for this command.
SetCheck | Sets the check state of the user-interface item for this command.
SetRadio | Like the SetCheck member function, but operates on radio groups.
SetText | Sets the text for the user-interface item for this command.
ContinueRouting | Tells the command-routing mechanism to continue routing the current message down the chain of handlers.


CCmdUI::ContinueRouting

void ContinueRouting( );

Remarks

Call this member function to tell the command-routing mechanism to continue routing the current message down the chain of handlers.

This is an advanced member function that should be used in conjunction with an ON_COMMAND_EX handler that returns FALSE. For more information, see Technical Note 21.


CCmdUI::Enable

virtual void Enable( BOOL bOn = TRUE );

Parameters

bOn

TRUE to enable the item, FALSE to disable it.

Remarks

Call this member function to enable or disable the user-interface item for this command.

CCmdUI Overview | Class Members | Hierarchy Chart

See Also CCmdUI::SetCheck


CCmdUI::SetCheck

virtual void SetCheck( int nCheck = 1 );

Parameters

nCheck

Specifies the check state to set. If 0, unchecks; if 1, checks; and if 2, sets indeterminate.

Remarks

Call this member function to set the user-interface item for this command to the appropriate check state. This member function works for menu items and toolbar buttons. The indeterminate state applies only to toolbar buttons.

CCmdUI Overview | Class Members | Hierarchy Chart

See Also CCmdUI::SetRadio


CCmdUI::SetRadio

virtual void SetRadio( BOOL bOn = TRUE );

Parameters

bOn

TRUE to enable the item; otherwise FALSE.

Remarks

Call this member function to set the user-interface item for this command to the appropriate check state. This member function operates like SetCheck, except that it operates on user-interface items acting as part of a radio group. Unchecking the other items in the group is not automatic unless the items themselves maintain the radio-group behavior.

CCmdUI Overview | Class Members | Hierarchy Chart

See Also CCmdUI::SetCheck


CCmdUI::SetText

virtual void SetText( LPCTSTR lpszText );

Parameters

lpszText

A pointer to a text string.

Remarks

Call this member function to set the text of the user-interface item for this command.

CCmdUI Overview | Class Members | Hierarchy Chart

See Also CCmdUI::Enable


CCmdUI::m_nID

Remarks

The ID of the menu item, toolbar button, or other user-interface object represented by the CCmdUI object.


CCmdUI::m_nIndex

Remarks

The index of the menu item, toolbar button, or other user-interface object represented by the CCmdUI object.


CCmdUI::m_pMenu

Remarks

Pointer (of CMenu type) to the menu represented by the CCmdUI object. NULL if the item is not a menu.

CCmdUI Overview | Class Members | Hierarchy Chart

See Also CMenu


CCmdUI::m_pSubMenu

Remarks

Pointer (of CMenu type) to the contained sub-menu represented by the CCmdUI object. NULL if the item is not a menu. If the sub menu is a pop-up, m_nID contains the ID of the first item in the pop-up menu. For more information, see Technical Note 21.

CCmdUI Overview | Class Members | Hierarchy Chart

See Also CMenu


CCmdUI::m_pOther

Remarks

Pointer (of type CWnd) to the window object, such as a tool or status bar, that sent the notification. NULL if the item is a menu or a non-CWnd object.

CCmdUI Overview | Class Members | Hierarchy Chart

See Also CWnd


CColorDialog

The CColorDialog class allows you to incorporate a color-selection dialog box into your application. A CColorDialog object is a dialog box with a list of colors that are defined for the display system. The user can select or create a particular color from the list, which is then reported back to the application when the dialog box exits.

To construct a CColorDialog object, use the provided constructor or derive a new class and use your own custom constructor.

Once the dialog box has been constructed, you can set or modify any values in the m_cc structure to initialize the values of the dialog box’s controls. The m_cc structure is of type CHOOSECOLOR.

After initializing the dialog box’s controls, call the DoModal member function to display the dialog box and allow the user to select a color. DoModal returns the user’s selection of either the dialog box’s OK (IDOK) or Cancel (IDCANCEL) button.

If DoModal returns IDOK, you can use one of CColorDialog’s member functions to retrieve the information input by the user.

You can use the Windows CommDlgExtendedError function to determine whether an error occurred during initialization of the dialog box and to learn more about the error.

CColorDialog relies on the COMMDLG.DLL file that ships with Windows versions 3.1 and later.

To customize the dialog box, derive a class from CColorDialog, provide a custom dialog template, and add a message map to process the notification messages from the extended controls. Any unprocessed messages should be passed to the base class.

Customizing the hook function is not required.

Note On some installations the CColorDialog object will not display with a gray background if you have used the framework to make other CDialog objects gray.

For more information on using CColorDialog, see Common Dialog Classes in Visual C++ Programmer's Guide.

#include <afxdlgs.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample MDI | MFC Sample DRAWCLI


CColorDialog Class Members

Data Members

m_cc A structure used to customize the settings of the dialog box.

Construction

CColorDialog Constructs a CColorDialog object.

Operations

DoModal | Displays a color dialog box and allows the user to make a selection.
GetColor | Returns a COLORREF structure containing the values of the selected color.
GetSavedCustomColors | Retrieves custom colors created by the user.
SetCurrentColor | Forces the current color selection to the specified color.

Overridables

OnColorOK Override to validate the color entered into the dialog box.


CColorDialog::CColorDialog

CColorDialog( COLORREF clrInit = 0, DWORD dwFlags = 0, CWnd* pParentWnd = NULL );

Parameters

clrInit

The default color selection. If no value is specified, the default is RGB(0,0,0) (black).

dwFlags

A set of flags that customize the function and appearance of the dialog box. For more information, see the CHOOSECOLOR structure in the Win32 SDK documentation.

pParentWnd

A pointer to the dialog box’s parent or owner window.

Remarks

Constructs a CColorDialog object.

CColorDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::DoModal


CColorDialog::DoModal

virtual int DoModal( );

Return Value

IDOK or IDCANCEL. If IDCANCEL is returned, call the Windows CommDlgExtendedError function to determine whether an error occurred.

IDOK and IDCANCEL are constants that indicate whether the user selected the OK or Cancel button.

Remarks

Call this function to display the Windows common color dialog box and allow the user to select a color.

If you want to initialize the various color dialog-box options by setting members of the m_cc structure, you should do this before calling DoModal but after the dialog-box object is constructed.

After calling DoModal, you can call other member functions to retrieve the settings or information input by the user into the dialog box.

CColorDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::DoModal, CColorDialog::CColorDialog


CColorDialog::GetColor

COLORREF GetColor( ) const;

Return Value

A COLORREF value that contains the RGB information for the color selected in the color dialog box.

Remarks

Call this function after calling DoModal to retrieve the information about the color the user selected.

CColorDialog Overview | Class Members | Hierarchy Chart

See Also CColorDialog::SetCurrentColor


CColorDialog::GetSavedCustomColors

static COLORREF * GetSavedCustomColors( );

Return Value

A pointer to an array of 16 RGB color values that stores custom colors created by the user.

Remarks

CColorDialog objects permit the user, in addition to choosing colors, to define up to 16 custom colors. The GetSavedCustomColors member function provides access to these colors. These colors can be retrieved after DoModal returns IDOK.

Each of the 16 RGB values in the returned array is initialized to RGB(255,255,255) (white). The custom colors chosen by the user are saved only between dialog box invocations within the application. If you wish to save these colors between invocations of the application, you must save them in some other manner, such as in an initialization (.INI) file.

CColorDialog Overview | Class Members | Hierarchy Chart

See Also CColorDialog::GetColor


CColorDialog::OnColorOK

virtual BOOL OnColorOK( );

Return Value

Nonzero if the dialog box should not be dismissed; otherwise 0 to accept the color that was entered.

Remarks

Override this function only if you want to provide custom validation of the color entered into the dialog box. This function allows you to reject a color entered by a user into a common color dialog box for any application-specific reason. Normally, you do not need to use this function because the framework provides default validation of colors and displays a message box if an invalid color is entered.

Use the GetColor member function to get the RGB value of the color.

If 0 is returned, the dialog box will remain displayed in order for the user to enter another filename.


CColorDialog::SetCurrentColor

void SetCurrentColor( COLORREF clr );

Parameters

clr

An RGB color value.

Remarks

Call this function after calling DoModal to force the current color selection to the color value specified in clr. This function is called from within a message handler or OnColorOK. The dialog box will automatically update the user’s selection based on the value of the clr parameter.

CColorDialog Overview | Class Members | Hierarchy Chart

See Also CColorDialog::GetColor, CColorDialog::OnColorOK


CColorDialog::m_cc

CHOOSECOLOR m_cc;

Remarks

A structure of type CHOOSECOLOR, whose members store the characteristics and values of the dialog box. After constructing a CColorDialog object, you can use m_cc to set various aspects of the dialog box before calling the DoModal member function.


CComboBox

The CComboBox class provides the functionality of a Windows combo box.

A combo box consists of a list box combined with either a static control or edit control. The list-box portion of the control may be displayed at all times or may only drop down when the user selects the drop-down arrow next to the control.

The currently selected item (if any) in the list box is displayed in the static or edit control. In addition, if the combo box has the drop-down list style, the user can type the initial character of one of the items in the list, and the list box, if visible, will highlight the next item with that initial character.

The following table compares the three combo-box styles.

Style | When is list box visible? | Static or edit control?
Simple | Always | Edit
Drop-down | When dropped down | Edit
Drop-down list | When dropped down | Static

You can create a CComboBox object from either a dialog template or directly in your code. In both cases, first call the constructor CComboBox to construct the CComboBox object; then call the Create member function to create the control and attach it to the CComboBox object.

If you want to handle Windows notification messages sent by a combo box to its parent (usually a class derived from CDialog), add a message-map entry and message-handler member function to the parent class for each message.

Each message-map entry takes the following form:

ON_Notification( id, memberFxn )

where id specifies the child-window ID of the combo-box control sending the notification and memberFxn is the name of the parent member function you have written to handle the notification.

The parent’s function prototype is as follows:

afx_msg void memberFxn( );

The order in which certain notifications will be sent cannot be predicted. In particular, a CBN_SELCHANGE notification may occur either before or after a CBN_CLOSEUP notification.

Potential message-map entries are the following:

  • ON_CBN_CLOSEUP (Windows 3.1 and later.) The list box of a combo box has closed. This notification message is not sent for a combo box that has the CBS_SIMPLE style.

  • ON_CBN_DBLCLK The user double-clicks a string in the list box of a combo box. This notification message is only sent for a combo box with the CBS_SIMPLE style. For a combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST style, a double-click cannot occur because a single click hides the list box.

  • ON_CBN_DROPDOWN The list box of a combo box is about to drop down (be made visible). This notification message can occur only for a combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

  • ON_CBN_EDITCHANGE The user has taken an action that may have altered the text in the edit-control portion of a combo box. Unlike the CBN_EDITUPDATE message, this message is sent after Windows updates the screen. It is not sent if the combo box has the CBS_DROPDOWNLIST style.

  • ON_CBN_EDITUPDATE The edit-control portion of a combo box is about to display altered text. This notification message is sent after the control has formatted the text but before it displays the text. It is not sent if the combo box has the CBS_DROPDOWNLIST style.

  • ON_CBN_ERRSPACE The combo box cannot allocate enough memory to meet a specific request.

  • ON_CBN_SELENDCANCEL (Windows 3.1 and later.) Indicates the user’s selection should be canceled. The user clicks an item and then clicks another window or control to hide the list box of a combo box. This notification message is sent before the CBN_CLOSEUP notification message to indicate that the user’s selection should be ignored. The CBN_SELENDCANCEL or CBN_SELENDOK notification message is sent even if the CBN_CLOSEUP notification message is not sent (as in the case of a combo box with the CBS_SIMPLE style).

  • ON_CBN_SELENDOK The user selects an item and then either presses the ENTER key or clicks the DOWN ARROW key to hide the list box of a combo box. This notification message is sent before the CBN_CLOSEUP message to indicate that the user’s selection should be considered valid. The CBN_SELENDCANCEL or CBN_SELENDOK notification message is sent even if the CBN_CLOSEUP notification message is not sent (as in the case of a combo box with the CBS_SIMPLE style).

  • ON_CBN_KILLFOCUS The combo box is losing the input focus.

  • ON_CBN_SELCHANGE The selection in the list box of a combo box is about to be changed as a result of the user either clicking in the list box or changing the selection by using the arrow keys. When processing this message, the text in the edit control of the combo box can only be retrieved via GetLBText or another similar function. GetWindowText cannot be used.

  • ON_CBN_SETFOCUS The combo box receives the input focus.

If you create a CComboBox object within a dialog box (through a dialog resource), the CComboBox object is automatically destroyed when the user closes the dialog box.

If you embed a CComboBox object within another window object, you do not need to destroy it. If you create the CComboBox object on the stack, it is destroyed automatically. If you create the CComboBox object on the heap by using the new function, you must call delete on the object to destroy it when the Windows combo box is destroyed.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CTRLBARS

See Also CWnd, CButton, CEdit, CListBox, CScrollBar, CStatic, CDialog


CComboBox Class Members

Construction/Destruction
Initialization
General Operations
String Operations
Overridables

Construction

CComboBox Constructs a CComboBox object.

Initialization

Create | Creates the combo box and attaches it to the CComboBox object.
InitStorage | Preallocates blocks of memory for items and strings in the list-box portion of the combo box.

General Operations

GetCount | Retrieves the number of items in the list box of a combo box.
GetCurSel | Retrieves the index of the currently selected item, if any, in the list box of a combo box.
SetCurSel | Selects a string in the list box of a combo box.
GetEditSel | Gets the starting and ending character positions of the current selection in the edit control of a combo box.
SetEditSel | Selects characters in the edit control of a combo box.
SetItemData | Sets the 32-bit value associated with the specified item in a combo box.
SetItemDataPtr | Sets the 32-bit value associated with the specified item in a combo box to the specified pointer (void*).
GetItemData | Retrieves the application-supplied 32-bit value associated with the specified combo-box item.
GetItemDataPtr | Retrieves the application-supplied 32-bit value associated with the specified combo-box item as a pointer (void*).
GetTopIndex | Returns the index of the first visible item in the list-box portion of the combo box.
SetTopIndex | Tells the list-box portion of the combo box to display the item with the specified index at the top.
SetHorizontalExtent | Sets the width in pixels that the list-box portion of the combo box can be scrolled horizontally.
GetHorizontalExtent | Returns the width in pixels that the list-box portion of the combo box can be scrolled horizontally.
SetDroppedWidth | Sets the minimum allowable width for the drop-down list-box portion of a combo box.
GetDroppedWidth | Retrieves the minimum allowable width for the drop-down list-box portion of a combo box.
Clear | Deletes (clears) the current selection (if any) in the edit control.
Copy | Copies the current selection (if any) onto the Clipboard in CF_TEXT format.
Cut | Deletes (cuts) the current selection, if any, in the edit control and copies the deleted text onto the Clipboard in CF_TEXT format.
Paste | Inserts the data from the Clipboard into the edit control at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format.
LimitText | Limits the length of the text that the user can enter into the edit control of a combo box.
SetItemHeight | Sets the height of list items in a combo box or the height of the edit-control (or static-text) portion of a combo box.
GetItemHeight | Retrieves the height of list items in a combo box.
GetLBText | Gets a string from the list box of a combo box.
GetLBTextLen | Gets the length of a string in the list box of a combo box.
ShowDropDown | Shows or hides the list box of a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.
GetDroppedControlRect | Retrieves the screen coordinates of the visible (dropped-down) list box of a drop-down combo box.
GetDroppedState | Determines whether the list box of a drop-down combo box is visible (dropped down).
SetExtendedUI | Selects either the default user interface or the extended user interface for a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.
GetExtendedUI | Determines whether a combo box has the default user interface or the extended user interface.
GetLocale | Retrieves the locale identifier for a combo box.
SetLocale | Sets the locale identifier for a combo box.

String Operations

AddString | Adds a string to the end of the list in the list box of a combo box or at the sorted position for list boxes with the CBS_SORT style.
DeleteString | Deletes a string from the list box of a combo box.
InsertString | Inserts a string into the list box of a combo box.
ResetContent | Removes all items from the list box and edit control of a combo box.
Dir | Adds a list of filenames to the list box of a combo box.
FindString | Finds the first string that contains the specified prefix in the list box of a combo box.
FindStringExact | Finds the first list-box string (in a combo box) that matches the specified string.
SelectString | Searches for a string in the list box of a combo box and, if the string is found, selects the string in the list box and copies the string to the edit control.

Overridables

DrawItem | Called by the framework when a visual aspect of an owner-draw combo box changes.
MeasureItem | Called by the framework to determine combo box dimensions when an owner-draw combo box is created.
CompareItem | Called by the framework to determine the relative position of a new list item in a sorted owner-draw combo box.
DeleteItem | Called by the framework when a list item is deleted from an owner-draw combo box.


CComboBox::AddString

int AddString( LPCTSTR lpszString );

Return Value

If the return value is greater than or equal to 0, it is the zero-based index to the string in the list box. The return value is CB_ERR if an error occurs; the return value is CB_ERRSPACE if insufficient space is available to store the new string.

Parameters

lpszString

Points to the null-terminated string that is to be added.

Remarks

Adds a string to the list box of a combo box. If the list box was not created with the CBS_SORT style, the string is added to the end of the list. Otherwise, the string is inserted into the list, and the list is sorted.

To insert a string into a specific location within the list, use the InsertString member function.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::InsertString, CComboBox::DeleteString, CB_ADDSTRING


CComboBox::CComboBox

CComboBox( );

Remarks

Constructs a CComboBox object.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::Create


CComboBox::Clear

void Clear( );

Remarks

Deletes (clears) the current selection, if any, in the edit control of the combo box.

To delete the current selection and place the deleted contents onto the Clipboard, use the Cut member function.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::Copy, CComboBox::Cut, CComboBox::Paste, WM_CLEAR


CComboBox::CompareItem

virtual int CompareItem( LPCOMPAREITEMSTRUCT lpCompareItemStruct );

Return Value

Indicates the relative position of the two items described in the COMPAREITEMSTRUCT structure. It can be any of the following values:

Value | Meaning
– 1 | Item 1 sorts before item 2.
0 | Item 1 and item 2 sort the same.
1 | Item 1 sorts after item 2.

See CWnd::OnCompareItem for a description of COMPAREITEMSTRUCT.

Parameters

lpCompareItemStruct

A long pointer to a COMPAREITEMSTRUCT structure.

Remarks

Called by the framework to determine the relative position of a new item in the list-box portion of a sorted owner-draw combo box. By default, this member function does nothing. If you create an owner-draw combo box with the LBS_SORT style, you must override this member function to assist the framework in sorting new items added to the list box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also WM_COMPAREITEM, CComboBox::DrawItem, CComboBox::MeasureItem, CComboBox::DeleteItem


CComboBox::Copy

void Copy( );

Remarks

Copies the current selection, if any, in the edit control of the combo box onto the Clipboard in CF_TEXT format.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::Clear, CComboBox::Cut, CComboBox::Paste, WM_COPY


CComboBox::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise 0.

Parameters

dwStyle

Specifies the style of the combo box. Apply any combination of combo-box styles to the box.

rect

Points to the position and size of the combo box. Can be a RECT structure or a CRect object.

pParentWnd

Specifies the combo box’s parent window (usually a CDialog). It must not be NULL.

nID

Specifies the combo box’s control ID.

Remarks

You construct a CComboBox object in two steps. First call the constructor, then call Create, which creates the Windows combo box and attaches it to the CComboBox object.

When Create executes, Windows sends the WM_NCCREATE, WM_CREATE, WM_NCCALCSIZE, and WM_GETMINMAXINFO messages to the combo box.

These messages are handled by default by the OnNcCreate, OnCreate, OnNcCalcSize, and OnGetMinMaxInfo member functions in the CWnd base class. To extend the default message handling, derive a class from CComboBox, add a message map to the new class, and override the preceding message-handler member functions. Override OnCreate, for example, to perform needed initialization for a new class.

Apply the following window styles to a combo-box control. :

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

  • WS_VSCROLL To add vertical scrolling for the list box in the combo box

  • WS_HSCROLL To add horizontal scrolling for the list box in the combo box

  • WS_GROUP To group controls

  • WS_TABSTOP To include the combo box in the tabbing order

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::CComboBox, Combo-Box Styles


CComboBox::Cut

void Cut( );

Remarks

Deletes (cuts) the current selection, if any, in the combo-box edit control and copies the deleted text onto the Clipboard in CF_TEXT format.

To delete the current selection without placing the deleted text onto the Clipboard, call the Clear member function.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::Clear, CComboBox::Copy, CComboBox::Paste, WM_CUT


CComboBox::DeleteItem

virtual void DeleteItem( LPDELETEITEMSTRUCT lpDeleteItemStruct );

Parameters

lpDeleteItemStruct A long pointer to a Windows DELETEITEMSTRUCT structure that contains information about the deleted item. See CWnd::OnDeleteItem for a description of this structure.

Remarks

Called by the framework when the user deletes an item from an owner-draw CComboBox object or destroys the combo box. The default implementation of this function does nothing. Override this function to redraw the combo box as needed.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::CompareItem, CComboBox::DrawItem, CComboBox::MeasureItem, WM_DELETEITEM


CComboBox::DeleteString

int DeleteString( UINT nIndex );

Return Value

If the return value is greater than or equal to 0, then it is a count of the strings remaining in the list. The return value is CB_ERR if nIndex specifies an index greater then the number of items in the list.

Parameters

nIndex

Specifies the index to the string that is to be deleted.

Remarks

Deletes a string in the list box of a combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::InsertString, CComboBox::AddString, CB_DELETESTRING


CComboBox::Dir

int Dir( UINT attr, LPCTSTR lpszWildCard );

Return Value

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

Parameters

attr

Can be any combination of the enum values described in CFile::GetStatus or any combination of the following values:

  • DDL_READWRITE File can be read from or written to.

  • DDL_READONLY File can be read from but not written to.

  • DDL_HIDDEN File is hidden and does not appear in a directory listing.

  • DDL_SYSTEM File is a system file.

  • DDL_DIRECTORY The name specified by lpszWildCard specifies a directory.

  • DDL_ARCHIVE File has been archived.

  • DDL_DRIVES Include all drives that match the name specified by lpszWildCard.

  • DDL_EXCLUSIVE Exclusive flag. If the exclusive flag is set, only files of the specified type are listed. Otherwise, files of the specified type are listed in addition to “normal” files.

lpszWildCard

Points to a file-specification string. The string can contain wildcards (for example, *.*).

Remarks

Adds a list of filenames and/or drives to the list box of a combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CWnd::DlgDirList, CB_DIR, CFile::GetStatus


CComboBox::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A pointer to a DRAWITEMSTRUCT structure that contains information about the type of drawing required.

Remarks

Called by the framework when a visual aspect of an owner-draw combo box changes. The itemAction member of the DRAWITEMSTRUCT structure defines the drawing action that is to be performed. See CWnd::OnDrawItem for a description of this structure.

By default, this member function does nothing. Override this member function to implement drawing for an owner-draw CComboBox object. Before this member function terminates, the application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::CompareItem, WM_DRAWITEM, CComboBox::MeasureItem, CComboBox::DeleteItem


CComboBox::FindString

int FindString( int nStartAfter, LPCTSTR lpszString ) const;

Return Value

If the return value is greater than or equal to 0, it is the zero-based index of the matching item. It is CB_ERR if the search was unsuccessful.

Parameters

nStartAfter

Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If –1, the entire list box is searched from the beginning.

lpszString

Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string can contain any combination of uppercase and lowercase letters.

Remarks

Finds, but doesn’t select, the first string that contains the specified prefix in the list box of a combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SelectString, CComboBox::SetCurSel, CB_FINDSTRING


CComboBox::FindStringExact

int FindStringExact( int nIndexStart, LPCTSTR lpszFind ) const;

Return Value

The zero-based index of the matching item, or CB_ERR if the search was unsuccessful.

Parameters

nIndexStart

Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nIndexStart. If nIndexStart is –1, the entire list box is searched from the beginning.

lpszFind

Points to the null-terminated string to search for. This string can contain a complete filename, including the extension. The search is not case sensitive, so this string can contain any combination of uppercase and lowercase letters.

Remarks

Call the FindStringExact member function to find the first list-box string (in a combo box) that matches the string specified in lpszFind.

If the combo box was created with an owner-draw style but without the CBS_HASSTRINGS style, FindStringExact attempts to match the doubleword value against the value of lpszFind.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::FindString, CB_FINDSTRINGEXACT


CComboBox::GetCount

int GetCount( ) const;

Return Value

The number of items. The returned count is one greater than the index value of the last item (the index is zero-based). It is CB_ERR if an error occurs.

Remarks

Call this member function to retrieve the number of items in the list-box portion of a combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CB_GETCOUNT


CComboBox::GetCurSel

int GetCurSel( ) const;

Return Value

The zero-based index of the currently selected item in the list box of a combo box, or CB_ERR if no item is selected.

Remarks

Call this member function to determine which item in the combo box is selected. GetCurSel returns an index into the list.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetCurSel, CB_GETCURSEL


CComboBox::GetDroppedControlRect

void GetDroppedControlRect( LPRECT lprect ) const;

Parameters

lprect

Points to the RECT structure that is to receive the coordinates.

Remarks

Call the GetDroppedControlRect member function to retrieve the screen coordinates of the visible (dropped-down) list box of a drop-down combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CB_GETDROPPEDCONTROLRECT


CComboBox::GetDroppedState

BOOL GetDroppedState( ) const;

Return Value

Nonzero if the list box is visible; otherwise 0.

Remarks

Call the GetDroppedState member function to determine whether the list box of a drop-down combo box is visible (dropped down).

CComboBox Overview | Class Members | Hierarchy Chart

See Also CB_SHOWDROPDOWN, CB_GETDROPPEDSTATE


CComboBox::GetDroppedWidth

int GetDroppedWidth( ) const;

Return Value

If successful, the minimum allowable width, in pixels; otherwise, CB_ERR.

Remarks

Call this function to retrieve the minimum allowable width, in pixels, of the list box of a combo box. This function only applies to combo boxes with the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

By default, the minimum allowable width of the drop-down list box is 0. The minimum allowable width can be set by calling SetDroppedWidth. When the list-box portion of the combo box is displayed, its width is the larger of the minimum allowable width or the combo box width.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetDroppedWidth, CB_GETDROPPEDWIDTH


CComboBox::GetEditSel

DWORD GetEditSel( ) const;

Return Value

A 32-bit value that contains the starting position in the low-order word and the position of the first nonselected character after the end of the selection in the high-order word. If this function is used on a combo box without an edit control, CB_ERR is returned.

Remarks

Gets the starting and ending character positions of the current selection in the edit control of a combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetEditSel, CB_GETEDITSEL


CComboBox::GetExtendedUI

BOOL GetExtendedUI( ) const;

Return Value

Nonzero if the combo box has the extended user interface; otherwise 0.

Remarks

Call the GetExtendedUI member function to determine whether a combo box has the default user interface or the extended user interface. The extended user interface can be identified in the following ways:

  • Clicking the static control displays the list box only for combo boxes with the CBS_DROPDOWNLIST style.

  • Pressing the DOWN ARROW key displays the list box (F4 is disabled).

Scrolling in the static control is disabled when the item list is not visible (arrow keys are disabled).

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetExtendedUI, CB_GETEXTENDEDUI


CComboBox::GetHorizontalExtent

UINT GetHorizontalExtent( ) const;

Return Value

The scrollable width of the list-box portion of the combo box, in pixels.

Remarks

Retrieves from the combo box the width in pixels by which the list-box portion of the combo box can be scrolled horizontally. This is applicable only if the list-box portion of the combo box has a horizontal scroll bar.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetHorizontalExtent, CB_GETHORIZONTALEXTENT


CComboBox::GetItemData

DWORD GetItemData( int nIndex ) const;

Return Value

The 32-bit value associated with the item, or CB_ERR if an error occurs.

Parameters

nIndex

Contains the zero-based index of an item in the combo box’s list box.

Remarks

Retrieves the application-supplied 32-bit value associated with the specified combo-box item. The 32-bit value can be set with the dwItemData parameter of a SetItemData member function call. Use the GetItemDataPtr member function if the 32-bit value to be retrieved is a pointer (void*).

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetItemData, CComboBox::GetItemDataPtr, CComboBox::SetItemDataPtr, CB_GETITEMDATA


CComboBox::GetItemDataPtr

void* GetItemDataPtr( int nIndex ) const;

Return Value

Retrieves a pointer, or –1 if an error occurs.

Parameters

nIndex

Contains the zero-based index of an item in the combo box’s list box.

Remarks

Retrieves the application-supplied 32-bit value associated with the specified combo-box item as a pointer (void*).

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetItemDataPtr, CComboBox::GetItemData, CComboBox::SetItemData, CB_GETITEMDATA


CComboBox::GetItemHeight

int GetItemHeight( int nIndex ) const;

Return Value

The height, in pixels, of the specified item in a combo box. The return value is CB_ERR if an error occurs.

Parameters

nIndex

Specifies the component of the combo box whose height is to be retrieved. If the nIndex parameter is –1, the height of the edit-control (or static-text) portion of the combo box is retrieved. If the combo box has the CBS_OWNERDRAWVARIABLE style, nIndex specifies the zero-based index of the list item whose height is to be retrieved. Otherwise, nIndex should be set to 0.

Remarks

Call the GetItemHeight member function to retrieve the height of list items in a combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetItemHeight, WM_MEASUREITEM, CB_GETITEMHEIGHT


CComboBox::GetLBText

int GetLBText( int nIndex, LPTSTR lpszText ) const;

void GetLBText( int nIndex, CString& rString ) const;

Return Value

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

Parameters

nIndex

Contains the zero-based index of the list-box string to be copied.

lpszText

Points to a buffer that is to receive the string. The buffer must have sufficient space for the string and a terminating null character.

rString

A reference to a CString.

Remarks

Gets a string from the list box of a combo box. The second form of this member function fills a CString object with the item’s text.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetLBTextLen, CB_GETLBTEXT


CComboBox::GetLBTextLen

int GetLBTextLen( int nIndex ) const;

Return Value

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

Parameters

nIndex

Contains the zero-based index of the list-box string.

Remarks

Gets the length of a string in the list box of a combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetLBText, CB_GETLBTEXTLEN


CComboBox::GetLocale

LCID GetLocale( ) const;

Return Value

The locale identifier (LCID) value for the strings in the combo box.

Remarks

Retrieves the locale used by the combo box. The locale is used, for example, to determine the sort order of the strings in a sorted combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetLocale, ::GetStringTypeW, ::GetSystemDefaultLCID, ::GetUserDefaultLCID


CComboBox::GetTopIndex

int GetTopIndex( ) const;

Return Value

The zero-based index of the first visible item in the list-box portion of the combo box if successful, CB_ERR otherwise.

Remarks

Retrieves the zero-based index of the first visible item in the list-box portion of the combo box. Initially, item 0 is at the top of the list box, but if the list box is scrolled, another item may be at the top.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::SetTopIndex, CB_GETTOPINDEX


CComboBox::InitStorage

int InitStorage( int nItems, UINT nBytes );

Return Value

If successful, the maximum number of items that the list-box portion of the combo box can store before a memory reallocation is needed, otherwise CB_ERR, meaning not enough memory is available.

Parameters

nItems

Specifies the number of items to add.

nBytes

Specifies the amount of memory, in bytes, to allocate for item strings.

Remarks

Allocates memory for storing list box items in the list-box portion of the combo box. Call this function before adding a large number of items to the list-box portion of the CComboBox.

Windows 95 only: The wParam parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size of the items in a list box is limited only by available memory.

This function helps speed up the initialization of list boxes that have a large number of items (more than 100). It preallocates the specified amount of memory so that subsequent AddString, InsertString, and Dir functions take the shortest possible time. You can use estimates for the parameters. If you overestimate, some extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the preallocated amount.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::CComboBox, CComboBox::Create, CComboBox::ResetContent, CB_INITSTORAGE


CComboBox::InsertString

int InsertString( int nIndex, LPCTSTR lpszString );

Return Value

The zero-based index of the position at which the string was inserted. The return value is CB_ERR if an error occurs. The return value is CB_ERRSPACE if insufficient space is available to store the new string.

Parameters

nIndex

Contains the zero-based index to the position in the list box that will receive the string. If this parameter is –1, the string is added to the end of the list.

lpszString

Points to the null-terminated string that is to be inserted.

Remarks

Inserts a string into the list box of a combo box. Unlike the AddString member function, the InsertString member function does not cause a list with the CBS_SORT style to be sorted.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::AddString, CComboBox::DeleteString, CComboBox::ResetContent, CB_INSERTSTRING


CComboBox::LimitText

BOOL LimitText( int nMaxChars );

Return Value

Nonzero if successful. If called for a combo box with the style CBS_DROPDOWNLIST or for a combo box without an edit control, the return value is CB_ERR.

Parameters

nMaxChars

Specifies the length (in bytes) of the text that the user can enter. If this parameter is 0, the text length is set to 65,535 bytes.

Remarks

Limits the length in bytes of the text that the user can enter into the edit control of a combo box.

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

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

CComboBox Overview | Class Members | Hierarchy Chart

See Also CB_LIMITTEXT


CComboBox::MeasureItem

virtual void MeasureItem( LPMEASUREITEMSTRUCT lpMeasureItemStruct );

Parameters

lpMeasureItemStruct

A long pointer to a MEASUREITEMSTRUCT structure.

Remarks

Called by the framework when a combo box with an owner-draw style is created.

By default, this member function does nothing. Override this member function and fill in the MEASUREITEMSTRUCT structure to inform Windows of the dimensions of the list box in the combo box. If the combo box is created with the CBS_OWNERDRAWVARIABLE style, the framework calls this member function for each item in the list box. Otherwise, this member is called only once.

Using the CBS_OWNERDRAWFIXED style in an owner-draw combo box created with the SubclassDlgItem member function of CWnd involves further programming considerations. See the discussion in Technical Note 14.

See CWnd::OnMeasureItem for a description of the MEASUREITEMSTRUCT structure.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::CompareItem, CComboBox::DrawItem, WM_MEASUREITEM, CComboBox::DeleteItem


CComboBox::Paste

void Paste( );

Remarks

Inserts the data from the Clipboard into the edit control of the combo box at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::Clear, CComboBox::Copy, CComboBox::Cut, WM_PASTE


CComboBox::ResetContent

void ResetContent( );

Remarks

Removes all items from the list box and edit control of a combo box.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CB_RESETCONTENT


CComboBox::SelectString

int SelectString( int nStartAfter, LPCTSTR lpszString );

Return Value

The zero-based index of the selected item if the string was found. If the search was unsuccessful, the return value is CB_ERR and the current selection is not changed.

Parameters

nStartAfter

Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If –1, the entire list box is searched from the beginning.

lpszString

Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string can contain any combination of uppercase and lowercase letters.

Remarks

Searches for a string in the list box of a combo box, and if the string is found, selects the string in the list box and copies it to the edit control.

A string is selected only if its initial characters (from the starting point) match the characters in the prefix string.

Note that the SelectString and FindString member functions both find a string, but the SelectString member function also selects the string.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::FindString, CB_SELECTSTRING


CComboBox::SetCurSel

int SetCurSel( int nSelect );

Return Value

The zero-based index of the item selected if the message is successful. The return value is CB_ERR if nSelect is greater than the number of items in the list or if nSelect is set to –1, which clears the selection.

Parameters

nSelect

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

Remarks

Selects a string in the list box of a combo box. If necessary, the list box scrolls the string into view (if the list box is visible). The text in the edit control of the combo box is changed to reflect the new selection. Any previous selection in the list box is removed.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetCurSel, CB_SETCURSEL


CComboBox::SetDroppedWidth

int SetDroppedWidth( UINT nWidth );

Return Value

If successful, the new width of the list box, otherwise CB_ERR.

Parameters

nWidth

The minimum allowable width of the list-box portion of the combo box, in pixels.

Remarks

Call this function to set the minimum allowable width, in pixels, of the list box of a combo box. This function only applies to combo boxes with the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

By default, the minimum allowable width of the drop-down list box is 0. When the list-box portion of the combo box is displayed, its width is the larger of the minimum allowable width or the combo box width.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetDroppedWidth, CB_SETDROPPEDWIDTH


CComboBox::SetEditSel

BOOL SetEditSel( int nStartChar, int nEndChar );

Return Value

Nonzero if the member function is successful; otherwise 0. It is CB_ERR if CComboBox has the CBS_DROPDOWNLIST style or does not have a list box.

Parameters

nStartChar

Specifies the starting position. If the starting position is set to –1, then any existing selection is removed.

nEndChar

Specifies the ending position. If the ending position is set to –1, then all text from the starting position to the last character in the edit control is selected.

Remarks

Selects characters in the edit control of a combo box.

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

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetEditSel, CB_SETEDITSEL


CComboBox::SetExtendedUI

int SetExtendedUI( BOOL bExtended = TRUE );

Return Value

CB_OKAY if the operation is successful, or CB_ERR if an error occurs.

Parameters

bExtended

Specifies whether the combo box should use the extended user interface or the default user interface. A value of TRUE selects the extended user interface; a value of FALSE selects the standard user interface.

Remarks

Call the SetExtendedUI member function to select either the default user interface or the extended user interface for a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style.

The extended user interface can be identified in the following ways:

  • Clicking the static control displays the list box only for combo boxes with the CBS_DROPDOWNLIST style.

  • Pressing the DOWN ARROW key displays the list box (F4 is disabled).

Scrolling in the static control is disabled when the item list is not visible (the arrow keys are disabled).

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetExtendedUI, CB_SETEXTENDEDUI


CComboBox::SetHorizontalExtent

void SetHorizontalExtent( UINT nExtent );

Parameters

nExtent

Specifies the number of pixels by which the list-box portion of the combo box can be scrolled horizontally.

Remarks

Sets the width, in pixels, by which the list-box portion of the combo box can be scrolled horizontally. If the width of the list box is smaller than this value, the horizontal scroll bar will horizontally scroll items in the list box. If the width of the list box is equal to or greater than this value, the horizontal scroll bar is hidden or, if the combo box has the CBS_DISABLENOSCROLL style, disabled.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetHorizontalExtent, CB_SETHORIZONTALEXTENT


CComboBox::SetItemData

int SetItemData( int nIndex, DWORD dwItemData );

Return Value

CB_ERR if an error occurs.

Parameters

nIndex

Contains a zero-based index to the item to set.

dwItemData

Contains the new value to associate with the item.

Remarks

Sets the 32-bit value associated with the specified item in a combo box. Use the SetItemDataPtr member function if the 32-bit item is to be a pointer.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetItemData, CComboBox::GetItemDataPtr, CComboBox::SetItemDataPtr, CB_SETITEMDATA, CComboBox::AddString, CComboBox::InsertString


CComboBox::SetItemDataPtr

int SetItemDataPtr( int nIndex, void* pData );

Return Value

CB_ERR if an error occurs.

Parameters

nIndex

Contains a zero-based index to the item.

pData

Contains the pointer to associate with the item.

Remarks

Sets the 32-bit value associated with the specified item in a combo box to be the specified pointer (void*). This pointer remains valid for the life of the combo box, even though the item’s relative position within the combo box might change as items are added or removed. Hence, the item’s index within the box can change, but the pointer remains reliable.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetItemData, CComboBox::GetItemDataPtr, CComboBox::SetItemData, CB_SETITEMDATA, CComboBox::AddString, CComboBox::InsertString


CComboBox::SetItemHeight

int SetItemHeight( int nIndex, UINT cyItemHeight );

Return Value

CB_ERR if the index or height is invalid; otherwise 0.

Parameters

nIndex

Specifies whether the height of list items or the height of the edit-control (or static-text) portion of the combo box is set.

If the combo box has the CBS_OWNERDRAWVARIABLE style, nIndex specifies the zero-based index of the list item whose height is to be set; otherwise, nIndex must be 0 and the height of all list items will be set.

If nIndex is –1, the height of the edit-control or static-text portion of the combo box is to be set.

cyItemHeight

Specifies the height, in pixels, of the combo-box component identified by nIndex.

Remarks

Call the SetItemHeight member function to set the height of list items in a combo box or the height of the edit-control (or static-text) portion of a combo box.

The height of the edit-control (or static-text) portion of the combo box is set independently of the height of the list items. An application must ensure that the height of the edit-control (or static-text) portion is not smaller than the height of a particular list-box item.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetItemHeight, WM_MEASUREITEM, CB_SETITEMHEIGHT


CComboBox::SetLocale

LCID SetLocale( LCID nNewLocale );

Return Value

The previous locale identifier (LCID) value for this combo box.

Parameters

nNewLocale

The new locale identifier (LCID) value to set for the combo box.

Remarks

Sets the locale identifier for this combo box. If SetLocale is not called, the default locale is obtained from the system. This system default locale can be modified by using Control Panel’s Regional (or International) application.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetLocale


CComboBox::SetTopIndex

int SetTopIndex( int nIndex );

Return Value

Zero if successful, or LB_ERR if an error occurs.

Parameters

nIndex

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

Remarks

Ensures that a particular item is visible in the list-box portion of the combo box.

The system scrolls the list box until either the item specified by nIndex appears at the top of the list box or the maximum scroll range has been reached.

CComboBox Overview | Class Members | Hierarchy Chart

See Also CComboBox::GetTopIndex, CB_SETTOPINDEX


CComboBox::ShowDropDown

void ShowDropDown( BOOL bShowIt = TRUE );

Parameters

bShowIt

Specifies whether the drop-down list box is to be shown or hidden. A value of TRUE shows the list box. A value of FALSE hides the list box.

Remarks

Shows or hides the list box of a combo box that has the CBS_DROPDOWN or CBS_DROPDOWNLIST style. By default, a combo box of this style will show the list box.

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

CComboBox Overview | Class Members | Hierarchy Chart

See Also CB_SHOWDROPDOWN


CComboBoxEx

The CComboBoxEx class extends the combo box control by providing support for image lists. By using CComboBoxEx to create combo box controls, you no longer need to implement your own image drawing code. Instead, use CComboBoxEx to access images from an image list.

Image List Support

In a standard combo box, the owner of the combo box is responsible for drawing an image by creating the combo box as an owner-draw control. When you use CComboBoxEx, you do not need to set the drawing styles CBS_OWNERDRAWFIXED and CBS_HASSTRINGS because they are implied. Otherwise, you must write code to perform drawing operations. A CComboBoxEx control supports up to three images per item: one for a selected state, one for an unselected state, and one for an overlay image.

Styles

CComboBoxEx supports the styles CBS_SIMPLE, CBS_DROPDOWN, CBS_DROPDOWNLIST, and WS_CHILD. All other styles passed when you create the window are ignored by the control. After the window is created, you can provide other combo box styles by calling the CComboBoxEx member function SetExtendedStyle. With these styles, you can:

  • Set string searches in the list to be case-sensitive.

  • Create a combo box control that uses the slash ('/'), backslash ('\'), and period ('.') characters as word delimiters. This allow users to jump from word to word, using the keyboard shortcut CTRL+ ARROW.

  • Set the combo box control to either display or not display an image. If no image is displayed, the combo box can remove the text indent that accommodates an image.

  • Create a narrow combo box control, including sizing it so it clips the wider combo box it contains.

These style flags are described further in Using CComboBoxEx in the Visual C++ Programmer’s Guide.

Item Retention and Callback Item Attributes

Item information, such as indexes for items and images, indentation values, and text strings, is stored in the Win32 structure COMBOBOXEXITEM, as described in the Platform SDK. The structure also contains members that correspond to callback flags.

For a detailed, conceptual discussion, see Using CComboBoxEx in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MFCIE

See Also CComboBox


CComboBoxEx Class Members

Constructors

CComboBoxEx Constructs a CComboBoxEx object.

Initialization

Create Creates the combo box and attaches it to the CComboBoxEx object.

Operators

DeleteItem | Removes an item from a ComboBoxEx control.
GetItem | Retrieves item information for a given ComboBoxEx item.
InsertItem | Inserts a new item in a ComboBoxEx control.
SetItem | Sets the attributes for an item in a ComboBoxEx control.

Attributes

HasEditChanged | Determines if the user has changed the contents of the ComboBoxEx edit control by typing.
GetExtendedStyle | Retrieves the extended styles that are in use for a ComboBoxEx control.
SetExtendedStyle | Sets extended styles within a ComboBoxEx control.
GetEditCtrl | Retrieves the handle to the edit control portion of a ComboBoxEx control.
GetComboBoxCtrl | Retrieves a pointer to the child combo box control.
GetImageList | Retrieves a pointer to the image list assigned to a ComboBoxEx control.
SetImageList | Sets an image list for a ComboBoxEx control.


CComboBoxEx::CComboBoxEx

CComboBoxEx( );

Remarks

Call this member function to create a CComboBoxEx object.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::Create, CComboBox


CComboBoxEx::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if the object was created successfully; otherwise 0.

Parameters

dwStyle

Specifies the combination of combo box styles applied to the combo box. See Remarks below for more information about styles.

rect

A reference to a CRect object or RECT structure, which is the position and size of the combo box.

pParentWnd

A pointer to a CWnd object that is the parent window of the combo box (usually a CDialog). It must not be NULL.

nID

Specifies the combo box’s control ID.

Remarks

Create a CComboBoxEx object in two steps:

  1. Call CComboBoxEx to construct a CComboBoxEx object.

  2. Call this member function, which creates the extended Windows combo box and attaches it to the CComboBoxEx object.

When you call Create, MFC initializes the common controls.

When you create the combo box, you can specify any or all of the following combo-box styles:

  • CBS_SIMPLE

  • CBS_DROPDOWN

  • CBS_DROPDOWNLIST

  • WS_CHILD

All other styles passed when you create the window are ignored. The ComboBoxEx control also supports extended styles that provide additional features. These styles are described in ComboBoxEx control extended styles, in the Platform SDK. Set these styles by calling SetExtendedStyle.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::CComboBoxEx


CComboBoxEx::DeleteItem

int DeleteItem( int iIndex );

Return Value

The number of items remaining in the control. If iIndex is invalid, the function returns CB_ERR.

Parameters

iIndex

Zero-based index of the item to be removed.

Remarks

This member function implements the functionality of the message CBEM_DELETEITEM, as described in the Platform SDK. When you call DeleteItem, a WM_NOTIFY message with CBEN_DELETEITEM notification will be sent to the parent window.


CComboBoxEx::GetComboBoxCtrl

CComboBox* GetComboBoxCtrl( );

Return Value

A pointer to a CComboBox object.

Remarks

Call this member function to get a pointer to a combo box control within a CComboBoxEx object. The CComboBoxEx control consists of a parent window, which encapsulates a CComboBox.

The CComboBox object pointed to by the return value is a temporary object and is destroyed during the next idle processing time.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::GetEditCtrl


CComboBoxEx::GetEditCtrl

CEdit* GetEditCtrl( );

Return Value

A pointer to a CEdit object.

Remarks

Call this member function to get a pointer to the edit control for a combo box. A CComboBoxEx control uses an edit box when it is created with the CBS_DROPDOWN style.

The CEdit object pointed to by the return value is a temporary object and is destroyed during the next idle processing time.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::Create


CComboBoxEx::GetExtendedStyle

DWORD GetExtendedStyle( ) const;

Return Value

The DWORD value that contains the extended styles that are used for the combo box control.

Remarks

Call this member function to get the extended styles used for a CComboBoxEx control. See ComboBoxEx Control Extended Styles in the Platform SDK for more information about these styles.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::SetExtendedStyle


CComboBoxEx::GetImageList

CImageList* GetImageList( ) const;

Return Value

A pointer to a CImageList object. If it fails, this member function returns NULL.

Remarks

Call this member function to get a pointer to the image list used by a CComboBoxEx control.

The CImageList object pointed to by the return value is a temporary object and is destroyed during the next idle processing time.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::SetImageList, COMBOBOXEXITEM


CComboBoxEx::GetItem

BOOL GetItem( COMBOBOXEXITEM* pCBItem );

Return Value

Nonzero if the operation was successful; otherwise 0.

Parameters

pCBItem

A pointer to a COMBOBOXEXITEM structure that will receive the item information.

Remarks

This member function implements the functionality of the message CBEM_GETITEM, as described in the Platform SDK.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::SetItem, CComboBoxEx::InsertItem


CComboBoxEx::HasEditChanged

BOOL HasEditChanged( );

Return Value

Nonzero if the user has typed in the control's edit box; otherwise 0.

Remarks

This member function implements the functionality of the message CBEM_HASEDITCHANGED, as described in the Platform SDK.


CComboBoxEx::InsertItem

int InsertItem( const COMBOBOXEXITEM* pCBItem );

Return Value

The index at which the new item was inserted if successful; otherwise -1.

Parameters

pCBItem

A pointer to a COMBOBOXEXITEM structure that will receive the item information. This structure contains callback flag values for the item.

Remarks

When you call InsertItem, a WM_NOTIFY message with CBEN_INSERTITEM notification will be sent to the parent window.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::GetItem, CComboBoxEx::SetItem


CComboBoxEx::SetExtendedStyle

DWORD SetExtendedStyle( DWORD dwExMask, DWORD dwExStyles );

Return Value

A DWORD value that contains the extended styles previously used for the control.

Parameters

dwExMask

A DWORD value that indicates which styles in dwExStyles are to be affected. Only the extended styles in dwExMask will be changed. All other styles will be maintained as is. If this parameter is zero, then all of the styles in dwExStyles will be affected.

dwExStyles

A DWORD value that contains the combo box control extended styles to set for the control.

Remarks

Call this member function to set the extended styles used for a combo box extended control. See ComboBoxEx Control Extended Styles in the Platform SDK for more information about these styles.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::GetExtendedStyle


CComboBoxEx::SetImageList

CImageList* SetImageList( CImageList* pImageList );

Return Value

A pointer to a CImageList object containing the images previously used by the CComboBoxEx control. NULL if no image list was previously set.

Parameters

pImageList

A pointer to a CImageList object containing the images to use with the CComboBoxEx control.

Remarks

This member function implements the functionality of the message CBEM_SETIMAGELIST, as described in the Platform SDK.

If you change the height of the default edit control, call the Win32 function SetWindowPos to resize your control after you call SetImageList, or it will not display properly.

The CImageList object pointed to by the return value is a temporary object and is destroyed during the next idle processing time.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::GetImageList


CComboBoxEx::SetItem

BOOL SetItem( const COMBOBOXEXITEM* pCBItem );

Return Value

Nonzero if the operation was successful; otherwise 0.

Parameters

pCBItem

A pointer to a COMBOBOXEXITEM structure that will receive the item information.

Remarks

This member function implements the functionality of the message CBEM_SETITEM, as described in the Platform SDK.

CComboBoxEx Overview | Class Members | Hierarchy Chart

See Also CComboBoxEx::GetItem, CComboBoxEx::InsertItem


CCommandLineInfo

The CCommandLineInfo class aids in parsing the command line at application startup.

An MFC application will typically create a local instance of this class in the InitInstance function of its application object. This object is then passed to CWinApp::ParseCommandLine, which repeatedly calls ParseParam to fill the CCommandLineInfo object. The CCommandLineInfo object is then passed to CWinApp::ProcessShellCommand to handle the command-line arguments and flags.

You can use this object to encapsulate the following command-line options and parameters:

Command-line argument | Command executed
app | New file.
app filename | Open file.
app /p filename | Print file to default printer.
app /pt filename printer driver port | Print file to the specified printer.
app /dde | Start up and await DDE command.
app /Automation | Start up as an OLE automation server.
app /Embedding | Start up to edit an embedded OLE item.

Derive a new class from CCommandLineInfo to handle other flags and parameter values. Override ParseParam to handle the new flags.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CWinApp::ParseCommandLine, CWinApp::ProcessShellCommand


CCommandLineInfo Class Members

Construction

CommandLineInfo Constructs a default CCommandLineInfo object.

Operations

ParseParam Override this callback to parse individual parameters.

Data Members

m_bShowSplash | Indicates if a splash screen should be shown.
m_bRunEmbedded | Indicates the command-line /Embedding option was found.
m_bRunAutomated | Indicates the command-line /Automation option was found.
m_nShellCommand | Indicates the shell command to be processed.
m_strFileName | Indicates the filename to be opened or printed; empty if the shell command is New or DDE.
m_strPrinterName | Indicates the printer name if the shell command is Print To; otherwise empty.
m_strDriverName | Indicates the driver name if the shell command is Print To; otherwise empty.
m_strPortName | Indicates the port name if the shell command is Print To; otherwise empty.


CCommandLineInfo::CCommandLineInfo

CCommandLineInfo( );

Remarks

This constructor creates a CCommandLineInfo object with default values. The default is to show the splash screen (m_bShowSplash = TRUE) and to execute the New command on the File menu (m_nShellCommand = NewFile).

The application framework calls ParseParam to fill data members of this object.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::ParseParam


CCommandLineInfo::ParseParam

virtual void ParseParam( LPCTSTR lpszParam, BOOL bFlag, BOOL bLast );

Parameters

lpszParam

The parameter or flag.

bFlag

Indicates whether lpszParam is a parameter or a flag.

bLast

Indicates if this is the last parameter or flag on the command line.

Remarks

The framework calls this function to parse/interpret individual parameters from the command line. CWinApp::ParseCommandLine calls ParseParam once for each parameter or flag on the command line, passing the argument to lpszParam. If the first character of the parameter is a ‘-’ or a ‘/’, then it is removed and bFlag is set to TRUE. When parsing the final parameter, bLast is set to TRUE.

The default implementation of this function recognizes the following flags: /p, /pt, /dde, /Automation, and /Embedding, as shown in the following table:

Command-line argument | Command executed
app | New file.
app filename | Open file.
app /p filename | Print file to default printer.
app /pt filename printer driver port | Print file to the specified printer.
app /dde | Start up and await DDE command.
app /Automation | Start up as an OLE automation server.
app /Embedding | Start up to edit an embedded OLE item.

This information is stored in m_bRunAutomated, m_bRunEmbedded, and m_nShellCommand. Flags are marked by either a forward-slash ‘/’ or hyphen ‘-’.

The default implementation puts the first non-flag parameter into m_strFileName. In the case of the /pt flag, the default implementation puts the second, third, and fourth non-flag parameters into m_strPrinterName, m_strDriverName, and m_strPortName, respectively.

The default implementation also sets m_bShowSplash to TRUE only in the case of a new file. In the case of a new file, the user has taken action involving the application itself. In any other case, including opening existing files using the shell, the user action involves the file directly. In a document-centric standpoint, the splash screen does not need to announce the application starting up.

Override this function in your derived class to handle other flag and parameter values.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CWinApp::ParseCommandLine


CCommandLineInfo::m_bRunAutomated

Remarks

Indicates that the /Automation flag was found on the command line. If TRUE, this means start up as an OLE automation server.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::ParseParam, CWinApp::ProcessShellCommand


CCommandLineInfo::m_bRunEmbedded

Remarks

Indicates that the /Embedding flag was found on the command line. If TRUE, this means start up for editing an embedded OLE item.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::m_bShowSplash, CWinApp::ProcessShellCommand


CCommandLineInfo::m_bShowSplash

Remarks

Indicates that the splash screen should be displayed. If TRUE, this means the splash screen for this application should be displayed during startup. The default implementation of ParseParam sets this data member to TRUE if m_nShellCommand is equal to CCommandLineInfo::FileNew.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::m_bRunAutomated, CCommandLineInfo::m_bRunEmbedded, CCommandLineInfo::m_nShellCommand, CCommandLineInfo::ParseParam, CWinApp::ProcessShellCommand


CCommandLineInfo::m_nShellCommand

Remarks

Indicates the shell command for this instance of the application.

The type for this data member is the following enumerated type, which is defined within the CCommandLineInfo class.

enum{
   FileNew,
   FileOpen,
   FilePrint,
   FilePrintTo,
   FileDDE,
   FileNothing = -1
};

For a brief description of these values, see the following list.

  • CCommandLineInfo::FileNew Indicates that no filename was found on the command line.

  • CCommandLineInfo::FileOpen Indicates that a filename was found on the command line and that none of the following flags were found on the command line: /p, /pt, /dde.

  • CCommandLineInfo::FilePrint Indicates that the /p flag was found on the command line.

  • CCommandLineInfo::FilePrintTo Indicates that the /pt flag was found on the command line.

  • CCommandLineInfo::FileDDE Indicates that the /dde flag was found on the command line.

  • CCommandLineInfo::FileNothing Turns off the display of a new MDI child window on startup. By design, AppWizard generated MDI applications display a new child window on startup. To turn off this feature, an application can use CCommandLineInfo::FileNothing as the shell command when calling ProcessShellCommand. ProcessShellCommand is called by the InitInstance( ) of all CWinApp derived classes.

Example

BOOL CMyWinApp::InitInstance()
{
...
// Parse command line for standard shell commands, DDE, file open
   CCommandLineInfo cmdInfo;
   ParseCommandLine(cmdInfo);
// DON'T display a new MDI child window during startup!!!
   cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing;
// Dispatch commands specified on the command line
   if (!ProcessShellCommand(cmdInfo))
      return FALSE;
...
};

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::m_strFileName, CCommandLineInfo::m_strPrinterName, CCommandLineInfo::m_strDriverName, CCommandLineInfo::m_strPortName, CWinApp::ProcessShellCommand


CCommandLineInfo::m_strFileName

Remarks

Stores the value of the first non-flag parameter on the command line. This parameter is typically the name of the file to open.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::m_strPrinterName, CCommandLineInfo::m_strDriverName, CCommandLineInfo::m_strPortName, CWinApp::ProcessShellCommand


CCommandLineInfo::m_strDriverName

Remarks

Stores the value of the third non-flag parameter on the command line. This parameter is typically the name of the printer driver for a Print To shell command. The default implementation of ParseParam sets this data member only if the /pt flag was found on the command line.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::m_strFileName, CCommandLineInfo::m_strPrinterName, CCommandLineInfo::m_strPortName, CWinApp::ProcessShellCommand


CCommandLineInfo::m_strPortName

Remarks

Stores the value of the fourth non-flag parameter on the command line. This parameter is typically the name of the printer port for a Print To shell command. The default implementation of ParseParam sets this data member only if the /pt flag was found on the command line.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::m_strFileName, CCommandLineInfo::m_strPrinterName, CCommandLineInfo::m_strDriverName, CWinApp::ProcessShellCommand


CCommandLineInfo::m_strPrinterName

Remarks

Stores the value of the second non-flag parameter on the command line. This parameter is typically the name of the printer for a Print To shell command. The default implementation of ParseParam sets this data member only if the /pt flag was found on the command line.

CCommandLineInfo Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo::m_strFileName, CCommandLineInfo::m_strDriverName, CCommandLineInfo::m_strPortName, CWinApp::ProcessShellCommand


CCommonDialog

CCommonDialog is the base class for classes that encapsulate functionality of the Windows common dialogs:

  • CFileDialog

  • CFontDialog

  • CColorDialog

  • CPageSetupDialog

  • CPrintDialog

  • CFindReplaceDialog

  • COleDialog

#include <afxdlgs.h>

Class Member | Base Class | Hierarchy Chart

See Also CFileDialog, CFontDialog, CColorDialog, CPageSetupDialog, CPrintDialog, CFindReplaceDialog, COleDialog


CCommonDialog Class Members

Construction

CCommonDialog Constructs a CCommonDialog object.


CCommonDialog::CCommonDialog

CCommonDialog( CWnd* pParentWnd );

Parameters

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the dialog object’s parent window is set to the main application window.

Remarks

Constructs a CCommonDialog object. See CDialog::CDialog for complete information.

CCommonDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::CDialog


CConnectionPoint

The CConnectionPoint class defines a special type of interface used to communicate with other OLE objects, called a “connection point.” Unlike normal OLE interfaces, which are used to implement and expose the functionality of an OLE control, a connection point implements an outgoing interface that is able to initiate actions on other objects, such as firing events and change notifications.

A connection consists of two parts: the object calling the interface, called the “source,” and the object implementing the interface, called the “sink.” By exposing a connection point, a source allows sinks to establish connections to itself. Through the connection point mechanism, a source object obtains a pointer to the sink’s implementation of a set of member functions. For example, to fire an event implemented by the sink, the source can call the appropriate method of the sink’s implementation.

By default, a COleControl-derived class implements two connection points: one for events and one for property change notifications. These connections are used, respectively, for event firing and for notifying a sink (for example, the control’s container) when a property value has changed. Support is also provided for OLE controls to implement additional connection points. For each additional connection point implemented in your control class, you must declare a “connection part” that implements the connection point. If you implement one or more connection points, you also need to declare a single “connection map” in your control class.

The following example demonstrates a simple connection map and one connection point for the Sample OLE control, consisting of two fragments of code: the first portion declares the connection map and point; the second implements this map and point. The first fragment is inserted into the declaration of the control class, under the protected section:

    // Connection point for ISample interface
    BEGIN_CONNECTION_PART(CSampleCtrl, SampleConnPt)
        CONNECTION_IID(IID_ISampleSink)
    END_CONNECTION_PART(SampleConnPt)

    DECLARE_CONNECTION_MAP()

The BEGIN_CONNECTION_PART and END_CONNECTION_PART macros declare an embedded class, XSampleConnPt (derived from CConnectionPoint) that implements this particular connection point. If you want to override any CConnectionPoint member functions, or add member functions of your own, declare them between these two macros. For example, the CONNECTION_IID macro overrides the CConnectionPoint::GetIID member function when placed between these two macros.

The second code fragment is inserted into the implementation file (.CPP) of your control class. This code implements the connection map, which includes the additional connection point, SampleConnPt:

BEGIN_CONNECTION_MAP(CSampleCtrl, COleControl)
    CONNECTION_PART(CSampleCtrl, IID_ISampleSink, SampleConnPt)
END_CONNECTION_MAP()

Once these code fragments have been inserted, the Sample OLE control exposes a connection point for the ISampleSink interface.

Typically, connection points support “multicasting”; the ability to broadcast to multiple sinks connected to the same interface. The following code fragment demonstrates how to accomplish multicasting by iterating through each sink on a connection point:

void CSampleCtrl::CallSinkFunc()
{
    const CPtrArray* pConnections = m_xSampleConnPt.GetConnections();
    ASSERT(pConnections != NULL);

    int cConnections = pConnections->GetSize();
    ISampleSink* pSampleSink;
    for (int i = 0; i < cConnections; i++)
    {
        pSampleSink = (ISampleSink*)(pConnections->GetAt(i));
        ASSERT(pSampleSink != NULL);
        pSampleSink->SinkFunc();
    }
}

This example retrieves the current set of connections on the SampleConnPt connection point with a call to CConnectionPoint::GetConnections. It then iterates through the connections and calls ISampleSink::SinkFunc on every active connection.

For more information on using CConnectionPoint, see the article Connection Points in Visual C++ Programmer's Guide.

#include <afxctl.h>


CConnectionPoint Class Members

Operations

GetConnections Retrieves all connection points in a connection map.

Overridables

GetContainer | Retrieves the container of the control that owns the connection map.
GetIID | Retrieves the interface ID of a connection point.
GetMaxConnections | Retrieves the maximum number of connection points supported by a control.
OnAdvise | Called by the framework when establishing or breaking connections.


CConnectionPoint::GetConnections

const CPtrArray* GetConnections( );

Return Value

A pointer to an array of active connections (sinks). Each pointer in this array can be safely converted to a pointer to the sink interface using a cast operator.

Remarks

Call this function to retrieve all active connections for a connection point.

CConnectionPoint Overview | Class Members | Hierarchy Chart

See Also CConnectionPoint::GetMaxConnections


CConnectionPoint::GetContainer

virtual LPCONNECTIONPOINTCONTAINER GetContainer( ) = 0;

Return Value

If successful, a pointer to the container; otherwise NULL.

Remarks

Called by the framework to retrieve the IConnectionPointContainer for the connection point. This function is typically implemented by the BEGIN_CONNECTION_PART macro.

CConnectionPoint Overview | Class Members | Hierarchy Chart

See Also BEGIN_CONNECTION_PART


CConnectionPoint::GetIID

virtual REFIID GetIID( ) = 0;

Return Value

A reference to the connection point’s interface ID.

Remarks

Called by the framework to retrieve the interface ID of a connection point.

Override this function to return the interface ID for this connection point.

CConnectionPoint Overview | Class Members | Hierarchy Chart

See Also CONNECTION_IID


CConnectionPoint::GetMaxConnections

virtual int GetMaxConnections( );

Return Value

The maximum number of connections supported by the control, or -1 if no limit.

Remarks

Called by the framework to retrieve the maximum number of connections supported by the connection point. The default implementation returns -1, indicating no limit.

Override this function if you want to limit the number of sinks that can connect to your control.

CConnectionPoint Overview | Class Members | Hierarchy Chart

See Also CConnectionPoint::GetConnections


CConnectionPoint::OnAdvise

virtual void OnAdvise( BOOL bAdvise );

Parameters

bAdvise

TRUE, if a connection is being established; otherwise FALSE.

Remarks

Called by the framework when a connection is being established or broken. The default implementation does nothing.

Override this function if you want notification when sinks connect to or disconnect from your connection point.


CControlBar

CControlBar is the base class for the control-bar classes CStatusBar, CToolBar, CDialogBar, CReBar, and COleResizeBar. A control bar is a window that is usually aligned to the left or right of a frame window. It may contain child items that are either HWND-based controls, which are Windows windows that generate and respond to Windows messages, or non-HWND-based items, which are not windows and are managed by application code or framework code. List boxes and edit controls are examples of HWND-based controls; status-bar panes and bitmap buttons are examples of non-HWND-based controls.

Control-bar windows are usually child windows of a parent frame window and are usually siblings to the client view or MDI client of the frame window. A CControlBar object uses information about the parent window’s client rectangle to position itself. It then informs the parent window as to how much space remains unallocated in the parent window’s client area.

For more information on CControlBar, see the article Control Bar Topics in Visual C++ Programmer's Guide and Technical Note 31, Control Bars.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CTRLBARS

See Also CToolBar, CDialogBar, CStatusBar, CReBar


CControlBar Class Members

Data Members

m_bAutoDelete If nonzero, the CControlBar object is deleted when the Windows control bar is destroyed.

Attributes

GetBarStyle | Retrieves the control bar style settings.
SetBarStyle | Modifies the control bar style settings.
GetBorders | Retrieves the border values of the control bar.
SetBorders | Sets the border values of the control bar.
GetCount | Returns the number of non-HWND elements in the control bar.
GetDockingFrame | Returns a pointer to the frame to which a control bar is docked.
IsFloating | Returns a nonzero value if the control bar in question is a floating control bar.
CalcFixedLayout | Returns the size of the control bar as a CSize object.
CalcDynamicLayout | Returns the size of a dynamic control bar as a CSize object.

Overridables

OnUpdateCmdUI Calls the Command UI handlers.

Operations

EnableDocking Allows a control bar to be docked or floating.


CControlBar::CalcDynamicLayout

virtual CSize CalcDynamicLayout( int nLength, DWORD dwMode );

Return Value

The control bar size, in pixels, of a CSize object.

Parameters

nLength

The requested dimension of the control bar, either horizontal or vertical, depending on dwMode.

dwMode

The following predefined flags are used to determine the height and width of the dynamc control bar. Use the bitwise-OR (|) operator to combine the flags.

Layout mode flags | What it means
LM_STRETCH | Indicates whether the control bar should be stretched to the size of the frame. Set if the bar is not a docking bar (not available for docking). Not set when the bar is docked or floating (available for docking). If set, LM_STRETCH ignores nLength and returns dimensions based on the LM_HORZ state. LM_STRETCH works similarly to the the bStretch parameter used in CalcFixedLayout; see that member function for more information about the relationship between stretching and orientation.
LM_HORZ | Indicates that the bar is horizontally or vertically oriented. Set if the bar is horizontally oriented, and if it is vertically oriented, it is not set. LM_HORZ works similarly to the the bHorz parameter used in CalcFixedLayout; see that member function for more information about the relationship between stretching and orientation.
LM_MRUWIDTH | Most Recently Used Dynamic Width. Ignores nLength parameter and uses the remembered most recently used width.
LM_HORZDOCK | Horizontal Docked Dimensions. Ignores nLength parameter and returns the dynamic size with the largest width.
LM_VERTDOCK | Vertical Docked Dimensions. Ignores nLength parameter and returns the dynamic size with the largest height.
LM_LENGTHY | Set if nLength indicates height (Y-direction) instead of width.
LM_COMMIT | Resets LM_MRUWIDTH to current width of floating control bar.

Remarks

The framework calls this member function to calculate the dimensions of a dynamic toolbar.

Override this member function to provide your own dynamic layout in classes you derive from CControlBar. MFC classes derived from CControlBar, such as CToolbar, override this member function and provide their own implementation.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CControlBar::CalcFixedLayout, CToolbar


CControlBar::CalcFixedLayout

virtual CSize CalcFixedLayout( BOOL bStretch, BOOL bHorz );

Return Value

The control bar size, in pixels, of a CSize object.

Parameters

bStretch

Indicates whether the bar should be stretched to the size of the frame. The bStretch parameter is nonzero when the bar is not a docking bar (not available for docking) and is 0 when it is docked or floating (available for docking).

bHorz

Indicates that the bar is horizontally or vertically oriented. The bHorz parameter is nonzero if the bar is horizontally oriented and is 0 if it is vertically oriented.

Remarks

Call this member function to calculate the horizontal size of a control bar.

Control bars such as toolbars can stretch horizontally or vertically to accommodate the buttons contained in the control bar.

If bStretch is TRUE, stretch the dimension along the orientation provided by bHorz. In other words, if bHorz is FALSE, the control bar is stretched vertically. If bStretch is FALSE, no stretch occurs. The following table shows the possible permutations, and resulting control-bar styles, of bStretch and bHorz.

bStretch | bHorz | Stretching | Orientation | Docking/Not docking
TRUE | TRUE | Horizontal stretching | Horizontally oriented | Not docking
TRUE | FALSE | Vertical stretching | Vertically oriented | Not docking
FALSE | TRUE | No stretching available | Horizontally oriented | Docking
FALSE | FALSE | No stretching available | Vertically oriented | Docking

CControlBar Overview | Class Members | Hierarchy Chart

See Also CControlBar::CalcDynamicLayout


CControlBar::EnableDocking

void EnableDocking( DWORD dwStyle );

Parameters

dwStyle

Specifies whether the control bar supports docking and the sides of its parent window to which the control bar can be docked, if supported. Can be one or more of the following:

  • CBRS_ALIGN_TOP Allows docking at the top of the client area.

  • CBRS_ALIGN_BOTTOM Allows docking at the bottom of the client area.

  • CBRS_ALIGN_LEFT Allows docking on the left side of the client area.

  • CBRS_ALIGN_RIGHT Allows docking on the right side of the client area.

  • CBRS_ALIGN_ANY Allows docking on any side of the client area.

  • CBRS_FLOAT_MULTI Allows multiple control bars to be floated in a single mini-frame window.

    If 0 (that is, indicating no flags), the control bar will not dock.

Remarks

Call this function to enable a control bar to be docked. The sides specified must match one of the sides enabled for docking in the destination frame window, or the control bar cannot be docked to that frame window.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::EnableDocking, CFrameWnd::DockControlBar, CFrameWnd::FloatControlBar, CControlBar::SetBarStyle


CControlBar::GetBarStyle

DWORD GetBarStyle( );

Return Value

The current CBRS_ (control bar styles) settings for the control bar. See CControlBar::SetBarStyle for the complete list of available styles.

Remarks

Call this function to determine which CBRS_ (control bar styles) settings are currently set for the control bar. Does not handle WS_ (window style) styles.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CControlBar::SetBarStyle


CControlBar::GetBorders

CRect GetBorders( ) const;

Return Value

A CRect object that contains the current width (in pixels) of each side of the control bar object. For example, the value of the left member, of CRect object, is the width of the left hand border.

Remarks

Returns the current border values for the control bar.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CControlBar::SetBorders


CControlBar::GetCount

int GetCount( ) const;

Return Value

The number of non-HWND items on the CControlBar object. This function returns 0 for a CDialogBar object.

Remarks

Returns the number of non-HWND items on the CControlBar object. The type of the item depends on the derived object: panes for CStatusBar objects, and buttons and separators for CToolBar objects.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::SetButtons, CStatusBar::SetIndicators, CStatusBar, CToolBar, CDialogBar


CControlBar::GetDockingFrame

CFrameWnd* GetDockingFrame( ) const;

Return Value

A pointer to a frame window if successful; otherwise NULL.

Remarks

Call this member function to obtain a pointer to the current frame window to which your control bar is docked.

For more information about dockable control bars, see CControlBar::EnableDocking and CFrameWnd::DockControlBar.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CControlBar::EnableDocking, CFrameWnd::DockControlBar


CControlBar::IsFloating

BOOL IsFloating( ) const;

Return Value

Nonzero if the control bar is floating; otherwise 0.

Remarks

Call this member function to determine whether the control bar is floating or docked.

To change the state of a control bar from docked to floating, call CFrameWnd::FloatControlBar.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::FloatControlBar


CControlBar::OnUpdateCmdUI

virtual void OnUpdateCmdUI( CFrameWnd* pTarget, BOOL bDisableIfNoHndler ) = 0;

Parameters

pTarget

Points to the main frame window of the application. This pointer is used for routing update messages.

bDisableIfNoHndler

Flag that indicates whether a control that has no update handler should be automatically displayed as disabled.

Remarks

This member function is called by the framework to update the status of the toolbar or status bar.

To update an individual button or pane, use the ON_UPDATE_COMMAND_UI macro in your message map to set an update handler appropriately. See ON_UPDATE_COMMAND_UI for more information about using this macro.

OnUpdateCmdUI is called by the framework when the application is idle. The frame window to be updated must be a child window, at least indirectly, of a visible frame window. OnUpdateCmdUI is an advanced overridable.

CControlBar Overview | Class Members | Hierarchy Chart

See Also ON_UPDATE_COMMAND_UI, Technical Note 31: Control Bars


CControlBar::SetBarStyle

void SetBarStyle( DWORD dwStyle );

Parameters

dwStyle

The desired styles for the control bar. Can be one or more of the following:

  • CBRS_ALIGN_TOP Allows the control bar to be docked to the top of the client area of a frame window.

  • CBRS_ALIGN_BOTTOM Allows the control bar to be docked to the bottom of the client area of a frame window.

  • CBRS_ALIGN_LEFT Allows the control bar to be docked to the left side of the client area of a frame window.

  • CBRS_ALIGN_RIGHT Allows the control bar to be docked to the right side of the client area of a frame window.

  • CBRS_ALIGN_ANY Allows the control bar to be docked to any side of the client area of a frame window.

  • CBRS_BORDER_TOP Causes a border to be drawn on the top edge of the control bar when it would be visible.

  • CBRS_BORDER_BOTTOM Causes a border to be drawn on the bottom edge of the control bar when it would be visible.

  • CBRS_BORDER_LEFT Causes a border to be drawn on the left edge of the control bar when it would be visible.

  • CBRS_BORDER_RIGHT Causes a border to be drawn on the right edge of the control bar when it would be visible.

  • CBRS_FLOAT_MULTI Allows multiple control bars to be floated in a single mini-frame window.

  • CBRS_TOOLTIPS Causes tool tips to be displayed for the control bar.

  • CBRS_FLYBY Causes message text to be updated at the same time as tool tips.

  • CBRS_GRIPPER Causes a gripper, similar to that used on bands in a CReBar object, to be drawn for any CControlBar-derived class.

Remarks

Call this function to set the desired CBRS_ styles for the control bar. Does not affect the WS_ (window style) settings.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CControlBar::GetBarStyle


CControlBar::SetBorders

void SetBorders( int cxLeft, int cyTop, int cxRight, int cyBottom );

void SetBorders( LPCRECT lpRect );

Parameters

cxLeft

The width (in pixels) of the control bar’s left border.

cxTop

The height (in pixels) of the control bar’s top border.

cxRight

The width (in pixels) of the control bar’s right border.

cxBottom

The height (in pixels) of the control bar’s bottom border.

lpRect

A pointer to a CRect object that contains the current width (in pixels)of each border of the control bar object.

Remarks

Call this function to set the size of the control bar’s borders. For instance, the following code example sets the top and bottom borders of the control bar to 5 pixels, and the left and right borders to 2 pixels:

m_myControlBar.SetBorders(2, 5, 2, 5);

CControlBar Overview | Class Members | Hierarchy Chart

See Also CControlBar::GetBorders


CControlBar::m_bAutoDelete

Remarks

m_bAutoDelete is a public variable of type BOOL. If it is nonzero when the Windows control-bar object is destroyed, the CControlBar object is deleted.

A control-bar object is usually embedded in a frame-window object. In this case, m_bAutoDelete is 0 because the embedded control-bar object is destroyed when the frame window is destroyed.

Set this variable to a nonzero value if you allocate a CControlBar object on the heap and you do not plan to call delete.

CControlBar Overview | Class Members | Hierarchy Chart

See Also CWnd::DestroyWindow


CCreateContext

CCreateContext does not have a base class.

The framework uses the CCreateContext structure when it creates the frame windows and views associated with a document. When creating a window, the values in this structure provide information used to connect the components that make up a document and the view of its data. You will only need to use CCreateContext if you are overriding parts of the creation process.

A CCreateContext structure contains pointers to the document, the frame window, the view, and the document template. It also contains a pointer to a CRuntimeClass that identifies the type of view to create. The run-time class information and the current document pointer are used to create a new view dynamically. The following table suggests how and when each CCreateContext member might be used:

Member | What it is for
m_pNewViewClass | CRuntimeClass of the new view to create.
m_pCurrentDoc | The existing document to be associated with the new view.
m_pNewDocTemplate | The document template associated with the creation of a new MDI frame window.
m_pLastView | The original view upon which additional views are modeled, as in the creation of a splitter window’s views or the creation of a second view on a document.
m_pCurrentFrame | The frame window upon which additional frame windows are modeled, as in the creation of a second frame window on a document.

When a document template creates a document and its associated components, it validates the information stored in the CCreateContext structure. For example, a view should not be created for a nonexistent document.

Note All of the pointers in CCreateContext are optional and can be NULL if unspecified or unknown.

CCreateContext is used by the member functions listed under “See Also.” Consult the descriptions of these functions for specific information if you plan to override them.

Here are a few general guidelines:

  • When passed as an argument for window creation, as in CWnd::Create, CFrameWnd::Create, and CFrameWnd::LoadFrame, the create context specifies what the new window should be connected to. For most windows, the entire structure is optional and a NULL pointer can be passed.

  • For overridable member functions, such as CFrameWnd::OnCreateClient, the CCreateContext argument is optional.

  • For member functions involved in view creation, you must provide enough information to create the view. For example, for the first view in a splitter window, you must supply the view class information and the current document.

In general, if you use the framework defaults, you can ignore CCreateContext. If you attempt more advanced modifications, the Microsoft Foundation Class Library source code or the sample programs, such as VIEWEX, will guide you. If you do forget a required parameter, a framework assertion will tell you what you forgot.

For more information on CCreateContext, see the MFC sample VIEWEX.

#include <afxext.h>

Hierarchy Chart

See Also CFrameWnd::Create, CFrameWnd::LoadFrame, CFrameWnd::OnCreateClient, CSplitterWnd::Create, CSplitterWnd::CreateView, CWnd::Create


CCriticalSection

An object of class CCriticalSection represents a “critical section” — a synchronization object that allows one thread at a time to access a resource or section of code. Critical sections are useful when only one thread at a time can be allowed to modify data or some other controlled resource. For example, adding nodes to a linked list is a process that should only be allowed by one thread at a time. By using a CCriticalSection object to control the linked list, only one thread at a time can gain access to the list.

Critical sections are used instead of mutexes when speed is critical and the resource will not be used across process boundaries. For more information on using mutexes in MFC, see CMutex.

To use a CCriticalSection object, construct the CCriticalSection object when it is needed. You can then access the critical section when the constructor returns. Call Unlock when you are done accessing the critical section.

To access a resource controlled by a CCriticalSection object in this manner, first create a variable of type CSingleLock in your resource’s access member function. Then call the lock object’s Lock member function (for example, CSingleLock::Lock). At this point, your thread will either gain access to the resource, wait for the resource to be released and gain access, or wait for the resource to be released and time out, failing to gain access to the resource. In any case, your resource has been accessed in a thread-safe manner. To release the resource, use the lock object’s Unlock member function (for example, CSingleLock::Unlock), or allow the lock object to fall out of scope.

Alternatively, you can create a CCriticalSection object stand-alone, and access it explicitly before attempting to access the controlled resource. This method, while clearer to someone reading your source code, is more prone to error as you must remember to lock and unlock the critical section before and after access.

For more information on using CCriticalSection objects, see the article Multithreading: How to Use the Synchronization Classes in Visual C++ Programmer's Guide.

#include <afxmt.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MTGDI

See Also CMutex


CCriticalSection Class Members

Construction

CCriticalSection Constructs a CCriticalSection object.

Methods

Unlock | Releases the CCriticalSection object.
Lock | Use to gain access to the CCriticalSection object.


CCriticalSection::CCriticalSection

CCriticalSection( );

Remarks

Constructs a CCriticalSection object. To access or release a CCriticalSection object, create a CSingleLock object and call its Lock and Unlock member functions. If the CCriticalSection object is being used stand-alone, call its Unlock member function to release it.


CCriticalSection::Lock

BOOL Lock( );

BOOL Lock( DWORD dwTimeout );

Return Value

Nonzero if the function was successful; otherwise 0.

Parameters

dwTimeout

Lock ignores this parameter value.

Remarks

Call this member function to gain access to the critical section object. Lock is a blocking call that will not return until the critical section object is signaled (becomes available).

If timed waits are necessary, you can use a CMutex object instead of a CCriticalSection object.

CCriticalSection Overview | Class Members | Hierarchy Chart

See Also CSingleLock::Lock


CCriticalSection::Unlock

virtual BOOL Unlock( );

Return Value

Nonzero if the CCriticalSection object was owned by the thread and the release was successful; otherwise 0.

Remarks

Releases the CCriticalSection object for use by another thread. If the CCriticalSection is being used stand-alone, Unlock must be called immediately after completing use of the resource controlled by the critical section. If a CSingleLock object is being used, CCriticalSection::Unlock will be called by the lock object’s Unlock member function.


CCtrlView

The class CCtrlView and its derivatives, CEditView, CListView, CTreeView, and CRichEditView, adapt the document-view architecture to the new common controls supported by Windows 95 and Windows NT versions 3.51 and later. For more information on the document-view architecture, see Document/View Architecture Topics in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CTreeView, CListView, CRichEditView


CCtrlView Class Members

Construction

CCtrlView Constructs a CCtrlView object.

Data Members

m_strClass | Contains the Windows class name for the view class.
m_dwDefaultStyle | Contains the default style for the view class.


CCtrlView::CCtrlView

CCtrlView( LPCTSTR lpszClass, DWORD dwStyle );

Parameters

lpszClass

Windows class name of the view class.

dwStyle

Style of the view class.

Remarks

Constructs a CCtrlView object. The framework calls the constructor when a new frame window is created or a window is split. Override CView::OnInitialUpdate to initialize the view after the document is attached. Call CWnd::Create or CWnd::CreateEx to create the Windows object.

CCtrlView Overview | Class Members | Hierarchy Chart

See Also CWnd::PreCreateWindow


CCtrlView::m_dwDefaultStyle

DWORD m_dwDefaultStyle;

Remarks

Contains the default style for the view class. This style is applied when a window is created.

CCtrlView Overview | Class Members | Hierarchy Chart

See Also CCtrlView::m_strClass


CCtrlView::m_strClass

CString m_strClass;

Remarks

Contains the Windows class name for the view class.

CCtrlView Overview | Class Members | Hierarchy Chart

See Also CCtrlView::m_dwDefaultStyle


CDaoDatabase

A CDaoDatabase object represents a connection to a database through which you can operate on the data. For information about the database formats supported, see the GetName member function. You can have one or more CDaoDatabase objects active at a time in a given “workspace,” represented by a CDaoWorkspace object. The workspace maintains a collection of open database objects, called the Databases collection.

Note The MFC DAO database classes are distinct from the MFC database classes based on ODBC. All DAO database class names have the “CDao” prefix. Class CDaoDatabase supplies an interface similar to that of the ODBC class CDatabase. The main difference is that CDatabase accesses the DBMS through Open Database Connectivity (ODBC) and an ODBC driver for that DBMS. CDaoDatabase accesses data through a Data Access Object (DAO) based on the Microsoft Jet database engine. In general, the MFC classes based on DAO are more capable than the MFC classes based on ODBC; the DAO-based classes can access data, including through ODBC drivers, via their own database engine. The DAO-based classes also support Data Definition Language (DDL) operations, such as adding tables via the classes, without having to call DAO directly.

Usage

You can create database objects implicitly, when you create recordset objects. But you can also create database objects explicitly. To use an existing database explicitly with CDaoDatabase, do either of the following:

  • Construct a CDaoDatabase object, passing a pointer to an open CDaoWorkspace object.

  • Or construct a CDaoDatabase object without specifying the workspace (MFC creates a temporary workspace object).

To create a new Microsoft Jet (.MDB) database, construct a CDaoDatabase object and call its Create member function. Do not call Open after Create.

To open an existing database, construct a CDaoDatabase object and call its Open member function.

Any of these techniques appends the DAO database object to the workspace’s Databases collection and opens a connection to the data. When you then construct CDaoRecordset, CDaoTableDef, or CDaoQueryDef objects for operating on the connected database, pass the constructors for these objects a pointer to your CDaoDatabase object. When you finish using the connection, call the Close member function and destroy the CDaoDatabase object. Close closes any recordsets you have not closed previously.

Transactions

Database transaction processing is supplied at the workspace level — see the BeginTrans, CommitTrans, and Rollback member functions of class CDaoWorkspace. For more information, see the article DAO Workspace: Managing Transactions in Visual C++ Programmer's Guide.

ODBC Connections

The recommended way to work with ODBC data sources is to attach external tables to a Microsoft Jet (.MDB) database. For more information, see the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

Collections

Each database maintains its own collections of tabledef, querydef, recordset, and relation objects. Class CDaoDatabase supplies member functions for manipulating these objects.

Note The objects are stored in DAO, not in the MFC database object. MFC supplies classes for tabledef, querydef, and recordset objects but not for relation objects.

For more information about CDaoDatabase, see the article DAO Database in Visual C++ Programmer's Guide.

#include <afxdao.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample DAOVIEW | MFC Sample DAOTABLE

See Also CDaoWorkspace, CDaoRecordset, CDaoTableDef, CDaoQueryDef, CDatabase, CDaoException


CDaoDatabase Class Members

Data Members

m_pWorkspace | A pointer to the CDaoWorkspace object that contains the database and defines its transaction space.
m_pDAODatabase | A pointer to the underlying DAO database object.

Construction

CDaoDatabase Constructs a CDaoDatabase object. Call Open to connect the object to a database.

Attributes

CanTransact | Returns nonzero if the database supports transactions.
CanUpdate | Returns nonzero if the CDaoDatabase object is updatable (not read-only).
GetConnect | Returns the connect string used to connect the CDaoDatabase object to a database. Used for ODBC.
GetName | Returns the name of the database currently in use.
GetQueryTimeout | Returns the number of seconds after which database query operations will time out. Affects all subsequent open, add new, update, and edit operations and other operations on ODBC data sources (only) such as Execute calls.
GetRecordsAffected | Returns the number of records affected by the last update, edit, or add operation or by a call to Execute.
GetVersion | Returns the version of the database engine associated with the database.
IsOpen | Returns nonzero if the CDaoDatabase object is currently connected to a database.
SetQueryTimeout | Sets the number of seconds after which database query operations (on ODBC data sources only) will time out. Affects all subsequent open, add new, update, and delete operations.

Operations

Close | Closes the database connection.
Create | Creates the underlying DAO database object and initializes the CDaoDatabase object.
CreateRelation | Defines a new relation among the tables in the database.
DeleteQueryDef | Deletes a querydef object saved in the database’s QueryDefs collection.
DeleteRelation | Deletes an existing relation between tables in the database.
DeleteTableDef | Deletes the definition of a table in the database. This deletes the actual table and all of its data.
Execute | Executes an action query. Calling Execute for a query that returns results throws an exception.
GetQueryDefCount | Returns the number of queries defined for the database.
GetQueryDefInfo | Returns information about a specified query defined in the database.
GetRelationCount | Returns the number of relations defined between tables in the database.
GetRelationInfo | Returns information about a specified relation defined between tables in the database.
GetTableDefCount | Returns the number of tables defined in the database.
GetTableDefInfo | Returns information about a specified table in the database.
Open | Establishes a connection to a database.


CDaoDatabase::CanTransact

BOOL CanTransact( );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the database supports transactions; otherwise 0.

Remarks

Call this member function to determine whether the database allows transactions. Transactions are managed in the database’s workspace. For information about transactions, see the article DAO Workspace: Managing Transactions in Visual C++ Programmer's Guide.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::BeginTrans, CDaoWorkspace::CommitTrans, CDaoWorkspace::Rollback


CDaoDatabase::CanUpdate

BOOL CanUpdate( );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the CDaoDatabase object allows updates; otherwise 0, indicating either that you passed TRUE in bReadOnly when you opened the CDaoDatabase object or that the database itself is read-only. See the Open member function.

Remarks

Call this member function to determine whether the CDaoDatabase object allows updates. For information about database updatability, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide and see the topic "Updatable Property" in DAO Help.


CDaoDatabase::CDaoDatabase

CDaoDatabase( CDaoWorkspace* pWorkspace = NULL );

Parameters

pWorkspace

A pointer to the CDaoWorkspace object that will contain the new database object. If you accept the default value of NULL, the constructor creates a temporary CDaoWorkspace object that uses the default DAO workspace. You can get a pointer to the workspace object via the m_pWorkspace data member.

Remarks

Constructs a CDaoDatabase object. After constructing the object, if you are creating a new Microsoft Jet (.MDB) database, call the object’s Create member function. If you are, instead, opening an existing database, call the object’s Open member function.

When you finish with the object, you should call its Close member function and then destroy the CDaoDatabase object.

You might find it convenient to embed the CDaoDatabase object in your document class.

Note A CDaoDatabase object is also created implicitly if you open a CDaoRecordset object without passing a pointer to an existing CDaoDatabase object. This database object is closed when you close the recordset object.

For information about workspaces, see the article DAO Workspace. For information about using CDaoDatabase objects, see the article DAO Database. These articles are in Visual C++ Programmer's Guide.


CDaoDatabase::Close

virtual void Close( );

Remarks

Call this member function to disconnect from a database and close any open recordsets, tabledefs, and querydefs associated with the database. It is good practice to close these objects yourself before you call this member function. Closing a CDaoDatabase object removes it from the Databases collection in the associated workspace. Because Close does not destroy the CDaoDatabase object, you can reuse the object by opening the same database or a different database.

CAUTION Call the Update member function (if there are pending edits) and the Close member function on all open recordset objects before you close a database. If you exit a function that declares CDaoRecordset or CDaoDatabase objects on the stack, the database is closed, any unsaved changes are lost, all pending transactions are rolled back, and any pending edits to your data are lost.

CAUTION If you try to close a database object while any recordset objects are open, or if you try to close a workspace object while any database objects belonging to that specific workspace are open, those recordset objects will be closed and any pending updates or edits will be rolled back. If you try to close a workspace object while any database objects belonging to it are open, the operation closes all database objects belonging to that specific workspace object, which may result in unclosed recordset objects being closed. If you do not close your database object, MFC reports an assertion failure in debug builds.

If the database object is defined outside the scope of a function, and you exit the function without closing it, the database object will remain open until explicitly closed or the module in which it is defined is out of scope.

For more information about CDaoDatabase objects, see the article DAO Database in Visual C++ Programmer's Guide. For related information, see the topic "Close Method" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoDatabase::Open, CDaoRecordset::Close, CDaoWorkspace::Close, CDaoQueryDef::Close, CDaoTableDef::Close


CDaoDatabase::Create

virtual void Create( LPCTSTR lpszName, LPCTSTR lpszLocale = dbLangGeneral, int dwOptions = 0 );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A string expression that is the name of the database file that you are creating. It can be the full path and filename, such as “C:\\MYDB.MDB”. You must supply a name. If you do not supply a filename extension, .MDB is appended. If your network supports the uniform naming convention (UNC), you can also specify a network path, such as “\\\\MYSERVER\\MYSHARE\\MYDIR\\MYDB”. Only Microsoft Jet (.MDB) database files can be created using this member function. (Double backslashes are required in string literals because “\” is the C++ escape character.)

lpszLocale

A string expression used to specify collating order for creating the database. The default value is dbLangGeneral. Possible values are:

  • dbLangGeneral English, German, French, Portuguese, Italian, and Modern Spanish

  • dbLangArabic Arabic

  • dbLangCyrillic Russian

  • dbLangCzech Czech

  • dbLangDutch Dutch

  • dbLangGreek Greek

  • dbLangHebrew Hebrew

  • dbLangHungarian Hungarian

  • dbLangIcelandic Icelandic

  • dbLangNordic Nordic languages (Microsoft Jet database engine version 1.0 only)

  • dbLangNorwdan Norwegian and Danish

  • dbLangPolish Polish

  • dbLangSpanish Traditional Spanish

  • dbLangSwedfin Swedish and Finnish

  • dbLangTurkish Turkish

dwOptions

An integer that indicates one or more options. Possible values are:

  • dbEncrypt Create an encrypted database.

  • dbVersion10 Create a database with Microsoft Jet database version 1.0.

  • dbVersion11 Create a database with Microsoft Jet database version 1.1.

  • dbVersion20 Create a database with Microsoft Jet database version 2.0.

  • dbVersion30 Create a database with Microsoft Jet database version 3.0.

    If you omit the encryption constant, an unencrypted database is created. You can specify only one version constant. If you omit a version constant, a database that uses the Microsoft Jet database version 3.0 is created.

    CAUTION If a database is not encrypted, it is possible, even if you implement user/password security, to directly read the binary disk file that constitutes the database.

Remarks

To create a new Microsoft Jet (.MDB) database, call this member function after you construct a CDaoDatabase object. Create creates the database file and the underlying DAO database object and initializes the C++ object. The object is appended to the associated workspace’s Databases collection. The database object is in an open state; do not call Open after Create.

Note With Create, you can create only Microsoft Jet (.MDB) databases. You cannot create ISAM databases or ODBC databases.

For information about databases, see the article DAO Database in Visual C++ Programmer's Guide. For related information, see the topic "CreateDatabase Method" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoDatabase::CDaoDatabase


CDaoDatabase::CreateRelation

void CreateRelation( LPCTSTR lpszName, LPCTSTR lpszTable, LPCTSTR lpszForeignTable, long lAttributes, LPCTSTR lpszField, LPCTSTR lpszForeignField );
throw( CDaoException, CMemoryException );

void CreateRelation( CDaoRelationInfo& relinfo );
throw( CDaoException, CMemoryException );

Parameters

lpszName

The unique name of the relation object. The name must start with a letter and can contain a maximum of 40 characters. It can include numbers and underscore characters but cannot include punctuation or spaces.

lpszTable

The name of the primary table in the relation. If the table does not exist, MFC throws an exception of type CDaoException.

lpszForeignTable

The name of the foreign table in the relation. If the table does not exist, MFC throws an exception of type CDaoException.

lAttributes

A long value that contains information about the relationship type. You can use this value to enforce referential integrity, among other things. You can use the bitwise-OR operator (|) to combine any of the following values (as long as the combination makes sense):

  • dbRelationUnique Relationship is one-to-one.

  • dbRelationDontEnforce Relationship is not enforced (no referential integrity).

  • dbRelationInherited Relationship exists in a noncurrent database that contains the two attached tables.

  • dbRelationUpdateCascade Updates will cascade (for more on cascades, see Remarks).

  • dbRelationDeleteCascade Deletions will cascade.

lpszField

A pointer to a null-terminated string containing the name of a field in the primary table (named by lpszTable).

lpszForeignField

A pointer to a null-terminated string containing the name of a field in the foreign table (named by lpszForeignTable).

relinfo

A reference to a CDaoRelationInfo object that contains information about the relation you want to create.

Remarks

Call this member function to establish a relation between one or more fields in a primary table in the database and one or more fields in a foreign table (another table in the database). The relationship cannot involve a query or an attached table from an external database.

Use the first version of the function when the relation involves one field in each of the two tables. Use the second version when the relation involves multiple fields. The maximum number of fields in a relation is 14.

This action creates an underlying DAO relation object, but this is an MFC implementation detail since MFC’s encapsulation of relation objects is contained within class CDaoDatabase. MFC does not supply a class for relations.

If you set the relation object’s attributes to activate cascade operations, the database engine automatically updates or deletes records in one or more other tables when changes are made to related primary key tables.

For example, suppose you establish a cascade delete relationship between a Customers table and an Orders table. When you delete records from the Customers table, records in the Orders table related to that customer are also deleted. In addition, if you establish cascade delete relationships between the Orders table and other tables, records from those tables are automatically deleted when you delete records from the Customers table.

For related information, see the topic "CreateRelation Method" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoDatabase::DeleteRelation


CDaoDatabase::DeleteQueryDef

void DeleteQueryDef( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

lpszName

The name of the saved query to delete.

Remarks

Call this member function to delete the specified querydef — saved query — from the CDaoDatabase object’s QueryDefs collection. Afterwards, that query is no longer defined in the database.

For information about creating querydef objects, see class CDaoQueryDef. A querydef object becomes associated with a particular CDaoDatabase object when you construct the CDaoQueryDef object, passing it a pointer to the database object.

For information about querydefs, see the article DAO QueryDef in Visual C++ Programmer's Guide.For related information, see the topic "Delete Method" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::Create, CDaoDatabase::CreateRelation, CDaoTableDef::Create


CDaoDatabase::DeleteRelation

void DeleteRelation( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

lpszName

The name of the relation to delete.

Remarks

Call this member function to delete an existing relation from the database object’s Relations collection. Afterwards, the relation no longer exists.

For related information, see the topic "Delete Method" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoDatabase::CreateRelation, CDaoTableDef::Create, CDaoQueryDef::Create


CDaoDatabase::DeleteTableDef

void DeleteTableDef( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

lpszName

The name of the tabledef to delete.

Remarks

Call this member function to delete the specified table and all of its data from the CDaoDatabase object’s TableDefs collection. Afterwards, that table is no longer defined in the database.

Warning Be very careful not to delete system tables.

For information about creating tabledef objects, see class CDaoTableDef. A tabledef object becomes associated with a particular CDaoDatabase object when you construct the CDaoTableDef object, passing it a pointer to the database object.

For information about tabledefs, see the article DAO TableDef in Visual C++ Programmer's Guide. For related information, see the topic "Delete Method" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::Create, CDaoQueryDef::Create, CDaoDatabase::CreateRelation


CDaoDatabase::Execute

void Execute( LPCTSTR lpszSQL, int nOptions = 0 );
throw( CDaoException, CMemoryException );

Parameters

lpszSQL

Pointer to a null-terminated string containing a valid SQL command to execute.

nOptions

An integer that specifies options relating to the integrity of the query. You can use the bitwise-OR operator (|) to combine any of the following constants (provided the combination makes sense — for example, you would not combine dbInconsistent with dbConsistent):

  • dbDenyWrite Deny write permission to other users.

  • dbInconsistent (Default) Inconsistent updates.

  • dbConsistent Consistent updates.

  • dbSQLPassThrough SQL pass-through. Causes the SQL statement to be passed to an ODBC data source for processing.

  • dbFailOnError Roll back updates if an error occurs.

  • dbSeeChanges Generate a run-time error if another user is changing data you are editing.

Note If both dbInconsistent and dbConsistent are included or if neither is included, the result is the default. For an explanation of these constants, see the topic "Execute Method" in DAO Help.

Remarks

Call this member function to run an action query or execute an SQL statement on the database. Execute works only for action queries or SQL pass-through queries that do not return results. It does not work for select queries, which return records.

For a definition and information about action queries, see the topics "Action Query" and "Execute Method" in DAO Help.

Tip Given a syntactically correct SQL statement and proper permissions, the Execute member function will not fail even if not a single row can be modified or deleted. Therefore, always use the dbFailOnError option when using the Execute member function to run an update or delete query. This option causes MFC to throw an exception of type CDaoException and rolls back all successful changes if any of the records affected are locked and cannot be updated or deleted. Note that you can always call GetRecordsAffected to see how many records were affected.

Call the GetRecordsAffected member function of the database object to determine the number of records affected by the most recent Execute call. For example, GetRecordsAffected returns information about the number of records deleted, updated, or inserted when executing an action query. The count returned will not reflect changes in related tables when cascade updates or deletes are in effect.

Execute does not return a recordset. Using Execute on a query that selects records causes MFC to throw an exception of type CDaoException. (There is no ExecuteSQL member function analogous to CDatabase::ExecuteSQL.)

For more information about using the Execute member function, see the article DAO Querydef: Using Querydefs in Visual C++ Programmer's Guide.


CDaoDatabase::GetConnect

CString GetConnect( );
throw( CDaoException, CMemoryException );

Return Value

The connect string if Open has been called successfully on an ODBC data source; otherwise, an empty string. For a Microsoft Jet (.MDB) database, the string is always empty unless you set it for use with the dbSQLPassThrough option used with the Execute member function or used in opening a recordset.

Remarks

Call this member function to retrieve the connect string used to connect the CDaoDatabase object to an ODBC or ISAM database. The string provides information about the source of an open database or a database used in a pass-through query. The connect string is composed of a database type specifier and zero or more parameters separated by semicolons. For additional information about connect strings in DAO, see the topic "Connect Property" in DAO Help.

Important Using the MFC DAO classes to connect to a data source via ODBC is less efficient than connecting via an attached table. For more information, see the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

Note The connect string is used to pass additional information to ODBC and certain ISAM drivers as needed. It is not used for .MDB databases. For Microsoft Jet database base tables, the connect string is an empty string ("") except when you use it for an SQL pass-through query as described under Return Value above.

See the Open member function for a description of how the connect string is created. Once the connect string has been set in the Open call, you can later use it to check the setting to determine the type, path, user ID, Password, or ODBC data source of the database.

For connect string syntax, see the topic "Connect Property" in DAO Help.


CDaoDatabase::GetName

CString GetName( );
throw( CDaoException, CMemoryException );

Return Value

The full path and filename for the database if successful; otherwise, an empty CString.

Remarks

Call this member function to retrieve the name of the currently open database, which is the name of an existing database file or registered ODBC data source name. If your network supports the uniform naming convention (UNC), you can also specify a network path, such as “\\\\MYSERVER\\MYSHARE\\MYDIR\\MYDB.MDB”. (Double backslashes are required in string literals because “\” is the C++ escape character.)

You might, for example, want to display this name in a heading. If an error occurs while retrieving the name, MFC throws an exception of type CDaoException.

Important For better performance when accessing external databases, it is recommended that you attach external database tables to a Microsoft Jet engine database (.MDB) rather than connecting directly to the data source.

The database type is indicated by the file or directory that the path points to, as follows:

Pathname points to.. | Database type
.MDB file | Microsoft Jet database (Microsoft Access)
Directory containing .DBF file(s) | dBASE® database
Directory containing .XLS file | Microsoft Excel database
Directory containing .DBF files(s) | Microsoft FoxPro® database
Directory containing .PDX file(s) | Paradox® database
Directory containing appropriately formatted text database files | Text format database

For ODBC databases, such as Microsoft SQL Server and Oracle®, the database’s connect string identifies a data source name (DSN) registered by ODBC.

For more about attaching external tables, see the article DAO External: Attaching External Tables in Visual C++ Programmer's Guide.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::Open, CDatabase::GetConnect


CDaoDatabase::GetQueryDefCount

short GetQueryDefCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of queries defined in the database.

Remarks

Call this member function to retrieve the number of queries defined in the database’s QueryDefs collection. GetQueryDefCount is useful if you need to loop through all querydefs in the QueryDefs collection. To obtain information about a given query in the collection, see GetQueryDefInfo.

For information about queries and querydef objects, see the articles DAO Queries and DAO QueryDef. Both articles are in Visual C++ Programmer's Guide.


CDaoDatabase::GetQueryDefInfo

void GetQueryDefInfo( int nIndex, CDaoQueryDefInfo& querydefinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetQueryDefInfo( LPCTSTR lpszName, CDaoQueryDefInfo& querydefinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The index of the predefined query in the database’s QueryDefs collection, for lookup by index.

querydefinfo

A reference to a CDaoQueryDefInfo object that returns the information requested.

dwInfoOptions

Options that specify which information about the recordset to retrieve. The available options are listed here along with what they cause the function to return about the recordset:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Type

  • AFX_DAO_SECONDARY_INFO Primary information plus: Date Created, Date of Last Update, Returns Records, Updatable

  • AFX_DAO_ALL_INFO Primary and secondary information plus: SQL, Connect, ODBCTimeout

lpszName

A string containing the name of a query defined in the database, for lookup by name.

Remarks

Call this member function to obtain various kinds of information about a query defined in the database. Two versions of the function are supplied so you can select a query either by index in the database’s QueryDefs collection or by the name of the query.

For a description of the information returned in querydefinfo, see the CDaoQueryDefInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. If you request one level of information, you get any prior levels of information as well.

For information about queries and querydef objects, see the articles DAO Queries and DAO QueryDef. Both articles are in Visual C++ Programmer's Guide.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoDatabase::GetQueryDefCount


CDaoDatabase::GetQueryTimeout

short GetQueryTimeout( );
throw( CDaoException, CMemoryException );

Return Value

A short integer containing the timeout value in seconds.

Remarks

Call this member function to retrieve the current number of seconds to allow before subsequent operations on the connected database are timed out. An operation might time out due to network access problems, excessive query processing time, and so on. While the setting is in effect, it affects all open, add new, update, and delete operations on any recordsets associated with this CDaoDatabase object. You can change the current timeout setting by calling SetQueryTimeout. Changing the query timeout value for a recordset after opening does not change the value for the recordset. For example, subsequent Move operations do not use the new value. The default value is initially set when the database engine is initialized.

The default value for query timeouts is taken from the Windows registry. If there is no registry setting, the default is 60 seconds. Not all databases support the ability to set a query timeout value. If you set a query timeout value of 0, no timeout occurs; and communication with the database may hang. This behavior may be useful during development. If the call fails, MFC throws an exception of type CDaoException.

For more information about database objects, see the article DAO Database in Visual C++ Programmer's Guide. For related information, see the topic "QueryTimeout Property" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::SetLoginTimeout


CDaoDatabase::GetRecordsAffected

long GetRecordsAffected( );
throw( CDaoException, CMemoryException );

Return Value

A long integer containing the number of records affected.

Remarks

Call this member function to determine the number of records affected by the most recent call of the Execute member function. The value returned includes the number of records deleted, updated, or inserted by an action query run with Execute. The count returned will not reflect changes in related tables when cascade updates or deletes are in effect.

For more information about database objects, see the article DAO Database in Visual C++ Programmer's Guide. For related information, see the topic "RecordsAffected Property" in DAO Help.


CDaoDatabase::GetRelationCount

short GetRelationCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of relations defined between tables in the database.

Remarks

Call this member function to obtain the number of relations defined between tables in the database. GetRelationCount is useful if you need to loop through all defined relations in the database’s Relations collection. To obtain information about a given relation in the collection, see GetRelationInfo.

To illustrate the concept of a relation, consider a Suppliers table and a Products table, which might have a one-to-many relationship. In this relationship, one supplier can supply more than one product. Other relations are one-to-one and many-to-many.

For more information about database objects, see the article DAO Database in Visual C++ Programmer's Guide.


CDaoDatabase::GetRelationInfo

void GetRelationInfo( int nIndex, CDaoRelationInfo& relinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetRelationInfo( LPCTSTR lpszName, CDaoRelationInfo& relinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The index of the relation object in the database’s Relations collection, for lookup by index.

relinfo

A reference to a CDaoRelationInfo object that returns the information requested.

dwInfoOptions

Options that specify which information about the relation to retrieve. The available options are listed here along with what they cause the function to return about the relation:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Table, Foreign Table

  • AFX_DAO_SECONDARY_INFO Attributes, Field Information

    The Field Information is a CDaoRelationFieldInfo object containing the fields from the primary table involved in the relation.

lpszName

A string containing the name of the relation object, for lookup by name.

Remarks

Call this member function to obtain information about a specified relation in the database’s Relations collection. Two versions of this function provide access either by index or by name. For a description of the information returned in relinfo, see the CDaoRelationInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. If you request information at one level, you also get information at any prior levels as well.

Note If you set the relation object’s attributes to activate cascade operations (dbRelationUpdateCascades or dbRelationDeleteCascades), the Microsoft Jet database engine automatically updates or deletes records in one or more other tables when changes are made to related primary key tables. For example, suppose you establish a cascade delete relationship between a Customers table and an Orders table. When you delete records from the Customers table, records in the Orders table related to that customer are also deleted. In addition, if you establish cascade delete relationships between the Orders table and other tables, records from those tables are automatically deleted when you delete records from the Customers table.

For more information about database objects, see the article DAO Database in Visual C++ Programmer's Guide.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoDatabase::GetRelationCount


CDaoDatabase::GetTableDefCount

short GetTableDefCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of tabledefs defined in the database.

Remarks

Call this member function to retrieve the number of tables defined in the database. GetTableDefCount is useful if you need to loop through all tabledefs in the database’s TableDefs collection. To obtain information about a given table in the collection, see GetTableDefInfo.

For more information about tables and tabledef objects, see the article DAO TableDef in Visual C++ Programmer's Guide.


CDaoDatabase::GetTableDefInfo

void GetTableDefInfo( int nIndex, CDaoTableDefInfo& tabledefinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetTableDefInfo( LPCTSTR lpszName, CDaoTableDefInfo& tabledefinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The index of the tabledef object in the database’s TableDefs collection, for lookup by index.

tabledefinfo

A reference to a CDaoTableDefInfo object that returns the information requested.

dwInfoOptions

Options that specify which information about the table to retrieve. The available options are listed here along with what they cause the function to return about the relation:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Updatable, Attributes

  • AFX_DAO_SECONDARY_INFO Primary information plus: Date Created, Date Last Updated, Source Table Name, Connect

  • AFX_DAO_ALL_INFO Primary and secondary information plus: Validation Rule, Validation Text, Record Count

lpszName

The name of the tabledef object, for lookup by name.

Remarks

Call this member function to obtain various kinds of information about a table defined in the database. Two versions of the function are supplied so you can select a table either by index in the database’s TableDefs collection or by the name of the table.

For a description of the information returned in tabledefinfo, see the CDaoTableDefInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. If you request information at one level, you get information for any prior levels as well.

! WARNING The AFX_DAO_ALL_INFO option provides information that can be slow to obtain. In this case, counting the records in the table could be very time consuming if there are many records.

For more information about tables and tabledef objects, see the article DAO TableDef in Visual C++ Programmer's Guide.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoDatabase::GetTableDefCount


CDaoDatabase::GetVersion

CString GetVersion( );
throw( CDaoException, CMemoryException );

Return Value

A CString that indicates the version of the database file associated with the object.

Remarks

Call this member function to determine the version of the Microsoft Jet database file. The value returned represents the version number in the form “major.minor”; for example, “3.0”. The product version number (for example, 3.0) consists of the version number (3), a period, and the release number (0). The versions to date are 1.0, 1.1, 2.0, and 3.0.

For more information about database objects, see the article DAO Database in Visual C++ Programmer's Guide. For related information, see the topic "Version Property" in DAO Help.


CDaoDatabase::IsOpen

BOOL IsOpen( ) const;

Return Value

Nonzero if the CDaoDatabase object is currently open; otherwise 0.

Remarks

Call this member function to determine whether the CDaoDatabase object is currently open on a database.

For more information about database objects, see the article DAO Database in Visual C++ Programmer's Guide.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::Open


CDaoDatabase::Open

virtual void Open( LPCTSTR lpszName, BOOL bExclusive = FALSE, BOOL bReadOnly = FALSE, LPCTSTR lpszConnect = _T("") );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A string expression that is the name of an existing Microsoft Jet (.MDB) database file. If the filename has an extension, it is required. If your network supports the uniform naming convention (UNC), you can also specify a network path, such as “\\\\MYSERVER\\MYSHARE\\MYDIR\\MYDB.MDB”. (Double backslashes are required in string literals because “\” is the C++ escape character.)

Some considerations apply when using lpszName. If it:

  • Refers to a database that is already open for exclusive access by another user, MFC throws an exception of type CDaoException. Trap that exception to let your user know that the database is unavailable.

  • Is an empty string ("") and lpszConnect is “ODBC;”, a dialog box listing all registered ODBC data source names is displayed so the user can select a database. You should avoid direct connections to ODBC data sources; use an attached table instead. For information, see the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

  • Otherwise does not refer to an existing database or valid ODBC data source name, MFC throws an exception of type CDaoException.

    Note For details about DAO error codes, see the DAOERR.H file. For related information, see the topic "Trappable Data Access Errors" in DAO Help.

bExclusive

A Boolean value that is TRUE if the database is to be opened for exclusive (nonshared) access and FALSE if the database is to be opened for shared access. If you omit this argument, the database is opened for shared access.

bReadOnly

A Boolean value that is TRUE if the database is to be opened for read-only access and FALSE if the database is to be opened for read/write access. If you omit this argument, the database is opened for read/write access. All dependent recordsets inherit this attribute.

lpszConnect

A string expression used for opening the database. This string constitutes the ODBC connect arguments. You must supply the exclusive and read-only arguments to supply a source string. For syntax, see the topic "Connect Property" in DAO Help. If the database is a Microsoft Jet database (.MDB), this string is empty (""). The syntax for the default value — _T("") — provides portability for Unicode as well as ANSI builds of your application.

Remarks

You must call this member function to initialize a newly constructed CDaoDatabase object that represents an existing database. Open associates the database with the underlying DAO object. You cannot use the database object to construct recordset, tabledef, or querydef objects until it is initialized. Open appends the database object to the associated workspace’s Databases collection.

Use the parameters as follows:

  • If you are opening a Microsoft Jet (.MDB) database, use the lpszName parameter and pass an empty string for the lpszConnect parameter or pass a password string of the form “;PWD=password” if the database is password-protected (.MDB databases only).

  • If you are opening an ODBC data source, pass a valid ODBC connect string in lpszConnect and an empty string in lpszName.

For related information, see the topic "OpenDatabase Method" in DAO Help.

Important For better performance when accessing external databases, including ISAM databases and ODBC data sources, it is recommended that you attach external database tables to a Microsoft Jet engine database (.MDB) rather than connecting directly to the data source.

It is possible for a connection attempt to time out if, for example, the DBMS host is unavailable. If the connection attempt fails, Open throws an exception of type CDaoException.

The remaining remarks apply only to ODBC databases:

If the database is an ODBC database and the parameters in your Open call do not contain enough information to make the connection, the ODBC driver opens a dialog box to obtain the necessary information from the user. When you call Open, your connect string, lpszConnect, is stored privately and is available by calling the GetConnect member function.

If you wish, you can open your own dialog box before you call Open to get information from the user, such as a password, then add that information to the connect string you pass to Open. Or you might want to save the connect string you pass (perhaps in the Windows registry) so you can reuse it the next time your application calls Open on a CDaoDatabase object.

You can also use the connect string for multiple levels of login authorization (each for a different CDaoDatabase object) or to convey other database-specific information.

For related information about connect strings, see the topic "Connect Property" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::CDatabase, CDatabase::Close


CDaoDatabase::SetQueryTimeout

void SetQueryTimeout( short nSeconds );
throw( CDaoException, CMemoryException );

Parameters

nSeconds

The number of seconds to allow before a query attempt times out.

Remarks

Call this member function to override the default number of seconds to allow before subsequent operations on the connected database time out. An operation might time out due to network access problems, excessive query processing time, and so on. Call SetQueryTimeout prior to opening your recordset or prior to calling the recordset’s AddNew, Update, or Delete member functions if you want to change the query timeout value. The setting affects all subsequent Open, AddNew, Update, and Delete calls to any recordsets associated with this CDaoDatabase object. Changing the query timeout value for a recordset after opening does not change the value for the recordset. For example, subsequent Move operations do not use the new value.

The default value for query timeouts is 60 seconds. Not all databases support the ability to set a query timeout value. If you set a query timeout value of 0, no timeout occurs; the communication with the database may hang. This behavior may be useful during development.

For related information, see the topic "QueryTimeout Property" in DAO Help.

CDaoDatabase Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::SetLoginTimeout


CDaoDatabase::m_pDAODatabase

Remarks

Contains a pointer to the OLE interface for the DAO database object underlying the CDaoDatabase object. Use this pointer if you need to access the DAO interface directly.

For more information about DAO databases, see the article DAO Database in Visual C++ Programmer's Guide. For information about calling DAO directly, see Technical Note 54.


CDaoDatabase::m_pWorkspace

Remarks

Contains a pointer to the CDaoWorkspace object that contains the database object. Use this pointer if you need to access the workspace directly — for example, to obtain pointers to other database objects in the workspace’s Databases collection.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide.


CDaoException

A CDaoException object represents an exception condition arising from the MFC database classes based on data access objects (DAO). The class includes public data members you can use to determine the cause of the exception. CDaoException objects are constructed and thrown by member functions of the DAO database classes.

Note The DAO database classes are distinct from the MFC database classes based on Open Database Connectivity (ODBC). All DAO database class names have the “CDao” prefix. You can still access ODBC data sources with the DAO classes. In general, the MFC classes based on DAO are more capable than the MFC classes based on ODBC; the DAO-based classes can access data, including through ODBC drivers, via their own database engine. The DAO-based classes also support Data Definition Language (DDL) operations, such as adding tables via the classes, without having to call DAO directly. For information on exceptions thrown by the ODBC classes, see CDBException.

You can access exception objects within the scope of a CATCH expression. You can also throw CDaoException objects from your own code with the AfxThrowDaoException global function.

In MFC, all DAO errors are expressed as exceptions, of type CDaoException. When you catch an exception of this type, you can use CDaoException member functions to retrieve information from any DAO error objects stored in the database engine’s Errors collection. As each error occurs, one or more error objects are placed in the Errors collection. (Normally the collection contains only one error object; if you are using an ODBC data source, you are more likely to get multiple error objects.) When another DAO operation generates an error, the Errors collection is cleared, and the new error object is placed in the Errors collection. DAO operations that do not generate an error have no effect on the Errors collection.

For DAO error codes, see the file DAOERR.H. For related information, see the topic "Trappable Data Access Errors" in DAO Help.

For more information about exception handling in general, or about CDaoException objects, see the articles Exceptions and Exceptions: Database Exceptions in Visual C++ Programmer's Guide. The second article contains example code that illustrates exception handling in DAO.

#include <afxdao.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample DAOVIEW

See Also CException


CDaoException Class Members

Data Members

m_scode | The SCODE value associated with the error.
m_nAfxDaoError | Contains an extended error code for any error in the MFC DAO classes.
m_pErrorInfo | A pointer to a CDaoErrorInfo object that contains information about one DAO error object.

Construction

CDaoException Constructs a CDaoException object.

Operations

GetErrorCount | Returns the number of errors in the database engine’s Errors collection.
GetErrorInfo | Returns error information about a particular error object in the Errors collection.


CDaoException::CDaoException

CDaoException( );

Remarks

Constructs a CDaoException object. Ordinarily, the framework creates exception objects when its code throws an exception. You seldom need to construct an exception object explicitly. If you want to throw a CDaoException from your own code, call the global function AfxThrowDaoException.

However, you might want to explicitly create an exception object if you are making direct calls to DAO via the DAO interface pointers that MFC classes encapsulate. In that case, you might need to retrieve error information from DAO. Suppose an error occurs in DAO when you call a DAO method via, say, the DAODatabases interface to a workspace’s Databases collection. To retrieve the DAO error information:

  1. Construct a CDaoException object.

  2. Call the exception object’s GetErrorCount member function to determine how many error objects are in the database engine’s Errors collection. (Normally only one, unless you are using an ODBC data source.)

  3. Call the exception object’s GetErrorInfo member function to retrieve one specific error object at a time, by index in the collection, via the exception object. Think of the exception object as a proxy for one DAO error object.

  4. Examine the current CDaoErrorInfo structure that GetErrorInfo returns in the m_pErrorInfo data member. Its members provide information on the DAO error.

  5. In the case of an ODBC data source, repeat steps 3 and 4 as needed, for more error objects.

  6. If you constructed the exception object on the heap, delete it with the delete operator when you finish.

For more information about handling errors in the MFC DAO classes, see the article Exceptions: Database Exceptions in Visual C++ Programmer's Guide.


CDaoException::GetErrorCount

short GetErrorCount( );

Return Value

The number of DAO error objects in the database engine’s Errors collection.

Remarks

Call this member function to retrieve the number of DAO error objects in the database engine’s Errors collection. This information is useful for looping through the Errors collection to retrieve each of the one or more DAO error objects in the collection. To retrieve an error object by index or by DAO error number, call the GetErrorInfo member function.

Note Normally there is only one error object in the Errors collection. If you are working with an ODBC data source, however, there could be more than one.


CDaoException::GetErrorInfo

void GetErrorInfo( int nIndex );

Parameters

nIndex

The index of the error information in the database engine’s Errors collection, for lookup by index.

Remarks

Call this member function to obtain the following kinds of information about the exception:

  • Error Code

  • Source

  • Description

  • Help File

  • Help Context

GetErrorInfo stores the information in the exception object’s m_pErrorInfo data member. For a brief description of the information returned, see m_pErrorInfo. If you catch an exception of type CDaoException thrown by MFC, the m_pErrorInfo member will already be filled in. If you choose to call DAO directly, you must call the exception object’s GetErrorInfo member function yourself to fill m_pErrorInfo. For a more detailed description, see the CDaoErrorInfo structure.

For information about DAO exceptions, and example code, see the article Exceptions: Database Exceptions. For more about getting information from DAO object collections, see the article DAO Collections: Obtaining Information About DAO Objects. Both articles are in Visual C++ Programmer's Guide.

CDaoException Overview | Class Members | Hierarchy Chart

See Also CDaoException::GetErrorCount


CDaoException::m_nAfxDaoError

Remarks

Contains an MFC extended error code. This code is supplied in cases where a specific component of the MFC DAO classes has erred.

Possible values are:

  • NO_AFX_DAO_ERROR The most recent operation did not result in an MFC extended error. However, the operation could have produced other errors from DAO or OLE, so you should check m_pErrorInfo and possibly m_scode.

  • AFX_DAO_ERROR_ENGINE_INITIALIZATION MFC could not initialize the Microsoft Jet database engine. OLE might have failed to initialize, or it might have been impossible to create an instance of the DAO database engine object. These problems usually suggest a bad installation of either DAO or OLE.

  • AFX_DAO_ERROR_DFX_BIND An address used in a DAO record field exchange (DFX) function call does not exist or is invalid (the address was not used to bind data). You might have passed a bad address in a DFX call, or the address might have become invalid between DFX operations.

  • AFX_DAO_ERROR_OBJECT_NOT_OPEN You attempted to open a recordset based on a querydef or a tabledef object that was not in an open state.

For more information about DFX, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide.

CDaoException Overview | Class Members | Hierarchy Chart

See Also CDaoException::GetErrorCount, CDaoException::GetErrorInfo


CDaoException::m_pErrorInfo

Remarks

Contains a pointer to a CDaoErrorInfo structure that provides information on the DAO error object that you last retrieved by calling GetErrorInfo. This object contains the following information:

CDaoErrorInfo member | Information | Meaning
m_lErrorCode | Error Code | The DAO error code
m_strSource | Source | The name of the object or application that originally generated the error
m_strDescription | Description | A descriptive string associated with the error
m_strHelpFile | Help File | A path to a Windows Help file in which the user can get information about the problem
m_lHelpContext | Help Context | The context ID for a topic in the DAO Help file

For full details about the information contained in the CDaoErrorInfo object, see the CDaoErrorInfo structure.

CDaoException Overview | Class Members | Hierarchy Chart

See Also CDaoException::m_scode, CDaoException::m_nAfxDaoError


CDaoException::m_scode

Remarks

Contains a value of type SCODE that describes the error. This is an OLE code. You will seldom need to use this value because, in almost all cases, more specific MFC or DAO error information is available in the other CDaoException data members.

For information about SCODE, see the topic Structure of OLE Error Codes in the Win32 SDK, OLE Programmer’s Reference, Volume 1. The SCODE data type maps to the HRESULT data type.

CDaoException Overview | Class Members | Hierarchy Chart

See Also CDaoException::m_pErrorInfo, CDaoException::m_nAfxDaoError


CDaoFieldExchange

CDaoFieldExchange does not have a base class.

The CDaoFieldExchange class supports the DAO record field exchange (DFX) routines used by the DAO database classes. Use this class if you are writing data exchange routines for custom data types; otherwise, you will not directly use this class. DFX exchanges data between the field data members of your CDaoRecordset object and the corresponding fields of the current record on the data source. DFX manages the exchange in both directions, from the data source and to the data source. See Technical Note 53 for information about writing custom DFX routines.

Note The DAO database classes are distinct from the MFC database classes based on Open Database Connectivity (ODBC). All DAO database class names have the “CDao” prefix. You can still access ODBC data sources with the DAO classes. In general, the MFC classes based on DAO are more capable than the MFC classes based on ODBC. The DAO-based classes can access data, including through ODBC drivers, via their own database engine. They also support Data Definition Language (DDL) operations, such as adding tables via the classes instead of having to call DAO yourself.

Note DAO record field exchange (DFX) is very similar to record field exchange (RFX) in the ODBC-based MFC database classes (CDatabase, CRecordset). If you understand RFX, you will find it easy to use DFX.

A CDaoFieldExchange object provides the context information needed for DAO record field exchange to take place. CDaoFieldExchange objects support a number of operations, including binding parameters and field data members and setting various flags on the fields of the current record. DFX operations are performed on recordset-class data members of types defined by the enum FieldType in CDaoFieldExchange. Possible FieldType values are:

  • CDaoFieldExchange::outputColumn for field data members.

  • CDaoFieldExchange::param for parameter data members.

The IsValidOperation member function is provided for writing your own custom DFX routines. You will use SetFieldType frequently in your CDaoRecordset::DoFieldExchange functions. For details about the DFX global functions, see Record Field Exchange Functions. For information about writing custom DFX routines for your own data types, see Technical Note 53.

For information about DFX, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide.

#include <afxdao.h>

Class Members | Hierarchy Chart

Sample MFC Sample DAOENROL

See Also CDaoRecordset


CDaoFieldExchange Class Members

Data Members

m_nOperation | The DFX operation being performed by the current call to the recordset’s DoFieldExchange member function.
m_prs | A pointer to the recordset on which DFX operations are being performed.

Member Functions

IsValidOperation | Returns nonzero if the current operation is appropriate for the type of field being updated.
SetFieldType | Specifies the type of recordset data member — column or parameter — represented by all subsequent calls to DFX functions until the next call to SetFieldType.


CDaoFieldExchange::IsValidOperation

BOOL IsValidOperation( );

Return Value

Nonzero if the current operation is appropriate for the type of field being updated.

Remarks

If you write your own DFX function, call IsValidOperation at the beginning of your function to determine whether the current operation can be performed on a particular field data member type (a CDaoFieldExchange::outputColumn or a CDaoFieldExchange::param). Some of the operations performed by the DFX mechanism apply only to one of the possible field types. Follow the model of the existing DFX functions.

For more information about DFX, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide. For additional information on writing custom DFX routines, see Technical Note 53.

CDaoFieldExchange Overview | Class Members | Hierarchy Chart

See Also CDaoFieldExchange::SetFieldType


CDaoFieldExchange::SetFieldType

void SetFieldType( UINT nFieldType );

Parameters

nFieldType

A value of the enum FieldType, declared in CDaoFieldExchange, which can be either of the following:

  • CDaoFieldExchange::outputColumn

  • CDaoFieldExchange::param

Remarks

Call SetFieldType in your CDaoRecordset class’s DoFieldExchange override. Normally, ClassWizard writes this call for you. If you write your own function and are using the wizard to write your DoFieldExchange function, add calls to your own function outside the field map. If you do not use the wizard, there will not be a field map. The call precedes calls to DFX functions, one for each field data member of your class, and identifies the field type as CDaoFieldExchange::outputColumn.

If you parameterize your recordset class, you should add DFX calls for all parameter data members (outside the field map) and precede these calls with a call to SetFieldType. Pass the value CDaoFieldExchange::param. (You can, instead, use a CDaoQueryDef and set its parameter values.)

In general, each group of DFX function calls associated with field data members or parameter data members must be preceded by a call to SetFieldType. The nFieldType parameter of each SetFieldType call identifies the type of the data members represented by the DFX function calls that follow the SetFieldType call.

For more information about DFX, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide.

CDaoFieldExchange Overview | Class Members | Hierarchy Chart

See Also CDaoFieldExchange::IsValidOperation, CDaoRecordset::DoFieldExchange


CDaoFieldExchange::m_nOperation

Remarks

Identifies the operation to be performed on the CDaoRecordset object associated with the field exchange object. The CDaoFieldExchange object supplies the context for a number of different DFX operations on the recordset.

Note The PSEUDO NULL value described under the MarkForAddNew and SetFieldNull operations below is a value used to mark fields Null. The DAO record field exchange mechanism (DFX) uses this value to determine which fields have been explicitly marked Null. PSEUDO NULL is not required for COleDateTime and COleCurrency fields.

For more information about DFX and these operations, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide.

Possible values of m_nOperation are:

Operation | Description
AddToParameterList | Builds the PARAMETERS clause of the SQL statement.
AddToSelectList | Builds the SELECT clause of the SQL statement.
BindField | Binds a field in the database to a memory location in your application.
BindParam | Sets parameter values for the recordset’s query.
Fixup | Sets the Null status for a field.
AllocCache | Allocates the cache used to check for “dirty” fields in the recordset.
StoreField | Saves the current record to the cache.
LoadField | Restores the cached data member variables in the recordset.
FreeCache | Frees the cache used to check for “dirty” fields in the recordset.
SetFieldNull | Sets a field’s status to Null and value to PSEUDO NULL.
MarkForAddNew | Marks fields “dirty” if not PSEUDO NULL.
MarkForEdit | Marks fields “dirty” if they do not match the cache.
SetDirtyField | Sets field values marked as “dirty.”
DumpField | Dumps a field’s contents (debug only).
MaxDFXOperation | Used for input checking.

CDaoFieldExchange Overview | Class Members | Hierarchy Chart

See Also CDaoFieldExchange::IsValidOperation, CDaoFieldExchange::m_prs, CDaoRecordset::DoFieldExchange


CDaoFieldExchange::m_prs

Remarks

Contains a pointer to the CDaoRecordset object associated with the CDaoFieldExchange object.

For more information about DFX, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide.

CDaoFieldExchange Overview | Class Members | Hierarchy Chart

See Also CDaoFieldExchange::m_nOperation, CDaoRecordset


CDaoQueryDef

A CDaoQueryDef object represents a query definition, or “querydef,” usually one saved in a database. A querydef is a data access object that contains the SQL statement that describes a query, and its properties, such as “Date Created” and “ODBC Timeout.” You can also create temporary querydef objects without saving them, but it is convenient — and much more efficient — to save commonly reused queries in a database. A CDaoDatabase object maintains a collection, called the QueryDefs collection, that contains its saved querydefs.

Note The DAO database classes are distinct from the MFC database classes based on Open Database Connectivity (ODBC). All DAO database class names have the “CDao” prefix. You can still access ODBC data sources with the DAO classes. In general, the MFC classes based on DAO are more capable than the MFC classes based on ODBC; the DAO-based classes can access data, including through ODBC drivers, via their own database engine. The DAO-based classes also support Data Definition Language (DDL) operations, such as adding tables via the classes, without having to call DAO directly.

Usage

Use querydef objects either to work with an existing saved query or to create a new saved query or temporary query:

  1. In all cases, first construct a CDaoQueryDef object, supplying a pointer to the CDaoDatabase object to which the query belongs.

  2. Then do the following, depending on what you want:
    • To use an existing saved query, call the querydef object’s Open member function, supplying the name of the saved query.

    • To create a new saved query, call the querydef object’s Create member function, supplying the name of the query. Then call Append to save the query by appending it to the database’s QueryDefs collection. Create puts the querydef into an open state, so after calling Create you do not call Open.

    • To create a temporary querydef, call Create. Pass an empty string for the query name. Do not call Append.

When you finish using a querydef object, call its Close member function; then destroy the querydef object.

Tip The easiest way to create saved queries is to create them and store them in your database using Microsoft Access. Then you can open and use them in your MFC code.

Purposes

You can use a querydef object for any of the following purposes:

  • To create a CDaoRecordset object

  • To call the object’s Execute member function to directly execute an action query or an SQL pass-through query

You can use a querydef object for any type of query, including select, action, crosstab, delete, update, append, make-table, data definition, SQL pass-through, union, and bulk queries. The query’s type is determined by the content of the SQL statement that you supply. For information about query types, see the Execute and GetType member functions. Recordsets are commonly used for row-returning queries, usually those using the SELECT ... FROM keywords. Execute is most commonly used for bulk operations. For more information, see Execute and CDaoRecordset.

Querydefs and Recordsets

To use a querydef object to create a CDaoRecordset object, you typically create or open a querydef as described above. Then construct a recordset object, passing a pointer to your querydef object when you call CDaoRecordset::Open. The querydef you pass must be in an open state. For more information, see class CDaoRecordset.

You cannot use a querydef to create a recordset (the most common use for a querydef) unless it is in an open state. Put the querydef into an open state by calling either Open or Create.

External Databases

Querydef objects are the preferred way to use the native SQL dialect of an external database engine. For example, you can create a Transact SQL query (as used on Microsoft SQL Server) and store it in a querydef object. When you need to use a SQL query not based on the Microsoft Jet database engine, you must provide a connect string that points to the external data source. Queries with valid connect strings bypass the database engine and pass the query directly to the external database server for processing.

Tip The preferred way to work with ODBC tables is to attach them to a Microsoft Jet (.MDB) database. For more information, see the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

For more information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For related information, see the topics "QueryDef Object", "QueryDefs Collection", and "Accessing External Databases with DAO" in DAO Help.

#include <afxdao.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample DAOVIEW | MFC Sample DAOTABLE

See Also CDaoRecordset, CDaoDatabase, CDaoTableDef, CDaoException


CDaoQueryDef Class Members

Data Members

m_pDatabase | A pointer to the CDaoDatabase object with which the querydef is associated. The querydef might be saved in the database or not.
m_pDAOQueryDef | A pointer to the OLE interface for the underlying DAO querydef object.

Construction

CDaoQueryDef | Constructs a CDaoQueryDef object. Next call Open or Create, depending on your needs.
Create | Creates the underlying DAO querydef object. Use the querydef as a temporary query, or call Append to save it in the database.
Append | Appends the querydef to the database’s QueryDefs collection as a saved query.
Open | Opens an existing querydef stored in the database’s QueryDefs collection.
Close | Closes the querydef object. Destroy the C++ object when you finish with it.

Attributes |
CanUpdate | Returns nonzero if the query can update the database.
GetConnect | Returns the connect string associated with the querydef. The connect string identifies the data source. (For SQL pass-through queries only; otherwise an empty string.)
GetDateCreated | Returns the date the saved query was created.
GetDateLastUpdated | Returns the date the saved query was last updated.
GetName | Returns the name of the querydef.
GetODBCTimeout | Returns the timeout value used by ODBC (for an ODBC query) when the querydef is executed. This determines how long to allow for the query’s action to complete.
GetRecordsAffected | Returns the number of records affected by an action query.
GetReturnsRecords | Returns nonzero if the query defined by the querydef returns records.
GetSQL | Returns the SQL string that specifies the query defined by the querydef.
GetType | Returns the query type: delete, update, append, make-table, and so on.
IsOpen | Returns nonzero if the querydef is open and can be executed.
SetConnect | Sets the connect string for an SQL pass-through query on an ODBC data source.
SetName | Sets the name of the saved query, replacing the name in use when the querydef was created.
SetODBCTimeout | Sets the timeout value used by ODBC (for an ODBC query) when the querydef is executed.
SetReturnsRecords | Specifies whether the querydef returns records. Setting this attribute to TRUE is only valid for SQL pass-through queries.
SetSQL | Sets the SQL string that specifies the query defined by the querydef.

Operations

Execute | Executes the query defined by the querydef object.
GetFieldCount | Returns the number of fields defined by the querydef.
GetFieldInfo | Returns information about a specified field defined in the query.
GetParameterCount | Returns the number of parameters defined for the query.
GetParameterInfo | Returns information about a specified parameter to the query.
GetParamValue | Returns the value of a specified parameter to the query.
SetParamValue | Sets the value of a specified parameter to the query.


CDaoQueryDef::Append

virtual void Append( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function after you call Create to create a new querydef object. Append saves the querydef in the database by appending the object to the database’s QueryDefs collection. You can use the querydef as a temporary object without appending it, but if you want it to persist, you must call Append.

If you attempt to append a temporary querydef object, MFC throws an exception of type CDaoException.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.


CDaoQueryDef::CanUpdate

BOOL CanUpdate( );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if you are permitted to modify the querydef; otherwise 0.

Remarks

Call this member function to determine whether you can modify the querydef — such as changing its name or SQL string. You can modify the querydef if:

  • It is not based on a database that is open read-only.

  • You have update permissions for the database.

    This depends on whether you have implemented security features. MFC does not provide support for security; you must implement it yourself by calling DAO directly or by using Microsoft Access. See the topic "Permissions Property" in DAO Help.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.


CDaoQueryDef::CDaoQueryDef

CDaoQueryDef( CDaoDatabase* pDatabase );

Parameters

pDatabase

A pointer to an open CDaoDatabase object.

Remarks

Constructs a CDaoQueryDef object. The object can represent an existing querydef stored in the database’s QueryDefs collection, a new query to be stored in the collection, or a temporary query, not to be stored. Your next step depends on the type of querydef:

  • If the object represents an existing querydef, call the object’s Open member function to initialize it.

  • If the object represents a new querydef to be saved, call the object’s Create member function. This adds the object to the database’s QueryDefs collection. Then call CDaoQueryDef member functions to set the object’s attributes. Finally, call Append.

  • If the object represents a temporary querydef (not to be saved in the database), call Create, passing an empty string for the query’s name. After calling Create, initialize the querydef by directly setting its attributes. Do not call Append.

To set the attributes of the querydef, you can use the SetName, SetSQL, SetConnect, SetODBCTimeout, and SetReturnsRecords member functions.

When you finish with the querydef object, call its Close member function. If you have a pointer to the querydef, use the delete operator to destroy the C++ object.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetConnect, CDaoQueryDef::GetDateCreated, CDaoQueryDef::GetDateLastUpdated, CDaoQueryDef::GetName, CDaoQueryDef::GetODBCTimeout, CDaoQueryDef::GetReturnsRecords, CDaoQueryDef::GetSQL


CDaoQueryDef::Close

virtual void Close( );

Remarks

Call this member function when you finish using the querydef object. Closing the querydef releases the underlying DAO object but does not destroy the saved DAO querydef object or the C++ CDaoQueryDef object. This is not the same as CDaoDatabase::DeleteQueryDef, which deletes the querydef from the database’s QueryDefs collection in DAO (if not a temporary querydef).

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::Open, CDaoQueryDef::Create, CDaoQueryDef::CDaoQueryDef


CDaoQueryDef::Create

virtual void Create( LPCTSTR lpszName = NULL, LPCTSTR lpszSQL = NULL );
throw( CDaoException, CMemoryException );

Parameters

lpszName

The unique name of the query saved in the database. For details about the string, see the topic "CreateQueryDef Method" in DAO Help. If you accept the default value, an empty string, a temporary querydef is created. Such a query is not saved in the QueryDefs collection.

lpszSQL

The SQL string that defines the query. If you accept the default value of NULL, you must later call SetSQL to set the string. Until then, the query is undefined. You can, however, use the undefined query to open a recordset; see Remarks for details. The SQL statement must be defined before you can append the querydef to the QueryDefs collection.

Remarks

Call this member function to create a new saved query or a new temporary query. If you pass a name in lpszName, you can then call Append to save the querydef in the database’s QueryDefs collection. Otherwise, the object is a temporary querydef and is not saved. In either case, the querydef is in an open state, and you can either use it to create a CDaoRecordset object or call the querydef’s Execute member function.

If you do not supply an SQL statement in lpszSQL, you cannot run the query with Execute but you can use it to create a recordset. In that case, MFC uses the recordset’s default SQL statement.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::Open, CDaoQueryDef::CDaoQueryDef, CDaoRecordset::GetSQL


CDaoQueryDef::Execute

virtual void Execute( int nOptions = dbFailOnError );
throw( CDaoException, CMemoryException );

Parameters

nOptions

An integer that determines the characteristics of the query. For related information, see the topic "Execute Method" in DAO Help. You can use the bitwise-OR operator (|) to combine the following constants for this argument:

  • dbDenyWrite Deny write permission to other users.

  • dbInconsistent Inconsistent updates.

  • dbConsistent Consistent updates.

  • dbSQLPassThrough SQL pass-through. Causes the SQL statement to be passed to an ODBC database for processing.

  • dbFailOnError Default value. Roll back updates if an error occurs and report the error to the user.

  • dbSeeChanges Generate a run-time error if another user is changing data you are editing.

    Note For an explanation of the terms “inconsistent” and “consistent,” see the topic "Execute Method" in DAO Help.

Remarks

Call this member function to run the query defined by the querydef object. Querydef objects used for execution in this manner can only represent one of the following query types:

  • Action queries

  • SQL pass-through queries

Execute does not work for queries that return records, such as select queries. Execute is commonly used for bulk operation queries, such as UPDATE, INSERT, or SELECT INTO, or for data definition language (DDL) operations.

For an explanation of action queries and SQL pass-through queries, see the article DAO Querydef: Action Queries and SQL Pass-Through Queries in Visual C++ Programmer's Guide.

Tip The preferred way to work with ODBC data sources is to attach tables to a Microsoft Jet (.MDB) database. For more information, see the topic "Accessing External Databases with DAO" in DAO Help and the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

Call the GetRecordsAffected member function of the querydef object to determine the number of records affected by the most recent Execute call. For example, GetRecordsAffected returns information about the number of records deleted, updated, or inserted when executing an action query. The count returned will not reflect changes in related tables when cascade updates or deletes are in effect.

If you include both dbInconsistent and dbConsistent or if you include neither, the result is the default, dbInconsistent.

Execute does not return a recordset. Using Execute on a query that selects records causes MFC to throw an exception of type CDaoException.

For more information about using the Execute member function for querydef objects, see the article DAO Querydef: Using Querydefs in Visual C++ Programmer's Guide.


CDaoQueryDef::GetConnect

CString GetConnect( );
throw( CDaoException, CMemoryException );

Return Value

A CString containing the connect string for the querydef.

Remarks

Call this member function to get the connect string associated with the querydef’s data source. This function is used only with ODBC data sources and certain ISAM drivers. It is not used with Microsoft Jet (.MDB) databases; in this case, GetConnect returns an empty string. For more information, see SetConnect.

Tip The preferred way to work with ODBC tables is to attach them to an .MDB database. For more information, see the topic "Accessing External Databases with DAO" in DAO Help and the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

For information about connect strings, see the topic "Connect Property" in DAO Help. For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.


CDaoQueryDef::GetDateCreated

COleDateTime GetDateCreated( );
throw( CDaoException, CMemoryException );

Return Value

A COleDateTime object containing the date and time the querydef was created.

Remarks

Call this member function to get the date the querydef object was created.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For related information, see the topic "DateCreated, LastUpdated Properties" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetDateLastUpdated


CDaoQueryDef::GetDateLastUpdated

COleDateTime GetDateLastUpdated( );
throw( CDaoException, CMemoryException );

Return Value

A COleDateTime object containing the date and time the querydef was last updated.

Remarks

Call this member function to get the date the querydef object was last updated — when any of its properties were changed, such as its name, its SQL string, or its connect string.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For related information, see the topic "DateCreated, LastUpdated Properties" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetDateCreated


CDaoQueryDef::GetFieldCount

short GetFieldCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of fields defined in the query.

Remarks

Call this member function to retrieve the number of fields in the query. GetFieldCount is useful for looping through all fields in the querydef. For that purpose, use GetFieldCount in conjunction with GetFieldInfo.

For information about obtaining information about querydef fields, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.


CDaoQueryDef::GetFieldInfo

void GetFieldInfo( int nIndex, CDaoFieldInfo& fieldinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetFieldInfo( LPCTSTR lpszName, CDaoFieldInfo& fieldinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The zero-based index of the desired field in the querydef’s Fields collection, for lookup by index.

fieldinfo

A reference to a CDaoFieldInfo object that returns the information requested.

dwInfoOptions

Options that specify which information about the field to retrieve. The available options are listed here along with what they cause the function to return:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Type, Size, Attributes

  • AFX_DAO_SECONDARY_INFO Primary information plus: Ordinal Position, Required, Allow Zero Length, Source Field, Foreign Name, Source Table, Collating Order

  • AFX_DAO_ALL_INFO Primary and secondary information plus: Default Value, Validation Text, Validation Rule

lpszName

A string containing the name of the desired field, for lookup by name. You can use a CString.

Remarks

Call this member function to obtain various kinds of information about a field defined in the querydef. For a description of the information returned in fieldinfo, see the CDaoFieldInfo structure. This structure has members that correspond to the descriptive information under dwInfoOptions above. If you request one level of information, you get any prior levels of information as well.

For more information about obtaining field information, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetFieldCount


CDaoQueryDef::GetName

CString GetName( );
throw( CDaoException, CMemoryException );

Return Value

The name of the query.

Remarks

Call this member function to retrieve the name of the query represented by the querydef. Querydef names are unique user-defined names. For more information about querydef names, see the topic "Name Property" in DAO Help.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::SetName, CDaoQueryDef::GetSQL, CDaoQueryDef::GetReturnsRecords, CDaoQueryDef::GetODBCTimeout


CDaoQueryDef::GetODBCTimeout

short GetODBCTimeout( );
throw( CDaoException, CMemoryException );

Return Value

The number of seconds before a query times out.

Remarks

Call this member function to retrieve the current time limit before a query to an ODBC data source times out. For information about this time limit, see the topic "ODBCTimeout Property" in DAO Help.

Tip The preferred way to work with ODBC tables is to attach them to a Microsoft Jet (.MDB) database. For more information, see the topic "Accessing External Databases with DAO" in DAO Help and the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::SetODBCTimeout, CDaoQueryDef::GetName, CDaoQueryDef::GetSQL, CDaoQueryDef::GetReturnsRecords


CDaoQueryDef::GetParameterCount

short GetParameterCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of parameters defined in the query.

Remarks

Call this member function to retrieve the number of parameters in the saved query. GetParameterCount is useful for looping through all parameters in the querydef. For that purpose, use GetParameterCount in conjunction with GetParameterInfo.

For information about parameterizing queries, see the article DAO Queries: Filtering and Parameterizing Queries in Visual C++ Programmer's Guide. For related information, see the topics "Parameter Object", "Parameters Collection", and "PARAMETERS Declaration (SQL)" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetParamValue, CDaoQueryDef::SetParamValue


CDaoQueryDef::GetParameterInfo

void GetParameterInfo( int nIndex, CDaoParameterInfo& paraminfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetParameterInfo( LPCTSTR lpszName, CDaoParameterInfo& paraminfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The zero-based index of the desired parameter in the querydef’s Parameters collection, for lookup by index.

paraminfo

A reference to a CDaoParameterInfo object that returns the information requested.

dwInfoOptions

Options that specify which information about the parameter to retrieve. The available option is listed here along with what it causes the function to return:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Type

lpszName

A string containing the name of the desired parameter, for lookup by name. You can use a CString.

Remarks

Call this member function to obtain information about a parameter defined in the querydef. For a description of the information returned in paraminfo, see the CDaoParameterInfo structure. This structure has members that correspond to the descriptive information under dwInfoOptions above.

For more information about obtaining parameter information, see the article DAO Collections: Obtaining Information About DAO Objects. For more information about parameterizing queries, see the article DAO Queries: Filtering and Parameterizing Queries. Both articles are in Visual C++ Programmer's Guide. For related information, see the topic "PARAMETERS Declaration (SQL)" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetParameterCount


CDaoQueryDef::GetParamValue

COleVariant GetParamValue( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

COleVariant GetParamValue( int nIndex );
throw( CDaoException, CMemoryException );

Return Value

An object of class COleVariant that contains the parameter’s value.

Parameters

lpszName

The name of the parameter whose value you want, for lookup by name.

nIndex

The zero-based index of the parameter in the querydef’s Parameters collection, for lookup by index. You can obtain this value with calls to GetParameterCount and GetParameterInfo.

Remarks

Call this member function to retrieve the current value of the specified parameter stored in the querydef’s Parameters collection. You can access the parameter either by name or by its ordinal position in the collection.

For examples and more information about parameterizing queries, see the article DAO Queries: Filtering and Parameterizing Queries in Visual C++ Programmer's Guide. For related information, see the topic "PARAMETERS Declaration (SQL)" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::SetParamValue


CDaoQueryDef::GetRecordsAffected

long GetRecordsAffected( );
throw( CDaoException, CMemoryException );

Return Value

The number of records affected.

Remarks

Call this member function to determine how many records were affected by the last call of Execute. The count returned will not reflect changes in related tables when cascade updates or deletes are in effect.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For related information see the topic "RecordsAffected Property" in DAO Help.


CDaoQueryDef::GetReturnsRecords

BOOL GetReturnsRecords( );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the querydef is based on a query that returns records; otherwise 0.

Remarks

Call this member function to determine whether the querydef is based on a query that returns records. This member function is only used for SQL pass-through queries. For more information about SQL queries, see the Execute member function. For more information about working with SQL pass-through queries, see the SetReturnsRecords member function.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For related information, see the topic "ReturnsRecords Property" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetName, CDaoQueryDef::GetSQL, CDaoQueryDef::GetODBCTimeout


CDaoQueryDef::GetSQL

CString GetSQL( );
throw( CDaoException, CMemoryException );

Return Value

The SQL statement that defines the query on which the querydef is based.

Remarks

Call this member function to retrieve the SQL statement that defines the query on which the querydef is based. You will then probably parse the string for keywords, table names, and so on.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For related information, see the topics "SQL Property", "Comparison of Microsoft Jet Database Engine SQL and ANSI SQL", and "Querying a Database with SQL in Code" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::SetSQL, CDaoQueryDef::GetName, CDaoQueryDef::GetReturnsRecords, CDaoQueryDef::GetODBCTimeout


CDaoQueryDef::GetType

short GetType( );
throw( CDaoException, CMemoryException );

Return Value

The type of the query defined by the querydef. For values, see Remarks.

Remarks

Call this member function to determine the query type of the querydef. The query type is set by what you specify in the querydef’s SQL string when you create the querydef or call an existing querydef’s SetSQL member function. The query type returned by this function can be one of the following values:

  • dbQSelect Select

  • dbQAction Action

  • dbQCrosstab Crosstab

  • dbQDelete Delete

  • dbQUpdate Update

  • dbQAppend Append

  • dbQMakeTable Make-table

  • dbQDDL Data-definition

  • dbQSQLPassThrough Pass-through

  • dbQSetOperation Union

  • dbQSPTBulk Used with dbQSQLPassThrough to specify a query that does not return records.

Note To create an SQL pass-through query, don’t set the dbSQLPassThrough constant. This is set automatically by the Microsoft Jet database engine when you create a querydef object and set the connect string.

For information about SQL strings, see GetSQL. For information about query types, see Execute.


CDaoQueryDef::IsOpen

BOOL IsOpen( ) const;

Return Value

Nonzero if the CDaoQueryDef object is currently open; otherwise 0.

Remarks

Call this member function to determine whether the CDaoQueryDef object is currently open. A querydef must be in an open state before you use it to call Execute or to create a CDaoRecordset object. To put a querydef into an open state call either Create (for a new querydef) or Open (for an existing querydef).

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.


CDaoQueryDef::Open

virtual void Open( LPCTSTR lpszName = NULL );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A string that contains the name of the saved querydef to open. You can use a CString.

Remarks

Call this member function to open a querydef previously saved in the database’s QueryDefs collection. Once the querydef is open, you can call its Execute member function or use the querydef to create a CDaoRecordset object.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::IsOpen, CDaoQueryDef::Close, CDaoQueryDef::SetName, CDaoQueryDef::Create


CDaoQueryDef::SetConnect

void SetConnect( LPCTSTR lpszConnect );
throw( CDaoException, CMemoryException );

Parameters

lpszConnect

A string that contains a connect string for the associated CDaoDatabase object.

Remarks

Call this member function to set the querydef object’s connect string. The connect string is used to pass additional information to ODBC and certain ISAM drivers as needed. It is not used for Microsoft Jet (.MDB) databases.

Tip The preferred way to work with ODBC tables is to attach them to an .MDB database. For more information, see the topic "Accessing External Databases with DAO" in DAO Help and the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

Before executing a querydef that represents an SQL pass-through query to an ODBC data source, set the connect string with SetConnect and call SetReturnsRecords to specify whether the query returns records.

For more information about the connect string’s structure and examples of connect string components, see the topic "Connect Property" in DAO Help. For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.


CDaoQueryDef::SetName

void SetName( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A string that contains the new name for a nontemporary query in the associated CDaoDatabase object.

Remarks

Call this member function if you want to change the name of a querydef that is not temporary. Querydef names are unique, user-defined names. You can call SetName before the querydef object is appended to the QueryDefs collection.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For more information about the querydef name, see the topic "Name Property" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetName, CDaoQueryDef::SetSQL, CDaoQueryDef::SetConnect, CDaoQueryDef::SetODBCTimeout, CDaoQueryDef::SetReturnsRecords


CDaoQueryDef::SetODBCTimeout

void SetODBCTimeout( short nODBCTimeout );
throw( CDaoException, CMemoryException );

Parameters

nODBCTimeout

The number of seconds before a query times out.

Remarks

Call this member function to set the time limit before a query to an ODBC data source times out.

Tip The preferred way to work with ODBC tables is to attach them to a Microsoft Jet (.MDB) database. For more information, see the topic "Accessing External Databases with DAO" in DAO Help and the article DAO External: Working with External Data Sources in Visual C++ Programmer's Guide.

This member function lets you override the default number of seconds before subsequent operations on the connected data source “time out.” An operation might time out due to network access problems, excessive query processing time, and so on. Call SetODBCTimeout prior to executing a query with this querydef if you want to change the query timeout value. (As ODBC reuses connections, the timeout value is the same for all clients on the same connection.)

The default value for query timeouts is 60 seconds.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For related information, see the topic "ODBCTimeout Property" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetODBCTimeout, CDaoQueryDef::SetName, CDaoQueryDef::SetSQL, CDaoQueryDef::SetConnect, CDaoQueryDef::SetReturnsRecords


CDaoQueryDef::SetParamValue

void SetParamValue( LPCTSTR lpszName, const COleVariant& varValue );
throw( CDaoException, CMemoryException );

void SetParamValue( int nOrdinal, const COleVariant& varValue );
throw( CDaoException, CMemoryException );

Parameters

lpszName

The name of the parameter whose value you want to set.

varValue

The value to set; see Remarks.

nOrdinal

The ordinal position of the parameter in the querydef’s Parameters collection. You can obtain this value with calls to GetParameterCount and GetParameterInfo.

Remarks

Call this member function to set the value of a parameter in the querydef at run time. The parameter must already have been established as part of the querydef’s SQL string. You can access the parameter either by name or by its ordinal position in the collection.

Specify the value to set as a COleVariant object. For information about setting the desired value and type in your COleVariant object, see class COleVariant.

For examples and more information about parameterizing queries, see the article DAO Queries: Filtering and Parameterizing Queries in Visual C++ Programmer's Guide. For related information, see the topic "PARAMETERS Declaration (SQL)" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetParamValue


CDaoQueryDef::SetReturnsRecords

void SetReturnsRecords( BOOL bReturnsRecords );
throw( CDaoException, CMemoryException );

Parameters

bReturnsRecords

Pass TRUE if the query on an external database returns records; otherwise, FALSE.

Remarks

Call this member function as part of the process of setting up an SQL pass-through query to an external database. In such a case, you must create the querydef and set its properties using other CDaoQueryDef member functions. For a description of external databases, see SetConnect.

For information about querydefs, see the article DAO Querydef. For information about external data sources, see the article DAO External: Working with External Data Sources. Both articles are in Visual C++ Programmer's Guide. For related information, see the topic "ReturnsRecords Property" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetReturnsRecords, CDaoQueryDef::SetName, CDaoQueryDef::SetSQL, CDaoQueryDef::SetConnect, CDaoQueryDef::SetODBCTimeout


CDaoQueryDef::SetSQL

void SetSQL( LPCTSTR lpszSQL );
throw( CDaoException, CMemoryException );

Parameters

lpszSQL

A string containing a complete SQL statement, suitable for execution. The syntax of this string depends on the DBMS that your query targets. For a discussion of syntax used in the Microsoft Jet database engine, see the topic "Building SQL Statements in Code" in DAO Help.

Remarks

Call this member function to set the SQL statement that the querydef executes. A typical use of SetSQL is setting up a querydef object for use in an SQL pass-through query. (For the syntax of SQL pass-through queries on your target DBMS, see the documentation for your DBMS.)

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide. For more information about SQL, see the topics "SQL Property", "Microsoft Jet Database Engine SQL Data Types", and "Querying a Database with SQL in Code" in DAO Help.

CDaoQueryDef Overview | Class Members | Hierarchy Chart

See Also CDaoQueryDef::GetSQL, CDaoQueryDef::SetName, CDaoQueryDef::SetConnect, CDaoQueryDef::SetODBCTimeout, CDaoQueryDef::SetReturnsRecords


CDaoQueryDef::m_pDatabase

Remarks

Contains a pointer to the CDaoDatabase object associated with the querydef object. Use this pointer if you need to access the database directly — for example, to obtain pointers to other querydef or recordset objects in the database’s collections.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.


CDaoQueryDef::m_pDAOQueryDef

Remarks

Contains a pointer to the OLE interface for the underlying DAO querydef object. This pointer is provided for completeness and consistency with the other classes. However, because MFC rather fully encapsulates DAO querydefs, you are unlikely to need it. If you do use it, do so cautiously — in particular, do not change the value of the pointer unless you know what you are doing.

For information about querydefs, see the article DAO Querydef in Visual C++ Programmer's Guide.


CDaoRecordset

A CDaoRecordset object represents a set of records selected from a data source. Known as “recordsets,” CDaoRecordset objects are available in the following three forms:

  • Table-type recordsets represent a base table that you can use to examine, add, change, or delete records from a single database table.

  • Dynaset-type recordsets are the result of a query that can have updatable records. These recordsets are a set of records that you can use to examine, add, change, or delete records from an underlying database table or tables. Dynaset-type recordsets can contain fields from one or more tables in a database.

  • Snapshot-type recordsets are a static copy of a set of records that you can use to find data or generate reports. These recordsets can contain fields from one or more tables in a database but cannot be updated.

Each form of recordset represents a set of records fixed at the time the recordset is opened. When you scroll to a record in a table-type recordset or a dynaset-type recordset, it reflects changes made to the record after the recordset is opened, either by other users or by other recordsets in your application. (A snapshot-type recordset cannot be updated.) You can use CDaoRecordset directly or derive an application-specific recordset class from CDaoRecordset. You can then:

  • Scroll through the records.

  • Set an index and quickly look for records using Seek (table-type recordsets only).

  • Find records based on a string comparison: "<", "<=", "=", ">=", or ">" (dynaset-type and snapshot-type recordsets).

  • Update the records and specify a locking mode (except snapshot-type recordsets).

  • Filter the recordset to constrain which records it selects from those available on the data source.

  • Sort the recordset.

  • Parameterize the recordset to customize its selection with information not known until run time.

Class CDaoRecordset supplies an interface similar to that of class CRecordset. The main difference is that class CDaoRecordset accesses data through a Data Access Object (DAO) based on OLE. Class CRecordset accesses the DBMS through Open Database Connectivity (ODBC) and an ODBC driver for that DBMS.

Note The DAO database classes are distinct from the MFC database classes based on Open Database Connectivity (ODBC). All DAO database class names have the “CDao” prefix. You can still access ODBC data sources with the DAO classes; the DAO classes generally offer superior capabilities because they are specific to the Microsoft Jet database engine.

You can either use CDaoRecordset directly or derive a class from CDaoRecordset. To use a recordset class in either case, open a database and construct a recordset object, passing the constructor a pointer to your CDaoDatabase object. You can also construct a CDaoRecordset object and let MFC create a temporary CDaoDatabase object for you. Then call the recordset’s Open member function, specifying whether the object is a table-type recordset, a dynaset-type recordset, or a snapshot-type recordset. Calling Open selects data from the database and retrieves the first record.

Use the object’s member functions and data members to scroll through the records and operate on them. The operations available depend on whether the object is a table-type recordset, a dynaset-type recordset, or a snapshot-type recordset, and whether it is updatable or read-only — this depends on the capability of the database or Open Database Connectivity (ODBC) data source. To refresh records that may have been changed or added since the Open call, call the object’s Requery member function. Call the object’s Close member function and destroy the object when you finish with it.

CDaoRecordset uses DAO record field exchange (DFX) to support reading and updating of record fields through type-safe C++ members of your CDaoRecordset or CDaoRecordset-derived class. You can also implement dynamic binding of columns in a database without using the DFX mechanism using GetFieldValue and SetFieldValue.

For more information about recordsets, see the article DAO: Recordset Architecture in Visual C++ Programmer's Guide. For related information, see the topic "Recordset Object" in DAO Help.

#include <afxdao.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample DAOVIEW | MFC Sample DBVLIST

See Also CDaoTableDef, CDaoWorkspace, CDaoDatabase, CDaoQueryDef


CDaoRecordset Class Members

Data Members
Construction
Attributes
Recordset Update Operations
Recordset Navigation Operations
Other Recordset Operations
Overridables

Data Members

m_bCheckCacheForDirtyFields | Contains a flag indicating whether fields are automatically marked as changed.
m_pDAORecordset | A pointer to the DAO interface underlying the recordset object.
m_nFields | Contains the number of field data members in the recordset class and the number of columns selected by the recordset from the data source.
m_nParams | Contains the number of parameter data members in the recordset class — the number of parameters passed with the recordset's query
m_pDatabase | Source database for this result set. Contains a pointer to a CDaoDatabase object.
m_strFilter | Contains a string used to construct an SQL WHERE statement.
m_strSort | Contains a string used to construct an SQL ORDER BY statement.

Construction

CDaoRecordset | Constructs a CDaoRecordset object.
Close | Closes the recordset.
Open | Creates a new recordset from a table, dynaset, or snapshot.

Attributes

CanAppend | Returns nonzero if new records can be added to the recordset via the AddNew member function.
CanBookmark | Returns nonzero if the recordset supports bookmarks.
CanRestart | Returns nonzero if Requery can be called to run the recordset’s query again.
CanScroll | Returns nonzero if you can scroll through the records.
CanTransact | Returns nonzero if the data source supports transactions.
CanUpdate | Returns nonzero if the recordset can be updated (you can add, update, or delete records).
GetCurrentIndex | Returns a CString containing the name of the index most recently used on an indexed, table-type CDaoRecordset.
GetDateCreated | Returns the date and time the base table underlying a CDaoRecordset object was created
GetDateLastUpdated | Returns the date and time of the most recent change made to the design of a base table underlying a CDaoRecordset object.
GetEditMode | Returns a value that indicates the state of editing for the current record.
GetLastModifiedBookmark | Used to determine the most recently added or updated record.
GetName | Returns a CString containing the name of the recordset.
GetParamValue | Retrieves the current value of the specified parameter stored in the underlying DAOParameter object.
GetRecordCount | Returns the number of records accessed in a recordset object.
GetSQL | Gets the SQL string used to select records for the recordset.
GetType | Called to determine the type of a recordset: table-type, dynaset-type, or snapshot-type.
GetValidationRule | Returns a CString containing the value that validates data as it is entered into a field.
GetValidationText | Retrieves the text that is displayed when a validation rule is not satisfied.
IsBOF | Returns nonzero if the recordset has been positioned before the first record. There is no current record.
IsDeleted | Returns nonzero if the recordset is positioned on a deleted record.
IsEOF | Returns nonzero if the recordset has been positioned after the last record. There is no current record.
IsFieldDirty | Returns nonzero if the specified field in the current record has been changed.
IsFieldNull | Returns nonzero if the specified field in the current record is Null (having no value).
IsFieldNullable | Returns nonzero if the specified field in the current record can be set to Null (having no value).
IsOpen | Returns nonzero if Open has been called previously.
SetCurrentIndex | Called to set an index on a table-type recordset.
SetParamValue | Sets the current value of the specified parameter stored in the underlying DAOParameter object
SetParamValueNull | Sets the current value of the specified parameter to Null (having no value).

Recordset Update Operations

AddNew | Prepares for adding a new record. Call Update to complete the addition.
CancelUpdate | Cancels any pending updates due to an Edit or AddNew operation.
Delete | Deletes the current record from the recordset. You must explicitly scroll to another record after the deletion.
Edit | Prepares for changes to the current record. Call Update to complete the edit.
Update | Completes an AddNew or Edit operation by saving the new or edited data on the data source.

Recordset Navigation Operations

Find | Locates the first, next, previous, or last location of a particular string in a dynaset-type recordset that satisfies the specified criteria and makes that record the current record.
FindFirst | Locates the first record in a dynaset-type or snapshot-type recordset that satisfies the specified criteria and makes that record the current record.
FindLast | Locates the last record in a dynaset-type or snapshot-type recordset that satisfies the specified criteria and makes that record the current record.
FindNext | Locates the next record in a dynaset-type or snapshot-type recordset that satisfies the specified criteria and makes that record the current record.
FindPrev | Locates the previous record in a dynaset-type or snapshot-type recordset that satisfies the specified criteria and makes that record the current record.
GetAbsolutePosition | Returns the record number of a recordset object’s current record.
GetBookmark | Returns a value that represents the bookmark on a record.
GetPercentPosition | Returns the position of the current record as a percentage of the total number of records.
Move | Positions the recordset to a specified number of records from the current record in either direction.
MoveFirst | Positions the current record on the first record in the recordset.
MoveLast | Positions the current record on the last record in the recordset.
MoveNext | Positions the current record on the next record in the recordset .
MovePrev | Positions the current record on the previous record in the recordset.
Seek | Locates the record in an indexed table-type recordset object that satisfies the specified criteria for the current index and makes that record the current record.
SetAbsolutePosition | Sets the record number of a recordset object’s current record.
SetBookmark | Positions the recordset on a record containing the specified bookmark.
SetPercentPosition | Sets the position of the current record to a location corresponding to a percentage of the total number of records in a recordset.

Other Recordset Operations

FillCache | Fills all or a part of a local cache for a recordset object that contains data from an ODBC data source.
GetCacheSize | Returns a value that specifies the number of records in a dynaset-type recordset containing data to be locally cached from an ODBC data source.
GetCacheStart | Returns a value that specifies the bookmark of the first record in the recordset to be cached.
GetFieldCount | Returns a value that represents the number of fields in a recordset.
GetFieldInfo | Returns specific kinds of information about the fields in the recordset.
GetFieldValue | Returns the value of a field in a recordset.
GetIndexCount | Retrieves the number of indexes in a table underlying a recordset.
GetIndexInfo | Returns various kinds of information about an index.
GetLockingMode | Returns a value that indicates the type of locking that is in effect during editing.
Requery | Runs the recordset’s query again to refresh the selected records.
SetCacheSize | Sets a value that specifies the number of records in a dynaset-type recordset containing data to be locally cached from an ODBC data source.
SetCacheStart | Sets a value that specifies the bookmark of the first record in the recordset to be cached.
SetFieldDirty | Marks the specified field in the current record as changed.
SetFieldNull | Sets the value of the specified field in the current record to Null (having no value).
SetFieldValue | Sets the value of a field in a recordset.
SetFieldValueNull | Sets the value of a field in a recordset to Null. (having no value).
SetLockingMode | Sets a value that indicates the type of locking to put into effect during editing.

Overridables

DoFieldExchange | Called to exchange data (in both directions) between the field data members of the recordset and the corresponding record on the data source. Implements DAO record field exchange (DFX).
GetDefaultDBName | Returns the name of the default data source.
GetDefaultSQL | Called to get the default SQL string to execute.


CDaoRecordset::AddNew

virtual void AddNew( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to add a new record to a table-type or dynaset-type recordset. The record’s fields are initially Null. (In database terminology, Null means “having no value” and is not the same as NULL in C++.) To complete the operation, you must call the Update member function. Update saves your changes to the data source.

Caution If you edit a record and then scroll to another record without calling Update, your changes are lost without warning.

If you add a record to a dynaset-type recordset by calling AddNew, the record is visible in the recordset and included in the underlying table where it becomes visible to any new CDaoRecordset objects.

The position of the new record depends on the type of recordset:

  • In a dynaset-type recordset, where the new record is inserted is not guaranteed. This behavior changed with Microsoft Jet 3.0 for reasons of performance and concurrency. If your goal is to make the newly added record the current record, get the bookmark of the last modified record and move to that bookmark:
    rs.SetBookmark( rs.GetLastModifiedBookmark( ) );
  • In a table-type recordset for which an index has been specified, records are returned in their proper place in the sort order. If no index has been specified, new records are returned at the end of the recordset.

The record that was current before you used AddNew remains current. If you want to make the new record current and the recordset supports bookmarks, call SetBookmark to the bookmark identified by the LastModified property setting of the underlying DAO recordset object. Doing so is useful for determining the value for counter (auto-increment) fields in an added record. For more information, see GetLastModifiedBookmark.

If the database supports transactions, you can make your AddNew call part of a transaction. For more information about transactions, see class CDaoWorkspace. Note that you should call CDaoWorkspace::BeginTrans before calling AddNew.

It is illegal to call AddNew for a recordset whose Open member function has not been called. A CDaoException is thrown if you call AddNew for a recordset that cannot be appended. You can determine whether the recordset is updatable by calling CanAppend.

The framework marks changed field data members to ensure they will be written to the record on the data source by the DAO record field exchange (DFX) mechanism. Changing the value of a field generally sets the field dirty automatically, so you will seldom need to call SetFieldDirty yourself, but you might sometimes want to ensure that columns will be explicitly updated or inserted regardless of what value is in the field data member. The DFX mechanism also employs the use of PSEUDO NULL. For more information, see CDaoFieldExchange::m_nOperation.

If the double-buffering mechanism is not being used, then changing the value of the field does not automatically set the field as dirty. In this case, it will be necessary to explicity set the field dirty. The flag contained in m_bCheckCacheForDirtyFields controls this automatic field checking.

Note If records are double-buffered (that is, automatic field checking is enabled), calling CancelUpdate will restore the member variables to the values they had before AddNew or Edit was called.

For more information about updating records, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topics "AddNew Method", "CancelUpdate Method", "LastModified Property", and "EditMode Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::CanUpdate, CDaoRecordset::CancelUpdate, CDaoRecordset::Delete, CDaoRecordset::Edit, CDaoRecordset::Update, CDaoRecordset::CanTransact


CDaoRecordset::CanAppend

BOOL CanAppend( ) const;

Return Value

Nonzero if the recordset allows adding new records; otherwise 0. CanAppend will return 0 if you opened the recordset as read-only.

Remarks

Call this member function to determine whether the previously opened recordset allows you to add new records by calling the AddNew member function.

For more information about updating records, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topic "Append Method" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::CanBookmark, CDaoRecordset::CanRestart, CDaoRecordset::CanScroll, CDaoRecordset::CanTransact, CDaoRecordset::CanUpdate


CDaoRecordset::CanBookmark

BOOL CanBookmark( ) const;
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the recordset supports bookmarks, otherwise 0.

Remarks

Call this member function to determine whether the previously opened recordset allows you to individually mark records using bookmarks. If you are using recordsets based entirely on Microsoft Jet database engine tables, bookmarks can be used except on snapshot-type recordsets flagged as forward-only scrolling recordsets. Other database products (external ODBC data sources) may not support bookmarks.

For more information about recordset navigation, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "Bookmarkable Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::CanAppend, CDaoRecordset::CanRestart, CDaoRecordset::CanScroll, CDaoRecordset::CanTransact, CDaoRecordset::CanUpdate


CDaoRecordset::CancelUpdate

virtual void CancelUpdate( );
throw( CDaoException, CMemoryException );

Remarks

The CancelUpdate member function cancels any pending updates due to an Edit or AddNew operation. For example, if an application calls the Edit or AddNew member function and has not called Update, CancelUpdate cancels any changes made after Edit or AddNew was called.

Note If records are double-buffered (that is, automatic field checking is enabled), calling CancelUpdate will restore the member variables to the values they had before AddNew or Edit was called.

If there is no Edit or AddNew operation pending, CancelUpdate causes MFC to throw an exception. Call the GetEditMode member function to determine if there is a pending operation that can be canceled.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topic "CancelUpdate Method" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::AddNew, CDaoRecordset::Delete, CDaoRecordset::Edit, CDaoRecordset::Update, CDaoRecordset::CanTransact


CDaoRecordset::CanRestart

BOOL CanRestart( );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if Requery can be called to run the recordset’s query again, otherwise 0.

Remarks

Call this member function to determine whether the recordset allows restarting its query (to refresh its records) by calling the Requery member function. Table-type recordsets do not support Requery.

If Requery is not supported, call Close then Open to refresh the data. You can call Requery to update a recordset object’s underlying parameter query after the parameter values have been changed.

For more information about working with DAO objects, see the article DAO: Creating, Opening, and Closing DAO Objects in Visual C++ Programmer's Guide. For related information, see the topic "Restartable Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::CanAppend, CDaoRecordset::CanBookmark, CDaoRecordset::CanScroll, CDaoRecordset::CanTransact, CDaoRecordset::CanUpdate


CDaoRecordset::CanScroll

BOOL CanScroll( ) const;

Return Value

Nonzero if you can scroll through the records, otherwise 0.

Remarks

Call this member function to determine whether the recordset allows scrolling. If you call Open with dbForwardOnly, the recordset can only scroll forward.

For more information about navigating through recordsets, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "Positioning the Current Record Pointer with DAO" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::CanAppend, CDaoRecordset::CanBookmark, CDaoRecordset::CanRestart, CDaoRecordset::CanTransact, CDaoRecordset::CanUpdate, CDaoRecordset::Open


CDaoRecordset::CanTransact

BOOL CanTransact( ) const;
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the underlying data source supports transactions, otherwise 0.

Remarks

Call this member function to determine whether the recordset allows transactions.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topic "Transactions Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::AddNew, CDaoRecordset::CanAppend, CDaoRecordset::CancelUpdate, CDaoRecordset::CanScroll, CDaoRecordset::CanRestart, CDaoRecordset::CanUpdate, CDaoRecordset::Delete, CDaoRecordset::Edit, CDaoRecordset::Update


CDaoRecordset::CanUpdate

BOOL CanUpdate( ) const;
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the recordset can be updated (add, update, and delete records), otherwise 0.

Remarks

Call this member function to determine whether the recordset can be updated. A recordset might be read-only if the underlying data source is read-only or if you specified dbReadOnly for nOptions when you called Open for the recordset.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topics "AddNew Method", "Edit Method", "Delete Method", "Update Method", and "Updatable Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::CanAppend, CDaoRecordset::CanBookmark, CDaoRecordset::CanScroll, CDaoRecordset::CanRestart, CDaoRecordset::CanTransact


CDaoRecordset::CDaoRecordset

CDaoRecordset( CDaoDatabase* pDatabase = NULL );

Parameters

pDatabase

Contains a pointer to a CDaoDatabase object or the value NULL. If not NULL and the CDaoDatabase object’s Open member function has not been called to connect it to the data source, the recordset attempts to open it for you during its own Open call. If you pass NULL, a CDaoDatabase object is constructed and connected for you using the data source information you specified if you derived your recordset class from CDaoRecordset.

Remarks

Constructs a CDaoRecordset object. You can either use CDaoRecordset directly or derive an application-specific class from CDaoRecordset. You can use ClassWizard to derive your recordset classes.

Note If you derive a CDaoRecordset class, your derived class must supply its own constructor. In the constructor of your derived class, call the constructor CDaoRecordset::CDaoRecordset, passing the appropriate parameters along to it.

Pass NULL to your recordset constructor to have a CDaoDatabase object constructed and connected for you automatically. This is a useful shortcut that does not require you to construct and connect a CDaoDatabase object prior to constructing your recordset. If the CDaoDatabase object is not open, a CDaoWorkspace object will also be created for you that uses the default workspace. For more information, see CDaoDatabase::CDaoDatabase.

For more information about constructing recordsets, see the article DAO: Creating, Opening, and Closing DAO Objects in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetDefaultDBName, CDaoRecordset::GetDefaultSQL, CDaoRecordset::GetDateCreated, CDaoRecordset::GetDateLastUpdated


CDaoRecordset::Close

virtual void Close( );
throw( CDaoException );

Remarks

Closing a CDaoRecordset object removes it from the collection of open recordsets in the associated database. Because Close does not destroy the CDaoRecordset object, you can reuse the object by calling Open on the same data source or a different data source.

All pending AddNew or Edit statements are canceled, and all pending transactions are rolled back. If you want to preserve pending additions or edits, call Update before you call Close for each recordset.

You can call Open again after calling Close. This lets you reuse the recordset object. A better alternative is to call Requery, if possible.

For more information about working with recordsets, see the article DAO: Creating, Opening, and Closing DAO Objects in Visual C++ Programmer's Guide. For related information, see the topic "Close Method" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Open, CDaoRecordset::CDaoRecordset


CDaoRecordset::Delete

virtual void Delete( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to delete the current record in an open dynaset-type or table-type recordset object. After a successful deletion, the recordset’s field data members are set to a Null value, and you must explicitly call one of the recordset navigation member functions (Move, Seek, SetBookmark, and so on) in order to move off the deleted record. When you delete records from a recordset, there must be a current record in the recordset before you call Delete; otherwise, MFC throws an exception.

Delete removes the current record and makes it inaccessible. Although you cannot edit or use the deleted record, it remains current. Once you move to another record, however, you cannot make the deleted record current again.

Caution The recordset must be updatable and there must be a valid record current in the recordset when you call Delete. For example, if you delete a record but do not scroll to a new record before you call Delete again, Delete throws a CDaoException.

You can undelete a record if you use transactions and you call the CDaoWorkspace::Rollback member function. If the base table is the primary table in a cascade delete relationship, deleting the current record may also delete one or more records in a foreign table. For more information, see the definition "cascade delete" in DAO Help.

Unlike AddNew and Edit, a call to Delete is not followed by a call to Update.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topics "AddNew Method", "Edit Method", "Delete Method", "Update Method", and "Updatable Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::AddNew, CDaoRecordset::CancelUpdate, CDaoRecordset::Edit, CDaoRecordset::Update, CDaoRecordset::CanTransact


CDaoRecordset::DoFieldExchange

virtual void DoFieldExchange( CDaoFieldExchange* pFX );

Parameters

pFX

Contains a pointer to a CDaoFieldExchange object. The framework will already have set up this object to specify a context for the field exchange operation.

Remarks

The framework calls this member function to automatically exchange data between the field data members of your recordset object and the corresponding columns of the current record on the data source. It also binds your parameter data members, if any, to parameter placeholders in the SQL statement string for the recordset’s selection. The exchange of field data, called DAO record field exchange (DFX), works in both directions: from the recordset object’s field data members to the fields of the record on the data source, and from the record on the data source to the recordset object. If you are binding columns dynamically, you are not required to implement DoFieldExchange.

The only action you must normally take to implement DoFieldExchange for your derived recordset class is to create the class with ClassWizard and specify the names and data types of the field data members. You might also add code to what ClassWizard writes to specify parameter data members. If all fields are to be bound dynamically, this function will be inactive unless you specify parameter data members. For more information, see the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

When you declare your derived recordset class with ClassWizard, the wizard writes an override of DoFieldExchange for you, which resembles the following example:

void CCustSet::DoFieldExchange(CDaoFieldExchange* pFX)
{
   //{{AFX_FIELD_MAP(CCustSet)
   pFX->SetFieldType(CDaoFieldExchange::outputColumn);
   DFX_Text(pFX, "Name", m_strName);
   DFX_Short(pFX, "Age", m_wAge);
   //}}AFX_FIELD_MAP
}

For more information about record field exchange, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoException


CDaoRecordset::Edit

virtual void Edit( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to allow changes to the current record.

Once you call the Edit member function, changes made to the current record’s fields are copied to the copy buffer. After you make the desired changes to the record, call Update to save your changes. Edit saves the values of the recordset’s data members. If you call Edit, make changes, then call Edit again, the record’s values are restored to what they were before the first Edit call.

Caution If you edit a record and then perform any operation that moves to another record without first calling Update, your changes are lost without warning. In addition, if you close the recordset or the parent database, your edited record is discarded without warning.

In some cases, you may want to update a column by making it Null (containing no data). To do so, call SetFieldNull with a parameter of TRUE to mark the field Null; this also causes the column to be updated. If you want a field to be written to the data source even though its value has not changed, call SetFieldDirty with a parameter of TRUE. This works even if the field had the value Null.

The framework marks changed field data members to ensure they will be written to the record on the data source by the DAO record field exchange (DFX) mechanism. Changing the value of a field generally sets the field dirty automatically, so you will seldom need to call SetFieldDirty yourself, but you might sometimes want to ensure that columns will be explicitly updated or inserted regardless of what value is in the field data member. The DFX mechanism also employs the use of PSEUDO NULL. For more information, see CDaoFieldExchange::m_nOperation.

If the double-buffering mechanism is not being used, then changing the value of the field does not automatically set the field as dirty. In this case, it will be necessary to explicity set the field dirty. The flag contained in m_bCheckCacheForDirtyFields controls this automatic field checking.

When the recordset object is pessimistically locked in a multiuser environment, the record remains locked from the time Edit is used until the updating is complete. If the recordset is optimistically locked, the record is locked and compared with the pre-edited record just before it is updated in the database. If the record has changed since you called Edit, the Update operation fails and MFC throws an exception. You can change the locking mode with SetLockingMode.

Note Optimistic locking is always used on external database formats, such as ODBC and installable ISAM.

The current record remains current after you call Edit. To call Edit, there must be a current record. If there is no current record or if the recordset does not refer to an open table-type or dynaset-type recordset object, an exception occurs. Calling Edit causes a CDaoException to be thrown under the following conditions:

  • There is no current record.

  • The database or recordset is read-only.

  • No fields in the record are updatable.

  • The database or recordset was opened for exclusive use by another user.

  • Another user has locked the page containing your record.

If the data source supports transactions, you can make the Edit call part of a transaction. Note that you should call CDaoWorkspace::BeginTrans before calling Edit and after the recordset has been opened. Also note that calling CDaoWorkspace::CommitTrans is not a substitute for calling Update to complete the Edit operation. For more information about transactions, see class CDaoWorkspace.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topics "AddNew Method", "Edit Method", "Delete Method", "Update Method", and "Updatable Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::AddNew, CDaoRecordset::CancelUpdate, CDaoRecordset::CanTransact, CDaoRecordset::Delete, CDaoRecordset::Update


CDaoRecordset::FillCache

void FillCache( long* pSize = NULL, COleVariant* pBookmark = NULL );
throw( CDaoException, CMemoryException );

Parameters

pSize

Specifies the number of rows to fill in the cache. If you omit this parameter, the value is determined by the CacheSize property setting of the underlying DAO object.

pBookmark

A COleVariant specifying a bookmark. The cache is filled starting from the record indicated by this bookmark. If you omit this parameter, the cache is filled starting from the record indicated by the CacheStart property of the underlying DAO object.

Remarks

Call this member function to cache a specified number of records from the recordset. Caching improves the performance of an application that retrieves, or fetches, data from a remote server. A cache is space in local memory that holds the data most recently fetched from the server on the assumption that the data will probably be requested again while the application is running. When data is requested, the Microsoft Jet database engine checks the cache for the data first rather than fetching it from the server, which takes more time. Using data caching on non-ODBC data sources has no effect as the data is not saved in the cache.

Rather than waiting for the cache to be filled with records as they are fetched, you can explicitly fill the cache at any time by calling the FillCache member function. This is a faster way to fill the cache because FillCache fetches several records at once instead of one at a time. For example, while each screenful of records is being displayed, you can have your application call FillCache to fetch the next screenful of records.

Any ODBC database accessed with recordset objects can have a local cache. To create the cache, open a recordset object from the remote data source, and then call the SetCacheSize and SetCacheStart member functions of the recordset. If lSize and lBookmark create a range that is partly or wholly outside the range specified by SetCacheSize and SetCacheStart, the portion of the recordset outside this range is ignored and is not loaded into the cache. If FillCache requests more records than remain in the remote data source, only the remaining records are fetched, and no exception is thrown.

Records fetched from the cache do not reflect changes made concurrently to the source data by other users.

FillCache fetches only records not already cached. To force an update of all the cached data, call the SetCacheSize member function with an lSize parameter equal to 0, call SetCacheSize again with the lSize parameter equal to the size of the cache you originally requested, and then call FillCache.

For more information about caching records, see the article DAO External: Improving Performance with External Data Sources in Visual C++ Programmer's Guide. For related information, see the topic "FillCache Method" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetCacheSize, CDaoRecordset::GetCacheStart, CDaoRecordset::SetCacheSize, CDaoRecordset::SetCacheStart


CDaoRecordset::Find

virtual BOOL Find( long lFindType, LPCTSTR lpszFilter );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if matching records are found, otherwise 0.

Parameters

lFindType

A value indicating the type of Find operation desired. The possible values are:

  • AFX_DAO_NEXT Find the next location of a matching string.

  • AFX_DAO_PREV Find the previous location of a matching string.

  • AFX_DAO_FIRST Find the first location of a matching string.

  • AFX_DAO_LAST Find the last location of a matching string.

lpszFilter

A string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record. For example:

Find(AFX_DAO_FIRST, "colRecID = 7")
Find(AFX_DAO_NEXT, "customerName = 'Jones'")

Remarks

Call this member function to locate a particular string in a dynaset- or snapshot-type recordset using a comparison operator. You can find the first, next, previous, or last instance of the string. Find is a virtual function, so you can override it and add your own implementation. The FindFirst, FindLast, FindNext, and FindPrev member functions call the Find member function, so you can use Find to control the behavior of all Find operations.

To locate a record in a table-type recordset, call the Seek member function.

Tip The smaller the set of records you have, the more effective Find will be. In general, and especally with ODBC data, it is better to create a new query that retrieves just the records you want.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "FindFirst, FindLast, FindNext, FindPrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::FindFirst, CDaoRecordset::FindLast, CDaoRecordset::FindNext, CDaoRecordset::FindPrev


CDaoRecordset::FindFirst

BOOL FindFirst( LPCTSTR lpszFilter );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if matching records are found, otherwise 0.

Parameters

lpszFilter

A string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

Call this member function to find the first record that matches a specified condition. The FindFirst member function begins its search from the beginning of the recordset and searches to the end of the recordset.

If you want to include all the records in your search (not just those that meet a specific condition) use one of the Move operations to move from record to record. To locate a record in a table-type recordset, call the Seek member function.

If a record matching the criteria is not located, the current record pointer is undetermined, and FindFirst returns zero. If the recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.

Caution If you edit the current record, be sure to save the changes by calling the Update member function before you move to another record. If you move to another record without updating, your changes are lost without warning.

The Find member functions search from the location and in the direction specified in the following table:

Find operations | Begin | Search direction
FindFirst | Beginning of recordset | End of recordset
FindLast | End of recordset | Beginning of recordset
FindNext | Current record | End of recordset
FindPrevious | Current record | Beginning of recordset

Important When you call FindLast, the Microsoft Jet database engine fully populates your recordset before beginning the search, if this has not already been done. The first search may take longer than subsequent searches.

Using one of the Find operations is not the same as calling MoveFirst or MoveNext, however, which simply makes the first or next record current without specifying a condition. You can follow a Find operation with a Move operation.

Keep the following in mind when using the Find operations:

  • If Find returns nonzero, the current record is not defined. In this case, you must position the current record pointer back to a valid record.

  • You cannot use a Find operation with a forward-only scrolling snapshot-type recordset.

  • You should use the U.S. date format (month-day-year) when you search for fields containing dates, even if you are not using the U.S. version of the Microsoft Jet database engine; otherwise, matching records may not be found.

  • When working with ODBC databases and large dynasets, you may discover that using the the Find operations is slow, especially when working with large recordsets. You can improve performance by using SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or CDaoQuerydef objects that retrieve specific indexed records.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "FindFirst, FindLast, FindNext, FindPrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Find, CDaoRecordset::FindLast, CDaoRecordset::FindNext, CDaoRecordset::FindPrev


CDaoRecordset::FindLast

BOOL FindLast( LPCTSTR lpszFilter );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if matching records are found, otherwise 0.

Parameters

lpszFilter

A string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

Call this member function to find the last record that matches a specified condition. The FindLast member function begins its search at the end of the recordset and searches backward towards the begining of the recordset.

If you want to include all the records in your search (not just those that meet a specific condition) use one of the Move operations to move from record to record. To locate a record in a table-type recordset, call the Seek member function.

If a record matching the criteria is not located, the current record pointer is undetermined, and FindLast returns zero. If the recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence after the first occurrence, and so on.

Caution If you edit the current record, be sure you save the changes by calling the Update member function before you move to another record. If you move to another record without updating, your changes are lost without warning.

Using one of the Find operations is not the same as calling MoveFirst or MoveNext, however, which simply makes the first or next record current without specifying a condition. You can follow a Find operation with a Move operation.

Keep the following in mind when using the Find operations:

  • If Find returns nonzero, the current record is not defined. In this case, you must position the current record pointer back to a valid record.

  • You cannot use a Find operation with a forward-only scrolling snapshot-type recordset.

  • You should use the U.S. date format (month-day-year) when you search for fields containing dates, even if you are not using the U.S. version of the Microsoft Jet database engine; otherwise, matching records may not be found.

  • When working with ODBC databases and large dynasets, you may discover that using the the Find operations is slow, especially when working with large recordsets. You can improve performance by using SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or CDaoQuerydef objects that retrieve specific indexed records.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "FindFirst, FindLast, FindNext, FindPrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Find, CDaoRecordset::FindFirst, CDaoRecordset::FindNext, CDaoRecordset::FindPrev


CDaoRecordset::FindNext

BOOL FindNext( LPCTSTR lpszFilter );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if matching records are found, otherwise 0.

Parameters

lpszFilter

A string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

Call this member function to find the next record that matches a specified condition. The FindNext member function begins its search at the current record and searches to the end of the recordset.

If you want to include all the records in your search (not just those that meet a specific condition) use one of the Move operations to move from record to record. To locate a record in a table-type recordset, call the Seek member function.

If a record matching the criteria is not located, the current record pointer is undetermined, and FindNext returns zero. If the recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.

Caution If you edit the current record, be sure you save the changes by calling the Update member function before you move to another record. If you move to another record without updating, your changes are lost without warning.

Using one of the Find operations is not the same as calling MoveFirst or MoveNext, however, which simply makes the first or next record current without specifying a condition. You can follow a Find operation with a Move operation.

Keep the following in mind when using the Find operations:

  • If Find returns nonzero, the current record is not defined. In this case, you must position the current record pointer back to a valid record.

  • You cannot use a Find operation with a forward-only scrolling snapshot-type recordset.

  • You should use the U.S. date format (month-day-year) when you search for fields containing dates, even if you are not using the U.S. version of the Microsoft Jet database engine; otherwise, matching records may not be found.

  • When working with ODBC databases and large dynasets, you may discover that using the the Find operations is slow, especially when working with large recordsets. You can improve performance by using SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or CDaoQuerydef objects that retrieve specific indexed records.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "FindFirst, FindLast, FindNext, FindPrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Find, CDaoRecordset::FindFirst, CDaoRecordset::FindLast, CDaoRecordset::FindPrev


CDaoRecordset::FindPrev

BOOL FindPrev( LPCTSTR lpszFilter );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if matching records are found, otherwise 0.

Parameters

lpszFilter

A string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

Call this member function to find the previous record that matches a specified condition. The FindPrev member function begins its search at the current record and searches backward towards the beginning of the recordset.

If you want to include all the records in your search (not just those that meet a specific condition) use one of the Move operations to move from record to record. To locate a record in a table-type recordset, call the Seek member function.

If a record matching the criteria is not located, the current record pointer is undetermined, and FindPrev returns zero. If the recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.

Caution If you edit the current record, be sure you save the changes by calling the Update member function before you move to another record. If you move to another record without updating, your changes are lost without warning.

Using one of the Find operations is not the same as calling MoveFirst or MoveNext, however, which simply makes the first or next record current without specifying a condition. You can follow a Find operation with a Move operation.

Keep the following in mind when using the Find operations:

  • If Find returns nonzero, the current record is not defined. In this case, you must position the current record pointer back to a valid record.

  • You cannot use a Find operation with a forward-only scrolling snapshot-type recordset.

  • You should use the U.S. date format (month-day-year) when you search for fields containing dates, even if you are not using the U.S. version of the Microsoft Jet database engine; otherwise, matching records may not be found.

  • When working with ODBC databases and large dynasets, you may discover that using the the Find operations is slow, especially when working with large recordsets. You can improve performance by using SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or CDaoQuerydef objects that retrieve specific indexed records.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "FindFirst, FindLast, FindNext, FindPrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Find, CDaoRecordset::FindFirst, CDaoRecordset::FindLast, CDaoRecordset::FindNext


CDaoRecordset::GetAbsolutePosition

long GetAbsolutePosition( );
throw( CDaoException, CMemoryException );

Return Value

An integer from 0 to the number of records in the recordset. Corresponds to the ordinal position of the current record in the recordset.

Remarks

Returns the record number of a recordset object’s current record. The AbsolutePosition property value of the underlying DAO object is zero-based; a setting of 0 refers to the first record in the recordset. You can determine the number of populated records in the recordset by calling GetRecordCount. Calling GetRecordCount may take some time because it must access all records to determine the count.

If there is no current record, as when there are no records in the recordset, – 1 is returned. If the current record is deleted, the AbsolutePosition property value is not defined, and MFC throws an exception if it is referenced. For dynaset-type recordsets, new records are added to the end of the sequence.

Note This property is not intended to be used as a surrogate record number. Bookmarks are still the recommended way of retaining and returning to a given position and are the only way to position the current record across all types of recordset objects. In particular, the position of a given record changes when record(s) preceding it are deleted. There is also no assurance that a given record will have the same absolute position if the recordset is re-created again because the order of individual records within a recordset is not guaranteed unless it is created with an SQL statement using an ORDER BY clause.

Note This member function is valid only for dynaset-type and snapshot-type recordsets.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "AbsolutePosition Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetAbsolutePosition


CDaoRecordset::GetBookmark

COleVariant GetBookmark( );
throw( CDaoException, CMemoryException );

Return Value

Returns a value representing the bookmark on the current record.

Remarks

Call this member function to obtain the bookmark value in a particular record. When a recordset object is created or opened, each of its records already has a unique bookmark if it supports them. Call CanBookmark to determine whether a recordset supports bookmarks.

You can save the bookmark for the current record by assigning the value of the bookmark to a COleVariant object. To quickly return to that record at any time after moving to a different record, call SetBookmark with a parameter corresponding to the value of that COleVariant object.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "Bookmark Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetBookmark, CDaoRecordset::CanBookmark


CDaoRecordset::GetCacheSize

long GetCacheSize( );
throw( CDaoException, CMemoryException );

Return Value

A value that specifies the number of records in a dynaset-type recordset containing data to be locally cached from an ODBC data source.

Remarks

Call this member function to obtain the number of records cached. Data caching improves the performance of an application that retrieves data from a remote server through dynaset-type recordset objects. A cache is a space in local memory that holds the data most recently retrieved from the server in the event that the data will be requested again while the application is running. When data is requested, the Microsoft Jet database engine checks the cache for the requested data first rather than retrieving it from the server, which takes more time. Data that does not come from an ODBC data source is not saved in the cache.

Any ODBC data source, such as an attached table, can have a local cache.

For more information about caching records, see the article DAO External: Improving Performance with External Data Sources in Visual C++ Programmer's Guide. For related information, see the topic "CacheSize, CacheStart Properties" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::FillCache, CDaoRecordset::GetCacheStart, CDaoRecordset::SetCacheSize, CDaoRecordset::SetCacheStart


CDaoRecordset::GetCacheStart

COleVariant GetCacheStart( );
throw( CDaoException, CMemoryException );

Return Value

A COleVariant that specifies the bookmark of the first record in the recordset to be cached.

Remarks

Call this member function to obtain the bookmark value of the first record in the recordset to be cached. The Microsoft Jet database engine requests records within the cache range from the cache, and it requests records outside the cache range from the server.

Note Records retrieved from the cache do not reflect changes made concurrently to the source data by other users.

For more information about caching records, see the article DAO External: Improving Performance with External Data Sources in Visual C++ Programmer's Guide. For related information, see the topic "CacheSize, CacheStart Properties" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::FillCache, CDaoRecordset::GetCacheSize, CDaoRecordset::SetCacheSize, CDaoRecordset::SetCacheStart


CDaoRecordset::GetCurrentIndex

CString GetCurrentIndex( );
throw( CDaoException, CMemoryException );

Return Value

A CString containing the name of the index currently in use with a table-type recordset. Returns an empty string if no index has been set.

Remarks

Call this member function to determine the index currently in use in an indexed table-type CDaoRecordset object. This index is the basis for ordering records in a table-type recordset, and is used by the Seek member function to locate records.

A CDaoRecordset object can have more than one index but can use only one index at a time (although a CDaoTableDef object may have several indexes defined on it).

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "Index Object" and the definition "current index" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetCurrentIndex


CDaoRecordset::GetDateCreated

COleDateTime GetDateCreated( );
throw( CDaoException, CMemoryException );

Return Value

A COleDateTime object containing the date and time the base table was created.

Remarks

Call this member function to retrieve the date and time a base table was created. Date and time settings are derived from the computer on which the base table was created.

For more information about creating recordsets, see the article DAO: Creating, Opening, and Closing DAO Objects in Visual C++ Programmer's Guide. For related information, see the topic "DateCreated, LastUpdated Properties" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetDateLastUpdated


CDaoRecordset::GetDateLastUpdated

COleDateTime GetDateLastUpdated( );
throw( CDaoException, CMemoryException );

Return Value

A COleDateTime object containing the date and time the base table structure (schema) was last updated.

Remarks

Call this member function to retrieve the date and time the schema was last updated. Date and time settings are derived from the computer on which the base table structure (schema) was last updated.

For more information about creating recordsets, see the article DAO: Creating, Opening, and Closing DAO Objects in Visual C++ Programmer's Guide. For related information, see the topic "DateCreated, LastUpdated Properties" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetDateCreated


CDaoRecordset::GetDefaultDBName

virtual CString GetDefaultDBName( );

Return Value

A CString that contains the path and name of the database from which this recordset is derived.

Remarks

Call this member function to determine the name of the database for this recordset. If a recordset is created without a pointer to a CDaoDatabase, then this path is used by the recordset to open the default database. By default, this function returns an empty string. When ClassWizard derives a new recordset from CDaoRecordset, it will create this function for you.

The following example illustrates the use of the double backslash (\\) in the string, as is required for the string to be interpreted correctly.

CString CMyRecordset::GetDefaultDBName(void)
{
   return _T("c:\\mydir\\datasrc.mdb");
}

For more information about connecting to databases, see the article DAO: Creating, Opening, and Closing DAO Objects in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetDefaultSQL, CDaoRecordset::GetName, CDaoRecordset::GetSQL, CDaoRecordset::GetType


CDaoRecordset::GetDefaultSQL

virtual CString GetDefaultSQL( );

Return Value

A CString that contains the default SQL statement.

Remarks

The framework calls this member function to get the default SQL statement on which the recordset is based. This might be a table name or an SQL SELECT statement.

You indirectly define the default SQL statement by declaring your recordset class with ClassWizard, and ClassWizard performs this task for you.

If you pass a null SQL string to Open, then this function is called to determine the table name or SQL for your recordset.

For more information about connecting to databases, see the article DAO: Creating, Opening, and Closing DAO Objects in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetDefaultDBName, CDaoRecordset::GetName, CDaoRecordset::GetSQL, CDaoRecordset::GetType


CDaoRecordset::GetEditMode

short GetEditMode( );
throw( CDaoException, CMemoryException );

Return Value

Returns a value that indicates the state of editing for the current record.

Remarks

Call this member function to determine the state of editing, which is one of the following values:

Value | Description
dbEditNone | No editing operation is in progress.
dbEditInProgress | Edit has been called.
dbEditAdd | AddNew has been called.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topic "EditMode Property" in DAO Help.


CDaoRecordset::GetFieldCount

short GetFieldCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of fields in the recordset.

Remarks

Call this member function to retrieve the number of fields (columns) defined in the recordset.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "Count Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetFieldInfo, CDaoRecordset::GetFieldValue, CDaoRecordset::GetIndexCount, CDaoRecordset::GetIndexInfo


CDaoRecordset::GetFieldInfo

void GetFieldInfo( int nIndex, CDaoFieldInfo& fieldinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetFieldInfo( LPCTSTR lpszName, CDaoFieldInfo& fieldinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The zero-based index of the predefined field in the recordset’s Fields collection, for lookup by index.

fieldinfo

A reference to a CDaoFieldInfo structure.

dwInfoOptions

Options that specify which information about the recordset to retrieve. The available options are listed here along with what they cause the function to return. For best performance, retrieve only the level of information you need:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Type, Size, Attributes

  • AFX_DAO_SECONDARY_INFO Primary information, plus: Ordinal Position, Required, Allow Zero Length, Collating Order, Foreign Name, Source Field, Source Table

  • AFX_DAO_ALL_INFO Primary and secondary information, plus: Default Value, Validation Rule, Validation Text

lpszName The name of the field.

Remarks

Call this member function to obtain information about the fields in a recordset. One version of the function lets you look up a field by index. The other version lets you look up a field by name.

For a description of the information returned, see the CDaoFieldInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. When you request information at one level, you get information for any prior levels as well.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "Attributes Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetFieldCount, CDaoRecordset::GetFieldValue, CDaoRecordset::GetIndexCount, CDaoRecordset::GetIndexInfo


CDaoRecordset::GetFieldValue

virtual void GetFieldValue( LPCTSTR lpszName, COleVariant& varValue );
throw( CDaoException, CMemoryException );

virtual void GetFieldValue( int nIndex, COleVariant& varValue );
throw( CDaoException, CMemoryException );

virtual COleVariant GetFieldValue( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

virtual COleVariant GetFieldValue( int nIndex );
throw( CDaoException, CMemoryException );

Return Value

The two versions of GetFieldValue that return a value return a COleVariant object that contains the value of a field.

Parameters

lpszName

A pointer to a string that contains the name of a field.

varValue

A reference to a COleVariant object that will store the value of a field.

nIndex

A zero-based index of the field in the recordset’s Fields collection, for lookup by index.

Remarks

Call this member function to retrieve data in a recordset. You can look up a field by name or by ordinal position.

Note It is more efficient to call one of the versions of this member function that takes a COleVariant object reference as a parameter, rather than calling a version that returns a COleVariant object.

Use GetFieldValue and SetFieldValue to dynamically bind fields at run time rather than statically binding columns using the DoFieldExchange mechanism.

GetFieldValue and the DoFieldExchange mechanism can be combined to improve performance. For example, use GetFieldValue to retrieve a value that you need only on demand, and assign that call to a “More Information” button in the interface.

For more information about binding fields dynamically, see the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide. For related information, see the topics "Field Object" and "Value Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetFieldValue


CDaoRecordset::GetIndexCount

short GetIndexCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of indexes in the table-type recordset.

Remarks

Call this member function to determine the number of indexes available on the table-type recordset. GetIndexCount is useful for looping through all indexes in the recordset. For that purpose, use GetIndexCount in conjunction with GetIndexInfo. If you call this member function on dynaset-type or snapshot-type recordsets, MFC throws an exception.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "Attributes Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetFieldCount, CDaoRecordset::GetFieldInfo, CDaoRecordset::GetIndexInfo


CDaoRecordset::GetIndexInfo

void GetIndexInfo( int nIndex, CDaoIndexInfo& indexinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetIndexInfo( LPCTSTR lpszName, CDaoIndexInfo& indexinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The zero-based index in the table’s Indexes collection, for lookup by numerical position.

indexinfo

A reference to a CDaoIndexInfo structure.

dwInfoOptions

Options that specify which information about the index to retrieve. The available options are listed here along with what they cause the function to return. For best performance, retrieve only the level of information you need:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Field Info, Fields

  • AFX_DAO_SECONDARY_INFO Primary information, plus: Primary, Unique, Clustered, IgnoreNulls, Required, Foreign

  • AFX_DAO_ALL_INFO Primary and secondary information, plus: Distinct Count

lpszName

A pointer to the name of the index object, for lookup by name.

Remarks

Call this member function to obtain various kinds of information about an index defined in the base table underlying a recordset. One version of the function lets you look up a index by its position in the collection. The other version lets you look up an index by name.

For a description of the information returned, see the CDaoIndexInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. When you request information at one level, you get information for any prior levels as well.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "Attributes Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetFieldCount, CDaoRecordset::GetFieldInfo, CDaoRecordset::GetIndexCount, CDaoRecordset::GetLastModifiedBookmark


CDaoRecordset::GetLastModifiedBookmark

COleVariant GetLastModifiedBookmark( );
throw( CDaoException, CMemoryException );

Return Value

A COleVariant containing a bookmark that indicates the most recently added or changed record.

Remarks

Call this member function to retrieve the bookmark of the most recently added or updated record. When a recordset object is created or opened, each of its records already has a unique bookmark if it supports them. Call GetBookmark to determine if the recordset supports bookmarks. If the recordset does not support bookmarks, a CDaoException is thrown.

When you add a record, it appears at the end of the recordset, and is not the current record. To make the new record current, call GetLastModifiedBookmark and then call SetBookmark to return to the newly added record.

For more information about navigating in recordsets, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "LastModified Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetBookmark, CDaoRecordset::SetBookmark


CDaoRecordset::GetLockingMode

BOOL GetLockingMode( );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the type of locking is pessimistic, otherwise 0 for optimistic record locking.

Remarks

Call this member function to determine the type of locking in effect for the recordset. When pessimistic locking is in effect, the data page containing the record you are editing is locked as soon as you call the Edit member function. The page is unlocked when you call the Update or Close member function or any of the Move or Find operations.

When optimistic locking is in effect, the data page containing the record is locked only while the record is being updated with the Update member function.

When working with ODBC data sources, the locking mode is always optimistic.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topics "LockEdits Property" and "Locking Behavior in Multiuser Applications" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetLockingMode


CDaoRecordset::GetName

CString GetName( );
throw( CDaoException, CMemoryException );

Return Value

A CString containing the name of the recordset.

Remarks

Call this member function to retrieve the name of the recordset. The name of the recordset must start with a letter and can contain a maximum of 40 characters. It can include numbers and underscore characters but can’t include punctuation or spaces.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "Name Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetDefaultDBName, CDaoRecordset::GetDefaultSQL, CDaoRecordset::GetSQL, CDaoRecordset::GetType


CDaoRecordset::GetParamValue

virtual COleVariant GetParamValue( int nIndex );
throw( CDaoException, CMemoryException );

virtual COleVariant GetParamValue( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Return Value

An object of class COleVariant that contains the parameter’s value.

Parameters

nIndex

The numerical position of the parameter in the underlying DAOParameter object.

lpszName

The name of the parameter whose value you want.

Remarks

Call this member function to retrieve the current value of the specified parameter stored in the underlying DAOParameter object. You can access the parameter either by name or by its numerical position in the collection.

For more information about parameters, see the article DAO Queries: Filtering and Parameterizing Queries in Visual C++ Programmer's Guide. For related information, see the topic "Parameter Object" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetParamValue, CDaoRecordset::m_nParams


CDaoRecordset::GetPercentPosition

float GetPercentPosition( );
throw( CDaoException, CMemoryException );

Return Value

A number between 0 and 100 that indicates the approximate location of the current record in the recordset object based on a percentage of the records in the recordset.

Remarks

When working with a dynaset-type or snapshot-type recordset, if you call GetPercentPosition before fully populating the recordset, the amount of movement is relative to the number of records accessed as indicated by calling GetRecordCount. You can move to the last record by calling MoveLast to complete the population of all recordsets, but this may take a significant amount of time.

You can call GetPercentPosition on all three types of recordset objects, including tables without indexes. However, you cannot call GetPercentPosition on forward-only scrolling snapshots, or on a recordset opened from a pass-through query against an external database. If there is no current record, or he current record has been deleted, a CDaoException is thrown.

For more information about navigating in recordsets, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "PercentPosition Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetPercentPosition


CDaoRecordset::GetRecordCount

long GetRecordCount( );
throw( CDaoException, CMemoryException );

Return Value

Returns the number of records accessed in a recordset object.

Remarks

Call this member function to find out how many records in a recordset have been accessed. GetRecordCount does not indicate how many records are contained in a dynaset-type or snapshot-type recordset until all records have been accessed. This member function call may take a significant amount of time to complete.

Once the last record has been accessed, the return value indicates the total number of undeleted records in the recordset. To force the last record to be accessed, call the MoveLast or FindLast member function for the recordset. You can also use a SQL Count to determine the approximate number of records your query will return.

As your application deletes records in a dynaset-type recordset, the return value of GetRecordCount decreases. However, records deleted by other users are not reflected by GetRecordCount until the current record is positioned to a deleted record. If you execute a transaction that affects the record count and subsequently roll back the transaction, GetRecordCount will not reflect the actual number of remaining records.

The value of GetRecordCount from a snapshot-type recordset is not affected by changes in the underlying tables.

The value of GetRecordCount from a table-type recordset reflects the approximate number of records in the table and is affected immediately as table records are added and deleted.

A recordset with no records returns a value of 0. When working with attached tables or ODBC databases, GetRecordCount always returns – 1. Calling the Requery member function on a recordset resets the value of GetRecordCount just as if the query were re-executed.

For more information about navigating in recordsets, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "RecordCount Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetFieldCount, CDaoRecordset::GetFieldInfo, CDaoRecordset::GetIndexCount, CDaoRecordset::GetIndexInfo


CDaoRecordset::GetSQL

CString GetSQL( ) const;

Return Value

A CString that contains the SQL statement.

Remarks

Call this member function to get the SQL statement that was used to select the recordset’s records when it was opened. This will generally be an SQL SELECT statement.

The string returned by GetSQL is typically different from any string you may have passed to the recordset in the lpszSQL parameter to the Open member function. This is because the recordset constructs a full SQL statement based on what you passed to Open, what you specified with ClassWizard, and what you may have specified in the m_strFilter and m_strSort data members.

Important Call this member function only after calling Open.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "SQL Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetDefaultSQL, CDaoRecordset::GetDefaultDBName, CDaoRecordset::GetName, CDaoRecordset::GetType


CDaoRecordset::GetType

short GetType( );
throw( CDaoException, CMemoryException );

Return Value

One of the following values that indicates the type of a recordset:

  • dbOpenTable Table-type recordset

  • dbOpenDynaset Dynaset-type recordset

  • dbOpenSnapshot Snapshot-type recordset

Remarks

Call this member function after opening the recordset to determine the type of the recordset object.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "Type Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetDefaultDBName, CDaoRecordset::GetDefaultSQL, CDaoRecordset::GetName, CDaoRecordset::GetSQL


CDaoRecordset::GetValidationRule

CString GetValidationRule( );
throw( CDaoException, CMemoryException );

Return Value

A CString object containing a value that validates the data in a record as it is changed or added to a table.

Remarks

Call this member function to determine the rule used to validate data. This rule is text-based, and is applied each time the underlying table is changed. If the data is not legal, MFC throws an exception. The returned error message is the text of the ValidationText property of the underlying field object, if specified, or the text of the expression specified by the ValidationRule property of the underlying field object. You can call GetValidationText to obtain the text of the error message.

For example, a field in a record that requires the day of the month might have a validation rule such as “DAY BETWEEN 1 AND 31.”

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "ValidationRule Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetValidationText


CDaoRecordset::GetValidationText

CString GetValidationText( );
throw( CDaoException, CMemoryException );

Return Value

A CString object containing the text of the message that is displayed if the value of a field does not satisfy the validation rule of the underlying field object.

Remarks

Call this member function to retrieve the text of the ValidationText property of the underlying field object.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide. For related information, see the topic "ValidationText Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetValidationRule


CDaoRecordset::IsBOF

BOOL IsBOF( ) const;
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the recordset contains no records or if you have scrolled backward before the first record; otherwise 0.

Remarks

Call this member function before you scroll from record to record to learn whether you have gone before the first record of the recordset. You can also call IsBOF along with IsEOF to determine whether the recordset contains any records or is empty. Immediately after you call Open, if the recordset contains no records, IsBOF returns nonzero. When you open a recordset that has at least one record, the first record is the current record and IsBOF returns 0.

If the first record is the current record and you call MovePrev, IsBOF will subsequently return nonzero. If IsBOF returns nonzero and you call MovePrev, an exception is thrown. If IsBOF returns nonzero, the current record is undefined, and any action that requires a current record will result in an exception.

Effect of specific methods on IsBOF and IsEOF settings:

  • Calling Open internally makes the first record in the recordset the current record by calling MoveFirst. Therefore, calling Open on an empty set of records causes IsBOF and IsEOF to return nonzero. (See the following table for the behavior of a failed MoveFirst or MoveLast call.)

  • All Move operations that successfully locate a record cause both IsBOF and IsEOF to return 0.

  • An AddNew call followed by an Update call that successfully inserts a new record will cause IsBOF to return 0, but only if IsEOF is already nonzero. The state of IsEOF will always remain unchanged. As defined by the Microsoft Jet database engine, the current record pointer of an empty recordset is at the end of a file, so any new record is inserted after the current record.

  • Any Delete call, even if it removes the only remaining record from a recordset, will not change the value of IsBOF or IsEOF.

This table shows which Move operations are allowed with different combinations of IsBOF/IsEOF.

 | MoveFirst, MoveLast | MovePrev, Move < 0 | Move 0 | MoveNext, Move > 0
IsBOF=nonzero, IsEOF=0 | Allowed | Exception | Exception | Allowed
IsBOF=0, IsEOF=nonzero | Allowed | Allowed | Exception | Exception
Both nonzero | Exception | Exception | Exception | Exception
Both 0 | Allowed | Allowed | Allowed | Allowed

Allowing a Move operation does not mean that the operation will successfully locate a record. It merely indicates that an attempt to perform the specified Move operation is allowed and will not generate an exception. The value of the IsBOF and IsEOF member functions may change as a result of the attempted move.

The effect of Move operations that do not locate a record on the value of IsBOF and IsEOF settings is shown in the following table.

 | IsBOF | IsEOF
MoveFirst, MoveLast | Nonzero | Nonzero
Move 0 | No change | No change
MovePrev, Move < 0 | Nonzero | No change
MoveNext, Move > 0 | No change | Nonzero

For more information about navigating in recordsets, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "BOF, EOF Properties" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::IsEOF


CDaoRecordset::IsDeleted

BOOL IsDeleted( ) const;

Return Value

Nonzero if the recordset is positioned on a deleted record; otherwise 0.

Remarks

Call this member function to determine whether the current record has been deleted. If you scroll to a record and IsDeleted returns TRUE (nonzero), then you must scroll to another record before you can perform any other recordset operations.

Note You don't need to check the deleted status for records in a snapshot or table-type recordset. Because records cannot be deleted from a snapshot, there is no need to call IsDeleted. For table-type recordsets, deleted records are actually removed from the recordset. Once a record has been deleted, either by you, another user, or in another recordset, you cannot scroll back to that record. Therefore, there is no need to call IsDeleted.

When you delete a record from a dynaset, it is removed from the recordset and you cannot scroll back to that record. However, if a record in a dynaset is deleted either by another user or in another recordset based on the same table, IsDeleted will return TRUE when you later scroll to that record.

For more information about navigating in recordsets, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topics "Delete Method", "LastModified Property", and "EditMode Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Delete, CDaoRecordset::IsBOF, CDaoRecordset::IsEOF


CDaoRecordset::IsEOF

BOOL IsEOF( ) const;
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the recordset contains no records or if you have scrolled beyond the last record; otherwise 0.

Remarks

Call this member function as you scroll from record to record to learn whether you have gone beyond the last record of the recordset. You can also call IsEOF to determine whether the recordset contains any records or is empty. Immediately after you call Open, if the recordset contains no records, IsEOF returns nonzero. When you open a recordset that has at least one record, the first record is the current record and IsEOF returns 0.

If the last record is the current record when you call MoveNext, IsEOF will subsequently return nonzero. If IsEOF returns nonzero and you call MoveNext, an exception is thrown. If IsEOF returns nonzero, the current record is undefined, and any action that requires a current record will result in an exception.

Effect of specific methods on IsBOF and IsEOF settings:

  • Calling Open internally makes the first record in the recordset the current record by calling MoveFirst. Therefore, calling Open on an empty set of records causes IsBOF and IsEOF to return nonzero. (See the following table for the behavior of a failed MoveFirst call.)

  • All Move operations that successfully locate a record cause both IsBOF and IsEOF to return 0.

  • An AddNew call followed by an Update call that successfully inserts a new record will cause IsBOF to return 0, but only if IsEOF is already nonzero. The state of IsEOF will always remain unchanged. As defined by the Microsoft Jet database engine, the current record pointer of an empty recordset is at the end of a file, so any new record is inserted after the current record.

  • Any Delete call, even if it removes the only remaining record from a recordset, will not change the value of IsBOF or IsEOF.

This table shows which Move operations are allowed with different combinations of IsBOF/IsEOF.

 | MoveFirst, MoveLast | MovePrev, Move < 0 | Move 0 | MoveNext, Move > 0
IsBOF=nonzero, IsEOF=0 | Allowed | Exception | Exception | Allowed
IsBOF=0, IsEOF=nonzero | Allowed | Allowed | Exception | Exception
Both nonzero | Exception | Exception | Exception | Exception
Both 0 | Allowed | Allowed | Allowed | Allowed

Allowing a Move operation does not mean that the operation will successfully locate a record. It merely indicates that an attempt to perform the specified Move operation is allowed and will not generate an exception. The value of the IsBOF and IsEOF member functions may change as a result of the attempted Move.

The effect of Move operations that do not locate a record on the value of IsBOF and IsEOF settings is shown in the following table.

 | IsBOF | IsEOF
MoveFirst, MoveLast | Nonzero | Nonzero
Move 0 | No change | No change
MovePrev, Move < 0 | Nonzero | No change
MoveNext, Move > 0 | No change | Nonzero

For more information about navigating in recordsets, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "BOF, EOF Properties" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::IsBOF


CDaoRecordset::IsFieldDirty

BOOL IsFieldDirty( void* pv ) const;
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the specified field data member is flagged as dirty; otherwise 0.

Parameters

pv

A pointer to the field data member whose status you want to check, or NULL to determine if any of the fields are dirty.

Remarks

Call this member function to determine whether the specified field data member of a dynaset has been flagged as “dirty” (changed). The data in all dirty field data members will be transferred to the record on the data source when the current record is updated by a call to the Update member function of CDaoRecordset (following a call to Edit or AddNew). With this knowledge, you can take further steps, such as unflagging the field data member to mark the column so it will not be written to the data source. For more information on the dirty flag, see the article DAO Recordset: Caching Multiple Records in Visual C++ Programmer's Guide.

IsFieldDirty is implemented through DoFieldExchange.

For more information about record field exchange, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::IsFieldNull, CDaoRecordset::IsFieldNullable


CDaoRecordset::IsFieldNull

BOOL IsFieldNull( void* pv );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the specified field data member is flagged as Null; otherwise 0.

Parameters

pv

A pointer to the field data member whose status you want to check, or NULL to determine if any of the fields are Null.

Remarks

Call this member function to determine whether the specified field data member of a recordset has been flagged as Null. (In database terminology, Null means “having no value” and is not the same as NULL in C++.) If a field data member is flagged as Null, it is interpreted as a column of the current record for which there is no value.

Note In certain situations, using IsFieldNull can be inefficient, as the following code example illustrates:

COleVariant varValue;
int nField;

// this code is inefficient because data
// must be retrieved for both IsFieldNull
// and GetFieldValue
if ( !rs.IsFieldNull( pField ) )
    rs.GetFieldValue( nField, varValue );

// this code is more efficient
rs.GetFieldValue( nField, varValue );
if ( varValue.vt == VT_NULL )
    // do something

Note If you are using dynamic record binding, without deriving from CDaoRecordset, be sure to use VT_NULL as shown in the example.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::IsFieldDirty, CDaoRecordset::IsFieldNullable


CDaoRecordset::IsFieldNullable

BOOL IsFieldNullable( void* pv );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the specified field data member can be made Null; otherwise 0.

Parameters

pv

A pointer to the field data member whose status you want to check, or NULL to determine if any of the fields are Null.

Remarks

Call this member function to to determine whether the specified field data member is “nullable” (can be set to a Null value; C++ NULL is not the same as Null, which, in database terminology, means “having no value”).

A field that cannot be Null must have a value. If you attempt to set such a field to Null when adding or updating a record, the data source rejects the addition or update, and Update will throw an exception. The exception occurs when you call Update, not when you call SetFieldNull.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::IsFieldDirty, CDaoRecordset::IsFieldNull


CDaoRecordset::IsOpen

BOOL IsOpen( ) const;

Return Value

Nonzero if the recordset object’s Open or Requery member function has previously been called and the recordset has not been closed; otherwise 0.

Remarks

Call this member function to determine if the recordset is open.

For more information about creating recordsets, see the article DAO Recordset: Creating Recordsets in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Open, CDaoRecordset::Close


CDaoRecordset::Move

virtual void Move( long lRows );
throw( CDaoException, CMemoryException );

Parameters

lRows

The number of records to move forward or backward. Positive values move forward, toward the end of the recordset. Negative values move backward, toward the beginning.

Remarks

Call this member function to position the recordset lRows records from the current record. You can move forward or backward. Move( 1 ) is equivalent to MoveNext, and Move( -1 ) is equivalent to MovePrev.

Caution Calling any of the Move functions throws an exception if the recordset has no records. In general, call both IsBOF and IsEOF before a Move operation to determine whether the recordset has any records. After you call Open or Requery, call either IsBOF or IsEOF.

If you have scrolled past the beginning or end of the recordset (IsBOF or IsEOF returns nonzero), a call to Move throws a CDaoException.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

When you call Move on a forward-only scrolling snapshot, the lRows parameter must be a positive integer and bookmarks are not allowed, so you can move forward only.

To make the first, last, next, or previous record in a recordset the current record, call the MoveFirst, MoveLast, MoveNext, or MovePrev member function.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topics "Move Method" and "MoveFirst, MoveLast, MoveNext, MovePrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::MoveFirst, CDaoRecordset::MoveLast, CDaoRecordset::MoveNext, CDaoRecordset::MovePrev


CDaoRecordset::MoveFirst

void MoveFirst( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to make the first record in the recordset (if any) the current record. You do not have to call MoveFirst immediately after you open the recordset. At that time, the first record (if any) is automatically the current record.

Caution Calling any of the Move functions throws an exception if the recordset has no records. In general, call both IsBOF and IsEOF before a Move operation to determine whether the recordset has any records. After you call Open or Requery, call either IsBOF or IsEOF.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

Use the Move functions to move from record to record without applying a condition. Use the Find operations to locate records in a dynaset-type or snapshot-type recordset object that satisfy a certain condition. To locate a record in a table-type recordset object, call Seek.

If the recordset refers to a table-type recordset, movement follows the table’s current index. You can set the current index by using the Index property of the underlying DAO object. If you do not set the current index, the order of returned records is undefined.

If you call MoveLast on a recordset object based on an SQL query or querydef, the query is forced to completion and the recordset object is fully populated.

You cannot call the MoveFirst or MovePrev member function with a forward-only scrolling snapshot.

To move the position of the current record in a recordset object a specific number of records forward or backward, call Move.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topics "Move Method" and "MoveFirst, MoveLast, MoveNext, MovePrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Move, CDaoRecordset::MoveLast, CDaoRecordset::MoveNext, CDaoRecordset::MovePrev


CDaoRecordset::MoveLast

void MoveLast( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to make the last record (if any) in the recordset the current record.

Caution Calling any of the Move functions throws an exception if the recordset has no records. In general, call both IsBOF and IsEOF before a Move operation to determine whether the recordset has any records. After you call Open or Requery, call either IsBOF or IsEOF.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

Use the Move functions to move from record to record without applying a condition. Use the Find operations to locate records in a dynaset-type or snapshot-type recordset object that satisfy a certain condition. To locate a record in a table-type recordset object, call Seek.

If the recordset refers to a table-type recordset, movement follows the table’s current index. You can set the current index by using the Index property of the underlying DAO object. If you do not set the current index, the order of returned records is undefined.

If you call MoveLast on a recordset object based on an SQL query or querydef, the query is forced to completion and the recordset object is fully populated.

To move the position of the current record in a recordset object a specific number of records forward or backward, call Move.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topics "Move Method" and "MoveFirst, MoveLast, MoveNext, MovePrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Move, CDaoRecordset::MoveFirst, CDaoRecordset::MoveNext, CDaoRecordset::MovePrev


CDaoRecordset::MoveNext

void MoveNext( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to make the next record in the recordset the current record. It is recommended that you call IsBOF before you attempt to move to the previous record. A call to MovePrev will throw a CDaoException if IsBOF returns nonzero, indicating either that you have already scrolled before the first record or that no records were selected by the recordset.

Caution Calling any of the Move functions throws an exception if the recordset has no records. In general, call both IsBOF and IsEOF before a Move operation to determine whether the recordset has any records. After you call Open or Requery, call either IsBOF or IsEOF.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

Use the Move functions to move from record to record without applying a condition. Use the Find operations to locate records in a dynaset-type or snapshot-type recordset object that satisfy a certain condition. To locate a record in a table-type recordset object, call Seek.

If the recordset refers to a table-type recordset, movement follows the table’s current index. You can set the current index by using the Index property of the underlying DAO object. If you do not set the current index, the order of returned records is undefined.

To move the position of the current record in a recordset object a specific number of records forward or backward, call Move.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topics "Move Method" and "MoveFirst, MoveLast, MoveNext, MovePrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Move, CDaoRecordset::MoveFirst, CDaoRecordset::MoveLast, CDaoRecordset::MovePrev


CDaoRecordset::MovePrev

void MovePrev( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to make the previous record in the recordset the current record.

It is recommended that you call IsBOF before you attempt to move to the previous record. A call to MovePrev will throw a CDaoException if IsBOF returns nonzero, indicating either that you have already scrolled before the first record or that no records were selected by the recordset.

Caution Calling any of the Move functions throws an exception if the recordset has no records. In general, call both IsBOF and IsEOF before a Move operation to determine whether the recordset has any records. After you call Open or Requery, call either IsBOF or IsEOF.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

Use the Move functions to move from record to record without applying a condition. Use the Find operations to locate records in a dynaset-type or snapshot-type recordset object that satisfy a certain condition. To locate a record in a table-type recordset object, call Seek.

If the recordset refers to a table-type recordset, movement follows the table’s current index. You can set the current index by using the Index property of the underlying DAO object. If you do not set the current index, the order of returned records is undefined.

You cannot call the MoveFirst or MovePrev member function with a forward-only scrolling snapshot.

To move the position of the current record in a recordset object a specific number of records forward or backward, call Move.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topics "Move Method" and "MoveFirst, MoveLast, MoveNext, MovePrevious Methods" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Move, CDaoRecordset::MoveFirst, CDaoRecordset::MoveLast, CDaoRecordset::MoveNext


CDaoRecordset::Open

virtual void Open( int nOpenType = AFX_DAO_USE_DEFAULT_TYPE, LPCTSTR lpszSQL = NULL, int nOptions = 0 );
throw( CDaoException, CMemoryException );

virtual void Open( CDaoTableDef* pTableDef, int nOpenType = dbOpenTable, int nOptions = 0 );
throw( CDaoException, CMemoryException );

virtual void Open( CDaoQueryDef* pQueryDef, int nOpenType = dbOpenDynaset, int nOptions = 0 );
throw( CDaoException, CMemoryException );

Parameters

nOpenType

One of the following values:

  • dbOpenDynaset A dynaset-type recordset with bidirectional scrolling. This is the default.

  • dbOpenTable A table-type recordset with bidirectional scrolling.

  • dbOpenSnapshot A snapshot-type recordset with bidirectional scrolling.

lpszSQL

A string pointer containing one of the following:

  • A NULL pointer.

  • The name of one or more tabledefs and/or querydefs (comma-separated).

  • An SQL SELECT statement (optionally with an SQL WHERE or ORDER BY clause).

  • A pass-through query.

nOptions

One or more of the options listed below. The default value is 0. Possible values are as follows:

  • dbAppendOnly You can only append new records (dynaset-type recordset only). This option means literally that records may only be appended. The MFC ODBC database classes have an append-only option that allows records to be retrieved and appended.

  • dbForwardOnly The recordset is a forward-only scrolling snapshot.

  • dbSeeChanges Generate an exception if another user is changing data you are editing.

  • dbDenyWrite Other users cannot modify or add records.

  • dbDenyRead Other users cannot view records (table-type recordset only).

  • dbReadOnly You can only view records; other users can modify them.

  • dbInconsistent Inconsistent updates are allowed (dynaset-type recordset only).

  • dbConsistent Only consistent updates are allowed (dynaset-type recordset only).

    Note The constants dbConsistent and dbInconsistent are mutually exclusive. You can use one or the other, but not both in a given instance of Open.

pTableDef

A pointer to a CDaoTableDef object. This version is valid only for table-type recordsets. When using this option, the CDaoDatabase pointer used to construct the CDaoRecordset is not used; rather, the database in which the tabledef resides is used.

pQueryDef

A pointer to a CDaoQueryDef object. This version is valid only for dynaset-type and snapshot-type recordsets. When using this option, the CDaoDatabase pointer used to construct the CDaoRecordset is not used; rather, the database in which the querydef resides is used.

Remarks

You must call this member function to retrieve the records for the recordset. Before calling Open, you must construct the recordset object. There are several ways to do this:

  • When you construct the recordset object, pass a pointer to a CDaoDatabase object that is already open.

  • When you construct the recordset object, pass a pointer to a CDaoDatabase object that is not open. The recordset opens a CDaoDatabase object, but will not close it when the recordset object closes.

  • When you construct the recordset object, pass a NULL pointer. The recordset object calls GetDefaultDBName to get the name of the Microsoft Access .MDB file to open. The recordset then opens a CDaoDatabase object and keeps it open as long as the recordset is open. When you call Close on the recordset, the CDaoDatabase object is also closed.

    Note When the recordset opens the CDaoDatabase object, it opens the data source with nonexclusive access.

For the version of Open that uses the lpszSQL parameter, once the recordset is open you can retrieve records in one of several ways. The first option is to have DFX functions in your DoFieldExchange. The second option is to use dynamic binding by calling the GetFieldValue member function. These options can be implemented separately or in combination. If they are combined, you will have to pass in the SQL statement yourself on the call to Open. For more information about dynamic binding, see the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

When you use the second version of Open where you pass in a CDaoTableDef object, the resulting columns will be available for you to bind via DoFieldExchange and the DFX mechanism, and/or bind dynamically via GetFieldValue.

Note You can only call Open using a CDaoTableDef object for table-type recordsets.

When you use the third version of Open where you pass in a CDaoQueryDef object, that query will be executed, and the resulting columns will be available for you to bind via DoFieldExchange and the DFX mechanism, and/or bind dynamically via GetFieldValue.

Note You can only call Open using a CDaoQueryDef object for dynaset-type and snapshot-type recordsets.

For the first version of Open that uses the lpszSQL parameter, records are selected based on criteria shown in the following table.

Value of the lpszSQL parameter | Records selected are determined by | Example
NULL | The string returned by GetDefaultSQL.
A comma-separated list of one or more tabledefs and/or querydef names. All columns represented in the DoFieldExchange.
"Customer"
SELECT column-list FROM table-list The specified columns from the specified tabledef(s) and/or querydef(s).
"SELECT CustId, CustName
FROM Customer"

The usual procedure is to pass NULL to Open; in that case, Open calls GetDefaultSQL, an overridable member function that ClassWizard generates when creating a CDaoRecordset-derived class. This value gives the tabledef(s) and/or querydef name(s) you specified in ClassWizard. You can instead specify other information in the lpszSQL parameter.

Whatever you pass, Open constructs a final SQL string for the query (the string may have SQL WHERE and ORDER BY clauses appended to the lpszSQL string you passed) and then executes the query. You can examine the constructed string by calling GetSQL after calling Open.

The field data members of your recordset class are bound to the columns of the data selected. If any records are returned, the first record becomes the current record.

If you want to set options for the recordset, such as a filter or sort, set m_strSort or m_strFilter after you construct the recordset object but before you call Open. If you want to refresh the records in the recordset after the recordset is already open, call Requery.

If you call Open on a dynaset-type or snapshot-type recordset, or if the data source refers to an SQL statement or a tabledef that represents an attached table, you cannot use dbOpenTable for the type argument; if you do, MFC throws an exception. To determine whether a tabledef object represents an attached table, create a CDaoTableDef object and call its GetConnect member function.

Use the dbSeeChanges flag if you wish to trap changes made by another user or another program on your machine when you are editing or deleting the same record. For example, if two users start editing the same record, the first user to call the Update member function succeeds. When Update is called by the second user, a CDaoException is thrown. Similarly, if the second user tries to call Delete to delete the record, and it has already been changed by the first user, a CDaoException occurs.

Typically, if the user gets this CDaoException while updating, your code should refresh the contents of the fields and retrieve the newly modified values. If the exception occurs in the process of deleting, your code could display the new record data to the user and a message indicating that the data has recently changed. At this point, your code can request a confirmation that the user still wants to delete the record.

Tip Use the forward-only scrolling option (dbForwardOnly) to improve performance when your application makes a single pass through a recordset opened from an ODBC data source.

For more information about opening recordsets, see the articles DAO Recordset: Creating Recordsets and DAO: Creating, Opening, and Closing DAO Objects in Visual C++ Programmer's Guide. For related information, see the topic "OpenRecordset Method" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Close, CDaoRecordset::CDaoRecordset


CDaoRecordset::Requery

virtual void Requery( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to rebuild (refresh) a recordset. If any records are returned, the first record becomes the current record.

In order for the recordset to reflect the additions and deletions that you or other users are making to the data source, you must rebuild the recordset by calling Requery. If the recordset is a dynaset, it automatically reflects updates that you or other users make to its existing records (but not additions). If the recordset is a snapshot, you must call Requery to reflect edits by other users as well as additions and deletions.

For either a dynaset or a snapshot, call Requery any time you want to rebuild the recordset using parameter values. Set the new filter or sort by setting m_strFilter and m_strSort before calling Requery. Set new parameters by assigning new values to parameter data members before calling Requery.

If the attempt to rebuild the recordset fails, the recordset is closed. Before you call Requery, you can determine whether the recordset can be requeried by calling the CanRestart member function. CanRestart does not guarantee that Requery will succeed.

Caution Call Requery only after you have called Open.

You can’t call Requery on a dynaset-type or snapshot-type recordset if calling CanRestart returns 0, nor can you use it on a table-type recordset.

If both IsBOF and IsEOF return nonzero after you call Requery, the query didn’t return any records and the recordset will contain no data.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topic "Requery Method" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::CanRestart


CDaoRecordset::Seek

BOOL Seek( LPCTSTR lpszComparison, COleVariant* pKey1, COleVariant* pKey2 = NULL, COleVariant* pKey3 = NULL );
throw( CDaoException, CMemoryException );

BOOL Seek (LPCTSTR lpszComparison, COleVariant* pKeyArray, WORD nKeys );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if matching records are found, otherwise 0.

Parameters

lpszComparison

One of the following string expressions: "<", "<=", "=", ">=", or ">".

pKey1

A pointer to a COleVariant whose value corresponds to the first field in the index. Required.

pKey2

A pointer to a COleVariant whose value corresponds to the second field in the index, if any. Defaults to NULL.

pKey3

A pointer to a COleVariant whose value corresponds to the third field in the index, if any. Defaults to NULL.

pKeyArray

A pointer to an array of variants. The array size corresponds to the number of fields in the index.

nKeys

An integer corresponding to the size of the array, which is the number of fields in the index.

Note Do not specify wildcards in the keys. Wildcards will cause Seek to return no matching records.

Remarks

Call this member function to locate the record in an indexed table-type recordset object that satisfies the specified criteria for the current index and make that record the current record. Use the second (array) version of Seek to handle indexes of four fields or more.

Seek enables high-performance index searching on table-type recordsets. You must set the current index by calling SetCurrentIndex before calling Seek. If the index identifies a nonunique key field or fields, Seek locates the first record that satisfies the criteria. If you do not set an index, an exception is thrown.

Note that if you are not creating a UNICODE recordset, the COleVariant objects must be explicitly declared ANSI. This can be done by using the COleVariant::COleVariant ( lpszSrc, vtSrc ) form of constructor with vtSrc set to VT_BSTRT (ANSI) or by using the COleVariant function SetString ( lpszSrc, vtSrc ) with vtSrc set to VT_BSTRT.

When you call Seek, you pass one or more key values and a comparison operator ("<", "<=", "=", ">=", or ">"). Seek searches through the specified key fields and locates the first record that satisfies the criteria specified by lpszComparison and pKey1. Once found, Seek returns nonzero, and makes that record current. If Seek fails to locate a match, Seek returns zero, and the current record is undefined. When using DAO directly, you must explicitly check the NoMatch property.

If lpszComparison is "=", ">=", or ">", Seek starts at the beginning of the index. If lpszComparison is "<" or "<=", Seek starts at the end of the index and searches backward unless there are duplicate index entries at the end. In this case, Seek starts at an arbitrary entry among the duplicate index entries at the end of the index.

There does not have to be a current record when you use Seek.

To locate a record in a dynaset-type or snapshot-type recordset that satisfies a specific condition, use the Find operations. To include all records, not just those that satisfy a specific condition, use the Move operations to move from record to record.

You cannot call Seek on an attached table of any type because attached tables must be opened as dynaset-type or snapshot-type recordsets. However, if you call CDaoDatabase::Open to directly open an installable ISAM database, you can call Seek on tables in that database, although the performance may be slow.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "Seek Method" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::FindFirst, CDaoRecordset::FindLast, CDaoRecordset::FindNext, CDaoRecordset::FindPrev, CDaoRecordset::Move, CDaoRecordset::MoveFirst, CDaoRecordset::MoveLast, CDaoRecordset::MoveNext, CDaoRecordset::MovePrev, COleVariant::COleVariant, COleVariant::SetString


CDaoRecordset::SetAbsolutePosition

void SetAbsolutePosition( long lPosition );
throw( CDaoException, CMemoryException );

Parameters

lPosition

Corresponds to the ordinal position of the current record in the recordset.

Remarks

Sets the relative record number of a recordset object’s current record. Calling SetAbsolutePosition enables you to position the current record pointer to a specific record based on its ordinal position in a dynaset-type or snapshot-type recordset. You can also determine the current record number by calling GetAbsolutePosition.

Note This member function is valid only for dynaset-type and snapshot-type recordsets.

The AbsolutePosition property value of the underlying DAO object is zero-based; a setting of 0 refers to the first record in the recordset. Setting a value greater than the number of populated records causes MFC to throw an exception. You can determine the number of populated records in the recordset by calling the GetRecordCount member function.

If the current record is deleted, the AbsolutePosition property value is not defined, and MFC throws an exception if it is referenced. New records are added to the end of the sequence.

Note This property is not intended to be used as a surrogate record number. Bookmarks are still the recommended way of retaining and returning to a given position and are the only way to position the current record across all types of recordset objects that support bookmarks. In particular, the position of a given record changes when record(s) preceding it are deleted. There is also no assurance that a given record will have the same absolute position if the recordset is re-created again because the order of individual records within a recordset is not guaranteed unless it is created with an SQL statement using an ORDER BY clause.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "AbsolutePosition Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetAbsolutePosition


CDaoRecordset::SetBookmark

void SetBookmark( COleVariant varBookmark );
throw( CDaoException, CMemoryException );

Parameters

varBookmark

A COleVariant object containing the bookmark value for a specific record.

Remarks

Call this member function to position the recordset on the record containing the specified bookmark. When a recordset object is created or opened, each of its records already has a unique bookmark. You can retrieve the bookmark for the current record by calling GetBookmark and saving the value to a COleVariant object. You can later return to that record by calling SetBookmark using the saved bookmark value.

Note that if you are not creating a UNICODE recordset, the COleVariant object must be explicitly declared ANSI. This can be done by using the COleVariant::COleVariant ( lpszSrc, vtSrc ) form of constructor with vtSrc set to VT_BSTRT (ANSI) or by using the COleVariant function SetString ( lpszSrc, vtSrc ) with vtSrc set to VT_BSTRT.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topics "Bookmark Property" and Bookmarkable Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetBookmark


CDaoRecordset::SetCacheSize

void SetCacheSize( long lSize );
throw( CDaoException, CMemoryException );

Parameters

lSize

Specifies the number of records. A typical value is 100. A setting of 0 turns off caching. The setting must be between 5 and 1200 records. The cache may use a considerable amount of memory.

Remarks

Call this member function to set the number of records to be cached. A cache is a space in local memory that holds the data most recently retrieved from the server in the event that the data will be requested again while the application is running. Data caching improves the performance of an application that retrieves data from a remote server through dynaset-type recordset objects. When data is requested, the Microsoft Jet database engine checks the cache for the requested data first rather than retrieving it from the server, which takes more time. Data that does not come from an ODBC data source is not saved in the cache.

Any ODBC data source, such as an attached table, can have a local cache. To create the cache, open a recordset object from the remote data source, call the SetCacheSize and SetCacheStart member functions, and then call the FillCache member function or step through the records by using one of the Move operations. The lSize parameter of the SetCacheSize member function can be based on the number of records your application can work with at one time. For example, if you are using a recordset as the source of the data to be displayed on screen, you could pass the SetCacheSize lSize parameter as 20 to display 20 records at one time.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "CacheSize, CacheStart Properties" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::FillCache, CDaoRecordset::GetCacheSize, CDaoRecordset::GetCacheStart, CDaoRecordset::SetCacheStart


CDaoRecordset::SetCacheStart

void SetCacheStart( COleVariant varBookmark );
throw( CDaoException, CMemoryException );

Parameters

varBookmark

A COleVariant that specifies the bookmark of the first record in the recordset to be cached.

Remarks

Call this member function to specify the bookmark of the first record in the recordset to be cached. You can use the bookmark value of any record for the varBookmark parameter of the SetCacheStart member function. Make the record you want to start the cache with the current record, establish a bookmark for that record using SetBookmark, and pass the bookmark value as the parameter for the SetCacheStart member function.

The Microsoft Jet database engine requests records within the cache range from the cache, and it requests records outside the cache range from the server.

Records retrieved from the cache do not reflect changes made concurrently to the source data by other users.

To force an update of all the cached data, pass the lSize parameter of SetCacheSize as 0, call SetCacheSize again with the size of the cache you originally requested, and then call the FillCache member function.

Note that if you are not creating a UNICODE recordset, the COleVariant object must be explicitly declared ANSI. This can be done by using the COleVariant::COleVariant ( lpszSrc, vtSrc ) form of constructor with vtSrc set to VT_BSTRT (ANSI) or by using the COleVariant function SetString ( lpszSrc, vtSrc ) with vtSrc set to VT_BSTRT.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic CacheSize, CacheStart Properties" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::FillCache, CDaoRecordset::GetCacheSize, CDaoRecordset::GetCacheStart, CDaoRecordset::SetCacheSize


CDaoRecordset::SetCurrentIndex

void SetCurrentIndex( LPCTSTR lpszIndex );
throw( CDaoException, CMemoryException );

Parameters

lpszIndex A pointer containing the name of the index to be set.

Remarks

Call this member function to set an index on a table-type recordset. Records in base tables are not stored in any particular order. Setting an index changes the order of records returned from the database, but it does not affect the order in which the records are stored. The specified index must already be defined. If you try to use an index object that does not exist, or if the index is not set when you call Seek, MFC throws an exception.

You can create a new index for the table by calling CDaoTableDef::CreateIndex and appending the new index to the Indexes collection of the underlying tabledef by calling CDaoTableDef::Append, and then reopening the recordset.

Records returned from a table-type recordset can be ordered only by the indexes defined for the underlying tabledef. To sort records in some other order, you can open a dynaset-type or snapshot-type recordset using an SQL ORDER BY clause stored in CDaoRecordset::m_strSort.

For more information about finding records, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "Index Object" and the definition "current index" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetCurrentIndex


CDaoRecordset::SetFieldDirty

void SetFieldDirty( void* pv, BOOL bDirty = TRUE );
throw( CDaoException, CMemoryException );

Parameters

pv

Contains the address of a field data member in the recordset or NULL. If NULL, all field data members in the recordset are flagged. (C++ NULL is not the same as Null in database terminology, which means “having no value.”)

bDirty

TRUE if the field data member is to be flagged as “dirty” (changed). Otherwise FALSE if the field data member is to be flagged as “clean” (unchanged).

Remarks

Call this member function to flag a field data member of the recordset as changed or as unchanged. Marking fields as unchanged ensures the field is not updated.

The framework marks changed field data members to ensure they will be written to the record on the data source by the DAO record field exchange (DFX) mechanism. Changing the value of a field generally sets the field dirty automatically, so you will seldom need to call SetFieldDirty yourself, but you might sometimes want to ensure that columns will be explicitly updated or inserted regardless of what value is in the field data member. The DFX mechanism also employs the use of PSEUDO NULL. For more information, see CDaoFieldExchange::m_nOperation.

If the double-buffering mechanism is not being used, then changing the value of the field does not automatically set the field as dirty. In this case, it will be necessary to explicity set the field as dirty. The flag contained in m_bCheckCacheForDirtyFields controls this automatic field checking.

Important Call this member function only after you have called Edit or AddNew.

Using NULL for the first argument of the function will apply the function to all outputColumns, not params in CDaoFieldExchange. For instance, the call

SetFieldDirty( NULL );

will set only outputColumns to NULL. The value of param will be unaffected.

To work on a param, you must supply the actual address of the individual param you want to work on, such as:

SetFieldDirty( &m_strParam );

This means you cannot set all params NULL, as you can with outputColumns.

SetFieldDirty is implemented through DoFieldExchange.

For more information about record field exchange, see the articles DAO Record Field Exchange (DFX) and DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetFieldNull, CDaoRecordset::SetFieldValue


CDaoRecordset::SetFieldNull

void SetFieldNull( void* pv, BOOL bNull = TRUE );
throw( CDaoException, CMemoryException );

Parameters

pv

Contains the address of a field data member in the recordset or NULL. If NULL, all field data members in the recordset are flagged. (C++ NULL is not the same as Null in database terminology, which means “having no value.”)

bNull

Nonzero if the field data member is to be flagged as having no value (Null). Otherwise 0 if the field data member is to be flagged as non-Null.

Remarks

Call this member function to flag a field data member of the recordset as Null (specifically having no value) or as non-Null. SetFieldNull is used for fields bound in the DoFieldExchange mechanism.

When you add a new record to a recordset, all field data members are initially set to a Null value and flagged as “dirty” (changed). When you retrieve a record from a data source, its columns either already have values or are Null. If it is not appropriate to make a field Null, a CDaoException is thrown.

If you are using the double-buffering mechanism, for example, if you specifically wish to designate a field of the current record as not having a value, call SetFieldNull with bNull set to TRUE to flag it as Null. If a field was previously marked Null and you now want to give it a value, simply set its new value. You do not have to remove the Null flag with SetFieldNull. To determine whether the field is allowed to be Null, call IsFieldNullable.

If you are not using the double-buffering mechanism, then changing the value of the field does not automatically set the field as dirty and non-Null. You must specifically set the fields dirty and non-Null. The flag contained in m_bCheckCacheForDirtyFields controls this automatic field checking.

The DFX mechanism employs the use of PSEUDO NULL. For more information, see CDaoFieldExchange::m_nOperation.

Important Call this member function only after you have called Edit or AddNew.

Using NULL for the first argument of the function will apply the function only to outputColumns, not params in CDaoFieldExchange. For instance, the call

SetFieldNull( NULL );

will set only outputColumns to NULL. The value of param will be unaffected.

For more information about record field exchange, see the articles DAO Record Field Exchange (DFX) and DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetParamValue


CDaoRecordset::SetFieldValue

void SetFieldValue( LPCTSTR lpszName, const COleVariant& varValue );
throw( CDaoException, CMemoryException );

void SetFieldValue( int nOrdinal, const COleVariant& varValue );
throw( CDaoException, CMemoryException );

void SetFieldValue( LPCTSTR lpszName, LPCTSTR lpszValue );

void SetFieldValue( int nOrdinal, LPCTSTR lpszValue );

Parameters

lpszName

A pointer to a string containing the name of a field.

varValue

A reference to a COleVariant object containing the value of the field’s contents.

nOrdinal

An integer that represents the ordinal position of the field in the recordset’s Fields collection (zero-based).

lpszValue

A pointer to a string containing the value of the field's contents.

Remarks

Call this member function to set the value of a field, either by ordinal position or by changing the value of the string. Use SetFieldValue and GetFieldValue to dynamically bind fields at run time rather than statically binding columns using the DoFieldExchange mechanism.

Note that if you are not creating a UNICODE recordset, you must either use a form of SetFieldValue that does not contain a COleVariant parameter (one of the last two syntax forms), or the COleVariant object must be explicitly declared ANSI. This can be done by using the COleVariant::COleVariant ( lpszSrc, vtSrc ) form of constructor with vtSrc set to VT_BSTRT (ANSI) or by using the COleVariant function SetString ( lpszSrc, vtSrc ) with vtSrc set to VT_BSTRT.

For more information about record field exchange, see the articles DAO Record Field Exchange (DFX) and DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide. For related information, see the topics "Field Object" and "Value Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetFieldValue, CDaoRecordset::m_nParams, CDaoRecordset::SetFieldValueNull, COleVariant::COleVariant, COleVariant::SetString


CDaoRecordset::SetFieldValueNull

void SetFieldValueNull( short nIndex );
throw( CDaoException, CMemoryException );

void SetFieldValueNull( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The index of the field in the recordset, for lookup by zero-based index.

lpszName

The name of the field in the recordset, for lookup by name.

Remarks

Call this member function to set the field to a Null value. C++ NULL is not the same as Null, which, in database terminology, means “having no value.”

For more information about record field exchange, see the articles DAO Record Field Exchange (DFX) and DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide. For related information, see the topics "Field Object" and "Value Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetFieldValue


CDaoRecordset::SetLockingMode

void SetLockingMode( BOOL bPessimistic );
throw( CDaoException, CMemoryException );

Parameters

bPessimistic

A flag that indicates the type of locking.

Remarks

Call this member function to set the type of locking for the recordset. When pessimistic locking is in effect, the 2K page containing the record you are editing is locked as soon as you call the Edit member function. The page is unlocked when you call the Update or Close member function or any of the Move or Find operations.

When optimistic locking is in effect, the 2K page containing the record is locked only while the record is being updated with the Update member function.

If a page is locked, no other user can edit records on the same page. If you call SetLockingMode and pass a nonzero value and another user already has the page locked, an exception is thrown when you call Edit. Other users can read data from locked pages.

If you call SetLockingMode with a zero value and later call Update while the page is locked by another user, an exception occurs. To see the changes made to your record by another user (and lose your changes), call the SetBookmark member function with the bookmark value of the current record.

When working with ODBC data sources, the locking mode is always optimistic.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topics "LockEdits Property", "EditMode Property", and "Locking Behavior in Multiuser Applications" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetLockingMode


CDaoRecordset::SetParamValue

virtual void SetParamValue( int nIndex, const COleVariant& var );
throw( CDaoException, CMemoryException );

virtual void SetParamValue( LPCTSTR lpszName, const COleVariant& var );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The numerical position of the parameter in the querydef’s Parameters collection.

var

The value to set; see Remarks.

lpszName

The name of the parameter whose value you want to set.

Remarks

Call this member function to set the value of a parameter in the recordset at run time. The parameter must already have been established as part of the recordset’s SQL string. You can access the parameter either by name or by its index position in the collection.

Specify the value to set as a COleVariant object. For information about setting the desired value and type in your COleVariant object, see class COleVariant. Note that if you are not creating a UNICODE recordset, the COleVariant object must be explicitly declared ANSI. This can be done by using the COleVariant::COleVariant ( lpszSrc, vtSrc ) form of constructor with vtSrc set to VT_BSTRT (ANSI) or by using the COleVariant function SetString ( lpszSrc, vtSrc ) with vtSrc set to VT_BSTRT.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topic "Parameter Object" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetParamValue, CDaoRecordset::m_nParams, CDaoRecordset::SetParamValueNull


CDaoRecordset::SetParamValueNull

void SetParamValueNull( short nIndex );
throw( CDaoException, CMemoryException );

void SetParamValueNull( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The index of the field in the recordset, for lookup by zero-based index.

lpszName

The name of the field in the recordset, for lookup by name.

Remarks

Call this member function to set the parameter to a Null value. C++ NULL is not the same as Null, which, in database terminology, means “having no value.”

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topic "Parameter Object" in DAO Help.


CDaoRecordset::SetPercentPosition

void SetPercentPosition( float fPosition );
throw( CDaoException, CMemoryException );

Parameters

fPosition

A number between 0 and 100.

Remarks

Call this member function to set a value that changes the approximate location of the current record in the recordset object based on a percentage of the records in the recordset.

When working with a dynaset-type or snapshot-type recordset, first populate the recordset by moving to the last record before you call SetPercentPosition. If you call SetPercentPosition before fully populating the recordset, the amount of movement is relative to the number of records accessed as indicated by the value of GetRecordCount. You can move to the last record by calling MoveLast.

Once you call SetPercentPosition, the record at the approximate position corresponding to that value becomes current.

Note Calling SetPercentPosition to move the current record to a specific record in a recordset is not recommended. Call the SetBookmark member function instead.

For more information about navigating in recordsets, see the article DAO Recordset: Recordset Navigation in Visual C++ Programmer's Guide. For related information, see the topic "PercentPosition Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::GetPercentPosition


CDaoRecordset::Update

virtual void Update( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function after a call to the AddNew or Edit member function. This call is required to complete the AddNew or Edit operation.

Both AddNew and Edit prepare an edit buffer in which the added or edited data is placed for saving to the data source. Update saves the data. Only those fields marked or detected as changed are updated.

If the data source supports transactions, you can make the Update call (and its corresponding AddNew or Edit call) part of a transaction. For more information about transactions, see the article DAO Workspace: Managing Transactions in Visual C++ Programmer's Guide.

Caution If you call Update without first calling either AddNew or Edit, Update throws a CDaoException. If you call AddNew or Edit, you must call Update before you call MoveNext or close either the recordset or the data source connection. Otherwise, your changes are lost without notification.

When the recordset object is pessimistically locked in a multiuser environment, the record remains locked from the time Edit is used until the updating is complete. If the recordset is optimistically locked, the record is locked and compared with the pre-edited record just before it is updated in the database. If the record has changed since you called Edit, the Update operation fails and MFC throws an exception. You can change the locking mode with SetLockingMode.

Note Optimistic locking is always used on external database formats, such as ODBC and installable ISAM.

For more information about updating data, see the article DAO Recordset: Recordset Operations in Visual C++ Programmer's Guide. For related information, see the topics "AddNew Method", "CancelUpdate Method", "Delete Method", "LastModified Property", "Update Method", and "EditMode Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::AddNew, CDaoRecordset::CancelUpdate, CDaoRecordset::Delete, CDaoRecordset::Edit, CDaoRecordset::CanTransact


CDaoRecordset::m_bCheckCacheForDirtyFields

Remarks

Contains a flag indicating whether cached fields are automatically marked as dirty (changed) and Null. The flag defaults to TRUE. The setting in this data member controls the entire double-buffering mechanism. If you set the flag to TRUE, you can turn off the caching on a field-by-field basis using the DFX mechanism. If you set the flag to FALSE, you must call SetFieldDirty and SetFieldNull yourself.

Set this data member before calling Open. This mechanism is primarily for ease-of-use. Performance may be slower because of the double-buffering of fields as changes are made.

For more information about binding records dynamically, see the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetFieldNull, CDaoRecordset::IsFieldNull, CDaoRecordset::IsFieldDirty, CDaoRecordset::SetFieldDirty


CDaoRecordset::m_nFields

Remarks

Contains the number of field data members in the recordset class and the number of columns selected by the recordset from the data source. The constructor for the recordset class must initialize m_nFields with the correct number of statically bound fields. ClassWizard writes this initialization for you when you use it to declare your recordset class. You can also write it manually.

The framework uses this number to manage interaction between the field data members and the corresponding columns of the current record on the data source.

Note This number must correspond to the number of output columns registered in DoFieldExchange after a call to SetFieldType with the parameter CDaoFieldExchange::outputColumn.

You can bind columns dynamically by way of CDaoRecordset::GetFieldValue and CDaoRecordset::SetFieldValue, as explained in the article DAO Recordset: Binding Records Dynamically. If you do so, you do not need to increment the count in m_nFields to reflect the number of DFX function calls in your DoFieldExchange member function.

For more information, see the article DAO Record Field Exchange (DFX) in Visual C++ Programmer's Guide.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::SetFieldValue, CDaoRecordset::GetFieldValue


CDaoRecordset::m_nParams

Remarks

Contains the number of parameter data members in the recordset class — the number of parameters passed with the recordset's query. If your recordset class has any parameter data members, the constructor for the class must initialize m_nParams with the correct number. The value of m_nParams defaults to 0. If you add parameter data members — which you must do manually — you must also manually add an initialization in the class constructor to reflect the number of parameters (which must be at least as large as the number of '?' placeholders in your m_strFilter or m_strSort string).

The framework uses this number when it parameterizes the recordset's query.

Important This number must correspond to the number of "params" registered in DoFieldExchange after a call to SetFieldType with the parameter CFieldExchange::param.

For more information about selecting records, see the article DAO Queries: Filtering and Parameterizing Queries in Visual C++ Programmer's Guide. For related information, see the topic "Parameter Object" in DAO Help.


CDaoRecordset::m_pDAORecordset

Remarks

Contains a pointer to the OLE interface for the DAO recordset object underlying the CDaoRecordset object. Use this pointer if you need to access the DAO interface directly.

For more information about accessing underlying DAO objects, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide. For related information, see the topic "Recordset Object" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::m_pDatabase


CDaoRecordset::m_pDatabase

Remarks

Contains a pointer to the CDaoDatabase object through which the recordset is connected to a data source. This variable is set in two ways. Typically, you pass a pointer to an already open CDaoDatabase object when you construct the recordset object. If you pass NULL instead, CDaoRecordset creates a CDaoDatabase object for you and opens it. In either case, CDaoRecordset stores the pointer in this variable.

Normally you will not directly need to use the pointer stored in m_pDatabase. If you write your own extensions to CDaoRecordset, however, you might need to use the pointer. For example, you might need the pointer if you throw your own CDaoException(s).

For more information about accessing underlying DAO objects, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide. For related information, see the topic "Database Object" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::m_pDAORecordset


CDaoRecordset::m_strFilter

Remarks

Contains a string that is used to construct the WHERE clause of an SQL statement. It does not include the reserved word WHERE to filter the recordset. The use of this data member is not applicable to table-type recordsets. The use of m_strFilter has no effect when opening a recordset using a CDaoQueryDef pointer.

Use the U.S. date format (month-day-year) when you filter fields containing dates, even if you are not using the U.S. version of the Microsoft Jet database engine; otherwise, the data may not be filtered as you expect.

For more information about selecting records, see the article DAO Queries: Filtering and Parameterizing Queries in Visual C++ Programmer's Guide. For related information, see the topic "Filter Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::m_strSort


CDaoRecordset::m_strSort

Remarks

Contains a string containing the ORDER BY clause of an SQL statement without the reserved words ORDER BY. You can sort on dynaset- and snapshot-type recordset objects.

You cannot sort table-type recordset objects. To determine the sort order of a table-type recordset, call SetCurrentIndex.

The use of m_strSort has no effect when opening a recordset using a CDaoQueryDef pointer.

For more information about selecting records, see the article DAO Queries: Filtering and Parameterizing Queries in Visual C++ Programmer's Guide. For related information, see the topic "Sort Property" in DAO Help.

CDaoRecordset Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::m_strFilter


CDaoRecordView

A CDaoRecordView object is a view that displays database records in controls. The view is a form view directly connected to a CDaoRecordset object. The view is created from a dialog template resource and displays the fields of the CDaoRecordset object in the dialog template’s controls. The CDaoRecordView object uses dialog data exchange (DDX) and DAO record field exchange (DFX) to automate the movement of data between the controls on the form and the fields of the recordset. CDaoRecordView also supplies a default implementation for moving to the first, next, previous, or last record and an interface for updating the record currently in view.

Note The DAO database classes are distinct from the MFC database classes based on Open Database Connectivity (ODBC). All DAO database class names have the “CDao” prefix. You can still access ODBC data sources with the DAO classes; the DAO classes generally offer superior capabilities because they use the Microsoft Jet database engine.

The most common way to create your record view is with AppWizard. AppWizard creates both the record view class and its associated recordset class as part of your skeleton starter application.

If you simply need a single form, the AppWizard approach is easier. ClassWizard lets you decide to use a record view later in the development process. If you don’t create the record view class with AppWizard, you can create it later with ClassWizard. Using ClassWizard to create a record view and a recordset separately and then connect them is the most flexible approach because it gives you more control in naming the recordset class and its .H/.CPP files. This approach also lets you have multiple record views on the same recordset class.

To make it easy for end-users to move from record to record in the record view, AppWizard creates menu (and optionally toolbar) resources for moving to the first, next, previous, or last record. If you create a record view class with ClassWizard, you need to create these resources yourself with the menu and bitmap editors. For more information about these resources, see Overview: Creating a Program That Supports a Database and ClassWizard: Creating a Database Form.

For information about the default implementation for moving from record to record, see IsOnFirstRecord and IsOnLastRecord and the article Record Views: Using a Record View, which applies to both CRecordView and CDaoRecordView.

CDaoRecordView keeps track of the user’s position in the recordset so that the record view can update the user interface. When the user moves to either end of the recordset, the record view disables user interface objects — such as menu items or toolbar buttons — for moving further in the same direction.

For more information about declaring and using your record view and recordset classes, see "Designing and Creating a Record View" in the article Record Views. For more information about how record views work and how to use them, see the article Record Views: Using a Record View. All the articles mentioned above apply to both CRecordView and CDaoRecordView and are found in Visual C++ Programmer's Guide.

#include <afxdao.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample DAOENROL

See Also CDaoRecordset, CDaoTableDef, CDaoQueryDef, CDaoDatabase, CDaoWorkspace, CFormView


CDaoRecordView Class Members

Construction

CDaoRecordView Constructs a CDaoRecordView object.

Attributes

OnGetRecordset | Returns a pointer to an object of a class derived from CDaoRecordset. ClassWizard overrides this function for you and creates the recordset if necessary.
IsOnLastRecord | Returns nonzero if the current record is the last record in the associated recordset.
IsOnFirstRecord | Returns nonzero if the current record is the first record in the associated recordset.

Operations

OnMove If the current record has changed, updates it on the data source, then moves to the specified record (next, previous, first, or last).


CDaoRecordView::CDaoRecordView

CDaoRecordView( LPCSTR lpszTemplateName );

CDaoRecordView( UINT nIDTemplate );

Parameters

lpszTemplateName

Contains a null-terminated string that is the name of a dialog template resource.

nIDTemplate

Contains the ID number of a dialog template resource.

Remarks

When you create an object of a type derived from CDaoRecordView, call either form of the constructor to initialize the view object and identify the dialog resource on which the view is based. You can either identify the resource by name (pass a string as the argument to the constructor) or by its ID (pass an unsigned integer as the argument). Using a resource ID is recommended.

Note Your derived class must supply its own constructor. In the constructor of your derived class, call the constructor CDaoRecordView::CDaoRecordView with the resource name or ID as an argument.

CDaoRecordView::OnInitialUpdate calls CWnd::UpdateData, which calls CWnd::DoDataExchange. This initial call to DoDataExchange connects CDaoRecordView controls (indirectly) to CDaoRecordset field data members created by ClassWizard. These data members cannot be used until after you call the base class CFormView::OnInitialUpdate member function.

Note If you use ClassWizard, the wizard defines an enum value CDaoRecordView::IDD and specifies it in the member initialization list for the constructor where you see IDD_MYFORM.

CMyRecordView::CMyRecordView()

   : CDaoRecordView( IDD_MYFORM )
{
   //{{AFX_DATA_INIT( CMyRecordView )
      // NOTE: the ClassWizard will add member initialization here
   //}}AFX_DATA_INIT
   // Other construction code, such as data initialization
}

CDaoRecordView Overview | Class Members | Hierarchy Chart

See Also CWnd::UpdateData, CWnd::DoDataExchange


CDaoRecordView::IsOnFirstRecord

BOOL IsOnFirstRecord( );

Return Value

Nonzero if the current record is the first record in the recordset; otherwise 0.

Remarks

Call this member function to determine whether the current record is the first record in the recordset object associated with this record view. This function is useful for writing your own implementations of the default command update handlers written by ClassWizard.

If the user moves to the first record, the framework disables any user interface objects (for example, menu items or toolbar buttons) you have for moving to the first or the previous record.

CDaoRecordView Overview | Class Members | Hierarchy Chart

See Also DaoRecordView::IsOnLastRecord


CDaoRecordView::IsOnLastRecord

BOOL IsOnLastRecord( );

Return Value

Nonzero if the current record is the last record in the recordset; otherwise 0.

Remarks

Call this member function to determine whether the current record is the last record in the recordset object associated with this record view. This function is useful for writing your own implementations of the default command update handlers that ClassWizard writes to support a user interface for moving from record to record.

Caution The result of this function is reliable except that the view may not be able to detect the end of the recordset until the user has moved past it. The user might have to move beyond the last record before the record view can tell that it must disable any user interface objects for moving to the next or last record. If the user moves past the last record and then moves back to the last record (or before it), the record view can track the user’s position in the recordset and disable user interface objects correctly.

CDaoRecordView Overview | Class Members | Hierarchy Chart

See Also CDaoRecordView::IsOnFirstRecord


CDaoRecordView::OnGetRecordset

virtual CDaoRecordset* OnGetRecordset( ) = 0;

Return Value

A pointer to a CDaoRecordset-derived object if the object was successfully created; otherwise a NULL pointer.

Remarks

Returns a pointer to the CDaoRecordset-derived object associated with the record view. You must override this member function to construct or obtain a recordset object and return a pointer to it. If you declare your record view class with ClassWizard, the wizard writes a default override for you. ClassWizard’s default implementation returns the recordset pointer stored in the record view if one exists. If not, it constructs a recordset object of the type you specified with ClassWizard and calls its Open member function to open the table or run the query, and then returns a pointer to the object.

For more information and examples, see the article Record Views: Using a Record View in Visual C++ Programmer's Guide.

CDaoRecordView Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset, CDaoRecordset::Open


CDaoRecordView::OnMove

virtual BOOL OnMove( UINT nIDMoveCommand );

Return Value

Nonzero if the move was successful; otherwise 0 if the move request was denied.

Parameters

nIDMoveCommand

One of the following standard command ID values:

  • ID_RECORD_FIRST Move to the first record in the recordset.

  • ID_RECORD_LAST Move to the last record in the recordset.

  • ID_RECORD_NEXT Move to the next record in the recordset.

  • ID_RECORD_PREV Move to the previous record in the recordset.

Remarks

Call this member function to move to a different record in the recordset and display its fields in the controls of the record view. The default implementation calls the appropriate Move member function of the CDaoRecordset object associated with the record view.

By default, OnMove updates the current record on the data source if the user has changed it in the record view.

AppWizard creates a menu resource with First Record, Last Record, Next Record, and Previous Record menu items. If you select the Initial Toolbar option, AppWizard also creates a toolbar with buttons corresponding to these commands.

If you move past the last record in the recordset, the record view continues to display the last record. If you move backward past the first record, the record view continues to display the first record.

Caution Calling OnMove throws an exception if the recordset has no records. Call the appropriate user interface update handler function — OnUpdateRecordFirst, OnUpdateRecordLast, OnUpdateRecordNext, or OnUpdateRecordPrev — before the corresponding move operation to determine whether the recordset has any records. For information about the update handlers, see Overview: Creating a Program That Supports a Database in Visual C++ Programmer's Guide.

CDaoRecordView Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset::Move


CDaoTableDef

A CDaoTableDef object represents the stored definition of a base table or an attached table. Each DAO database object maintains a collection, called TableDefs, that contains all saved DAO tabledef objects.

You manipulate a table definition using a CDaoTableDef object. For example, you can:

  • Examine the field and index structure of any local, attached, or external table in a database.

  • Call the SetConnect and SetSourceTableName member functions for attached tables, and use the RefreshLink member function to update connections to attached tables.

  • Call the CanUpdate member function to determine if you can edit field definitions in the table.

  • Get or set validation conditions using the GetValidationRule and SetValidationRule, and the GetValidationText and SetValidationText member functions.

  • Use the Open member function to create a table-, dynaset-, or snapshot-type CDaoRecordset object.

Note The DAO database classes are distinct from the MFC database classes based on Open Database Connectivity (ODBC). All DAO database class names have the “CDao” prefix. You can still access ODBC data sources with the DAO classes; the DAO classes generally offer superior capabilities because they are specific to the Microsoft Jet database engine.

Use tabledef objects either to work with an existing table or to create a new table:

  1. In all cases, first construct a CDaoTableDef object, supplying the a pointer to a CDaoDatabase object to which the table belongs.

  2. Then do the following, depending on what you want:
    • To use an existing saved table, call the tabledef object’s Open member function, supplying the name of the saved table.

    • To create a new table, call the tabledef object’s Create member function, supplying the name of the table. Call CreateField and CreateIndex to add fields and indexes to the table.

    • Call Append to save the table by appending it to the database’s TableDefs collection. Create puts the tabledef into an open state, so after calling Create you do not call Open.

Tip The easiest way to create saved tables is to create them and store them in your database using Microsoft Access. Then you can open and use them in your MFC code.

To use the tabledef object you have opened or created, create and open a CDaoRecordset object, specifying the name of the tabledef with a dbOpenTable value in the nOpenType parameter.

To use a tabledef object to create a CDaoRecordset object, you typically create or open a tabledef as described above, then construct a recordset object, passing a pointer to your tabledef object when you call CDaoRecordset::Open. The tabledef you pass must be in an open state. For more information, see class CDaoRecordset.

When you finish using a tabledef object, call its Close member function; then destroy the tabledef object.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide.

#include <afxdao.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample DAOVIEW | MFC Sample DAOTABLE

See Also CDaoDatabase, CDaoRecordset


CDaoTableDef Class Members

Data Members

m_pDatabase | Source database for this table.
m_pDAOTableDef | A pointer to the DAO interface underlying the tabledef object.

Construction

Append | Adds a new table to the database.
CDaoTableDef | Constructs a CDaoTableDef object.
Close | Closes an open tabledef.
Create | Creates a table which can be added to the database using Append.
Open | Opens an existing tabledef stored in the database’s TableDef’s collection.

Attributes

CanUpdate | Returns nonzero if the table can be updated (you can modify the definition of fields or the table properties).
GetAttributes | Returns a value that indicates one or more characteristics of a CDaoTableDef object.
GetConnect | Returns a value that provides information about the source of a table.
GetDateCreated | Returns the date and time the base table underlying a CDaoTableDef object was created.
GetDateLastUpdated | Returns the date and time of the most recent change made to the design of the base table.
GetFieldCount | Returns a value that represents the number of fields in the table.
GetFieldInfo | Returns specific kinds of information about the fields in the table.
GetIndexCount | Returns the number of indexes for the table.
GetIndexInfo | Returns specific kinds of information about the indexes for the table.
GetName | Returns the user-defined name of the table.
GetRecordCount | Returns the number of records in the table.
GetSourceTableName | Returns a value that specifies the name of the attached table in the source database.
GetValidationRule | Returns a value that validates the data in a field as it is changed or added to a table.
GetValidationText | Returns a value that specifies the text of the message that your application displays if the value of a Field object does not satisfy the specified validation rule.
IsOpen | Returns nonzero if the table is open.
SetAttributes | Sets a value that indicates one or more characteristics of a CDaoTableDef object.
SetConnect | Sets a value that provides information about the source of a table.
SetName | Sets the name of the table.
SetSourceTableName | Sets a value that specifies the name of an attached table in the source database.
SetValidationRule | Sets a value that validates the data in a field as it is changed or added to a table.
SetValidationText | Sets a value that specifies the text of the message that your application displays if the value of a Field object does not satisfy the specified validation rule.

Operations

CreateField | Called to create a field for a table.
CreateIndex | Called to create an index for a table.
DeleteField | Called to delete a field from a table.
DeleteIndex | Called to delete an index from a table.
RefreshLink | Updates the connection information for an attached table.


CDaoTableDef::Append

virtual void Append( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function after you call Create to create a new tabledef object to save the tabledef in the database. The function appends the object to the database’s TableDefs collection. You can use the tabledef as a temporary object while defining it by not appending it, but if you want to save and use it, you must call Append.

Note If you attempt to append an unnamed tabledef (containing a null or empty string), MFC throws an exception.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Append Method" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::Create


CDaoTableDef::CanUpdate

BOOL CanUpdate( );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the table structure (schema) can be modified (add or delete fields and indexes), otherwise 0.

Remarks

Call this member function to determine whether the definition of the table underlying a CDaoTableDef object can be changed.

By default, a newly created table underlying a CDaoTableDef object can be updated, and an attached table underlying a CDaoTableDef object cannot be updated. A CDaoTableDef object may be updatable, even if the resulting recordset is not updatable.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Updatable Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetDateLastUpdated


CDaoTableDef::CDaoTableDef

CDaoTableDef( CDaoDatabase* pDatabase );

Parameters

pDatabase

A pointer to a CDaoDatabase object.

Remarks

Constructs a CDaoTableDef object. After constructing the object, you must call the Create or Open member function. When you finish with the object, you must call its Close member function and destroy the CDaoTableDef object.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::Open, CDaoTableDef::Close, CDaoTableDef::Create, CDaoDatabase


CDaoTableDef::Close

virtual void Close( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to close and release the tabledef object. Usually after calling Close, you delete the tabledef object if it was allocated with new.

You can call Open again after calling Close. This lets you reuse the tabledef object.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Close Method" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::Open, CDaoTableDef::Create


CDaoTableDef::Create

virtual void Create( LPCTSTR lpszName, long lAttributes = 0, LPCTSTR lpszSrcTable = NULL, LPCTSTR lpszConnect = NULL );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A pointer to a string containing the name of the table.

lAttributes

A value corresponding to characteristics of the table represented by the tabledef object. You can use the bitwise-OR to combine any of the following constants:

Constant | Description
dbAttachExclusive | For databases that use the Microsoft Jet database engine, indicates the table is an attached table opened for exclusive use.
dbAttachSavePWD | For databases that use the Microsoft Jet database engine, indicates that the user ID and password for the attached table are saved with the connection information.
dbSystemObject | Indicates the table is a system table provided by the Microsoft Jet database engine.
dbHiddenObject | Indicates the table is a hidden table provided by the Microsoft Jet database engine.

lpszSrcTable

A pointer to a string containing the source table name. By default this value is initialized as NULL.

lpszConnect

A pointer to a string containing the default connect string. By default this value is initialized as NULL.

Remarks

Call this member function to create a new saved table. Once you have named the tabledef, you can then call Append to save the tabledef in the database’s TableDefs collection. After calling Append, the tabledef is in an open state, and you can use it to create a CDaoRecordset object.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "CreateTableDef Method" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::Open, CDaoTableDef::Close, CDaoRecordset


CDaoTableDef::CreateField

void CreateField( LPCTSTR lpszName, short nType, long lSize, long lAttributes = 0 );
throw( CDaoException, CMemoryException );

void CreateField( CDaoFieldInfo& fieldinfo );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A pointer to a string expression specifying the name of this field.

nType

A value indicating the data type of the field. The setting can be one of these values:

Type | Size (bytes) | Description
dbBoolean | 1 byte | BOOL
dbByte | 1 | BYTE
dbInteger | 2 | int
dbLong | 4 | long
dbCurrency | 8 | Currency (COleCurrency)
dbSingle | 4 | float
dbDouble | 8 | double
dbDate | 8 | Date/Time (COleDateTime)
dbText | 1 – 255 | Text (CString)
dbLongBinary | 0 | Long Binary (OLE Object), CLongBinary or CByteArray
dbMemo | 0 | Memo (CString)

lSize

A value that indicates the maximum size, in bytes, of a field that contains text, or the fixed size of a field that contains text or numeric values. The lSize parameter is ignored for all but text fields.

lAttributes

A value corresponding to characteristics of the field and that can be combined using a bitwise-OR.

Constant | Description
dbFixedField | The field size is fixed (default for Numeric fields).
dbVariableField | The field size is variable (Text fields only).
dbAutoIncrField | The field value for new records is automatically incremented to a unique long integer that cannot be changed. Only supported for Microsoft Jet database tables.
dbUpdatableField | The field value can be changed.
dbDescending | The field is sorted in descending (Z – A or 100 – 0) order (applies only to a Field object in a Fields collection of an Index object). If you omit this constant, the field is sorted in ascending (A – Z or 0 – 100) order (default).

fieldinfo

A reference to a CDaoFieldInfo structure.

Remarks

Call this member function to add a field to the table. A DAOField (OLE) object is created and appended to the Fields collection of the DAOTableDef (OLE) object. Besides its use for examining object properties, you can also use CDaoFieldInfo to construct an input parameter for creating new fields in a tabledef. The first version of CreateField is simpler to use, but if you want finer control, you can use the second version of CreateField, which takes a CDaoFieldInfo parameter.

If you use the version of CreateField that takes a CDaoFieldInfo parameter, you must carefully set each of the following members of the CDaoFieldInfo structure:

  • m_strName

  • m_nType

  • m_lSize

  • m_lAttributes

  • m_bAllowZeroLength

The remaining members of CDaoFieldInfo should be set to 0, FALSE, or an empty string, as appropriate for the member, or a CDaoException may occur.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "CreateField Method" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::DeleteField, CDaoTableDef::CreateIndex, CDaoTableDef::DeleteIndex


CDaoTableDef::CreateIndex

void CreateIndex( CDaoIndexInfo& indexinfo );
throw( CDaoException, CMemoryException );

Parameters

indexinfo

A reference to a CDaoIndexInfo structure.

Remarks

Call this function to add an index to a table. Indexes specify the order of records accessed from database tables and whether or not duplicate records are accepted. Indexes also provide efficient access to data.

You do not have to create indexes for tables, but in large, unindexed tables, accessing a specific record or creating a recordset can take a long time. On the other hand, creating too many indexes slows down update, append, and delete operations as all indexes are automatically updated. Consider these factors as you decide which indexes to create.

The following members of the CDaoIndexInfo structure must be set:

  • m_strName A name must be supplied.

  • m_pFieldInfos Must point to an array of CDaoIndexFieldInfo structures.

  • m_nFields Must specify the number of fields in the array of CDaoFieldInfo structures.

The remaining members will be ignored if set to FALSE. In addition, the m_lDistinctCount member is ignored during creation of the index.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "CreateIndex Method" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::DeleteIndex, CDaoTableDef::CreateField, CDaoTableDef::DeleteField, CDaoIndexInfo


CDaoTableDef::DeleteField

void DeleteField( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

void DeleteField( int nIndex );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A pointer to a string expression that is the name of an existing field.

nIndex

The index of the field in the table’s zero-based Fields collection, for lookup by index.

Remarks

Call this member function to remove a field and make it inaccessible. You can use this member function on a new object that has not been appended to the database or when CanUpdate returns nonzero.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Delete Method" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::CreateField, CDaoTableDef::CreateIndex, CDaoTableDef::DeleteIndex


CDaoTableDef::DeleteIndex

void DeleteIndex( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

void DeleteIndex( int nIndex );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A pointer to a string expression that is the name of an existing index.

nIndex

The array index of the index object in the database’s zero-based TableDefs collection, for lookup by index.

Remarks

Call this member function to delete an index in an underlying table. You can use this member function on a new object that hasn’t been appended to the database or when CanUpdate returns nonzero.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Delete Method" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::CreateIndex, CDaoTableDef::CreateField, CDaoTableDef::DeleteField


CDaoTableDef::GetAttributes

long GetAttributes( );
throw( CDaoException, CMemoryException );

Return Value

Returns a value that indicates one or more characteristics of a CDaoTableDef object.

Remarks

For a CDaoTableDef object, the return value specifies characteristics of the table represented by the CDaoTableDef object and can be a sum of these constants:

Constant | Description
dbAttachExclusive | For databases that use the Microsoft Jet database engine, indicates the table is an attached table opened for exclusive use.
dbAttachSavePWD | For databases that use the Microsoft Jet database engine, indicates that the user ID and password for the attached table are saved with the connection information.
dbSystemObject | Indicates the table is a system table provided by the Microsoft Jet database engine.
dbHiddenObject | Indicates the table is a hidden table provided by the Microsoft Jet database engine.
dbAttachedTable | Indicates the table is an attached table from a non-ODBC database, such as a Paradox database.
dbAttachedODBC | Indicates the table is an attached table from an ODBC database, such as Microsoft SQL Server.

A system table is a table created by the Microsoft Jet database engine to contain various internal information.

A hidden table is a table created for temporary use by the Microsoft Jet database engine.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Attributes Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::SetAttributes


CDaoTableDef::GetConnect

CString GetConnect( );
throw( CDaoException, CMemoryException );

Return Value

A CString object containing the path and database type for the table.

Remarks

Call this member function to obtain the connect string for a data source. For a CDaoTableDef object that represents an attached table, the CString object consists of one or two parts (a database type specifier and a path to the database).

The path as shown in the table below is the full path for the directory containing the database files and must be preceded by the identifier "DATABASE=". In some cases (as with Microsoft Jet and Microsoft Excel databases), a specific filename is included in the database path argument.

The table in CDaoTableDef::SetConnect shows possible database types and their corresponding database specifiers and paths:

For Microsoft Jet database base tables, the specifier is a empty string ("").

If a password is required but not provided, the ODBC driver displays a login dialog box the first time a table is accessed and again if the connection is closed and reopened. If an attached table has the dbAttachSavePWD attribute, the login prompt will not appear when the table is reopened.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Connect Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::SetConnect


CDaoTableDef::GetDateCreated

COleDateTime GetDateCreated( );
throw( CDaoException, CMemoryException );

Return Value

A value containing the date and time of the creation of the table underlying the CDaoTableDef object.

Remarks

Call this function to determine the date and time the table underlying the CDaoTableDef object was created.

The date and time settings are derived from the computer on which the base table was created or last updated. In a multiuser environment, users should get these settings directly from the file server to avoid discrepancies; that is, all clients should use a “standard” time source — perhaps from one server.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "DateCreated, LastUpdated Properties" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetLastDateUpdated


CDaoTableDef::GetDateLastUpdated

COleDateTime GetDateLastUpdated( );
throw( CDaoException, CMemoryException );

Return Value

A value that contains the date and time the table underlying the CDaoTableDef object was last updated.

Remarks

Call this function to determine the date and time the table underlying the CDaoTableDef object was last updated.

The date and time settings are derived from the computer on which the base table was created or last updated. In a multiuser environment, users should get these settings directly from the file server to avoid discrepancies; that is, all clients should use a “standard” time source — perhaps from one server.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "DateCreated, LastUpdated Properties" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetDateCreated


CDaoTableDef::GetFieldCount

short GetFieldCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of fields in the table.

Remarks

Call this member function to retrieve the number of fields defined in the table. If its value is 0, there are no objects in the collection.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Count Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetFieldInfo, CDaoTableDef::GetIndexInfo, CDaoTableDef::GetIndexCount


CDaoTableDef::GetFieldInfo

void GetFieldInfo( int nIndex, CDaoFieldInfo& fieldinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetFieldInfo( LPCTSTR lpszName, CDaoFieldInfo& fieldinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The index of the field object in the table’s zero-based Fields collection, for lookup by index.

fieldinfo

A reference to a CDaoFieldInfo structure.

dwInfoOptions

Options that specify which information about the field to retrieve. The available options are listed here along with what they cause the function to return:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Type, Size, Attributes. Use this option for fastest performance.

  • AFX_DAO_SECONDARY_INFO Primary information, plus: Ordinal Position, Required, Allow Zero Length, Collating Order, Foreign Name, Source Field, Source Table

  • AFX_DAO_ALL_INFO Primary and secondary information, plus: Validation Rule, Validation Text, Default Value

lpszName

A pointer to the name of the field object, for lookup by name. The name is a string with up to 64 characters that uniquely names the field.

Remarks

Call this member function to obtain various kinds of information about a field defined in the tabledef. One version of the function lets you look up a field by index. The other version lets you look up a field by name.

For a description of the information returned, see the CDaoFieldInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. When you request information at one level, you get information for any prior levels as well.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Attributes Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetIndexInfo, CDaoTableDef::GetIndexCount, CDaoTableDef::GetFieldCount


CDaoTableDef::GetIndexCount

short GetIndexCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of indexes for the table.

Remarks

Call this member function to obtain the number of indexes for a table. If its value is 0, there are no indexes in the collection.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Count Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetIndexInfo, CDaoTableDef::GetFieldInfo, CDaoTableDef::GetFieldCount


CDaoTableDef::GetIndexInfo

void GetIndexInfo( int nIndex, CDaoIndexInfo& indexinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetIndexInfo( LPCTSTR lpszName, CDaoIndexInfo& indexinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The numeric index of the Index object in the table’s zero-based Indexes collection, for lookup by its position in the collection.

indexinfo

A reference to a CDaoIndexInfo structure.

dwInfoOptions

Options that specify which information about the index to retrieve. The available options are listed here along with what they cause the function to return:

  • AFX_DAO_PRIMARY_INFO Name, Field Info, Fields. Use this option for fastest performance.

  • AFX_DAO_SECONDARY_INFO Primary information, plus: Primary, Unique, Clustered, Ignore Nulls, Required, Foreign

  • AFX_DAO_ALL_INFO Primary and secondary information, plus: Distinct Count

lpszName

A pointer to the name of the index object, for lookup by name.

Remarks

Call this member function to obtain various kinds of information about an index defined in the tabledef. One version of the function lets you look up an index by its position in the collection. The other version lets you look up an index by name.

For a description of the information returned, see the CDaoIndexInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. When you request information at one level, you get information for any prior levels as well.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Attributes Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetFieldInfo, CDaoTableDef::GetIndexCount, CDaoTableDef::GetFieldCount


CDaoTableDef::GetName

CString GetName( );
throw( CDaoException, CMemoryException );

Return Value

A user-defined name for a table.

Remarks

Call this member function to obtain the user-defined name of the underlying table. This name starts with a letter and can contain a maximum of 64 characters. It can include numbers and underscore characters but cannot include punctuation or spaces.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Name Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::SetName, CDaoTableDef::GetConnect, CDaoTableDef::SetConnect


CDaoTableDef::GetRecordCount

long GetRecordCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of records accessed in a tabledef object.

Remarks

Call this member function to find out how many records are in a CDaoTableDef object.

Calling GetRecordCount for a table-type CDaoTableDef object reflects the approximate number of records in the table and is affected immediately as table records are added and deleted. Rolled back transactions will appear as part of the record count until you call CDaoWorkSpace::CompactDatabase. A CDaoTableDef object with no records has a record count property setting of 0. When working with attached tables or ODBC databases, GetRecordCount always returns –1.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "RecordCount Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetSourceTableName, CDaoTableDef::SetSourceTableName


CDaoTableDef::GetSourceTableName

CString GetSourceTableName( );
throw( CDaoException, CMemoryException );

Return Value

A CString object that specifies the source name of an attached table, or an empty string if a native data table.

Remarks

Call this member function to retrieve the name of an attached table in a source database. An attached table is a table in another database linked to a Microsoft Jet database. Data for attached tables remains in the external database, where it can be manipulated by other applications.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "SourceTableName Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetRecordCount, CDaoTableDef::SetSourceTableName


CDaoTableDef::GetValidationRule

CString GetValidationRule( );
throw( CDaoException, CMemoryException );

Return Value

A CString object that validates the data in a field as it is changed or added to a table.

Remarks

Call this member function to retrieve the validation rule for a tabledef. Validation rules are used in connection with update operations. If a tabledef contains a validation rule, updates to that tabledef must match predetermined criteria before the data is changed. If the change does not match the criteria, an exception containing the value of GetValidationText is thrown. For a CDaoTableDef object, this CString is read-only for an attached table and read/write for a base table.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "ValidationRule Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::SetValidationRule, CDaoTableDef::GetValidationText, CDaoTableDef::SetValidationText


CDaoTableDef::GetValidationText

CString GetValidationText( );
throw( CDaoException, CMemoryException );

Return Value

A CString object that specifies the text displayed if the user enters data that does not match the validation rule.

Remarks

Call this function to retrieve the string to display when a user enters data that does not match the validation rule. For a CDaoTableDef object, this CString is read-only for an attached table and read/write for a base table.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "ValidationText Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::SetValidationRule, CDaoTableDef::SetValidationText, CDaoTableDef::GetValidationRule


CDaoTableDef::IsOpen

BOOL IsOpen( ) const;
throw( CDaoException, CMemoryException );

Return Value

Nonzero if the CDaoTableDef object is open; otherwise 0.

Remarks

Call this member function to determine whether the CDaoTableDef object is currently open.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::Open


CDaoTableDef::Open

virtual void Open( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A pointer to a string that specifies a table name.

Remarks

Call this member function to open a tabledef previously saved in the database’s TableDef’s collection.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::IsOpen, CDaoTableDef::Create, CDaoTableDef::Close


CDaoTableDef::RefreshLink

void RefreshLink( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to update the connection information for an attached table. You change the connection information for an attached table by calling SetConnect on the corresponding CDaoTableDef object and then using the RefreshLink member function to update the information. When you call RefreshLink, the attached table’s properties are not changed.

To force the modified connect information to take effect, all open CDaoRecordset objects based on this tabledef must be closed.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "RefreshLink Method" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::SetConnect


CDaoTableDef::SetAttributes

void SetAttributes( long lAttributes );
throw( CDaoException, CMemoryException );

Parameters

lAttributes

Characteristics of the table represented by the CDaoTableDef object and can be a sum of these constants:

Constant | Description
dbAttachExclusive | For databases that use the Microsoft Jet database engine, indicates the table is an attached table opened for exclusive use.
dbAttachSavePWD | For databases that use the Microsoft Jet database engine, indicates that the user ID and password for the attached table are saved with the connection information.
dbSystemObject | Indicates the table is a system table provided by the Microsoft Jet database engine.
dbHiddenObject | Indicates the table is a hidden table provided by the Microsoft Jet database engine.

Remarks

When setting multiple attributes, you can combine them by summing the appropriate constants using the bitwise-OR operator. Setting dbAttachExclusive on a nonattached table produces an exception. Combining the following values also produce an exception:

  • dbAttachExclusive | dbAttachedODBC

  • dbAttachSavePWD | dbAttachedTable

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Attributes Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::SetConnect


CDaoTableDef::SetConnect

void SetConnect( LPCTSTR lpszConnect );
throw( CDaoException, CMemoryException );

Parameters

lpszConnect

A pointer to a string expression that specifies additional parameters to pass to ODBC or installable ISAM drivers.

Remarks

For a CDaoTableDef object that represents an attached table, the string object consists of one or two parts (a database type specifier and a path to the database).

The path as shown in the table below is the full path for the directory containing the database files and must be preceded by the identifier "DATABASE=". In some cases (as with Microsoft Jet and Microsoft Excel databases), a specific filename is included in the database path argument.

Note Do not include whitespace around the equal sign in path statements of the form "DATABASE=drive:\\path". This will result in an exception being thrown and the connection failing.

The following table shows possible database types and their corresponding database specifiers and paths:

Database type | Specifier | Path
Database using the Jet database engine | “[database];” | "drive:\\path\\filename.MDB"
dBASE III | "dBASE III;" | "drive:\\path"
dBASE IV | "dBASE IV;" | "drive:\\path"
dBASE 5 | “dBASE 5.0;” | “drive:\\path”
Paradox 3.x | "Paradox 3.x;" | "drive:\\path"
Paradox 4.x | "Paradox 4.x;" | "drive:\\path"
Paradox 5.x | “Paradox 5.x;” | “drive:\\path”
FoxPro 2.0 | "FoxPro 2.0;" | "drive:\\path"
FoxPro 2.5 | "FoxPro 2.5;" | "drive:\\path"
FoxPro 2.6 | "FoxPro 2.6;" | "drive:\\path"
Excel 3.0 | "Excel 3.0;" | "drive:\\path\\filename.XLS"
Excel 4.0 | "Excel 4.0;" | "drive:\\path\\filename.XLS"
Excel 5.0 or Excel 95 | "Excel 5.0;" | "drive:\\path\\filename.XLS"
Excel 97 | “Excel 8.0;” | “drive:\\path\filename.XLS”
HTML Import | “HTML Import;” | “drive:\\path\filename”
HTML Export | “HTML Export;” | “drive:\\path”
Text | "Text;" | "drive:\\path"
ODBC "ODBC;
DATABASE=database;
UID=user;PWD=password;
DSN=datasourcename;
LOGINTIMEOUT=seconds;" (This may not be a complete connection string for all servers; it is just an example. It is very important not to have spaces between the parameters.) 		None
Exchange “Exchange;

MAPILEVEL=folderpath;

[TABLETYPE={ 0 | 1 };]

[PROFILE=profile;]

[PWD=password;]

[DATABASE=database;]”

 “drive:\\path\\filename.MDB”

Note Btrieve is no longer supported as of DAO 3.5.

You must use a double backslash (\\) in the connect strings. If you have modified the properties of an existing connection using SetConnect, you must subsequently call RefreshLink. If you are initializing the connection properties using SetConnect, you need not call RefreshLink, but should you choose to do so, first append the tabledef.

If a password is required but not provided, the ODBC driver displays a login dialog box the first time a table is accessed and again if the connection is closed and reopened.

You can set the connect string for a CDaoTableDef object by providing a source argument to the Create member function. You can check the setting to determine the type, path, user ID, password, or ODBC data source of the database. For more information, see the documentation for the specific driver.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Connect Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::RefreshLink, CDaoTableDef::SetAttributes


CDaoTableDef::SetName

void SetName( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A pointer to a string expression that specifies a name for a table.

Remarks

Call this member function to set a user-defined name for a table. The name must start with a letter and can contain a maximum of 64 characters. It can include numbers and underscore characters but cannot include punctuation or spaces.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "Name Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::RefreshLink, CDaoTableDef::SetConnect


CDaoTableDef::SetSourceTableName

void SetSourceTableName( LPCTSTR lpszSrcTableName );
throw( CDaoException, CMemoryException );

Parameters

lpszSrcTableName

A pointer to a string expression that specifies a table name in the external database. For a base table, the setting is an empty string ("").

Remarks

Call this member function to specify the name of an attached table or the name of the base table on which the CDaoTableDef object is based, as it exists in the original source of the data. You must then call RefreshLink. This property setting is empty for a base table and read/write for an attached table or an object not appended to a collection.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "SourceTableName Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::RefreshLink, CDaoTableDef::GetSourceTableName


CDaoTableDef::SetValidationRule

void SetValidationRule( LPCTSTR lpszValidationRule );
throw( CDaoException, CMemoryException );

Parameters

lpszValidationRule

A pointer to a string expression that validates an operation.

Remarks

Call this member function to set a validation rule for a tabledef. Validation rules are used in connection with update operations. If a tabledef contains a validation rule, updates to that tabledef must match predetermined criteria before the data is changed. If the change does not match the criteria, an exception containing the text of GetValidationText is displayed.

Validation is supported only for databases that use the Microsoft Jet database engine. The expression cannot refer to user-defined functions, domain aggregate functions, SQL aggregate functions, or queries. A validation rule for a CDaoTableDef object can refer to multiple fields in that object.

For example, for fields named hire_date and termination_date, a validation rule might be:

CString strRule = _T(“termination_date>hire_date”);
MyRs.SetValidationRule(strRule);

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "ValidationRule Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::GetValidationText, CDaoTableDef::SetValidationText, CDaoTableDef::GetValidationRule


CDaoTableDef::SetValidationText

void SetValidationText( LPCTSTR lpszValidationText );
throw( CDaoException, CMemoryException );

Parameters

lpszValidationText

A pointer to a string expression that specifies the text displayed if entered data is invalid.

Remarks

Call this member function to set the exception text of a validation rule for a CDaoTableDef object with an underlying base table supported by the Microsoft Jet database engine. You cannot set the validation text of an attached table.

For more information on tabledefs, see the articles DAO Tabledef and DAO Tabledef: Using Tabledefs in Visual C++ Programmer's Guide. For related information, see the topic "ValidationText Property" in DAO Help.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::SetValidationRule, CDaoTableDef::GetValidationText, CDaoTableDef::GetValidationRule


CDaoTableDef::m_pDatabase

Remarks

Contains a pointer to the CDaoDatabase object for this table.

For more information on accessing underlying DAO objects, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::m_pDAOTableDef


CDaoTableDef::m_pDAOTableDef

Remarks

Contains a pointer to the OLE interface for the DAO tabledef object underlying the CDaoTableDef object. Use this pointer if you need to access the DAO interface directly.

For more information on accessing underlying DAO objects, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

CDaoTableDef Overview | Class Members | Hierarchy Chart

See Also CDaoTableDef::m_pDatabase


CDaoWorkspace

A CDaoWorkspace object manages a named, password-protected database session from login to logoff, by a single user. In most cases, you will not need multiple workspaces, and you will not need to create explicit workspace objects; when you open database and recordset objects, they use DAO’s default workspace. However, if needed, you can run multiple sessions at a time by creating additional workspace objects. Each workspace object can contain multiple open database objects in its own Databases collection. In MFC, a workspace is primarily a transaction manager, specifying a set of open databases all in the same “transaction space.”

Note The DAO database classes are distinct from the MFC database classes based on Open Database Connectivity (ODBC). All DAO database class names have a “CDao” prefix. In general, the MFC classes based on DAO are more capable than the MFC classes based on ODBC. The DAO-based classes access data through the Microsoft Jet database engine, including ODBC drivers. They also support Data Definition Language (DDL) operations, such as creating databases and adding tables and fields via the classes, without having to call DAO directly.

Capabilities

Class CDaoWorkspace provides the following:

  • Explicit access, if needed, to a default workspace, created by initializing the database engine. Usually you use DAO’s default workspace implicitly by creating database and recordset objects.

  • A transaction space in which transactions apply to all databases open in the workspace. You can create additional workspaces to manage separate transaction spaces.

  • An interface to many properties of the underlying Microsoft Jet database engine (see the static member functions). Opening or creating a workspace, or calling a static member function before open or create, initializes the database engine.

  • Access to the database engine’s Workspaces collection, which stores all active workspaces that have been appended to it. You can also create and work with workspaces without appending them to the collection.

Security

MFC does not implement the Users and Groups collections in DAO, which are used for security control. If you need those aspects of DAO, you must program them yourself via direct calls to DAO interfaces. For information, see Technical Note 54.

Usage

You can use class CDaoWorkspace to:

  • Explicitly open the default workspace.

    Usually your use of the default workspace is implicit — when you open new CDaoDatabase or CDaoRecordset objects. But you might need to access it explicitly — for example, to access database engine properties or the Workspaces collection. See “Implicit Use of the Default Workspace” below.

  • Create new workspaces. Call Append if you want to add them to the Workspaces collection.

  • Open an existing workspace in the Workspaces collection.

Creating a new workspace that does not already exist in the Workspaces collection is described under the Create member function. Workspace objects do not persist in any way between datababase engine sessions. If your application links MFC statically, ending the application uninitializes the database engine. If your application links with MFC dynamically, the database engine is uninitialized when the MFC DLL is unloaded.

Feature Only in Professional and Enterprise Editions Static linking to MFC is supported only in Visual C++ Professional and Enterprise Editions. For more information, see Visual C++ Editions.

Explicitly opening the default workspace, or opening an existing workspace in the Workspaces collection, is described under the Open member function.

End a workspace session by closing the workspace with the Close member function. Close closes any databases you have not closed previously, rolling back any uncommitted transactions.

Transactions

DAO manages transactions at the workspace level; hence, transactions on a workspace with multiple open databases apply to all of the databases. For example, if two databases have uncommitted updates and you call CommitTrans, all of the updates are committed. If you want to limit transactions to a single database, you need a separate workspace object for it.

Implicit Use of the Default Workspace

MFC uses DAO’s default workspace implicitly under the following circumstances:

  • If you create a new CDaoDatabase object but do not do so through an existing CDaoWorkspace object, MFC creates a temporary workspace object for you, which corresponds to DAO’s default workspace. If you do so for multiple databases, all of the database objects are associated with the default workspace. You can access a database’s workspace through a CDaoDatabase data member.

  • Similarly, if you create a CDaoRecordset object without supplying a pointer to a CDaoDatabase object, MFC creates a temporary database object and, by extension, a temporary workspace object. You can access a recordset’s database, and indirectly its workspace, through a CDaoRecordset data member.

Other Operations

Other database operations are also provided, such as repairing a corrupted database or compacting a database.

For more about CDaoWorkspace, see the article DAO Workspace. For information about calling DAO directly and about DAO security, see Technical Note 54. For more about working with ODBC data sources through DAO, see the article DAO External: Working with External Data Sources. For information about the database engine, see the article DAO Workspace: The Database Engine. All articles are in Visual C++ Programmer's Guide. The MFC Database sample DAOVIEW illustrates using CDaoWorkspace.

#include <afxdao.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample DAOVIEW

See Also CDaoDatabase, CDaoRecordset, CDaoTableDef, CDaoQueryDef, CDaoException


CDaoWorkspace Class Members

Data Members

m_pDAOWorkspace Points to the underlying DAO workspace object.

Construction

CDaoWorkspace Constructs a workspace object. Afterwards, call Create or Open.

Attributes

GetIsolateODBCTrans | Returns a value that indicates whether multiple transactions that involve the same ODBC data source are isolated via forced multiple connections to the data source.
GetName | Returns the user-defined name for the workspace object.
GetUserName | Returns the user name specified when the workspace was created. This is the name of the workspace owner.
IsOpen | Returns nonzero if the workspace is open.
SetIsolateODBCTrans | Specifies whether multiple transactions that involve the same ODBC data source are isolated by forcing multiple connections to the data source.

Operations

Append | Appends a newly created workspace to the database engine’s Workspaces collection.
BeginTrans | Begins a new transaction, which applies to all databases open in the workspace.
Close | Closes the workspace and all of the objects it contains. Pending transactions are rolled back.
CommitTrans | Completes the current transaction and saves the changes.
CompactDatabase | Compacts (or duplicates) a database.
Create | Creates a new DAO workspace object.
GetDatabaseCount | Returns the number of DAO database objects in the workspace’s Databases collection.
GetDatabaseInfo | Returns information about a specified DAO database defined in the workspace’s Databases collection.
GetWorkspaceCount | Returns the number of DAO workspace objects in the database engine’s Workspaces collection.
GetWorkspaceInfo | Returns information about a specified DAO workspace defined in the database engine’s Workspaces collection.
Open | Explicitly opens a workspace object associated with DAO’s default workspace.
RepairDatabase | Attempts to repair a damaged database.
Rollback | Ends the current transaction and does not save the changes.
Idle | Allows the database engine to perform background tasks.

Database Engine Properties

GetVersion | Returns a string that contains the version of the database engine associated with the workspace.
GetIniPath | Returns the location of the Microsoft Jet database engine’s initialization settings in the Windows registry.
GetLoginTimeout | Returns the number of seconds before an error occurs when the user attempts to log in to an ODBC database.
SetDefaultPassword | Sets the password that the database engine uses when a workspace object is created without a specific password.
SetDefaultUser | Sets the user name that the database engine uses when a workspace object is created without a specific user name.
SetIniPath | Sets the location of the Microsoft Jet database engine’s initialization settings in the Windows registry.
SetLoginTimeout | Sets the number of seconds before an error occurs when the user attempts to log in to an ODBC data source.


CDaoWorkspace::Append

void Append( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function after you call Create. Append appends a newly created workspace object to the database engine’s Workspaces collection. Workspaces do not persist between database engine sessions; they are stored only in memory, not on disk. You do not have to append a workspace; if you do not, you can still use it.

An appended workspace remains in the Workspaces collection, in an active, open state, until you call its Close member function.

For more information about workspaces, see the article DAO Workspace. For more information about the database engine, see the article DAO Workspace: The Database Engine. Both articles are in Visual C++ Programmer's Guide. For related information, see the topic "Append Method" in DAO Help.


CDaoWorkspace::BeginTrans

void BeginTrans( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to initiate a transaction. After you call BeginTrans, updates you make to your data or database structure take effect when you commit the transaction. Because the workspace defines a single transaction space, the transaction applies to all open databases in the workspace. There are two ways to complete the transaction:

  • Call the CommitTrans member function to commit the transaction and save changes to the data source.

  • Or call the Rollback member function to cancel the transaction.

Closing the workspace object or a database object while a transaction is pending rolls back all pending transactions.

If you need to isolate transactions on one ODBC data source from those on another ODBC data source, see the SetIsolateODBCTrans member function.

For information about transactions, see the article DAO Workspace: Managing Transactions. For more information about workspaces, see the article DAO Workspace. Both articles are in Visual C++ Programmer's Guide.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::GetIsolateODBCTrans, CDaoWorkspace::CommitTrans, CDaoWorkspace::Rollback


CDaoWorkspace::CDaoWorkspace

CDaoWorkspace( );

Remarks

Constructs a CDaoWorkspace object. After constructing the C++ object, you have two options:

  • Call the object’s Open member function to open the default workspace or to open an existing object in the Workspaces collection.

  • Or call the object’s Create member function to create a new DAO workspace object. This explicitly starts a new workspace session, which you can refer to via the CDaoWorkspace object. After calling Create, you can call Append if you want to add the workspace to the database engine’s Workspaces collection.

See the class overview for CDaoWorkspace for information about when you need to explicitly create a CDaoWorkspace object. Usually, you use workspaces created implicitly when you open a CDaoDatabase object without specifying a workspace or when you open a CDaoRecordset object without specifying a database object. MFC DAO objects created in this way use DAO’s default workspace, which is created once and reused.

To release a workspace and its contained objects, call the workspace object’s Close member function.

For more information about workspaces, see the article DAO Workspace. For more information about implicit workspace creation, see the article DAO: Accessing Implicit MFC DAO Objects. Both articles are in Visual C++ Programmer's Guide.


CDaoWorkspace::Close

virtual void Close( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to close the workspace object. Closing an open workspace object releases the underlying DAO object and, if the workspace is a member of the Workspaces collection, removes it from the collection. Calling Close is good programming practice.

CAUTION Closing a workspace object closes any open databases in the workspace. This results in any recordsets open in the databases being closed as well, and any pending edits or updates are rolled back. For related information, see the CDaoDatabase::Close, CDaoRecordset::Close, CDaoTableDef::Close, and CDaoQueryDef::Close member functions.

Workspace objects are not permanent; they only exist while references to them exist. This means that when the database engine session ends, the workspace and its Databases collection do not persist. You must re-create them for the next session by opening your workspace and database(s) again.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide. For related information, see the topic "Close Method" in DAO Help.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::Open


CDaoWorkspace::CommitTrans

void CommitTrans( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to commit a transaction — save a group of edits and updates to one or more databases in the workspace. A transaction consists of a series of changes to the database’s data or its structure, beginning with a call to BeginTrans. When you complete the transaction, either commit it or roll it back (cancel the changes) with Rollback. By default, without transactions, updates to records are committed immediately. Calling BeginTrans causes commitment of updates to be delayed until you call CommitTrans.

CAUTION Within one workspace, transactions are always global to the workspace and are not limited to only one database or recordset. If you perform operations on more than one database or recordset within a workspace transaction, CommitTrans commits all pending updates, and Rollback restores all operations on those databases and recordsets.

When you close a database or workspace with pending transactions, the transactions are all rolled back.

Note This is not a two-phase commit mechanism. If one update fails to commit, others still will commit.

For more information about workspaces, see the article DAO Workspace. For more about transactions, including information about separate transaction spaces, see the article DAO Workspace: Managing Transactions. Both articles are in Visual C++ Programmer's Guide.


CDaoWorkspace::CompactDatabase

static void PASCAL CompactDatabase( LPCTSTR lpszSrcName, LPCTSTR lpszDestName, LPCTSTR lpszLocale = dbLangGeneral, int nOptions = 0 );
throw( CDaoException, CMemoryException );

static void PASCAL CompactDatabase( LPCTSTR lpszSrcName, LPCTSTR lpszDestName, LPCTSTR lpszLocale, int nOptions, LPCTSTR lpszPassword );
throw( CDaoException, CMemoryException );

Parameters

lpszSrcName

The name of an existing, closed database. It can be a full path and filename, such as “C:\\MYDB.MDB”. If the filename has an extension, you must specify it. If your network supports the uniform naming convention (UNC), you can also specify a network path, such as “\\\\MYSERVER\\MYSHARE\\MYDIR\\MYDB.MDB”. (Double backslashes are required in the path strings because “\” is the C++ escape character.)

lpszDestName

The full path of the compacted database that you are creating. You can also specify a network path as with lpszSrcName. You cannot use the lpszDestName argument to specify the same database file as lpszSrcName.

lpszPassword

A password, used when you want to compact a password-protected database. Note that if you use the version of CompactDatabase that takes a password, you must supply all parameters. Also, because this is a connect parameter, it requires special formatting, as follows: ;PWD=lpszPassword. For example: ;PWD=“Happy”. (The leading semicolon is required.)

lpszLocale

A string expression used to specify collating order for creating lpszDestName. If you omit this argument by accepting the default value of dbLangGeneral (see below), the locale of the new database is the same as that of the old database. Possible values are:

  • dbLangGeneral English, German, French, Portuguese, Italian, and Modern Spanish

  • dbLangArabic Arabic

  • dbLangCyrillic Russian

  • dbLangCzech Czech

  • dbLangDutch Dutch

  • dbLangGreek Greek

  • dbLangHebrew Hebrew

  • dbLangHungarian Hungarian

  • dbLangIcelandic Icelandic

  • dbLangNordic Nordic languages (Microsoft Jet database engine version 1.0 only)

  • dbLangNorwdan Norwegian and Danish

  • dbLangPolish Polish

  • dbLangSpanish Traditional Spanish

  • dbLangSwedfin Swedish and Finnish

  • dbLangTurkish Turkish

nOptions

Indicates one or more options for the target database, lpszDestName. If you omit this argument by accepting the default value, the lpszDestName will have the same encryption and the same version as lpszSrcName. You can combine the dbEncrypt or dbDecrypt option with one of the version options using the bitwise-OR operator. Possible values, which specify a database format, not a database engine version, are:

  • dbEncrypt Encrypt the database while compacting.

  • dbDecrypt Decrypt the database while compacting.

  • dbVersion10 Create a database that uses the Microsoft Jet database engine version 1.0 while compacting.

  • dbVersion11 Create a database that uses the Microsoft Jet database engine version 1.1 while compacting.

  • dbVersion20 Create a database that uses the Microsoft Jet database engine version 2.0 while compacting.

  • dbVersion30 Create a database that uses the Microsoft Jet database engine version 3.0 while compacting.

    You can use dbEncrypt or dbDecrypt in the options argument to specify whether to encrypt or to decrypt the database as it is compacted. If you omit an encryption constant or if you include both dbDecrypt and dbEncrypt, lpszDestName will have the same encryption as lpszSrcName. You can use one of the version constants in the options argument to specify the version of the data format for the compacted database. This constant affects only the version of the data format of lpszDestName. You can specify only one version constant. If you omit a version constant, lpszDestName will have the same version as lpszSrcName. You can compact lpszDestName only to a version that is the same or later than that of lpszSrcName.

    CAUTION If a database is not encrypted, it is possible, even if you implement user/password security, to directly read the binary disk file that constitutes the database.

Remarks

Call this member function to compact a specified Microsoft Jet (.MDB) database. As you change data in a database, the database file can become fragmented and use more disk space than necessary. Periodically, you should compact your database to defragment the database file. The compacted database is usually smaller. You can also choose to change the collating order, the encryption, or the version of the data format while you copy and compact the database.

! WARNING The CompactDatabase member function will not correctly convert a complete Microsoft Access database from one version to another. Only the data format is converted. Microsoft Access-defined objects, such as forms and reports, are not converted. However, the data is correctly converted.

Tip You can also use CompactDatabase to copy a database file.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide. For more information about compacting databases, see the topic "CompactDatabase Method" in DAO Help.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::RepairDatabase


CDaoWorkspace::Create

virtual void Create( LPCTSTR lpszName, LPCTSTR lpszUserName, LPCTSTR lpszPassword );
throw( CDaoException, CMemoryException );

Parameters

lpszName

A string with up to 14 characters that uniquely names the new workspace object. You must supply a name. For related information, see the topic "Name Property" in DAO Help.

lpszUserName

The user name of the workspace’s owner. For requirements, see the lpszDefaultUser parameter to the SetDefaultUser member function. For related information, see the topic "UserName Property" in DAO Help.

lpszPassword

The password for the new workspace object. A password can be up to 14 characters long and can contain any character except ASCII 0 (null). Passwords are case-sensitive. For related information, see the topic "Password Property" in DAO Help.

Remarks

Call this member function to create a new DAO workspace object and associate it with the MFC CDaoWorkspace object. The overall creation process is:

  1. Construct a CDaoWorkspace object.

  2. Call the object’s Create member function to create the underlying DAO workspace. You must specify a workspace name.

  3. Optionally call Append if you want to add the workspace to the database engine’s Workspaces collection. You can work with the workspace without appending it.

After the Create call, the workspace object is in an open state, ready for use. You do not call Open after Create. You do not call Create if the workspace already exists in the Workspaces collection. Create initializes the database engine if it has not already been initialized for your application.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::CDaoWorkspace, CDaoWorkspace::Close, CDaoWorkspace::Open


CDaoWorkspace::GetDatabaseCount

short GetDatabaseCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of open databases in the workspace.

Remarks

Call this member function to retrieve the number of DAO database objects in the workspace’s Databases collection — the number of open databases in the workspace. GetDatabaseCount is useful if you need to loop through all defined databases in the workspace’s Databases collection. To obtain information about a given database in the collection, see GetDatabaseInfo. Typical usage is to call GetDatabaseCount for the number of open databases, then use that number as a loop index for repeated calls to GetDatabaseInfo.

For more information about obtaining database information, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.


CDaoWorkspace::GetDatabaseInfo

void GetDatabaseInfo( int nIndex, CDaoDatabaseInfo& dbinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetDatabaseInfo( LPCTSTR lpszName, CDaoDatabaseInfo& dbinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The zero-based index of the database object in the workspace’s Databases collection, for lookup by index.

dbinfo

A reference to a CDaoDatabaseInfo object that returns the information requested.

dwInfoOptions

Options that specify which information about the database to retrieve. The available options are listed here along with what they cause the function to return:

  • AFX_DAO_PRIMARY_INFO (Default) Name, Updatable, Transactions

  • AFX_DAO_SECONDARY_INFO Primary information plus: Version, Collating Order, Query Timeout

  • AFX_DAO_ALL_INFO Primary and secondary information plus: Connect

lpszName

The name of the database object, for lookup by name. The name is a string with up to 14 characters that uniquely names the new workspace object.

Remarks

Call this member function to obtain various kinds of information about a database open in the workspace. One version of the function lets you look up a database by index. The other version lets you look up a database by name.

For a description of the information returned in dbinfo, see the CDaoDatabaseInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. When you request information at one level, you get information for any prior levels as well.

For more information about obtaining database information, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::GetDatabaseCount


CDaoWorkspace::GetIniPath

static CString PASCAL GetIniPath( );
throw( CDaoException, CMemoryException );

Return Value

A CString containing the registry location.

Remarks

Call this member function to obtain the location of the Microsoft Jet database engine’s initialization settings in the Windows registry. You can use the location to obtain information about settings for the database engine. The information returned is actually the name of a registry subkey.

For more information about the database engine, see the article DAO Workspace: The Database Engine in Visual C++ Programmer's Guide. For related information, see the topics "IniPath Property" and "Customizing Windows Registry Settings for Data Access" in DAO Help.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::SetIniPath, CDaoWorkspace::GetVersion


CDaoWorkspace::GetIsolateODBCTrans

BOOL GetIsolateODBCTrans( );
throw( CDaoException, CMemoryException );

Return Value

Nonzero if ODBC transactions are isolated; otherwise 0.

Remarks

Call this member function to get the current value of the DAO IsolateODBCTrans property for the workspace. In some situations, you might need to have multiple simultaneous transactions pending on the same ODBC database. To do this, you need to open a separate workspace for each transaction. Keep in mind that although each workspace can have its own ODBC connection to the database, this slows system performance. Because transaction isolation is not normally required, ODBC connections from multiple workspace objects opened by the same user are shared by default.

Some ODBC servers, such as Microsoft SQL Server, do not allow simultaneous transactions on a single connection. If you need to have more than one transaction at a time pending against such a database, set the IsolateODBCTrans property to TRUE on each workspace as soon as you open it. This forces a separate ODBC connection for each workspace.

For more information about workspaces, see the article DAO Workspace. For more information about working with ODBC data sources through DAO, see the article DAO External: Working with External Data Sources. Both articles are in Visual C++ Programmer's Guide. For related information, see the topic "IsolateODBCTrans Property" in DAO Help.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::SetIsolateODBCTrans


CDaoWorkspace::GetLoginTimeout

static short PASCAL GetLoginTimeout( );
throw( CDaoException, CMemoryException );

Return Value

The number of seconds before an error occurs when you attempt to log in to an ODBC database.

Remarks

Call this member function to get the current value of the DAO LoginTimeout property for the workspace. This value represents the number of seconds before an error occurs when you attempt to log in to an ODBC database. The default LoginTimeout setting is 20 seconds. When LoginTimeout is set to 0, no timeout occurs and the communication with the data source might hang.

When you are attempting to log in to an ODBC database, such as Microsoft SQL Server, the connection may fail as a result of network errors or because the server is not running. Rather than waiting for the default 20 seconds to connect, you can specify how long the database engine waits before it produces an error. Logging in to the server happens implicitly as part of a number of different events, such as running a query on an external server database.

For more information about workspaces, see the article DAO Workspace. For more information about working with ODBC data sources through DAO, see the article DAO External: Working with External Data Sources. Both articles are in Visual C++ Programmer's Guide. For related information, see the topic "LoginTimeout Property" in DAO Help.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::SetLoginTimeout


CDaoWorkspace::GetName

CString GetName( );
throw( CDaoException, CMemoryException );

Return Value

A CString containing the user-defined name of the DAO workspace object.

Remarks

Call this member function to get the user-defined name of the DAO workspace object underlying the CDaoWorkspace object. The name is useful for accessing the DAO workspace object in the database engine’s Workspaces collection by name.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide. For related information, see the topic "Name Property" in DAO Help.


CDaoWorkspace::GetUserName

CString GetUserName( );
throw( CDaoException, CMemoryException );

Return Value

A CString that represents the owner of the workspace object.

Remarks

Call this member function to obtain the name of the owner of the workspace.

To get or set the permissions for the workspace owner, call DAO directly to check the Permissions property setting; this determines what permissions that user has. To work with permissions, you need a SYSTEM.MDA file.

For more information about workspaces, see the article DAO Workspace. For information about calling DAO directly, see Technical Note 54. For related information, see the topic "UserName Property" in DAO Help.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::SetDefaultUser


CDaoWorkspace::GetVersion

static CString PASCAL GetVersion( );
throw( CDaoException, CMemoryException );

Return Value

A CString that indicates the version of the database engine associated with the object.

Remarks

Call this member function to determine the version of the Microsoft Jet database engine in use. The value returned represents the version number in the form “major.minor”; for example, “3.0”. The product version number (for example, 3.0) consists of the version number (3), a period, and the release number (0).

For more information about obtaining workspace information, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide. For related information, see the topic "Version Property" in DAO Help.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoDatabase::GetVersion


CDaoWorkspace::GetWorkspaceCount

short GetWorkspaceCount( );
throw( CDaoException, CMemoryException );

Return Value

The number of open workspaces in the Workspaces collection.

Remarks

Call this member function to retrieve the number of DAO workspace objects in the database engine’s Workspaces collection. This count does not include any open workspaces not appended to the collection. GetWorkspaceCount is useful if you need to loop through all defined workspaces in the Workspaces collection. To obtain information about a given workspace in the collection, see GetWorkspaceInfo. Typical usage is to call GetWorkspaceCount for the number of open workspaces, then use that number as a loop index for repeated calls to GetWorkspaceInfo.

For more information about obtaining workspace information, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.


CDaoWorkspace::GetWorkspaceInfo

void GetWorkspaceInfo( int nIndex, CDaoWorkspaceInfo& wkspcinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

void GetWorkspaceInfo( LPCTSTR lpszName, CDaoWorkspaceInfo& wkspcinfo, DWORD dwInfoOptions = AFX_DAO_PRIMARY_INFO );
throw( CDaoException, CMemoryException );

Parameters

nIndex

The zero-based index of the database object in the Workspaces collection, for lookup by index.

wkspcinfo

A reference to a CDaoWorkspaceInfo object that returns the information requested.

dwInfoOptions

Options that specify which information about the workspace to retrieve. The available options are listed here along with what they cause the function to return:

  • AFX_DAO_PRIMARY_INFO (Default) Name

  • AFX_DAO_SECONDARY_INFO Primary information plus: User Name

  • AFX_DAO_ALL_INFO Primary and secondary information plus: Isolate ODBCTrans

lpszName

The name of the workspace object, for lookup by name. The name is a string with up to 14 characters that uniquely names the new workspace object.

Remarks

Call this member function to obtain various kinds of information about a workspace open in the session. For a description of the information returned in wkspcinfo, see the CDaoWorkspaceInfo structure. This structure has members that correspond to the items of information listed above in the description of dwInfoOptions. When you request information at one level, you get information for prior levels as well.

For more information about obtaining workspace information, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::GetWorkspaceCount


CDaoWorkspace::Idle

static void PASCAL Idle( int nAction = dbFreeLocks );
throw( CDaoException, CMemoryException );

Parameters

nAction

An action to take during the idle processing. Currently the only valid action is dbFreeLocks.

Remarks

Call Idle to provide the database engine with the opportunity to perform background tasks that may not be up-to-date because of intense data processing. This is often true in multiuser, multitasking environments in which there is not enough background processing time to keep all records in a recordset current.

Important Calling Idle is not necessary with databases created with version 3.0 of the Microsoft Jet database engine. Use Idle only for databases created with earlier versions.

Usually, read locks are removed and data in local dynaset-type recordset objects is updated only when no other actions (including mouse movements) are occurring. If you periodically call Idle, you provide the database engine with time to catch up on background processing tasks by releasing unneeded read locks. Specifying the dbFreeLocks constant as an argument delays processing until all read locks are released.

This member function is not needed in single-user environments unless multiple instances of an application are running. The Idle member function may increase performance in a multiuser environment because it forces the database engine to flush data to disk, releasing locks on memory. You can also release read locks by making operations part of a transaction.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide. For related information, see the topic "Idle Method" in DAO Help.


CDaoWorkspace::IsOpen

BOOL IsOpen( ) const;

Return Value

Nonzero if the workspace object is open; otherwise 0.

Remarks

Call this member function to determine whether the CDaoWorkspace object is open — that is, whether the MFC object has been initialized by a call to Open or a call to Create. You can call any of the member functions of a workspace that is in an open state.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide.


CDaoWorkspace::Open

virtual void Open( LPCTSTR lpszName = NULL );
throw( CDaoException, CMemoryException );

Parameters

lpszName

The name of the DAO workspace object to open — a string with up to 14 characters that uniquely names the workspace. Accept the default value NULL to explicitly open the default workspace. For naming requirements, see the lpszName parameter for Create. For related information, see the topic "Name Property" in DAO Help.

Remarks

After constructing a CDaoWorkspace object, call this member function to do one of the following:

  • Explicitly open the default workspace. Pass NULL for lpszName.

  • Open an existing CDaoWorkspace object, a member of the Workspaces collection, by name. Pass a valid name for an existing workspace object.

Open puts the workspace object into an open state and also initializes the database engine if it has not already been initialized for your application.

Although many CDaoWorkspace member functions can only be called after the workspace has been opened, the following member functions, which operate on the database engine, are available after construction of the C++ object but before a call to Open:

Create | GetVersion | SetDefaultUser
GetIniPath | Idle | SetIniPath
GetLoginTimeout | SetDefaultPassword | SetLoginTimeout

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::IsOpen, CDaoWorkspace::CDaoWorkspace, CDaoWorkspace::Create, CDaoWorkspace::Close


CDaoWorkspace::RepairDatabase

static void PASCAL RepairDatabase( LPCTSTR lpszName );
throw( CDaoException, CMemoryException );

Parameters

lpszName

The path and filename for an existing Microsoft Jet engine database file. If you omit the path, only the current directory is searched. If your system supports the uniform naming convention (UNC), you can also specify a network path, such as: “\\\\MYSERVER\\MYSHARE\\MYDIR\\MYDB.MDB”. (Double backslashes are required in the path string because “\” is the C++ escape character.)

Remarks

Call this member function if you need to attempt to repair a corrupted database that accesses the Microsoft Jet database engine. You must close the database specified by lpszName before you repair it. In a multiuser environment, other users cannot have lpszName open while you are repairing it. If lpszName is not closed or is not available for exclusive use, an error occurs.

This member function attempts to repair a database that was marked as possibly corrupt by an incomplete write operation. This can occur if an application using the Microsoft Jet database engine is closed unexpectedly because of a power outage or computer hardware problem. If you complete the operation and call the Close member function or you quit the application in a usual way, the database will not be marked as possibly corrupt.

Note After repairing a database, it is also a good idea to compact it using the CompactDatabase member function to defragment the file and to recover disk space.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide. For more information about repairing databases, see the topic "RepairDatabase Method" in DAO Help.


CDaoWorkspace::Rollback

void Rollback( );
throw( CDaoException, CMemoryException );

Remarks

Call this member function to end the current transaction and restore all databases in the workspace to their condition before the transaction was begun.

CAUTION Within one workspace object, transactions are always global to the workspace and are not limited to only one database or recordset. If you perform operations on more than one database or recordset within a workspace transaction, Rollback restores all operations on all of those databases and recordsets.

If you close a workspace object without saving or rolling back any pending transactions, the transactions are automatically rolled back. If you call CommitTrans or Rollback without first calling BeginTrans, an error occurs.

Note When you begin a transaction, the database engine records its operations in a file kept in the directory specified by the TEMP environment variable on the workstation. If the transaction log file exhausts the available storage on your TEMP drive, the database engine will cause MFC to throw a CDaoException (DAO error 2004). At this point, if you call CommitTrans, an indeterminate number of operations are committed but the remaining uncompleted operations are lost, and the operation has to be restarted. Calling Rollback releases the transaction log and rolls back all operations in the transaction.

For more information about workspaces, see the article DAO Workspace. For more about transactions, see the article DAO Workspace: Managing Transactions. Both articles are in Visual C++ Programmer's Guide.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoRecordset


CDaoWorkspace::SetDefaultPassword

static void PASCAL SetDefaultPassword( LPCTSTR lpszPassword );
throw( CDaoException, CMemoryException );

Parameters

lpszPassword

The default password. A password can be up to 14 characters long and can contain any character except ASCII 0 (null). Passwords are case-sensitive.

Remarks

Call this member function to set the default password that the database engine uses when a workspace object is created without a specific password. The default password that you set applies to new workspaces you create after the call. When you create subsequent workspaces, you do not need to specify a password in the Create call.

To use this member function:

  1. Construct a CDaoWorkspace object but do not call Create.

  2. Call SetDefaultPassword and, if you like, SetDefaultUser.

  3. Call Create for this workspace object or subsequent ones, without specifying a password.

By default, the DefaultUser property is set to “admin” and the DefaultPassword property is set to an empty string ("").

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide. For more about security, see the topic "Permissions Property" in DAO Help. For related information, see the topics "DefaultPassword Property" and "DefaultUser Property" in DAO Help.


CDaoWorkspace::SetDefaultUser

static void PASCAL SetDefaultUser( LPCTSTR lpszDefaultUser );
throw( CDaoException, CMemoryException );

Parameters

lpszDefaultUser

The default user name. A user name can be 1 – 20 characters long and include alphabetic characters, accented characters, numbers, spaces, and symbols except for: " (quotation marks), / (forward slash), \ (backslash), [ ] (brackets), : (colon), | (pipe), < (less-than sign), > (greater-than sign), + (plus sign), = (equal sign), ; (semicolon), , ( comma), ? (question mark), * (asterisk), leading spaces, and control characters (ASCII 00 to ASCII 31). For related information, see the topic "UserName Property" in DAO Help.

Remarks

Call this member function to set the default user name that the database engine uses when a workspace object is created without a specific user name. The default user name that you set applies to new workspaces you create after the call. When you create subsequent workspaces, you do not need to specify a user name in the Create call.

To use this member function:

  1. Construct a CDaoWorkspace object but do not call Create.

  2. Call SetDefaultUser and, if you like, SetDefaultPassword.

  3. Call Create for this workspace object or subsequent ones, without specifying a user name.

By default, the DefaultUser property is set to “admin” and the DefaultPassword property is set to an empty string ("").

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide. For related information, see the topics "DefaultUser Property" and "DefaultPassword Property" in DAO Help.


CDaoWorkspace::SetIniPath

static void PASCAL SetIniPath( LPCTSTR lpszRegistrySubkey );
throw( CDaoException, CMemoryException );

Parameters

lpszRegistrySubkey

A string containing the name of a Windows registry subkey for the location of Microsoft Jet database engine settings or parameters needed for installable ISAM databases.

Remarks

Call this member function to specify the location of Windows registry settings for the Microsoft Jet database engine. Call SetIniPath only if you need to specify special settings. For more information, see the topic "IniPath Property" in DAO Help.

Important Call SetIniPath during application installation, not when the application runs. SetIniPath must be called before you open any workspaces, databases, or recordsets; otherwise, MFC throws an exception.

You can use this mechanism to configure the database engine with user-provided registry settings. The scope of this attribute is limited to your application and cannot be changed without restarting your application.

For more information about workspaces, see the article DAO Workspace in Visual C++ Programmer's Guide.


CDaoWorkspace::SetIsolateODBCTrans

void SetIsolateODBCTrans( BOOL bIsolateODBCTrans );
throw( CDaoException, CMemoryException );

Parameters

bIsolateODBCTrans

Pass TRUE if you want to begin isolating ODBC transactions. Pass FALSE if you want to stop isolating ODBC transactions.

Remarks

Call this member function to set the value of the DAO IsolateODBCTrans property for the workspace. In some situations, you might need to have multiple simultaneous transactions pending on the same ODBC database. To do this, you need to open a separate workspace for each transaction. Although each workspace can have its own ODBC connection to the database, this slows system performance. Because transaction isolation is not normally required, ODBC connections from multiple workspace objects opened by the same user are shared by default.

Some ODBC servers, such as Microsoft SQL Server, do not allow simultaneous transactions on a single connection. If you need to have more than one transaction at a time pending against such a database, set the IsolateODBCTrans property to TRUE on each workspace as soon as you open it. This forces a separate ODBC connection for each workspace.

For more information about workspaces, see the article DAO Workspace. For more about transactions, see the article DAO Workspace: Managing Transactions. For more about working with ODBC data sources through DAO, see the article DAO External: Working with External Data Sources. All articles are in Visual C++ Programmer's Guide.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::GetIsolateODBCTrans


CDaoWorkspace::SetLoginTimeout

static void PASCAL SetLoginTimeout( short nSeconds );
throw( CDaoException, CMemoryException );

Parameters

nSeconds

The number of seconds before an error occurs when you attempt to log in to an ODBC database.

Remarks

Call this member function to set the value of the DAO LoginTimeout property for the workspace. This value represents the number of seconds before an error occurs when you attempt to log in to an ODBC database. The default LoginTimeout setting is 20 seconds. When LoginTimeout is set to 0, no timeout occurs and the communication with the data source might hang.

When you are attempting to log in to an ODBC database, such as Microsoft SQL Server, the connection may fail as a result of network errors or because the server is not running. Rather than waiting for the default 20 seconds to connect, you can specify how long the database engine waits before it produces an error. Logging on to the server happens implicitly as part of a number of different events, such as running a query on an external server database. The timeout value is determined by the current setting of the LoginTimeout property.

For more information about workspaces, see the article DAO Workspace. For more information about working with ODBC data sources through DAO, see the article DAO External: Working with External Data Sources. Both articles are in Visual C++ Programmer's Guide. For related information, see the topic "LoginTimeout Property" in DAO Help.

CDaoWorkspace Overview | Class Members | Hierarchy Chart

See Also CDaoWorkspace::GetLoginTimeout


CDaoWorkspace::m_pDAOWorkspace

Remarks

A pointer to the underlying DAO workspace object. Use this data member if you need direct access to the underlying DAO object. You can call the DAO object’s interfaces through this pointer.

For information about accessing DAO objects directly, see Technical Note 54.


CDatabase

A CDatabase object represents a connection to a data source, through which you can operate on the data source. A data source is a specific instance of data hosted by some database management system (DBMS). Examples include Microsoft SQL Server, Microsoft Access, Borland® dBASE®, and xBASE. You can have one or more CDatabase objects active at a time in your application.

Note If you are working with the Data Access Objects (DAO) classes rather than the Open Database Connectivity (ODBC) classes, use class CDaoDatabase instead. For more information, see the articles Database Topics (General) and DAO and MFC. Both articles are in Visual C++ Programmer's Guide.

To use CDatabase, construct a CDatabase object and call its OpenEx member function. This opens a connection. When you then construct CRecordset objects for operating on the connected data source, pass the recordset constructor a pointer to your CDatabase object. When you finish using the connection, call the Close member function and destroy the CDatabase object. Close closes any recordsets you have not closed previously.

For more information about CDatabase, see the articles Data Source (ODBC) and Database Topics (General) in Visual C++ Programmer's Guide.

#include <afxdb.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CATALOG | MFC Sample DBFETCH | MFC Sample WWWQUOTE

See Also CRecordset


CDatabase Class Members

Data Members

m_hdbc Open Database Connectivity (ODBC) connection handle to a data source. Type HDBC.

Construction

CDatabase | Constructs a CDatabase object. You must initialize the object by calling OpenEx or Open.
Open | Establishes a connection to a data source (through an ODBC driver).
OpenEx | Establishes a connection to a data source (through an ODBC driver).
Close | Closes the data source connection.

Database Attributes

GetConnect | Returns the ODBC connect string used to connect the CDatabase object to a data source.
IsOpen | Returns nonzero if the CDatabase object is currently connected to a data source.
GetDatabaseName | Returns the name of the database currently in use.
CanUpdate | Returns nonzero if the CDatabase object is updatable (not read-only).
CanTransact | Returns nonzero if the data source supports transactions.
SetLoginTimeout | Sets the number of seconds after which a data source connection attempt will time out.
SetQueryTimeout | Sets the number of seconds after which database query operations will time out. Affects all subsequent recordset Open, AddNew, Edit, and Delete calls.
GetBookmarkPersistence | Identifies the operations through which bookmarks persist on recordset objects.
GetCursorCommitBehavior | Identifies the effect of committing a transaction on an open recordset object.
GetCursorRollbackBehavior | Identifies the effect of rolling back a transaction on an open recordset object.

Database Operations

BeginTrans | Starts a “transaction” — a series of reversible calls to the AddNew, Edit, Delete, and Update member functions of class CRecordset — on the connected data source. The data source must support transactions for BeginTrans to have any effect.
BindParameters | Allows you to bind parameters before calling CDatabase::ExecuteSQL.
CommitTrans | Completes a transaction begun by BeginTrans. Commands in the transaction that alter the data source are carried out.
Rollback | Reverses changes made during the current transaction. The data source returns to its previous state, as defined at the BeginTrans call, unaltered.
Cancel | Cancels an asynchronous operation or a process from a second thread.
ExecuteSQL | Executes an SQL statement. No data records are returned.

Database Overridables

OnSetOptions Called by the framework to set standard connection options. The default implementation sets the query timeout value. You can establish these options ahead of time by calling SetQueryTimeout.


CDatabase::BeginTrans

BOOL BeginTrans( );

Return Value

Nonzero if the call was successful and changes are committed only manually; otherwise 0.

Remarks

Call this member function to begin a transaction with the connected data source. A transaction consists of one or more calls to the AddNew, Edit, Delete, and Update member functions of a CRecordset object. Before beginning a transaction, the CDatabase object must already have been connected to the data source by calling its OpenEx or Open member function. To end the transaction, call CommitTrans to accept all changes to the data source (and carry them out) or call Rollback to abort the entire transaction. Call BeginTrans after you open any recordsets involved in the transaction and as close to the actual update operations as possible.

CAUTION Depending on your ODBC driver, opening a recordset before calling BeginTrans may cause problems when calling Rollback. You should check the specific driver you are using. For example, when using the Microsoft Access driver included in the Microsoft ODBC Desktop Driver Pack 3.0, you must account for the Jet database engine's requirement that you should not begin a transaction on any database that has an open cursor. In the MFC database classes, an open cursor means an open CRecordset object. For more information, see Technical Note 68.

BeginTrans may also lock data records on the server, depending on the requested concurrency and the capabilities of the data source. For information about locking data, see the article Recordset: Locking Records (ODBC) in Visual C++ Programmer's Guide.

User-defined transactions are explained in the article Transaction (ODBC) in Visual C++ Programmer's Guide.

BeginTrans establishes the state to which the sequence of transactions can be rolled back (reversed). To establish a new state for rollbacks, commit any current transaction, then call BeginTrans again.

! WARNING Calling BeginTrans again without calling CommitTrans or Rollback is an error.

Call the CanTransact member function to determine whether your driver supports transactions for a given database. You should also call GetCursorCommitBehavior and GetCursorRollbackBehavior to determine the support for cursor preservation.

For more information about transactions, see the article Transaction (ODBC) in Visual C++ Programmer's Guide.

Example

See the article Transaction: Performing a Transaction in a Recordset (ODBC) in Visual C++ Programmer's Guide.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::CommitTrans, CDatabase::Rollback, CRecordset::CanTransact


CDatabase::BindParameters

virtual void BindParameters( HSTMT hstmt );

Parameters

hstmt

The ODBC statement handle for which you want to bind parameters.

Remarks

Override BindParameters when you need to bind parameters before calling CDatabase::ExecuteSQL. This approach is useful when you do not need the result set from a stored procedure.

In your override, call SQLBindParameters and related ODBC functions to bind the parameters. MFC calls your override before your call to ExecuteSQL. You do not need to call SQLPrepare; ExecuteSQL calls SQLExecDirect and destroys the hstmt, which is used only once.


CDatabase::Cancel

void Cancel( );

Remarks

Call this member function to request that the data source cancel either an asynchronous operation in progress or a process from a second thread. Note that the MFC ODBC classes no longer use asynchronous processing; to perform an asychronous operation, you must directly call the ODBC API function SQLSetConnectOption. For more information, see Asynchronous Execution in the Platform SDK.


CDatabase::CanTransact

BOOL CanTransact( ) const;

Return Value

Nonzero if recordsets using this CDatabase object allow transactions; otherwise 0.

Remarks

Call this member function to determine whether the database allows transactions. For information about transactions, see the article Transaction (ODBC) in Visual C++ Programmer's Guide.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::BeginTrans, CDatabase::CommitTrans, CDatabase::Rollback


CDatabase::CanUpdate

BOOL CanUpdate( ) const;

Return Value

Nonzero if the CDatabase object allows updates; otherwise 0, indicating either that you passed TRUE in bReadOnly when you opened the CDatabase object or that the data source itself is read-only. The data source is read-only if a call to the ODBC API function ::SQLGetInfo for SQL_DATASOURCE_READ_ONLY returns “y”.

Remarks

Call this member function to determine whether the CDatabase object allows updates. Not all drivers support updates.


CDatabase::CDatabase

CDatabase( );

Remarks

Constructs a CDatabase object. After constructing the object, you must call its OpenEx or Open member function to establish a connection to a specified data source.

You may find it convenient to embed the CDatabase object in your document class.

Example

// This example illustrates using CDatabase
// in a CDocument-derived class.

class CMyDocument : public CDocument
{
public:
   // Declare a CDatabase embedded in the document
   CDatabase m_dbCust;
   // ...
};

// ...

// Initialize when needed
CDatabase* CMyDocument::GetDatabase( )
{
   // Connect the object to a data source
   if( !m_dbCust.IsOpen( ) &&
       !m_dbCust.OpenEx( NULL ) )
      return NULL;

   return &m_dbCust;
}

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::OpenEx, CDatabase::Open


CDatabase::Close

virtual void Close( );

Remarks

Call this member function if you want to disconnect from a data source. You must close any recordsets associated with the CDatabase object before you call this member function. Because Close does not destroy the CDatabase object, you can reuse the object by opening a new connection to the same data source or a different data source.

All pending AddNew or Edit statements of recordsets using the database are canceled, and all pending transactions are rolled back. Any recordsets dependent on the CDatabase object are left in an undefined state.

Example

// Close the current connection
m_dbCust.Close( );

// Perhaps connect the object to a
// different data source
m_dbCust.OpenEx("DSN=MYDATASOURCE;UID=JOES");

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::OpenEx, CDatabase::Open


CDatabase::CommitTrans

BOOL CommitTrans( );

Return Value

Nonzero if the updates were successfully committed; otherwise 0. If CommitTrans fails, the state of the data source is undefined. You must check the data to determine its state.

Remarks

Call this member function upon completing transactions. A transaction consists of a series of calls to the AddNew, Edit, Delete, and Update member functions of a CRecordset object that began with a call to the BeginTrans member function. CommitTrans commits the transaction. By default, updates are committed immediately; calling BeginTrans causes commitment of updates to be delayed until CommitTrans is called.

Until you call CommitTrans to end a transaction, you can call the Rollback member function to abort the transaction and leave the data source in its original state. To begin a new transaction, call BeginTrans again.

For more information about transactions, see the article Transaction (ODBC) in Visual C++ Programmer's Guide.

Example

See the article Transaction: Performing a Transaction in a Recordset (ODBC) in Visual C++ Programmer's Guide.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::BeginTrans, CDatabase::Rollback


CDatabase::ExecuteSQL

void ExecuteSQL( LPCSTR lpszSQL );
throw( CDBException );

Parameters

lpszSQL

Pointer to a null-terminated string containing a valid SQL command to execute. You can pass a CString.

Remarks

Call this member function when you need to execute an SQL command directly. Create the command as a null-terminated string. ExecuteSQL does not return data records. If you want to operate on records, use a recordset object instead.

Most of your commands for a data source are issued through recordset objects, which support commands for selecting data, inserting new records, deleting records, and editing records. However, not all ODBC functionality is directly supported by the database classes, so you may at times need to make a direct SQL call with ExecuteSQL.

Example

CString strCmd = "UPDATE Taxes SET Federal = 36%";

TRY
{
   m_dbCust.ExecuteSQL( strCmd );
}

CATCH(CDBException, e)
{
   // The error code is in e->m_nRetCode
}

END_CATCH

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::SetLoginTimeout, CRecordset


CDatabase::GetBookmarkPersistence

DWORD GetBookmarkPersistence( ) const;

Return Value

A bitmask that identifies the operations through which bookmarks persist on a recordset object. For details, see Remarks.

Remarks

Call this member function to determine the persistence of bookmarks on a recordset object after certain operations. For example, if you call CRecordset::GetBookmark and then call CRecordset::Requery, the bookmark obtained from GetBookmark may no longer be valid. You should call GetBookmarkPersistence before calling CRecordset::SetBookmark.

The following table lists the bitmask values that can be combined for the return value of GetBookmarkPersistence.

Bitmask value | Bookmark persistence
SQL_BP_CLOSE | Bookmarks are valid after a Requery operation.
SQL_BP_DELETE | The bookmark for a row is valid after a Delete operation on that row.
SQL_BP_DROP | Bookmarks are valid after a Close operation.
SQL_BP_SCROLL | Bookmarks are valid after any Move operation. This simply identifies if bookmarks are supported on the recordset, as returned by CRecordset::CanBookmark.
SQL_BP_TRANSACTION | Bookmarks are valid after a transaction is committed or rolled back.
SQL_BP_UPDATE | The bookmark for a row is valid after an Update operation on that row.
SQL_BP_OTHER_HSTMT | Bookmarks associated with one recordset object are valid on a second recordset.

For more information about this return value, see the ODBC API function SQLGetInfo in the ODBC SDK Programmer's Reference. For more information about bookmarks, see the article Recordset: Bookmarks and Absolute Positions (ODBC) in Visual C++ Programmer's Guide.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CRecordset, CRecordset::CanBookmark, CRecordset::GetBookmark, CRecordset::SetBookmark


CDatabase::GetConnect

const CString& GetConnect( ) const;

Return Value

A const reference to a CString containing the connect string if OpenEx or Open has been called; otherwise, an empty string.

Remarks

Call this member function to retrieve the connect string used during the call to OpenEx or Open that connected the CDatabase object to a data source.

See CDatabase::Open for a description of how the connect string is created.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::OpenEx, CDatabase::Open


CDatabase::GetCursorCommitBehavior

int GetCursorCommitBehavior( ) const;

Return Value

A value indicating the effect of transactions on open recordset objects. For details, see Remarks.

Remarks

Call this member function to determine how a CommitTrans operation affects cursors on open recordset objects.

The following table lists the possible return values for GetCursorCommitBehavior and the corresponding effect on the open recordset.

Return value | Effect on CRecordset objects
SQL_CB_CLOSE | Call CRecordset::Requery immediately following the transaction commit.
SQL_CB_DELETE | Call CRecordset::Close immediately following the transaction commit.
SQL_CB_PRESERVE | Proceed normally with CRecordset operations.

For more information about this return value, see the ODBC API function SQLGetInfo in the ODBC SDK Programmer's Reference. For more information about transactions, see the article Transaction (ODBC) in Visual C++ Programmer's Guide.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::GetCursorRollbackBehavior, CDatabase::CanTransact, CDatabase::BeginTrans, CDatabase::CommitTrans, CDatabase::Rollback, CRecordset


CDatabase::GetCursorRollbackBehavior

int GetCursorRollbackBehavior( ) const;

Return Value

A value indicating the effect of transactions on open recordset objects. For details, see Remarks.

Remarks

Call this member function to determine how a Rollback operation affects cursors on open recordset objects.

The following table lists the possible return values for GetCursorRollbackBehavior and the corresponding effect on the open recordset.

Return value | Effect on CRecordset objects
SQL_CB_CLOSE | Call CRecordset::Requery immediately following the transaction rollback.
SQL_CB_DELETE | Call CRecordset::Close immediately following the transaction rollback.
SQL_CB_PRESERVE | Proceed normally with CRecordset operations.

For more information about this return value, see the ODBC API function SQLGetInfo in the ODBC SDK Programmer's Reference. For more information about transactions, see the article Transaction (ODBC) in Visual C++ Programmer's Guide.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::GetCursorCommitBehavior, CDatabase::CanTransact, CDatabase::BeginTrans, CDatabase::CommitTrans, CDatabase::Rollback, CRecordset


CDatabase::GetDatabaseName

CString GetDatabaseName( ) const;

Return Value

A CString containing the database name if successful; otherwise, an empty CString.

Remarks

Call this member function to retrieve the name of the currently connected database (provided that the data source defines a named object called “database”). This is not the same as the data source name (DSN) specified in the OpenEx or Open call. What GetDatabaseName returns depends on ODBC. In general, a database is a collection of tables. If this entity has a name, GetDatabaseName returns it.

You might, for example, want to display this name in a heading. If an error occurs while retrieving the name from ODBC, GetDatabaseName returns an empty Cstring.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::OpenEx, CDatabase::Open, CDatabase::GetConnect


CDatabase::IsOpen

BOOL IsOpen( ) const;

Return Value

Nonzero if the CDatabase object is currently connected; otherwise 0.

Remarks

Call this member function to determine whether the CDatabase object is currently connected to a data source.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::OpenEx, CDatabase::Open


CDatabase::OnSetOptions

virtual void OnSetOptions( HSTMT hstmt );

Parameters

hstmt

The ODBC statement handle for which options are being set.

Remarks

The framework calls this member function when directly executing an SQL statement with the ExecuteSQL member function. CRecordset::OnSetOptions also calls this member function.

OnSetOptions sets the login timeout value. If there have been previous calls to the SetQueryTimeout and member function, OnSetOptions reflects the current values; otherwise, it sets default values.

Note Prior to MFC 4.2, OnSetOptions also set the processing mode to either snychronous or asynchronous. Beginning with MFC 4.2, all operations are synchronous. To perform an asynchronous operation, you must make a direct call to the ODBC API function SQLSetPos.

You do not need to override OnSetOptions to change the timeout value. Instead, to customize the query timeout value, call SetQueryTimeout before creating a recordset; OnSetOptions will use the new value. The values set apply to subsequent operations on all recordsets or direct SQL calls.

Override OnSetOptions if you want to set additional options. Your override should call the base class OnSetOptions either before or after you call the ODBC API function ::SQLSetStmtOption. Follow the method illustrated in the framework’s default implementation of OnSetOptions.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::ExecuteSQL, CDatabase::SetQueryTimeout, CRecordset::OnSetOptions


CDatabase::Open

virtual BOOL Open( LPCTSTR lpszDSN, BOOL bExclusive = FALSE, BOOL bReadOnly = FALSE, LPCTSTR lpszConnect = “ODBC;”, BOOL bUseCursorLib = TRUE );
throw( CDBException, CMemoryException );

Return Value

Nonzero if the connection is successfully made; otherwise 0 if the user chooses Cancel when presented a dialog box asking for more connection information. In all other cases, the framework throws an exception.

Parameters

lpszDSN

Specifies a data source name — a name registered with ODBC through the ODBC Administrator program. If a DSN value is specified in lpszConnect (in the form “DSN=<data-source>”), it must not be specified again in lpszDSN. In this case, lpszDSN should be NULL. Otherwise, you can pass NULL if you want to present the user with a Data Source dialog box in which the user can select a data source. For further information, see Remarks.

bExclusive

Not supported in this version of the class library. Currently, an assertion fails if this parameter is TRUE. The data source is always opened as shared (not exclusive).

bReadOnly

TRUE if you intend the connection to be read-only and to prohibit updates to the data source. All dependent recordsets inherit this attribute. The default value is FALSE.

lpszConnect

Specifies a connect string. The connect string concatenates information, possibly including a data source name, a user ID valid on the data source, a user authentication string (password, if the data source requires one), and other information. The whole connect string must be prefixed by the string “ODBC;” (uppercase or lowercase). The “ODBC;” string is used to indicate that the connection is to an ODBC data source; this is for upward compatibility when future versions of the class library might support non-ODBC data sources.

bUseCursorLib

TRUE if you want the ODBC Cursor Library DLL to be loaded. The cursor library masks some functionality of the underlying ODBC driver, effectively preventing the use of dynasets (if the driver supports them). The only cursors supported if the cursor library is loaded are static snapshots and forward-only cursors. The default value is TRUE. If you plan to create a recordset object directly from CRecordset without deriving from it, you should not load the cursor library.

Remarks

Call this member function to initialize a newly constructed CDatabase object. Your database object must be initialized before you can use it to construct a recordset object.

Note Calling the OpenEx member function is the preferred way to connect to a data source and initialize your database object.

If the parameters in your Open call do not contain enough information to make the connection, the ODBC driver opens a dialog box to obtain the necessary information from the user. When you call Open, your connect string, lpszConnect, is stored privately in the CDatabase object and is available by calling the GetConnect member function.

If you wish, you can open your own dialog box before you call Open to get information from the user, such as a password, then add that information to the connect string you pass to Open. Or you might want to save the connect string you pass so you can reuse it the next time your application calls Open on a CDatabase object.

You can also use the connect string for multiple levels of login authorization (each for a different CDatabase object) or to convey other data source-specific information. For more information about connect strings, see Chapter 5 in the ODBC SDK Programmer’s Reference.

It is possible for a connection attempt to time out if, for example, the DBMS host is unavailable. If the connection attempt fails, Open throws a CDBException.

Example

// Embed a CDatabase object
// in your document class
CDatabase m_dbCust;

// Connect the object to a
// data source (no password)
// the ODBC connection dialog box
// will always remain hidden
m_dbCust.Open( _T( "MYDATASOURCE" ), FALSE,
               FALSE, _T( "ODBC;UID=JOES" ),

// ...Or, query the user for all
// connection information
m_dbCust.Open( NULL );

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::OpenEx, CDatabase::CDatabase, CDatabase::Close, CDBException, CRecordset::Open


CDatabase::OpenEx

virtual BOOL OpenEx( LPCTSTR lpszConnectString, DWORD dwOptions = 0 );
throw( CDBException, CMemoryException );

Return Value

Nonzero if the connection is successfully made; otherwise 0 if the user chooses Cancel when presented a dialog box asking for more connection information. In all other cases, the framework throws an exception.

Parameters

lpszConnectString

Specifies an ODBC connect string. This includes the data source name as well as other optional information, such as a user ID and password. For example, "DSN=SQLServer_Source;UID=SA;PWD=abc123" is a possible connect string. Note that if you pass NULL for lpszConnectString, a Data Source dialog box will prompt the user to select a data source.

dwOptions

A bitmask which specifies a combination of the following values. The default value is 0, meaning that the database will be opened as shared with write access, the ODBC Cursor Library DLL will not be loaded, and the ODBC connection dialog box will display only if there is not enough information to make the connection.

  • CDatabase::openExclusive Not supported in this version of the class library. A data source is always opened as shared (not exclusive). Currently, an assertion fails if you specify this option.

  • CDatabase::openReadOnly Open the data source as read-only.

  • CDatabase::useCursorLib Load the ODBC Cursor Library DLL. The cursor library masks some functionality of the underlying ODBC driver, effectively preventing the use of dynasets (if the driver supports them). The only cursors supported if the cursor library is loaded are static snapshots and forward-only cursors. If you plan to create a recordset object directly from CRecordset without deriving from it, you should not load the cursor library.

  • CDatabase::noOdbcDialog Do not display the ODBC connection dialog box, regardless of whether enough connection information is supplied.

  • CDatabase::forceOdbcDialog Always display the ODBC connection dialog box.

Remarks

Call this member function to initialize a newly constructed CDatabase object. Your database object must be initialized before you can use it to construct a recordset object.

If the lpszConnectString parameter in your OpenEx call does not contain enough information to make the connection, the ODBC driver opens a dialog box to obtain the necessary information from the user, provided you have not set CDatabase::noOdbcDialog or CDatabase::forceOdbcDialog in the dwOptions parameter. When you call OpenEx, your connect string, lpszConnectString, is stored privately in the CDatabase object and is available by calling the GetConnect member function.

If you wish, you can open your own dialog box before you call OpenEx to get information from the user, such as a password, and then add that information to the connect string you pass to OpenEx. Or you might want to save the connect string you pass so you can reuse it the next time your application calls OpenEx on a CDatabase object.

You can also use the connect string for multiple levels of login authorization (each for a different CDatabase object) or to convey other data source-specific information. For more information about connect strings, see Chapter 5 in the ODBC SDK Programmer’s Reference.

It is possible for a connection attempt to time out if, for example, the DBMS host is unavailable. If the connection attempt fails, OpenEx throws a CDBException.

Example

// Embed a CDatabase object
// in your document class
CDatabase m_dbCust;

// Connect the object to a
// read-only data source where
// the ODBC connection dialog box
// will always remain hidden
m_dbCust.OpenEx( _T( "DSN=MYDATASOURCE;UID=JOES" ),
                 CDatabase::openReadOnly |
                 CDatabase::noOdbcDialog );

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::Open, CDatabase::CDatabase, CDatabase::Close, CDBException, CRecordset::Open


CDatabase::Rollback

BOOL Rollback( );

Return Value

Nonzero if the transaction was successfully reversed; otherwise 0. If a Rollback call fails, the data source and transaction states are undefined. If Rollback returns 0, you must check the data source to determine its state.

Remarks

Call this member function to reverse the changes made during a transaction. All CRecordset AddNew, Edit, Delete, and Update calls executed since the last BeginTrans are rolled back to the state that existed at the time of that call.

After a call to Rollback, the transaction is over, and you must call BeginTrans again for another transaction. The record that was current before you called BeginTrans becomes the current record again after Rollback.

After a rollback, the record that was current before the rollback remains current. For details about the state of the recordset and the data source after a rollback, see the article Transaction (ODBC) in Visual C++ Programmer's Guide.

Example

See the article Transaction: Performing a Transaction in a Recordset (ODBC) in Visual C++ Programmer's Guide.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::BeginTrans, CDatabase::CommitTrans


CDatabase::SetLoginTimeout

void SetLoginTimeout( DWORD dwSeconds );

Parameters

dwSeconds

The number of seconds to allow before a connection attempt times out.

Remarks

Call this member function — before you call OpenEx or Open — to override the default number of seconds allowed before an attempted data source connection times out. A connection attempt might time out if, for example, the DBMS is not available. Call SetLoginTimeout after you construct the uninitialized CDatabase object but before you call OpenEx or Open.

The default value for login timeouts is 15 seconds. Not all data sources support the ability to specify a login timeout value. If the data source does not support timeout, you get trace output but not an exception. A value of 0 means “infinite.”

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::OnSetOptions, CDatabase::SetQueryTimeout


CDatabase::SetQueryTimeout

void SetQueryTimeout( DWORD dwSeconds );

Parameters

dwSeconds

The number of seconds to allow before a query attempt times out.

Remarks

Call this member function to override the default number of seconds to allow before subsequent operations on the connected data source time out. An operation might time out due to network access problems, excessive query processing time, and so on. Call SetQueryTimeout prior to opening your recordset or prior to calling the recordset’s AddNew, Update or Delete member functions if you want to change the query timeout value. The setting affects all subsequent Open, AddNew, Update, and Delete calls to any recordsets associated with this CDatabase object. Changing the query timeout value for a recordset after opening does not change the value for the recordset. For example, subsequent Move operations do not use the new value.

The default value for query timeouts is 15 seconds. Not all data sources support the ability to set a query timeout value. If you set a query timeout value of 0, no timeout occurs; the communication with the data source may hang. This behavior may be useful during development. If the data source does not support timeout, you get trace output but not an exception.

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::SetLoginTimeout


CDatabase::m_hdbc

Remarks

Contains a public handle to an ODBC data source connection — a “connection handle.” Normally, you will have no need to access this member variable directly. Instead, the framework allocates the handle when you call OpenEx or Open. The framework deallocates the handle when you call the delete operator on the CDatabase object. Note that the Close member function does not deallocate the handle.

Under some circumstances, however, you may need to use the handle directly. For example, if you need to call ODBC API functions directly rather than through class CDatabase, you may need a connection handle to pass as a parameter. See the code example below.

Example

// Using m_hdbc for a direct ODBC API call.
// m_db is the CDatabase object; m_hdbc is
// its HDBC member variable
nRetcode = ::SQLGetInfo( m_db.m_hdbc,
                         SQL_ODBC_SQL_CONFORMANCE,
                         &nValue,
                         sizeof( nValue ),
                         &cbValue );

CDatabase Overview | Class Members | Hierarchy Chart

See Also CDatabase::OpenEx, CDatabase::Open, CDatabase::Close


CDataExchange

CDataExchange does not have a base class.

The CDataExchange class supports the dialog data exchange (DDX) and dialog data validation (DDV) routines used by the Microsoft Foundation classes. Use this class if you are writing data exchange routines for custom data types or controls, or if you are writing your own data validation routines. For more information on writing your own DDX and DDV routines, see Technical Note 26. For an overview of DDX and DDV, see Dialog Data Exchange and Validation and Dialog Box Topics in Visual C++ Programmer's Guide.

A CDataExchange object provides the context information needed for DDX and DDV to take place. The flag m_bSaveAndValidate is FALSE when DDX is used to fill the initial values of dialog controls from data members. The flag m_bSaveAndValidate is TRUE when DDX is used to set the current values of dialog controls into data members and when DDV is used to validate the data values. If the DDV validation fails, the DDV procedure will display a message box explaining the input error. The DDV procedure will then call Fail to reset the focus to the offending control and throw an exception to stop the validation process.

#include <afxwin.h>

Class Members | Hierarchy Chart

Sample MFC Sample VIEWEX

See Also CWnd::DoDataExchange, CWnd::UpdateData


CDataExchange Class Members

Data Members

m_bSaveAndValidate | Flag for the direction of DDX and DDV.
m_pDlgWnd | The dialog box or window where the data exchange takes place.

Operations

PrepareCtrl | Prepares the specified control for data exchange or validation. Use for nonedit controls.
PrepareEditCtrl | Prepares the specified edit control for data exchange or validation.
Fail | Called when validation fails. Resets focus to the previous control and throws an exception.


CDataExchange::Fail

void Fail( );
throw( CUserException );

Remarks

The framework calls this member function when a dialog data validation (DDV) operation fails. Fail restores the focus and selection to the control whose validation failed (if there is a control to restore). Fail then throws an exception of type CUserException to stop the validation process. The exception causes a message box explaining the error to be displayed. After DDV validation fails, the user can reenter data in the offending control.

Implementors of custom DDV routines can call Fail from their routines when a validation fails.

For more information on writing your own DDX and DDV routines, see Technical Note 26. For an overview of DDX and DDV, see Dialog Data Exchange and Validation and Dialog Box Topics in Visual C++ Programmer's Guide.

CDataExchange Overview | Class Members | Hierarchy Chart

See Also CDataExchange::PrepareCtrl, CDataExchange::PrepareEditCtrl


CDataExchange::PrepareCtrl

HWND PrepareCtrl( int nIDC );
throw( CNotSupportedException );

Return Value

The HWND of the control being prepared for DDX or DDV.

Parameters

nIDC

The ID of the control to be prepared for DDX or DDV.

Remarks

The framework calls this member function to prepare the specified control for dialog data exchange (DDX) and validation (DDV). Use PrepareEditCtrl instead for edit controls; use this member function for all other controls.

Preparation consists of storing the control’s HWND in the CDataExchange class. The framework uses this handle to restore the focus to the previously focused control in the event of a DDX or DDV failure.

Implementors of custom DDX or DDV routines should call PrepareCtrl for all non-edit controls for which they are exchanging data via DDX or validating data via DDV.

For more information on writing your own DDX and DDV routines, see Technical Note 26. For an overview of DDX and DDV, see Dialog Data Exchange and Validation and Dialog Box Topics in Visual C++ Programmer's Guide.

CDataExchange Overview | Class Members | Hierarchy Chart

See Also CDataExchange::Fail


CDataExchange::PrepareEditCtrl

HWND PrepareEditCtrl( int nIDC );
throw( CNotSupportedException );

Return Value

The HWND of the edit control being prepared for DDX or DDV.

Parameters

nIDC

The ID of the edit control to be prepared for DDX or DDV.

Remarks

The framework calls this member function to prepare the specified edit control for dialog data exchange (DDX) and validation (DDV). Use PrepareCtrl instead for all non-edit controls.

Preparation consists of two things. First, PrepareEditCtrl stores the control’s HWND in the CDataExchange class. The framework uses this handle to restore the focus to the previously focused control in the event of a DDX or DDV failure. Second, PrepareEditCtrl sets a flag in the CDataExchange class to indicate that the control whose data is being exchanged or validated is an edit control.

Implementors of custom DDX or DDV routines should call PrepareEditCtrl for all edit controls for which they are exchanging data via DDX or validating data via DDV.

For more information on writing your own DDX and DDV routines, see Technical Note 26. For an overview of DDX and DDV, see Dialog Data Exchange and Validation and Dialog Box Topics in Visual C++ Programmer's Guide.

CDataExchange Overview | Class Members | Hierarchy Chart

See Also CDataExchange::Fail


CDataExchange::m_bSaveAndValidate

Remarks

This flag indicates the direction of a dialog data exchange (DDX) operation. The flag is nonzero if the CDataExchange object is being used to move data from the dialog controls to dialog-class data members after the user edits the controls. The flag is zero if the object is being used to initialize dialog controls from dialog-class data members.

The flag is also nonzero during dialog data validation (DDV).

For more information on writing your own DDX and DDV routines, see Technical Note 26. For an overview of DDX and DDV, see Dialog Data Exchange and Validation and Dialog Box Topics in Visual C++ Programmer's Guide.


CDataExchange::m_pDlgWnd

Remarks

Contains a pointer to the CWnd object for which dialog data exchange (DDX) or validation (DDV) is taking place. This object is usually a CDialog object. Implementors of custom DDX or DDV routines can use this pointer to obtain access to the dialog window that contains the controls they are operating on.

For more information on writing your own DDX and DDV routines, see Technical Note 26. For an overview of DDX and DDV, see Dialog Data Exchange and Validation and Dialog Box Topics in Visual C++ Programmer's Guide.


CDataPathProperty

Class CDataPathProperty implements an OLE control property that can be loaded asynchronously. Asynchronous properties are loaded after synchronous initiation.

The class CDataPathProperty is derived from CAysncMonikerFile. To implement asynchronous properties in your OLE controls, derive a class from CDataPathProperty, and override OnDataAvailable.

For more information about how to use asynchronous monikers and ActiveX controls in Internet applications, see the following articles in Visual C++ Programmer's Guide:

  • Internet First Steps: ActiveX Controls

  • Internet First Steps: Asynchronous Monikers

#include <afxctl.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample Image

See Also CAsyncMonikerFile


CDataPathProperty Class Members

Construction

CDataPathProperty Constructs a CDataPathProperty object.

Operations

GetControl | Retrieves the asynchronous OLE control associated with the CDataPathProperty object.
GetPath | Retrieves the pathname of the property.
Open | Initiates loading of the asynchronous property for the associated ActiveX (OLE) control.
ResetData | Calls CAsyncMonikerFile::OnDataAvailable to notify the container that the control properties have changed.
SetControl | Sets the asynchronous ActiveX (OLE) control associated with the property.
SetPath | Sets the pathname of the property.


CDataPathProperty::CDataPathProperty

CDataPathProperty( COleControl* pControl );

CDataPathProperty( LPCTSTR lpszPath, COleControl* pControl );

Parameters

pControl

A pointer to the OLE control object to be associated with this CDataPathProperty object.

lpszPath

The path, which may be absolute or relative, used to create an asynchronous moniker that references the actual absolute location of the property. CDataPathProperty uses URLs, not filenames. If you want a CDataPathProperty object for a file, prepend file:// to the path.

Remarks

Constructs a CDataPathProperty object. The COleControl object pointed to by pControl is used by Open and retrieved by derived classes. If pControl is NULL, the control used with Open should be set with SetControl. If lpszPath is NULL, you can pass in the path through Open or set it with SetPath.

CDataPathProperty Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty::Open, CDataPathProperty::SetControl


CDataPathProperty::GetControl

COleControl* GetControl( );

Return Value

Returns a pointer to the OLE control associated with the CDataPathProperty object. NULL if not control is associated.

Remarks

Call this member function to retrieve the COleControl object associated with the CDataPathProperty object.

CDataPathProperty Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty::SetControl


CDataPathProperty::GetPath

CString GetPath( ) const;

Return Value

Returns the pathname to the property itself. Can be empty if no path has been specified.

Remarks

Call this member function to retrieve the path, set when the CDataPathProperty object was constructed, or specified in Open, or specified in a previous call to the SetPath member function.

CDataPathProperty Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty::SetPath, CDataPathProperty::Open, CDataPathProperty::CDataPathProperty


CDataPathProperty::Open

virtual BOOL Open( COleControl* pControl, CFileException* pError = NULL );

virtual BOOL Open( LPCTSTR lpszPath, COleControl* pControl, CFileException* pError = NULL );

virtual BOOL Open( LPCTSTR lpszPath, CFileException* pError = NULL );

virtual BOOL Open( CFileException* pError = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pControl

A pointer to the OLE control object to be associated with this CDataPathProperty object.

pError

A pointer to a file exception. In the event of an error, will be set to the cause.

lpszPath

The path, which may be absolute or relative, used to create an asynchronous moniker that references the actual absolute location of the property. CDataPathProperty uses URLs, not filenames. If you want a CDataPathProperty object for a file, prepend file:// to the path.

Remarks

Call this member function to initiate loading of the asynchronous property for the associated control. The function attempts to obtain the IBindHost interface from the control.

Before calling Open without a path, the value for the property's path must be set. This can be done when the object is constructed, or by calling the SetPath member function.

Before calling Open without a control, an ActiveX control (formerly known as an OLE control) can be associated with the object. This can be done when the object is constructed, or by calling SetControl.

All overloads of CAsyncMonikerFile::Open are also available from CDataPathProperty.

CDataPathProperty Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty::SetControl, CDataPathProperty::CDataPathProperty, CAsyncMonikerFile::Open


CDataPathProperty::ResetData

virtual void ResetData( );

Remarks

Call this function to get CAsyncMonikerFile::OnDataAvailable to notify the container that the control properties have changed, and all the information loaded asynchronously is no longer useful. Opening should be restarted. Derived classes can override this function for different defaults.

CDataPathProperty Overview | Class Members | Hierarchy Chart

See Also CAsyncMonikerFile::OnDataAvailable, CDataPathProperty::Open


CDataPathProperty::SetControl

void SetControl( COleControl* pControl );

Parameters

pControl

A pointer to the asynchronous OLE control to be associated with the property.

Remarks

Call this member function to associate an asynchronous OLE control with the CDataPathProperty object.

CDataPathProperty Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty::GetControl, CDataPathProperty::SetPath, CDataPathProperty::CDataPathProperty


CDataPathProperty::SetPath

void SetPath( LPCTSTR lpszPath );

Parameters

lpszPath

A path, which may be absolute or relative, to the property being loaded asynchronously. CDataPathProperty uses URLs, not filenames. If you want a CDataPathProperty object for a file, prepend file:// to the path.

Remarks

Call this member function to set the pathname of the property.

CDataPathProperty Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty::GetPath, CDataPathProperty::SetControl, CDataPathProperty::CDataPathProperty


CDateTimeCtrl

A CDateTimeCtrl object encapsulates the functionality of a date and time picker control. The date and time picker control (DTP control) provides a simple interface to exchange date and time information with a user. This interface contains fields, each of which displays a part of the date and time information stored in the control. The user can change the information stored in the control by changing the content of the string in a given field. The user can move from field to field using the mouse or the keyboard.

You can customize the date and time picker control by applying a variety of styles to the object when you create it. See Date and Time Picker Control Styles in the Platform SDK for more information about styles specific to the date and time picker control. You can set the display format of the DTP control using format styles. These format styles are described in Preset DTP Display Formats in the Platform SDK.

The date and time picker control also uses notifications and callbacks, which are described in Using CDateTimeCtrl in the Visual C++ Programmer’s Guide.

#include <afxdtctl.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CMNCTRL1

See Also CMonthCalCtrl


CDateTimeCtrl Class Members

Construction

CDateTimeCtrl | Constructs a CDateTimeCtrl object.
Create | Creates the date and time picker control and attaches it to the CDateTimeCtrl object.

Attributes

GetMonthCalColor | Retrieves the color for a given portion of the month calendar within the date and time picker control.
SetMonthCalColor | Sets the color for a given portion of the month calendar within a date and time picker control.
SetFormat | Sets the display of a date and time picker control based on a given format string.
GetMonthCalCtrl | Retrieves the date and time picker's child month calendar control.
GetMonthCalFont | Retrieves the font currently used by the date and time picker control's child month calendar control.
SetMonthCalFont | Sets the font to be used by the date and time picker control's child month calendar control.
SetRange | Sets the minimum and maximum allowable system times for a date and time picker control.
GetRange | Retrieves the current minimum and maximum allowable system times for a date and time picker control.

Operations

SetTime | Sets the time in a date and time picker control.
GetTime | Retrieves the currently selected time from a date and time picker control and places it in a specified SYSTEMTIME structure.


CDateTimeCtrl::CDateTimeCtrl

CDateTimeCtrl( );

Remarks

Call this member function to construct a CDateTimeCtrl object.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::Create


CDateTimeCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if creation was successful; otherwise 0.

Parameters

dwStyle

Specifies the combination of date time control styles. See Date and Time Picker Control Styles in the Platform SDK for more information about date and time picker styles.

rect

A reference to a RECT structure, which is the position and size of the date and time picker control.

pParentWnd

A pointer to a CWnd object that is the parent window of the date and time picker control. It must not be NULL.

nID

Specifies the date and time picker control's control ID.

Remarks

Create a date and time picker control in two steps:

  1. Call CDateTimeCtrl to construct a CDateTimeCtrl object.

  2. Call this member function, which creates the Windows date and time picker control and attaches it to the CDateTimeCtrl object.

When you call Create, the common controls are initialized.


CDateTimeCtrl::GetMonthCalColor

COLORREF GetMonthCalColor( int iColor ) const;

Return Value

A COLORREF value that represents the color setting for the specified portion of the month calendar control if successful. The function returns -1 if unsuccessful.

Parameters

iColor

An int value specifying which color area of the month calendar to retrieve. For a list of values, see the iColor parameter for SetMonthCalColor.

Remarks

This member function implements the behavior of the Win32 message DTM_GETMCCOLOR, as described in the Platform SDK.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::SetMonthCalColor


CDateTimeCtrl::GetMonthCalCtrl

CMonthCalCtrl* GetMonthCalCtrl( ) const;

Return Value

A pointer to a CMonthCalCtrl object, or NULL if unsuccessful or if the window is not visible.

Remarks

Call this member function to retrieve the CMonthCalCtrl object associated with the date and time picker control. Date and time picker controls create a child month calendar control when the user clicks the drop-down arrow. When the CMonthCalCtrl object is no longer needed, it is destroyed, so your application must not rely on storing the object representing the date time picker control's child month calendar.


CDateTimeCtrl::GetMonthCalFont

CFont* GetMonthCalFont( ) const;

Return Value

A pointer to a CFont object, or NULL if unsuccessful.

Remarks

Call this member function to get the font currently used by the date and time picker control's month calendar control. The CFont object pointed to by the return value is a temporary object and is destroyed during the next idle processing time.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::SetMonthCalFont


CDateTimeCtrl::GetRange

DWORD GetRange( COleDateTime* pMinRange, COleDateTime* pMaxRange ) const;

DWORD GetRange( CTime* pMinRange, CTime* pMaxRange ) const;

Return Value

A DWORD value containing flags that indicate which ranges are set.

Parameters

pMinRange

A pointer to a COleDateTime object or a CTime object containing the earliest time allowed in the CDateTimeCtrl object.

pMaxRange

A pointer to a COleDateTime object or a CTime object containing the latest time allowed in the CDateTimeCtrl object.

Remarks

This member function implements the behavior of the Win32 message DTM_GETRANGE, as described in the Platform SDK.

In MFC's implementation, you can specify either COleDateTime or CTime usages.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::SetRange


CDateTimeCtrl::GetTime

BOOL GetTime( COleDateTime& timeDest ) const;

DWORD GetTime( CTime& timeDest ) const;

DWORD GetTime( LPSYSTEMTIME pTimeDest ) const;

Return Value

In the first version, nonzero if the time is successfully written to the COleDateTime object; otherwise 0. In the second and third versions, a DWORD value equal to the dwFlag member set in the NMDATETIMECHANGE structure. See the Remarks section below for more information.

Parameters

timeDest

In the first version, a reference to a COleDateTime object that will receive the system time information. In the second version, a reference to a CTime object that will receive the system time information.

pTimeDest

A pointer to the SYSTEMTIME structure to receive the system time information. Must not be NULL.

Remarks

This member function implements the behavior of the Win32 message DTM_GETSYSTEMTIME, as described in the Platform SDK.

In the MFC implementation of GetTime, you can use COleDateTime or CTime classes, or you can use a SYSTEMTIME structure, to store the time information.

The return value DWORD in the second and third versions, above, indicates whether or not the date and time picker control is set to the "no date" status, as indicated in the NMDATETIMECHANGE structure member dwFlags. If the value returned equals GDT_NONE, the control is set to "no date" status, and uses the DTS_SHOWNONE style. If the value returned equals GDT_VALID, the system time is successfully stored in the destination location.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::SetTime


CDateTimeCtrl::SetFormat

BOOL SetFormat( LPCTSTR pstrFormat );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pstrFormat

A pointer to 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.

Remarks

This member function implements the behavior of the Win32 message DTM_SETFORMAT, as described in the Platform SDK.


CDateTimeCtrl::SetMonthCalColor

COLORREF SetMonthCalColor( int iColor, COLORREF ref );

Return Value

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.

Parameters

iColor

int value specifying which area of the month calendar control 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 a 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 and trailing-day text. Header and trailing days are the days from the previous and following months that appear on the current calendar.

ref

A COLORREF value representing the color that will be set for the specified area of the month calendar.

Remarks

This member function implements the behavior of the Win32 message DTM_SETMCCOLOR, as described in the Platform SDK.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::GetMonthCalColor


CDateTimeCtrl::SetMonthCalFont

void SetMonthCalFont( HFONT hFont, BOOL bRedraw = TRUE );

Parameters

hFont

Handle to the font that will be set.

bRedraw

Specifies whether the control should be redrawn immediately upon setting the font. Setting this parameter to TRUE causes the control to redraw itself.

Remarks

This member function implements the behavior of the Win32 message DTM_SETMCFONT, as described in the Platform SDK.

Example

// The following code example creates a font
// (Arial, 10 pixels high) and if successful,
// stores the result in m_pMonthFont. SetMonthCalFont
// is then called passing in the new font, causing
// the month calendar control to display all
// text and dates with an Arial font.

BOOL CYourDialog::OnInitDialog()
{
   CDialog::OnInitDialog();

   // ... other code here ...

//initializing the necessary members of the LOGFONT
// structure

   m_pMonthFont = new CFont;
   LOGFONT lf;   memset(&lf, 0, sizeof(lf));
   lf.lfHeight = 10;
   strcpy(lf.lfFaceName, "Arial");

   if (m_pMonthFont->CreateFontIndirect(&lf))
   {
// if successful, grab the month calendar control from
// our dialog and set the font

      CMonthCalCtrl* pCtrl = (CMonthCalCtrl*) GetDlgItem(IDC_DATETIME1);
      ASSERT(pCtrl != NULL);
      pCtrl->SetMonthCalFont(m_pMonthFont);
   }
   else
   {

// if not successful, clean up the font pointer and
// set equal to NULL

      delete m_pMonthFont;
      m_pMonthFont = NULL;
   }

   // ... other code here ...
}

CYourDialog::CYourDialog(CWnd* pParent /*=NULL*/)
   : CDialog(CYourDialog::IDD, pParent)
{
   // ... other code here ...
   m_pMonthFont = NULL;
   // ... other code here ...
}

CYourDialog::~CYourDialog()
{
   // ... other code here ...
   delete m_pMonthFont;
   // ... other code here ...
}

Note If you use this code, you'll want to make a member of your CDialog-derived class called m_pMonthFont of type CFont*.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::GetMonthCalFont


CDateTimeCtrl::SetRange

BOOL SetRange( const COleDateTime* pMinRange, const COleDateTime* pMaxRange );

BOOL SetRange( const CTime* pMinRange, const CTime* pMaxRange );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pMinRange

A pointer to a COleDateTime object or a CTime object containing the earliest time allowed in the CDateTimeCtrl object.

pMaxRange

A pointer to a COleDateTime object or a CTime object containing the latest time allowed in the CDateTimeCtrl object.

Remarks

This member function implements the behavior of the Win32 message DTM_SETRANGE, as described in the Platform SDK.

In MFC's implementation, you can specify either COleDateTime or CTime usages. If the COleDateTime object has a NULL status, the range will be removed. If the CTime pointer or the COleDateTime pointer is NULL, the range will be removed.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::GetRange


CDateTimeCtrl::SetTime

BOOL SetTime( const COleDateTime& timeNew );

BOOL SetTime( const CTime* pTimeNew );

BOOL SetTime( LPSYSTEMTIME pTimeNew = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

timeNew

A reference to a COleDateTime object containing the to which the control will be set.

pTimeNew

In the second version above, a pointer to a CTime object containing the time to which the control will be set. In the third version above, a pointer to a SYSTEMTIME structure containing the time to which the control will be set.

Remarks

This member function implements the behavior of the Win32 message DTM_SETSYSTEMTIME, as described in the Platform SDK.

In the MFC implementation of SetTime, you can use the COleDateTime or CTime classes, or you can use a SYSTEMTIME structure, to set the time information.

CDateTimeCtrl Overview | Class Members | Hierarchy Chart

See Also CDateTimeCtrl::GetTime


CDBException

A CDBException object represents an exception condition arising from the database classes. The class includes two public data members you can use to determine the cause of the exception or to display a text message describing the exception. CDBException objects are constructed and thrown by member functions of the database classes.

Note This class is one of MFC’s Open Database Connectivity (ODBC) classes. If you are instead using the newer Data Access Objects (DAO) classes, use CDaoException instead. All DAO class names have “CDao” as a prefix. For more information, see the articles DatabaseTopics (General) and DAO and MFC in Visual C++ Programmer's Guide.

Exceptions are cases of abnormal execution involving conditions outside the program’s control, such as data source or network I/O errors. Errors that you might expect to see in the normal course of executing your program are usually not considered exceptions.

You can access these objects within the scope of a CATCH expression. You can also throw CDBException objects from your own code with the AfxThrowDBException global function.

For more information about exception handling in general, or about CDBException objects, see the articles Exceptions and Exceptions: Database Exceptions in Visual C++ Programmer's Guide.

#include <afxdb.h>

Class Members | Base Class | Hierarchy Chart

See Also CDatabase, CRecordset, CFieldExchange, AfxThrowDBException, CRecordset::Update, CRecordset::Delete, CException


CDBException Class Members

Data Members

m_nRetCode | Contains an Open Database Connectivity (ODBC) return code, of type RETCODE.
m_strError | Contains a string that describes the error in alphanumeric terms.
m_strStateNativeOrigin | Contains a string describing the error in terms of the error codes returned by ODBC.


CDBException::m_nRetCode

Remarks

Contains an ODBC error code of type RETCODE returned by an ODBC application programming interface (API) function. This type includes SQL-prefixed codes defined by ODBC and AFX_SQL-prefixed codes defined by the database classes. For a CDBException, this member will contain one of the following values:

  • AFX_SQL_ERROR_API_CONFORMANCE The driver for a CDatabase::OpenEx or CDatabase::Open call does not conform to required ODBC API Conformance level 1 (SQL_OAC_LEVEL1).

  • AFX_SQL_ERROR_CONNECT_FAIL Connection to the data source failed. You passed a NULL CDatabase pointer to your recordset constructor and the subsequent attempt to create a connection based on GetDefaultConnect failed.

  • AFX_SQL_ERROR_DATA_TRUNCATED You requested more data than you have provided storage for. For information on increasing the provided data storage for CString or CByteArray data types, see the nMaxLength argument for RFX_Text and RFX_Binary under “Macros and Globals.”

  • AFX_SQL_ERROR_DYNASET_NOT_SUPPORTED A call to CRecordset::Open requesting a dynaset failed. Dynasets are not supported by the driver.

  • AFX_SQL_ERROR_EMPTY_COLUMN_LIST You attempted to open a table (or what you gave could not be identified as a procedure call or SELECT statement) but there are no columns identified in record field exchange (RFX) function calls in your DoFieldExchange override.

  • AFX_SQL_ERROR_FIELD_SCHEMA_MISMATCH The type of an RFX function in your DoFieldExchange override is not compatible with the column data type in the recordset.

  • AFX_SQL_ERROR_ILLEGAL_MODE You called CRecordset::Update without previously calling CRecordset::AddNew or CRecordset::Edit.

  • AFX_SQL_ERROR_LOCK_MODE_NOT_SUPPORTED Your request to lock records for update could not be fulfilled because your ODBC driver does not support locking.

  • AFX_SQL_ERROR_MULTIPLE_ROWS_AFFECTED You called CRecordset::Update or Delete for a table with no unique key and changed multiple records.

  • AFX_SQL_ERROR_NO_CURRENT_RECORD You attempted to edit or delete a previously deleted record. You must scroll to a new current record after a deletion.

  • AFX_SQL_ERROR_NO_POSITIONED_UPDATES Your request for a dynaset could not be fulfilled because your ODBC driver does not support positioned updates.

  • AFX_SQL_ERROR_NO_ROWS_AFFECTED You called CRecordset::Update or Delete, but when the operation began the record could no longer be found.

  • AFX_SQL_ERROR_ODBC_LOAD_FAILED An attempt to load the ODBC.DLL failed; Windows could not find or could not load this DLL. This error is fatal.

  • AFX_SQL_ERROR_ODBC_V2_REQUIRED Your request for a dynaset could not be fulfilled because a Level 2-compliant ODBC driver is required.

  • AFX_SQL_ERROR_RECORDSET_FORWARD_ONLY An attempt to scroll did not succeed because the data source does not support backward scrolling.

  • AFX_SQL_ERROR_SNAPSHOT_NOT_SUPPORTED A call to CRecordset::Open requesting a snapshot failed. Snapshots are not supported by the driver. (This should only occur when the ODBC cursor library — ODBCCURS.DLL — is not present.)

  • AFX_SQL_ERROR_SQL_CONFORMANCE The driver for a CDatabase::OpenEx or CDatabase::Open call does not conform to the required ODBC SQL Conformance level of "Minimum" (SQL_OSC_MINIMUM).

  • AFX_SQL_ERROR_SQL_NO_TOTAL The ODBC driver was unable to specify the total size of a CLongBinary data value. The operation probably failed because a global memory block could not be preallocated.

  • AFX_SQL_ERROR_RECORDSET_READONLY You attempted to update a read-only recordset, or the data source is read-only. No update operations can be performed with the recordset or the CDatabase object it is associated with.

  • SQL_ERROR Function failed. The error message returned by ::SQLError is stored in the m_strError data member.

  • SQL_INVALID_HANDLE Function failed due to an invalid environment handle, connection handle, or statement handle. This indicates a programming error. No additional information is available from ::SQLError.

The SQL-prefixed codes are defined by ODBC. The AFX-prefixed codes are defined in AFXDB.H, found in MFC\INCLUDE.

CDBException Overview | Class Members | Hierarchy Chart

See Also CDatabase, CLongBinary, CRecordset


CDBException::m_strError

Remarks

Contains a string describing the error that caused the exception. The string describes the error in alphanumeric terms. For more detailed information and an example, see m_strStateNativeOrigin.

CDBException Overview | Class Members | Hierarchy Chart

See Also CDBException::m_strStateNativeOrigin


CDBException::m_strStateNativeOrigin

Remarks

Contains a string describing the error that caused the exception. The string is of the form “State:%s,Native:%ld,Origin:%s”, where the format codes, in order, are replaced by values that describe:

  • The SQLSTATE, a null-terminated string containing a five-character error code returned in the szSqlState parameter of the ::SQLError function. SQLSTATE values are listed in Appendix A, “ODBC Error Codes,” in the ODBC SDK Programmer’s Reference. Example: “S0022”.

  • The native error code, specific to the data source, returned in the pfNativeError parameter of the ::SQLError function. Example: 207.

  • The error message text returned in the szErrorMsg parameter of the ::SQLError function. This message consists of several bracketed names. As an error is passed from its source to the user, each ODBC component (data source, driver, Driver Manager) appends its own name. This information helps to pinpoint the origin of the error. Example: [Microsoft][ODBC SQL Server Driver][SQL Server]

The framework interprets the error string and puts its components into m_strStateNativeOrigin; if m_strStateNativeOrigin contains information for more than one error, the errors are separated by newlines. The framework puts the alphanumeric error text into m_strError.

For additional information about the codes used to make up this string, see the ::SQLError function in the ODBC SDK Programmer’s Reference.

Example

From ODBC: “State:S0022,Native:207,Origin:[Microsoft][ODBC SQL Server Driver][SQL Server] Invalid column name ‘ColName’”

In m_strStateNativeOrigin: “State:S0022,Native:207,Origin:[Microsoft][ODBC SQL Server Driver][SQL Server]”

In m_strError: “Invalid column name ‘ColName’”

CDBException Overview | Class Members | Hierarchy Chart

See Also CDBException::m_strError


CDBVariant

CDBVariant does not have a base class.

A CDBVariant object represents a variant data type for the MFC ODBC classes. CDBVariant is similar to COleVariant; however, CDBVariant does not use OLE. CDBVariant allows you to store a value without worrying about the value’s data type. CDBVariant tracks the data type of the current value, which is stored in a union.

Class CRecordset utilizes CDBVariant objects in three member functions: GetFieldValue, GetBookmark, and SetBookmark. For example, GetFieldValue allows you to dynamically fetch data in a column. Because the data type of the column may not be known at run time, GetFieldValue uses a CDBVariant object to store the column’s data.

#include <afxdb.h>

Class Members | Hierarchy Chart

See Also CRecordset, CRecordset::GetFieldValue, CRecordset::GetBookmark, CRecordset::SetBookmark


CDBVariant Class Members

Data Members

m_dwType | Contains the data type of the currently stored value. Type DWORD.
m_boolVal | Contains a value of type BOOL.
m_chVal | Contains a value of type unsigned char.
m_iVal | Contains a value of type short.
m_lVal | Contains a value of type long.
m_fltVal | Contains a value of type float.
m_dblVal | Contains a value of type double.
m_pdate | Contains a pointer to an object of type TIMESTAMP_STRUCT.
m_pstring | Contains a pointer to an object of type CString.
m_pbinary | Contains a pointer to an object of type CLongBinary.

Construction

CDBVariant Constructs a CDBVariant object.

Operations

Clear Clears the CDBVariant object.


CDBVariant::CDBVariant

CDBVariant( );

Remarks

Creates a NULL CDBVariant object. Sets the m_dwType data member to DBVT_NULL.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::Clear

void Clear( );

Remarks

Call this member function to clear the CDBVariant object. If the value of the m_dwType data member is DBVT_DATE, DBVT_STRING, or DBVT_BINARY, Clear frees the memory associated with the union pointer member. Clear sets m_dwType to DBVT_NULL.

The CDBVariant destructor calls Clear.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_boolVal

Remarks

Stores a value of type BOOL. The m_boolVal data member belongs to a union. Before accessing m_boolVal, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_BOOL, then m_boolVal will contain a valid value; otherwise, accessing m_boolVal will produce unreliable results.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_chVal

Remarks

Stores a value of type unsigned char. The m_chVal data member belongs to a union. Before accessing m_chVal, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_UCHAR, then m_chVal contains a valid value; otherwise, accessing m_chVal will produce unreliable results.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_dblVal

Remarks

Stores a value of type double. The m_dblVal data member belongs to a union. Before accessing m_dblVal, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_DOUBLE, then m_dblVal contains a valid value; otherwise, accessing m_dblVal will produce unreliable results.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_dwType

Remarks

This data member contains the data type for the value that is currently stored in the CDBVariant object's union data member. Before accessing this union, you must check the value of m_dwType in order to determine which union data member to access. The following table lists the possible values for m_dwType and the corresponding union data member.

m_dwType | Union data member
DBVT_NULL | No union member is valid for access.
DBVT_BOOL | m_boolVal
DBVT_UCHAR | m_chVal
DBVT_SHORT | m_iVal
DBVT_LONG | m_lVal
DBVT_SINGLE | m_fltVal
DBVT_DOUBLE | m_dblVal
DBVT_DATE | m_pdate
DBVT_STRING | m_pstring
DBVT_BINARY | m_pbinary


CDBVariant::m_fltVal

Remarks

Stores a value of type float. The m_fltVal data member belongs to a union. Before accessing m_fltVal, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_SINGLE, then m_fltVal contains a valid value; otherwise, accessing m_fltVal will produce unreliable results.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_iVal

Remarks

Stores a value of type short. The m_iVal data member belongs to a union. Before accessing m_iVal, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_SHORT, then m_iVal contains a valid value; otherwise, accessing m_iVal will produce unreliable results.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_lVal

Remarks

Stores a value of type long. The m_lVal data member belongs to a union. Before accessing m_lVal, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_LONG, then m_lVal contains a valid value; otherwise, accessing m_lVal will produce unreliable results.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_pbinary

Remarks

Stores a pointer to an object of type CLongBinary. The m_pbinary data member belongs to a union. Before accessing m_pbinary, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_BINARY, then m_pbinary contains a valid pointer; otherwise, accessing m_pbinary will produce unreliable results.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_pdate

Remarks

Stores a pointer to an object of type TIMESTAMP_STRUCT. The m_pdate data member belongs to a union. Before accessing m_pdate, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_DATE, then m_pdate contains a valid pointer; otherwise, accessing m_pdate will produce unreliable results.

For more information about the TIMESTAMP_STRUCT data type, see the topic "C Data Types" in Appendix D of the ODBC SDK Programmer's Reference.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDBVariant::m_pstring

Remarks

Stores a pointer to an object of type CString. The m_pstring data member belongs to a union. Before accessing m_pstring, first check the value of CDBVariant::m_dwType. If m_dwType is set to DBVT_STRING, then m_pstring contains a valid pointer; otherwise, accessing m_pstring will produce unreliable results.

CDBVariant Overview | Class Members | Hierarchy Chart

See Also CDBVariant::m_dwType


CDC

The CDC class defines a class of device-context objects. The CDC object provides member functions for working with a device context, such as a display or printer, as well as members for working with a display context associated with the client area of a window.

Do all drawing through the member functions of a CDC object. The class provides member functions for device-context operations, working with drawing tools, type-safe graphics device interface (GDI) object selection, and working with colors and palettes. It also provides member functions for getting and setting drawing attributes, mapping, working with the viewport, working with the window extent, converting coordinates, working with regions, clipping, drawing lines, and drawing simple shapes, ellipses, and polygons. Member functions are also provided for drawing text, working with fonts, using printer escapes, scrolling, and playing metafiles.

To use a CDC object, construct it, and then call its member functions that parallel Windows functions that use device contexts.

Note Under Windows 95, all screen coordinates are limited to 16 bits. Therefore, an int passed to a CDC member function must lie in the range –32768 to 32767.

For specific uses, the Microsoft Foundation Class Library provides several classes derived from CDC . CPaintDC encapsulates calls to BeginPaint and EndPaint. CClientDC manages a display context associated with a window’s client area. CWindowDC manages a display context associated with an entire window, including its frame and controls. CMetaFileDC associates a device context with a metafile.

CDC contains two device contexts, m_hDC and m_hAttribDC, which, on creation of a CDC object, refer to the same device. CDC directs all output GDI calls to m_hDC and most attribute GDI calls to m_hAttribDC. (An example of an attribute call is GetTextColor, while SetTextColor is an output call.)

For example, the framework uses these two device contexts to implement a CMetaFileDC object that will send output to a metafile while reading attributes from a physical device. Print preview is implemented in the framework in a similar fashion. You can also use the two device contexts in a similar way in your application-specific code.

There are times when you may need text-metric information from both the m_hDC and m_hAttribDC device contexts. The following pairs of functions provide this capability:

Uses m_hAttribDC | Uses m_hDC
GetTextExtent | GetOutputTextExtent
GetTabbedTextExtent | GetOutputTabbedTextExtent
GetTextMetrics | GetOutputTextMetrics
GetCharWidth | GetOutputCharWidth

For more information on CDC, see Device Contexts in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CPaintDC, CWindowDC, CClientDC, CMetaFileDC


CDC Class Members

Data Members
Construction/Destruction
Initialization
Device-Context Functions
Drawing-Tool Functions
Type-Safe Selection. Helpers
Color and Color Palette Functions
Drawing-Attribute Functions
Mapping Functions
Coordinate Functions
Region Functions
Clipping Functions
Line-Output Functions
Simple Drawing Functions
Ellipse and Polygon Functions
Bitmap Functions
Text Functions
Font Functions
Printer Escape Functions
Scrolling Functions
Metafile Functions
Path Functions

Data Members

m_hDC | The output-device context used by this CDC object.
m_hAttribDC | The attribute-device context used by this CDC object.

Construction

CDC Constructs a CDC object.

Initialization

CreateDC | Creates a device context for a specific device.
CreateIC | Creates an information context for a specific device. This provides a fast way to get information about the device without creating a device context.
CreateCompatibleDC | Creates a memory-device context that is compatible with another device context. You can use it to prepare images in memory.
DeleteDC | Deletes the Windows device context associated with this CDC object.
FromHandle | Returns a pointer to a CDC object when given a handle to a device context. If a CDC object is not attached to the handle, a temporary CDC object is created and attached.
DeleteTempMap | Called by the CWinApp idle-time handler to delete any temporary CDC object created by FromHandle. Also detaches the device context.
Attach | Attaches a Windows device context to this CDC object.
Detach | Detaches the Windows device context from this CDC object.
SetAttribDC | Sets m_hAttribDC, the attribute device context.
SetOutputDC | Sets m_hDC, the output device context.
ReleaseAttribDC | Releases m_hAttribDC, the attribute device context.
ReleaseOutputDC | Releases m_hDC, the output device context.
GetCurrentBitmap | Returns a pointer to the currently selected CBitmap object.
GetCurrentBrush | Returns a pointer to the currently selected CBrush object.
GetCurrentFont | Returns a pointer to the currently selected CFont object.
GetCurrentPalette | Returns a pointer to the currently selected CPalette object.
GetCurrentPen | Returns a pointer to the currently selected CPen object.
GetWindow | Returns the window associated with the display device context.

Device-Context Functions

GetSafeHdc | Returns m_hDC, the output device context.
SaveDC | Saves the current state of the device context.
RestoreDC | Restores the device context to a previous state saved with SaveDC.
ResetDC | Updates the m_hAttribDC device context.
GetDeviceCaps | Retrieves a specified kind of device-specific information about a given display device’s capabilities.
IsPrinting | Determines whether the device context is being used for printing.

Drawing-Tool Functions

GetBrushOrg | Retrieves the origin of the current brush.
SetBrushOrg | Specifies the origin for the next brush selected into a device context.
EnumObjects | Enumerates the pens and brushes available in a device context.

Type-Safe Selection Helpers

SelectObject | Selects a GDI drawing object such as a pen.
SelectStockObject | Selects one of the predefined stock pens, brushes, or fonts provided by Windows.

Color and Color Palette Functions

GetNearestColor | Retrieves the closest logical color to a specified logical color that the given device can represent.
SelectPalette | Selects the logical palette.
RealizePalette | Maps palette entries in the current logical palette to the system palette.
UpdateColors | Updates the client area of the device context by matching the current colors in the client area to the system palette on a pixel-by-pixel basis.
GetHalftoneBrush | Retrieves a halftone brush.

Drawing-Attribute Functions

GetBkColor | Retrieves the current background color.
SetBkColor | Sets the current background color.
GetBkMode | Retrieves the background mode.
SetBkMode | Sets the background mode.
GetPolyFillMode | Retrieves the current polygon-filling mode.
SetPolyFillMode | Sets the polygon-filling mode.
GetROP2 | Retrieves the current drawing mode.
SetROP2 | Sets the current drawing mode.
GetStretchBltMode | Retrieves the current bitmap-stretching mode.
SetStretchBltMode | Sets the bitmap-stretching mode.
GetTextColor | Retrieves the current text color.
SetTextColor | Sets the text color.
GetColorAdjustment | Retrieves the color adjustment values for the device context.
SetColorAdjustment | Sets the color adjustment values for the device context using the specified values.

Mapping Functions

GetMapMode | Retrieves the current mapping mode.
SetMapMode | Sets the current mapping mode.
GetViewportOrg | Retrieves the x- and y-coordinates of the viewport origin.
SetViewportOrg | Sets the viewport origin.
OffsetViewportOrg | Modifies the viewport origin relative to the coordinates of the current viewport origin.
GetViewportExt | Retrieves the x- and y-extents of the viewport.
SetViewportExt | Sets the x- and y-extents of the viewport.
ScaleViewportExt | Modifies the viewport extent relative to the current values.
GetWindowOrg | Retrieves the x- and y-coordinates of the origin of the associated window.
SetWindowOrg | Sets the window origin of the device context.
OffsetWindowOrg | Modifies the window origin relative to the coordinates of the current window origin.
GetWindowExt | Retrieves the x- and y-extents of the associated window.
SetWindowExt | Sets the x- and y-extents of the associated window.
ScaleWindowExt | Modifies the window extents relative to the current values.

Coordinate Functions

DPtoHIMETRIC | Converts device units into HIMETRIC units.
DPtoLP | Converts device units into logical units.
HIMETRICtoDP | Converts HIMETRIC units into device units.
HIMETRICtoLP | Converts HIMETRIC units into logical units.
LPtoDP | Converts logical units into device units.
LPtoHIMETRIC | Converts logical units into HIMETRIC units.

Region Functions

FillRgn | Fills a specific region with the specified brush.
FrameRgn | Draws a border around a specific region using a brush.
InvertRgn | Inverts the colors in a region.
PaintRgn | Fills a region with the selected brush.

Clipping Functions

SetBoundsRect | Controls the accumulation of bounding-rectangle information for the specified device context.
GetBoundsRect | Returns the current accumulated bounding rectangle for the specified device context.
GetClipBox | Retrieves the dimensions of the tightest bounding rectangle around the current clipping boundary.
SelectClipRgn | Combines the given region with the current clipping region by using the specified mode.
ExcludeClipRect | Creates a new clipping region that consists of the existing clipping region minus the specified rectangle.
ExcludeUpdateRgn | Prevents drawing within invalid areas of a window by excluding an updated region in the window from a clipping region.
IntersectClipRect | Creates a new clipping region by forming the intersection of the current region and a rectangle.
OffsetClipRgn | Moves the clipping region of the given device.
PtVisible | Specifies whether the given point is within the clipping region.
RectVisible | Determines whether any part of the given rectangle lies within the clipping region.

Line-Output Functions

GetCurrentPosition | Retrieves the current position of the pen (in logical coordinates).
MoveTo | Moves the current position.
LineTo | Draws a line from the current position up to, but not including, a point.
Arc | Draws an elliptical arc.
ArcTo | Draws an elliptical arc. This function is similar to Arc, except that the current position is updated.
AngleArc | Draws a line segment and an arc, and moves the current position to the ending point of the arc.
GetArcDirection | Returns the current arc direction for the device context.
SetArcDirection | Sets the drawing direction to be used for arc and rectangle functions.
PolyDraw | Draws a set of line segments and Bézier splines. This function updates the current position.
Polyline | Draws a set of line segments connecting the specified points.
PolyPolyline | Draws multiple series of connected line segments. The current position is neither used nor updated by this function.
PolylineTo | Draws one or more straight lines and moves the current position to the ending point of the last line.
PolyBezier | Draws one or more Bézier splines. The current position is neither used nor updated.
PolyBezierTo | Draws one or more Bézier splines, and moves the current position to the ending point of the last Bézier spline.

Simple Drawing Functions

FillRect | Fills a given rectangle by using a specific brush.
FrameRect | Draws a border around a rectangle.
InvertRect | Inverts the contents of a rectangle.
DrawIcon | Draws an icon.
DrawDragRect | Erases and redraws a rectangle as it is dragged.
FillSolidRect | Fills a rectangle with a solid color.
Draw3dRect | Draws a three-dimensional rectangle.
DrawEdge | Draws the edges of a rectangle.
DrawFrameControl | Draw a frame control.
DrawState | Displays an image and applies a visual effect to indicate a state.

Ellipse and Polygon Functions

Chord | Draws a chord (a closed figure bounded by the intersection of an ellipse and a line segment).
DrawFocusRect | Draws a rectangle in the style used to indicate focus.
Ellipse | Draws an ellipse.
Pie | Draws a pie-shaped wedge.
Polygon | Draws a polygon consisting of two or more points (vertices) connected by lines.
PolyPolygon | Creates two or more polygons that are filled using the current polygon-filling mode. The polygons may be disjoint or they may overlap.
Polyline | Draws a polygon consisting of a set of line segments connecting specified points.
Rectangle | Draws a rectangle using the current pen and fills it using the current brush.
RoundRect | Draws a rectangle with rounded corners using the current pen and filled using the current brush.

Bitmap Functions

PatBlt | Creates a bit pattern.
BitBlt | Copies a bitmap from a specified device context.
StretchBlt | Moves a bitmap from a source rectangle and device into a destination rectangle, stretching or compressing the bitmap if necessary to fit the dimensions of the destination rectangle.
GetPixel | Retrieves the RGB color value of the pixel at the specified point.
SetPixel | Sets the pixel at the specified point to the closest approximation of the specified color.
SetPixelV | Sets the pixel at the specified coordinates to the closest approximation of the specified color. SetPixelV is faster than SetPixel because it does not need to return the color value of the point actually painted.
FloodFill | Fills an area with the current brush.
ExtFloodFill | Fills an area with the current brush. Provides more flexibility than the FloodFill member function.
MaskBlt | Combines the color data for the source and destination bitmaps using the given mask and raster operation.
PlgBlt | Performs a bit-block transfer of the bits of color data from the specified rectangle in the source device context to the specified parallelogram in the given device context.

Text Functions

TextOut | Writes a character string at a specified location using the currently selected font.
ExtTextOut | Writes a character string within a rectangular region using the currently selected font.
TabbedTextOut | Writes a character string at a specified location, expanding tabs to the values specified in an array of tab-stop positions.
DrawText | Draws formatted text in the specified rectangle.
GetTextExtent | Computes the width and height of a line of text on the attribute device context using the current font to determine the dimensions.
GetOutputTextExtent | Computes the width and height of a line of text on the output device context using the current font to determine the dimensions.
GetTabbedTextExtent | Computes the width and height of a character string on the attribute device context.
GetOutputTabbedTextExtent | Computes the width and height of a character string on the output device context.
GrayString | Draws dimmed (grayed) text at the given location.
GetTextAlign | Retrieves the text-alignment flags.
SetTextAlign | Sets the text-alignment flags.
GetTextFace | Copies the typeface name of the current font into a buffer as a null-terminated string.
GetTextMetrics | Retrieves the metrics for the current font from the attribute device context.
GetOutputTextMetrics | Retrieves the metrics for the current font from the output device context.
SetTextJustification | Adds space to the break characters in a string.
GetTextCharacterExtra | Retrieves the current setting for the amount of intercharacter spacing.
SetTextCharacterExtra | Sets the amount of intercharacter spacing.

Font Functions

GetFontData | Retrieves font metric information from a scalable font file. The information to retrieve is identified by specifying an offset into the font file and the length of the information to return.
GetKerningPairs | Retrieves the character kerning pairs for the font that is currently selected in the specified device context.
GetOutlineTextMetrics | Retrieves font metric information for TrueType fonts.
GetGlyphOutline | Retrieves the outline curve or bitmap for an outline character in the current font.
GetCharABCWidths | Retrieves the widths, in logical units, of consecutive characters in a given range from the current font.
GetCharWidth | Retrieves the fractional widths of consecutive characters in a given range from the current font.
GetOutputCharWidth | Retrieves the widths of individual characters in a consecutive group of characters from the current font using the output device context.
SetMapperFlags | Alters the algorithm that the font mapper uses when it maps logical fonts to physical fonts.
GetAspectRatioFilter | Retrieves the setting for the current aspect-ratio filter.

Printer Escape Functions

QueryAbort | Calls the AbortProc callback function for a printing application and queries whether the printing should be terminated.
Escape | Allows applications to access facilities that are not directly available from a particular device through GDI. Also allows access to Windows escape functions. Escape calls made by an application are translated and sent to the device driver.
DrawEscape | Accesses drawing capabilities of a video display that are not directly available through the graphics device interface (GDI).
StartDoc | Informs the device driver that a new print job is starting.
StartPage | Informs the device driver that a new page is starting.
EndPage | Informs the device driver that a page is ending.
SetAbortProc | Sets a programmer-supplied callback function that Windows calls if a print job must be aborted.
AbortDoc | Terminates the current print job, erasing everything the application has written to the device since the last call of the StartDoc member function.
EndDoc | Ends a print job started by the StartDoc member function.

Scrolling Functions

ScrollDC Scrolls a rectangle of bits horizontally and vertically.

Metafile Functions

PlayMetaFile | Plays the contents of the specified metafile on the given device. The enhanced version of PlayMetaFile displays the picture stored in the given enhanced-format metafile. The metafile can be played any number of times.
AddMetaFileComment | Copies the comment from a buffer into a specified enhanced-format metafile.

Path Functions

AbortPath | Closes and discards any paths in the device context.
BeginPath | Opens a path bracket in the device context.
CloseFigure | Closes an open figure in a path.
EndPath | Closes a path bracket and selects the path defined by the bracket into the device context.
FillPath | Closes any open figures in the current path and fills the path’s interior by using the current brush and polygon-filling mode.
FlattenPath | Transforms any curves in the path selected into the current device context, and turns each curve into a sequence of lines.
GetMiterLimit | Returns the miter limit for the device context.
GetPath | Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the device context.
SelectClipPath | Selects the current path as a clipping region for the device context, combining the new region with any existing clipping region by using the specified mode.
SetMiterLimit | Sets the limit for the length of miter joins for the device context.
StrokeAndFillPath | Closes any open figures in a path, strikes the outline of the path by using the current pen, and fills its interior by using the current brush.
StrokePath | Renders the specified path by using the current pen.
WidenPath | Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the device context.


CDC::AbortDoc

int AbortDoc( );

Return Value

A value greater than or equal to 0 if successful, or a negative value if an error has occurred. The following list shows common error values and their meanings:

  • SP_ERROR General error.

  • SP_OUTOFDISK Not enough disk space is currently available for spooling, and no more space will become available.

  • SP_OUTOFMEMORY Not enough memory is available for spooling.

  • SP_USERABORT User terminated the job through the Print Manager.

Remarks

Terminates the current print job and erases everything the application has written to the device since the last call to the StartDoc member function.

This member function replaces the ABORTDOC printer escape.

AbortDoc should be used to terminate the following:

  • Printing operations that do not specify an abort function using SetAbortProc.

  • Printing operations that have not yet reached their first NEWFRAME or NEXTBAND escape call.

If an application encounters a printing error or a canceled print operation, it must not attempt to terminate the operation by using either the EndDoc or AbortDoc member functions of class CDC. GDI automatically terminates the operation before returning the error value.

If the application displays a dialog box to allow the user to cancel the print operation, it must call AbortDoc before destroying the dialog box.

If Print Manager was used to start the print job, calling AbortDoc erases the entire spool job — the printer receives nothing. If Print Manager was not used to start the print job, the data may have been sent to the printer before AbortDoc was called. In this case, the printer driver would have reset the printer (when possible) and closed the print job.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::StartDoc, CDC::EndDoc, CDC::SetAbortProc


CDC::AbortPath

BOOL AbortPath( )

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Closes and discards any paths in the device context. If there is an open path bracket in the device context, the path bracket is closed and the path is discarded. If there is a closed path in the device context, the path is discarded.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::EndPath


CDC::AddMetaFileComment

BOOL AddMetaFileComment( UINT nDataSize, const BYTE* pCommentData );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nDataSize

Specifies the length of the comment buffer, in bytes.

pCommentData

Points to the buffer that contains the comment.

Remarks

Copies the comment from a buffer into a specified enhanced-format metafile. A comment may include any private information—for example, the source of the picture and the date it was created. A comment should begin with an application signature, followed by the data. Comments should not contain position-specific data. Position-specific data specifies the location of a record, and it should not be included because one metafile may be embedded within another metafile. This function can only be used with enhanced metafiles.

CDC Overview | Class Members | Hierarchy Chart

See Also CMetaFileDC::CreateEnhanced, ::GdiComment


CDC::AngleArc

BOOL AngleArc( int x, int y, int nRadius, float fStartAngle, float fSweepAngle );

Return Value

Nonzero if successful; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the center of the circle.

y

Specifies the logical y-coordinate of the center of the circle.

nRadius

Specifies the radius of the circle in logical units. This value must be positive.

fStartAngle

Specifies the starting angle in degrees relative to the x-axis.

fSweepAngle

Specifies the sweep angle in degrees relative to the starting angle.

Remarks

Draws a line segment and an arc. The line segment is drawn from the current position to the beginning of the arc. The arc is drawn along the perimeter of a circle with the given radius and center. The length of the arc is defined by the given start and sweep angles.

AngleArc moves the current position to the ending point of the arc. The arc drawn by this function may appear to be elliptical, depending on the current transformation and mapping mode. Before drawing the arc, this function draws the line segment from the current position to the beginning of the arc. The arc is drawn by constructing an imaginary circle with the specified radius around the specified center point. The starting point of the arc is determined by measuring counterclockwise from the x-axis of the circle by the number of degrees in the start angle. The ending point is similarly located by measuring counterclockwise from the starting point by the number of degrees in the sweep angle.

If the sweep angle is greater than 360 degrees the arc is swept multiple times. This function draws lines by using the current pen. The figure is not filled.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Arc, CDC::ArcTo, CDC::MoveTo, ::AngleArc


CDC::Arc

BOOL Arc( int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4 );

BOOL Arc( LPCRECT lpRect, POINT ptStart, POINT ptEnd );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x1

Specifies the x-coordinate of the upper-left corner of the bounding rectangle (in logical units).

y1

Specifies the y-coordinate of the upper-left corner of the bounding rectangle (in logical units).

x2

Specifies the x-coordinate of the lower-right corner of the bounding rectangle (in logical units).

y2

Specifies the y-coordinate of the lower-right corner of the bounding rectangle (in logical units).

x3

Specifies the x-coordinate of the point that defines the arc’s starting point (in logical units). This point does not have to lie exactly on the arc.

y3

Specifies the y-coordinate of the point that defines the arc’s starting point (in logical units). This point does not have to lie exactly on the arc.

x4

Specifies the x-coordinate of the point that defines the arc’s endpoint (in logical units). This point does not have to lie exactly on the arc.

y4

Specifies the y-coordinate of the point that defines the arc’s endpoint (in logical units). This point does not have to lie exactly on the arc.

lpRect

Specifies the bounding rectangle (in logical units). You can pass either an LPRECT or a CRect object for this parameter.

ptStart

Specifies the x- and y-coordinates of the point that defines the arc’s starting point (in logical units). This point does not have to lie exactly on the arc. You can pass either a POINT structure or a CPoint object for this parameter.

ptEnd

Specifies the x- and y-coordinates of the point that defines the arc’s ending point (in logical units). This point does not have to lie exactly on the arc. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Draws an elliptical arc. The arc drawn by using the function is a segment of the ellipse defined by the specified bounding rectangle.

The actual starting point of the arc is the point at which a ray drawn from the center of the bounding rectangle through the specified starting point intersects the ellipse. The actual ending point of the arc is the point at which a ray drawn from the center of the bounding rectangle through the specified ending point intersects the ellipse. The arc is drawn in a counterclockwise direction. Since an arc is not a closed figure, it is not filled. Both the width and height of the rectangle must be greater than 2 units and less than 32,767 units.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Chord, ::Arc, POINT, RECT


CDC::ArcTo

BOOL ArcTo( int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4 );

BOOL ArcTo( LPCRECT lpRect, POINT ptStart, POINT ptEnd );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x1

Specifies the x-coordinate of the upper-left corner of the bounding rectangle (in logical units).

y1

Specifies the y-coordinate of the upper-left corner of the bounding rectangle (in logical units).

x2

Specifies the x-coordinate of the lower-right corner of the bounding rectangle (in logical units).

y2

Specifies the y-coordinate of the lower-right corner of the bounding rectangle (in logical units).

x3

Specifies the x-coordinate of the point that defines the arc’s starting point (in logical units). This point does not have to lie exactly on the arc.

y3

Specifies the y-coordinate of the point that defines the arc’s starting point (in logical units). This point does not have to lie exactly on the arc.

x4

Specifies the x-coordinate of the point that defines the arc’s endpoint (in logical units). This point does not have to lie exactly on the arc.

y4

Specifies the y-coordinate of the point that defines the arc’s endpoint (in logical units). This point does not have to lie exactly on the arc.

lpRect

Specifies the bounding rectangle (in logical units). You can pass either a pointer to a RECT data structure or a CRect object for this parameter.

ptStart

Specifies the x- and y-coordinates of the point that defines the arc’s starting point (in logical units). This point does not have to lie exactly on the arc. You can pass either a POINT data structure or a CPoint object for this parameter.

ptEnd

Specifies the x- and y-coordinates of the point that defines the arc’s ending point (in logical units). This point does not have to lie exactly on the arc. You can pass either a POINT data structure or a CPoint object for this parameter.

Remarks

Draws an elliptical arc. This function is similar to CDC::Arc, except that the current position is updated. The points (x1,y1) and (x2,y2) specify the bounding rectangle. An ellipse formed by the given bounding rectangle defines the curve of the arc. The arc extends counterclockwise (the default arc direction) from the point where it intersects the radial line from the center of the bounding rectangle to (x3,y3). The arc ends where it intersects the radial line from the center of the bounding rectangle to (x4,y4). If the starting point and ending point are the same, a complete ellipse is drawn.

A line is drawn from the current position to the starting point of the arc. If no error occurs, the current position is set to the ending point of the arc. The arc is drawn using the current pen; it is not filled.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::AngleArc, CDC::Arc, CDC::SetArcDirection, ::ArcTo


CDC::Attach

BOOL Attach( HDC hDC );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

hDC

A Windows device context.

Remarks

Use this member function to attach an hDC to the CDC object. The hDC is stored in both m_hDC, the output device context, and in m_hAttribDC, the attribute device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Detach, CDC::m_hDC, CDC::m_hAttribDC


CDC::BeginPath

BOOL BeginPath( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Opens a path bracket in the device context. After a path bracket is open, an application can begin calling GDI drawing functions to define the points that lie in the path. An application can close an open path bracket by calling the EndPath member function. When an application calls BeginPath, any previous paths are discarded.

See BeginPath in the Platform SDK for a list of the drawing functions that define points in a path for Windows NT and Windows 95.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::EndPath, CDC::FillPath, CRgn::CreateFromPath, CDC::SelectClipPath, CDC::StrokeAndFillPath, CDC::StrokePath, CDC::WidenPath


CDC::BitBlt

BOOL BitBlt( int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, DWORD dwRop );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.

y

Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

nWidth

Specifies the width (in logical units) of the destination rectangle and source bitmap.

nHeight

Specifies the height (in logical units) of the destination rectangle and source bitmap.

pSrcDC

Pointer to a CDC object that identifies the device context from which the bitmap will be copied. It must be NULL if dwRop specifies a raster operation that does not include a source.

xSrc

Specifies the logical x-coordinate of the upper-left corner of the source bitmap.

ySrc

Specifies the logical y-coordinate of the upper-left corner of the source bitmap.

dwRop

Specifies the raster operation to be performed. Raster-operation codes define how the GDI combines colors in output operations that involve a current brush, a possible source bitmap, and a destination bitmap. The following lists raster-operation codes for dwRop and their descriptions:

  • BLACKNESS Turns all output black.

  • DSTINVERT Inverts the destination bitmap.

  • MERGECOPY Combines the pattern and the source bitmap using the Boolean AND operator.

  • MERGEPAINT Combines the inverted source bitmap with the destination bitmap using the Boolean OR operator.

  • NOTSRCCOPY Copies the inverted source bitmap to the destination.

  • NOTSRCERASE Inverts the result of combining the destination and source bitmaps using the Boolean OR operator.

  • PATCOPY Copies the pattern to the destination bitmap.

  • PATINVERT Combines the destination bitmap with the pattern using the Boolean XOR operator.

  • PATPAINT Combines the inverted source bitmap with the pattern using the Boolean OR operator. Combines the result of this operation with the destination bitmap using the Boolean OR operator.

  • SRCAND Combines pixels of the destination and source bitmaps using the Boolean AND operator.

  • SRCCOPY Copies the source bitmap to the destination bitmap.

  • SRCERASE Inverts the desination bitmap and combines the result with the source bitmap using the Boolean AND operator.

  • SRCINVERT Combines pixels of the destination and source bitmaps using the Boolean XOR operator.

  • SRCPAINT Combines pixels of the destination and source bitmaps using the Boolean OR operator.

  • WHITENESS Turns all output white.

For a complete list of raster-operation codes, see About Raster Operation Codes in the Appendices section of the Win32 SDK Programmer’s Reference.

Remarks

Copies a bitmap from the source device context to this current device context.

The application can align the windows or client areas on byte boundaries to ensure that the BitBlt operations occur on byte-aligned rectangles. (Set the CS_BYTEALIGNWINDOW or CS_BYTEALIGNCLIENT flags when you register the window classes.)

BitBlt operations on byte-aligned rectangles are considerably faster than BitBlt operations on rectangles that are not byte aligned. If you want to specify class styles such as byte-alignment for your own device context, you will have to register a window class rather than relying on the Microsoft Foundation classes to do it for you. Use the global function AfxRegisterWndClass.

GDI transforms nWidth and nHeight, once by using the destination device context, and once by using the source device context. If the resulting extents do not match, GDI uses the Windows StretchBlt function to compress or stretch the source bitmap as necessary.

If destination, source, and pattern bitmaps do not have the same color format, the BitBlt function converts the source and pattern bitmaps to match the destination. The foreground and background colors of the destination bitmap are used in the conversion.

When the BitBlt function converts a monochrome bitmap to color, it sets white bits (1) to the background color and black bits (0) to the foreground color. The foreground and background colors of the destination device context are used. To convert color to monochrome, BitBlt sets pixels that match the background color to white and sets all other pixels to black. BitBlt uses the foreground and background colors of the color device context to convert from color to monochrome.

Note that not all device contexts support BitBlt. To check whether a given device context does support BitBlt, use the GetDeviceCaps member function and specify the RASTERCAPS index.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetDeviceCaps, CDC::PatBlt, CDC::SetTextColor, CDC::StretchBlt, ::StretchDIBits, ::BitBlt


CDC::CDC

CDC( );

Remarks

Constructs a CDC object.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::CreateDC, CDC::CreateIC, CDC::CreateCompatibleDC


CDC::Chord

BOOL Chord( int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4 );

BOOL Chord( LPCRECT lpRect, POINT ptStart, POINT ptEnd );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x1

Specifies the x-coordinate of the upper-left corner of the chord’s bounding rectangle (in logical units).

y1

Specifies the y-coordinate of the upper-left corner of the chord’s bounding rectangle (in logical units).

x2

Specifies the x-coordinate of the lower-right corner of the chord’s bounding rectangle (in logical units).

y2

Specifies the y-coordinate of the lower-right corner of the chord’s bounding rectangle (in logical units).

x3

Specifies the x-coordinate of the point that defines the chord’s starting point (in logical units).

y3

Specifies the y-coordinate of the point that defines the chord’s starting point (in logical units).

x4

Specifies the x-coordinate of the point that defines the chord’s endpoint (in logical units).

y4

Specifies the y-coordinate of the point that defines the chord’s endpoint (in logical units).

lpRect

Specifies the bounding rectangle (in logical units). You can pass either a LPRECT or a CRect object for this parameter.

ptStart

Specifies the x- and y-coordinates of the point that defines the chord’s starting point (in logical units). This point does not have to lie exactly on the chord. You can pass either a POINT structure or a CPoint object for this parameter.

ptEnd

Specifies the x- and y-coordinates of the point that defines the chord’s ending point (in logical units). This point does not have to lie exactly on the chord. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Draws a chord (a closed figure bounded by the intersection of an ellipse and a line segment). The (x1, y1) and (x2, y2) parameters specify the upper-left and lower-right corners, respectively, of a rectangle bounding the ellipse that is part of the chord. The (x3, y3) and (x4, y4) parameters specify the endpoints of a line that intersects the ellipse. The chord is drawn by using the selected pen and filled by using the selected brush.

The figure drawn by the Chord function extends up to, but does not include the right and bottom coordinates. This means that the height of the figure is y2 – y1 and the width of the figure is x2 – x1.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Arc, ::Chord, POINT


CDC::CloseFigure

BOOL CloseFigure( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Closes an open figure in a path. The function closes the figure by drawing a line from the current position to the first point of the figure (usually, the point specified by the most recent call to the MoveTo member function) and connects the lines by using the line join style. If a figure is closed by using the LineTo member function instead of CloseFigure, end caps are used to create the corner instead of a join. CloseFigure should only be called if there is an open path bracket in the device context.

A figure in a path is open unless it is explicitly closed by using this function. (A figure can be open even if the current point and the starting point of the figure are the same.) Any line or curve added to the path after CloseFigure starts a new figure.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::EndPath, CDC::MoveTo, ::CloseFigure


CDC::CreateCompatibleDC

virtual BOOL CreateCompatibleDC( CDC* pDC );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

pDC

A pointer to a device context. If pDC is NULL, the function creates a memory device context that is compatible with the system display.

Remarks

Creates a memory device context that is compatible with the device specified by pDC. A memory device context is a block of memory that represents a display surface. It can be used to prepare images in memory before copying them to the actual device surface of the compatible device.

When a memory device context is created, GDI automatically selects a 1-by-1 monochrome stock bitmap for it. GDI output functions can be used with a memory device context only if a bitmap has been created and selected into that context.

This function can only be used to create compatible device contexts for devices that support raster operations. See the CDC::BitBlt member function for information regarding bit-block transfers between device contexts. To determine whether a device context supports raster operations, see the RC_BITBLT raster capability in the member function CDC::GetDeviceCaps.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::CDC, CDC::GetDeviceCaps, ::CreateCompatibleDC, CDC::BitBlt, CDC::CreateDC, CDC::CreateIC, CDC::DeleteDC


CDC::CreateDC

virtual BOOL CreateDC( LPCTSTR lpszDriverName, LPCTSTR lpszDeviceName, LPCTSTR lpszOutput, const void* lpInitData );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpszDriverName

Points to a null-terminated string that specifies the filename (without extension) of the device driver (for example, “EPSON”). You can also pass a CString object for this parameter.

lpszDeviceName

Points to a null-terminated string that specifies the name of the specific device to be supported (for example, “EPSON FX-80”). The lpszDeviceName parameter is used if the module supports more than one device. You can also pass a CString object for this parameter.

lpszOutput

Points to a null-terminated string that specifies the file or device name for the physical output medium (file or output port). You can also pass a CString object for this parameter.

lpInitData

Points to a DEVMODE structure containing device-specific initialization data for the device driver. The Windows DocumentProperties function retrieves this structure filled in for a given device. The lpInitData parameter must be NULL if the device driver is to use the default initialization (if any) specified by the user through the Control Panel.

Remarks

Creates a device context for the specified device.

The PRINT.H header file is required if the DEVMODE structure is used.

Device names follow these conventions: an ending colon (:) is recommended, but optional. Windows strips the terminating colon so that a device name ending with a colon is mapped to the same port as the same name without a colon. The driver and port names must not contain leading or trailing spaces. GDI output functions cannot be used with information contexts.

CDC Overview | Class Members | Hierarchy Chart

See Also ::DocumentProperties, ::CreateDC, CDC::DeleteDC, CDC::CreateIC


CDC::CreateIC

virtual BOOL CreateIC( LPCTSTR lpszDriverName, LPCTSTR lpszDeviceName, LPCTSTR lpszOutput, const void* lpInitData );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszDriverName

Points to a null-terminated string that specifies the filename (without extension) of the device driver (for example, “EPSON”). You can pass a CString object for this parameter.

lpszDeviceName

Points to a null-terminated string that specifies the name of the specific device to be supported (for example, “EPSON FX-80”). The lpszDeviceName parameter is used if the module supports more than one device. You can pass a CString object for this parameter.

lpszOutput

Points to a null-terminated string that specifies the file or device name for the physical output medium (file or port). You can pass a CString object for this parameter.

lpInitData

Points to device-specific initialization data for the device driver. The lpInitData parameter must be NULL if the device driver is to use the default initialization (if any) specified by the user through the Control Panel. See CreateDC for the data format for device-specific initialization.

Remarks

Creates an information context for the specified device. The information context provides a fast way to get information about the device without creating a device context.

Device names follow these conventions: an ending colon (:) is recommended, but optional. Windows strips the terminating colon so that a device name ending with a colon is mapped to the same port as the same name without a colon. The driver and port names must not contain leading or trailing spaces. GDI output functions cannot be used with information contexts.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::CreateDC, ::CreateIC, CDC::DeleteDC


CDC::DeleteDC

virtual BOOL DeleteDC( );

Return Value

Nonzero if the function completed successfully; otherwise 0.

Remarks

In general, do not call this function; the destructor will do it for you. The DeleteDC member function deletes the Windows device contexts that are associated with m_hDC in the current CDC object. If this CDC object is the last active device context for a given device, the device is notified and all storage and system resources used by the device are released.

An application should not call DeleteDC if objects have been selected into the device context. Objects must first be selected out of the device context before it it is deleted.

An application must not delete a device context whose handle was obtained by calling CWnd::GetDC. Instead, it must call CWnd::ReleaseDC to free the device context. The CClientDC and CWindowDC classes are provided to wrap this functionality.

The DeleteDC function is generally used to delete device contexts created with CreateDC, CreateIC, or CreateCompatibleDC.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::CDC, ::DeleteDC, CDC::CreateDC, CDC::CreateIC, CDC::CreateCompatibleDC, CWnd::GetDC, CWnd::ReleaseDC


CDC::DeleteTempMap

static void PASCAL DeleteTempMap( );

Remarks

Called automatically by the CWinApp idle-time handler, DeleteTempMap deletes any temporary CDC objects created by FromHandle, but does not destroy the device context handles (hDCs) temporarily associated with the CDC objects.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Detach, CDC::FromHandle, CWinApp::OnIdle


CDC::Detach

HDC Detach( );

Return Value

A Windows device context.

Remarks

Call this function to detach m_hDC (the output device context) from the CDC object and set both m_hDC and m_hAttribDC to NULL.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Attach, CDC::m_hDC, CDC::m_hAttribDC


CDC::DPtoHIMETRIC

void DPtoHIMETRIC( LPSIZE lpSize ) const;

Parameters

lpSize

Points to a SIZE structure or CSize object.

Remarks

Use this function when you give HIMETRIC sizes to OLE, converting pixels to HIMETRIC.

If the mapping mode of the device context object is MM_LOENGLISH, MM_HIENGLISH, MM_LOMETRIC, or MM_HIMETRIC, then the conversion is based on the number of pixels in the physical inch. If the mapping mode is one of the other non-constrained modes (e.g., MM_TEXT), then the conversion is based on the number of pixels in the logical inch.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::DPtoLP, CDC::LPtoDP, CDC::HIMETRICtoLP, CDC::HIMETRICtoDP, CDC::LPtoHIMETRIC


CDC::DPtoLP

void DPtoLP( LPPOINT lpPoints, int nCount = 1 ) const;

void DPtoLP( LPRECT lpRect ) const;

void DPtoLP( LPSIZE lpSize ) const;

Parameters

lpPoints

Points to an array of POINT structures or CPoint objects.

nCount

The number of points in the array.

lpRect

Points to a RECT structure or CRect object. This parameter is used for the simple case of converting one rectangle from device points to logical points.

lpSize

Points to a SIZE structure or CSize object.

Remarks

Converts device units into logical units. The function maps the coordinates of each point, or dimension of a size, from the device coordinate system into GDI’s logical coordinate system. The conversion depends on the current mapping mode and the settings of the origins and extents for the device’s window and viewport.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::LPtoDP, CDC::HIMETRICtoDP, ::DPtoLP, POINT, RECT, CDC::GetWindowExt, CDC::GetWindowOrg


CDC::Draw3dRect

void Draw3dRect( LPCRECT lpRect, COLORREF clrTopLeft, COLORREF clrBottomRight );

void Draw3dRect( int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight );

Parameters

lpRect

Specifies the bounding rectangle (in logical units). You can pass either a pointer to a RECT structure or a CRect object for this parameter.

clrTopLeft

Specifies the color of the top and left sides of the three-dimensional rectangle.

clrBottomRight

Specifies the color of the bottom and right sides of the three-dimensional rectangle.

x

Specifies the logical x-coordinate of the upper-left corner of the three-dimensional rectangle.

y

Specifies the logical y-coordinate of the upper-left corner of the three-dimensional rectangle.

cx

Specifies the width of the three-dimensional rectangle.

cy

Specifies the height of the three-dimensional rectangle.

Remarks

Call this member function to draw a three-dimensional rectangle. The rectangle will be drawn with the top and left sides in the color specified by clrTopLeft and the bottom and right sides in the color specified by clrBottomRight.

CDC Overview | Class Members | Hierarchy Chart

See Also RECT, CRect


CDC::DrawDragRect

void DrawDragRect( LPCRECT lpRect, SIZE size, LPCRECT lpRectLast, SIZE sizeLast, CBrush* pBrush = NULL, CBrush* pBrushLast = NULL );

Parameters

lpRect

Points to a RECT structure or a CRect object that specifies the logical coordinates of a rectangle — in this case, the end position of the rectangle being redrawn.

size

Specifies the displacement from the top-left corner of the outer border to the top-left corner of the inner border (that is, the thickness of the border) of a rectangle.

lpRectLast

Points to a RECT structure or a CRect object that specifies the logical coordinates of the position of a rectangle — in this case, the original position of the rectangle being redrawn.

sizeLast

Specifies the displacement from the top-left corner of the outer border to the top-left corner of the inner border (that is, the thickness of the border) of the original rectangle being redrawn.

pBrush

Pointer to a brush object. Set to NULL to use the default halftone brush.

pBrushLast

Pointer to the last brush object used. Set to NULL to use the default halftone brush.

Remarks

Call this member function repeatedly to redraw a drag rectangle. Call it in a loop as you sample mouse position, in order to give visual feedback. When you call DrawDragRect, the previous rectangle is erased and a new one is drawn. For example, as the user drags a rectangle across the screen, DrawDragRect will erase the original rectangle and redraw a new one in its new position. By default, DrawDragRect draws the rectangle by using a halftone brush to eliminate flicker and to create the appearance of a smoothly moving rectangle.

The first time you call DrawDragRect, the lpRectLast parameter should be NULL.

CDC Overview | Class Members | Hierarchy Chart

See Also RECT, CRect, CDC::GetHalftoneBrush


CDC::DrawEdge

BOOL DrawEdge( LPRECT lpRect, UINT nEdge, UINT nFlags );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpRect

A pointer to a RECT structure that contains the logical coordinates of the rectangle.

nEdge

Specifies the type of inner and outer edge to draw. This parameter must be a combination of one inner-border flag and one outer-border flag. See the Remarks section for a table of the parameter’s types.

nFlags

The flags that specify the type of border to be drawn. See the Remarks section for a table of the parameter’s values:

Remarks

Call this member function to draw the edges of a rectangle of the specified type and style.

The inner and outer border flags are as follows:

  • Inner-border flags
    • BDR_RAISEDINNER Raised inner edge.

    • BDR_SUNKENINNER Sunken inner edge.
  • Outer-border flags
    • BDR_RAISEDOUTER Raised outer edge.

    • BDR_SUNKENOUTER Sunken outer edge.

The nEdge parameter must be a combination of one inner and one outer border flag. The nEdge parameter can specify one of the following flags:

  • EDGE_BUMP Combination of BDR_RAISEDOUTER and BDR_SUNKENINNER.

  • EDGE_ETCHED Combination of BDR_SUNKENOUTER and BDR_RAISEDINNER.

  • EDGE_RAISED Combination of BDR_RAISEDOUTER and BDR_RAISEDINNER.

  • EDGE_SUNKEN Combination of BDR_SUNKENOUTER and BDR_SUNKENINNER.

The nFlags parameter types are as follows:

  • BF_RECT Entire border rectangle.

  • BF_LEFT Left side of border rectangle.

  • BF_BOTTOM Bottom of border rectangle.

  • BF_RIGHT Right side of border rectangle.

  • BF_TOP Top of border rectangle.

  • BF_TOPLEFT Top and left side of border rectangle.

  • BF_TOPRIGHT Top and right side of border rectangle.

  • BF_BOTTOMLEFT Bottom and left side of border rectangle.

  • BF_BOTTOMRIGHT Bottom and right side of border rectangle.

For diagonal lines, the BF_RECT flags specify the end point of the vector bounded by the rectangle parameter.

  • BF_DIAGONAL_ENDBOTTOMLEFT Diagonal border. The end point is the bottom-left corner of the rectangle; the origin is top-right corner.

  • BF_DIAGONAL_ENDBOTTOMRIGHT Diagonal border. The end point is the bottom-right corner of the rectangle; the origin is top-left corner.

  • BF_DIAGONAL_ENDTOPLEFT Diagonal border. The end point is the top-left corner of the rectangle; the origin is bottom-right corner.

  • BF_DIAGONAL_ENDTOPRIGHT Diagonal border. The end point is the top-right corner of the rectangle; the origin is bottom-left corner.

For more information about the Windows API DrawEdge, see ::DrawEdge in the Win32 SDK Programmer’s Reference.

CDC Overview | Class Members | Hierarchy Chart

See Also ::DrawEdge


CDC::DrawEscape

int DrawEscape( int nEscape, int nInputSize, LPCSTR lpszInputData );

Return Value

Specifies the outcome of the function. Greater than zero if successful, except for the QUERYESCSUPPORT draw escape, which checks for implementation only; or zero if the escape is not implemented; or less than zero if an error occurred.

Parameters

nEscape

Specifies the escape function to be performed.

nInputSize

Specifies the number of bytes of data pointed to by the lpszInputData parameter.

lpszInputData

Points to the input structure required for the specified escape.

Remarks

Accesses drawing capabilities of a video display that are not directly available through the graphics device interface (GDI). When an application calls DrawEscape, the data identified by nInputSize and lpszInputData is passed directly to the specified display driver.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Escape, ::DrawEscape


CDC::DrawFocusRect

void DrawFocusRect( LPCRECT lpRect );

Parameters

lpRect

Points to a RECT structure or a CRect object that specifies the logical coordinates of the rectangle to be drawn.

Remarks

Draws a rectangle in the style used to indicate that the rectangle has the focus.

Since this is a Boolean XOR function, calling this function a second time with the same rectangle removes the rectangle from the display. The rectangle drawn by this function cannot be scrolled. To scroll an area containing a rectangle drawn by this function, first call DrawFocusRect to remove the rectangle from the display, then scroll the area, and then call DrawFocusRect again to draw the rectangle in the new position.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::FrameRect, ::DrawFocusRect, RECT


CDC::DrawFrameControl

BOOL DrawFrameControl( LPRECT lpRect, UINT nType, UINT nState );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpRect

A pointer to a RECT structure that contains the logical coordinates of the rectangle.

nType

Specifies the type of frame control to draw. This parameter can be one of the following values:

  • DFC_BUTTON Standard button

  • DFC_CAPTION Title bar

  • DFC_MENU Menu

  • DFC_SCROLL Scroll bar

nState

Specifies the initial state of the frame control. See the Remarks section for a table of the parameter’s values:

Remarks

Call this member function to draw a frame control of the specified type and style.

Use the nState value DFCS_ADJUSTRECT to adjust the bounding rectangle to exclude the surrounding edge of the push button. One or more of the following values can be used to set the state of the control to be drawn:

  • DFCS_CHECKED Button is checked.

  • DFCS_FLAT Button has a flat border.

  • DFCS_INACTIVE Button is inactive (grayed).

  • DFCS_MONO Button has a monochrome border.

  • DFCS_PUSHED Button is pushed.

In several cases, nState depends on the nType parameter. The following list shows the relationship between the four nType values and nState:

  • DFC_BUTTON
    • DFCS_BUTTON3STATE Three-state button

    • DFCS_BUTTONCHECK Check box

    • DFCS_BUTTONPUSH Push button

    • DFCS_BUTTONRADIO Radio button

    • DFCS_BUTTONRADIOIMAGE Image for radio button (nonsquare needs image)

    • DFCS_BUTTONRADIOMASK Mask for radio button (nonsquare needs mask)
  • DFC_CAPTION
    • DFCS_CAPTIONCLOSE Close button

    • DFCS_CAPTIONHELP Help button

    • DFCS_CAPTIONMAX Maximize button

    • DFCS_CAPTIONMIN Minimize button

    • DFCS_CAPTIONRESTORE Restore button
  • DFC_MENU
    • DFCS_MENUARROW Submenu arrow

    • DFCS_MENUBULLET Bullet

    • DFCS_MENUCHECK Check mark
  • DFC_SCROLL
    • DFCS_SCROLLCOMBOBOX Combo box scroll bar

    • DFCS_SCROLLDOWN Down arrow of scroll bar

    • DFCS_SCROLLLEFT Left arrow of scroll bar

    • DFCS_SCROLLRIGHT Right arrow of scroll bar

    • DFCS_SCROLLSIZEGRIP Size grip in bottom-right corner of window

    • DFCS_SCROLLUP Up arrow of scroll bar

For more information about the Windows API DrawFrameControl, see ::DrawFrameControl in the Win32 SDK Programmer’s Reference.

CDC Overview | Class Members | Hierarchy Chart

See Also ::DrawFrameControl


CDC::DrawIcon

BOOL DrawIcon( int x, int y, HICON hIcon );

BOOL DrawIcon( POINT point, HICON hIcon );

Return Value

Nonzero if the function completed successfully; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the upper-left corner of the icon.

y

Specifies the logical y-coordinate of the upper-left corner of the icon.

hIcon

Identifies the handle of the icon to be drawn.

point

Specifies the logical x- and y-coordinates of the upper-left corner of the icon. You can pass a POINT structure or a CPoint object for this parameter.

Remarks

Draws an icon on the device represented by the current CDC object. The function places the icon’s upper-left corner at the location specified by x and y. The location is subject to the current mapping mode of the device context.

The icon resource must have been previously loaded by using the functions CWinApp::LoadIcon, CWinApp::LoadStandardIcon, or CWinApp::LoadOEMIcon. The MM_TEXT mapping mode must be selected prior to using this function.

CDC Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadIcon, CWinApp::LoadStandardIcon, CWinApp::LoadOEMIcon, CDC::GetMapMode, CDC::SetMapMode, ::DrawIcon, POINT


CDC::DrawState

BOOL DrawState( CPoint pt, CSize size, HBITMAP hBitmap, UINT nFlags, HBRUSH hBrush = NULL );

BOOL DrawState( CPoint pt, CSize size, CBitmap* pBitmap, UINT nFlags, CBrush* pBrush = NULL );

BOOL DrawState( CPoint pt, CSize size, HICON hIcon, UINT nFlags, HBRUSH hBrush = NULL );

BOOL DrawState( CPoint pt, CSize size, HICON hIcon, UINT nFlags, CBrush* pBrush = NULL );

BOOL DrawState( CPoint pt, CSize size, LPCTSTR lpszText, UINT nFlags, BOOL bPrefixText = TRUE, int nTextLen = 0, HBRUSH hBrush = NULL );

BOOL DrawState( CPoint pt, CSize size, LPCTSTR lpszText, UINT nFlags, BOOL bPrefixText = TRUE, int nTextLen = 0, CBrush* pBrush = NULL );

BOOL DrawState( CPoint pt, CSize size, DRAWSTATEPROC lpDrawProc, LPARAM lData, UINT nFlags, HBRUSH hBrush = NULL );

BOOL DrawState( CPoint pt, CSize size, DRAWSTATEPROC lpDrawProc, LPARAM lData, UINT nFlags, CBrush* pBrush = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pt

Specifies the location of the image.

size

Specifies the size of the image.

hBitmap

A handle to a bitmap.

nFlags

Flags that specify the image type and state. See the Remarks section for the possible nFlags types and states.

hBrush

A handle to a brush.

pBitmap

A pointer to a Cbitmap object.

pBrush

A pointer to a Cbrush object.

hIcon

A handle to an icon.

lpszText

A pointer to text.

bPrefixText

Text that may contain an accelerator mnemonic. The lData parameter specifies the address of the string, and the nTextLen parameter specifies the length. If nTextLen is 0, the string is assumed to be null-terminated.

nTextLen

Length of the text string pointed to by lpszText. If nTextLen is 0, the string is assumed to be null-terminated.

lpDrawProc

A pointer to a callback function used to render an image. This parameter is required if the image type in nFlags is DST_COMPLEX. It is optional and can be NULL if the image type is DST_TEXT. For all other image types, this parameter is ignored. For more information about the callback function, see the ::DrawStateProc function in the Win32 SDK Programmer’s Reference.

lData

Specifies information about the image. The meaning of this parameter depends on the image type.

Remarks

Call this member function to display an image and apply a visual effect to indicate a state, such as a disabled or default state.

The parameter nFlag type can be set to one of the following values:

  • DST_BITMAP The image is a bitmap. The low-order word of the lData parameter is the bitmap handle.

  • DST_COMPLEX The image is application defined. To render the image, DrawState calls the callback function specified by the lpDrawProc parameter.

  • DST_ICON The image is an icon. The low-order word of lData is the icon handle.

  • DST_PREFIXTEXT The image is text that may contain an accelerator mnemonic. DrawState interprets the ampersand (&) prefix character as a directive to underscore the character that follows. The lData parameter specifies the address of the string.

  • DST_TEXT The image is text. The lData parameter specifies the address of the string.

The parameter nFlag state can be one of following values:

  • DSS_NORMAL Draws the image without any modification.

  • DSS_UNION Dithers the image.

  • DSS_DISABLED Embosses the image.

  • DSS_DEFAULT Makes the image bold.

  • DSS_MONO Draws the image using the brush specified by the hBrush or pBrush parameter.

Note For all nFlag states except DSS_NORMAL, the image is converted to monochrome before the visual effect is applied.

For more information about the Windows API DrawState, see ::DrawState in the Win32 SDK Programmer’s Reference.

CDC Overview | Class Members | Hierarchy Chart

See Also ::DrawState, ::DrawStateProc


CDC::DrawText

virtual int DrawText( LPCTSTR lpszString, int nCount, LPRECT lpRect, UINT nFormat );

int DrawText( const CString& str, LPRECT lpRect, UINT nFormat );

Return Value

The height of the text if the function is successful.

Parameters

lpszString

Points to the string to be drawn. If nCount is –1, the string must be null-terminated.

nCount

Specifies the number of chars in the string. If nCount is –1, then lpszString is assumed to be a long pointer to a null-terminated string and DrawText computes the character count automatically.

lpRect

Points to a RECT structure or CRect object that contains the rectangle (in logical coordinates) in which the text is to be formatted.

str

A CString object that contains the specified characters to be drawn.

nFormat

Specifies the method of formatting the text. It can be any combination of the following values (combine using the bitwise OR operator):

  • DT_BOTTOM Specifies bottom-justified text. This value must be combined with DT_SINGLELINE.

  • DT_CALCRECT Determines the width and height of the rectangle. If there are multiple lines of text, DrawText will use the width of the rectangle pointed to by lpRect and extend the base of the rectangle to bound the last line of text. If there is only one line of text, DrawText will modify the right side of the rectangle so that it bounds the last character in the line. In either case, DrawText returns the height of the formatted text, but does not draw the text.

  • DT_CENTER Centers text horizontally.

  • DT_END_ELLIPSIS or DT_PATH_ELLIPSIS Replaces part of the given string with ellipses, if necessary, so that the result fits in the specified rectangle. The given string is not modified unless the DT_MODIFYSTRING flag is specified.

    You can specify DT_END_ELLIPSIS to replace characters at the end of the string, or DT_PATH_ELLIPSIS to replace characters in the middle of the string. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much as possible of the text after the last backslash.

  • DT_EXPANDTABS Expands tab characters. The default number of characters per tab is eight.

  • DT_EXTERNALLEADING Includes the font’s external leading in the line height. Normally, external leading is not included in the height of a line of text.

  • DT_LEFT Aligns text flush-left.

  • DT_MODIFYSTRING Modifies the given string to match the displayed text. This flag has no effect unless the DT_END_ELLIPSIS or DT_PATH_ELLIPSIS flag is specified.

    Note Some uFormat flag combinations can cause the passed string to be modified. Using DT_MODIFYSTRING with either DT_END_ELLIPSIS or DT_PATH_ELLIPSIS may cause the string to be modified, causing an assertion in the CString override.

  • DT_NOCLIP Draws without clipping. DrawText is somewhat faster when DT_NOCLIP is used.

  • DT_NOPREFIX Turns off processing of prefix characters. Normally, DrawText interprets the ampersand (&) mnemonic-prefix character as a directive to underscore the character that follows, and the two-ampersand (&&) mnemonic-prefix characters as a directive to print a single ampersand. By specifying DT_NOPREFIX, this processing is turned off.

  • DT_PATH_ELLIPSIS

  • DT_RIGHT Aligns text flush-right.

  • DT_SINGLELINE Specifies single line only. Carriage returns and linefeeds do not break the line.

  • DT_TABSTOP Sets tab stops. The high-order byte of nFormat is the number of characters for each tab. The default number of characters per tab is eight.

  • DT_TOP Specifies top-justified text (single line only).

  • DT_VCENTER Specifies vertically centered text (single line only).

  • DT_WORDBREAK Specifies word-breaking. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by lpRect. A carriage return–linefeed sequence will also break the line.

Note The values DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX cannot be used with the DT_TABSTOP value.

Remarks

Call this member function to format text in the given rectangle. It formats text by expanding tabs into appropriate spaces, aligning text to the left, right, or center of the given rectangle, and breaking text into lines that fit within the given rectangle. The type of formatting is specified by nFormat.

This member function uses the device context’s selected font, text color, and background color to draw the text. Unless the DT_NOCLIP format is used, DrawText clips the text so that the text does not appear outside the given rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is given.

If the selected font is too large for the specified rectangle, the DrawText member function does not attempt to substitute a smaller font.

If the DT_CALCRECT flag is specified, the rectangle specified by lpRect will be updated to reflect the width and height needed to draw the text.

If the TA_UPDATECP text-alignment flag has been set (see CDC::SetTextAlign), DrawText will display text starting at the current position, rather than at the left of the given rectangle. DrawText will not wrap text when the TA_UPDATECP flag has been set (that is, the DT_WORDBREAK flag will have no effect).

The text color may be set by CDC::SetTextColor.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetTextColor, CDC::ExtTextOut, CDC::TabbedTextOut, CDC::TextOut, ::DrawText, RECT, CDC::SetTextAlign


CDC::Ellipse

BOOL Ellipse( int x1, int y1, int x2, int y2 );

BOOL Ellipse( LPCRECT lpRect );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x1

Specifies the logical x-coordinate of the upper-left corner of the ellipse’s bounding rectangle.

y1

Specifies the logical y-coordinate of the upper-left corner of the ellipse’s bounding rectangle.

x2

Specifies the logical x-coordinate of the lower-right corner of the ellipse’s bounding rectangle.

y2

Specifies the logical y-coordinate of the lower-right corner of the ellipse’s bounding rectangle.

lpRect

Specifies the ellipse’s bounding rectangle. You can also pass a CRect object for this parameter.

Remarks

Draws an ellipse. The center of the ellipse is the center of the bounding rectangle specified by x1, y1, x2, and y2, or lpRect. The ellipse is drawn with the current pen, and its interior is filled with the current brush.

The figure drawn by this function extends up to, but does not include, the right and bottom coordinates. This means that the height of the figure is y2 – y1 and the width of the figure is x2 – x1.

If either the width or the height of the bounding rectangle is 0, no ellipse is drawn.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Arc, CDC::Chord, ::Ellipse


CDC::EndDoc

int EndDoc( );

Return Value

Greater than or equal to 0 if the function is successful, or a negative value if an error occurred. The following list shows common error values:

  • SP_ERROR General error.

  • SP_OUTOFDISK Not enough disk space is currently available for spooling, and no more space will become available.

  • SP_OUTOFMEMORY Not enough memory is available for spooling.

  • SP_USERABORT User ended the job through the Print Manager.

Remarks

Ends a print job started by a call to the StartDoc member function. This member function replaces the ENDDOC printer escape, and should be called immediately after finishing a successful print job.

If an application encounters a printing error or a canceled print operation, it must not attempt to terminate the operation by using either EndDoc or AbortDoc. GDI automatically terminates the operation before returning the error value.

This function should not be used inside metafiles.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::AbortDoc, CDC::Escape, CDC::StartDoc


CDC::EndPage

int EndPage( );

Return Value

Greater than or equal to 0 if successful; otherwise it is an error value, which can be one of the following:

  • SP_ERROR General error.

  • SP_APPABORT Job was ended because the application’s abort function returned 0.

  • SP_USERABORT User ended the job through Print Manager.

  • SP_OUTOFDISK Not enough disk space is currently available for spooling, and no more space will become available.

  • SP_OUTOFMEMORY Not enough memory is available for spooling.

Remarks

Informs the device that the application has finished writing to a page. This member function is typically used to direct the device driver to advance to a new page.

This member function replaces the NEWFRAME printer escape. Unlike NEWFRAME, this function is always called after printing a page.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::StartPage, CDC::StartDoc, CDC::Escape


CDC::EndPath

BOOL EndPath( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Closes a path bracket and selects the path defined by the bracket into the device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath


CDC::EnumObjects

int EnumObjects( int nObjectType, int ( CALLBACK EXPORT* lpfn )( LPVOID, LPARAM ), LPARAM lpData );

Return Value

Specifies the last value returned by the callback function. Its meaning is user-defined.

Parameters

nObjectType

Specifies the object type. It can have the values OBJ_BRUSH or OBJ_PEN.

lpfn

Is the procedure-instance address of the application-supplied callback function. See the “Remarks” section below.

lpData

Points to the application-supplied data. The data is passed to the callback function along with the object information.

Remarks

Enumerates the pens and brushes available in a device context. For each object of a given type, the callback function that you pass is called with the information for that object. The system calls the callback function until there are no more objects or the callback function returns 0.

Note that new features of Microsoft Visual C++ let you use an ordinary function as the function passed to EnumObjects. The address passed to EnumObjects is a pointer to a function exported with EXPORT and with the Pascal calling convention. In protect-mode applications, you do not have to create this function with the Windows MakeProcInstance function or free the function after use with the FreeProcInstance Windows function.

You also do not have to export the function name in an EXPORTS statement in your application’s module-definition file. You can instead use the EXPORT function modifier, as in

int CALLBACK EXPORT AFunction( LPSTR, LPSTR );

to cause the compiler to emit the proper export record for export by name without aliasing. This works for most needs. For some special cases, such as exporting a function by ordinal or aliasing the export, you still need to use an EXPORTS statement in a module-definition file.

For compiling Microsoft Foundation programs, you will normally use the /GA and /GEs compiler options. The /Gw compiler option is not used with the Microsoft Foundation classes. (If you do use the Windows function MakeProcInstance, you will need to explicitly cast the returned function pointer from FARPROC to the type needed in this API.) Callback registration interfaces are now type-safe (you must pass in a function pointer that points to the right kind of function for the specific callback).

Also note that all callback functions must trap Microsoft Foundation exceptions before returning to Windows, since exceptions cannot be thrown across callback boundaries. For more information about exceptions, see the article Exceptions in Visual C++ Programmer's Guide.

CDC Overview | Class Members | Hierarchy Chart

See Also ::EnumObjects


CDC::Escape

virtual int Escape( int nEscape, int nCount, LPCSTR lpszInData, LPVOID lpOutData );

int ExtEscape( int nEscape, int nInputSize, LPCSTR lpszInputData,
int nOutputSize, LPSTR lpszOutputData );

Return Value

Positive if the function is successful, except for the QUERYESCSUPPORT escape, which only checks for implementation. Zero is returned if the escape is not implemented, and a negative value is returned if an error occurred. The following are common error values:

  • SP_ERROR General error.

  • SP_OUTOFDISK Not enough disk space is currently available for spooling, and no more space will become available.

  • SP_OUTOFMEMORY Not enough memory is available for spooling.

  • SP_USERABORT User ended the job through the Print Manager.

Parameters

nEscape

Specifies the escape function to be performed.

For a complete list of escape functions, see the information on printer escapes in the Windows Software Development Kit documentation.

nCount

Specifies the number of bytes of data pointed to by lpszInData.

lpszInData

Points to the input data structure required for this escape.

lpOutData

Points to the structure that is to receive output from this escape. The lpOutData parameter is NULL if no data is returned.

nInputSize

Specifies the number of bytes of data pointed to by the lpszInputData parameter.

lpszInputData

Points to the input structure required for the specified escape.

nOutputSize

Specifies the number of bytes of data pointed to by the lpszOutputData parameter.

lpszOutputData

Points to the structure that receives output from this escape. This parameter should be NULL if no data is returned.

Remarks

Allows applications to access facilities of a particular device that are not directly available through GDI. Use the first version of Escape to pass a driver-defined escape value to a device. Use the second version of Escape to pass one of the escape values defined by Windows to a device. Escape calls made by an application are translated and sent to the device driver.

The nEscape parameter specifies the escape function to be performed. For possible values, see the information on printer escapes in the Windows SDK documentation.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::StartDoc, CDC::StartPage, CDC::EndPage, CDC::SetAbortProc, CDC::AbortDoc, CDC::EndDoc, CDC::GetDeviceCaps, ::ExtEscape, ::Escape


CDC::ExcludeClipRect

virtual int ExcludeClipRect( int x1, int y1, int x2, int y2 );

virtual int ExcludeClipRect( LPCRECT lpRect );

Return Value

Specifies the new clipping region’s type. It can be any of the following values:

  • COMPLEXREGION The region has overlapping borders.

  • ERROR No region was created.

  • NULLREGION The region is empty.

  • SIMPLEREGION The region has no overlapping borders.

Parameters

x1

Specifies the logical x-coordinate of the upper-left corner of the rectangle.

y1

Specifies the logical y-coordinate of the upper-left corner of the rectangle.

x2

Specifies the logical x-coordinate of the lower-right corner of the rectangle.

y2

Specifies the logical y-coordinate of the lower-right corner of the rectangle.

lpRect

Specifies the rectangle. Can also be a CRect object.

Remarks

Creates a new clipping region that consists of the existing clipping region minus the specified rectangle.

The width of the rectangle, specified by the absolute value of x2 – x1, must not exceed 32,767 units. This limit applies to the height of the rectangle as well.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::ExcludeUpdateRgn, ::ExcludeClipRect


CDC::ExcludeUpdateRgn

int ExcludeUpdateRgn( CWnd* pWnd );

Return Value

The type of excluded region. It can be any one of the following values:

  • COMPLEXREGION The region has overlapping borders.

  • ERROR No region was created.

  • NULLREGION The region is empty.

  • SIMPLEREGION The region has no overlapping borders.

Parameters

pWnd

Points to the window object whose window is being updated.

Remarks

Prevents drawing within invalid areas of a window by excluding an updated region in the window from the clipping region associated with the CDC object.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::ExcludeClipRect, ::ExcludeUpdateRgn


CDC::ExtFloodFill

BOOL ExtFloodFill( int x, int y, COLORREF crColor, UINT nFillType );

Return Value

Nonzero if the function is successful; otherwise 0 if the filling could not be completed, if the given point has the boundary color specified by crColor (if FLOODFILLBORDER was requested), if the given point does not have the color specified by crColor (if FLOODFILLSURFACE was requested), or if the point is outside the clipping region.

Parameters

x

Specifies the logical x-coordinate of the point where filling begins.

y

Specifies the logical y-coordinate of the point where filling begins.

crColor

Specifies the color of the boundary or of the area to be filled. The interpretation of crColor depends on the value of nFillType.

nFillType

Specifies the type of flood fill to be performed. It must be either of the following values:

  • FLOODFILLBORDER The fill area is bounded by the color specified by crColor. This style is identical to the filling performed by FloodFill.

  • FLOODFILLSURFACE The fill area is defined by the color specified by crColor. Filling continues outward in all directions as long as the color is encountered. This style is useful for filling areas with multicolored boundaries.

Remarks

Fills an area of the display surface with the current brush. This member function offers more flexibility than FloodFill because you can specify a fill type in nFillType.

If nFillType is set to FLOODFILLBORDER, the area is assumed to be completely bounded by the color specified by crColor. The function begins at the point specified by x and y and fills in all directions to the color boundary.

If nFillType is set to FLOODFILLSURFACE, the function begins at the point specified by x and y and continues in all directions, filling all adjacent areas containing the color specified by crColor.

Only memory-device contexts and devices that support raster-display technology support ExtFloodFill. For more information, see the GetDeviceCaps member function.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::FloodFill, CDC::GetDeviceCaps, ::ExtFloodFill


CDC::ExtTextOut

virtual BOOL ExtTextOut( int x, int y, UINT nOptions, LPCRECT lpRect, LPCTSTR lpszString, UINT nCount, LPINT lpDxWidths );

BOOL ExtTextOut( int x, int y, UINT nOptions, LPCRECT lpRect, const CString& str, LPINT lpDxWidths );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the character cell for the first character in the specified string.

y

Specifies the logical y-coordinate of the top of the character cell for the first character in the specified string.

nOptions

Specifies the rectangle type. This parameter can be one, both, or neither of the following values:

  • ETO_CLIPPED Specifies that text is clipped to the rectangle.

  • ETO_OPAQUE Specifies that the current background color fills the rectangle. (You can set and query the current background color with the SetBkColor and GetBkColor member functions.)

lpRect

Points to a RECT structure that determines the dimensions of the rectangle. This parameter can be NULL. You can also pass a CRect object for this parameter.

lpszString

Points to the specified character string to be drawn. You can also pass a CString object for this parameter.

nCount

Specifies the number of characters in the string.

lpDxWidths

Points to an array of values that indicate the distance between origins of adjacent character cells. For instance, lpDxWidths[i] logical units will separate the origins of character cell i and character cell i + 1. If lpDxWidths is NULL, ExtTextOut uses the default spacing between characters.

str

A CString object that contains the specified characters to be drawn.

Remarks

Call this member function to write a character string within a rectangular region using the currently selected font. The rectangular region can be opaque (filled with the current background color), and it can be a clipping region.

If nOptions is 0 and lpRect is NULL, the function writes text to the device context without using a rectangular region. By default, the current position is not used or updated by the function. If an application needs to update the current position when it calls ExtTextOut, the application can call the CDC member function SetTextAlign with nFlags set to TA_UPDATECP. When this flag is set, Windows ignores x and y on subsequent calls to ExtTextOut and uses the current position instead. When an application uses TA_UPDATECP to update the current position, ExtTextOut sets the current position either to the end of the previous line of text or to the position specified by the last element of the array pointed to by lpDxWidths, whichever is greater.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetTextAlign, CDC::TabbedTextOut, CDC::TextOut, CDC::GetBkColor, CDC::SetBkColor, CDC::SetTextColor, ::ExtTextOut, RECT


CDC::FillPath

BOOL FillPath( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Closes any open figures in the current path and fills the path’s interior by using the current brush and polygon-filling mode. After its interior is filled, the path is discarded from the device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::SetPolyFillMode, CDC::StrokeAndFillPath, CDC::StrokePath, ::FillPath


CDC::FillRect

void FillRect( LPCRECT lpRect, CBrush* pBrush );

Parameters

lpRect

Points to a RECT structure that contains the logical coordinates of the rectangle to be filled. You can also pass a CRect object for this parameter.

pBrush

Identifies the brush used to fill the rectangle.

Remarks

Call this member function to fill a given rectangle using the specified brush. The function fills the complete rectangle, including the left and top borders, but it does not fill the right and bottom borders.

The brush needs to either be created using the CBrush member functions CreateHatchBrush, CreatePatternBrush, and CreateSolidBrush, or retrieved by the ::GetStockObject Windows function.

When filling the specified rectangle, FillRect does not include the rectangle’s right and bottom sides. GDI fills a rectangle up to, but does not include, the right column and bottom row, regardless of the current mapping mode. FillRect compares the values of the top, bottom, left, and right members of the specified rectangle. If bottom is less than or equal to top, or if right is less than or equal to left, the rectangle is not drawn.

FillRect is similar to CDC::FillSolidRect; however, FillRect takes a brush and therefore can be used to fill a rectangle with a solid color, a dithered color, hatched brushes, or a pattern. FillSolidRect uses only solid colors (indicated by a COLORREF parameter). FillRect usually is slower than FillSolidRect.

CDC Overview | Class Members | Hierarchy Chart

See Also CBrush::CreateHatchBrush, CBrush::CreatePatternBrush, CBrush::CreateSolidBrush, ::FillRect, ::GetStockObject, RECT, CBrush, CDC::FillSolidRect


CDC::FillRgn

BOOL FillRgn( CRgn* pRgn, CBrush* pBrush );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

pRgn

A pointer to the region to be filled. The coordinates for the given region are specified in device units.

pBrush

Identifies the brush to be used to fill the region.

Remarks

Fills the region specified by pRgn with the brush specified by pBrush.

The brush must either be created using the CBrush member functions CreateHatchBrush, CreatePatternBrush, CreateSolidBrush, or be retrieved by GetStockObject.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::PaintRgn, CDC::FillRect, CBrush, CRgn, ::FillRgn


CDC::FillSolidRect

void FillSolidRect( LPCRECT lpRect, COLORREF clr );

void FillSolidRect( int x, int y, int cx, int cy, COLORREF clr );

Parameters

lpRect

Specifies the bounding rectangle (in logical units). You can pass either a pointer to a RECT data structure or a CRect object for this parameter.

clr Specifies the color to to be used to fill the rectangle.

x

Specifies the logical x-coordinate of the upper-left corner of the rectangle.

y

Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

cx

Specifies the width of the rectangle.

cy

Specifies the height of the rectangle.

Remarks

Call this member function to fill the given rectangle with the specified solid color.

FillSolidRect is very similar to CDC::FillRect; however, FillSolidRect uses only solid colors (indicated by the COLORREF parameter), while FillRect takes a brush and therefore can be used to fill a rectangle with a solid color, a dithered color, hatched brushes, or a pattern. FillSolidRect usually is faster than FillRect.

Note When you call FillSolidRect, the background color, which was previously set using SetBkColor, is set to the color indicated by clr.

CDC Overview | Class Members | Hierarchy Chart

See Also RECT, CRect, CDC::FillRect


CDC::FlattenPath

BOOL FlattenPath( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Transforms any curves in the path selected into the current device context, and turns each curve into a sequence of lines.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::WidenPath


CDC::FloodFill

BOOL FloodFill( int x, int y, COLORREF crColor );

Return Value

Nonzero if the function is successful; otherwise 0 is returned if the filling could not be completed, the given point has the boundary color specified by crColor, or the point is outside the clipping region.

Parameters

x

Specifies the logical x-coordinate of the point where filling begins.

y

Specifies the logical y-coordinate of the point where filling begins.

crColor

Specifies the color of the boundary.

Remarks

Fills an area of the display surface with the current brush. The area is assumed to be bounded as specified by crColor. The FloodFill function begins at the point specified by x and y and continues in all directions to the color boundary.

Only memory-device contexts and devices that support raster-display technology support the FloodFill member function. For information about RC_BITBLT capability, see the GetDeviceCaps member function.

The ExtFloodFill function provides similar capability but greater flexibility.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::ExtFloodFill, CDC::GetDeviceCaps, ::FloodFill


CDC::FrameRect

void FrameRect( LPCRECT lpRect, CBrush* pBrush );

Parameters

lpRect

Points to a RECT structure or CRect object that contains the logical coordinates of the upper-left and lower-right corners of the rectangle. You can also pass a CRect object for this parameter.

pBrush

Identifies the brush to be used for framing the rectangle.

Remarks

Draws a border around the rectangle specified by lpRect. The function uses the given brush to draw the border. The width and height of the border is always 1 logical unit.

If the rectangle’s bottom coordinate is less than or equal to top, or if right is less than or equal to left, the rectangle is not drawn.

The border drawn by FrameRect is in the same position as a border drawn by the Rectangle member function using the same coordinates (if Rectangle uses a pen that is 1 logical unit wide). The interior of the rectangle is not filled by FrameRect.

CDC Overview | Class Members | Hierarchy Chart

See Also CBrush, ::FrameRect, CDC::Rectangle, CDC::FrameRgn, RECT


CDC::FrameRgn

BOOL FrameRgn( CRgn* pRgn, CBrush* pBrush, int nWidth, int nHeight );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

pRgn

Points to the CRgn object that identifies the region to be enclosed in a border. The coordinates for the given region are specified in device units.

pBrush

Points to the CBrush object that identifies the brush to be used to draw the border.

nWidth

Specifies the width of the border in vertical brush strokes in device units.

nHeight

Specifies the height of the border in horizontal brush strokes in device units.

Remarks

Draws a border around the region specified by pRgn using the brush specified by pBrush.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Rectangle, CDC::FrameRect, CBrush, CRgn, ::FrameRgn


CDC::FromHandle

static CDC* PASCAL FromHandle( HDC hDC );

Return Value

The pointer may be temporary and should not be stored beyond immediate use.

Parameters

hDC

Contains a handle to a Windows device context.

Remarks

Returns a pointer to a CDC object when given a handle to a device context. If a CDC object is not attached to the handle, a temporary CDC object is created and attached.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::DeleteTempMap


CDC::GetArcDirection

int GetArcDirection( ) const;

Return Value

Specifies the current arc direction, if successful. Following are the valid return values:

  • AD_COUNTERCLOCKWISE Arcs and rectangles drawn counterclockwise.

  • AD_CLOCKWISE Arcs and rectangles drawn clockwise.

If an error occurs, the return value is zero.

Remarks

Returns the current arc direction for the device context. Arc and rectangle functions use the arc direction.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetArcDirection, ::GetArcDirection


CDC::GetAspectRatioFilter

CSize GetAspectRatioFilter( ) const;

Return Value

A CSize object representing the aspect ratio used by the current aspect ratio filter.

Remarks

Retrieves the setting for the current aspect-ratio filter. The aspect ratio is the ratio formed by a device’s pixel width and height. Information about a device’s aspect ratio is used in the creation, selection, and display of fonts. Windows provides a special filter, the aspect-ratio filter, to select fonts designed for a particular aspect ratio from all of the available fonts. The filter uses the aspect ratio specified by the SetMapperFlags member function.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetMapperFlags, CSize


CDC::GetBkColor

COLORREF GetBkColor( ) const;

Return Value

An RGB color value.

Remarks

Returns the current background color. If the background mode is OPAQUE, the system uses the background color to fill the gaps in styled lines, the gaps between hatched lines in brushes, and the background in character cells. The system also uses the background color when converting bitmaps between color and monochrome device contexts.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetBkMode, CDC::SetBkColor, CDC::SetBkMode, ::GetBkColor


CDC::GetBkMode

int GetBkMode( ) const;

Return Value

The current background mode, which can be OPAQUE or TRANSPARENT.

Remarks

Returns the background mode. The background mode defines whether the system removes existing background colors on the drawing surface before drawing text, hatched brushes, or any pen style that is not a solid line.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetBkColor, CDC::SetBkColor, CDC::SetBkMode, ::GetBkMode


CDC::GetBoundsRect

UINT GetBoundsRect( LPRECT lpRectBounds, UINT flags );

Return Value

Specifies the current state of the bounding rectangle if the function is successful. It can be a combination of the following values:

  • DCB_ACCUMULATE Bounding rectangle accumulation is occurring.

  • DCB_RESET Bounding rectangle is empty.

  • DCB_SET Bounding rectangle is not empty.

  • DCB_ENABLE Bounding accumulation is on.

  • DCB_DISABLE Bounding accumulation is off.

Parameters

lpRectBounds

Points to a buffer that will receive the current bounding rectangle. The rectangle is returned in logical coordinates.

flags

Specifies whether the bounding rectangle is to be cleared after it is returned. This parameter can be either of the following values:

  • DCB_RESET Forces the bounding rectangle to be cleared after it is returned.

  • DCB_WINDOWMGR Queries the Windows bounding rectangle instead of the application’s.

Remarks

Returns the current accumulated bounding rectangle for the specified device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetBoundsRect, ::GetBoundsRect


CDC::GetBrushOrg

CPoint GetBrushOrg( ) const;

Return Value

The current origin of the brush (in device units) as a CPoint object.

Remarks

Retrieves the origin (in device units) of the brush currently selected for the device context.

The initial brush origin is at (0,0) of the client area. The return value specifies this point in device units relative to the origin of the desktop window.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetBrushOrg, CPoint


CDC::GetCharABCWidths

BOOL GetCharABCWidths( UINT nFirstChar, UINT nLastChar, LPABC lpabc ) const;

BOOL GetCharABCWidths( UINT nFirstChar, UINT nLastChar, LPABCFLOAT lpABCF ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nFirstChar

Specifies the first character in the range of characters from the current font for which character widths are returned.

nLastChar

Specifies the last character in the range of characters from the current font for which character widths are returned.

lpabc

Points to an array of ABC structures that receive the character widths when the function returns. This array must contain at least as many ABC structures as there are characters in the range specified by the nFirstChar and nLastChar parameters.

lpABCF

Points to an application-supplied buffer with an array of ABCFLOAT structures to receive the character widths when the function returns. The widths returned by this function are in the IEEE floating-point format.

Remarks

Retrieves the widths of consecutive characters in a specified range from the current TrueType font. The widths are returned in logical units. This function succeeds only with TrueType fonts.

The TrueType rasterizer provides “ABC” character spacing after a specific point size has been selected. “A” spacing is the distance that is added to the current position before placing the glyph. “B” spacing is the width of the black part of the glyph. “C” spacing is added to the current position to account for the white space to the right of the glyph. The total advanced width is given by A + B + C.

When the GetCharABCWidths member function retrieves negative “A” or “C” widths for a character, that character includes underhangs or overhangs.

To convert the ABC widths to font design units, an application should create a font whose height (as specified in the lfHeight member of the LOGFONT structure) is equal to the value stored in the ntmSizeEM member of the NEWTEXTMETRIC structure. (The value of the ntmSizeEM member can be retrieved by calling the EnumFontFamilies Windows function.)

The ABC widths of the default character are used for characters that are outside the range of the currently selected font.

To retrieve the widths of characters in non-TrueType fonts, applications should use the GetCharWidth member function.

CDC Overview | Class Members | Hierarchy Chart

See Also ::EnumFontFamilies, CDC::GetCharWidth, ::GetCharABCWidths, ::GetCharABCWidthsFloat, ::GetCharWidthFloat


CDC::GetCharWidth

BOOL GetCharWidth( UINT nFirstChar, UINT nLastChar, LPINT lpBuffer ) const;

BOOL GetCharWidth( UINT nFirstChar, UINT nLastChar, float* lpFloatBuffer ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nFirstChar

Specifies the first character in a consecutive group of characters in the current font.

nLastChar

Specifies the last character in a consecutive group of characters in the current font.

lpBuffer

Points to a buffer that will receive the width values for a consecutive group of characters in the current font.

lpFloatBuffer

Points to a buffer to receive the character widths. The returned widths are in the 32-bit IEEE floating-point format. (The widths are measured along the base line of the characters.)

Remarks

Retrieves the widths of individual characters in a consecutive group of characters from the current font, using m_hAttribDC, the input device context. For example, if nFirstChar identifies the letter ‘a’ and nLastChar identifies the letter ‘z’, the function retrieves the widths of all lowercase characters.

The function stores the values in the buffer pointed to by lpBuffer. This buffer must be large enough to hold all of the widths. That is, there must be at least 26 entries in the example given.

If a character in the consecutive group of characters does not exist in a particular font, it will be assigned the width value of the default character.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetOutputCharWidth, CDC::m_hAttribDC, CDC::m_hDC, CDC::GetCharABCWidths, ::GetCharWidth, ::GetCharABCWidths, ::GetCharABCWidthsFloat, ::GetCharWidthFloat


CDC::GetClipBox

virtual int GetClipBox( LPRECT lpRect ) const;

Return Value

The clipping region’s type. It can be any of the following values:

  • COMPLEXREGION Clipping region has overlapping borders.

  • ERROR Device context is not valid.

  • NULLREGION Clipping region is empty.

  • SIMPLEREGION Clipping region has no overlapping borders.

Parameters

lpRect

Points to the RECT structure or CRect object that is to receive the rectangle dimensions.

Remarks

Retrieves the dimensions of the tightest bounding rectangle around the current clipping boundary. The dimensions are copied to the buffer pointed to by lpRect.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SelectClipRgn, ::GetClipBox, RECT


CDC::GetColorAdjustment

BOOL GetColorAdjustment( LPCOLORADJUSTMENT lpColorAdjust ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpColorAdjust

Points to a COLORADJUSTMENT data structure to receive the color adjustment values.

Remarks

Retrieves the color adjustment values for the device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetColorAdjustment


CDC::GetCurrentBitmap

CBitmap* GetCurrentBitmap( ) const;

Return Value

Pointer to a CBitmap object, if successful; otherwise NULL.

Remarks

Returns a pointer to the currently selected CBitmap object. This member function may return temporary objects.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SelectObject, ::GetCurrentObject


CDC::GetCurrentBrush

CBrush* GetCurrentBrush( ) const;

Return Value

Pointer to a CBrush object, if successful; otherwise NULL.

Remarks

Returns a pointer to the currently selected CBrush object. This member function may return temporary objects.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SelectObject, ::GetCurrentObject


CDC::GetCurrentFont

CFont* GetCurrentFont( ) const;

Return Value

Pointer to a CFont object, if successful; otherwise NULL.

Remarks

Returns a pointer to the currently selected CFont object. This member function may return temporary objects.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SelectObject, ::GetCurrentObject


CDC::GetCurrentPalette

CPalette* GetCurrentPalette( ) const;

Return Value

Pointer to a CPalette object, if successful; otherwise NULL.

Remarks

Returns a pointer to the currently selected CPalette object. This member function may return temporary objects.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SelectObject, ::GetCurrentObject


CDC::GetCurrentPen

CPen* GetCurrentPen( ) const;

Return Value

Pointer to a CPen object, if successful; otherwise NULL.

Remarks

Returns a pointer to the currently selected CPen object. This member function may return temporary objects.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SelectObject, ::GetCurrentObject


CDC::GetCurrentPosition

CPoint GetCurrentPosition( ) const;

Return Value

The current position as a CPoint object.

Remarks

Retrieves the current position (in logical coordinates). The current position can be set with the MoveTo member function.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::MoveTo, CPoint


CDC::GetDeviceCaps

int GetDeviceCaps( int nIndex ) const;

Return Value

The value of the requested capability if the function is successful.

Parameters

nIndex

Specifies the type of information to return. It can be any one of the following values:

  • DRIVERVERSION Version number; for example, 0x100 for 1.0.

  • TECHNOLOGY Device technology. It can be any one of the following:
Value | Meaning
DT_PLOTTER | Vector plotter
DT_RASDISPLAY | Raster display
DT_RASPRINTER | Raster printer
DT_RASCAMERA | Raster camera
DT_CHARSTREAM | Character stream
DT_METAFILE | Metafile
DT_DISPFILE | Display file

  • HORZSIZE Width of the physical display (in millimeters).

  • VERTSIZE Height of the physical display (in millimeters).

  • HORZRES Width of the display (in pixels).

  • VERTRES Height of the display (in raster lines).

  • LOGPIXELSX Number of pixels per logical inch along the display width.

  • LOGPIXELSY Number of pixels per logical inch along the display height.

  • BITSPIXEL Number of adjacent color bits for each pixel.

  • PLANES Number of color planes.

  • NUMBRUSHES Number of device-specific brushes.

  • NUMPENS Number of device-specific pens.

  • NUMFONTS Number of device-specific fonts.

  • NUMCOLORS Number of entries in the device’s color table.

  • ASPECTX Relative width of a device pixel as used for line drawing.

  • ASPECTY Relative height of a device pixel as used for line drawing.

  • ASPECTXY Diagonal width of the device pixel as used for line drawing.

  • PDEVICESIZE Size of the PDEVICE internal data structure.

  • CLIPCAPS Clipping capabilities of the device. It can be one of the following:
Value | Meaning
CP_NONE | Output is not clipped.
CP_RECTANGLE | Output is clipped to rectangles.
CP_REGION | Output is clipped to regions.

  • SIZEPALETTE Number of entries in the system palette. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index.

  • NUMRESERVED Number of reserved entries in the system palette. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index.

  • COLORRES Actual color resolution of the device in bits per pixel. This index is valid only if the device driver sets the RC_PALETTE bit in the RASTERCAPS index.

  • RASTERCAPS Value that indicates the raster capabilities of the device. It can be a combination of the following:
Value | Meaning
RC_BANDING | Requires banding support.
RC_BIGFONT | Supports fonts larger than 64K.
RC_BITBLT | Capable of transferring bitmaps.
RC_BITMAP64 | Supports bitmaps larger than 64K.
RC_DEVBITS | Supports device bitmaps.
RC_DI_BITMAP | Capable of supporting the SetDIBits and GetDIBits Windows functions.
RC_DIBTODEV | Capable of supporting the SetDIBitsToDevice Windows function.
RC_FLOODFILL | Capable of performing flood fills.
RC_GDI20_OUTPUT | Capable of supporting Windows version 2.0 features.
RC_GDI20_STATE | Includes a state block in the device context.
RC_NONE | Supports no raster operations.
RC_OP_DX_OUTPUT | Supports dev opaque and DX array.
RC_PALETTE | Specifies a palette-based device.
RC_SAVEBITMAP | Capable of saving bitmaps locally.
RC_SCALING | Capable of scaling.
RC_STRETCHBLT | Capable of performing the StretchBlt member function.
RC_STRETCHDIB | Capable of performing the StretchDIBits Windows function.

  • CURVECAPS The curve capabilities of the device. It can be a combination of the following:
Value | Meaning
CC_NONE | Supports curves.
CC_CIRCLES | Supports circles.
CC_PIE | Supports pie wedges.
CC_CHORD | Supports chords.
CC_ELLIPSES | Supports ellipses.
CC_WIDE | Supports wide borders.
CC_STYLED | Supports styled borders.
CC_WIDESTYLED | Supports wide, styled borders.
CC_INTERIORS | Supports interiors.
CC_ROUNDRECT | Supports rectangles with rounded corners.

  • LINECAPS Line capabilities the device supports. It can be a combination of the following:
Value | Meaning
LC_NONE | Supports no lines.
LC_POLYLINE | Supports polylines.
LC_MARKER | Supports markers.
LC_POLYMARKER | Supports polymarkers.
LC_WIDE | Supports wide lines.
LC_STYLED | Supports styled lines.
LC_WIDESTYLED | Supports wide, styled lines.
LC_INTERIORS | Supports interiors.

  • POLYGONALCAPS Polygonal capabilities the device supports. It can be a combination of the following:
Value | Meaning
PC_NONE | Supports no polygons.
PC_POLYGON | Supports alternate fill polygons.
PC_RECTANGLE | Supports rectangles.
PC_WINDPOLYGON | Supports winding number fill polygons.
PC_SCANLINE | Supports scan lines.
PC_WIDE | Supports wide borders.
PC_STYLED | Supports styled borders.
PC_WIDESTYLED | Supports wide, styled borders.
PC_INTERIORS | Supports interiors.

  • TEXTCAPS Text capabilities the device supports. It can be a combination of the following:
Value | Meaning
TC_OP_CHARACTER | Supports character output precision, which indicates the device can place device fonts at any pixel location. This is required for any device with device fonts.
TC_OP_STROKE | Supports stroke output precision, which indicates the device can omit any stroke of a device font.
TC_CP_STROKE | Supports stroke clip precision, which indicates the device can clip device fonts to a pixel boundary.
TC_CR_90 | Supports 90-degree character rotation, which indicates the device can rotate characters only 90 degrees at a time.
TC_CR_ANY | Supports character rotation at any degree, which indicates the device can rotate device fonts through any angle.
TC_SF_X_YINDEP | Supports scaling independent of x and y directions, which indicates the device can scale device fonts separately in x and y directions.
TC_SA_DOUBLE | Supports doubled characters for scaling, which indicates the device can double the size of device fonts.
TC_SA_INTEGER | Supports integer multiples for scaling, which indicates the device can scale the size of device fonts in any integer multiple.
TC_SA_CONTIN | Supports any multiples for exact scaling, which indicates the device can scale device fonts by any amount but still preserve the x and y ratios.
TC_EA_DOUBLE | Supports double-weight characters, which indicates the device can make device fonts bold. If this bit is not set for printer drivers, GDI attempts to create bold device fonts by printing them twice.
TC_IA_ABLE | Supports italics, which indicates the device can make device fonts italic. If this bit is not set, GDI assumes italics are not available.
TC_UA_ABLE | Supports underlining, which indicates the device can underline device fonts. If this bit is not set, GDI creates underlines for device fonts.
TC_SO_ABLE | Supports strikeouts, which indicates the device can strikeout device fonts. If this bit is not set, GDI creates strikeouts for device fonts.
TC_RA_ABLE | Supports raster fonts, which indicates that GDI should enumerate any raster or TrueType fonts available for this device in response to a call to the EnumFonts or EnumFontFamilies Windows functions. If this bit is not set, GDI-supplied raster or TrueType fonts are not enumerated when these functions are called.
TC_VA_ABLE | Supports vector fonts, which indicates that GDI should enumerate any vector fonts available for this device in response to a call to the EnumFonts or EnumFontFamilies Windows functions. This is significant for vector devices only (that is, for plotters). Display drivers (which must be able to use raster fonts) and raster printer drivers always enumerate vector fonts, because GDI rasterizes vector fonts before sending them to the driver.
TC_RESERVED | Reserved; must be 0.

Remarks

Retrieves a wide range of device-specific information about the display device.

CDC Overview | Class Members | Hierarchy Chart

See Also ::GetDeviceCaps


CDC::GetFontData

DWORD GetFontData( DWORD dwTable, DWORD dwOffset, LPVOID lpData, DWORD cbData ) const;

Return Value

Specifies the number of bytes returned in the buffer pointed to by lpData if the function is successful; otherwise –1.

Parameters

dwTable

Specifies the name of the metric table to be returned. This parameter can be one of the metric tables documented in the TrueType Font Files specification published by Microsoft Corporation. If this parameter is 0, the information is retrieved starting at the beginning of the font file.

dwOffset

Specifies the offset from the beginning of the table at which to begin retrieving information. If this parameter is 0, the information is retrieved starting at the beginning of the table specified by the dwTable parameter. If this value is greater than or equal to the size of the table, GetFontData returns 0.

lpData

Points to a buffer that will receive the font information. If this value is NULL, the function returns the size of the buffer required for the font data specified in the dwTable parameter.

cbData

Specifies the length, in bytes, of the information to be retrieved. If this parameter is 0, GetFontData returns the size of the data specified in the dwTable parameter.

Remarks

Retrieves font-metric information from a scalable font file. The information to retrieve is identified by specifying an offset into the font file and the length of the information to return.

An application can sometimes use the GetFontData member function to save a TrueType font with a document. To do this, the application determines whether the font can be embedded and then retrieves the entire font file, specifying 0 for the dwTable, dwOffset, and cbData parameters.

Applications can determine whether a font can be embedded by checking the otmfsType member of the OUTLINETEXTMETRIC structure. If bit 1 of otmfsType is set, embedding is not permitted for the font. If bit 1 is clear, the font can be embedded. If bit 2 is set, the embedding is read only.

If an application attempts to use this function to retrieve information for a non-TrueType font, the GetFontData member function returns –1.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetOutlineTextMetrics, ::GetFontData, OUTLINETEXTMETRIC


CDC::GetGlyphOutline

DWORD GetGlyphOutline( UINT nChar, UINT nFormat, LPGLYPHMETRICS lpgm, DWORD cbBuffer, LPVOID lpBuffer, const MAT2 FAR* lpmat2 ) const;

Return Value

The size, in bytes, of the buffer required for the retrieved information if cbBuffer is 0 or lpBuffer is NULL. Otherwise, it is a positive value if the function is successful, or –1 if there is an error.

Parameters

nChar

Specifies the character for which information is to be returned.

nFormat

Specifies the format in which the function is to return information. It can be one of the following values, or 0:

Value | Meaning
GGO_BITMAP | Returns the glyph bitmap. When the function returns, the buffer pointed to by lpBuffer contains a 1-bit-per-pixel bitmap whose rows start on doubleword boundaries.
GGO_NATIVE | Returns the curve data points in the rasterizer’s native format, using device units. When this value is specified, any transformation specified in lpmat2 is ignored.

When the value of nFormat is 0, the function fills in a GLYPHMETRICS structure but does not return glyph-outline data.

lpgm

Points to a GLYPHMETRICS structure that describes the placement of the glyph in the character cell.

cbBuffer

Specifies the size of the buffer into which the function copies information about the outline character. If this value is 0 and the nFormat parameter is either the GGO_BITMAP or GGO_NATIVE values, the function returns the required size of the buffer.

lpBuffer

Points to a buffer into which the function copies information about the outline character. If nFormat specifies the GGO_NATIVE value, the information is copied in the form of TTPOLYGONHEADER and TTPOLYCURVE structures. If this value is NULL and nFormat is either the GGO_BITMAP or GGO_NATIVE value, the function returns the required size of the buffer.

lpmat2

Points to a MAT2 structure that contains a transformation matrix for the character. This parameter cannot be NULL, even when the GGO_NATIVE value is specified for nFormat.

Remarks

Retrieves the outline curve or bitmap for an outline character in the current font.

An application can rotate characters retrieved in bitmap format by specifying a 2-by-2 transformation matrix in the structure pointed to by lpmat2.

A glyph outline is returned as a series of contours. Each contour is defined by a TTPOLYGONHEADER structure followed by as many TTPOLYCURVE structures as are required to describe it. All points are returned as POINTFX structures and represent absolute positions, not relative moves. The starting point given by the pfxStart member of the TTPOLYGONHEADER structure is the point at which the outline for a contour begins. The TTPOLYCURVE structures that follow can be either polyline records or spline records. Polyline records are a series of points; lines drawn between the points describe the outline of the character. Spline records represent the quadratic curves used by TrueType (that is, quadratic b-splines).

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetOutlineTextMetrics, ::GetGlyphOutline, GLYPHMETRICS, TTPOLYGONHEADER, TTPOLYCURVE


CDC::GetHalftoneBrush

static CBrush* PASCAL GetHalftoneBrush( );

Return Value

A pointer to a CBrush object if successful; otherwise NULL.

Remarks

Call this member function to retrieve a halftone brush. A halftone brush shows pixels that are alternately foreground and background colors to create a dithered pattern. The following is an example of a dithered pattern created by a halftone brush.

CDC Overview | Class Members | Hierarchy Chart

See Also CBrush


CDC::GetKerningPairs

int GetKerningPairs( int nPairs, LPKERNINGPAIR lpkrnpair ) const;

Return Value

Specifies the number of kerning pairs retrieved or the total number of kerning pairs in the font, if the function is successful. Zero is returned if the function fails or there are no kerning pairs for the font.

Parameters

nPairs

Specifies the number of KERNINGPAIR structures pointed to by lpkrnpair. The function will not copy more kerning pairs than specified by nPairs.

lpkrnpair

Points to an array of KERNINGPAIR structures that receive the kerning pairs when the function returns. This array must contain at least as many structures as specified by nPairs. If this parameter is NULL, the function returns the total number of kerning pairs for the font.

Remarks

Retrieves the character kerning pairs for the font that is currently selected in the specified device context.

CDC Overview | Class Members | Hierarchy Chart

See Also ::GetKerningPairs, KERNINGPAIR


CDC::GetMapMode

int GetMapMode( ) const;

Return Value

The mapping mode.

Remarks

Retrieves the current mapping mode.

See the SetMapMode member function for a description of the mapping modes.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetMapMode, ::GetMapMode


CDC::GetMiterLimit

float GetMiterLimit( ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Returns the miter limit for the device context. The miter limit is used when drawing geometric lines that have miter joins.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetMiterLimit, ::GetMiterLimit


CDC::GetNearestColor

COLORREF GetNearestColor( COLORREF crColor ) const;

Return Value

An RGB (red, green, blue) color value that defines the solid color closest to the crColor value that the device can represent.

Parameters

crColor

Specifies the color to be matched.

Remarks

Returns the solid color that best matches a specified logical color. The given device must be able to represent this color.

CDC Overview | Class Members | Hierarchy Chart

See Also ::GetNearestColor, CPalette::GetNearestPaletteIndex


CDC::GetOutlineTextMetrics

UINT CDC::GetOutlineTextMetrics( UINT cbData, LPOUTLINETEXTMETRIC lpotm ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpotm

Points to an array of OUTLINETEXTMETRIC structures. If this parameter is NULL, the function returns the size of the buffer required for the retrieved metric data.

cbData

Specifies the size, in bytes, of the buffer to which information is returned.

lpotm

Points to an OUTLINETEXTMETRIC structure. If this parameter is NULL, the function returns the size of the buffer required for the retrieved metric information.

Remarks

Retrieves metric information for TrueType fonts.

The OUTLINETEXTMETRIC structure contains most of the font metric information provided with the TrueType format, including a TEXTMETRIC structure. The last four members of the OUTLINETEXTMETRIC structure are pointers to strings. Applications should allocate space for these strings in addition to the space required for the other members. Because there is no system-imposed limit to the size of the strings, the simplest method for allocating memory is to retrieve the required size by specifying NULL for lpotm in the first call to the GetOutlineTextMetrics function.

CDC Overview | Class Members | Hierarchy Chart

See Also ::GetTextMetrics, ::GetOutlineTextMetrics, CDC::GetTextMetrics


CDC::GetOutputCharWidth

BOOL GetOutputCharWidth( UINT nFirstChar, UINT nLastChar, LPINT lpBuffer ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nFirstChar

Specifies the first character in a consecutive group of characters in the current font.

nLastChar

Specifies the last character in a consecutive group of characters in the current font.

lpBuffer

Points to a buffer that will receive the width values for a consecutive group of characters in the current font.

Remarks

Uses the output device context, m_hDC, and retrieves the widths of individual characters in a consecutive group of characters from the current font. For example, if nFirstChar identifies the letter ‘a’ and nLastChar identifies the letter ‘z’, the function retrieves the widths of all lowercase characters.

The function stores the values in the buffer pointed to by lpBuffer. This buffer must be large enough to hold all of the widths; that is, there must be at least 26 entries in the example given.

If a character in the consecutive group of characters does not exist in a particular font, it will be assigned the width value of the default character.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetCharWidth, CDC::m_hAttribDC, CDC::m_hDC, ::GetCharWidth


CDC::GetOutputTabbedTextExtent

CSize GetOutputTabbedTextExtent( LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions ) const;

CSize GetOutputTabbedTextExtent( const CString& str, int nTabPositions, LPINT lpnTabStopPositions ) const;

Return Value

The dimensions of the string (in logical units) in a CSize object.

Parameters

lpszString

Points to a character string to be measured. You can also pass a CString object for this parameter.

nCount

Specifies the number of characters in the string. If nCount is –1, the length is calculated.

nTabPositions

Specifies the number of tab-stop positions in the array pointed to by lpnTabStopPositions.

lpnTabStopPositions

Points to an array of integers containing the tab-stop positions in logical units. The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array. Back tabs are not allowed.

str

A CString object that contains the specified characters to be measured.

Remarks

Call this member function to compute the width and height of a character string using m_hDC, the output device context. If the string contains one or more tab characters, the width of the string is based upon the tab stops specified by lpnTabStopPositions. The function uses the currently selected font to compute the dimensions of the string.

The current clipping region does not offset the width and height returned by the GetOutputTabbedTextExtent function.

Since some devices do not place characters in regular cell arrays (that is, they kern the characters), the sum of the extents of the characters in a string may not be equal to the extent of the string.

If nTabPositions is 0 and lpnTabStopPositions is NULL, tabs are expanded to eight average character widths. If nTabPositions is 1, the tab stops will be separated by the distance specified by the first value in the array to which lpnTabStopPositions points. If lpnTabStopPositions points to more than a single value, a tab stop is set for each value in the array, up to the number specified by nTabPositions.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTextExtent, CDC::m_hAttribDC, CDC::m_hDC, CDC::GetTabbedTextExtent, CDC::GetOutputTextExtent, CDC::TabbedTextOut, ::GetTabbedTextExtent, CSize


CDC::GetOutputTextExtent

CSize GetOutputTextExtent( LPCTSTR lpszString, int nCount ) const;

CSize GetOutputTextExtent( const CString& str ) const;

Return Value

The dimensions of the string (in logical units) returned in a CSize object.

Parameters

lpszString

Points to a string of characters. You can also pass a CString object for this parameter.

nCount

Specifies the number of characters in the string. If nCount is –1, the length is calculated.

str

A CString object that contains the specified characters to be measured.

Remarks

Call this member function to use the output device context, m_hDC, and compute the width and height of a line of text, using the current font.

The current clipping region does not affect the width and height returned by GetOutputTextExtent.

Since some devices do not place characters in regular cell arrays (that is, they carry out kerning), the sum of the extents of the characters in a string may not be equal to the extent of the string.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTabbedTextExtent, CDC::GetOutputTabbedTextExtent, CDC::m_hAttribDC, CDC::m_hDC, CDC::GetTextExtent, CDC::SetTextJustification, CSize


CDC::GetOutputTextMetrics

BOOL GetOutputTextMetrics( LPTEXTMETRIC lpMetrics ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpMetrics

Points to the TEXTMETRIC structure that receives the metrics.

Remarks

Retrieves the metrics for the current font using m_hDC, the output device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTextAlign, CDC::m_hAttribDC, CDC::m_hDC, CDC::GetTextMetrics, CDC::GetTextExtent, CDC::GetTextFace, CDC::SetTextJustification, ::GetTextMetrics


CDC::GetPath

int GetPath( LPPOINT lpPoints, LPBYTE lpTypes, int nCount ) const;

Return Value

If the nCount parameter is nonzero, the number of points enumerated. If nCount is 0, the total number of points in the path (and GetPath writes nothing to the buffers). If nCount is nonzero and is less than the number of points in the path, the return value is -1.

Parameters

lpPoints

Points to an array of POINT data structures or CPoint objects where the line endpoints and curve control points are placed.

lpTypes

Points to an array of bytes where the vertex types are placed. Values are one of the following:

  • PT_MOVETO Specifies that the corresponding point in lpPoints starts a disjoint figure.

  • PT_LINETO Specifies that the previous point and the corresponding point in lpPoints are the endpoints of a line.

  • PT_BEZIERTO Specifies that the corresponding point in lpPoints is a control point or ending point for a Bézier curve.

    PT_BEZIERTO types always occur in sets of three. The point in the path immediately preceding them defines the starting point for the Bézier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the end point (if hard-coded).

    A PT_LINETO or PT_BEZIERTO type may be combined with the following flag (by using the bitwise operator OR) to indicate that the corresponding point is the last point in a figure and that the figure should be closed:

  • PT_CLOSEFIGURE Specifies that the figure is automatically closed after the corresponding line or curve is drawn. The figure is closed by drawing a line from the line or curve endpoint to the point corresponding to the last PT_MOVETO.

nCount

Specifies the total number of POINT data structures that may be placed in the lpPoints array. This value must be the same as the number of bytes that may be placed in the lpTypes array.

Remarks

Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the device context. The device context must contain a closed path. The points of the path are returned in logical coordinates. Points are stored in the path in device coordinates, so GetPath changes the points from device coordinates to logical coordinates by using the inverse of the current transformation. The FlattenPath member function may be called before GetPath, to convert all curves in the path into line segments.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::FlattenPath, CDC::PolyDraw, CDC::WidenPath


CDC::GetPixel

COLORREF GetPixel( int x, int y ) const;

COLORREF GetPixel( POINT point ) const;

Return Value

For either version of the function, an RGB color value for the color of the given point. It is –1 if the coordinates do not specify a point in the clipping region.

Parameters

x

Specifies the logical x-coordinate of the point to be examined.

y

Specifies the logical y-coordinate of the point to be examined.

point

Specifies the logical x- and y-coordinates of the point to be examined.

Remarks

Retrieves the RGB color value of the pixel at the point specified by x and y. The point must be in the clipping region. If the point is not in the clipping region, the function has no effect and returns –1.

Not all devices support the GetPixel function. For more information, see the RC_BITBLT raster capability under the GetDeviceCaps member function.

The GetPixel member function has two forms. The first takes two coordinate values; the second takes either a POINT structure or a CPoint object.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetDeviceCaps, CDC::SetPixel, ::GetPixel, POINT, CPoint


CDC::GetPolyFillMode

int GetPolyFillMode( ) const;

Return Value

The current polygon-filled mode, ALTERNATE or WINDING, if the function is successful.

Remarks

Retrieves the current polygon-filling mode.

See the SetPolyFillMode member function for a description of the polygon-filling modes.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetPolyFillMode, ::GetPolyFillMode


CDC::GetROP2

int GetROP2( ) const;

Return Value

The drawing mode. For a list of the drawing mode values, see the SetROP2 member function.

Remarks

Retrieves the current drawing mode. The drawing mode specifies how the colors of the pen and the interior of filled objects are combined with the color already on the display surface.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetDeviceCaps, CDC::SetROP2, ::GetROP2


CDC::GetSafeHdc

HDC GetSafeHdc( ) const;

Return Value

A device context handle.

Remarks

Call this member function to get m_hDC, the output device context. This member function also works with null pointers.


CDC::GetStretchBltMode

int GetStretchBltMode( ) const;

Return Value

The return value specifies the current bitmap-stretching mode — STRETCH_ANDSCANS, STRETCH_DELETESCANS, or STRETCH_ORSCANS — if the function is successful.

Remarks

Retrieves the current bitmap-stretching mode. The bitmap-stretching mode defines how information is removed from bitmaps that are stretched or compressed by the StretchBlt member function.

The STRETCH_ANDSCANS and STRETCH_ORSCANS modes are typically used to preserve foreground pixels in monochrome bitmaps. The STRETCH_DELETESCANS mode is typically used to preserve color in color bitmaps.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::StretchBlt, CDC::SetStretchBltMode, ::GetStretchBltMode


CDC::GetTabbedTextExtent

CSize GetTabbedTextExtent( LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions ) const;

CSize GetTabbedTextExtent( const CString& str, int nTabPositions, LPINT lpnTabStopPositions ) const;

Return Value

The dimensions of the string (in logical units) in a CSize object.

Parameters

lpszString

Points to a character string. You can also pass a CString object for this parameter.

nCount

Specifies the number of characters in the string. If nCount is –1, the length is calculated.

nTabPositions

Specifies the number of tab-stop positions in the array pointed to by lpnTabStopPositions.

lpnTabStopPositions

Points to an array of integers containing the tab-stop positions in logical units. The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array. Back tabs are not allowed.

str

A CString object that contains the specified characters to be drawn.

Remarks

Call this member function to compute the width and height of a character string using m_hAttribDC, the attribute device context. If the string contains one or more tab characters, the width of the string is based upon the tab stops specified by lpnTabStopPositions. The function uses the currently selected font to compute the dimensions of the string.

The current clipping region does not offset the width and height returned by the GetTabbedTextExtent function.

Since some devices do not place characters in regular cell arrays (that is, they kern the characters), the sum of the extents of the characters in a string may not be equal to the extent of the string.

If nTabPositions is 0 and lpnTabStopPositions is NULL, tabs are expanded to eight times the average character width. If nTabPositions is 1, the tab stops will be separated by the distance specified by the first value in the array to which lpnTabStopPositions points. If lpnTabStopPositions points to more than a single value, a tab stop is set for each value in the array, up to the number specified by nTabPositions.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTextExtent, CDC::GetOutputTabbedTextExtent, CDC::GetOutputTextExtent, CDC::TabbedTextOut, ::GetTabbedTextExtent, CSize


CDC::GetTextAlign

UINT GetTextAlign( ) const;

Return Value

The status of the text-alignment flags. The return value is one or more of the following values:

  • TA_BASELINE Specifies alignment of the x-axis and the baseline of the chosen font within the bounding rectangle.

  • TA_BOTTOM Specifies alignment of the x-axis and the bottom of the bounding rectangle.

  • TA_CENTER Specifies alignment of the y-axis and the center of the bounding rectangle.

  • TA_LEFT Specifies alignment of the y-axis and the left side of the bounding rectangle.

  • TA_NOUPDATECP Specifies that the current position is not updated.

  • TA_RIGHT Specifies alignment of the y-axis and the right side of the bounding rectangle.

  • TA_TOP Specifies alignment of the x-axis and the top of the bounding rectangle.

  • TA_UPDATECP Specifies that the current position is updated.

Remarks

Retrieves the status of the text-alignment flags for the device context.

The text-alignment flags determine how the TextOut and ExtTextOut member functions align a string of text in relation to the string’s starting point. The text-alignment flags are not necessarily single-bit flags and may be equal to 0. To test whether a flag is set, an application should follow these steps:

  1. Apply the bitwise OR operator to the flag and its related flags, grouped as follows:
    • TA_LEFT, TA_CENTER, and TA_RIGHT

    • TA_BASELINE, TA_BOTTOM, and TA_TOP

    • TA_NOUPDATECP and TA_UPDATECP
  2. Apply the bitwise-AND operator to the result and the return value of GetTextAlign.

  3. Test for the equality of this result and the flag.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::ExtTextOut, CDC::SetTextAlign, CDC::TextOut, ::GetTextAlign


CDC::GetTextCharacterExtra

int GetTextCharacterExtra( ) const;

Return Value

The amount of the intercharacter spacing.

Remarks

Retrieves the current setting for the amount of intercharacter spacing. GDI adds this spacing to each character, including break characters, when it writes a line of text to the device context.

The default value for the amount of intercharacter spacing is 0.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetTextCharacterExtra, ::GetTextCharacterExtra


CDC::GetTextColor

COLORREF GetTextColor( ) const;

Return Value

The current text color as an RGB color value.

Remarks

Retrieves the current text color. The text color is the foreground color of characters drawn by using the GDI text-output member functions TextOut, ExtTextOut, and TabbedTextOut.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetBkColor, CDC::GetBkMode, CDC::SetBkMode, CDC::SetTextColor, ::GetTextColor


CDC::GetTextExtent

CSize GetTextExtent( LPCTSTR lpszString, int nCount ) const;

CSize GetTextExtent( const CString& str ) const;

Return Value

The dimensions of the string (in logical units) in a CSize object.

Parameters

lpszString

Points to a string of characters. You can also pass a CString object for this parameter.

nCount

Specifies the number of characters in the string.

str

A CString object that contains the specified characters.

Remarks

Call this member function to compute the width and height of a line of text using the current font to determine the dimensions. The information is retrieved from m_hAttribDC, the attribute device context.

The current clipping region does not affect the width and height returned by GetTextExtent.

Since some devices do not place characters in regular cell arrays (that is, they carry out kerning), the sum of the extents of the characters in a string may not be equal to the extent of the string.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTabbedTextExtent, CDC::m_hAttribDC, CDC::m_hDC, CDC::GetOutputTextExtent, CDC::SetTextJustification, CSize


CDC::GetTextFace

int GetTextFace( int nCount, LPTSTR lpszFacename ) const;

int GetTextFace( CString& rString ) const;

Return Value

The number of bytes copied to the buffer, not including the terminating null character. It is 0 if an error occurs.

Parameters

nCount

Specifies the size of the buffer (in bytes). If the typeface name is longer than the number of bytes specified by this parameter, the name is truncated.

lpszFacename

Points to the buffer for the typeface name.

rString

A reference to a CString object.

Remarks

Call this member function to copy the typeface name of the current font into a buffer. The typeface name is copied as a null-terminated string.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTextMetrics, CDC::SetTextAlign, CDC::TextOut, ::GetTextFace


CDC::GetTextMetrics

BOOL GetTextMetrics( LPTEXTMETRIC lpMetrics ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpMetrics

Points to the TEXTMETRIC structure that receives the metrics.

Remarks

Retrieves the metrics for the current font using the attribute device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTextAlign, CDC::m_hAttribDC, CDC::m_hDC, CDC::GetOutputTextMetrics, CDC::GetTextExtent, CDC::GetTextFace, CDC::SetTextJustification, ::GetTextMetrics


CDC::GetViewportExt

CSize GetViewportExt( ) const;

Return Value

The x- and y-extents (in device units) as a CSize object.

Remarks

Retrieves the x- and y-extents of the device context’s viewport.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetViewportExt, CSize, CDC::SetWindowExt


CDC::GetViewportOrg

CPoint GetViewportOrg( ) const;

Return Value

The origin of the viewport (in device coordinates) as a CPoint object.

Remarks

Retrieves the x- and y-coordinates of the origin of the viewport associated with the device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetWindowOrg, CPoint, CDC::SetViewportOrg


CDC::GetWindow

CWnd* GetWindow( ) const;

Return Value

Pointer to a CWnd object if successful; otherwise NULL.

Remarks

Returns the window associated with the display device context. This is an advanced function. For example, this member function may not return the view window when printing or in print preview. It always returns the window associated with output. Output functions that use the given DC draw into this window.

CDC Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDC, CWnd::GetWindowDC, ::GetWindow


CDC::GetWindowExt

CSize GetWindowExt( ) const;

Return Value

The x- and y-extents (in logical units) as a CSize object.

Remarks

Retrieves the x- and y-extents of the window associated with the device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetWindowExt, CSize, CDC::GetViewportExt


CDC::GetWindowOrg

CPoint GetWindowOrg( ) const;

Return Value

The origin of the window (in logical coordinates) as a CPoint object.

Remarks

Retrieves the x- and y-coordinates of the origin of the window associated with the device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetViewportOrg, CDC::SetWindowOrg, CPoint


CDC::GrayString

virtual BOOL GrayString( CBrush* pBrush, BOOL ( CALLBACK EXPORT* lpfnOutput )( HDC, LPARAM, int ), LPARAM lpData, int nCount, int x, int y, int nWidth, int nHeight );

Return Value

Nonzero if the string is drawn, or 0 if either the TextOut function or the application-supplied output function returned 0, or if there was insufficient memory to create a memory bitmap for dimming.

Parameters

pBrush

Identifies the brush to be used for dimming (graying).

lpfnOutput

Specifies the procedure-instance address of the application-supplied callback function that will draw the string. For more information, see the description of the Windows OutputFunc callback function. If this parameter is NULL, the system uses the Windows TextOut function to draw the string, and lpData is assumed to be a long pointer to the character string to be output.

lpData

Specifies a far pointer to data to be passed to the output function. If lpfnOutput is NULL, lpData must be a long pointer to the string to be output.

nCount

Specifies the number of characters to be output. If this parameter is 0, GrayString calculates the length of the string (assuming that lpData is a pointer to the string). If nCount is –1 and the function pointed to by lpfnOutput returns 0, the image is shown but not dimmed.

x

Specifies the logical x-coordinate of the starting position of the rectangle that encloses the string.

y

Specifies the logical y-coordinate of the starting position of the rectangle that encloses the string.

nWidth

Specifies the width (in logical units) of the rectangle that encloses the string. If nWidth is 0, GrayString calculates the width of the area, assuming lpData is a pointer to the string.

nHeight

Specifies the height (in logical units) of the rectangle that encloses the string. If nHeight is 0, GrayString calculates the height of the area, assuming lpData is a pointer to the string.

Remarks

Draws dimmed (gray) text at the given location by writing the text in a memory bitmap, dimming the bitmap, and then copying the bitmap to the display. The function dims the text regardless of the selected brush and background. The GrayString member function uses the currently selected font. The MM_TEXT mapping mode must be selected before using this function.

An application can draw dimmed (grayed) strings on devices that support a solid gray color without calling the GrayString member function. The system color COLOR_GRAYTEXT is the solid-gray system color used to draw disabled text. The application can call the GetSysColor Windows function to retrieve the color value of COLOR_GRAYTEXT. If the color is other than 0 (black), the application can call the SetTextColor member function to set the text color to the color value and then draw the string directly. If the retrieved color is black, the application must call GrayString to dim (gray) the text.

If lpfnOutput is NULL, GDI uses the Windows TextOut function, and lpData is assumed to be a far pointer to the character to be output. If the characters to be output cannot be handled by the TextOut member function (for example, the string is stored as a bitmap), the application must supply its own output function.

Also note that all callback functions must trap Microsoft Foundation exceptions before returning to Windows, since exceptions cannot be thrown across callback boundaries. For more information about exceptions, see the article Exceptions in Visual C++ Programmer's Guide.

The callback function passed to GrayString must use the __stdcall calling convention and must be exported with __declspec.

When the framework is in preview mode, a call to the GrayString member function is translated to a TextOut call, and the callback function is not called.

CDC Overview | Class Members | Hierarchy Chart

See Also ::GetSysColor, CDC::SetTextColor, CDC::TextOut, ::GrayString


CDC::HIMETRICtoDP

void HIMETRICtoDP( LPSIZE lpSize ) const;

Parameters

lpSize

Points to a SIZE structure or CSize object.

Remarks

Use this function when you convert HIMETRIC sizes from OLE to pixels.

If the mapping mode of the device context object is MM_LOENGLISH, MM_HIENGLISH, MM_LOMETRIC or MM_HIMETRIC, then the conversion is based on the number of pixels in the physical inch. If the mapping mode is one of the other non-constrained modes (e.g., MM_TEXT), then the conversion is based on the number of pixels in the logical inch.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::LPtoDP, CDC::HIMETRICtoLP


CDC::HIMETRICtoLP

void HIMETRICtoLP( LPSIZE lpSize ) const;

Parameters

lpSize

Points to a SIZE structure or CSize object.

Remarks

Call this function to convert HIMETRIC units into logical units. Use this function when you get HIMETRIC sizes from OLE and wish to convert them to your application’s natural mapping mode.

The conversion is accomplished by first converting the HIMETRIC units into pixels and then converting these units into logical units using the device context’s current mapping units. Note that the extents of the device’s window and viewport will affect the result.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::HIMETRICtoDP, CDC::DPtoLP


CDC::IntersectClipRect

virtual int IntersectClipRect( int x1, int y1, int x2, int y2 );

virtual int IntersectClipRect( LPCRECT lpRect );

Return Value

The new clipping region’s type. It can be any one of the following values:

  • COMPLEXREGION New clipping region has overlapping borders.

  • ERROR Device context is not valid.

  • NULLREGION New clipping region is empty.

  • SIMPLEREGION New clipping region has no overlapping borders.

Parameters

x1

Specifies the logical x-coordinate of the upper-left corner of the rectangle.

y1

Specifies the logical y-coordinate of the upper-left corner of the rectangle.

x2

Specifies the logical x-coordinate of the lower-right corner of the rectangle.

y2

Specifies the logical y-coordinate of the lower-right corner of the rectangle.

lpRect

Specifies the rectangle. You can pass either a CRect object or a pointer to a RECT structure for this parameter.

Remarks

Creates a new clipping region by forming the intersection of the current region and the rectangle specified by x1, y1, x2, and y2. GDI clips all subsequent output to fit within the new boundary. The width and height must not exceed 32,767.

CDC Overview | Class Members | Hierarchy Chart

See Also ::IntersectClipRect, CRect, RECT


CDC::InvertRect

void InvertRect( LPCRECT lpRect );

Parameters

lpRect

Points to a RECT that contains the logical coordinates of the rectangle to be inverted. You can also pass a CRect object for this parameter.

Remarks

Inverts the contents of the given rectangle. Inversion is a logical NOT operation and flips the bits of each pixel. On monochrome displays, the function makes white pixels black and black pixels white. On color displays, the inversion depends on how colors are generated for the display. Calling InvertRect twice with the same rectangle restores the display to its previous colors.

If the rectangle is empty, nothing is drawn.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::FillRect, ::InvertRect, CRect, RECT


CDC::InvertRgn

BOOL InvertRgn( CRgn* pRgn );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

pRgn

Identifies the region to be inverted. The coordinates for the region are specified in device units.

Remarks

Inverts the colors in the region specified by pRgn. On monochrome displays, the function makes white pixels black and black pixels white. On color displays, the inversion depends on how the colors are generated for the display.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::FillRgn, CDC::PaintRgn, CRgn, ::InvertRgn


CDC::IsPrinting

BOOL IsPrinting( ) const;

Return Value

Nonzero if the CDC object is a printer DC; otherwise 0.


CDC::LineTo

BOOL LineTo( int x, int y );

BOOL LineTo( POINT point );

Return Value

Nonzero if the line is drawn; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the endpoint for the line.

y

Specifies the logical y-coordinate of the endpoint for the line.

point

Specifies the endpoint for the line. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Draws a line from the current position up to, but not including, the point specified by x and y (or point). The line is drawn with the selected pen. The current position is set to x,y or to point.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::MoveTo, CDC::GetCurrentPosition, ::LineTo, CPoint, POINT


CDC::LPtoDP

void LPtoDP( LPPOINT lpPoints, int nCount = 1 ) const;

void LPtoDP( LPRECT lpRect ) const;

void LPtoDP( LPSIZE lpSize ) const;

Parameters

lpPoints

Points to an array of points. Each point in the array is a POINT structure or a CPoint object.

nCount

The number of points in the array.

lpRect

Points to a RECT structure or a CRect object. This parameter is used for the common case of mapping a rectangle from logical to device units.

lpSize

Points to a SIZE structure or a CSize object.

Remarks

Converts logical units into device units. The function maps the coordinates of each point, or dimensions of a size, from GDI’s logical coordinate system into a device coordinate system. The conversion depends on the current mapping mode and the settings of the origins and extents of the device’s window and viewport.

The x- and y-coordinates of points are 2-byte signed integers in the range –32,768 through 32,767. In cases where the mapping mode would result in values larger than these limits, the system sets the values to –32,768 and 32,767, respectively.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::DPtoLP, CDC::HIMETRICtoLP, ::LPtoDP, CDC::GetWindowOrg, CDC::GetWindowExt


CDC::LPtoHIMETRIC

void LPToHIMETRIC( LPSIZE lpSize ) const;

Parameters

lpSize

Points to a SIZE structure or a CSize object.

Remarks

Call this function to convert logical units into HIMETRIC units. Use this function when you give HIMETRIC sizes to OLE, converting from your application’s natural mapping mode. Note that the extents of the device’s window and viewport will affect the result.

The conversion is accomplished by first converting the logical units into pixels using the device context’s current mapping units and then converting these units into HIMETRIC units.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::HIMETRICtoLP, CDC::LPtoDP, CDC::DPtoHIMETRIC


CDC::MaskBlt

BOOL MaskBlt( int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, CBitmap& maskBitmap, int xMask, int yMask, DWORD dwRop );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the upper-left corner of the destination rectangle.

y

Specifies the logical y-coordinate of the upper-left corner of the destination rectangle.

nWidth

Specifies the width, in logical units, of the destination rectangle and source bitmap.

nHeight

Specifies the height, in logical units, of the destination rectangle and source bitmap.

pSrcDC

Identifies the device context from which the bitmap is to be copied. It must be zero if the dwRop parameter specifies a raster operation that does not include a source.

xSrc

Specifies the logical x-coordinate of the upper-left corner of the source bitmap.

ySrc

Specifies the logical y-coordinate of the upper-left corner of the source bitmap.

maskBitmap

Identifies the monochrome mask bitmap combined with the color bitmap in the source device context.

xMask

Specifies the horizontal pixel offset for the mask bitmap specified by the maskBitmap parameter.

yMask

Specifies the vertical pixel offset for the mask bitmap specified by the maskBitmap parameter.

dwRop

Specifies both foreground and background ternary raster operation codes, which the function uses to control the combination of source and destination data. The background raster operation code is stored in the high byte of the high word of this value; the foreground raster operation code is stored in the low byte of the high word of this value; the low word of this value is ignored, and should be zero. The macro MAKEROP4 creates such combinations of foreground and background raster operation codes. See the Remarks section for a discussion of foreground and background in the context of this function. See the BitBlt member function for a list of common raster operation codes.

Remarks

Combines the color data for the source and destination bitmaps using the given mask and raster operation. A value of 1 in the mask specified by maskBitmap indicates that the foreground raster operation code specified by dwRop should be applied at that location. A value of 0 in the mask indicates that the background raster operation code specified by dwRop should be applied at that location. If the raster operations require a source, the mask rectangle must cover the source rectangle. If it does not, the function will fail. If the raster operations do not require a source, the mask rectangle must cover the destination rectangle. If it does not, the function will fail.

If a rotation or shear transformation is in effect for the source device context when this function is called, an error occurs. However, other types of transformations are allowed.

If the color formats of the source, pattern, and destination bitmaps differ, this function converts the pattern or source format, or both, to match the destination format. If the mask bitmap is not a monochrome bitmap, an error occurs. When an enhanced metafile is being recorded, an error occurs (and the function returns 0) if the source device context identifies an enhanced-metafile device context. Not all devices support MaskBlt. An application should call GetDeviceCaps to determine whether a device supports this function. If no mask bitmap is supplied, this function behaves exactly like BitBlt, using the foreground raster operation code. The pixel offsets in the mask bitmap map to the point (0,0) in the source device context’s bitmap. This is useful for cases in which a mask bitmap contains a set of masks; an application can easily apply any one of them to a mask-blitting task by adjusting the pixel offsets and rectangle sizes sent to MaskBlt.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BitBlt, CDC::GetDeviceCaps, CDC::PlgBlt, CDC::StretchBlt, ::MaskBlt


CDC::MoveTo

CPoint MoveTo( int x, int y );

CPoint MoveTo( POINT point );

Return Value

The x- and y-coordinates of the previous position as a CPoint object.

Parameters

x

Specifies the logical x-coordinate of the new position.

y

Specifies the logical y-coordinate of the new position.

point

Specifies the new position. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Moves the current position to the point specified by x and y (or by point).

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetCurrentPosition, CDC::LineTo, CPoint, POINT


CDC::OffsetClipRgn

virtual int OffsetClipRgn( int x, int y );

virtual int OffsetClipRgn( SIZE size );

Return Value

The new region’s type. It can be any one of the following values:

  • COMPLEXREGION Clipping region has overlapping borders.

  • ERROR Device context is not valid.

  • NULLREGION Clipping region is empty.

  • SIMPLEREGION Clipping region has no overlapping borders.

Parameters

x

Specifies the number of logical units to move left or right.

y

Specifies the number of logical units to move up or down.

size

Specifies the amount to offset.

Remarks

Moves the clipping region of the device context by the specified offsets. The function moves the region x units along the x-axis and y units along the y-axis.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SelectClipRgn, ::OffsetClipRgn


CDC::OffsetViewportOrg

virtual CPoint OffsetViewportOrg( int nWidth, int nHeight );

Return Value

The previous viewport origin (in device coordinates) as a CPoint object.

Parameters

nWidth

Specifies the number of device units to add to the current origin’s x-coordinate.

nHeight

Specifies the number of device units to add to the current origin’s y-coordinate.

Remarks

Modifies the coordinates of the viewport origin relative to the coordinates of the current viewport origin.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetViewportOrg, CDC::OffsetWindowOrg, CDC::SetViewportOrg, CPoint


CDC::OffsetWindowOrg

CPoint OffsetWindowOrg( int nWidth, int nHeight );

Return Value

The previous window origin (in logical coordinates) as a CPoint object.

Parameters

nWidth

Specifies the number of logical units to add to the current origin’s x-coordinate.

nHeight

Specifies the number of logical units to add to the current origin’s y-coordinate.

Remarks

Modifies the coordinates of the window origin relative to the coordinates of the current window origin.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetWindowOrg, CDC::OffsetViewportOrg, CDC::SetWindowOrg, CPoint


CDC::PaintRgn

BOOL PaintRgn( CRgn* pRgn );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

pRgn

Identifies the region to be filled. The coordinates for the given region are specified in device units.

Remarks

Fills the region specified by pRgn using the current brush.

CDC Overview | Class Members | Hierarchy Chart

See Also CBrush, CDC::SelectObject, CDC::FillRgn, ::PaintRgn, CRgn


CDC::PatBlt

BOOL PatBlt( int x, int y, int nWidth, int nHeight, DWORD dwRop );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the upper-left corner of the rectangle that is to receive the pattern.

y

Specifies the logical y-coordinate of the upper-left corner of the rectangle that is to receive the pattern.

nWidth

Specifies the width (in logical units) of the rectangle that is to receive the pattern.

nHeight

Specifies the height (in logical units) of the rectangle that is to receive the pattern.

dwRop

Specifies the raster-operation code. Raster-operation codes (ROPs) define how GDI combines colors in output operations that involve a current brush, a possible source bitmap, and a destination bitmap. This parameter can be one of the following values:

  • PATCOPY Copies pattern to destination bitmap.

  • PATINVERT Combines destination bitmap with pattern using the Boolean XOR operator.

  • DSTINVERT Inverts the destination bitmap.

  • BLACKNESS Turns all output black.

  • WHITENESS Turns all output white.

Remarks

Creates a bit pattern on the device. The pattern is a combination of the selected brush and the pattern already on the device. The raster-operation code specified by dwRop defines how the patterns are to be combined. The raster operations listed for this function are a limited subset of the full 256 ternary raster-operation codes; in particular, a raster-operation code that refers to a source cannot be used.

Not all device contexts support the PatBlt function. To determine whether a device context supports PatBlt, call the GetDeviceCaps member function with the RASTERCAPS index and check the return value for the RC_BITBLT flag.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetDeviceCaps, ::PatBlt


CDC::Pie

BOOL Pie( int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4 );

BOOL Pie( LPCRECT lpRect, POINT ptStart, POINT ptEnd );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x1

Specifies the x-coordinate of the upper-left corner of the bounding rectangle (in logical units).

y1

Specifies the y-coordinate of the upper-left corner of the bounding rectangle (in logical units).

x2

Specifies the x-coordinate of the lower-right corner of the bounding rectangle (in logical units).

y2

Specifies the y-coordinate of the lower-right corner of the bounding rectangle (in logical units).

x3

Specifies the x-coordinate of the arc’s starting point (in logical units). This point does not have to lie exactly on the arc.

y3

Specifies the y-coordinate of the arc’s starting point (in logical units). This point does not have to lie exactly on the arc.

x4

Specifies the x-coordinate of the arc’s endpoint (in logical units). This point does not have to lie exactly on the arc.

y4

Specifies the y-coordinate of the arc’s endpoint (in logical units). This point does not have to lie exactly on the arc.

lpRect

Specifies the bounding rectangle. You can pass either a CRect object or a pointer to a RECT structure for this parameter.

ptStart

Specifies the starting point of the arc. This point does not have to lie exactly on the arc. You can pass either a POINT structure or a CPoint object for this parameter.

ptEnd

Specifies the endpoint of the arc. This point does not have to lie exactly on the arc. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Draws a pie-shaped wedge by drawing an elliptical arc whose center and two endpoints are joined by lines. The center of the arc is the center of the bounding rectangle specified by x1, y1, x2, and y2 (or by lpRect). The starting and ending points of the arc are specified by x3, y3, x4, and y4 (or by ptStart and ptEnd).

The arc is drawn with the selected pen, moving in a counterclockwise direction. Two additional lines are drawn from each endpoint to the arc’s center. The pie-shaped area is filled with the current brush. If x3 equals x4 and y3 equals y4, the result is an ellipse with a single line from the center of the ellipse to the point (x3, y3) or (x4, y4).

The figure drawn by this function extends up to but does not include the right and bottom coordinates. This means that the height of the figure is y2 – y1 and the width of the figure is x2 – x1. Both the width and the height of the bounding rectangle must be greater than 2 units and less than 32,767 units.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Chord, ::Pie, RECT, POINT, CRect, CPoint


CDC::PlayMetaFile

BOOL PlayMetaFile( HMETAFILE hMF );

BOOL PlayMetaFile( HENHMETAFILE hEnhMetaFile, LPCRECT lpBounds );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

hMF

Identifies the metafile to be played.

hEnhMetaFile

Identifies the enhanced metafile.

lpBounds

Points to a RECT structure or a CRect object that contains the coordinates of the bounding rectangle used to display the picture. The coordinates are specified in logical units.

Remarks

Plays the contents of the specified metafile on the device context. The metafile can be played any number of times.

The second version of PlayMetaFile displays the picture stored in the given enhanced-format metafile. When an application calls the second version of PlayMetaFile, Windows uses the picture frame in the enhanced-metafile header to map the picture onto the rectangle pointed to by the lpBounds parameter. (This picture may be sheared or rotated by setting the world transform in the output device before calling PlayMetaFile.) Points along the edges of the rectangle are included in the picture. An enhanced-metafile picture can be clipped by defining the clipping region in the output device before playing the enhanced metafile.

If an enhanced metafile contains an optional palette, an application can achieve consistent colors by setting up a color palette on the output device before calling the second version of PlayMetaFile. To retrieve the optional palette, use the ::GetEnhMetaFilePaletteEntries function. An enhanced metafile can be embedded in a newly created enhanced metafile by calling the second version of PlayMetaFile and playing the source enhanced metafile into the device context for the new enhanced metafile.

The states of the output device context are preserved by this function. Any object created but not deleted in the enhanced metafile is deleted by this function. To stop this function, an application can call the ::CancelDC function from another thread to terminate the operation. In this case, the function returns zero.

CDC Overview | Class Members | Hierarchy Chart

See Also ::CancelDC, ::GetEnhMetaFileHeader, ::GetEnhMetaFilePaletteEntries, ::SetWorldTransform, ::PlayMetaFile, ::PlayEnhMetaFile, ::PlayMetaFile


CDC::PlgBlt

BOOL PlgBlt( POINT lpPoint, CDC* pSrcDC, int xSrc, int ySrc, int nWidth, int nHeight, CBitmap& maskBitmap, int xMask, int yMask );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoint

Points to an array of three points in logical space that identifies three corners of the destination parallelogram. The upper-left corner of the source rectangle is mapped to the first point in this array, the upper-right corner to the second point in this array, and the lower-left corner to the third point. The lower-right corner of the source rectangle is mapped to the implicit fourth point in the parallelogram.

pSrcDC

Identifies the source device context.

xSrc

Specifies the x-coordinate, in logical units, of the upper-left corner of the source rectangle.

ySrc

Specifies the y-coordinate, in logical units, of the upper-left corner of the source rectangle.

nWidth

Specifies the width, in logical units, of the source rectangle.

nHeight

Specifies the height, in logical units, of the source rectangle.

maskBitmap

Identifies an optional monochrome bitmap that is used to mask the colors of the source rectangle.

xMask

Specifies the x-coordinate of the upper-left corner of the monochrome bitmap.

yMask

Specifies the y-coordinate of the upper-left corner of the monochrome bitmap.

Remarks

Performs a bit-block transfer of the bits of color data from the specified rectangle in the source device context to the specified parallelogram in the given device context. If the given bitmask handle identifies a valid monochrome bitmap, the function uses this bitmap to mask the bits of color data from the source rectangle.

The fourth vertex of the parallelogram (D) is defined by treating the first three points (A, B, and C) as vectors and computing D = B + C - A.

If the bitmask exists, a value of 1 in the mask indicates that the source pixel color should be copied to the destination. A value of 0 in the mask indicates that the destination pixel color is not to be changed.

If the mask rectangle is smaller than the source and destination rectangles, the function replicates the mask pattern.

Scaling, translation, and reflection transformations are allowed in the source device context; however, rotation and shear transformations are not. If the mask bitmap is not a monochrome bitmap, an error occurs. The stretching mode for the destination device context is used to determine how to stretch or compress the pixels, if that is necessary. When an enhanced metafile is being recorded, an error occurs if the source device context identifies an enhanced-metafile device context.

The destination coordinates are transformed according to the destination device context; the source coordinates are transformed according to the source device context. If the source transformation has a rotation or shear, an error is returned. If the destination and source rectangles do not have the same color format, PlgBlt converts the source rectangle to match the destination rectangle. Not all devices support PlgBlt. For more information, see the description of the RC_BITBLT raster capability in the CDC::GetDeviceCaps member function.

If the source and destination device contexts represent incompatible devices, PlgBlt returns an error.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BitBlt, CDC::GetDeviceCaps, CDC::MaskBlt, CDC::StretchBlt, ::SetStretchBltMode , ::PlgBlt


CDC::PolyBezier

BOOL PolyBezier( const POINT* lpPoints, int nCount );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoints

Points to an array of POINT data structures that contain the endpoints and control points of the spline(s).

nCount

Specifies the number of points in the lpPoints array. This value must be one more than three times the number of splines to be drawn, because each Bézier spline requires two control points and an endpoint, and the initial spline requires an additional starting point.

Remarks

Draws one or more Bézier splines. This function draws cubic Bézier splines by using the endpoints and control points specified by the lpPoints parameter. The first spline is drawn from the first point to the fourth point by using the second and third points as control points. Each subsequent spline in the sequence needs exactly three more points: the end point of the previous spline is used as the starting point, the next two points in the sequence are control points, and the third is the end point.

The current position is neither used nor updated by the PolyBezier function. The figure is not filled. This function draws lines by using the current pen.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::PolyBezierTo, ::PolyBezier


CDC::PolyBezierTo

BOOL PolyBezierTo( const POINT* lpPoints, int nCount );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoints

Points to an array of POINT data structures that contains the endpoints and control points.

nCount

Specifies the number of points in the lpPoints array. This value must be three times the number of splines to be drawn, because each Bézier spline requires two control points and an end point.

Remarks

Draws one or more Bézier splines. This function draws cubic Bézier splines by using the control points specified by the lpPoints parameter. The first spline is drawn from the current position to the third point by using the first two points as control points. For each subsequent spline, the function needs exactly three more points, and uses the end point of the previous spline as the starting point for the next. PolyBezierTo moves the current position to the end point of the last Bézier spline. The figure is not filled. This function draws lines by using the current pen.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::MoveTo, CDC::PolyBezier, ::PolyBezierTo


CDC::PolyDraw

BOOL PolyDraw( const POINT* lpPoints, const BYTE* lpTypes, int nCount );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoints

Points to an array of POINT data structures that contains the endpoints for each line segment and the endpoints and control points for each Bézier spline.

lpTypes

Points to an array that specifies how each point in the lpPoints array is used. Values can be one of the following:

  • PT_MOVETO Specifies that this point starts a disjoint figure. This point becomes the new current position.

  • PT_LINETO Specifies that a line is to be drawn from the current position to this point, which then becomes the new current position.

  • PT_BEZIERTO Specifies that this point is a control point or ending point for a Bézier spline.

    PT_BEZIERTO types always occur in sets of three. The current position defines the starting point for the Bézier spline. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending point. The ending point becomes the new current position. If there are not three consecutive PT_BEZIERTO points, an error results.

    A PT_LINETO or PT_BEZIERTO type can be combined with the following constant by using the bitwise operator OR to indicate that the corresponding point is the last point in a figure and the figure is closed:

  • PT_CLOSEFIGURE Specifies that the figure is automatically closed after the PT_LINETO or PT_BEZIERTO type for this point is done. A line is drawn from this point to the most recent PT_MOVETO or MoveTo point.

    This flag is combined with the PT_LINETO type for a line, or with the PT_BEZIERTO type of ending point for a Bézier spline, by using the bitwise OR operator. The current position is set to the ending point of the closing line.

nCount

Specifies the total number of points in the lpPoints array, the same as the number of bytes in the lpTypes array.

Remarks

Draws a set of line segments and Bézier splines. This function can be used to draw disjoint figures in place of consecutive calls to CDC::MoveTo, CDC::LineTo, and CDC::PolyBezierTo member functions. The lines and splines are drawn using the current pen, and figures are not filled. If there is an active path started by calling the CDC::BeginPath member function, PolyDraw adds to the path. The points contained in the lpPoints array and in lpTypes indicate whether each point is part of a CDC::MoveTo, a CDC::LineTo, or a CDC::BezierTo operation. It is also possible to close figures. This function updates the current position.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::EndPath, CDC::LineTo, CDC::MoveTo, CDC::PolyBezierTo, CDC::PolyLine, ::PolyDraw


CDC::Polygon

BOOL Polygon( LPPOINT lpPoints, int nCount );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoints

Points to an array of points that specifies the vertices of the polygon. Each point in the array is a POINT structure or a CPoint object.

nCount

Specifies the number of vertices in the array.

Remarks

Draws a polygon consisting of two or more points (vertices) connected by lines, using the current pen. The system closes the polygon automatically, if necessary, by drawing a line from the last vertex to the first.

The current polygon-filling mode can be retrieved or set by using the GetPolyFillMode and SetPolyFillMode member functions.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetPolyFillMode, CDC::Polyline, CDC::PolyPolygon, CDC::SetPolyFillMode, CPoint, ::Polygon


CDC::Polyline

BOOL Polyline( LPPOINT lpPoints, int nCount );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoints

Points to an array of POINT structures or CPoint objects to be connected.

nCount

Specifies the number of points in the array. This value must be at least 2.

Remarks

Draws a set of line segments connecting the points specified by lpPoints. The lines are drawn from the first point through subsequent points using the current pen. Unlike the LineTo member function, the Polyline function neither uses nor updates the current position.

For more information, see ::PolyLine in the Win32 SDK Programmer’s Reference.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::LineTo, CDC::Polygon, POINT, CPoint


CDC::PolylineTo

BOOL PolylineTo( const POINT* lpPoints, int nCount );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoints

Points to an array of POINT data structures that contains the vertices of the line.

nCount

Specifies the number of points in the array.

Remarks

Draws one or more straight lines. A line is drawn from the current position to the first point specified by the lpPoints parameter by using the current pen. For each additional line, the function draws from the ending point of the previous line to the next point specified by lpPoints. PolylineTo moves the current position to the ending point of the last line. If the line segments drawn by this function form a closed figure, the figure is not filled.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::LineTo, CDC::Polyline, CDC::MoveTo, ::PolylineTo


CDC::PolyPolygon

BOOL PolyPolygon( LPPOINT lpPoints, LPINT lpPolyCounts, int nCount );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoints

Points to an array of POINT structures or CPoint objects that define the vertices of the polygons.

lpPolyCounts

Points to an array of integers, each of which specifies the number of points in one of the polygons in the lpPoints array.

nCount

The number of entries in the lpPolyCounts array. This number specifies the number of polygons to be drawn. This value must be at least 2.

Remarks

Creates two or more polygons that are filled using the current polygon-filling mode. The polygons may be disjoint or overlapping.

Each polygon specified in a call to the PolyPolygon function must be closed. Unlike polygons created by the Polygon member function, the polygons created by PolyPolygon are not closed automatically.

The function creates two or more polygons. To create a single polygon, an application should use the Polygon member function.

The current polygon-filling mode can be retrieved or set by using the GetPolyFillMode and SetPolyFillMode member functions.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetPolyFillMode, CDC::Polygon, CDC::Polyline, CDC::SetPolyFillMode, ::PolyPolygon, POINT, CPoint


CDC::PolyPolyline

BOOL PolyPolyline( const POINT* lpPoints, const DWORD* lpPolyPoints, int nCount );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPoints

Points to an array of structures that contains the vertices of the polylines. The polylines are specified consecutively.

lpPolyPoints

Points to an array of variables specifying the number of points in the lpPoints array for the corresponding polygon. Each entry must be greater than or equal to 2.

nCount

Specifies the total number of counts in the lpPolyPoints array.

Remarks

Draws multiple series of connected line segments. The line segments are drawn by using the current pen. The figures formed by the segments are not filled. The current position is neither used nor updated by this function.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Polyline, CDC::PolylineTo, ::PolyPolyline


CDC::PtVisible

virtual BOOL PtVisible( int x, int y ) const;

virtual BOOL PtVisible( POINT point ) const;

Return Value

Nonzero if the specified point is within the clipping region; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the point.

y

Specifies the logical y-coordinate of the point.

point

Specifies the point to check in logical coordinates. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Determines whether the given point is within the clipping region of the device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::RectVisible, CDC::SelectClipRgn, CPoint, ::PtVisible, POINT


CDC::QueryAbort

BOOL QueryAbort( ) const;

Return Value

The return value is nonzero if printing should continue or if there is no abort procedure. It is 0 if the print job should be terminated. The return value is supplied by the abort function.

Remarks

Calls the abort function installed by the SetAbortProc member function for a printing application and queries whether the printing should be terminated.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetAbortProc


CDC::RealizePalette

UINT RealizePalette( );

Return Value

Indicates how many entries in the logical palette were mapped to different entries in the system palette. This represents the number of entries that this function remapped to accommodate changes in the system palette since the logical palette was last realized.

Remarks

Maps entries from the current logical palette to the system palette.

A logical color palette acts as a buffer between color-intensive applications and the system, allowing an application to use as many colors as needed without interfering with its own displayed colors or with colors displayed by other windows.

When a window has the input focus and calls RealizePalette, Windows ensures that the window will display all the requested colors, up to the maximum number simultaneously available on the screen. Windows also displays colors not found in the window’s palette by matching them to available colors.

In addition, Windows matches the colors requested by inactive windows that call the function as closely as possible to the available colors. This significantly reduces undesirable changes in the colors displayed in inactive windows.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SelectPalette, CPalette, ::RealizePalette


CDC::Rectangle

BOOL Rectangle( int x1, int y1, int x2, int y2 );

BOOL Rectangle( LPCRECT lpRect );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x1

Specifies the x-coordinate of the upper-left corner of the rectangle (in logical units).

y1

Specifies the y-coordinate of the upper-left corner of the rectangle (in logical units).

x2

Specifies the x-coordinate of the lower-right corner of the rectangle (in logical units).

y2

Specifies the y-coordinate of the lower-right corner of the rectangle (in logical units).

lpRect

Specifies the rectangle in logical units. You can pass either a CRect object or a pointer to a RECT structure for this parameter.

Remarks

Draws a rectangle using the current pen. The interior of the rectangle is filled using the current brush.

The rectangle extends up to, but does not include, the right and bottom coordinates. This means that the height of the rectangle is y2 – y1 and the width of the rectangle is x2 – x1. Both the width and the height of a rectangle must be greater than 2 units and less than 32,767 units.

CDC Overview | Class Members | Hierarchy Chart

See Also ::Rectangle, CDC::PolyLine, CDC::RoundRect, RECT, CRect


CDC::RectVisible

virtual BOOL RectVisible( LPCRECT lpRect ) const;

Return Value

Nonzero if any portion of the given rectangle lies within the clipping region; otherwise 0.

Parameters

lpRect Points to a RECT structure or a CRect object that contains the logical coordinates of the specified rectangle.

Remarks

Determines whether any part of the given rectangle lies within the clipping region of the display context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::PtVisible, CDC::SelectClipRgn, CRect, ::RectVisible, RECT


CDC::ReleaseAttribDC

virtual void ReleaseAttribDC( );

Remarks

Call this member function to set m_hAttribDC to NULL. This does not cause a Detach to occur. Only the output device context is attached to the CDC object, and only it can be detached.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetOutputDC, CDC::SetAttribDC, CDC::ReleaseOutputDC, CDC::m_hAttribDC


CDC::ReleaseOutputDC

virtual void ReleaseOutputDC( );

Remarks

Call this member function to set the m_hDC member to NULL. This member function cannot be called when the output device context is attached to the CDC object. Use the Detach member function to detach the output device context.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetAttribDC, CDC::SetOutputDC, CDC::ReleaseAttribDC, CDC::m_hDC


CDC::ResetDC

BOOL ResetDC( const DEVMODE* lpDevMode );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpDevMode

A pointer to a Windows DEVMODE structure.

Remarks

Call this member function to update the device context wrapped by the CDC object. The device context is updated from the information specified in the Windows DEVMODE structure. This member function only resets the attribute device context.

An application will typically use the ResetDC member function when a window processes a WM_DEVMODECHANGE message. You can also use this member function to change the paper orientation or paper bins while printing a document.

You cannot use this member function to change the driver name, device name, or output port. When the user changes the port connection or device name, you must delete the original device context and create a new device context with the new information.

Before you call this member function, you must ensure that all objects (other than stock objects) that had been selected into the device context have been selected out.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::m_hAttribDC, ::ResetDC, WM_DEVMODECHANGE, DEVMODE


CDC::RestoreDC

virtual BOOL RestoreDC( int nSavedDC );

Return Value

Nonzero if the specified context was restored; otherwise 0.

Parameters

nSavedDC

Specifies the device context to be restored. It can be a value returned by a previous SaveDC function call. If nSavedDC is –1, the most recently saved device context is restored.

Remarks

Restores the device context to the previous state identified by nSavedDC. RestoreDC restores the device context by popping state information off a stack created by earlier calls to the SaveDC member function.

The stack can contain the state information for several device contexts. If the context specified by nSavedDC is not at the top of the stack, RestoreDC deletes all state information between the device context specified by nSavedDC and the top of the stack. The deleted information is lost.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SaveDC, ::RestoreDC


CDC::RoundRect

BOOL RoundRect( int x1, int y1, int x2, int y2, int x3, int y3 );

BOOL RoundRect( LPCRECT lpRect, POINT point );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x1

Specifies the x-coordinate of the upper-left corner of the rectangle (in logical units).

y1

Specifies the y-coordinate of the upper-left corner of the rectangle (in logical units).

x2

Specifies the x-coordinate of the lower-right corner of the rectangle (in logical units).

y2

Specifies the y-coordinate of the lower-right corner of the rectangle (in logical units).

x3

Specifies the width of the ellipse used to draw the rounded corners (in logical units).

y3

Specifies the height of the ellipse used to draw the rounded corners (in logical units).

lpRect

Specifies the bounding rectangle in logical units. You can pass either a CRect object or a pointer to a RECT structure for this parameter.

point

The x-coordinate of point specifies the width of the ellipse to draw the rounded corners (in logical units). The y-coordinate of point specifies the height of the ellipse to draw the rounded corners (in logical units). You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Draws a rectangle with rounded corners using the current pen. The interior of the rectangle is filled using the current brush.

The figure this function draws extends up to but does not include the right and bottom coordinates. This means that the height of the figure is y2 – y1 and the width of the figure is x2 – x1. Both the height and the width of the bounding rectangle must be greater than 2 units and less than 32,767 units.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Rectangle, ::RoundRect, CRect, RECT, POINT, CPoint


CDC::SaveDC

virtual int SaveDC( );

Return Value

An integer identifying the saved device context. It is 0 if an error occurs. This return value can be used to restore the device context by calling RestoreDC.

Remarks

Saves the current state of the device context by copying state information (such as clipping region, selected objects, and mapping mode) to a context stack maintained by Windows. The saved device context can later be restored by using RestoreDC.

SaveDC can be used any number of times to save any number of device-context states.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::RestoreDC, ::SaveDC


CDC::ScaleViewportExt

virtual CSize ScaleViewportExt( int xNum, int xDenom, int yNum, int yDenom );

Return Value

The previous viewport extents (in device units) as a CSize object.

Parameters

xNum

Specifies the amount by which to multiply the current x-extent.

xDenom

Specifies the amount by which to divide the result of multiplying the current x-extent by the value of the xNum parameter.

yNum

Specifies the amount by which to multiply the current y-extent.

yDenom

Specifies the amount by which to divide the result of multiplying the current y-extent by the value of the yNum parameter.

Remarks

Modifies the viewport extents relative to the current values. The formulas are written as follows:

xNewVE = ( xOldVE * xNum ) / xDenom
yNewVE = ( yOldVE * yNum ) / yDenom

The new viewport extents are calculated by multiplying the current extents by the given numerator and then dividing by the given denominator.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetViewportExt, CSize


CDC::ScaleWindowExt

virtual CSize ScaleWindowExt( int xNum, int xDenom, int yNum, int
yDenom );

Return Value

The previous window extents (in logical units) as a CSize object.

Parameters

xNum

Specifies the amount by which to multiply the current x-extent.

xDenom

Specifies the amount by which to divide the result of multiplying the current x-extent by the value of the xNum parameter.

yNum

Specifies the amount by which to multiply the current y-extent.

yDenom

Specifies the amount by which to divide the result of multiplying the current y-extent by the value of the yNum parameter.

Remarks

Modifies the window extents relative to the current values. The formulas are written as follows:

xNewWE = ( xOldWE * xNum ) / xDenom
yNewWE = ( yOldWE * yNum ) / yDenom

The new window extents are calculated by multiplying the current extents by the given numerator and then dividing by the given denominator.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetWindowExt, CSize


CDC::ScrollDC

BOOL ScrollDC( int dx, int dy, LPCRECT lpRectScroll, LPCRECT lpRectClip, CRgn* pRgnUpdate, LPRECT lpRectUpdate );

Return Value

Nonzero if scrolling is executed; otherwise 0.

Parameters

dx

Specifies the number of horizontal scroll units.

dy

Specifies the number of vertical scroll units.

lpRectScroll

Points to the RECT structure or CRect object that contains the coordinates of the scrolling rectangle.

lpRectClip

Points to the RECT structure or CRect object that contains the coordinates of the clipping rectangle. When this rectangle is smaller than the original one pointed to by lpRectScroll, scrolling occurs only in the smaller rectangle.

pRgnUpdate

Identifies the region uncovered by the scrolling process. The ScrollDC function defines this region; it is not necessarily a rectangle.

lpRectUpdate

Points to the RECT structure or CRect object that receives the coordinates of the rectangle that bounds the scrolling update region. This is the largest rectangular area that requires repainting. The values in the structure or object when the function returns are in client coordinates, regardless of the mapping mode for the given device context.

Remarks

Scrolls a rectangle of bits horizontally and vertically.

If lpRectUpdate is NULL, Windows does not compute the update rectangle. If both pRgnUpdate and lpRectUpdate are NULL, Windows does not compute the update region. If pRgnUpdate is not NULL, Windows assumes that it contains a valid pointer to the region uncovered by the scrolling process (defined by the ScrollDC member function). The update region returned in lpRectUpdate can be passed to CWnd::InvalidateRgn if required.

An application should use the ScrollWindow member function of class CWnd when it is necessary to scroll the entire client area of a window. Otherwise, it should use ScrollDC.

CDC Overview | Class Members | Hierarchy Chart

See Also CWnd::InvalidateRgn, CWnd::ScrollWindow, ::ScrollDC, CRgn, RECT, CRect


CDC::SelectClipPath

BOOL SelectClipPath( int nMode );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nMode

Specifies the way to use the path. The following values are allowed:

  • RGN_AND The new clipping region includes the intersection (overlapping areas) of the current clipping region and the current path.

  • RGN_COPY The new clipping region is the current path.

  • RGN_DIFF The new clipping region includes the areas of the current clipping region, and those of the current path are excluded.

  • RGN_OR The new clipping region includes the union (combined areas) of the current clipping region and the current path.

  • RGN_XOR The new clipping region includes the union of the current clipping region and the current path, but without the overlapping areas.

Remarks

Selects the current path as a clipping region for the device context, combining the new region with any existing clipping region by using the specified mode. The device context identified must contain a closed path.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::EndPath


CDC::SelectClipRgn

virtual int SelectClipRgn( CRgn* pRgn );

int SelectClipRgn( CRgn* pRgn, int nMode );

Return Value

The region’s type. It can be any of the following values:

  • COMPLEXREGION New clipping region has overlapping borders.

  • ERROR Device context or region is not valid.

  • NULLREGION New clipping region is empty.

  • SIMPLEREGION New clipping region has no overlapping borders.

Parameters

pRgn

Identifies the region to be selected.

  • For the first version of this function, if this value is NULL, the entire client area is selected and output is still clipped to the window.

  • For the second version of this function, this handle can be NULL only when the RGN_COPY mode is specified.

nMode

Specifies the operation to be performed. It must be one of the following values:

  • RGN_AND The new clipping region combines the overlapping areas of the current clipping region and the region identified by pRgn.

  • RGN_COPY The new clipping region is a copy of the region identified by pRgn. This is functionality is identical to the first version of SelectClipRgn. If the region identified by pRgn is NULL, the new clipping region becomes the default clipping region (a null region).

  • RGN_DIFF The new clipping region combines the areas of the current clipping region with those areas excluded from the region identified by pRgn.

  • RGN_OR The new clipping region combines the current clipping region and the region identified by pRgn.

  • RGN_XOR The new clipping region combines the current clipping region and the region identified by pRgn but excludes any overlapping areas.

Remarks

Selects the given region as the current clipping region for the device context. Only a copy of the selected region is used. The region itself can be selected for any number of other device contexts, or it can be deleted.

The function assumes that the coordinates for the given region are specified in device units. Some printer devices support text output at a higher resolution than graphics output in order to retain the precision needed to express text metrics. These devices report device units at the higher resolution, that is, in text units. These devices then scale coordinates for graphics so that several reported device units map to only 1 graphic unit. You should always call the SelectClipRgn function using text units.

Applications that must take the scaling of graphics objects in the GDI can use the GETSCALINGFACTOR printer escape to determine the scaling factor. This scaling factor affects clipping. If a region is used to clip graphics, GDI divides the coordinates by the scaling factor. If the region is used to clip text, GDI makes no scaling adjustment. A scaling factor of 1 causes the coordinates to be divided by 2; a scaling factor of 2 causes the coordinates to be divided by 4; and so on.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetClipBox, CDC::Escape, CRgn ::SelectClipRgn


CDC::SelectObject

CPen* SelectObject( CPen* pPen );

CBrush* SelectObject( CBrush* pBrush );

virtual CFont* SelectObject( CFont* pFont );

CBitmap* SelectObject( CBitmap* pBitmap );

int SelectObject( CRgn* pRgn );

Return Value

A pointer to the object being replaced. This is a pointer to an object of one of the classes derived from CGdiObject, such as CPen, depending on which version of the function is used. The return value is NULL if there is an error. This function may return a pointer to a temporary object. This temporary object is only valid during the processing of one Windows message. For more information, see CGdiObject::FromHandle.

The version of the member function that takes a region parameter performs the same task as the SelectClipRgn member function. Its return value can be any of the following:

  • COMPLEXREGION New clipping region has overlapping borders.

  • ERROR Device context or region is not valid.

  • NULLREGION New clipping region is empty.

  • SIMPLEREGION New clipping region has no overlapping borders.

Parameters

pPen

A pointer to a CPen object to be selected.

pBrush

A pointer to a CBrush object to be selected.

pFont

A pointer to a CFont object to be selected.

pBitmap

A pointer to a CBitmap object to be selected.

pRgn

A pointer to a CRgn object to be selected.

Remarks

Selects an object into the device context. Class CDC provides five versions specialized for particular kinds of GDI objects, including pens, brushes, fonts, bitmaps, and regions. The newly selected object replaces the previous object of the same type. For example, if pObject of the general version of SelectObject points to a CPen object, the function replaces the current pen with the pen specified by pObject.

An application can select a bitmap into memory device contexts only and into only one memory device context at a time. The format of the bitmap must either be monochrome or compatible with the device context; if it is not, SelectObject returns an error.

For Windows 3.1 and later, the SelectObject function returns the same value whether it is used in a metafile or not. Under previous versions of Windows, SelectObject returned a nonzero value for success and 0 for failure when it was used in a metafile.

CDC Overview | Class Members | Hierarchy Chart

See Also CGdiObject::DeleteObject, CGdiObject::FromHandle, CDC::SelectClipRgn, CDC::SelectPalette, ::SelectObject


CDC::SelectPalette

CPalette* SelectPalette( CPalette* pPalette, BOOL bForceBackground );

Return Value

A pointer to a CPalette object identifying the logical palette replaced by the palette specified by pPalette. It is NULL if there is an error.

Parameters

pPalette

Identifies the logical palette to be selected. This palette must already have been created with the CPalette member function CreatePalette.

bForceBackground

Specifies whether the logical palette is forced to be a background palette. If bForceBackground is nonzero, the selected palette is always a background palette, regardless of whether the window has the input focus. If bForceBackground is 0 and the device context is attached to a window, the logical palette is a foreground palette when the window has the input focus.

Remarks

Selects the logical palette that is specified by pPalette as the selected palette object of the device context. The new palette becomes the palette object used by GDI to control colors displayed in the device context and replaces the previous palette.

An application can select a logical palette into more than one device context. However, changes to a logical palette will affect all device contexts for which it is selected. If an application selects a palette into more than one device context, the device contexts must all belong to the same physical device.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::RealizePalette, CPalette, ::SelectPalette


CDC::SelectStockObject

virtual CGdiObject* SelectStockObject( int nIndex );

Return Value

A pointer to the CGdiObject object that was replaced if the function is successful. The actual object pointed to is a CPen, CBrush, or CFont object. If the call is unsuccessful, the return value is NULL.

Parameters

nIndex

Specifies the kind of stock object desired. It can be one of the following values:

  • BLACK_BRUSH Black brush.

  • DKGRAY_BRUSH Dark gray brush.

  • GRAY_BRUSH Gray brush.

  • HOLLOW_BRUSH Hollow brush.

  • LTGRAY_BRUSH Light gray brush.

  • NULL_BRUSH Null brush.

  • WHITE_BRUSH White brush.

  • BLACK_PEN Black pen.

  • NULL_PEN Null pen.

  • WHITE_PEN White pen.

  • ANSI_FIXED_FONT ANSI fixed system font.

  • ANSI_VAR_FONT ANSI variable system font.

  • DEVICE_DEFAULT_FONT Device-dependent font.

  • OEM_FIXED_FONT OEM-dependent fixed font.

  • SYSTEM_FONT The system font. By default, Windows uses the system font to draw menus, dialog-box controls, and other text. In Windows versions 3.0 and later, the system font is proportional width; earlier versions of Windows use a fixed-width system font.

  • SYSTEM_FIXED_FONT The fixed-width system font used in Windows prior to version 3.0. This object is available for compatibility with earlier versions of Windows.

  • DEFAULT_PALETTE Default color palette. This palette consists of the 20 static colors in the system palette.

Remarks

Selects a CGdiObject object that corresponds to one of the predefined stock pens, brushes, or fonts.

CDC Overview | Class Members | Hierarchy Chart

See Also CGdiObject::GetObject


CDC::SetAbortProc

int SetAbortProc( BOOL ( CALLBACK EXPORT* lpfn )( HDC, int ) );

Return Value

Specifies the outcome of the SetAbortProc function. Some of the following values are more probable than others, but all are possible.

  • SP_ERROR General error.

  • SP_OUTOFDISK Not enough disk space is currently available for spooling, and no more space will become available.

  • SP_OUTOFMEMORY Not enough memory is available for spooling.

  • SP_USERABORT User ended the job through the Print Manager.

Parameters

lpfn

A pointer to the abort function to install as the abort procedure. For more about the callback function, see Callback Function for CDC::SetAbortProc.

Remarks

Installs the abort procedure for the print job.

If an application is to allow the print job to be canceled during spooling, it must set the abort function before the print job is started with the StartDoc member function. The Print Manager calls the abort function during spooling to allow the application to cancel the print job or to process out-of-disk-space conditions. If no abort function is set, the print job will fail if there is not enough disk space for spooling.

Note that the features of Microsoft Visual C++ simplify the creation of the callback function passed to SetAbortProc. The address passed to the EnumObjects member function is a pointer to a function exported with __declspec(dllexport) and with the __stdcall calling convention.

You also do not have to export the function name in an EXPORTS statement in your application’s module-definition file. You can instead use the EXPORT function modifier, as in

BOOL CALLBACK EXPORT AFunction( HDC, int );

to cause the compiler to emit the proper export record for export by name without aliasing. This works for most needs. For some special cases, such as exporting a function by ordinal or aliasing the export, you still need to use an EXPORTS statement in a module-definition file.

Callback registration interfaces are now type-safe (you must pass in a function pointer that points to the right kind of function for the specific callback).

Also note that all callback functions must trap Microsoft Foundation exceptions before returning to Windows, since exceptions cannot be thrown across callback boundaries. For more information about exceptions, see the article Exceptions in Visual C++ Programmer's Guide.


CDC::SetArcDirection

int SetArcDirection( int nArcDirection );

Return Value

Specifies the old arc direction, if successful; otherwise 0.

Parameters

nArcDirection

Specifies the new arc direction. This parameter can be either of the following values:

  • AD_COUNTERCLOCKWISE Figures drawn counterclockwise.

  • AD_CLOCKWISE Figures drawn clockwise.

Remarks

Sets the drawing direction to be used for arc and rectangle functions. The default direction is counterclockwise. The SetArcDirection function specifies the direction in which the following functions draw:

Arc | Pie
ArcTo | Rectangle
Chord | RoundRect
Ellipse |

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetArcDirection, ::SetArcDirection


CDC::SetAttribDC

virtual void SetAttribDC( HDC hDC );

Parameters

hDC

A Windows device context.

Remarks

Call this function to set the attribute device context, m_hAttribDC. This member function does not attach the device context to the CDC object. Only the output device context is attached to a CDC object.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetOutputDC, CDC::ReleaseAttribDC, CDC::ReleaseOutputDC


CDC::SetBkColor

virtual COLORREF SetBkColor( COLORREF crColor );

Return Value

The previous background color as an RGB color value. If an error occurs, the return value is 0x80000000.

Parameters

crColor

Specifies the new background color.

Remarks

Sets the current background color to the specified color. If the background mode is OPAQUE, the system uses the background color to fill the gaps in styled lines, the gaps between hatched lines in brushes, and the background in character cells. The system also uses the background color when converting bitmaps between color and monochrome device contexts.

If the device cannot display the specified color, the system sets the background color to the nearest physical color.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BitBlt, CDC::GetBkColor, CDC::GetBkMode, CDC::SetBkMode, CDC::StretchBlt, ::SetBkColor


CDC::SetBkMode

int SetBkMode( int nBkMode );

Return Value

The previous background mode.

Parameters

nBkMode

Specifies the mode to be set. This parameter can be either of the following values:

  • OPAQUE Background is filled with the current background color before the text, hatched brush, or pen is drawn. This is the default background mode.

  • TRANSPARENT Background is not changed before drawing.

Remarks

Sets the background mode. The background mode defines whether the system removes existing background colors on the drawing surface before drawing text, hatched brushes, or any pen style that is not a solid line.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetBkColor, CDC::GetBkMode, CDC::SetBkColor, ::SetBkMode


CDC::SetBoundsRect

UINT SetBoundsRect( LPCRECT lpRectBounds, UINT flags );

Return Value

The current state of the bounding rectangle, if the function is successful. Like flags, the return value can be a combination of DCB_ values:

  • DCB_ACCUMULATE The bounding rectangle is not empty. This value will always be set.

  • DCB_DISABLE Bounds accumulation is off.

  • DCB_ENABLE Bounds accumulation is on.

Parameters

lpRectBounds

Points to a RECT structure or CRect object that is used to set the bounding rectangle. Rectangle dimensions are given in logical coordinates. This parameter can be NULL.

flags

Specifies how the new rectangle will be combined with the accumulated rectangle. This parameter can be a combination of the following values:

  • DCB_ACCUMULATE Add the rectangle specified by lpRectBounds to the bounding rectangle (using a rectangle-union operation).

  • DCB_DISABLE Turn off bounds accumulation.

  • DCB_ENABLE Turn on bounds accumulation. (The default setting for bounds accumulation is disabled.)

Remarks

Controls the accumulation of bounding-rectangle information for the specified device context.

Windows can maintain a bounding rectangle for all drawing operations. This rectangle can be queried and reset by the application. The drawing bounds are useful for invalidating bitmap caches.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetBoundsRect, ::SetBoundsRect, RECT, CRect


CDC::SetBrushOrg

CPoint SetBrushOrg( int x, int y );

CPoint SetBrushOrg( POINT point );

Return Value

The previous origin of the brush in device units.

Parameters

x

Specifies the x-coordinate (in device units) of the new origin. This value must be in the range 0–7.

y

Specifies the y-coordinate (in device units) of the new origin. This value must be in the range 0–7.

point

Specifies the x- and y-coordinates of the new origin. Each value must be in the range 0–7. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Specifies the origin that GDI will assign to the next brush that the application selects into the device context.

The default coordinates for the brush origin are (0, 0). To alter the origin of a brush, call the UnrealizeObject function for the CBrush object, call SetBrushOrg, and then call the SelectObject member function to select the brush into the device context.

Do not use SetBrushOrg with stock CBrush objects.

CDC Overview | Class Members | Hierarchy Chart

See Also CBrush, CDC::GetBrushOrg, CDC::SelectObject, CGdiObject::UnrealizeObject, POINT, CPoint


CDC::SetColorAdjustment

BOOL SetColorAdjustment( const COLORADJUSTMENT* lpColorAdjust );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpColorAdjust

Points to a COLORADJUSTMENT data structure containing the color adjustment values.

Remarks

Sets the color adjustment values for the device context using the specified values. The color adjustment values are used to adjust the input color of the source bitmap for calls to the CDC::StretchBlt member function when HALFTONE mode is set.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetStretchBltMode, CDC::StretchBlt, ::StretchDIBits


CDC::SetMapMode

virtual int SetMapMode( int nMapMode );

Return Value

The previous mapping mode.

Parameters

nMapMode

Specifies the new mapping mode. It can be any one of the following values:

MM_ANISOTROPIC Logical units are converted to arbitrary units with arbitrarily scaled axes. Setting the mapping mode to MM_ANISOTROPIC does not change the current window or viewport settings. To change the units, orientation, and scaling, call the SetWindowExt and SetViewportExt member functions.

  • MM_HIENGLISH Each logical unit is converted to 0.001 inch. Positive x is to the right; positive y is up.

  • MM_HIMETRIC Each logical unit is converted to 0.01 millimeter. Positive x is to the right; positive y is up.

  • MM_ISOTROPIC Logical units are converted to arbitrary units with equally scaled axes; that is, 1 unit along the x-axis is equal to 1 unit along the y-axis. Use the SetWindowExt and SetViewportExt member functions to specify the desired units and the orientation of the axes. GDI makes adjustments as necessary to ensure that the x and y units remain the same size.

  • MM_LOENGLISH Each logical unit is converted to 0.01 inch. Positive x is to the right; positive y is up.

  • MM_LOMETRIC Each logical unit is converted to 0.1 millimeter. Positive x is to the right; positive y is up.

  • MM_TEXT Each logical unit is converted to 1 device pixel. Positive x is to the right; positive y is down.

  • MM_TWIPS Each logical unit is converted to 1/20 of a point. (Because a point is 1/72 inch, a twip is 1/1440 inch.) Positive x is to the right; positive y is up.

Remarks

Sets the mapping mode. The mapping mode defines the unit of measure used to convert logical units to device units; it also defines the orientation of the device’s x- and y-axes. GDI uses the mapping mode to convert logical coordinates into the appropriate device coordinates. The MM_TEXT mode allows applications to work in device pixels, where 1 unit is equal to 1 pixel. The physical size of a pixel varies from device to device.

The MM_HIENGLISH, MM_HIMETRIC, MM_LOENGLISH, MM_LOMETRIC, and MM_TWIPS modes are useful for applications that must draw in physically meaningful units (such as inches or millimeters). The MM_ISOTROPIC mode ensures a 1:1 aspect ratio, which is useful when it is important to preserve the exact shape of an image. The MM_ANISOTROPIC mode allows the x- and y-coordinates to be adjusted independently.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetViewportExt, CDC::SetWindowExt, ::SetMapMode


CDC::SetMapperFlags

DWORD SetMapperFlags( DWORD dwFlag );

Return Value

The previous value of the font-mapper flag.

Parameters

dwFlag

Specifies whether the font mapper attempts to match a font’s aspect height and width to the device. When this value is ASPECT_FILTERING, the mapper selects only fonts whose x-aspect and y-aspect exactly match those of the specified device.

Remarks

Changes the method used by the font mapper when it converts a logical font to a physical font. An application can use SetMapperFlags to cause the font mapper to attempt to choose only a physical font that exactly matches the aspect ratio of the specified device.

An application that uses only raster fonts can use the SetMapperFlags function to ensure that the font selected by the font mapper is attractive and readable on the specified device. Applications that use scalable (TrueType) fonts typically do not use SetMapperFlags.

If no physical font has an aspect ratio that matches the specification in the logical font, GDI chooses a new aspect ratio and selects a font that matches this new aspect ratio.

CDC Overview | Class Members | Hierarchy Chart

See Also ::SetMapperFlags


CDC::SetMiterLimit

BOOL SetMiterLimit( float fMiterLimit );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

fMiterLimit

Specifies the new miter limit for the device context.

Remarks

Sets the limit for the length of miter joins for the device context. The miter length is defined as the distance from the intersection of the line walls on the inside of the join to the intersection of the line walls on the outside of the join. The miter limit is the maximum allowed ratio of the miter length to the line width. The default miter limit is 10.0.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetMiterLimit, ::SetMiterLimit


CDC::SetOutputDC

virtual void SetOutputDC( HDC hDC );

Parameters

hDC

A Windows device context.

Remarks

Call this member function to set the output device context, m_hDC. This member function can only be called when a device context has not been attached to the CDC object. This member function sets m_hDC but does not attach the device context to the CDC object.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetAttribDC, CDC::ReleaseAttribDC, CDC::ReleaseOutputDC, CDC::m_hDC


CDC::SetPixel

COLORREF SetPixel( int x, int y, COLORREF crColor );

COLORREF SetPixel( POINT point, COLORREF crColor );

Return Value

An RGB value for the color that the point is actually painted. This value can be different from that specified by crColor if an approximation of that color is used. If the function fails (if the point is outside the clipping region), the return value is –1.

Parameters

x

Specifies the logical x-coordinate of the point to be set.

y

Specifies the logical y-coordinate of the point to be set.

crColor

Specifies the color used to paint the point.

point

Specifies the logical x- and y-coordinates of the point to be set. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Sets the pixel at the point specified to the closest approximation of the color specified by crColor. The point must be in the clipping region. If the point is not in the clipping region, the function does nothing.

Not all devices support the SetPixel function. To determine whether a device supports SetPixel, call the GetDeviceCaps member function with the RASTERCAPS index and check the return value for the RC_BITBLT flag.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetDeviceCaps, CDC::GetPixel, ::SetPixel, POINT, CPoint


CDC::SetPixelV

BOOL SetPixelV(int x, int y, COLORREF crColor);

BOOL SetPixelV( POINT point, COLORREF crColor );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x

Specifies the x-coordinate, in logical units, of the point to be set.

y

Specifies the y-coordinate, in logical units, of the point to be set.

crColor

Specifies the color to be used to paint the point.

point

Specifies the logical x- and y-coordinates of the point to be set. You can pass either a POINT data structure or a CPoint object for this parameter.

Remarks

Sets the pixel at the specified coordinates to the closest approximation of the specified color. The point must be in both the clipping region and the visible part of the device surface. Not all devices support the member function. For more information, see the RC_BITBLT capability in the CDC::GetDeviceCaps member function. SetPixelV is faster than SetPixel because it does not need to return the color value of the point actually painted.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetDeviceCaps, CDC::SetPixel, ::SetPixelV


CDC::SetPolyFillMode

int SetPolyFillMode( int nPolyFillMode );

Return Value

The previous filling mode, if successful; otherwise 0.

Parameters

nPolyFillMode

Specifies the new filling mode. This value may be either ALTERNATE or WINDING. The default mode set in Windows is ALTERNATE.

Remarks

Sets the polygon-filling mode.

When the polygon-filling mode is ALTERNATE, the system fills the area between odd-numbered and even-numbered polygon sides on each scan line. That is, the system fills the area between the first and second side, between the third and fourth side, and so on. This mode is the default.

When the polygon-filling mode is WINDING, the system uses the direction in which a figure was drawn to determine whether to fill an area. Each line segment in a polygon is drawn in either a clockwise or a counterclockwise direction. Whenever an imaginary line drawn from an enclosed area to the outside of a figure passes through a clockwise line segment, a count is incremented. When the line passes through a counterclockwise line segment, the count is decremented. The area is filled if the count is nonzero when the line reaches the outside of the figure.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetPolyFillMode, CDC::PolyPolygon, ::SetPolyFillMode


CDC::SetROP2

int SetROP2( int nDrawMode );

Return Value

The previous drawing mode.

It can be any of the values given in the Windows SDK documentation.

Parameters

nDrawMode

Specifies the new drawing mode. It can be any of the following values:

  • R2_BLACK Pixel is always black.

  • R2_WHITE Pixel is always white.

  • R2_NOP Pixel remains unchanged.

  • R2_NOT Pixel is the inverse of the screen color.

  • R2_COPYPEN Pixel is the pen color.

  • R2_NOTCOPYPEN Pixel is the inverse of the pen color.

  • R2_MERGEPENNOT Pixel is a combination of the pen color and the inverse of the screen color (final pixel = (NOT screen pixel) OR pen).

  • R2_MASKPENNOT Pixel is a combination of the colors common to both the pen and the inverse of the screen (final pixel = (NOT screen pixel) AND pen).

  • R2_MERGENOTPEN Pixel is a combination of the screen color and the inverse of the pen color (final pixel = (NOT pen) OR screen pixel).

  • R2_MASKNOTPEN Pixel is a combination of the colors common to both the screen and the inverse of the pen (final pixel = (NOT pen) AND screen pixel).

  • R2_MERGEPEN Pixel is a combination of the pen color and the screen color (final pixel = pen OR screen pixel).

  • R2_NOTMERGEPEN Pixel is the inverse of the R2_MERGEPEN color (final pixel = NOT(pen OR screen pixel)).

  • R2_MASKPEN Pixel is a combination of the colors common to both the pen and the screen (final pixel = pen AND screen pixel).

  • R2_NOTMASKPEN Pixel is the inverse of the R2_MASKPEN color (final pixel = NOT(pen AND screen pixel)).

  • R2_XORPEN Pixel is a combination of the colors that are in the pen or in the screen, but not in both (final pixel = pen XOR screen pixel).

  • R2_NOTXORPEN Pixel is the inverse of the R2_XORPEN color (final pixel = NOT(pen XOR screen pixel)).

Remarks

Sets the current drawing mode. The drawing mode specifies how the colors of the pen and the interior of filled objects are combined with the color already on the display surface.

The drawing mode is for raster devices only; it does not apply to vector devices. Drawing modes are binary raster-operation codes representing all possible Boolean combinations of two variables, using the binary operators AND, OR, and XOR (exclusive OR), and the unary operation NOT.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetDeviceCaps, CDC::GetROP2, ::SetROP2


CDC::SetStretchBltMode

int SetStretchBltMode( int nStretchMode );

Return Value

The previous stretching mode. It can be STRETCH_ANDSCANS, STRETCH_DELETESCANS, or STRETCH_ORSCANS.

Parameters

nStretchMode

Specifies the stretching mode. It can be any of the following values:

Value | Description
BLACKONWHITE | Performs a Boolean AND operation using the color values for the eliminated and existing pixels. If the bitmap is a monochrome bitmap, this mode preserves black pixels at the expense of white pixels.
COLORONCOLOR | Deletes the pixels. This mode deletes all eliminated lines of pixels without trying to preserve their information.
HALFTONE | Maps pixels from the source rectangle into blocks of pixels in the destination rectangle. The average color over the destination block of pixels approximates the color of the source pixels.
After setting the HALFTONE stretching mode, an application must call the Win32 function ::SetBrushOrgEx to set the brush origin. If it fails to do so, brush misalignment occurs.
STRETCH_ANDSCANS | Windows 95: Same as BLACKONWHITE
STRETCH_DELETESCANS | Windows 95: Same as COLORONCOLOR
STRETCH_HALFTONE | Windows 95: Same as HALFTONE.
STRETCH_ORSCANS | Windows 95: Same as WHITEONBLACK
WHITEONBLACK | Performs a Boolean OR operation using the color values for the eliminated and existing pixels. If the bitmap is a monochrome bitmap, this mode preserves white pixels at the expense of black pixels.

Remarks

Sets the bitmap-stretching mode for the StretchBlt member function. The bitmap-stretching mode defines how information is removed from bitmaps that are compressed by using the function.

The BLACKONWHITE (STRETCH_ANDSCANS) and WHITEONBLACK (STRETCH_ORSCANS) modes are typically used to preserve foreground pixels in monochrome bitmaps. The COLORONCOLOR (STRETCH_DELETESCANS) mode is typically used to preserve color in color bitmaps.

The HALFTONE mode requires more processing of the source image than the other three modes; it is slower than the others, but produces higher quality images. Also note that SetBrushOrgEx must be called after setting the HALFTONE mode to avoid brush misalignment.

Additional stretching modes might also be available depending on the capabilities of the device driver.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetStretchBltMode, CDC::StretchBlt, ::SetStretchBltMode


CDC::SetTextAlign

UINT SetTextAlign( UINT nFlags );

Return Value

The previous text-alignment setting, if successful. The low-order byte contains the horizontal setting and the high-order byte contains the vertical setting; otherwise 0.

Parameters

nFlags

Specifies text-alignment flags. The flags specify the relationship between a point and a rectangle that bounds the text. The point can be either the current position or coordinates specified by a text-output function. The rectangle that bounds the text is defined by the adjacent character cells in the text string. The nFlags parameter can be one or more flags from the following three categories. Choose only one flag from each category. The first category affects text alignment in the x-direction:

  • TA_CENTER Aligns the point with the horizontal center of the bounding rectangle.

  • TA_LEFT Aligns the point with the left side of the bounding rectangle. This is the default setting.

  • TA_RIGHT Aligns the point with the right side of the bounding rectangle.

    The second category affects text alignment in the y-direction:

  • TA_BASELINE Aligns the point with the base line of the chosen font.

  • TA_BOTTOM Aligns the point with the bottom of the bounding rectangle.

  • TA_TOP Aligns the point with the top of the bounding rectangle. This is the default setting.

    The third category determines whether the current position is updated when text is written:

  • TA_NOUPDATECP Does not update the current position after each call to a text-output function. This is the default setting.

  • TA_UPDATECP Updates the current x-position after each call to a text-output function. The new position is at the right side of the bounding rectangle for the text. When this flag is set, the coordinates specified in calls to the TextOut member function are ignored.

Remarks

Sets the text-alignment flags.

The TextOut and ExtTextOut member functions use these flags when positioning a string of text on a display or device. The flags specify the relationship between a specific point and a rectangle that bounds the text. The coordinates of this point are passed as parameters to the TextOut member function. The rectangle that bounds the text is formed by the adjacent character cells in the text string.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::ExtTextOut, CDC::GetTextAlign, CDC::TabbedTextOut, CDC::TextOut, ::SetTextAlign


CDC::SetTextCharacterExtra

int SetTextCharacterExtra( int nCharExtra );

Return Value

The amount of the previous intercharacter spacing.

Parameters

nCharExtra

Specifies the amount of extra space (in logical units) to be added to each character. If the current mapping mode is not MM_TEXT, nCharExtra is transformed and rounded to the nearest pixel.

Remarks

Sets the amount of intercharacter spacing. GDI adds this spacing to each character, including break characters, when it writes a line of text to the device context. The default value for the amount of intercharacter spacing is 0.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTextCharacterExtra, ::SetTextCharacterExtra


CDC::SetTextColor

virtual COLORREF SetTextColor( COLORREF crColor );

Return Value

An RGB value for the previous text color.

Parameters

crColor

Specifies the color of the text as an RGB color value.

Remarks

Sets the text color to the specified color. The system will use this text color when writing text to this device context and also when converting bitmaps between color and monochrome device contexts.

If the device cannot represent the specified color, the system sets the text color to the nearest physical color. The background color for a character is specified by the SetBkColor and SetBkMode member functions.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTextColor, CDC::BitBlt, CDC::SetBkColor, CDC::SetBkMode, ::SetTextColor


CDC::SetTextJustification

int SetTextJustification( int nBreakExtra, int nBreakCount );

Return Value

One if the function is successful; otherwise 0.

Parameters

nBreakExtra

Specifies the total extra space to be added to the line of text (in logical units). If the current mapping mode is not MM_TEXT, the value given by this parameter is converted to the current mapping mode and rounded to the nearest device unit.

nBreakCount

Specifies the number of break characters in the line.

Remarks

Adds space to the break characters in a string. An application can use the GetTextMetrics member functions to retrieve a font’s break character.

After the SetTextJustification member function is called, a call to a text-output function (such as TextOut) distributes the specified extra space evenly among the specified number of break characters. The break character is usually the space character (ASCII 32), but may be defined by a font as some other character.

The member function GetTextExtent is typically used with SetTextJustification. GetTextExtent computes the width of a given line before alignment. An application can determine how much space to specify in the nBreakExtra parameter by subtracting the value returned by GetTextExtent from the width of the string after alignment.

The SetTextJustification function can be used to align a line that contains multiple runs in different fonts. In this case, the line must be created piecemeal by aligning and writing each run separately.

Because rounding errors can occur during alignment, the system keeps a running error term that defines the current error. When aligning a line that contains multiple runs, GetTextExtent automatically uses this error term when it computes the extent of the next run. This allows the text-output function to blend the error into the new run.

After each line has been aligned, this error term must be cleared to prevent it from being incorporated into the next line. The term can be cleared by calling SetTextJustification with nBreakExtra set to 0.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetMapMode, CDC::GetTextExtent, CDC::GetTextMetrics, CDC::SetMapMode, CDC::TextOut, ::SetTextJustification


CDC::SetViewportExt

virtual CSize SetViewportExt( int cx, int cy );

virtual CSize SetViewportExt( SIZE size );

Return Value

The previous extents of the viewport as a CSize object. When an error occurs, the x- and y-coordinates of the returned CSize object are both set to 0.

Parameters

cx

Specifies the x-extent of the viewport (in device units).

cy

Specifies the y-extent of the viewport (in device units).

size

Specifies the x- and y-extents of the viewport (in device units).

Remarks

Sets the x- and y-extents of the viewport of the device context. The viewport, along with the device-context window, defines how GDI maps points in the logical coordinate system to points in the coordinate system of the actual device. In other words, they define how GDI converts logical coordinates into device coordinates.

When the following mapping modes are set, calls to SetWindowExt and SetViewportExt are ignored:

MM_HIENGLISH | MM_LOMETRIC
MM_HIMETRIC | MM_TEXT
MM_LOENGLISH | MM_TWIPS

When MM_ISOTROPIC mode is set, an application must call the SetWindowExt member function before it calls SetViewportExt.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetWindowExt, CSize, CDC::GetViewportExt


CDC::SetViewportOrg

virtual CPoint SetViewportOrg( int x, int y );

virtual CPoint SetViewportOrg( POINT point );

Return Value

The previous origin of the viewport (in device coordinates) as a CPoint object.

Parameters

x

Specifies the x-coordinate (in device units) of the origin of the viewport. The value must be within the range of the device coordinate system.

y

Specifies the y-coordinate (in device units) of the origin of the viewport. The value must be within the range of the device coordinate system.

point

Specifies the origin of the viewport. The values must be within the range of the device coordinate system. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Sets the viewport origin of the device context. The viewport, along with the device-context window, defines how GDI maps points in the logical coordinate system to points in the coordinate system of the actual device. In other words, they define how GDI converts logical coordinates into device coordinates.

The viewport origin marks the point in the device coordinate system to which GDI maps the window origin, a point in the logical coordinate system specified by the SetWindowOrg member function. GDI maps all other points by following the same process required to map the window origin to the viewport origin. For example, all points in a circle around the point at the window origin will be in a circle around the point at the viewport origin. Similarly, all points in a line that passes through the window origin will be in a line that passes through the viewport origin.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::SetWindowOrg, CPoint, POINT, CDC::GetViewportOrg


CDC::SetWindowExt

virtual CSize SetWindowExt( int cx, int cy );

virtual CSize SetWindowExt( SIZE size );

Return Value

The previous extents of the window (in logical units) as a CSize object. If an error occurs, the x- and y-coordinates of the returned CSize object are both set to 0.

Parameters

cx

Specifies the x-extent (in logical units) of the window.

cy

Specifies the y-extent (in logical units) of the window.

size

Specifies the x- and y-extents (in logical units) of the window.

Remarks

Sets the x- and y-extents of the window associated with the device context. The window, along with the device-context viewport, defines how GDI maps points in the logical coordinate system to points in the device coordinate system.

When the following mapping modes are set, calls to SetWindowExt and SetViewportExt functions are ignored:

  • MM_HIENGLISH

  • MM_HIMETRIC

  • MM_LOENGLISH

  • MM_LOMETRIC

  • MM_TEXT

  • MM_TWIPS

When MM_ISOTROPIC mode is set, an application must call the SetWindowExt member function before calling SetViewportExt.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetWindowExt, CDC::SetViewportExt, CSize


CDC::SetWindowOrg

CPoint SetWindowOrg( int x, int y );

CPoint SetWindowOrg( POINT point );

Return Value

The previous origin of the window as a CPoint object.

Parameters

x

Specifies the logical x-coordinate of the new origin of the window.

y

Specifies the logical y-coordinate of the new origin of the window.

point

Specifies the logical coordinates of the new origin of the window. You can pass either a POINT structure or a CPoint object for this parameter.

Remarks

Sets the window origin of the device context. The window, along with the device-context viewport, defines how GDI maps points in the logical coordinate system to points in the device coordinate system.

The window origin marks the point in the logical coordinate system from which GDI maps the viewport origin, a point in the device coordinate system specified by the SetWindowOrg function. GDI maps all other points by following the same process required to map the window origin to the viewport origin. For example, all points in a circle around the point at the window origin will be in a circle around the point at the viewport origin. Similarly, all points in a line that passes through the window origin will be in a line that passes through the viewport origin.

CDC Overview | Class Members | Hierarchy Chart

See Also CPoint, POINT, CDC::GetWindowOrg


CDC::StartDoc

int StartDoc( LPDOCINFO lpDocInfo );

Return Value

The value –1 if there is an error such as insufficient memory or an invalid port specification occurs; otherwise a positive value.

Parameters

lpDocInfo

Points to a DOCINFO structure containing the name of the document file and the name of the output file.

Remarks

Informs the device driver that a new print job is starting and that all subsequent StartPage and EndPage calls should be spooled under the same job until an EndDoc call occurs. This ensures that documents longer than one page will not be interspersed with other jobs.

For Windows versions 3.1 and later, this function replaces the STARTDOC printer escape. Using this function ensures that documents containing more than one page are not interspersed with other print jobs.

StartDoc should not be used inside metafiles.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Escape, CDC::EndDoc, CDC::AbortDoc


CDC::StartPage

int StartPage( );

Remarks

Call this member function to prepare the printer driver to receive data. StartPage supersedes the NEWFRAME and BANDINFO escapes.

For an overview of the sequence of printing calls, see the StartDoc member function.

The system disables the ResetDC member function between calls to StartPage and EndPage.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::Escape, CDC::EndPage


CDC::StretchBlt

BOOL StretchBlt( int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, DWORD dwRop );

Return Value

Nonzero if the bitmap is drawn; otherwise 0.

Parameters

x

Specifies the x-coordinate (in logical units) of the upper-left corner of the destination rectangle.

y

Specifies the y-coordinate (in logical units) of the upper-left corner of the destination rectangle.

nWidth

Specifies the width (in logical units) of the destination rectangle.

nHeight

Specifies the height (in logical units) of the destination rectangle.

pSrcDC

Specifies the source device context.

xSrc

Specifies the x-coordinate (in logical units) of the upper-left corner of the source rectangle.

ySrc

Specifies the x-coordinate (in logical units) of the upper-left corner of the source rectangle.

nSrcWidth

Specifies the width (in logical units) of the source rectangle.

nSrcHeight

Specifies the height (in logical units) of the source rectangle.

dwRop

Specifies the raster operation to be performed. Raster operation codes define how GDI combines colors in output operations that involve a current brush, a possible source bitmap, and a destination bitmap. This parameter may be one of the following values:

  • BLACKNESS Turns all output black.

  • DSTINVERT Inverts the destination bitmap.

  • MERGECOPY Combines the pattern and the source bitmap using the Boolean AND operator.

  • MERGEPAINT Combines the inverted source bitmap with the destination bitmap using the Boolean OR operator.

  • NOTSRCCOPY Copies the inverted source bitmap to the destination.

  • NOTSRCERASE Inverts the result of combining the destination and source bitmaps using the Boolean OR operator.

  • PATCOPY Copies the pattern to the destination bitmap.

  • PATINVERT Combines the destination bitmap with the pattern using the Boolean XOR operator.

  • PATPAINT Combines the inverted source bitmap with the pattern using the Boolean OR operator. Combines the result of this operation with the destination bitmap using the Boolean OR operator.

  • SRCAND Combines pixels of the destination and source bitmaps using the Boolean AND operator.

  • SRCCOPY Copies the source bitmap to the destination bitmap.

  • SRCERASE Inverts the destination bitmap and combines the result with the source bitmap using the Boolean AND operator.

  • SRCINVERT Combines pixels of the destination and source bitmaps using the Boolean XOR operator.

  • SRCPAINT Combines pixels of the destination and source bitmaps using the Boolean OR operator.

  • WHITENESS Turns all output white.

Remarks

Copies a bitmap from a source rectangle into a destination rectangle, stretching or compressing the bitmap if necessary to fit the dimensions of the destination rectangle. The function uses the stretching mode of the destination device context (set by SetStretchBltMode) to determine how to stretch or compress the bitmap.

The StretchBlt function moves the bitmap from the source device given by pSrcDC to the destination device represented by the device-context object whose member function is being called. The xSrc, ySrc, nSrcWidth, and nSrcHeight parameters define the upper-left corner and dimensions of the source rectangle. The x, y, nWidth, and nHeight parameters give the upper-left corner and dimensions of the destination rectangle. The raster operation specified by dwRop defines how the source bitmap and the bits already on the destination device are combined.

The StretchBlt function creates a mirror image of a bitmap if the signs of the nSrcWidth and nWidth or nSrcHeight and nHeight parameters differ. If nSrcWidth and nWidth have different signs, the function creates a mirror image of the bitmap along the x-axis. If nSrcHeight and nHeight have different signs, the function creates a mirror image of the bitmap along the y-axis.

The StretchBlt function stretches or compresses the source bitmap in memory and then copies the result to the destination. If a pattern is to be merged with the result, it is not merged until the stretched source bitmap is copied to the destination. If a brush is used, it is the selected brush in the destination device context. The destination coordinates are transformed according to the destination device context; the source coordinates are transformed according to the source device context.

If the destination, source, and pattern bitmaps do not have the same color format, StretchBlt converts the source and pattern bitmaps to match the destination bitmaps. The foreground and background colors of the destination device context are used in the conversion.

If StretchBlt must convert a monochrome bitmap to color, it sets white bits (1) to the background color and black bits (0) to the foreground color. To convert color to monochrome, it sets pixels that match the background color to white (1) and sets all other pixels to black (0). The foreground and background colors of the device context with color are used.

Not all devices support the StretchBlt function. To determine whether a device supports StretchBlt, call the GetDeviceCaps member function with the RASTERCAPS index and check the return value for the RC_STRETCHBLT flag.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BitBlt, CDC::GetDeviceCaps, CDC::SetStretchBltMode, ::StretchBlt


CDC::StrokeAndFillPath

BOOL StrokeAndFillPath( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Closes any open figures in a path, strokes the outline of the path by using the current pen, and fills its interior by using the current brush. The device context must contain a closed path. The StrokeAndFillPath member function has the same effect as closing all the open figures in the path, and stroking and filling the path separately, except that the filled region will not overlap the stroked region even if the pen is wide.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::FillPath, CDC::SetPolyFillMode, CDC::StrokePath, ::StrokeAndFillPath


CDC::StrokePath

BOOL StrokePath( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Renders the specified path by using the current pen. The device context must contain a closed path.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::EndPath, ::StrokePath


CDC::TabbedTextOut

virtual CSize TabbedTextOut( int x, int y, LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions, int nTabOrigin );

CSize TabbedTextOut( int x, int y, const CString& str, int nTabPositions, LPINT lpnTabStopPositions, int nTabOrigin );

Return Value

The dimensions of the string (in logical units) as a CSize object.

Parameters

x

Specifies the logical x-coordinate of the starting point of the string.

y

Specifies the logical y-coordinate of the starting point of the string.

lpszString

Points to the character string to draw. You can pass either a pointer to an array of characters or a CString object for this parameter.

nCount

Specifies the number of characters in the string. If nCount is –1, the length is calculated.

nTabPositions

Specifies the number of values in the array of tab-stop positions.

lpnTabStopPositions

Points to an array containing the tab-stop positions (in logical units). The tab stops must be sorted in increasing order; the smallest x-value should be the first item in the array.

nTabOrigin

Specifies the x-coordinate of the starting position from which tabs are expanded (in logical units).

str

A CString object that contains the specified characters.

Remarks

Call this member function to write a character string at the specified location, expanding tabs to the values specified in the array of tab-stop positions. Text is written in the currently selected font. If nTabPositions is 0 and lpnTabStopPositions is NULL, tabs are expanded to eight times the average character width.

If nTabPositions is 1, the tab stops are separated by the distance specified by the first value in the lpnTabStopPositions array. If the lpnTabStopPositions array contains more than one value, a tab stop is set for each value in the array, up to the number specified by nTabPositions. The nTabOrigin parameter allows an application to call the TabbedTextOut function several times for a single line. If the application calls the function more than once with the nTabOrigin set to the same value each time, the function expands all tabs relative to the position specified by nTabOrigin.

By default, the current position is not used or updated by the function. If an application needs to update the current position when it calls the function, the application can call the SetTextAlign member function with nFlags set to TA_UPDATECP. When this flag is set, Windows ignores the x and y parameters on subsequent calls to TabbedTextOut, using the current position instead.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::GetTabbedTextExtent, CDC::SetTextAlign, CDC::TextOut, CDC::SetTextColor, ::TabbedTextOut, CSize


CDC::TextOut

virtual BOOL TextOut( int x, int y, LPCTSTR lpszString, int nCount );

BOOL TextOut( int x, int y, const CString& str );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the starting point of the text.

y

Specifies the logical y-coordinate of the starting point of the text.

lpszString

Points to the character string to be drawn.

nCount

Specifies the number of bytes in the string.

str

A CString object that contains the characters to be drawn.

Remarks

Writes a character string at the specified location using the currently selected font.

Character origins are at the upper-left corner of the character cell. By default, the current position is not used or updated by the function.

If an application needs to update the current position when it calls TextOut, the application can call the SetTextAlign member function with nFlags set to TA_UPDATECP. When this flag is set, Windows ignores the x and y parameters on subsequent calls to TextOut, using the current position instead.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::ExtTextOut, CDC::GetTextExtent, CDC::SetTextAlign, CDC::SetTextColor, CDC::TabbedTextOut, ::TextOut


CDC::UpdateColors

void UpdateColors( );

Remarks

Updates the client area of the device context by matching the current colors in the client area to the system palette on a pixel-by-pixel basis. An inactive window with a realized logical palette may call UpdateColors as an alternative to redrawing its client area when the system palette changes.

For more information about using color palettes, see ::UpdateColors in the Win32 SDK Programmer’s Reference.

The UpdateColors member function typically updates a client area faster than redrawing the area. However, because the function performs the color translation based on the color of each pixel before the system palette changed, each call to this function results in the loss of some color accuracy.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::RealizePalette, CPalette, ::UpdateColors


CDC::WidenPath

BOOL WidenPath( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the device context. This function is successful only if the current pen is a geometric pen created by the second version of CreatePen member function, or if the pen is created with the first version of CreatePen and has a width, in device units, of greater than 1. The device context must contain a closed path. Any Bézier curves in the path are converted to sequences of straight lines approximating the widened curves. As such, no Bézier curves remain in the path after WidenPath is called.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::EndPath, CDC::SetMiterLimit, ::WidenPath


CDC::m_hAttribDC

Remarks

The attribute device context for this CDC object. By default, this device context is equal to m_hDC. In general, CDC GDI calls that request information from the device context are directed to m_hAttribDC. See the CDC class description for more on the use of these two device contexts.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::m_hDC, CDC::SetAttribDC, CDC::ReleaseAttribDC


CDC::m_hDC

Remarks

The output device context for this CDC object. By default, m_hDC is equal to m_hAttribDC, the other device context wrapped by CDC. In general, CDC GDI calls that create output go to the m_hDC device context. You can initialize m_hDC and m_hAttribDC to point to different devices. See the CDC class description for more on the use of these two device contexts.

CDC Overview | Class Members | Hierarchy Chart

See Also CDC::m_hAttribDC, CDC::SetOutputDC, CDC::ReleaseOutputDC


CDialog

The CDialog class is the base class used for displaying dialog boxes on the screen. Dialog boxes are of two types: modal and modeless. A modal dialog box must be closed by the user before the application continues. A modeless dialog box allows the user to display the dialog box and return to another task without canceling or removing the dialog box.

A CDialog object is a combination of a dialog template and a CDialog-derived class. Use the dialog editor to create the dialog template and store it in a resource, then use ClassWizard to create a class derived from CDialog.

A dialog box, like any other window, receives messages from Windows. In a dialog box, you are particularly interested in handling notification messages from the dialog box’s controls since that is how the user interacts with your dialog box. ClassWizard browses through the potential messages generated by each control in your dialog box, and you can select which messages you wish to handle. ClassWizard then adds the appropriate message-map entries and message-handler member functions to the new class for you. You only need to write application-specific code in the handler member functions.

If you prefer, you can always write message-map entries and member functions yourself instead of using ClassWizard.

In all but the most trivial dialog box, you add member variables to your derived dialog class to store data entered in the dialog box’s controls by the user or to display data for the user. ClassWizard browses through those controls in your dialog box that can be mapped to data and prompts you to create a member variable for each control. At the same time, you choose a variable type and permissible range of values for each variable. ClassWizard adds the member variables to your derived dialog class.

ClassWizard then writes a data map to automatically handle the exchange of data between the member variables and the dialog box’s controls. The data map provides functions that initialize the controls in the dialog box with the proper values, retrieve the data, and validate the data.

To create a modal dialog box, construct an object on the stack using the constructor for your derived dialog class and then call DoModal to create the dialog window and its controls. If you wish to create a modeless dialog, call Create in the constructor of your dialog class.

You can also create a template in memory by using a DLGTEMPLATE data structure as described in the Win32 SDK documentation. After you construct a CDialog object, call CreateIndirect to create a modeless dialog box, or call InitModalIndirect and DoModal to create a modal dialog box.

ClassWizard writes the exchange and validation data map in an override of CWnd::DoDataExchange that ClassWizard adds to your new dialog class. See the DoDataExchange member function in CWnd for more on the exchange and validation functionality.

Both the programmer and the framework call DoDataExchange indirectly through a call to CWnd::UpdateData.

The framework calls UpdateData when the user clicks the OK button to close a modal dialog box. (The data is not retrieved if the Cancel button is clicked.) The default implementation of OnInitDialog also calls UpdateData to set the initial values of the controls. You typically override OnInitDialog to further initialize controls. OnInitDialog is called after all the dialog controls are created and just before the dialog box is displayed.

You can call CWnd::UpdateData at any time during the execution of a modal or modeless dialog box.

If you develop a dialog box by hand, you add the necessary member variables to the derived dialog-box class yourself, and you add member functions to set or get these values.

For more on ClassWizard, see Using ClassWizard in the Visual C++ Programmer's Guide.

Call CWinApp::SetDialogBkColor to set the background color for dialog boxes in your application.

A modal dialog box closes automatically when the user presses the OK or Cancel buttons or when your code calls the EndDialog member function.

When you implement a modeless dialog box, always override the OnCancel member function and call DestroyWindow from within it. Don’t call the base class CDialog::OnCancel, because it calls EndDialog, which will make the dialog box invisible but will not destroy it. You should also override PostNcDestroy for modeless dialog boxes in order to delete this, since modeless dialog boxes are usually allocated with new. Modal dialog boxes are usually constructed on the frame and do not need PostNcDestroy cleanup.

For more information on CDialog, see the article Dialog Box Topics in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample DBFETCH | MFC Sample DLGCBR32 | MFC Sample DLGTEMPL | MFC Sample EXTBIND | MFC Sample FTPTREE | MFC Sample HELLO | MFC Sample MDIBIND | MFC Sample VCTERM


CDialog Class Members

Construction

CDialog Constructs a CDialog object.

Initialization

Create | Initializes the CDialog object. Creates a modeless dialog box and attaches it to the CDialog object.
CreateIndirect | Creates a modeless dialog box from a dialog-box template in memory (not resource-based).
InitModalIndirect | Creates a modal dialog box from a dialog-box template in memory (not resource-based). The parameters are stored until the function DoModal is called.

Operations

DoModal | Calls a modal dialog box and returns when done.
MapDialogRect | Converts the dialog-box units of a rectangle to screen units.
NextDlgCtrl | Moves the focus to the next dialog-box control in the dialog box.
PrevDlgCtrl | Moves the focus to the previous dialog-box control in the dialog box.
GotoDlgCtrl | Moves the focus to a specified dialog-box control in the dialog box.
SetDefID | Changes the default pushbutton control for a dialog box to a specified pushbutton.
GetDefID | Gets the ID of the default pushbutton control for a dialog box.
SetHelpID | Sets a context-sensitive help ID for the dialog box.
EndDialog | Closes a modal dialog box.

Overridables

OnInitDialog | Override to augment dialog-box initialization.
OnSetFont | Override to specify the font that a dialog-box control is to use when it draws text.
OnOK | Override to perform the OK button action in a modal dialog box. The default closes the dialog box and DoModal returns IDOK.
OnCancel | Override to perform the Cancel button or ESC key action. The default closes the dialog box and DoModal returns IDCANCEL.


CDialog::CDialog

CDialog( LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL );

CDialog( UINT nIDTemplate, CWnd* pParentWnd = NULL );

CDialog( );

Parameters

lpszTemplateName

Contains a null-terminated string that is the name of a dialog-box template resource.

nIDTemplate

Contains the ID number of a dialog-box template resource.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the dialog object’s parent window is set to the main application window.

Remarks

To construct a resource-based modal dialog box, call either public form of the constructor. One form of the constructor provides access to the dialog resource by template name. The other constructor provides access by template ID number, usually with an IDD_ prefix (for example, IDD_DIALOG1).

To construct a modal dialog box from a template in memory, first invoke the parameterless, protected constructor and then call InitModalIndirect.

After you construct a modal dialog box with one of the above methods, call DoModal.

To construct a modeless dialog box, use the protected form of the CDialog constructor. The constructor is protected because you must derive your own dialog-box class to implement a modeless dialog box. Construction of a modeless dialog box is a two-step process. First call the constructor; then call the Create member function to create a resource-based dialog box, or call CreateIndirect to create the dialog box from a template in memory.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::Create, CWnd::DestroyWindow, CDialog::InitModalIndirect, CDialog::DoModal, ::CreateDialog


CDialog::Create

BOOL Create( LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL );

BOOL Create( UINT nIDTemplate, CWnd* pParentWnd = NULL );

Return Value

Both forms return nonzero if dialog-box creation and initialization were successful; otherwise 0.

Parameters

lpszTemplateName

Contains a null-terminated string that is the name of a dialog-box template resource.

pParentWnd

Points to the parent window object (of type CWnd) to which the dialog object belongs. If it is NULL, the dialog object’s parent window is set to the main application window.

nIDTemplate

Contains the ID number of a dialog-box template resource.

Remarks

Call Create to create a modeless dialog box using a dialog-box template from a resource. You can put the call to Create inside the constructor or call it after the constructor is invoked.

Two forms of the Create member function are provided for access to the dialog-box template resource by either template name or template ID number (for example, IDD_DIALOG1).

For either form, pass a pointer to the parent window object. If pParentWnd is NULL, the dialog box will be created with its parent or owner window set to the main application window.

The Create member function returns immediately after it creates the dialog box.

Use the WS_VISIBLE style in the dialog-box template if the dialog box should appear when the parent window is created. Otherwise, you must call ShowWindow. For further dialog-box styles and their application, see the DLGTEMPLATE structure in the Win32 SDK documentation and Window Styles in the Class Library Reference.

Use the CWnd::DestroyWindow function to destroy a dialog box created by the Create function.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::CDialog, CWnd::DestroyWindow, CDialog::InitModalIndirect, CDialog::DoModal, ::CreateDialog


CDialog::CreateIndirect

BOOL CreateIndirect( LPCDLGTEMPLATE lpDialogTemplate, CWnd* pParentWnd = NULL );

BOOL CreateIndirect( HGLOBAL hDialogTemplate, CWnd* pParentWnd = NULL );

Return Value

Nonzero if the dialog box was created and initialized successfully; otherwise 0.

Parameters

lpDialogTemplate

Points to memory that contains a dialog-box template used to create the dialog box. This template is in the form of a DLGTEMPLATE structure and control information. For more information on this structure, see the Win32 SDK documentation.

pParentWnd

Points to the dialog object’s parent window object (of type CWnd). If it is NULL, the dialog object’s parent window is set to the main application window.

hDialogTemplate

Contains a handle to global memory containing a dialog-box template. This template is in the form of a DLGTEMPLATE structure and data for each control in the dialog box.

Remarks

Call this member function to create a modeless dialog box from a dialog-box template in memory.

The CreateIndirect member function returns immediately after it creates the dialog box.

Use the WS_VISIBLE style in the dialog-box template if the dialog box should appear when the parent window is created. Otherwise, you must call ShowWindow to cause it to appear. For more information on how you can specify other dialog-box styles in the template, see the DLGTEMPLATE structure in the Win32 SDK documentation.

Use the CWnd::DestroyWindow function to destroy a dialog box created by the CreateIndirect function.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::CDialog, CWnd::DestroyWindow, CDialog::Create, ::CreateDialogIndirect


CDialog::DoModal

virtual int DoModal( );

Return Value

An int value that specifies the value of the nResult parameter that was passed to the CDialog::EndDialog member function, which is used to close the dialog box. The return value is –1 if the function could not create the dialog box, or IDABORT if some other error occurred.

Remarks

Call this member function to invoke the modal dialog box and return the dialog-box result when done. This member function handles all interaction with the user while the dialog box is active. This is what makes the dialog box modal; that is, the user cannot interact with other windows until the dialog box is closed.

If the user clicks one of the pushbuttons in the dialog box, such as OK or Cancel, a message-handler member function, such as OnOK or OnCancel, is called to attempt to close the dialog box. The default OnOK member function will validate and update the dialog-box data and close the dialog box with result IDOK, and the default OnCancel member function will close the dialog box with result IDCANCEL without validating or updating the dialog-box data. You can override these message-handler functions to alter their behavior.

Note PreTranslateMessage is now called for modal dialog box message processing.

CDialog Overview | Class Members | Hierarchy Chart

See Also ::DialogBox, CWnd::IsDialogMessage


CDialog::EndDialog

void EndDialog( int nResult );

Parameters

nResult

Contains the value to be returned from the dialog box to the caller of DoModal.

Remarks

Call this member function to terminate a modal dialog box. This member function returns nResult as the return value of DoModal. You must use the EndDialog function to complete processing whenever a modal dialog box is created.

You can call EndDialog at any time, even in OnInitDialog, in which case you should close the dialog box before it is shown or before the input focus is set.

EndDialog does not close the dialog box immediately. Instead, it sets a flag that directs the dialog box to close as soon as the current message handler returns.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::DoModal, CDialog::OnOK, CDialog::OnCancel


CDialog::GetDefID

DWORD GetDefID( ) const;

Return Value

A 32-bit value (DWORD). If the default pushbutton has an ID value, the high-order word contains DC_HASDEFID and the low-order word contains the ID value. If the default pushbutton does not have an ID value, the return value is 0.

Remarks

Call the GetDefID member function to get the ID of the default pushbutton control for a dialog box. This is usually an OK button.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::SetDefID, DM_GETDEFID


CDialog::GotoDlgCtrl

void GotoDlgCtrl( CWnd* pWndCtrl );

Parameters

pWndCtrl

Identifies the window (control) that is to receive the focus.

Remarks

Moves the focus to the specified control in the dialog box.

To get a pointer to the control (child window) to pass as pWndCtrl, call the CWnd::GetDlgItem member function, which returns a pointer to a CWnd object.

CDialog Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDlgItem, CDialog::PrevDlgCtrl, CDialog::NextDlgCtrl


CDialog::InitModalIndirect

BOOL InitModalIndirect( LPCDLGTEMPLATE lpDialogTemplate, CWnd* pParentWnd = NULL );

BOOL InitModalIndirect( HGLOBAL hDialogTemplate, CWnd* pParentWnd = NULL );

Return Value

Nonzero if the dialog object was created and initialized successfully; otherwise 0.

Parameters

lpDialogTemplate

Points to memory that contains a dialog-box template used to create the dialog box. This template is in the form of a DLGTEMPLATE structure and control information. For more information on this structure, see the Win32 SDK documentation.

hDialogTemplate

Contains a handle to global memory containing a dialog-box template. This template is in the form of a DLGTEMPLATE structure and data for each control in the dialog box.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the dialog object’s parent window is set to the main application window.

Remarks

Call this member function to initialize a modal dialog object using a dialog-box template that you construct in memory.

To create a modal dialog box indirectly, first allocate a global block of memory and fill it with the dialog box template. Then call the empty CDialog constructor to construct the dialog-box object. Next, call InitModalIndirect to store your handle to the in-memory dialog-box template. The Windows dialog box is created and displayed later, when the DoModal member function is called.

CDialog Overview | Class Members | Hierarchy Chart

See Also ::DialogBoxIndirect, CDialog::DoModal, CWnd::DestroyWindow, CDialog::CDialog


CDialog::MapDialogRect

void MapDialogRect( LPRECT lpRect ) const;

Parameters

lpRect

Points to a RECT structure or CRect object that contains the dialog-box coordinates to be converted.

Remarks

Call to convert the dialog-box units of a rectangle to screen units. Dialog-box units are stated in terms of the current dialog-box base unit derived from the average width and height of characters in the font used for dialog-box text. One horizontal unit is one-fourth of the dialog-box base-width unit, and one vertical unit is one-eighth of the dialog-box base height unit.

The GetDialogBaseUnits Windows function returns size information for the system font, but you can specify a different font for each dialog box if you use the DS_SETFONT style in the resource-definition file. The MapDialogRect Windows function uses the appropriate font for this dialog box.

The MapDialogRect member function replaces the dialog-box units in lpRect with screen units (pixels) so that the rectangle can be used to create a dialog box or position a control within a box.

CDialog Overview | Class Members | Hierarchy Chart

See Also ::GetDialogBaseUnits, ::MapDialogRect, WM_SETFONT


CDialog::NextDlgCtrl

void NextDlgCtrl( ) const;

Remarks

Moves the focus to the next control in the dialog box. If the focus is at the last control in the dialog box, it moves to the first control.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::PrevDlgCtrl, CDialog::GotoDlgCtrl


CDialog::OnCancel

virtual void OnCancel( );

Remarks

The framework calls this member function when the user clicks the Cancel button or presses the ESC key in a modal or modeless dialog box.

Override this member function to perform Cancel button action. The default simply terminates a modal dialog box by calling EndDialog and causing DoModal to return IDCANCEL.

If you implement the Cancel button in a modeless dialog box, you must override the OnCancel member function and call DestroyWindow from within it. Don’t call the base-class member function, because it calls EndDialog, which will make the dialog box invisible but not destroy it.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::OnOK, CDialog::EndDialog


CDialog::OnInitDialog

virtual BOOL OnInitDialog( );

Return Value

Specifies whether the application has set the input focus to one of the controls in the dialog box. If OnInitDialog returns nonzero, Windows sets the input focus to the first control in the dialog box. The application can return 0 only if it has explicitly set the input focus to one of the controls in the dialog box.

Remarks

This member function is called in response to the WM_INITDIALOG message. This message is sent to the dialog box during the Create, CreateIndirect, or DoModal calls, which occur immediately before the dialog box is displayed.

Override this member function if you need to perform special processing when the dialog box is initialized. In the overridden version, first call the base class OnInitDialog but disregard its return value. You will normally return TRUE from your overridden member function.

Windows calls the OnInitDialog function via the standard global dialog-box procedure common to all Microsoft Foundation Class Library dialog boxes, rather than through your message map, so you do not need a message-map entry for this member function.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::Create, CDialog::CreateIndirect, WM_INITDIALOG


CDialog::OnOK

virtual void OnOK( );

Remarks

Called when the user clicks the OK button (the button with an ID of IDOK).

Override this member function to perform the OK button action. If the dialog box includes automatic data validation and exchange, the default implementation of this member function validates the dialog-box data and updates the appropriate variables in your application.

If you implement the OK button in a modeless dialog box, you must override the OnOK member function and call DestroyWindow from within it. Don’t call the base-class member function, because it calls EndDialog, which makes the dialog box invisible but does not destroy it.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::OnCancel, CDialog::EndDialog


CDialog::OnSetFont

virtual void OnSetFont( CFont* pFont );

Parameters

pFont

Specifies a pointer to the font. Used as the default font for all controls in this dialog box.

Remarks

Specifies the font a dialog-box control will use when drawing text. The dialog-box control will use the specified font as the default for all dialog-box controls.

The dialog editor typically sets the dialog-box font as part of the dialog-box template resource.

CDialog Overview | Class Members | Hierarchy Chart

See Also WM_SETFONT, CWnd::SetFont


CDialog::PrevDlgCtrl

void PrevDlgCtrl( ) const;

Remarks

Sets the focus to the previous control in the dialog box. If the focus is at the first control in the dialog box, it moves to the last control in the box.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::NextDlgCtrl, CDialog::GotoDlgCtrl


CDialog::SetDefID

void SetDefID( UINT nID );

Parameters

nID

Specifies the ID of the pushbutton control that will become the default.

Remarks

Changes the default pushbutton control for a dialog box.

CDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::GetDefID


CDialog::SetHelpID

void SetHelpID( UINT nIDR );

Parameters

nIDR

Specifies the context-sensitive help ID.

Remarks

Sets a context-sensitive help ID for the dialog box.


CDialogBar

The CDialogBar class provides the functionality of a Windows modeless dialog box in a control bar. A dialog bar resembles a dialog box in that it contains standard Windows controls that the user can tab between. Another similarity is that you create a dialog template to represent the dialog bar.

Creating and using a dialog bar is similar to creating and using a CFormView object. First, use the dialog editor (described in the Visual C++ User's Guide) to define a dialog template with the style WS_CHILD and no other style. The template must not have the style WS_VISIBLE. In your application code, call the constructor to construct the CDialogBar object, then call Create to create the dialog-bar window and attach it to the CDialogBar object.

For more information on CDialogBar, see the article Dialog Bar Topics in Visual C++ Programmer's Guide and Technical Note 31, Control Bars.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CTRLBARS

See Also CFormView, CControlBar


CDialogBar Class Members

Construction

CDialogBar | Constructs a CDialogBar object.
Create | Creates a Windows dialog bar and attaches it to the CDialogBar object.


CDialogBar::CDialogBar

CDialogBar( );

Remarks

Constructs a CDialogBar object.

CDialogBar Overview | Class Members | Hierarchy Chart

See Also CControlBar


CDialogBar::Create

BOOL Create( CWnd* pParentWnd, LPCTSTR lpszTemplateName, UINT nStyle, UINT nID );

BOOL Create( CWnd* pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pParentWnd

A pointer to the parent CWnd object.

lpszTemplateName

A pointer to the name of the CDialogBar object’s dialog-box resource template.

nStyle

The alignment style of the dialog bar. The following styles are supported:

  • CBRS_TOP Control bar is at the top of the frame window.

  • CBRS_BOTTOM Control bar is at the bottom of the frame window.

  • CBRS_NOALIGN Control bar is not repositioned when the parent is resized.

  • CBRS_LEFT Control bar is at the left of the frame window.

  • CBRS_RIGHT Control bar is at the right of the frame window.

nID

The control ID of the dialog bar.

nIDTemplate

The resource ID of the CDialogBar object’s dialog-box template.

Remarks

Loads the dialog-box resource template specified by lpszTemplateName or nIDTemplate, creates the dialog-bar window, sets its style, and associates it with the CDialogBar object.

If you specify the CBRS_TOP or CBRS_BOTTOM alignment style, the dialog bar’s width is that of the frame window and its height is that of the resource specified by nIDTemplate. If you specify the CBRS_LEFT or CBRS_RIGHT alignment style, the dialog bar’s height is that of the frame window and its width is that of the resource specified by nIDTemplate.

CDialogBar Overview | Class Members | Hierarchy Chart

See Also CDialogBar::CDialogBar


CDocItem

CDocItem is the base class for document items, which are components of a document’s data. CDocItem objects are used to represent OLE items in both client and server documents.

For more information, see the article Containers: Implementing a Container in Visual C++ Programmer's Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

See Also COleDocument, COleServerItem, COleClientItem


CDocItem Class Members

Operations

GetDocument Returns the document that contains the item.

Overridables

IsBlank Determines whether the item contains any information.


CDocItem::IsBlank

virtual BOOL IsBlank( ) const;

Return Value

Nonzero if the item contains no information; otherwise 0.

Remarks

Called by the framework when default serialization occurs.

By default, CDocItem objects are not blank. COleClientItem objects are sometimes blank because they derive directly from CDocItem. However, COleServerItem objects are always blank. By default, OLE applications containing COleClientItem objects that have no x or y extent are serialized. This is done by returning TRUE from an override of IsBlank when the item has no x or y extent.

Override this function if you want to implement other actions during serialization.

CDocItem Overview | Class Members | Hierarchy Chart

See Also CObject::Serialize


CDocItem::GetDocument

CDocument* GetDocument( ) const;

Return Value

A pointer to the document that contains the item; NULL, if the item is not part of a document.

Remarks

Call this function to get the document that contains the item.

This function is overridden in the derived classes COleClientItem and COleServerItem, returning a pointer to either a COleDocument, a COleLinkingDoc, or a COleServerDoc object.

CDocItem Overview | Class Members | Hierarchy Chart

See Also COleDocument, COleLinkingDoc, COleServerDoc, COleClientItem, COleServerItem


CDockState

CDockState is a serialized CObject class that loads, unloads, or clears the state of one or more docking control bars in persistent memory (a file). The dock state includes the size and position of the bar and whether or not it is docked. When retrieving the stored dock state, CDockState checks the bar's position and, if the bar is not visible with the current screen settings, CDockState scales the bar's position so that it is visible. The main purpose of CDockState is to hold the entire state of a number of control bars and to allow that state to be saved and loaded either to the registry, the application's .INI file, or in binary form as part of a CArchive object's contents.

The bar can be any dockable control bar, including a toolbar, status bar, or dialog bar. CDockState objects are written and read to or from a file via a CArchive object.

CFrameWnd::GetDockState retrieves the state information of all the frame window's CControlBar objects and puts it into the CDockState object. You can then write the contents of the CDockState object to storage with Serialize or CDockState::SaveState. If you later want to restore the state of the control bars in the frame window, you can load the state with Serialize or CDockState::LoadState, then use CFrameWnd::SetDockState to apply the saved state to the frame window's control bars.

For more information on docking control bars, see the articles Control Bar Topics, Toolbars: Docking and Floating, and Frame Window Topics in Visual C++ Programmer's Guide.

#include <afxadv.h>


CDockState Class Members

Data Members

m_arrBarInfo Array of pointers to the stored dock state information with one entry for each control bar.

Construction

CDockState Constructs a CDockState object.

Operations

Clear | Clears the dock state information.
GetVersion | Retrieves the version number of the stored bar state.
LoadState | Retrieves state information from the registry or .INI file.
SaveState | Saves state information to the registry or INI file.


CDockState::CDockState

CDockState( );

Remarks

Constructs a CDockState object.

CDockState Overview | Class Members | Hierarchy Chart

See Also CDockState::Clear, CDockState::GetVersion, CDockState::LoadState, CDockState::SaveState, CFrameWnd::GetDockState, CFrameWnd::SetDockState


CDockState::Clear

void Clear( );

Remarks

Call this function to clear all docking information stored in the CDockState object. This includes not only whether the bar is docked or not, but the bar's size and position and whether or not it is visible.

CDockState Overview | Class Members | Hierarchy Chart

See Also CDockState::LoadState, CDockState::SaveState, CDockState::GetVersion, CFrameWnd::GetDockState, CFrameWnd::SetDockState


CDockState::GetVersion

DWORD GetVersion( );

Return Value

1 if the stored bar information is older than current bar state; 2 if the stored bar information is the same as the current bar state.

Remarks

Call this function to retrieve the version number of the stored bar state. Version support enables a revised bar to add new persistent properties and still be able to detect and load the persistent state created by an earlier version of the bar.

CDockState Overview | Class Members | Hierarchy Chart

See Also CDockState::LoadState, CDockState::SaveState, CDockState::Clear, CFrameWnd::GetDockState, CFrameWnd::SetDockState


CDockState::LoadState

void LoadState( LPCTSTR lpszProfileName );

Parameters

lpszProfileName

Points to a null-teminated string that specifies the name of a section in the initialization file or a key in the Windows registry where state information is stored.

Remarks

Call this function to retrieve state information from the registry or .INI file. The profile name is the section of the application's .INI file or the registry that contains the bars' state information. You can save control bar state information to the registry or .INI file with SaveState.

CDockState Overview | Class Members | Hierarchy Chart

See Also CDockState::SaveState, CDockState::GetVersion, CDockState::Clear, CFrameWnd::GetDockState, CFrameWnd::SetDockState


CDockState::SaveState

void SaveState( LPCTSTR lpszProfileName );

Parameters

lpszProfileName

Points to a null-teminated string that specifies the name of a section in the initialization file or a key in the Windows registry where state information is stored.

Remarks

Call this function to save the state information to the registry or .INI file. The profile name is the section of the application's .INI file or the registry that contains the control bar's state information. SaveState also saves the current screen size. You can retrieve control bar information from the registry or .INI file with LoadState.

CDockState Overview | Class Members | Hierarchy Chart

See Also CDockState::LoadState, CDockState::GetVersion, CDockState::Clear, CFrameWnd::GetDockState, CFrameWnd::SetDockState


CDockState::m_arrBarInfo

Remarks

A CPtrArray object that is an array of pointers to the stored control bar information for each control bar that has saved state information in the CDockState object.

CDockState Overview | Class Members | Hierarchy Chart

See Also CDockState::LoadState, CDockState::SaveState, CDockState::Clear, CFrameWnd::GetDockState, CFrameWnd::SetDockState


CDocObjectServer

Class CDocObjectServer implements the additional OLE interfaces needed to make a normal COleDocument server into a full DocObject server: IOleDocument, IOleDocumentView, IOleCommandTarget, and IPrint. CDocObjectServer is derived from CCmdTarget and works closely with COleServerDoc to expose the interfaces.

A DocObject server document can contain CDocObjectServerItem objects, which represent the server interface to DocObject items.

To customize your DocObject server, derive your own class from CDocObjectServer and override its view setup functions, OnActivateView, OnApplyViewState, and OnSaveViewState. You will need to provide a new instance of your class in response to framework calls.

For further information on DocObjects, see CDocObjectServerItem and COleCmdUI in the MFC Class Library Reference. Also see Internet First Steps: Active Documents and Active Documents in Visual C++ Programmer's Guide.

#include <afxdocobj.h>

Class Members | Base Class | Hierarchy Chart

See Also CDocObjectServerItem


CDocObjectServer Class Members

Constructors

CDocObjectServer Constructs a CDocObjectServer object.

Operations

ActivateDocObject Activates the document object server, but does not show it.

Overrideables

OnActivateView | Displays the DocObject view.
OnApplyViewState | Restores the state of the DocObject view.
OnSaveViewState | Saves the state of the DocObject view.


CDocObjectServer::ActivateDocObject

void ActivateDocObject( );

Remarks

Call this function to activate (but not show) the document object server. ActivateDocObject calls IOleDocumentSite's ActivateMe method, but does not show the view because it waits for specific instructions on how to set up and display the view, given in the call to CDocObjectServer::OnActivateView.

Together, ActivateDocObject and OnActivateView activate and display the DocObject view. DocObject activation differs from other kinds of OLE in-place activation. DocObject activation bypasses displaying in-place hatch borders and object adornments (such as sizing handles), ignores object extent functions, and draws scroll bars within the view rectangle as opposed to drawing them outside that rectangle (as in normal in-place activation).

CDocObjectServer Overview | Class Members | Hierarchy Chart

See Also CDocObjectServerItem


CDocObjectServer::CDocObjectServer

CDocObjectServer( COleServerDoc* pOwner, LPOLEDOCUMENTSITE pDocSite = NULL );

Parameters

pOwner

A pointer to the client site document that is the client for the DocObject server.

pDocSite

A pointer to the IOleDocumentSite interface implemented by the container.

Remarks

Constructs and initializes a CDocObjectServer object.

When a DocObject is active, the client site OLE interface (IOleDocumentSite) is what allows the DocObject server to communicate with its client (the container). When a DocObject server is activated, it first checks that the container implements the IOleDocumentSite interface. If so, COleServerDoc::GetDocObjectServer is called to see if the container supports DocObjects. By default, GetDocObjectServer returns NULL. You must override COleServerDoc::GetDocObjectServer to construct a new CDocObjectServer object or a derived object of your own, with pointers to the COleServerDoc container and its IOleDocumentSite interface as arguments to the constructor.

CDocObjectServer Overview | Class Members | Hierarchy Chart

See Also CDocObjectServerItem, COleServerDoc::GetDocObjectServer


CDocObjectServer::OnActivateView

virtual HRESULT OnActivateView( );

Return Value

Returns an error or warning value. By default, returns NOERROR if successful; otherwise, E_FAIL.

Remarks

Call this function to display the DocObject view. This function creates an in-place frame window, draws scrollbars within the view, sets up the menus the server shares with its container, adds frame controls, sets the active object, then finally shows the in-place frame window and sets the focus.

CDocObjectServer Overview | Class Members | Hierarchy Chart

See Also CDocObjectServer::OnApplyViewState


CDocObjectServer::OnApplyViewState

virtual void OnApplyViewState( CArchive& ar );

Parameters

ar

A CArchive object from which to serialize the view state.

Remarks

Override this function to restore the state of the DocObject view.

This function is called when the view is being displayed for the first time after its instantiation. OnApplyViewState instructs a view to reinitialize itself according to the data in the CArchive object previously saved with OnSaveViewState. The view must validate the data in the CArchive object because the container does not attempt to interpret the view state data in any way.

You can use OnSaveViewState to store persistent information specific to your view's state. If you override OnSaveViewState to store information, you will want to override OnApplyViewState to read that information and apply it to your view when it is newly activated.

CDocObjectServer Overview | Class Members | Hierarchy Chart

See Also CDocObjectServer::OnSaveViewState


CDocObjectServer::OnSaveViewState

virtual void OnSaveViewState( CArchive& ar );

Parameters

ar

A CArchive object to which the view state is serialized.

Remarks

Override this function to save extra state information about your DocObject view.

Your state might include properties like the view type, zoom factor, insertion and selection point, and so on. The container typically calls this function before deactivating the view. The saved state can later be restored through OnApplyViewState.

You can use OnSaveViewState to store persistent information specific to your view's state. If you override OnSaveViewState to store information, you will want to override OnApplyViewState to read that information and apply it to your view when it is newly activated.

CDocObjectServer Overview | Class Members | Hierarchy Chart

See Also CDocObjectServer::OnApplyViewState


CDocObjectServerItem

Class CDocObjectServerItem, derived from COleServerItem, implements OLE server verbs specifically for DocObject servers.

CDocObjectServerItem defines overridable member functions: OnHide, OnOpen, and OnShow.

To use CDocObjectServerItem, assure that the OnGetEmbeddedItem override in your COleServerDoc-derived class returns a new CDocObjectServerItem object. If you need to change any functionality in your item, you can create a new instance of your own CDocObjectServerItem-derived class.

For further information on DocObjects, see CDocObjectServer and COleCmdUI in the MFC Class Library Reference. Also see Internet First Steps: Active Documents and Active Documents in Visual C++ Programmer's Guide.

#include <afxdocobj.h>

Class Members | Base Class | Hierarchy Chart

See Also CDocObjectServer, COleDocObjectItem


CDocObjectServerItem Class Members

Constructors

CDocObjectServerItem Constructs a CDocObjectServerItem object.

Overridables

OnHide | Throws an exception if the framework tries to hide a DocObject item.
OnOpen | Called by the framework to make the DocObject item in-place active. If the item is not a DocObject, calls COleServerItem::OnOpen.
OnShow | Called by the framework to make the DocObject item in-place active. If the item is not a DocObject, calls COleServerItem::OnShow.


CDocObjectServerItem::CDocObjectServerItem

CDocObjectServerItem( COleServerDoc* pServerDoc, BOOL bAutoDelete );

Parameters

pServerDoc

A pointer to the document that will contain the new DocObject item.

bAutoDelete

Indicates whether the object can be deleted when a link to it is released. Set the argument to FALSE if the CDocObjectServerItem object is an integral part of your document’s data. Set it to TRUE if the object is a secondary structure used to identify a range in your document’s data that can be deleted by the framework.

Remarks

Constructs a CDocObjectServerItem object.

CDocObjectServerItem Overview | Class Members | Hierarchy Chart

See Also CDocObjectServer


CDocObjectServerItem::OnHide

virtual void OnHide( );

Remarks

Called by the framework to hide the item. The default implementation throws an exception if the item is a DocObject. You cannot hide an active DocObject item because it takes the whole view. You must deactivate the DocObject item to make it disappear. If the item is not a DocObject, the default implementation calls COleServerItem::OnHide.

CDocObjectServerItem Overview | Class Members | Hierarchy Chart

See Also CDocObjectServerItem::OnOpen, CDocObjectServerItem::OnShow


CDocObjectServerItem::OnOpen

virtual void OnOpen( );

Remarks

Called by the framework to instruct the server application to make the DocObject item in-place active. If the item is not a DocObject, the default implementation calls COleServerItem::OnOpen. Override this function if you want to perform special processing when opening a DocObject item.

CDocObjectServerItem Overview | Class Members | Hierarchy Chart

See Also CDocObjectServerItem::OnHide, CDocObjectServerItem::OnShow


CDocObjectServerItem::OnShow

virtual void OnShow( );

Remarks

Called by the framework to instruct the server application to make the DocObject item in-place active. If the item is not a DocObject, the default implementation calls COleServerItem::OnShow. Override this function if you want to perform special processing when opening a DocObject item.

CDocObjectServerItem Overview | Class Members | Hierarchy Chart

See Also CDocObjectServerItem::OnHide, CDocObjectServerItem::OnOpen


CDocTemplate

CDocTemplate is an abstract base class that defines the basic functionality for document templates. You usually create one or more document templates in the implementation of your application’s InitInstance function. A document template defines the relationships among three types of classes:

  • A document class, which you derive from CDocument.

  • A view class, which displays data from the document class listed above. You can derive this class from CView, CScrollView, CFormView, or CEditView. (You can also use CEditView directly.)

  • A frame window class, which contains the view. For a single document interface (SDI) application, you derive this class from CFrameWnd. For a multiple document interface (MDI) application, you derive this class from CMDIChildWnd. If you don’t need to customize the behavior of the frame window, you can use CFrameWnd or CMDIChildWnd directly without deriving your own class.

Your application has one document template for each type of document that it supports. For example, if your application supports both spreadsheets and text documents, the application has two document template objects. Each document template is responsible for creating and managing all the documents of its type.

The document template stores pointers to the CRuntimeClass objects for the document, view, and frame window classes. These CRuntimeClass objects are specified when constructing a document template.

The document template contains the ID of the resources used with the document type (such as menu, icon, or accelerator table resources). The document template also has strings containing additional information about its document type. These include the name of the document type (for example, “Worksheet”) and the file extension (for example, “.xls”). Optionally, it can contain other strings used by the application’s user interface, the Windows File Manager, and Object Linking and Embedding (OLE) support.

If your application is an OLE container and/or server, the document template also defines the ID of the menu used during in-place activation. If your application is an OLE server, the document template defines the ID of the toolbar and menu used during in-place activation. You specify these additional OLE resources by calling SetContainerInfo and SetServerInfo.

Because CDocTemplate is an abstract class, you cannot use the class directly. A typical application uses one of the two CDocTemplate-derived classes provided by the Microsoft Foundation Class Library: CSingleDocTemplate, which implements SDI, and CMultiDocTemplate, which implements MDI. See those classes for more information on using document templates.

If your application requires a user-interface paradigm that is fundamentally different from SDI or MDI, you can derive your own class from CDocTemplate.

For more information on CDocTemplate, see Document Templates and the Document/View Creation Process in Visual C++ Programmer's Guide.

include# <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CHKBOOK

See Also CSingleDocTemplate, CMultiDocTemplate, CDocument, CView, CScrollView, CEditView, CFormView, CFrameWnd, CMDIChildWnd


CDocTemplate Class Members

Constructors

CDocTemplate Constructs a CDocTemplate object.

Attributes

SetContainerInfo | Determines the resources for OLE containers when editing an in-place OLE item.
SetServerInfo | Determines the resources and classes when the server document is embedded or edited in-place.
GetFirstDocPosition | Retrieves the position of the first document associated with this template.
GetNextDoc | Retrieves a document and the position of the next one.
LoadTemplate | Loads the resources for a given CDocTemplate or derived class.

Operations

AddDocument | Adds a document to a template.
RemoveDocument | Removes a document from a template.
GetDocString | Retrieves a string associated with the document type.
CreateOleFrame | Creates an OLE-enabled frame window.

Overridables

MatchDocType | Determines the degree of confidence in the match between a document type and this template.
CreateNewDocument | Creates a new document.
CreateNewFrame | Creates a new frame window containing a document and view.
InitialUpdateFrame | Initializes the frame window, and optionally makes it visible.
SaveAllModified | Saves all documents associated with this template which have been modified.
CloseAllDocuments | Closes all documents associated with this template.
OpenDocumentFile | Opens a file specified by a pathname.
SetDefaultTitle | Displays the default title in the document window’s title bar.


CDocTemplate::AddDocument

virtual void AddDocument( CDocument* pDoc );

Parameters

pDoc

A pointer to the document to be added.

Remarks

Use this function to add a document to a template. The derived classes CMultiDocTemplate and CSingleDocTemplate override this function. If you derive your own document-template class from CDocTemplate, your derived class must override this function.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::RemoveDocument, CMultiDocTemplate, CSingleDocTemplate


CDocTemplate::CDocTemplate

CDocTemplate ( UINT nIDResource, CRuntimeClass* pDocClass, CRuntimeClass* pFrameClass, CRuntimeClass* pViewClass );

Parameters

nIDResource

Specifies the ID of the resources used with the document type. This may include menu, icon, accelerator table, and string resources.

The string resource consists of up to seven substrings separated by the ‘\n’ character (the ‘\n’ character is needed as a place holder if a substring is not included; however, trailing ‘\n’ characters are not necessary); these substrings describe the document type. For information on the substrings, see GetDocString. This string resource is found in the application’s resource file. For example:

// MYCALC.RC
STRINGTABLE PRELOAD DISCARDABLE
BEGIN
    IDR_SHEETTYPE "\nSheet\nWorksheet\nWorksheets (*.myc)\n.myc\n MyCalcSheet\nMyCalc Worksheet"
END

Note that the string begins with a ‘\n’ character; this is because the first substring is not used for MDI applications and so is not included. You can edit this string using the string editor; the entire string appears as a single entry in the String Editor, not as seven separate entries.

For more information about these resource types, see the Visual C++ User's Guide.

pDocClass

Points to the CRuntimeClass object of the document class. This class is a CDocument-derived class you define to represent your documents.

pFrameClass

Points to the CRuntimeClass object of the frame window class. This class can be a CFrameWnd-derived class, or it can be CFrameWnd itself if you want default behavior for your main frame window.

pViewClass

Points to the CRuntimeClass object of the view class. This class is a CView-derived class you define to display your documents.

Remarks

Use this member function to construct a CDocTemplate object. Dynamically allocate a CDocTemplate object and pass it to CWinApp::AddDocTemplate from the InitInstance member function of your application class.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::GetDocString, CWinApp::AddDocTemplate, CWinApp::InitInstance, CRuntimeClass


CDocTemplate::CloseAllDocuments

virtual void CloseAllDocuments( BOOL bEndSession );

Parameters

bEndSession

Specifies whether or not the session is being ended. It is TRUE if the session is being ended; otherwise FALSE.

Remarks

Call this member function to close all open documents. This member function is typically used as part of the File Exit command. The default implementation of this function calls the CDocument::DeleteContents member function to delete the document's data and then closes the frame windows for all the views attached to the document.

Override this function if you want to require the user to perform special cleanup processing before the document is closed. For example, if the document represents a record in a database, you may want to override this function to close the database.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::OpenDocumentFile, CDocTemplate::SaveAllModified


CDocTemplate::CreateNewDocument

virtual CDocument* CreateNewDocument( );

Return Value

A pointer to the newly created document, or NULL if an error occurs.

Remarks

Call this member function to create a new document of the type associated with this document template.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::CreateNewFrame


CDocTemplate::CreateNewFrame

virtual CFrameWnd* CreateNewFrame( CDocument* pDoc, CFrameWnd* pOther );

Return Value

A pointer to the newly created frame window, or NULL if an error occurs.

Parameters

pDoc

The document to which the new frame window should refer. Can be NULL.

pOther

The frame window on which the new frame window is to be based. Can be NULL.

Remarks

CreateNewFrame uses the CRuntimeClass objects passed to the constructor to create a new frame window with a view and document attached. If the pDoc parameter is NULL, the framework outputs a TRACE message.

The pOther parameter is used to implement the Window New command. It provides a frame window on which to model the new frame window. The new frame window is usually created invisible. Call this function to create frame windows outside the standard framework implementation of File New and File Open.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CCreateContext, CFrameWnd::LoadFrame, CDocTemplate::InitialUpdateFrame


CDocTemplate::CreateOleFrame

CFrameWnd* CreateOleFrame( CWnd* pParentWnd, CDocument* pDoc, BOOL bCreateView );

Return Value

A pointer to a frame window if successful; otherwise NULL.

Parameters

pParentWnd

A pointer to the frame’s parent window.

pDoc

A pointer to the document to which the new OLE frame window should refer.

bCreateView

Determines whether a view is created along with the frame.

Remarks

Creates an OLE frame window. If bCreateView is zero, an empty frame is created.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::CreateNewFrame, COleDocument, COleIPFrameWnd


CDocTemplate::GetDocString

virtual BOOL GetDocString( CString& rString, enum DocStringIndex index ) const;

Return Value

Nonzero if the specified substring was found; otherwise 0.

Parameters

rString

A reference to a CString object that will contain the string when the function returns.

index

An index of the substring being retrieved from the string that describes the document type. This parameter can have one of the following values:

  • CDocTemplate::windowTitle Name that appears in the application window’s title bar (for example, “Microsoft Excel”). Present only in the document template for SDI applications.

  • CDocTemplate::docName Root for the default document name (for example, “Sheet”). This root, plus a number, is used for the default name of a new document of this type whenever the user chooses the New command from the File menu (for example, “Sheet1” or “Sheet2”). If not specified, “Untitled” is used as the default.

  • CDocTemplate::fileNewName Name of this document type. If the application supports more than one type of document, this string is displayed in the File New dialog box (for example, “Worksheet”). If not specified, the document type is inaccessible using the File New command.

  • CDocTemplate::filterName Description of the document type and a wildcard filter matching documents of this type. This string is displayed in the List Files Of Type drop-down list in the File Open dialog box (for example, “Worksheets (*.xls)”). If not specified, the document type is inaccessible using the File Open command.

  • CDocTemplate::filterExt Extension for documents of this type (for example, “.xls”). If not specified, the document type is inaccessible using the File Open command.

  • CDocTemplate::regFileTypeId Identifier for the document type to be stored in the registration database maintained by Windows. This string is for internal use only (for example, “ExcelWorksheet”). If not specified, the document type cannot be registered with the Windows File Manager.

  • CDocTemplate::regFileTypeName Name of the document type to be stored in the registration database. This string may be displayed in dialog boxes of applications that access the registration database (for example, “Microsoft Excel Worksheet”).

Remarks

Call this function to retrieve a specific substring describing the document type. The string containing these substrings is stored in the document template and is derived from a string in the resource file for the application. The framework calls this function to get the strings it needs for the application’s user interface. If you have specified a filename extension for your application’s documents, the framework also calls this function when adding an entry to the Windows registration database; this allows documents to be opened from the Windows File Manager.

Call this function only if you are deriving your own class from CDocTemplate.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CMultiDocTemplate::CMultiDocTemplate, CSingleDocTemplate::CSingleDocTemplate, CWinApp::RegisterShellFileTypes


CDocTemplate::GetFirstDocPosition

virtual POSITION GetFirstDocPosition( ) const = 0;

Return Value

A POSITION value that can be used to iterate through the list of documents associated with this document template; or NULL if the list is empty.

Remarks

Use this function to get the position of the first document in the list of documents associated with this template. Use the POSITION value as an argument to CDocTemplate::GetNextDoc to iterate through the list of documents associated with the template.

CSingleDocTemplate and CMultiDocTemplate both override this pure virtual function. Any class you derive from CDocTemplate must also override this function.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::GetNextDoc, CSingleDocTemplate, CMultiDocTemplate


CDocTemplate::GetNextDoc

virtual CDocument* GetNextDoc( POSITION& rPos ) const = 0;

Return Value

A pointer to the next document in the list of documents associated with this template.

Parameters

rPos

A reference to a POSITION value returned by a previous call to GetFirstDocPosition or GetNextDoc.

Remarks

Retrieves the list element identified by rPos, then sets rrPos to the POSITION value of the next entry in the list. If the retrieved element is the last in the list, then the new value of rPos is set to NULL.

You can use GetNextDoc in a forward iteration loop if you establish the initial position with a call to GetFirstDocPosition.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::GetFirstDocPosition


CDocTemplate::InitialUpdateFrame

virtual void InitialUpdateFrame( CFrameWnd* pFrame, CDocument* pDoc, BOOL bMakeVisible = TRUE );

Parameters

pFrame

The frame window that needs the initial update.

pDoc

The document to which the frame is associated. Can be NULL.

bMakeVisible

Indicates whether the frame should become visible and active.

Remarks

Call IntitialUpdateFrame after creating a new frame with CreateNewFrame. Calling this function causes the views in that frame window to receive their OnInitialUpdate calls. Also, if there was not previously an active view, the primary view of the frame window is made active; the primary view is a view with a child ID of AFX_IDW_PANE_FIRST. Finally, the frame window is made visible if bMakeVisible is non-zero. If bMakeVisible is zero, the current focus and visible state of the frame window will remain unchanged.

It is not necessary to call this function when using the framework’s implementation of File New and File Open.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CView::OnInititalUpdate, CFrameWnd::SetActiveView, CDocTemplate::CreateNewFrame


CDocTempate::LoadTemplate

virtual void LoadTemplate( );

Remarks

This member function is called by the framework to load the resources for a given CDocTemplate or derived class. Normally it is called during construction, except when the template is being constructed globally. In that case, the call to LoadTemplate is delayed until CWinApp::AddDocTemplate is called.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CWinApp::AddDocTemplate


CDocTemplate::MatchDocType

virtual Confidence MatchDocType( LPCTSTR lpszPathName, CDocument*& rpDocMatch );

virtual Confidence MatchDocType( LPCTSTR lpszPathName, DWORD dwFileType, CDocument*& rpDocMatch );

Return Value

A value from the Confidence enumeration, which is defined as follows:

enum Confidence
{
        noAttempt,
        maybeAttemptForeign,
        maybeAttemptNative,
        yesAttemptForeign,
        yesAttemptNative,
        yesAlreadyOpen
};

Parameters

lpszPathName

Pathname of the file whose type is to be determined.

rpDocMatch

Pointer to a document that is assigned the matching document, if the file specified by lpszPathName is already open.

dwFileType

The type of the document (Macintosh only).

Remarks

Use this function to determine the type of document template to use for opening a file. If your application supports multiple file types, for example, you can use this function to determine which of the available document templates is appropriate for a given file by calling MatchDocType for each template in turn, and choosing a template according to the confidence value returned.

If the file specified by lpszPathName is already open, this function returns CDocTemplate::yesAlreadyOpen and copies the file’s Cdocument object into the object at rpDocMatch.

If the file is not open but the extension in lpszPathName matches the extension specified by CDocTemplate::filterExt (or the Macintosh file type matches), this function returns CDocTemplate::yesAttemptNative and sets rpDocMatch to NULL. For more information on CDocTemplate::filterExt, see CDocTemplate::GetDocString.

If neither case is true, the function returns CDocTemplate::yesAttemptForeign.

The default implementation does not return CDocTemplate::maybeAttemptForeign or CDocTemplate::maybeAttemptNative. Override this function to implement type-matching logic appropriate to your application, perhaps using these two values from the Confidence enumeration.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::GetDocString


CDocTemplate::OpenDocumentFile

virtual CDocument* OpenDocumentFile( LPCTSTR lpszPathName, BOOL bMakeVisible = TRUE ) = 0;

Return Value

A pointer to the document whose file is named by lpszPathName; NULL if unsuccessful.

Parameters

lpszPathName

Pointer to the pathname of the file containing the document to be opened.

bMakeVisible

Determines whether the window containing the document is to be made visible.

Remarks

Opens the file whose pathname is specified by lpzsPathName. If lpszPathName is NULL, a new file, containing a document of the type associated with this template, is created.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::CloseAllDocuments


CDocTemplate::RemoveDocument

virtual void RemoveDocument( CDocument* pDoc );

Parameters

pDoc

Pointer to the document to be removed.

Remarks

Removes the document pointed to by pDoc from the list of documents associated with this template. The derived classes CMultiDocTemplate and CSingleDocTemplate override this function. If you derive your own document-template class from CDocTemplate, your derived class must override this function.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::AddDocument, CMultiDocTemplate, CSingleDocTemplate


CDocTemplate::SaveAllModified

virtual BOOL SaveAllModified( );

Return Value

Non-zero if successful; otherwise 0.

Remarks

Saves all documents that have been modified.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::OpenDocumentFile, CDocTemplate::CloseAllDocuments


CDocTemplate::SetContainerInfo

void SetContainerInfo( UINT nIDOleInPlaceContainer );

Parameters

nIDOleInPlaceContainer

The ID of the resources used when an embedded object is activated.

Remarks

Call this function to set the resources to be used when an OLE 2 object is in-place activated. These resources may include menus and accelerator tables. This function is usually called in the CWinApp::InitInstance function of your application.

The menu associated with nIDOleInPlaceContainer contains separators that allow the menu of the activated in-place item to merge with the menu of the container application. For more information about merging server and container menus, see the article Menus and Resources (OLE) in Visual C++ Programmer's Guide.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::SetServerInfo, CWinApp::InitInstance, CMultiDocTemplate::CMultiDocTemplate


CDocTemplate::SetDefaultTitle

virtual void SetDefaultTitle( CDocument* pDocument ) = 0;

Parameters

pDocument

Pointer to the document whose title is to be set.

Remarks

Call this function to load the document’s default title and display it in the document’s title bar. For information on the default title, see the description of CDocTemplate::docName in CDocTemplate::GetDocString.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::GetDocString


CDocTemplate::SetServerInfo

void SetServerInfo( UINT nIDOleEmbedding, UINT nIDOleInPlaceServer = 0, CRuntimeClass* pOleFrameClass = NULL, CRuntimeClass* pOleViewClass = NULL );

Parameters

nIDOleEmbedding

The ID of the resources used when an embedded object is opened in a separate window.

nIDOleInPlaceServer

The ID of the resources used when an embedded object is activated in-place.

pOleFrameClass

Pointer to a CRuntimeClass structure containing class information for the frame window object created when in-place activation occurs.

pOleViewClass

Pointer to a CRuntimeClass structure containing class information for the view object created when in-place activation occurs.

Remarks

Call this member function to identify resources that will be used by the server application when the user requests activation of an embedded object. These resources consist of menus and accelerator tables. This function is usually called in the InitInstance of your application.

The menu associated with nIDOleInPlaceServer contains separators that allow the server menu to merge with the menu of the container. For more information about merging server and container menus, see the article Menus and Resources (OLE) in Visual C++ Programmer's Guide.

CDocTemplate Overview | Class Members | Hierarchy Chart

See Also CMultiDocTemplate::CMultiDocTemplate, CDocTemplate::SetContainerInfo, CWinApp::InitInstance


CDocument

The CDocument class provides the basic functionality for user-defined document classes. A document represents the unit of data that the user typically opens with the File Open command and saves with the File Save command.

CDocument supports standard operations such as creating a document, loading it, and saving it. The framework manipulates documents using the interface defined by CDocument.

An application can support more than one type of document; for example, an application might support both spreadsheets and text documents. Each type of document has an associated document template; the document template specifies what resources (for example, menu, icon, or accelerator table) are used for that type of document. Each document contains a pointer to its associated CDocTemplate object.

Users interact with a document through the CView object(s) associated with it. A view renders an image of the document in a frame window and interprets user input as operations on the document. A document can have multiple views associated with it. When the user opens a window on a document, the framework creates a view and attaches it to the document. The document template specifies what type of view and frame window are used to display each type of document.

Documents are part of the framework’s standard command routing and consequently receive commands from standard user-interface components (such as the File Save menu item). A document receives commands forwarded by the active view. If the document doesn’t handle a given command, it forwards the command to the document template that manages it.

When a document’s data is modified, each of its views must reflect those modifications. CDocument provides the UpdateAllViews member function for you to notify the views of such changes, so the views can repaint themselves as necessary. The framework also prompts the user to save a modified file before closing it.

To implement documents in a typical application, you must do the following:

  • Derive a class from CDocument for each type of document.

  • Add member variables to store each document’s data.

  • Implement member functions for reading and modifying the document’s data. The document’s views are the most important users of these member functions.

  • Override the CObject::Serialize member function in your document class to write and read the document’s data to and from disk.

CDocument supports sending your document via mail if mail support (MAPI) is present. See the articles MAPI Topics and MAPI Support in MFC in Visual C++ Programmer's Guide.

For more information on CDocument, see Serialization (Object Persistence), Document/View Architecture Topics, and Document/View Creation in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HELLO | MFCSample MDIBIND | MFC Sample MDIDOCVW | MFC Sample SNAPVW | MFC Sample NPP

See Also CCmdTarget, CView, CDocTemplate


CDocument Class Members

Construction

CDocument Constructs a CDocument object.

Operations

AddView | Attaches a view to the document.
GetDocTemplate | Returns a pointer to the document template that describes the type of the document.
GetFirstViewPosition | Returns the position of the first in the list of views; used to begin iteration.
GetNextView | Iterates through the list of views associated with the document.
GetPathName | Returns the path of the document’s data file.
GetTitle | Returns the document’s title.
IsModified | Indicates whether the document has been modified since it was last saved.
RemoveView | Detaches a view from the document.
SetModifiedFlag | Sets a flag indicating that you have modified the document since it was last saved.
SetPathName | Sets the path of the data file used by the document.
SetTitle | Sets the document’s title.
UpdateAllViews | Notifies all views that document has been modified.

Overridables

CanCloseFrame | Advanced overridable; called before closing a frame window viewing this document.
DeleteContents | Called to perform cleanup of the document.
OnChangedViewList | Called after a view is added to or removed from the document.
OnCloseDocument | Called to close the document.
OnNewDocument | Called to create a new document.
OnOpenDocument | Called to open an existing document.
OnSaveDocument | Called to save the document to disk.
ReportSaveLoadException | Advanced overridable; called when an open or save operation cannot be completed because of an exception.
GetFile | Returns a pointer to the desired CFile object.
ReleaseFile | Releases a file to make it available for use by other applications.
SaveModified | Advanced overridable; called to ask the user whether the document should be saved.
PreCloseFrame | Called before the frame window is closed.

Mail Functions

OnFileSendMail | Sends a mail message with the document attached.
OnUpdateFileSendMail | Enables the Send Mail command if mail support is present.


CDocument::AddView

void AddView( CView* pView );

Parameters

pView

Points to the view being added.

Remarks

Call this function to attach a view to the document. This function adds the specified view to the list of views associated with the document; the function also sets the view’s document pointer to this document. The framework calls this function when attaching a newly created view object to a document; this occurs in response to a File New, File Open, or New Window command or when a splitter window is split.

Call this function only if you are manually creating and attaching a view. Typically you will let the framework connect documents and views by defining a CDocTemplate object to associate a document class, view class, and frame window class.

Example

// The following example toggles two views in an SDI (single document
// interface) frame window. A design decision must be made as to
// whether to leave the inactive view connected to the document,
// such that the inactive view continues to receive OnUpdate
// notifications from the document. It is usually desirable to
// keep the inactive view continuously in sync with the document, even
// though it is inactive. However, doing so incurs a performance cost,
// as well as the programming cost of implementing OnUpdate hints.
// It may be less expensive, in terms of performance and/or programming,
// to re-sync the inactive view with the document only with it is
// reactivated. This example illustrates this latter approach, by
// reconnecting the newly active view and disconnecting the newly
// inactive view, via calls to CDocument::AddView and RemoveView.

BOOL CMainFrame::OnViewChange(UINT nCmdID)
{
 CView* pViewAdd;
 CView* pViewRemove;
 CDocument* pDoc = GetActiveDocument();
 UINT nCmdID;

 nCmdID = LOWORD(GetCurrentMessage()->wParam);

 if((nCmdID == ID_VIEW_VIEW1) && (m_currentView == 1))
    return;
 if((nCmdID == ID_VIEW_VIEW2) && (m_currentView == 2))
   return;

 if (nCmdID == ID_VIEW_VIEW2)
 {
  if (m_pView2 == NULL)
  {
   m_pView1 = GetActiveView();
   m_pView2 = new CMyView2;

//Note that if OnSize has been overridden in CMyView2
//and GetDocument() is used in this override it can
//cause assertions and, if the assertions are ignored,
//cause access violation.

   m_pView2->Create(NULL, NULL, AFX_WS_DEFAULT_VIEW,
      rectDefault, this, AFX_IDW_PANE_FIRST + 1, NULL);
  }
   pViewAdd = m_pView2;
   pViewRemove = m_pView1;
   m_currentView= 2;
 }
 else
 {
  pViewAdd = m_pView1;
  pViewRemove = m_pView2;
  m_currentView= 1;
 }

// Set the child i.d. of the active view to AFX_IDW_PANE_FIRST,
// so that CFrameWnd::RecalcLayout will allocate to this
// "first pane" that portion of   the frame window's client area
// not allocated to control   bars.  Set the child i.d. of the
// other view to anything other than AFX_IDW_PANE_FIRST; this
// examples switches the child id's of the two views.

 int nSwitchChildID = pViewAdd->GetDlgCtrlID();
 pViewAdd->SetDlgCtrlID(AFX_IDW_PANE_FIRST);
 pViewRemove->SetDlgCtrlID(nSwitchChildID);

 // Show the newly active view and hide the inactive view.

 pViewAdd->ShowWindow(SW_SHOW);
 pViewRemove->ShowWindow(SW_HIDE);

 // Connect the newly active view to the document, and
 // disconnect the inactive view.
 pDoc->AddView(pViewAdd);
 pDoc->RemoveView(pViewRemove);

 SetActiveView(pViewAdd);
 RecalcLayout();
}

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocTemplate, CDocument::GetFirstViewPosition, CDocument::GetNextView, CDocument::RemoveView, CView::GetDocument


CDocument::CanCloseFrame

virtual BOOL CanCloseFrame( CFrameWnd* pFrame );

Return Value

Nonzero if it is safe to close the frame window; otherwise 0.

Parameters

pFrame

Points to the frame window of a view attached to the document.

Remarks

Called by the framework before a frame window displaying the document is closed. The default implementation checks if there are other frame windows displaying the document. If the specified frame window is the last one that displays the document, the function prompts the user to save the document if it has been modified. Override this function if you want to perform special processing when a frame window is closed. This is an advanced overridable.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::SaveModified


CDocument::CDocument

CDocument( );

Remarks

Constructs a CDocument object. The framework handles document creation for you. Override the OnNewDocument member function to perform initialization on a per-document basis; this is particularly important in single document interface (SDI) applications.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::OnNewDocument, CDocument::OnOpenDocument


CDocument::DeleteContents

virtual void DeleteContents( );

Remarks

Called by the framework to delete the document’s data without destroying the CDocument object itself. It is called just before the document is to be destroyed. It is also called to ensure that a document is empty before it is reused. This is particularly important for an SDI application, which uses only one document; the document is reused whenever the user creates or opens another document. Call this function to implement an “Edit Clear All” or similar command that deletes all of the document’s data. The default implementation of this function does nothing. Override this function to delete the data in your document.

Example

// This example is the handler for an Edit Clear All command.

void CMyDoc::OnEditClearAll()
{
   DeleteContents();
   UpdateAllViews(NULL);
}

void CMyDoc::DeleteContents()
{
   // Re-initialize document data here.

}

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::OnCloseDocument, CDocument::OnNewDocument, CDocument::OnOpenDocument


CDocument::GetDocTemplate

CDocTemplate* GetDocTemplate( ) const;

Return Value

A pointer to the document template for this document type, or NULL if the document is not managed by a document template.

Remarks

Call this function to get a pointer to the document template for this document type.

Example

   // This example accesses the doc template object to construct
   // a default document name such as SHEET.XLS, where "sheet"
   // is the base document name and ".xls" is the file extension
   // for the document type.
   CString strDefaultDocName, strBaseName, strExt;
   CDocTemplate* pDocTemplate = GetDocTemplate();
   if (!pDocTemplate->GetDocString(strBaseName, CDocTemplate::docName)
      || !pDocTemplate->GetDocString(strExt, CDocTemplate::filterExt))
   {
      AfxThrowUserException(); // These doc template strings will
         // be available if you created the application using AppWizard
         // and specified the file extension as an option for
         // the document class produced by AppWizard.
   }
   strDefaultDocName = strBaseName + strExt;

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocTemplate


CDocument::GetFile

virtual CFile* GetFile( LPCTSTR lpszFileName, UINT nOpenFlags, CFileException* pError );

Return Value

A pointer to a CFile object.

Parameters

lpszFileName

A string that is the path to the desired file. The path may be relative or absolute.

pError

A pointer to an existing file-exception object that indicates the completion status of the operation.

nOpenFlags

Sharing and access mode. Specifies the action to take when opening the file. You can combine options listed in the CFile constructor CFile::CFile by using the bitwise OR (|) operator. One access permission and one share option are required; the modeCreate and modeNoInherit modes are optional.

Remarks

Call this member function to get a pointer to a CFile object.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocTemplate


CDocument::GetFirstViewPosition

virtual POSITION GetFirstViewPosition( ) const;

Return Value

A POSITION value that can be used for iteration with the GetNextView member function.

Remarks

Call this function to get the position of the first view in the list of views associated with the document.

Example

//To get the first view in the list of views:

POSITION pos = GetFirstViewPosition();
CView* pFirstView = GetNextView( pos );
// This example uses CDocument::GetFirstViewPosition
// and GetNextView to repaint each view.
void CMyDoc::OnRepaintAllViews()
{
   POSITION pos = GetFirstViewPosition();
   while (pos != NULL)
   {
      CView* pView = GetNextView(pos);
      pView->UpdateWindow();
   }
}

// An easier way to accomplish the same result is to call
// UpdateAllViews(NULL);

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::GetNextView


CDocument::GetNextView

virtual CView* GetNextView( POSITION& rPosition ) const;

Return Value

A pointer to the view identified by rPosition.

Parameters

rPosition

A reference to a POSITION value returned by a previous call to the GetNextView or GetFirstViewPosition member functions. This value must not be NULL.

Remarks

Call this function to iterate through all of the document’s views. The function returns the view identified by rPosition and then sets rPosition to the POSITION value of the next view in the list. If the retrieved view is the last in the list, then rPosition is set to NULL.

Example

// This example uses CDocument::GetFirstViewPosition
// and GetNextView to repaint each view.
void CMyDoc::OnRepaintAllViews()
{
   POSITION pos = GetFirstViewPosition();
   while (pos != NULL)
   {
      CView* pView = GetNextView(pos);
      pView->UpdateWindow();
   }
}

// An easier way to accomplish the same result is to call
// UpdateAllViews(NULL);

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::AddView, CDocument::GetFirstViewPosition, CDocument::RemoveView, CDocument::UpdateAllViews


CDocument::GetPathName

const CString& GetPathName( ) const;

Return Value

The document’s fully qualified path. This string is empty if the document has not been saved or does not have a disk file associated with it.

Remarks

Call this function to get the fully qualified path of the document’s disk file.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::SetPathName


CDocument::GetTitle

const CString& GetTitle( ) const;

Return Value

The document’s title.

Remarks

Call this function to get the document’s title, which is usually derived from the document’s filename.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::SetTitle


CDocument::IsModified

BOOL IsModified( );

Return Value

Nonzero if the document has been modified since it was last saved; otherwise 0.

Remarks

Call this function to determine whether the document has been modified since it was last saved.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::SetModifiedFlag, CDocument::SaveModified


CDocument::OnChangedViewList

virtual void OnChangedViewList( );

Remarks

Called by the framework after a view is added to or removed from the document. The default implementation of this function checks whether the last view is being removed and, if so, deletes the document. Override this function if you want to perform special processing when the framework adds or removes a view. For example, if you want a document to remain open even when there are no views attached to it, override this function.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::AddView, CDocument::RemoveView


CDocument::OnCloseDocument

virtual void OnCloseDocument( );

Remarks

Called by the framework when the document is closed, typically as part of the File Close command. The default implementation of this function destroys all of the frames used for viewing the document, closes the view, cleans up the document's contents, and then calls the DeleteContents member function to delete the document’s data.

Override this function if you want to perform special cleanup processing when the framework closes a document. For example, if the document represents a record in a database, you may want to override this function to close the database. You should call the base class version of this function from your override.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::DeleteContents, CDocument::OnNewDocument, CDocument::OnOpenDocument


CDocument::OnFileSendMail

void OnFileSendMail( );

Remarks

Sends a message via the resident mail host (if any) with the document as an attachment. OnFileSendMail calls OnSaveDocument to serialize (save) untitled and modified documents to a temporary file, which is then sent via electronic mail. If the document has not been modified, a temporary file is not needed; the original is sent. OnFileSendMail loads MAPI32.DLL if it has not already been loaded.

A special implementation of OnFileSendMail for COleDocument handles compound files correctly.

CDocument supports sending your document via mail if mail support (MAPI) is present. See the articles MAPI Topics and MAPI Support in MFC in Visual C++ Programmer's Guide.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::OnUpdateFileSendMail, COleDocument::OnFileSendMail, CDocument::OnSaveDocument


CDocument::OnNewDocument

virtual BOOL OnNewDocument( );

Return Value

Nonzero if the document was successfully initialized; otherwise 0.

Remarks

Called by the framework as part of the File New command. The default implementation of this function calls the DeleteContents member function to ensure that the document is empty and then marks the new document as clean. Override this function to initialize the data structure for a new document. You should call the base class version of this function from your override.

If the user chooses the File New command in an SDI application, the framework uses this function to reinitialize the existing document, rather than creating a new one. If the user chooses File New in a multiple document interface (MDI) application, the framework creates a new document each time and then calls this function to initialize it. You must place your initialization code in this function instead of in the constructor for the File New command to be effective in SDI applications.

Example

// The following examples illustrate alternative methods of
// initializing a document object.

// Method 1: In an MDI application, the simplest place to do
// initialization is in the document constructor.  The framework
// always creates a new document object for File New or File Open.

CMyDoc::CMyDoc()
{
   // Do initialization of MDI document here.
   // ...
}

// Method 2: In an SDI or MDI application, do all initialization
// in an override of OnNewDocument, if you are certain that
// the initialization is effectively saved upon File Save
// and fully restored upon File Open, via serialization.

BOOL CMyDoc::OnNewDocument()
{
   if (!CDocument::OnNewDocument())
      return FALSE;

   // Do initialization of new document here.

   return TRUE;
}

// Method 3: If the initialization of your document is not
// effectively saved and restored by serialization (during File Save
// and File Open), then implement the initialization in single
// function (named InitMyDocument in this example).  Call the
// shared initialization function from overrides of both
// OnNewDocument and OnOpenDocument.

BOOL CMyDoc::OnNewDocument()
{
   if (!CDocument::OnNewDocument())
      return FALSE;

   InitMyDocument(); // call your shared initialization function

   // If your new document object requires additional initialization
   // not necessary when the document is deserialized via File Open,
   // then perform that additional initialization here.

   return TRUE;
}

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::CDocument, CDocument::DeleteContents, CDocument::OnCloseDocument, CDocument::OnOpenDocument, CDocument::OnSaveDocument


CDocument::OnOpenDocument

virtual BOOL OnOpenDocument( LPCTSTR lpszPathName );

Return Value

Nonzero if the document was successfully loaded; otherwise 0.

Parameters

lpszPathName

Points to the path of the document to be opened.

Remarks

Called by the framework as part of the File Open command. The default implementation of this function opens the specified file, calls the DeleteContents member function to ensure that the document is empty, calls CObject::Serialize to read the file’s contents, and then marks the document as clean. Override this function if you want to use something other than the archive mechanism or the file mechanism. For example, you might write an application where documents represent records in a database rather than separate files.

If the user chooses the File Open command in an SDI application, the framework uses this function to reinitialize the existing CDocument object, rather than creating a new one. If the user chooses File Open in an MDI application, the framework constructs a new CDocument object each time and then calls this function to initialize it. You must place your initialization code in this function instead of in the constructor for the File Open command to be effective in SDI applications.

Example

// The following examples illustrate alternative methods of
// initializing a document object.

// Method 1: In an MDI application, the simplest place to do
// initialization is in the document constructor.  The framework
// always creates a new document object for File New or File Open.

CMyDoc::CMyDoc()
{
   // Do initialization of MDI document here.
   // ...
}

// Method 2: In an SDI or MDI application, do all initialization
// in an override of OnNewDocument, if you are certain that
// the initialization is effectively saved upon File Save
// and fully restored upon File Open, via serialization.

BOOL CMyDoc::OnNewDocument()
{
   if (!CDocument::OnNewDocument())
      return FALSE;

   // Do initialization of new document here.

   return TRUE;
}

// Method 3: If the initialization of your document is not
// effectively saved and restored by serialization (during File Save
// and File Open), then implement the initialization in single
// function (named InitMyDocument in this example).  Call the
// shared initialization function from overrides of both
// OnNewDocument and OnOpenDocument.

BOOL CMyDoc::OnNewDocument()
{
   if (!CDocument::OnNewDocument())
      return FALSE;

   InitMyDocument(); // call your shared initialization function

   // If your new document object requires additional initialization
   // not necessary when the document is deserialized via File Open,
   // then perform that additional initialization here.

   return TRUE;
}

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::DeleteContents, CDocument::OnCloseDocument, CDocument::OnNewDocument, CDocument::OnSaveDocument, CDocument::ReportSaveLoadException, CObject::Serialize


CDocument::OnSaveDocument

virtual BOOL OnSaveDocument( LPCTSTR lpszPathName );

Return Value

Nonzero if the document was successfully saved; otherwise 0.

Parameters

lpszPathName

Points to the fully qualified path to which the file should be saved.

Remarks

Called by the framework as part of the File Save or File Save As command. The default implementation of this function opens the specified file, calls CObject::Serialize to write the document’s data to the file, and then marks the document as clean. Override this function if you want to perform special processing when the framework saves a document. For example, you might write an application where documents represent records in a database rather than separate files.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::OnCloseDocument, CDocument::OnNewDocument, CDocument::OnOpenDocument, CDocument::ReportSaveLoadException, CObject::Serialize


CDocument::OnUpdateFileSendMail

void OnUpdateFileSendMail( CCmdUI* pCmdUI );

Parameters

pCmdUI

A pointer to the CCmdUI object associated with the ID_FILE_SEND_MAIL command.

Remarks

Enables the ID_FILE_SEND_MAIL command if mail support (MAPI) is present. Otherwise the function removes the ID_FILE_SEND_MAIL command from the menu, including separators above or below the menu item as appropriate. MAPI is enabled if MAPI32.DLL is present in the path and, in the [Mail] section of the WIN.INI file, MAPI=1. Most applications put this command on the File menu.

CDocument supports sending your document via mail if mail support (MAPI) is present. See the articles MAPI Topics and MAPI Support in MFC in Visual C++ Programmer's Guide.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::OnFileSendMail


CDocument::PreCloseFrame

virtual void PreCloseFrame( CFrameWnd* pFrame );

Parameters

pFrame

Pointer to the CFrameWnd that holds the associated CDocument object.

Remarks

This member function is called by the framework before the frame window is destroyed. It can be overridden to provide custom cleanup, but be sure to call the base class as well.

The default of PreCloseFrame does nothing in CDocument. The CDocument-derived classes COleDocument and CRichEditDoc use this member function.


CDocument::ReleaseFile

virtual void ReleaseFile( CFile* pFile, BOOL bAbort );

Parameters

pFile

A pointer to the CFile object to be released.

bAbort

Specifies whether the file is to be released by using either CFile::Close or CFile::Abort. FALSE if the file is to be released using CFile::Close; TRUE if the file is to be released using CFile::Abort.

Remarks

This member function is called by the framework to release a file, making it available for use by other applications. If bAbort is TRUE, ReleaseFile calls CFile::Abort, and the file is released. CFile::Abort will not throw an exception.

If bAbort is FALSE, ReleaseFile calls CFile::Close and the file is released.

Override this member function to require an action by the user before the file is released.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocTemplate, CFile::Close, CFile::Abort


CDocument::RemoveView

void RemoveView( CView* pView );

Parameters

pView

Points to the view being removed.

Remarks

Call this function to detach a view from a document. This function removes the specified view from the list of views associated with the document; it also sets the view’s document pointer to NULL. This function is called by the framework when a frame window is closed or a pane of a splitter window is closed.

Call this function only if you are manually detaching a view. Typically you will let the framework detach documents and views by defining a CDocTemplate object to associate a document class, view class, and frame window class.

See the example at AddView for a sample implementation.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::AddView, CDocument::GetFirstViewPosition, CDocument::GetNextView


CDocument::ReportSaveLoadException

virtual void ReportSaveLoadException( LPCTSTR lpszPathName, CException* e, BOOL bSaving, UINT nIDPDefault );

Parameters

lpszPathName

Points to name of document that was being saved or loaded.

e

Points to the exception that was thrown. May be NULL.

bSaving

Flag indicating what operation was in progress; nonzero if the document was being saved, 0 if the document was being loaded.

nIDPDefault

Identifier of the error message to be displayed if the function does not specify a more specific one.

Remarks

Called if an exception is thrown (typically a CFileException or CArchiveException) while saving or loading the document. The default implementation examines the exception object and looks for an error message that specifically describes the cause. If a specific message is not found or if e is NULL, the general message specified by the nIDPDefault parameter is used. The function then displays a message box containing the error message. Override this function if you want to provide additional, customized failure messages. This is an advanced overridable.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::OnOpenDocument, CDocument::OnSaveDocument, CFileException, CArchiveException


CDocument::SaveModified

virtual BOOL SaveModified( );

Return Value

Nonzero if it is safe to continue and close the document; 0 if the document should not be closed.

Remarks

Called by the framework before a modified document is to be closed. The default implementation of this function displays a message box asking the user whether to save the changes to the document, if any have been made. Override this function if your program requires a different prompting procedure. This is an advanced overridable.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::CanCloseFrame, CDocument::IsModified, CDocument::OnNewDocument, CDocument::OnOpenDocument, CDocument::OnSaveDocument


CDocument::SetModifiedFlag

void SetModifiedFlag( BOOL bModified = TRUE );

Parameters

bModified

Flag indicating whether the document has been modified.

Remarks

Call this function after you have made any modifications to the document. By calling this function consistently, you ensure that the framework prompts the user to save changes before closing a document. Typically you should use the default value of TRUE for the bModified parameter. To mark a document as clean (unmodified), call this function with a value of FALSE.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::IsModified, CDocument::SaveModified


CDocument::SetPathName

virtual void SetPathName( LPCTSTR lpszPathName, BOOL bAddToMRU = TRUE );

Parameters

lpszPathName

Points to the string to be used as the path for the document.

bAddToMRU

Determines whether the filename is added to the most recently used (MRU) file list. If TRUE, the filename is added; if FALSE, it is not added.

Remarks

Call this function to specify the fully qualified path of the document’s disk file. Depending on the value of bAddToMRU the path is added, or not added, to the MRU list maintained by the application. Note that some documents are not associated with a disk file. Call this function only if you are overriding the default implementation for opening and saving files used by the framework.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::GetPathName, CWinApp::AddToRecentFileList


CDocument::SetTitle

virtual void SetTitle( LPCTSTR lpszTitle );

Parameters

lpszTitle

Points to the string to be used as the document’s title.

Remarks

Call this function to specify the document’s title (the string displayed in the title bar of a frame window). Calling this function updates the titles of all frame windows that display the document.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::GetTitle


CDocument::UpdateAllViews

void UpdateAllViews( CView* pSender, LPARAM lHint = 0L, CObject* pHint = NULL );

Parameters

pSender

Points to the view that modified the document, or NULL if all views are to be updated.

lHint

Contains information about the modification.

pHint

Points to an object storing information about the modification.

Remarks

Call this function after the document has been modified. You should call this function after you call the SetModifiedFlag member function. This function informs each view attached to the document, except for the view specified by pSender, that the document has been modified. You typically call this function from your view class after the user has changed the document through a view.

This function calls the CView::OnUpdate member function for each of the document’s views except the sending view, passing pHint and lHint. Use these parameters to pass information to the views about the modifications made to the document. You can encode information using lHint and/or you can define a CObject-derived class to store information about the modifications and pass an object of that class using pHint. Override the CView::OnUpdate member function in your CView-derived class to optimize the updating of the view’s display based on the information passed.

CDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::SetModifiedFlag, CDocument::GetFirstViewPosition, CDocument::GetNextView, CView::OnUpdate


CDragListBox

In addition to providing the functionality of a Windows list box, the CDragListBox class allows the user to move list box items, such as filenames, within the list box. List boxes with this capability allow users to order the items in a list in whatever manner is most useful to them. By default, the list box will move the item to the new location in the list. However, CDragListBox objects can be customized to copy items instead of moving them.

The list box control associated with the CDragListBox class must not have the LBS_SORT or the LBS_MULTIPLESELECT style. For a description of list box styles, see List-Box Styles.

To use a drag list box in an existing dialog box of your application, add a list box control to your dialog template using the dialog editor and then assign a member variable (of Category Control and Variable Type CDragListBox) corresponding to the list box control in your dialog template.

For more information on assigning controls to member variables, see Shortcut for Defining Member Variables for Dialog Controls in the Visual C++ Programmer's Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample TSTCON

See Also CListBox


CDragListBox Class Members

Attributes

ItemFromPt Returns the coordinates of the item being dragged.

Construction

CDragListBox Constructs a CDragListBox object.

Operations

DrawInsert Draws the insertion guide of the drag list box.

Overridables

BeginDrag | Called by the framework when a drag operation starts.
CancelDrag | Called by the framework when a drag operation has been canceled.
Dragging | Called by the framework during a drag operation.
Dropped | Called by the framework after the item has been dropped.


CDragListBox::BeginDrag

virtual BOOL BeginDrag( CPoint pt );

Return Value

Nonzero if dragging is allowed, otherwise 0.

Parameters

pt

A CPoint object that contains the coordinates of the item being dragged.

Remarks

Called by the framework when an event occurs that could begin a drag operation, such as pressing the left mouse button. Override this function if you want to control what happens when a drag operation begins. The default implementation captures the mouse and stays in drag mode until the user clicks the left or right mouse button or presses ESC, at which time the drag operation is canceled.

CDragListBox Overview | Class Members | Hierarchy Chart

See Also CDragListBox::CancelDrag, CDragListBox::Dragging


CDragListBox::CancelDrag

virtual void CancelDrag( CPoint pt );

Parameters

pt

A CPoint object that contains the coordinates of the item being dragged.

Remarks

Called by the framework when a drag operation has been canceled. Override this function to handle any special processing for your list box control.

CDragListBox Overview | Class Members | Hierarchy Chart

See Also CDragListBox::BeginDrag, CDragListBox::Dragging


CDragListBox::CDragListBox

CDragListBox( );

Remarks

Constructs a CDragListBox object.

CDragListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::Create


CDragListBox::Dragging

virtual UINT Dragging( CPoint pt );

Return Value

The resource ID of the cursor to be displayed. The following values are possible:

  • DL_COPYCURSOR Indicates that the item will be copied.

  • DL_MOVECURSOR Indicates that the item will be moved.

  • DL_STOPCURSOR Indicates that the current drop target is not acceptable.

Parameters

pt

A CPoint object that contains the x and y screen coordinates of the cursor.

Remarks

Called by the framework when a list box item is being dragged within the CDragListBox object. The default behavior returns DL_MOVECURSOR. Override this function if you want to provide additional functionality.

CDragListBox Overview | Class Members | Hierarchy Chart

See Also CDragListBox::BeginDrag, CDragListBox::CancelDrag


CDragListBox::DrawInsert

virtual void DrawInsert( int nItem );

Parameters

nItem Zero-based index of the insertion point.

Remarks

Called by the framework to draw the insertion guide before the item with the indicated index. A value of - 1 clears the insertion guide. Override this function to modify the appearance or behavior of the insertion guide.


CDragListBox::Dropped

virtual void Dropped( int nSrcIndex, CPoint pt );

Parameters

nSrcIndex

Specifies the zero-based index of the dropped string.

pt

A CPoint object that contains the coordinates of the drop site.

Remarks

Called by the framework when an item is dropped within a CDragListBox object. The default behavior copies the list box item and its data to the new location and then deletes the original item. Override this function to customize the default behavior, such as enabling copies of list box items to be dragged to other locations within the list.

CDragListBox Overview | Class Members | Hierarchy Chart

See Also CDragListBox::BeginDrag


CDragListBox::ItemFromPt

int ItemFromPt( CPoint pt, BOOL bAutoScroll = TRUE );

Return Value

Zero-based index of the drag list box item.

Parameters

pt

A CPoint object containing the coordinates of a point within the list box.

bAutoScroll

Nonzero if scrolling is allowed, otherwise 0.

Remarks

Call this function to retrieve the zero-based index of the list box item located at pt.


CDumpContext

CDumpContext does not have a base class.

The CDumpContext class supports stream-oriented diagnostic output in the form of human-readable text. You can use afxDump, a predeclared CDumpContext object, for most of your dumping. The afxDump object is available only in the Debug version of the Microsoft Foundation Class Library.

Several of the memory diagnostic functions use afxDump for their output.

Under the Windows environment, the output from the predefined afxDump object, conceptually similar to the cerr stream, is routed to the debugger via the Windows function OutputDebugString.

The CDumpContext class has an overloaded insertion (<<) operator for CObject pointers that dumps the object’s data. If you need a custom dump format for a derived object, override CObject::Dump. Most Microsoft Foundation classes implement an overridden Dump member function.

Classes that are not derived from CObject, such as CString, CTime, and CTimeSpan, have their own overloaded CDumpContext insertion operators, as do often-used structures such as CFileStatus, CPoint, and CRect.

If you use the IMPLEMENT_DYNAMIC or IMPLEMENT_SERIAL macro in the implementation of your class, then CObject::Dump will print the name of your CObject-derived class. Otherwise, it will print CObject.

The CDumpContext class is available with both the Debug and Release versions of the library, but the Dump member function is defined only in the Debug version. Use #ifdef _DEBUG / #endif statements to bracket your diagnostic code, including your custom Dump member functions.

Before you create your own CDumpContext object, you must create a CFile object that serves as the dump destination.

For more information on CDumpContext, see MFC Debugging Support in Visual C++ Programmer's Guide.

#define _DEBUG

#include <afx.h>

Class Members | Hierarchy Chart

See Also CFile, CObject


CDumpContext Class Members

Construction

CDumpContext Constructs a CDumpContext object.

Basic Input/Output

Flush | Flushes any data in the dump context buffer.
operator << | Inserts variables and objects into the dump context.
HexDump | Dumps bytes in hexadecimal format.

Status

GetDepth | Gets an integer corresponding to the depth of the dump.
SetDepth | Sets the depth of the dump.


CDumpContext::CDumpContext

CDumpContext( CFile* pFile );
throw( CMemoryException, CFileException );

Parameters

pFile

A pointer to the CFile object that is the dump destination.

Remarks

Constructs an object of class CDumpContext. The afxDump object is constructed automatically.

Do not write to the underlying CFile while the dump context is active; otherwise, you will interfere with the dump. Under the Windows environment, the output is routed to the debugger via the Windows function OutputDebugString.

Example

//example for CDumpContext::CDumpContext
CFile f;
if( !f.Open( "dump.txt", CFile::modeCreate | CFile::modeWrite ) ) {
   afxDump << "Unable to open file" << "\n";
   exit( 1 );
}
CDumpContext dc( &f );


CDumpContext::Flush

void Flush( );
throw( CFileException );

Remarks

Forces any data remaining in buffers to be written to the file attached to the dump context.

Example

//example for CDumpContext::Flush
afxDump.Flush();


CDumpContext::GetDepth

int GetDepth( ) const;

Return Value

The depth of the dump as set by SetDepth.

Remarks

Determines whether a deep or shallow dump is in process.

Example

See the example for SetDepth.

CDumpContext Overview | Class Members | Hierarchy Chart

See Also CDumpContext::SetDepth


CDumpContext::HexDump

void HexDump( LPCTSTR lpszLine, BYTE* pby, int nBytes, int nWidth );
throw( CFileException );

Parameters

lpszLine

A string to output at the start of a new line.

pby

A pointer to a buffer containing the bytes to dump.

nBytes

The number of bytes to dump.

nWidth

Maximum number of bytes dumped per line (not the width of the output line).

Remarks

Dumps an array of bytes formatted as hexadecimal numbers.

Example

//example for CDumpContext::HexDump
char test[] = "This is a test of CDumpContext::HexDump\n";
afxDump.HexDump( ".", (BYTE*) test, sizeof test, 20 );

The output from this program is:

    . 54 68 69 73 20 69 73 20 61 20 74 65 73 74 20 6F 66 20 43 44
    . 75 6D 70 43 6F 6E 74 65 78 74 3A 3A 48 65 78 44 75 6D 70 0A
    . 00


CDumpContext::SetDepth

void SetDepth( int nNewDepth );

Parameters

nNewDepth

The new depth value.

Remarks

Sets the depth for the dump. If you are dumping a primitive type or simple CObject that contains no pointers to other objects, then a value of 0 is sufficient. A value greater than 0 specifies a deep dump where all objects are dumped recursively. For example, a deep dump of a collection will dump all elements of the collection. You may use other specific depth values in your derived classes.

Note Circular references are not detected in deep dumps and can result in infinite loops.

Example

//example for CDumpContext::SetDepth
afxDump.SetDepth( 1 );  // Specifies deep dump
ASSERT( afxDump.GetDepth() == 1 );

CDumpContext Overview | Class Members | Hierarchy Chart

See Also CObject::Dump


CDumpContext::operator <<

CDumpContext& operator <<( const CObject* pOb );
throw( CFileException );

CDumpContext& operator <<( const CObject& ob );
throw( CFileException );

CDumpContext& operator <<( LPCTSTR lpsz );
throw( CFileException );

CDumpContext& operator <<( const void* lp );
throw( CFileException );

CDumpContext& operator <<( BYTE by );
throw( CFileException );

CDumpContext& operator <<( WORD w );
throw( CFileException );

CDumpContext& operator <<( DWORD dw );
throw( CFileException );

CDumpContext& operator <<( int n );
throw( CFileException );

CDumpContext& operator <<( double d );
throw( CFileException );

CDumpContext& operator <<( float f );
throw( CFileException );

CDumpContext& operator <<( LONG l );
throw( CFileException );

CDumpContext& operator <<( UINT u );
throw( CFileException );

CDumpContext& operator <<( LPCWSTR lpsz );
throw( CFileException );

CDumpContext& operator <<( LPCSTR lpsz );
throw( CFileException );

Return Value

A CDumpContext reference. Using the return value, you can write multiple insertions on a single line of source code.

Remarks

Outputs the specified data to the dump context.

The insertion operator is overloaded for CObject pointers as well as for most primitive types. A pointer to character results in a dump of string contents; a pointer to void results in a hexadecimal dump of the address only.

If you use the IMPLEMENT_DYNAMIC or IMPLEMENT_SERIAL macro in the implementation of your class, then the insertion operator, through CObject::Dump, will print the name of your CObject-derived class. Otherwise, it will print CObject. If you override the Dump function of the class, then you can provide a more meaningful output of the object’s contents instead of a hexadecimal dump.

Example

//example for CDumpContext::operator <<
extern CObList li;
CString s = "test";
int i = 7;
long lo = 1000000000L;
afxDump << "list=" << &li << "string="
        << s << "int=" << i << "long=" << lo << "\n";


CDWordArray

The CDWordArray class supports arrays of 32-bit doublewords.

The member functions of CDWordArray are similar to the member functions of class CObArray. Because of this similarity, you can use the CObArray reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a DWORD.

CObject* CObArray::GetAt( int <nIndex> ) const;

for example, translates to

DWORD CDWordArray::GetAt( int <nIndex> ) const;

CDWordArray incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. If an array of doublewords is stored to an archive, either with the overloaded insertion (<<) operator or with the Serialize member function, each element is, in turn, serialized.

Note Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

If you need debug output from individual elements in the array, you must set the depth of the CDumpContext object to 1 or greater.

For more information on using CDWordArray, see the article Collections in Visual C++ Programmer's Guide.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

See Also CObArray


CDWordArray Class Members

Construction

CDWordArray Constructs an empty array for doublewords.

Bounds

GetSize | Gets the number of elements in this array.
GetUpperBound | Returns the largest valid index.
SetSize | Sets the number of elements to be contained in this array.

Operations

FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.

Element Access

GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; array not allowed to grow.
ElementAt | Returns a temporary reference to the doubleword within the array.
GetData | Allows access to elements in the array. Can be NULL.

Growing the Array

SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds an element to the end of the array; grows the array if necessary.
Append | Appends another array to the array; grows the array if necessary.
Copy | Copies another array to the array; grows the array if necessary.

Insertion/Removal

InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.

Operators

operator [] Sets or gets the element at the specified index.


CEdit

The CEdit class provides the functionality of a Windows edit control. An edit control is a rectangular child window in which the user can enter text.

You can create an edit control either from a dialog template or directly in your code. In both cases, first call the constructor CEdit to construct the CEdit object, then call the Create member function to create the Windows edit control and attach it to the CEdit object.

Construction can be a one-step process in a class derived from CEdit. Write a constructor for the derived class and call Create from within the constructor.

CEdit inherits significant functionality from CWnd. To set and retrieve text from a CEdit object, use the CWnd member functions SetWindowText and GetWindowText, which set or get the entire contents of an edit control, even if it is a multiline control. Also, if an edit control is multiline, get and set part of the control’s text by calling the CEdit member functions GetLine, SetSel, GetSel, and ReplaceSel.

If you want to handle Windows notification messages sent by an edit control to its parent (usually a class derived from CDialog), add a message-map entry and message-handler member function to the parent class for each message.

Each message-map entry takes the following form:

ON_Notification( id, memberFxn )

where id specifies the child window ID of the edit control sending the notification, and memberFxn is the name of the parent member function you have written to handle the notification.

The parent’s function prototype is as follows:

afx_msg void memberFxn( );

Following is a list of potential message-map entries and a description of the cases in which they would be sent to the parent:

  • ON_EN_CHANGE The user has taken an action that may have altered text in an edit control. Unlike the EN_UPDATE notification message, this notification message is sent after Windows updates the display.

  • ON_EN_ERRSPACE The edit control cannot allocate enough memory to meet a specific request.

  • ON_EN_HSCROLL The user clicks an edit control’s horizontal scroll bar. The parent window is notified before the screen is updated.

  • ON_EN_KILLFOCUS The edit control loses the input focus.

  • ON_EN_MAXTEXT The current insertion has exceeded the specified number of characters for the edit control and has been truncated. Also sent when an edit control does not have the ES_AUTOHSCROLL style and the number of characters to be inserted would exceed the width of the edit control. Also sent when an edit control does not have the ES_AUTOVSCROLL style and the total number of lines resulting from a text insertion would exceed the height of the edit control.

  • ON_EN_SETFOCUS Sent when an edit control receives the input focus.

  • ON_EN_UPDATE The edit control is about to display altered text. Sent after the control has formatted the text but before it screens the text so that the window size can be altered, if necessary.

  • ON_EN_VSCROLL The user clicks an edit control’s vertical scroll bar. The parent window is notified before the screen is updated.

If you create a CEdit object within a dialog box, the CEdit object is automatically destroyed when the user closes the dialog box.

If you create a CEdit object from a dialog resource using the dialog editor, the CEdit object is automatically destroyed when the user closes the dialog box.

If you create a CEdit object within a window, you may also need to destroy it. If you create the CEdit object on the stack, it is destroyed automatically. If you create the CEdit object on the heap by using the new function, you must call delete on the object to destroy it when the user terminates the Windows edit control. If you allocate any memory in the CEdit object, override the CEdit destructor to dispose of the allocations.

For more information on CEdit, see Control Topics in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CALCDRIV | MFC Sample CMNCTRL2 | MFC Sample VCTERM

See Also CWnd, CButton, CComboBox, CListBox, CScrollBar, CStatic, CDialog


CEdit Class Members

Construction
Attributes
Operations
Clipboard Operations

Construction

CEdit | Constructs a CEdit control object.
Create | Creates the Windows edit control and attaches it to the CEdit object.

CEdit Attributes

CanUndo | Determines whether an edit-control operation can be undone.
GetLineCount | Retrieves the number of lines in a multiple-line edit control.
GetModify | Determines whether the contents of an edit control have been modified.
SetModify | Sets or clears the modification flag for an edit control.
GetRect | Gets the formatting rectangle of an edit control.
GetSel | Gets the starting and ending character positions of the current selection in an edit control.
GetHandle | Retrieves a handle to the memory currently allocated for a multiple-line edit control.
SetHandle | Sets the handle to the local memory that will be used by a multiple-line edit control.
SetMargins | Sets the left and right margins for this CEdit.
GetMargins | Gets the left and right margins for this CEdit.
SetLimitText | Sets the maximum amount of text this CEdit can contain.
GetLimitText | Gets the maximum amount of text this CEdit can contain.
PosFromChar | Retrieves the coordinates of the upper-left corner of a specified character index.
CharFromPos | Retrieves the line and character indices for the character closest to a specified position.
GetLine | Retrieves a line of text from an edit control.
GetPasswordChar | Retrieves the password character displayed in an edit control when the user enters text.
GetFirstVisibleLine | Determines the topmost visible line in an edit control.

CEdit Operations

EmptyUndoBuffer | Resets (clears) the undo flag of an edit control.
FmtLines | Sets the inclusion of soft line-break characters on or off within a multiple-line edit control.
LimitText | Limits the length of the text that the user may enter into an edit control.
LineFromChar | Retrieves the line number of the line that contains the specified character index.
LineIndex | Retrieves the character index of a line within a multiple-line edit control.
LineLength | Retrieves the length of a line in an edit control.
LineScroll | Scrolls the text of a multiple-line edit control.
ReplaceSel | Replaces the current selection in an edit control with the specified text.
SetPasswordChar | Sets or removes a password character displayed in an edit control when the user enters text.
SetRect | Sets the formatting rectangle of a multiple-line edit control and updates the control.
SetRectNP | Sets the formatting rectangle of a multiple-line edit control without redrawing the control window.
SetSel | Selects a range of characters in an edit control.
SetTabStops | Sets the tab stops in a multiple-line edit control.
SetReadOnly | Sets the read-only state of an edit control.

CEdit Clipboard Operations

Undo | Reverses the last edit-control operation.
Clear | Deletes (clears) the current selection (if any) in the edit control.
Copy | Copies the current selection (if any) in the edit control to the Clipboard in CF_TEXT format.
Cut | Deletes (cuts) the current selection (if any) in the edit control and copies the deleted text to the Clipboard in CF_TEXT format.
Paste | Inserts the data from the Clipboard into the edit control at the current cursor position. Data is inserted only if the Clipboard contains data in CF_TEXT format.


CEdit::CanUndo

BOOL CanUndo( ) const;

Return Value

Nonzero if the last edit operation can be undone by a call to the Undo member function; 0 if it cannot be undone.

Remarks

Call this function to determine if the last edit operation can be undone.

For more information, see EM_CANUNDO in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::Undo, CEdit::EmptyUndoBuffer


CEdit::CEdit

CEdit( );

Remarks

Constructs a CEdit object. Use Create to construct the Windows edit control.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::Create


CEdit::CharFromPos

int CharFromPos( CPoint pt ) const;

Return Value

The character index in the low-order WORD, and the line index in the high-order WORD.

Parameters

pt

The coordinates of a point in the client area of this CEdit object.

Remarks

Call this function to retrieve the zero-based line and character indices of the character nearest the specified point in this CEdit control

Note This member function is available beginning with Windows 95 and Windows NT 4.0.

For more information, see EM_CHARFROMPOS in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::PosFromChar


CEdit::Clear

void Clear( );

Remarks

Call this function to delete (clear) the current selection (if any) in the edit control.

The deletion performed by Clear can be undone by calling the Undo member function.

To delete the current selection and place the deleted contents into the Clipboard, call the Cut member function.

For more information, see WM_CLEAR in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::Undo, CEdit::Copy, CEdit::Cut, CEdit::Paste


CEdit::Copy

void Copy( );

Remarks

Call this function to coy the current selection (if any) in the edit control to the Clipboard in CF_TEXT format.

For more information, see WM_COPY in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::Clear, CEdit::Cut, CEdit::Paste


CEdit::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if initialization is successful; otherwise 0.

Parameters

dwStyle

Specifies the edit control’s style. Apply any combination of edit styles to the control.

rect

Specifies the edit control’s size and position. Can be a CRect object or RECT structure.

pParentWnd

Specifies the edit control’s parent window (usually a CDialog). It must not be NULL.

nID

Specifies the edit control’s ID.

Remarks

You construct a CEdit object in two steps. First, call the CEdit constructor, then call Create, which creates the Windows edit control and attaches it to the CEdit object.

When Create executes, Windows sends the WM_NCCREATE, WM_NCCALCSIZE, WM_CREATE, and WM_GETMINMAXINFO messages to the edit control.

These messages are handled by default by the OnNcCreate, OnNcCalcSize, OnCreate, and OnGetMinMaxInfo member functions in the CWnd base class. To extend the default message handling, derive a class from CEdit, add a message map to the new class, and override the above message-handler member functions. Override OnCreate, for example, to perform needed initialization for the new class.

Apply the following window styles to an edit control.

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

  • WS_GROUP To group controls

  • WS_TABSTOP To include edit control in the tabbing order

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::CEdit


CEdit::Cut

void Cut( );

Remarks

Call this function to delete (cut) the current selection (if any) in the edit control and copy the deleted text to the Clipboard in CF_TEXT format.

The deletion performed by Cut can be undone by calling the Undo member function.

To delete the current selection without placing the deleted text into the Clipboard, call the Clear member function.

For more information, see WM_CUT in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::Undo, CEdit::Clear, CEdit::Copy, CEdit::Paste


CEdit::EmptyUndoBuffer

void EmptyUndoBuffer( );

Remarks

Call this function to reset (clear) the undo flag of an edit control. The edit control will now be unable to undo the last operation. The undo flag is set whenever an operation within the edit control can be undone.

The undo flag is automatically cleared whenever the SetWindowText or SetHandle CWnd member functions are called.

For more information, see EM_EMPTYUNDOBUFFER in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::CanUndo, CEdit::SetHandle, CEdit::Undo, CWnd::SetWindowText


CEdit::FmtLines

BOOL FmtLines( BOOL bAddEOL );

Return Value

Nonzero if any formatting occurs; otherwise 0.

Parameters

bAddEOL

Specifies whether soft line-break characters are to be inserted. A value of TRUE inserts the characters; a value of FALSE removes them.

Remarks

Call this function to set the inclusion of soft line-break characters on or off within a multiple-line edit control. A soft line break consists of two carriage returns and a linefeed inserted at the end of a line that is broken because of word wrapping. A hard line break consists of one carriage return and a linefeed. Lines that end with a hard line break are not affected by FmtLines.

Windows will only respond if the CEdit object is a multiple-line edit control.

FmtLines only affects the buffer returned by GetHandle and the text returned by WM_GETTEXT. It has no impact on the display of the text within the edit control.

For more information, see EM_FMTLINES in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::GetHandle, CWnd::GetWindowText


CEdit::GetFirstVisibleLine

int GetFirstVisibleLine( ) const;

Return Value

The zero-based index of the topmost visible line. For single-line edit controls, the return value is 0.

Remarks

Call this function to determine the topmost visible line in an edit control.

For more information, see EM_GETFIRSTVISIBLELINE in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::GetLine


CEdit::GetHandle

HLOCAL GetHandle( ) const;

Return Value

A local memory handle that identifies the buffer holding the contents of the edit control. If an error occurs, such as sending the message to a single-line edit control, the return value is 0.

Remarks

Call this function to retrieve a handle to the memory currently allocated for a multiple-line edit control. The handle is a local memory handle and may be used by any of the Local Windows memory functions that take a local memory handle as a parameter.

GetHandle is processed only by multiple-line edit controls.

Call GetHandle for a multiple-line edit control in a dialog box only if the dialog box was created with the DS_LOCALEDIT style flag set. If the DS_LOCALEDIT style is not set, you will still get a nonzero return value, but you will not be able to use the returned value.

Note GetHandle will not work with Windows 95. If you call GetHandle in Windows 95, it will return NULL. GetHandle will work as documented under Windows NT, versions 3.51 and later.

For more information, see EM_GETHANDLE in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::SetHandle


CEdit::GetLimitText

UINT GetLimitText( ) const;

Return Value

The current text limit, in bytes, for this CEdit object.

Remarks

Call this member function to get the text limit for this CEdit object. The text limit is the maximum amount of text, in bytes, that the edit control can accept.

Note This member function is available beginning with Windows 95 and Windows NT 4.0.

For more information, see EM_GETLIMITTEXT in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::SetLimitText, CEdit::LimitText


CEdit::GetLine

int GetLine( int nIndex, LPTSTR lpszBuffer ) const;

int GetLine( int nIndex, LPTSTR lpszBuffer, int nMaxLength ) const;

Return Value

The number of bytes actually copied. The return value is 0 if the line number specified by nIndex is greater then the number of lines in the edit control.

Parameters

nIndex

Specifies the line number to retrieve from a multiple-line edit control. Line numbers are zero-based; a value of 0 specifies the first line. This parameter is ignored by a single-line edit control.

lpszBuffer

Points to the buffer that receives a copy of the line. The first word of the buffer must specify the maximum number of bytes that can be copied to the buffer.

nMaxLength

Specifies the maximum number of bytes that can be copied to the buffer. GetLine places this value in the first word of lpszBuffer before making the call to Windows.

Remarks

Call this function to retrieve a line of text from an edit control and places it in lpszBuffer.

The copied line does not contain a null-termination character.

For more information, see EM_GETLINE in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::LineLength, CWnd::GetWindowText


CEdit::GetLineCount

int GetLineCount( ) const;

Return Value

An integer containing the number of lines in the multiple-line edit control. If no text has been entered into the edit control, the return value is 1.

Remarks

Call this function to retrieve the number of lines in a multiple-line edit control.

GetLineCount is only processed by multiple-line edit controls.

For more information, see EM_GETLINECOUNT in the Win32 documentation.


CEdit::GetMargins

DWORD GetMargins( ) const;

Return Value

The width of the left margin in the low-order WORD and the width of the right margin in the high-order WORD.

Remarks

Call this member function to retrieve the left and right margins of this edit control. Margins are measured in pixels.

Note This member function is available beginning with Windows 95 and Windows NT 4.0.

For more information, see EM_GETMARGINS in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::SetMargins


CEdit::GetModify

BOOL GetModify( ) const;

Return Value

Nonzero if the edit-control contents have been modified; 0 if they have remained unchanged.

Remarks

Call this function to determine whether the contents of an edit control have been modified.

Windows maintains an internal flag indicating whether the contents of the edit control have been changed. This flag is cleared when the edit control is first created and may also be cleared by calling the SetModify member function.

For more information, see EM_GETMODIFY in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::SetModify


CEdit::GetPasswordChar

TCHAR GetPasswordChar( ) const;

Return Value

Specifies the character to be displayed in place of the character typed by the user. The return value is NULL if no password character exists.

Remarks

Call this function to retrieve the password character displayed in an edit control when the user enters text.

If the edit control is created with the ES_PASSWORD style, the default password character is set to an asterisk (*).

For more information, see EM_GETPASSWORDCHAR in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::SetPasswordChar


CEdit::GetRect

void GetRect( LPRECT lpRect ) const;

Parameters

lpRect

Points to the RECT structure that receives the formatting rectangle.

Remarks

Call this function to get the formatting rectangle of an edit control. The formatting rectangle is the limiting rectangle of the text, which is independent of the size of the edit-control window.

The formatting rectangle of a multiple-line edit control can be modified by the SetRect and SetRectNP member functions.

For more information, see EM_GETRECT in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::SetRect, CEdit::SetRectNP


CEdit::GetSel

DWORD GetSel( ) const;

void GetSel( int& nStartChar, int& nEndChar ) const;

Return Value

The version that returns a DWORD returns a value that contains the starting position in the low-order word and the position of the first nonselected character after the end of the selection in the high-order word.

Parameters

nStartChar

Reference to an integer that will receive the position of the first character in the current selection.

nEndChar

Reference to an integer that will receive the position of the first nonselected character past the end of the current selection.

Remarks

Call this function to get the starting and ending character positions of the current selection (if any) in an edit control, using either the return value or the parameters.

For more information, see EM_GETSEL in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::SetSel


CEdit::LimitText

void LimitText( int nChars = 0 );

Parameters

nChars

Specifies the length (in bytes) of the text that the user can enter. If this parameter is 0, the text length is set to UINT_MAX bytes. This is the default behavior.

Remarks

Call this function to limit the length of the text that the user may enter into an edit control.

Changing the text limit restricts only the text the user can enter. It has no effect on any text already in the edit control, nor does it affect the length of the text copied to the edit control by the SetWindowText member function in CWnd. If an application uses the SetWindowText function to place more text into an edit control than is specified in the call to LimitText, the user can delete any of the text within the edit control. However, the text limit will prevent the user from replacing the existing text with new text, unless deleting the current selection causes the text to fall below the text limit.

Note In Win32 (Windows NT and Windows 95), SetLimitText replaces this function.

For more information, see EM_LIMITTEXT in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CWnd::SetWindowText, CEdit::GetLimitText, CEdit::SetLimitText


CEdit::LineFromChar

int LineFromChar( int nIndex = -1 ) const;

Return Value

The zero-based line number of the line containing the character index specified by nIndex. If nIndex is –1, the number of the line that contains the first character of the selection is returned. If there is no selection, the current line number is returned.

Parameters

nIndex

Contains the zero-based index value for the desired character in the text of the edit control, or contains –1. If nIndex is –1, it specifies the current line, that is, the line that contains the caret.

Remarks

Call this function to retrieve the line number of the line that contains the specified character index. A character index is the number of characters from the beginning of the edit control.

This member function is only used by multiple-line edit controls.

For more information, see EM_LINEFROMCHAR in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::LineIndex


CEdit::LineIndex

int LineIndex( int nLine = -1 ) const;

Return Value

The character index of the line specified in nLine or –1 if the specified line number is greater then the number of lines in the edit control.

Parameters

nLine

Contains the index value for the desired line in the text of the edit control, or contains –1. If nLine is –1, it specifies the current line, that is, the line that contains the caret.

Remarks

Call this function to retrieve the character index of a line within a multiple-line edit control. The character index is the number of characters from the beginning of the edit control to the specified line.

This member function is only processed by multiple-line edit controls.

For more information, see EM_LINEINDEX in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::LineFromChar


CEdit::LineLength

int LineLength( int nLine = -1 ) const;

Return Value

When LineLength is called for a multiple-line edit control, the return value is the length (in bytes) of the line specified by nLine. When LineLength is called for a single-line edit control, the return value is the length (in bytes) of the text in the edit control.

Parameters

nLine

Specifies the character index of a character in the line whose length is to be retrieved. If this parameter is –1, the length of the current line (the line that contains the caret) is returned, not including the length of any selected text within the line. When LineLength is called for a single-line edit control, this parameter is ignored.

Remarks

Call this function to retrieve the length of a line in an edit control.

Use the LineIndex member function to retrieve a character index for a given line number within a multiple-line edit control.

For more information, see EM_LINELENGTH in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::LineIndex


CEdit::LineScroll

void LineScroll( int nLines, int nChars = 0 );

Parameters

nLines

Specifies the number of lines to scroll vertically.

nChars

Specifies the number of character positions to scroll horizontally. This value is ignored if the edit control has either the ES_RIGHT or ES_CENTER style.

Remarks

Call this function to scroll the text of a multiple-line edit control.

This member function is processed only by multiple-line edit controls.

The edit control does not scroll vertically past the last line of text in the edit control. If the current line plus the number of lines specified by nLines exceeds the total number of lines in the edit control, the value is adjusted so that the last line of the edit control is scrolled to the top of the edit-control window.

LineScroll can be used to scroll horizontally past the last character of any line.

For more information, see EM_LINESCROLL in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::LineIndex


CEdit::Paste

void Paste( );

Remarks

Call this function to insert the data from the Clipboard into the CEdit at the insertion point. Data is inserted only if the Clipboard contains data in CF_TEXT format.

For more information, see WM_PASTE in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::Clear, CEdit::Copy, CEdit::Cut


CEdit::PosFromChar

CPoint PosFromChar( UINT nChar ) const;

Return Value

The coordinates of the top-left corner of the character specified by nChar.

Parameters

nChar

The zero-based index of the specified character.

Remarks

Call this function to get the position (top-left corner) of a given character within this CEdit object. The character is specified by giving its zero-based index value. If nChar is greater than the index of the last character in this CEdit object, the return value specifies the coordinates of the character position just past the last character in this CEdit object.

Note This member function is available beginning with Windows 95 and Windows NT 4.0.

For more information, see EM_POSFROMCHAR in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::CharFromPos


CEdit::ReplaceSel

void ReplaceSel( LPCTSTR lpszNewText, BOOL bCanUndo = FALSE );

Parameters

lpszNewText

Points to a null-terminated string containing the replacement text.

bCanUndo

To specify that this function can be undone, set the value of this parameter to TRUE . The default value is FALSE.

Remarks

Call this function to replace the current selection in an edit control with the text specified by lpszNewText.

Replaces only a portion of the text in an edit control. If you want to replace all of the text, use the CWnd::SetWindowText member function.

If there is no current selection, the replacement text is inserted at the current cursor location.

For more information, see EM_REPLACESEL in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CWnd::SetWindowText


CEdit::SetHandle

void SetHandle( HLOCAL hBuffer );

Parameters

hBuffer

Contains a handle to the local memory. This handle must have been created by a previous call to the LocalAlloc Windows function using the LMEM_MOVEABLE flag. The memory is assumed to contain a null-terminated string. If this is not the case, the first byte of the allocated memory should be set to 0.

Remarks

Call this function to set the handle to the local memory that will be used by a multiple-line edit control. The edit control will then use this buffer to store the currently displayed text instead of allocating its own buffer.

This member function is processed only by multiple-line edit controls.

Before an application sets a new memory handle, it should use the GetHandle member function to get the handle to the current memory buffer and free that memory using the LocalFree Windows function.

SetHandle clears the undo buffer (the CanUndo member function then returns 0) and the internal modification flag (the GetModify member function then returns 0). The edit-control window is redrawn.

You can use this member function in a multiple-line edit control in a dialog box only if you have created the dialog box with the DS_LOCALEDIT style flag set.

Note GetHandle will not work with Windows 95. If you call GetHandle in Windows 95, it will return NULL. GetHandle will work as documented under Windows NT, versions 3.51 and later.

For more information, see EM_SETHANDLE, LocalAlloc, and LocalFree in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::CanUndo, CEdit::GetHandle, CEdit::GetModify


CEdit::SetLimitText

void SetLimitText( UINT nMax );

Parameters

nMax

The new text limit, in bytes.

Remarks

Call this member function to set the text limit for this CEdit object. The text limit is the maximum amount of text, in bytes, that the edit control can accept.

Changing the text limit restricts only the text the user can enter. It has no effect on any text already in the edit control, nor does it affect the length of the text copied to the edit control by the SetWindowText member function in CWnd. If an application uses the SetWindowText function to place more text into an edit control than is specified in the call to LimitText, the user can delete any of the text within the edit control. However, the text limit will prevent the user from replacing the existing text with new text, unless deleting the current selection causes the text to fall below the text limit.

This function replaces LimitText in Win32.

For more information, see EM_SETLIMITTEXT in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::GetLimitText, CEdit::LimitText


CEdit::SetMargins

void SetMargins( UINT nLeft, UINT nRight );

Parameters

nLeft

The width of the new left margin, in pixels.

nRight

The width of the new right margin, in pixels.

Remarks

Call this member function to set the left and right margins of this edit control.

Note This member function is available beginning with Windows 95 and Windows NT 4.0.

For more information, see EM_SETMARGINS in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::GetMargins


CEdit::SetModify

void SetModify( BOOL bModified = TRUE );

Parameters

bModified

A value of TRUE indicates that the text has been modified, and a value of FALSE indicates it is unmodified. By default, the modified flag is set.

Remarks

Call this function to set or clear the modified flag for an edit control. The modified flag indicates whether or not the text within the edit control has been modified. It is automatically set whenever the user changes the text. Its value may be retrieved with the GetModify member function.

For more information, see EM_SETMODIFY in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::GetModify


CEdit::SetPasswordChar

void SetPasswordChar( TCHAR ch );

Parameters

ch

Specifies the character to be displayed in place of the character typed by the user. If ch is 0, the actual characters typed by the user are displayed.

Remarks

Call this function to set or remove a password character displayed in an edit control when the user types text. When a password character is set, that character is displayed for each character the user types.

This member function has no effect on a multiple-line edit control.

When the SetPasswordChar member function is called, CEdit will redraw all visible characters using the character specified by ch.

If the edit control is created with the ES_PASSWORD style, the default password character is set to an asterisk (*). This style is removed if SetPasswordChar is called with ch set to 0.

For more information, see EM_SETPASSWORDCHAR in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::GetPasswordChar


CEdit::SetReadOnly

BOOL SetReadOnly( BOOL bReadOnly = TRUE );

Return Value

Nonzero if the operation is successful, or 0 if an error occurs.

Parameters

bReadOnly

Specifies whether to set or remove the read-only state of the edit control. A value of TRUE sets the state to read-only; a value of FALSE sets the state to read/write.

Remarks

Calls this function to set the read-only state of an edit control.

The current setting can be found by testing the ES_READONLY flag in the return value of CWnd::GetStyle.

For more information, see EM_SETREADONLY in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CWnd::GetStyle


CEdit::SetRect

void SetRect( LPCRECT lpRect );

Parameters

lpRect

Points to the RECT structure or CRect object that specifies the new dimensions of the formatting rectangle.

Remarks

Call this function to set the dimensions of a rectangle using the specified coordinates. This member is processed only by multiple-line edit controls.

Use SetRect to set the formatting rectangle of a multiple-line edit control. The formatting rectangle is the limiting rectangle of the text, which is independent of the size of the edit-control window. When the edit control is first created, the formatting rectangle is the same as the client area of the edit-control window. By using the SetRect member function, an application can make the formatting rectangle larger or smaller than the edit-control window.

If the edit control has no scroll bar, text will be clipped, not wrapped, if the formatting rectangle is made larger than the window. If the edit control contains a border, the formatting rectangle is reduced by the size of the border. If you adjust the rectangle returned by the GetRect member function, you must remove the size of the border before you pass the rectangle to SetRect.

When SetRect is called, the edit control’s text is also reformatted and redisplayed.

For more information, see EM_SETRECT in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CRect::CRect, CRect::CopyRect, CRect::operator =, CRect::SetRectEmpty, CEdit::GetRect, CEdit::SetRectNP


CEdit::SetRectNP

void SetRectNP( LPCRECT lpRect );

Parameters

lpRect

Points to a RECT structure or CRect object that specifies the new dimensions of the rectangle.

Remarks

Call this function to set the formatting rectangle of a multiple-line edit control. The formatting rectangle is the limiting rectangle of the text, which is independent of the size of the edit-control window.

SetRectNP is identical to the SetRect member function except that the edit-control window is not redrawn.

When the edit control is first created, the formatting rectangle is the same as the client area of the edit-control window. By calling the SetRectNP member function, an application can make the formatting rectangle larger or smaller than the edit-control window.

If the edit control has no scroll bar, text will be clipped, not wrapped, if the formatting rectangle is made larger than the window.

This member is processed only by multiple-line edit controls.

For more information, see EM_SETRECTNP in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CRect::CRect, CRect::CopyRect, CRect::operator =, CRect::SetRectEmpty, CEdit::GetRect, CEdit::SetRect


CEdit::SetSel

void SetSel( DWORD dwSelection, BOOL bNoScroll = FALSE );

void SetSel( int nStartChar, int nEndChar, BOOL bNoScroll = FALSE );

Parameters

dwSelection

Specifies the starting position in the low-order word and the ending position in the high-order word. If the low-order word is 0 and the high-order word is –1, all the text in the edit control is selected. If the low-order word is –1, any current selection is removed.

bNoScroll

Indicates whether the caret should be scrolled into view. If FALSE, the caret is scrolled into view. If TRUE, the caret is not scrolled into view.

nStartChar

Specifies the starting position. If nStartChar is 0 and nEndChar is –1, all the text in the edit control is selected. If nStartChar is –1, any current selection is removed.

nEndChar

Specifies the ending position.

Remarks

Call this function to select a range of characters in an edit control.

For more information, see EM_SETSEL in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::GetSel, CEdit::ReplaceSel


CEdit::SetTabStops

void SetTabStops( );

BOOL SetTabStops( const int& cxEachStop );

BOOL SetTabStops( int nTabStops, LPINT rgTabStops );

Return Value

Nonzero if the tabs were set; otherwise 0.

Parameters

cxEachStop

Specifies that tab stops are to be set at every cxEachStop dialog units.

nTabStops

Specifies the number of tab stops contained in rgTabStops. This number must be greater than 1.

rgTabStops

Points to an array of unsigned integers specifying the tab stops in dialog units. A dialog unit is a horizontal or vertical distance. One horizontal dialog unit is equal to one-fourth of the current dialog base width unit, and 1 vertical dialog unit is equal to one-eighth of the current dialog base height unit. The dialog base units are computed based on the height and width of the current system font. The GetDialogBaseUnits Windows function returns the current dialog base units in pixels.

Remarks

Call this function to set the tab stops in a multiple-line edit control. When text is copied to a multiple-line edit control, any tab character in the text will cause space to be generated up to the next tab stop.

To set tab stops to the default size of 32 dialog units, call the parameterless version of this member function. To set tab stops to a size other than 32, call the version with the cxEachStop parameter. To set tab stops to an array of sizes, use the version with two parameters.

This member function is only processed by multiple-line edit controls.

SetTabStops does not automatically redraw the edit window. If you change the tab stops for text already in the edit control, call CWnd::InvalidateRect to redraw the edit window.

For more information, see EM_SETTABSTOPS and GetDialogBaseUnits in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CWnd::InvalidateRect


CEdit::Undo

BOOL Undo( );

Return Value

For a single-line edit control, the return value is always nonzero. For a multiple-line edit control, the return value is nonzero if the undo operation is successful, or 0 if the undo operation fails.

Remarks

Call this function to undo the last edit-control operation.

An undo operation can also be undone. For example, you can restore deleted text with the first call to Undo. As long as there is no intervening edit operation, you can remove the text again with a second call to Undo.

For more information, see EM_UNDO in the Win32 documentation.

CEdit Overview | Class Members | Hierarchy Chart

See Also CEdit::CanUndo


CEditView

A CEditView object is a view that, like the CEdit class, provides the functionality of a Windows edit control and can be used to implement simple text-editor functionality. The CEditView class provides the following additional functions:

  • Printing

  • Find and replace

Because class CEditView is a derivative of class CView, objects of class CEditView can be used with documents and document templates.

Each CEditView control’s text is kept in its own global memory object. Your application can have any number of CEditView objects.

Create objects of type CEditView if you want an edit window with the added functionality listed above, or if you want simple text-editor functionality. A CEditView object can occupy the entire client area of a window. Derive your own classes from CEditView to add or modify the basic functionality, or to declare classes that can be added to a document template.

The default implementation of class CEditView handles the following commands: ID_EDIT_SELECT_ALL, ID_EDIT_FIND, ID_EDIT_REPLACE, ID_EDIT_REPEAT, and ID_FILE_PRINT.

Objects of type CEditView (or of types derived from CEditView) have the following limitations:

  • CEditView does not implement true WYSIWYG (what you see is what you get) editing. Where there is a choice between readability on the screen and matching printed output, CEditView opts for screen readability.

  • CEditView can display text in only a single font. No special character formatting is supported. See class CRichEditView for greater capabilities.

  • The amount of text a CEditView can contain is limited. The limits are the same as for the CEdit control.

For more information on CEditView, see Derived View Classes in Visual C++ Programmer's Guide.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample MULTIPAD | MFC Sample SUPERPAD

See Also CEdit, CDocument, CDocTemplate, CCtrlView, CRichEditView


CEditView Class Members

Data Members

dwStyleDefault Default style for objects of type CEditView.

Construction

CEditView Constructs an object of type CEditView.

Attributes

GetEditCtrl | Provides access to the CEdit portion of a CEditView object (the Windows edit control).
GetPrinterFont | Retrieves the current printer font.
GetSelectedText | Retrieves the current text selection.
LockBuffer | Locks the buffer.
UnlockBuffer | Unlocks the buffer.
GetBufferLength | Obtains the length of the character buffer.
SetPrinterFont | Sets a new printer font.
SetTabStops | Sets tab stops for both screen display and printing.

Operations

FindText | Searches for a string within the text.
PrintInsideRect | Renders text inside a given rectangle.
SerializeRaw | Serializes a CEditView object to disk as raw text.

Overridables

OnFindNext | Finds next occurrence of a text string.
OnReplaceAll | Replaces all occurrences of a given string with a new string.
OnReplaceSel | Replaces current selection.
OnTextNotFound | Called when a find operation fails to match any further text.


CEditView::CEditView

CEditView( );

Remarks

Constructs an object of type CEditView. After constructing the object, you must call the CWnd::Create function before the edit control is used. If you derive a class from CEditView and add it to the template using CWinApp::AddDocTemplate, the framework calls both this constructor and the Create function.

CEditView Overview | Class Members | Hierarchy Chart

See Also CWnd::Create, CWinApp::AddDocTemplate


CEditView::FindText

BOOL FindText( LPCTSTR lpszFind, BOOL bNext = TRUE, BOOL bCase = TRUE );

Return Value

Nonzero if the search text is found; otherwise 0.

Parameters

lpszFind

The text to be found.

bNext

Specifies the direction of the search. If TRUE, the search direction is toward the end of the buffer. If FALSE, the search direction is toward the beginning of the buffer.

bCase

Specifies whether the search is case sensitive. If TRUE, the search is case sensitive. If FALSE, the search is not case sensitive.

Remarks

Call the FindText function to search the CEditView object’s text buffer. This function searches the text in the buffer for the text specified by lpszFind, starting at the current selection, in the direction specified by bNext, and with case sensitivity specified by bCase. If the text is found, it sets the selection to the found text and returns a nonzero value. If the text is not found, the function returns 0.

You normally do not need to call the FindText function unless you override OnFindNext, which calls FindText.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::OnFindNext, CEditView::OnReplaceAll, CEditView::OnReplaceSel, CEditView::OnTextNotFound


CEditView::GetBufferLength

UINT GetBufferLength( ) const;

Return Value

The length of the string in the buffer.

Remarks

Call this member function to obtain the number of characters currently in the edit control’s buffer, not including the null terminator.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::LockBuffer, CEditView::UnlockBuffer


CEditView::GetEditCtrl

CEdit& GetEditCtrl( ) const;

Return Value

A reference to a CEdit object.

Remarks

Call GetEditCtrl to get a reference to the edit control used by the edit view. This control is of type CEdit, so you can manipulate the Windows edit control directly using the CEdit member functions.

! WARNING Using the CEdit object can change the state of the underlying Windows edit control. For example, you should not change the tab settings using the CEdit::SetTabStops function because CEditView caches these settings for use both in the edit control and in printing. Instead, use CEditView::SetTabStops.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEdit, CEditView::SetTabStops


CEditView::GetPrinterFont

CFont* GetPrinterFont( ) const;

Return Value

A pointer to a CFont object that specifies the current printer font; NULL if the printer font has not been set. The pointer may be temporary and should not be stored for later use.

Remarks

Call GetPrinterFont to get a pointer to a CFont object that describes the current printer font. If the printer font has not been set, the default printing behavior of the CEditView class is to print using the same font used for display.

Use this function to determine the current printer font. If it is not the desired printer font, use CEditView::SetPrinterFont to change it.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::SetPrinterFont


CEditView::GetSelectedText

void GetSelectedText( CString& strResult ) const;

Parameters

strResult

A reference to the CString object that is to receive the selected text.

Remarks

Call GetSelectedText to copy the selected text into a CString object, up to the end of the selection or the character preceding the first carriage-return character in the selection.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::OnReplaceSel


CEditView::LockBuffer

LPCTSTR LockBuffer( ) const;

Return Value

A pointer to the edit control’s buffer.

Remarks

Call this member function to obtain a pointer to the buffer. The buffer should not be modified.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::UnlockBuffer, CEditView::GetBufferLength


CEditView::OnFindNext

virtual void OnFindNext( LPCTSRT lpszFind, BOOL bNext, BOOL bCase );

Parameters

lpszFind

The text to be found.

bNext

Specifies the direction of the search. If TRUE, the search direction is toward the end of the buffer. If FALSE, the search direction is toward the beginning of the buffer.

bCase

Specifies whether the search is case sensitive. If TRUE, the search is case sensitive. If FALSE, the search is not case sensitive.

Remarks

Searches the text in the buffer for the text specified by lpszFind, in the direction specified by bNext, with case sensitivity specified by bCase. The search starts at the beginning of the current selection and is accomplished through a call to FindText. In the default implementation, OnFindNext calls OnTextNotFound if the text is not found.

Override OnFindNext to change the way a CEditView-derived object searches text. CEditView calls OnFindNext when the user chooses the Find Next button in the standard Find dialog box.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::OnTextNotFound, CEditView::FindText, CEditView::OnReplaceAll, CEditView::OnReplaceSel


CEditView::OnReplaceAll

virtual void OnReplaceAll( LPCTSTR lpszFind, LPCTSTR lpszReplace, BOOL bCase );

Parameters

lpszFind

The text to be found.

lpszReplace

The text to replace the search text.

bCase

Specifies whether search is case sensitive. If TRUE, the search is case sensitive. If FALSE, the search is not case sensitive.

Remarks

CEditView calls OnReplaceAll when the user selects the Replace All button in the standard Replace dialog box. OnReplaceAll searches the text in the buffer for the text specified by lpszFind, with case sensitivity specified by bCase. The search starts at the beginning of the current selection. Each time the search text is found, this function replaces that occurrence of the text with the text specified by lpszReplace. The search is accomplished through a call to FindText. In the default implementation, OnTextNotFound is called if the text is not found.

If the current selection does not match lpszFind, the selection is updated to the first occurrence of the text specified by lpszFind and a replace is not performed. This allows the user to confirm that this is what they want to do when the selection does not match the text to be replaced.

Override OnReplaceAll to change the way a CEditView-derived object replaces text.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::OnFindNext, CEditView::OnTextNotFound, CEditView::FindText, CEditView::OnReplaceSel


CEditView::OnReplaceSel

virtual void OnReplaceSel( LPCTSTR lpszFind, BOOL bNext, BOOL bCase, LPCTSTR lpszReplace );

Parameters

lpszFind

The text to be found.

bNext

Specifies the direction of the search. If TRUE, the search direction is toward the end of the buffer. If FALSE, the search direction is toward the beginning of the buffer.

bCase

Specifies whether the search is case sensitive. If TRUE, the search is case sensitive. If FALSE, the search is not case sensitive.

lpszReplace

The text to replace the found text.

Remarks

CEditView calls OnReplaceSel when the user selects the Replace button in the standard Replace dialog box.

After replacing the selection, this function searches the text in the buffer for the next occurrence of the text specified by lpszFind, in the direction specified by bNext, with case sensitivity specified by bCase. The search is accomplished through a call to FindText. If the text is not found, OnTextNotFound is called.

Override OnReplaceSel to change the way a CEditView-derived object replaces the selected text.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::OnFindNext, CEditView::OnTextNotFound, CEditView::FindText, CEditView::OnReplaceAll


CEditView::OnTextNotFound

virtual void OnTextNotFound( LPCTSTR lpszFind );

Parameters

lpszFind

The text to be found.

Remarks

Override this function to change the default implementation, which calls the Windows function MessageBeep.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::FindText, CEditView::OnFindNext, CEditView::OnReplaceAll, CEditView::OnReplaceSel


CEditView::PrintInsideRect

UINT PrintInsideRect( CDC *pDC, RECT& rectLayout, UINT nIndexStart, UINT nIndexStop );

Return Value

The index of the next character to be printed (that is, the character following the last character rendered).

Parameters

pDC

Pointer to the printer device context.

rectLayout

Reference to a CRect object or RECT structure specifying the rectangle in which the text is to be rendered.

nIndexStart

Index within the buffer of the first character to be rendered.

nIndexStop

Index within the buffer of the character following the last character to be rendered.

Remarks

Call PrintInsideRect to print text in the rectangle specified by rectLayout.

If the CEditView control does not have the style ES_AUTOHSCROLL, text is wrapped within the rendering rectangle. If the control does have the style ES_AUTOHSCROLL, the text is clipped at the right edge of the rectangle.

The rect.bottom element of the rectLayout object is changed so that the rectangle’s dimensions define the part of the original rectangle that is occupied by the text.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::SetPrinterFont, CEditView::GetPrinterFont


CEditView::SerializeRaw

void SerializeRaw( CArchive& ar );

Parameters

ar

Reference to the CArchive object that stores the serialized text.

Remarks

Call SerializeRaw to have a CArchive object read or write the text in the CEditView object to a text file. SerializeRaw differs from CEditView’s internal implementation of Serialize in that it reads and writes only the text, without preceding object-description data.

CEditView Overview | Class Members | Hierarchy Chart

See Also CArchive, CObject::Serialize


CEditView::SetPrinterFont

void SetPrinterFont( CFont* pFont );

Parameters

pFont

A pointer to an object of type CFont. If NULL, the font used for printing is based on the display font.

Remarks

Call SetPrinterFont to set the printer font to the font specified by pFont.

If you want your view to always use a particular font for printing, include a call to SetPrinterFont in your class’s OnPreparePrinting function. This virtual function is called before printing occurs, so the font change takes place before the view’s contents are printed.

CEditView Overview | Class Members | Hierarchy Chart

See Also CWnd::SetFont, CFont, CView::OnPreparePrinting


CEditView::SetTabStops

void SetTabStops( int nTabStops );

Parameters

nTabStops

Width of each tab stop, in dialog units.

Remarks

Call this function to set the tab stops used for display and printing. Only a single tab-stop width is supported. (CEdit objects support multiple tab widths.) Widths are in dialog units, which equal one-fourth of the average character width (based on uppercase and lowercase alphabetic characters only) of the font used at the time of printing or displaying. You should not use CEdit::SetTabStops because CEditView must cache the tab-stop value.

This function modifies only the tabs of the object for which it is called. To change the tab stops for each CEditView object in your application, call each object’s SetTabStops function.

CEditView Overview | Class Members | Hierarchy Chart

See Also CWnd::SetFont, CEditView::SetPrinterFont


CEditView::UnlockBuffer

void UnlockBuffer( ) const;

Remarks

Call this member function to unlock the buffer. Call UnlockBuffer after you have finished using the pointer returned by LockBuffer.

CEditView Overview | Class Members | Hierarchy Chart

See Also CEditView::LockBuffer, CEditView::GetBufferLength


CEditView::dwStyleDefault

Remarks

Pass this static member as the dwStyle parameter of the Create function to obtain the default style for the CEditView object. dwStyleDefault is a public member of type DWORD.


CEvent

An object of class CEvent represents an “event” — a synchronization object that allows one thread to notify another that an event has occurred. Events are useful when a thread needs to know when to perform its task. For example, a thread that copies data to a data archive would need to be notified when new data is available. By using a CEvent object to notify the copy thread when new data is available, the thread can perform its task as soon as possible.

CEvent objects have two types: manual and automatic. A manual CEvent object stays in the state set by SetEvent or ResetEvent until the other function is called. An automatic CEvent object automatically returns to a nonsignaled (unavailable) state after at least one thread is released.

To use a CEvent object, construct the CEvent object when it is needed. Specify the name of the event you wish to wait on, and that your application should initially own it. You can then access the event when the constructor returns. Call SetEvent to signal (make available) the event object and then call Unlock when you are done accessing the controlled resource.

An alternative method for using CEvent objects is to add a variable of type CEvent as a data member to the class you wish to control. During construction of the controlled object, call the constructor of the CEvent data member specifying if the event is initially signaled, the type of event object you want, the name of the event (if it will be used across process boundaries), and desired security attributes.

To access a resource controlled by a CEvent object in this manner, first create a variable of either type CSingleLock or type CMultiLock in your resource’s access member function. Then call the lock object’s Lock member function (for example, CMultiLock::Lock). At this point, your thread will either gain access to the resource, wait for the resource to be released and gain access, or wait for the resource to be released and time out, failing to gain access to the resource. In any case, your resource has been accessed in a thread-safe manner. To release the resource, call SetEvent to signal the event object, and then use the lock object’s Unlock member function (for example, CMultiLock::Unlock), or allow the lock object to fall out of scope.

For more information on using CEvent objects, see the article Multithreading: How to Use the Synchronization Classes in Visual C++ Programmer's Guide.

#include <afxmt.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MTGDI


CEvent Class Members

Construction

CEvent Constructs a CEvent object.

Methods

SetEvent | Sets the event to available (signaled) and releases any waiting threads.
PulseEvent | Sets the event to available (signaled), releases waiting threads, and sets the event to unavailable (nonsignaled).
ResetEvent | Sets the event to unavailable (nonsignaled).
Unlock | Releases the event object.


CEvent::CEvent

CEvent( BOOL bInitiallyOwn = FALSE, BOOL bManualReset = FALSE, LPCTSTR lpszName = NULL, LPSECURITY_ATTRIBUTES lpsaAttribute = NULL );

Parameters

bInitiallyOwn

If TRUE, the thread for the CMultilock or CSingleLock object is enabled. Otherwise, all threads wanting to access the resource must wait.

bManualReset

If TRUE, specifies that the event object is a manual event, otherwise the event object is an automatic event.

lpszName

Name of the CEvent object. Must be supplied if the object will be used across process boundaries. If the name matches an existing event, the constructor builds a new CEvent object which references the event of that name. If the name matches an existing synchronization object that is not an event, the construction will fail. If NULL, the name will be null.

lpsaAttribute

Security attributes for the event object. For a full description of this structure, see SECURITY_ATTRIBUTES in the Win32 SDK Programmer’s Reference.

Remarks

Constructs a named or unnamed CEvent object. To access or release a CEvent object, create a CMultiLock or CSingleLock object and call its Lock and Unlock member functions.

To change the state of a CEvent object to signaled (threads do not have to wait), call SetEvent or PulseEvent. To set the state of a CEvent object to nonsignaled (threads must wait), call ResetEvent.


CEvent::PulseEvent

BOOL PulseEvent( );

Return Value

Nonzero if the function was successful; otherwise 0.

Remarks

Sets the state of the event to signaled (available), releases any waiting threads, and resets it to nonsignaled (unavailable) automatically. If the event is manual, all waiting threads are released, the event is set to nonsignaled, and PulseEvent returns. If the event is automatic, a single thread is released, the event is set to nonsignaled, and PulseEvent returns.

If no threads are waiting, or no threads can be released immediately, PulseEvent sets the state of the event to nonsignaled and returns.


CEvent::ResetEvent

BOOL ResetEvent( );

Return Value

Nonzero if the function was successful; otherwise 0.

Remarks

Sets the state of the event to nonsignaled until explicitly set to signaled by the SetEvent member function. This causes all threads wishing to access this event to wait.

This member function is not used by automatic events.


CEvent::SetEvent

BOOL SetEvent( );

Return Value

Nonzero if the function was successful, otherwise 0.

Remarks

Sets the state of the event to signaled, releasing any waiting threads. If the event is manual, the event will remain signaled until ResetEvent is called. More than one thread can be released in this case. If the event is automatic, the event will remain signaled until a single thread is released. The system will then set the state of the event to nonsignaled. If no threads are waiting, the state remains signaled until one thread is released.


CEvent::Unlock

virtual BOOL Unlock( );

Return Value

Nonzero if the thread owned the event object and the event is an automatic event; otherwise 0.

Remarks

Releases the event object. This member function is called by threads that currently own an automatic event to release it after they are done, if their lock object is to be reused. If the lock object is not to be reused, this function will be called by the lock object’s destructor.


CException

CException is the base class for all exceptions in the Microsoft Foundation Class Library. The derived classes and their descriptions are listed below:

CMemoryException | Out-of-memory exception
CNotSupportedException | Request for an unsupported operation
CArchiveException | Archive-specific exception
CFileException | File-specific exception
CResourceException | Windows resource not found or not createable
COleException | OLE exception
CDBException | Database exception (that is, exception conditions arising for MFC database classes based on Open Database Connectivity)
COleDispatchException | OLE dispatch (automation) exception
CUserException | Exception that indicates that a resource could not be found
CDaoException | Data access object exception (that is, exception conditions arising for DAO classes)
CInternetException | Internet exception (that is, exception conditions arising for Internet classes).

These exceptions are intended to be used with the THROW, THROW_LAST, TRY, CATCH, AND_CATCH, and END_CATCH macros. For more information on exceptions, see Exception Processing, or see the article Exceptions in Visual C++ Programmer's Guide.

To catch a specific exception, use the appropriate derived class. To catch all types of exceptions, use CException, and then use CObject::IsKindOf to differentiate among CException-derived classes. Note that CObject::IsKindOf works only for classes declared with the IMPLEMENT_DYNAMIC macro, in order to take advantage of dynamic type checking. Any CException-derived class that you create should use the IMPLEMENT_DYNAMIC macro, too.

You can report details about exceptions to the user by calling GetErrorMessage or ReportError, two member functions that work with any of CException’s derived classes.

If an exception is caught by one of the macros, the CException object is deleted automatically; do not delete it yourself. If an exception is caught by using a catch keyword, it is not automatically deleted. See the article Exceptions in Visual C++ Programmer's Guide for more information about when to delete an exeption object.

CException is an abstract base class. You cannot create CException objects; you must create objects of derived classes. If you need to create your own CException type, use one of the derived classes listed above as a model. Make sure that your derived class also uses IMPLEMENT_DYNAMIC.

#include <afx.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample TEAR

See Also Exception Processing


CException Class Members

Operations

CException | Constructs a CException object.
Delete | Deletes a CException object.
GetErrorMessage | Retrieves the message describing an exception.
ReportError | Reports an error message in a message box to the user.


CException::CException

CException( BOOL b_AutoDelete );

Parameters

bAutoDelete

Specify TRUE if the memory for the CException object has been allocated on the heap. This will cause the CException object to be deleted when the Delete member function is called to delete the exception. Specify FALSE if the CException object is on the stack or is a global object. In this case, the CException object will not be deleted when the Delete member function is called.

Remarks

This member function constructs a CException object. You should not directly create a CException object using new. Use this constructor when you derive a class from Cexception.


CException::Delete

void CException::Delete( );

Remarks

This function checks to see if the CException object was created on the heap, and if so, it calls the delete operator on the object. When deleting a CException object, use the Delete member function to delete the exception. Do not use the delete operator directly, because the CException object may be a global object or have been created on the stack.

You can specify whether the object should be deleted when the object is constructed. For more information, see CException::CException.

You only need to call Delete if you are using the C++ try-catch mechanism. If you are using the MFC macros TRY and CATCH, then these macros will automatically call this function.


CException::GetErrorMessage

virtual BOOL GetErrorMessage( LPTSTR lpszError, UINT nMaxError, PUINT pnHelpContext = NULL );

Return Value

Nonzero if the function is successful; otherwise 0 if no error message text is available.

Parameters

lpszError

A pointer to a buffer that will receive an error message.

nMaxError

The maximum number of characters the buffer can hold, including the NULL terminator.

pnHelpContext

The address of a UINT that will receive the help context ID. If NULL, no ID will be returned.

Remarks

Call this member function to provide text about an error that has occurred. For example, call GetErrorMessage to retrieve a string describing the error which caused MFC to throw a CFileException when writing to a CFile object.

Note GetErrorMessage will not copy more than nMaxError -1 characters to the buffer, and it will always add a trailing null to end the string. If the buffer is too small, the error message may be truncated.

Example

Here is an example of the use of CException::GetErrorMessage.

   CFile fileInput;
   CFileException ex;

   // try to open a file for reading.
   // The file will certainly not
   // exist because there are too many explicit
   // directories in the name.

   // if the call to Open() fails, ex will be
   // initialized with exception
   // information.  the call to ex.GetErrorMessage()
   // will retrieve an appropriate message describing
   // the error, and we'll add our own text
   // to make sure the user is perfectly sure what
   // went wrong.

   if (!fileInput.Open("\\Too\\Many\\Bad\\Dirs.DAT", CFile::modeRead, &ex))
   {
      TCHAR   szCause[255];
      CString strFormatted;

      ex.GetErrorMessage(szCause, 255);

      // (in real life, it's probably more
      // appropriate to read this from
      //  a string resource so it would be easy to
      // localize)

      strFormatted = _T("The data file could not be opened because of this error: ");
      strFormatted += szCause;

      AfxMessageBox(strFormatted);
   }
   else
   {
      // the file was opened, so do whatever work
      // with fileInput
      // we were planning...
      // :

      fileInput.Close();
   }

CException Overview | Class Members | Hierarchy Chart

See Also CException::ReportError


CException::ReportError

virtual int ReportError( UINT nType = MB_OK, UINT nMessageID = 0 );

Return Value

An AfxMessageBox value; otherwise 0 if there is not enough memory to display the message box. See AfxMessageBox for the possible return values.

Parameters

nType

Specifies the style of the message box. Apply any combination of the message-box styles to the box. If you don’t specify this parameter, the default is MB_OK.

nMessageID

Specifies the resource ID (string table entry) of a message to display if the exception object does not have an error message. If 0, the message “No error message is available” is displayed.

Remarks

Call this member function to report error text in a message box to the user.

Example

Here is an example of the use of CException::ReportError.

   CFile fileInput;
   CFileException ex;

   // try to open a file for reading.
   // The file will certainly not
   // exist because there are too many explicit
   // directories in the name.

   // if the call to Open() fails, ex will be
   // initialized with exception
   // information.  the call to ex.ReportError() will
   // display an appropriate
   // error message to the user, such as
   // "\Too\Many\Bad\Dirs.DAT contains an
   // invalid path."  The error message text will be
   // appropriate for the
   // file name and error condition.

   if (!fileInput.Open("\\Too\\Many\\Bad\\Dirs.DAT", CFile::modeRead, &ex))
   {
      ex.ReportError();
   }
   else
   {
      // the file was opened, so do whatever work
      // with fileInput we were planning...
      // :

      fileInput.Close();
   }

CException Overview | Class Members | Hierarchy Chart

See Also AfxMessageBox, CException::GetErrorMessage


CFieldExchange

CFieldExchange does not have a base class.

The CFieldExchange class supports the record field exchange (RFX) and bulk record field exchange (Bulk RFX) routines used by the database classes. Use this class if you are writing data exchange routines for custom data types or when you are implementing bulk row fetching; otherwise, you will not directly use this class. RFX and Bulk RFX exchanges data between the field data members of your recordset object and the corresponding fields of the current record on the data source.

Note If you are working with the Data Access Objects (DAO) classes rather than the Open Database Connectivity (ODBC) classes, use class CDaoFieldExchange instead. For more information, see the articles Database Topics (General) and DAO and MFC in Visual C++ Programmer's Guide.

A CFieldExchange object provides the context information needed for record field exchange or bulk record field exchange to take place. CFieldExchange objects support a number of operations, including binding parameters and field data members and setting various flags on the fields of the current record. RFX and Bulk RFX operations are performed on recordset-class data members of types defined by the enum FieldType in CFieldExchange. Possible FieldType values are:

  • CFieldExchange::outputColumn for field data members.

  • CFieldExchange::inputParam or CFieldExchange::param for input parameter data members.

  • CFieldExchange::outputParam for output parameter data members.

  • CFieldExchange::inoutParam for input/output parameter data members.

Most of the class’s member functions and data members are provided for writing your own custom RFX routines. You will use SetFieldType frequently. For more information, see the articles Record Field Exchange (RFX) and Recordset (ODBC) in Visual C++ Programmer's Guide. For information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer's Guide.For details about the RFX and Bulk RFX global functions, see Record Field Exchange Functions in the Macros and Globals section in this manual.

#include <afxdb.h>

Class Members | Hierarchy Chart

Sample MFC Sample CATALOG

See Also CRecordset


CFieldExchange Class Members

Operations

IsFieldType | Returns nonzero if the current operation is appropriate for the type of field being updated.
SetFieldType | Specifies the type of recordset data member — column or parameter — represented by all following calls to RFX functions until the next call to SetFieldType.


CFieldExchange::IsFieldType

BOOL IsFieldType( UINT* pnField );

Return Value

Nonzero if the current operation can be performed on the current field or parameter type.

Parameters

pnField

The sequential number of the field or parameter data member is returned in this parameter. This number corresponds to the data member’s order in the CRecordset::DoFieldExchange or CRecordset::DoBulkFieldExchange function.

Remarks

If you write your own RFX function, call IsFieldType at the beginning of your function to determine whether the current operation can be performed on a particular field or parameter data member type (a CFieldExchange::outputColumn, CFieldExchange::inputParam, CFieldExchange::param, CFieldExchange::outputParam, or CFieldExchange::inoutParam). Follow the model of the existing RFX functions.


CFieldExchange::SetFieldType

void SetFieldType( UINT nFieldType );

Parameters

nFieldType

A value of the enum FieldType, declared in CFieldExchange, which can be one of the following:

  • CFieldExchange::outputColumn

  • CFieldExchange::inputParam

  • CFieldExchange::param

  • CFieldExchange::outputParam

  • CFieldExchange::inoutParam

Remarks

You need a call to SetFieldType in your recordset class's DoFieldExchange or DoBulkFieldExchange override. For field data members, you must call SetFieldType with a parameter of CFieldExchange::outputColumn, followed by calls to the RFX or Bulk RFX functions. If you have not implemented bulk row fetching, then ClassWizard places this SetFieldType call for you in the field map section of DoFieldExchange.

If you parameterize your recordset class, you must call SetFieldType again, outside any field map section, followed by RFX calls for all the parameter data members. Each type of parameter data member must have its own SetFieldType call. The following table distinguishes the different values you can pass to SetFieldType to represent the parameter data members of your class:

SetFieldType parameter value | Type of parameter data member
CFieldExchange::inputParam | Input parameter. A value that is passed into the recordset's query or stored procedure.
CFieldExchange::param | Same as CFieldExchange::inputParam.
CFieldExchange::outputParam | Output parameter. A return value of the recordset's stored procedure.
CFieldExchange::inoutParam | Input/output parameter. A value that is passed into and returned from the recordset's stored procedure.

In general, each group of RFX function calls associated with field data members or parameter data members must be preceded by a call to SetFieldType. The nFieldType parameter of each SetFieldType call identifies the type of the data members represented by the RFX function calls that follow the SetFieldType call.

For more information about handling output and input/output parameters, see the CRecordset member function FlushResultSet. For more information about the RFX and Bulk RFX functions, see the topic Record Field Exchange Functions. For related information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer's Guide.

Example

This example shows several calls to RFX functions with accompanying calls to SetFieldType. Note that SetFieldType is called through the pFX pointer to a CFieldExchange object.

void CSections::DoFieldExchange( CFieldExchange* pFX )
{
   //{{AFX_FIELD_MAP(CSections)
   pFX->SetFieldType( CFieldExchange::outputColumn );
   RFX_Text( pFX, "CourseID", m_strCourseID );
   RFX_Text( pFX, "InstructorID", m_strInstructorID );
   RFX_Text( pFX, "RoomNo", m_strRoomNo );
   RFX_Text( pFX, "Schedule", m_strSchedule );
   //}}AFX_FIELD_MAP

   // output parameter
   pFX->SetFieldType( CFieldExchange::outputParam );
   RFX_Long( pFX, "Instructor_Count", m_nCountParam );

   // input parameter
   pFX->SetFieldType( CFieldExchange::inputParam );
   RFX_Text( pFX, "Department_Name", m_strNameParam );
}

CFieldExchange Overview | Class Members | Hierarchy Chart

See Also CRecordset::DoFieldExchange, CRecordset::DoBulkFieldExchange, CRecordset::FlushResultSet, Record Field Exchange Functions


CFile

CFile is the base class for Microsoft Foundation file classes. It directly provides unbuffered, binary disk input/output services, and it indirectly supports text files and memory files through its derived classes. CFile works in conjunction with the CArchive class to support serialization of Microsoft Foundation Class objects.

The hierarchical relationship between this class and its derived classes allows your program to operate on all file objects through the polymorphic CFile interface. A memory file, for example, behaves like a disk file.

Use CFile and its derived classes for general-purpose disk I/O. Use ofstream or other Microsoft iostream classes for formatted text sent to a disk file.

Normally, a disk file is opened automatically on CFile construction and closed on destruction. Static member functions permit you to interrogate a file’s status without opening the file.

For more information on using CFile, see the article Files in MFC in Visual C++ Programmer's Guide and File Handling in the Run-Time Library Reference.

#include <afx.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample DRAWCLI | MFC Sample CHKBOOK

See Also CStdioFile, CMemFile


CFile Class Members

Data Members

m_hFile Usually contains the operating-system file handle.

Construction

CFile | Constructs a CFile object from a path or file handle.
Abort | Closes a file ignoring all warnings and errors.
Duplicate | Constructs a duplicate object based on this file.
Open | Safely opens a file with an error-testing option.
Close | Closes a file and deletes the object.

Input/Output

Read | Reads (unbuffered) data from a file at the current file position.
ReadHuge | Can read more than 64K of (unbuffered) data from a file at the current file position. Obsolete in 32-bit programming. See Read.
Write | Writes (unbuffered) data in a file to the current file position.
WriteHuge | Can write more than 64K of (unbuffered) data in a file to the current file position. Obsolete in 32-bit programming. See Write.
Flush | Flushes any data yet to be written.

Position

Seek | Positions the current file pointer.
SeekToBegin | Positions the current file pointer at the beginning of the file.
SeekToEnd | Positions the current file pointer at the end of the file.
GetLength | Retrieves the length of the file.
SetLength | Changes the length of the file.

Locking

LockRange | Locks a range of bytes in a file.
UnlockRange | Unlocks a range of bytes in a file.

Status

GetPosition | Retrieves the current file pointer.
GetStatus | Retrieves the status of this open file.
GetFileName | Retrieves the filename of the selected file.
GetFileTitle | Retrieves the title of the selected file.
GetFilePath | Retrieves the full file path of the selected file.
SetFilePath | Sets the full file path of the selected file.

Static

Rename | Renames the specified file (static function).
Remove | Deletes the specified file (static function).
GetStatus | Retrieves the status of the specified file (static, virtual function).
SetStatus | Sets the status of the specified file (static, virtual function).


CFile::Abort

virtual void Abort( );

Remarks

Closes the file associated with this object and makes the file unavailable for reading or writing. If you have not closed the file before destroying the object, the destructor closes it for you.

When handling exceptions, CFile::Abort differs from CFile::Close in two important ways. First, the Abort function will not throw an exception on failures because failures are ignored by Abort. Second, Abort will not ASSERT if the file has not been opened or was closed previously.

If you used new to allocate the CFile object on the heap, then you must delete it after closing the file. Abort sets m_hFile to CFile::hFileNull.

Example

//example for CFile::Abort
CStdioFile fileTest;
char* pFileName = "test.dat";
TRY
{
   // do stuff that may throw exceptions
   fileTest.Open( pFileName, CFile::modeWrite );
}
CATCH_ALL( e )
{
   fileTest.Abort();   // close file safely and quietly
   THROW_LAST();
}
END_CATCH_ALL

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::Close, CFile::Open


CFile::CFile

CFile( );

CFile( int hFile );

CFile( LPCTSTR lpszFileName, UINT nOpenFlags );
throw( CFileException );

Parameters

hFile

The handle of a file that is already open.

lpszFileName

A string that is the path to the desired file. The path can be relative or absolute.

nOpenFlags

Sharing and access mode. Specifies the action to take when opening the file. You can combine options listed below by using the bitwise-OR (|) operator. One access permission and one share option are required; the modeCreate and modeNoInherit modes are optional. The values are as follows:

  • CFile::modeCreate Directs the constructor to create a new file. If the file exists already, it is truncated to 0 length.

  • CFile::modeNoTruncate Combine this value with modeCreate. If the file being created already exists, it is not truncated to 0 length. Thus the file is guaranteed to open, either as a newly created file or as an existing file. This might be useful, for example, when opening a settings file that may or may not exist already. This option applies to CStdioFile as well.

  • CFile::modeRead Opens the file for reading only.

  • CFile::modeReadWrite Opens the file for reading and writing.

  • CFile::modeWrite Opens the file for writing only.

  • CFile::modeNoInherit Prevents the file from being inherited by child processes.

  • CFile::shareDenyNone Opens the file without denying other processes read or write access to the file. Create fails if the file has been opened in compatibility mode by any other process.

  • CFile::shareDenyRead Opens the file and denies other processes read access to the file. Create fails if the file has been opened in compatibility mode or for read access by any other process.

  • CFile::shareDenyWrite Opens the file and denies other processes write access to the file. Create fails if the file has been opened in compatibility mode or for write access by any other process.

  • CFile::shareExclusive Opens the file with exclusive mode, denying other processes both read and write access to the file. Construction fails if the file has been opened in any other mode for read or write access, even by the current process.

  • CFile::shareCompat This flag is not available in 32 bit MFC. This flag maps to CFile::shareExclusive when used in CFile::Open.

  • CFile::typeText Sets text mode with special processing for carriage return–linefeed pairs (used in derived classes only).

  • CFile::typeBinary Sets binary mode (used in derived classes only).

Remarks

The default constructor does not open a file but rather sets m_hFile to CFile::hFileNull. Because this constructor does not throw an exception, it does not make sense to use TRY/CATCH logic. Use the Open member function, then test directly for exception conditions. For a discussion of exception-processing strategy, see the article Exceptions in Visual C++ Programmer's Guide.

The constructor with one argument creates a CFile object that corresponds to an existing operating-system file identified by hFile. No check is made on the access mode or file type. When the CFile object is destroyed, the operating-system file will not be closed. You must close the file yourself.

The constructor with two arguments creates a CFile object and opens the corresponding operating-system file with the given path. This constructor combines the functions of the first constructor and the Open member function. It throws an exception if there is an error while opening the file. Generally, this means that the error is unrecoverable and that the user should be alerted.

Example

//example for CFile::CFile
char* pFileName = "test.dat";
TRY
{
   CFile f( pFileName, CFile::modeCreate | CFile::modeWrite );
}
CATCH( CFileException, e )
{
   #ifdef _DEBUG
      afxDump << "File could not be opened " << e->m_cause << "\n";
   #endif
}
END_CATCH


CFile::Close

virtual void Close( );
throw( CFileException );

Remarks

Closes the file associated with this object and makes the file unavailable for reading or writing. If you have not closed the file before destroying the object, the destructor closes it for you.

If you used new to allocate the CFile object on the heap, then you must delete it after closing the file. Close sets m_hFile to CFile::hFileNull.

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::Open


CFile::Duplicate

virtual CFile* Duplicate( ) const;
throw( CFileException );

Return Value

A pointer to a duplicate CFile object.

Remarks

Constructs a duplicate CFile object for a given file. This is equivalent to the C run-time function _dup.


CFile::Flush

virtual void Flush( );
throw( CFileException );

Remarks

Forces any data remaining in the file buffer to be written to the file.

The use of Flush does not guarantee flushing of CArchive buffers. If you are using an archive, call CArchive::Flush first.


CFile::GetFileName

virtual CString GetFileName( ) const;

Return Value

The name of the file.

Remarks

Call this member function to retrieve the name of a specified file. For example, when you call GetFileName to generate a message to the user about the file c:\windows\write\myfile.wri, the filename, myfile.wri, is returned.

To return the entire path of the file, including the name, call GetFilePath. To return the title of the file (myfile), call GetFileTitle.

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::GetFilePath, CFile::GetFileTitle


CFile::GetFilePath

virtual CString GetFilePath( ) const;

Return Value

The full path of the specified file.

Remarks

Call this member function to retrieve the full path of a specified file. For example, when you call GetFilePath to generate a message to the user about the file c:\windows\write\myfile.wri, the file path, c:\windows\write\myfile.wri, is returned.

To return just the name of the file (myfile.wri), call GetFileName. To return the title of the file (myfile), call GetFileTitle.

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::SetFilePath, CFile::GetFileTitle, CFile::GetFileName


CFile::GetFileTitle

virtual CString GetFileTitle( ) const;

Return Value

The title of the specified file.

Remarks

Call this member function to retrieve the file title for a specified file. For example, when you call GetFileTitle to generate a message to the user about the file c:\windows\write\myfile.wri, the file title (myfile) is returned.

Note In Windows 95, the file title typically does not include the extention. For a explanation of this, see GetFileTitle in the Win32 documentation.

To return the entire path of the file, including the name, call GetFilePath. To return just the name of the file (myfile.wri), call GetFileName.

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::GetFileName, CFile::GetFilePath, GetFileTitle


CFile::GetLength

virtual DWORD GetLength( ) const;
throw( CFileException );

Return Value

The length of the file.

Remarks

Obtains the current logical length of the file in bytes, not the amount.

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::SetLength


CFile::GetPosition

virtual DWORD GetPosition( ) const;
throw( CFileException );

Return Value

The file pointer as a 32-bit doubleword.

Remarks

Obtains the current value of the file pointer, which can be used in subsequent calls to Seek.

Example

//example for CFile::GetPosition
extern CFile cfile;
DWORD dwPosition = cfile.GetPosition();


CFile::GetStatus

BOOL GetStatus( CFileStatus& rStatus ) const;

static BOOL PASCAL GetStatus( LPCTSTR lpszFileName, CFileStatus& rStatus );

Return Value

TRUE if the status information for the specified file is successfully obtained; otherwise, FALSE.

Parameters

rStatus

A reference to a user-supplied CFileStatus structure that will receive the status information. The CFileStatus structure has the following fields:

  • CTime m_ctime The date and time the file was created.

  • CTime m_mtime The date and time the file was last modified.

  • CTime m_atime The date and time the file was last accessed for reading.

  • LONG m_size The logical size of the file in bytes, as reported by the DIR command.

  • BYTE m_attribute The attribute byte of the file.

  • char m_szFullName[_MAX_PATH] The absolute filename in the Windows character set.

lpszFileName

A string in the Windows character set that is the path to the desired file. The path can be relative or absolute, but cannot contain a network name.

Remarks

The virtual version of GetStatus retrieves the status of the open file associated with this CFile object. It does not insert a value into the m_szFullName structure member.

The static version gets the status of the named file and copies the filename to m_szFullName. This function obtains the file status from the directory entry without actually opening the file. It is useful for testing the existence and access rights of a file.

The m_attribute is the file attribute. The Microsoft Foundation classes provide an enum type attribute so that you can specify attributes symbolically:

enum Attribute {
   normal =    0x00,
   readOnly =  0x01,
   hidden =    0x02,
   system =    0x04,
   volume =    0x08,
   directory = 0x10,
   archive =   0x20
   };

Example

//example for CFile::GetStatus
CFileStatus status;
extern CFile cfile;
if( cfile.GetStatus( status ) )    // virtual member function
   {
      #ifdef _DEBUG
         afxDump << "File size = " << status.m_size << "\n";
      #endif
   }
char* pFileName = "test.dat";
if( CFile::GetStatus( pFileName, status ) )   // static function
   {
      #ifdef _DEBUG
         afxDump << "Full file name = " << status.m_szFullName << "\n";
      #endif
   }

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::SetStatus, CTime


CFile::LockRange

virtual void LockRange( DWORD dwPos, DWORD dwCount );
throw( CFileException );

Parameters

dwPos

The byte offset of the start of the byte range to lock.

dwCount

The number of bytes in the range to lock.

Remarks

Locks a range of bytes in an open file, throwing an exception if the file is already locked. Locking bytes in a file prevents access to those bytes by other processes. You can lock more than one region of a file, but no overlapping regions are allowed.

When you unlock the region, using the UnlockRange member function, the byte range must correspond exactly to the region that was previously locked. The LockRange function does not merge adjacent regions; if two locked regions are adjacent, you must unlock each region separately.

Note This function is not available for the CMemFile-derived class.

Example

//example for CFile::LockRange
extern DWORD dwPos;
extern DWORD dwCount;
extern CFile cfile;
cfile.LockRange( dwPos, dwCount );

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::UnlockRange


CFile::Open

virtual BOOL Open( LPCTSTR lpszFileName, UINT nOpenFlags, CFileException* pError = NULL );

Return Value

Nonzero if the open was successful; otherwise 0. The pError parameter is meaningful only if 0 is returned.

Parameters

lpszFileName

A string that is the path to the desired file. The path can be relative, absolute, or a network name (UNC).

nOpenFlags

A UINT that defines the file’s sharing and access mode. It specifies the action to take when opening the file. You can combine options by using the bitwise-OR ( | ) operator. One access permission and one share option are required; the modeCreate and modeNoInherit modes are optional. See the CFile constructor for a list of mode options.

pError

A pointer to an existing file-exception object that will receive the status of a failed operation.

Remarks

Open is designed for use with the default CFile constructor. The two functions form a “safe” method for opening a file where a failure is a normal, expected condition.

While the CFile constructor will throw an exception in an error condition, Open will return FALSE for error conditions. Open can still initialize a CFileException object to describe the error, however. If you don’t supply the pError parameter, or if you pass NULL for pError, Open will return FALSE and not throw a CFileException. If you pass a pointer to an existing CFileException, and Open encounters an error, the function will fill it with information describing that error. In neither case will Open throw an exception.

The following table describes the possible results of Open.

pError | Error encountered? | Return value | CFileException content
NULL | No | TRUE | n/a
ptr to CFileException | No | TRUE | unchanged
NULL | Yes | FALSE | n/a
ptr to CFileException | Yes | FALSE | initialized to describe error

Example

//example for CFile::Open
CFile f;
CFileException e;
char* pFileName = "test.dat";
if( !f.Open( pFileName, CFile::modeCreate | CFile::modeWrite, &e ) )
   {
#ifdef _DEBUG
   afxDump << "File could not be opened " << e.m_cause << "\n";
#endif
   }

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::CFile, CFile::Close


CFile::Read

virtual UINT Read( void* lpBuf, UINT nCount );
throw( CFileException );

Return Value

The number of bytes transferred to the buffer. Note that for all CFile classes, the return value may be less than nCount if the end of file was reached.

Parameters

lpBuf

Pointer to the user-supplied buffer that is to receive the data read from the file.

nCount

The maximum number of bytes to be read from the file. For text-mode files, carriage return–linefeed pairs are counted as single characters.

Remarks

Reads data into a buffer from the file associated with the CFile object.

Example

//example for CFile::Read
extern CFile cfile;
char pbuf[100];
UINT nBytesRead = cfile.Read( pbuf, 100 );


CFile::ReadHuge

DWORD ReadHuge( void* lpBuffer, DWORD dwCount );
throw( CFileException );

Return Value

The number of bytes transferred to the buffer. Note that for all CFile objects, the return value can be less than dwCount if the end of file was reached.

Parameters

lpBuf

Pointer to the user-supplied buffer that is to receive the data read from the file.

dwCount

The maximum number of bytes to be read from the file. For text-mode files, carriage return–linefeed pairs are counted as single characters.

Remarks

Reads data into a buffer from the file associated with the CFile object.

This function differs from Read in that more than 64K–1 bytes of data can be read by ReadHuge. This function can be used by any object derived from CFile.

Note ReadHuge is provided only for backward compatibility. ReadHuge and Read have the same semantics under Win32.

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::Write, CFile::WriteHuge, CFile::Read


CFile::Remove

static void PASCAL Remove( LPCTSTR lpszFileName );
throw( CFileException );

Parameters

lpszFileName

A string that is the path to the desired file. The path can be relative or absolute but cannot contain a network name.

Remarks

This static function deletes the file specified by the path. It will not remove a directory.

The Remove member function throws an exception if the connected file is open or if the file cannot be removed. This is equivalent to the DEL command.

Example

//example for CFile::Remove
char* pFileName = "test.dat";
TRY
{
    CFile::Remove( pFileName );
}
CATCH( CFileException, e )
{
    #ifdef _DEBUG
        afxDump << "File " << pFileName << " cannot be removed\n";
    #endif
}
END_CATCH


CFile::Rename

static void PASCAL Rename( LPCTSTR lpszOldName, LPCTSTR lpszNewName );
throw( CFileException );

Parameters

lpszOldName

The old path.

lpszNewName

The new path.

Remarks

This static function renames the specified file. Directories cannot be renamed. This is equivalent to the REN command.

Example

//example for CFile::Rename
extern char* pOldName;
extern char* pNewName;
TRY
{
    CFile::Rename( pOldName, pNewName );
}
CATCH( CFileException, e )
{
    #ifdef _DEBUG
        afxDump << "File " << pOldName << " not found, cause = "
            << e->m_cause << "\n";
    #endif
}
END_CATCH


CFile::Seek

virtual LONG Seek( LONG lOff, UINT nFrom );
throw( CFileException );

Return Value

If the requested position is legal, Seek returns the new byte offset from the beginning of the file. Otherwise, the return value is undefined and a CFileException object is thrown.

Parameters

lOff

Number of bytes to move the pointer.

nFrom

Pointer movement mode. Must be one of the following values:

  • CFile::begin Move the file pointer lOff bytes forward from the beginning of the file.

  • CFile::current Move the file pointer lOff bytes from the current position in the file.

  • CFile::end Move the file pointer lOff bytes from the end of the file. Note that lOff must be negative to seek into the existing file; positive values will seek past the end of the file.

Remarks

Repositions the pointer in a previously opened file. The Seek function permits random access to a file’s contents by moving the pointer a specified amount, absolutely or relatively. No data is actually read during the seek.

When a file is opened, the file pointer is positioned at offset 0, the beginning of the file.

Example

//example for CFile::Seek
extern CFile cfile;
LONG lOffset = 1000, lActual;
lActual = cfile.Seek( lOffset, CFile::begin );


CFile::SeekToBegin

void SeekToBegin( );
throw( CFileException );

Remarks

Sets the value of the file pointer to the beginning of the file. SeekToBegin() is equivalent to Seek( 0L, CFile::begin ).

Example

//example for CFile::SeekToBegin
extern CFile cfile;
cfile.SeekToBegin();


CFile::SeekToEnd

DWORD SeekToEnd( );
throw( CFileException );

Return Value

The length of the file in bytes.

Remarks

Sets the value of the file pointer to the logical end of the file. SeekToEnd() is equivalent to CFile::Seek( 0L, CFile::end ).

Example

//example for CFile::SeekToEnd
extern CFile cfile;
DWORD dwActual = cfile.SeekToEnd();

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::GetLength, CFile::Seek, CFile::SeekToBegin


CFile::SetFilePath

virtual void SetFilePath( LPCTSTR lpszNewName );

Parameters

lpszNewName

Pointer to a string specifying the new path.

Remarks

Call this function to specify the path of the file; for example, if the path of a file is not available when a CFile object is constructed, call SetFilePath to provide it.

Note SetFilePath does not open the file or create the file; it simply associates the CFile object with a path name, which can then be used.

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::GetFilePath, CFile::CFile


CFile::SetLength

virtual void SetLength( DWORD dwNewLen );
throw( CFileException );

Parameters

dwNewLen

Desired length of the file in bytes. This value can be larger or smaller than the current length of the file. The file will be extended or truncated as appropriate.

Remarks

Call this function to change the length of the file.

Note With CMemFile, this function could throw a CMemoryException object.

Example

//example for CFile::SetLength
extern CFile cfile;
DWORD dwNewLength = 10000;
cfile.SetLength( dwNewLength );


CFile::SetStatus

static void SetStatus( LPCTSTR lpszFileName, const CFileStatus& status );
throw( CFileException );

Parameters

lpszFileName

A string that is the path to the desired file. The path can be relative or absolute but cannot contain a network name.

status

The buffer containing the new status information. Call the GetStatus member function to prefill the CFileStatus structure with current values, then make changes as required. If a value is 0, then the corresponding status item is not updated. See the GetStatus member function for a description of the CFileStatus structure.

Remarks

Sets the status of the file associated with this file location.

To set the time, modify the m_mtime field of status.

Please note that when you make a call to SetStatus in an attempt to change only the attributes of the file, and the m_mtime member of the file status structure is nonzero, the attributes may also be affected (changing the time stamp may have side effects on the attributes). If you want to only change the attributes of the file, first set the m_mtime member of the file status structure to zero and then make a call to SetStatus.

Example

//example for CFile::SetStatus
char* pFileName = "test.dat";
extern BYTE newAttribute;
CFileStatus status;
CFile::GetStatus( pFileName, status );
status.m_attribute = newAttribute;
CFile::SetStatus( pFileName, status );

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::GetStatus


CFile::UnlockRange

virtual void UnlockRange( DWORD dwPos, DWORD dwCount );
throw( CFileException );

Parameters

dwPos

The byte offset of the start of the byte range to unlock.

dwCount

The number of bytes in the range to unlock.

Remarks

Unlocks a range of bytes in an open file. See the description of the LockRange member function for details.

Note This function is not available for the CMemFile-derived class.

Example

//example for CFile::UnlockRange
extern DWORD dwPos;
extern DWORD dwCount;
extern CFile cfile;
cfile.UnlockRange( dwPos, dwCount );

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::LockRange


CFile::Write

virtual void Write( const void* lpBuf, UINT nCount );
throw( CFileException );

Parameters

lpBuf

A pointer to the user-supplied buffer that contains the data to be written to the file.

nCount

The number of bytes to be transferred from the buffer. For text-mode files, carriage return–linefeed pairs are counted as single characters.

Remarks

Writes data from a buffer to the file associated with the CFile object.

Write throws an exception in response to several conditions, including the disk-full condition.

Example

//example for CFile::Write
extern CFile cfile;
char pbuf[100];
cfile.Write( pbuf, 100 );

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::Read, CStdioFile::WriteString


CFile::WriteHuge

void WriteHuge( const void* lpBuf, DWORD dwCount );
throw( CFileException );

Parameters

lpBuf

A pointer to the user-supplied buffer that contains the data to be written to the file.

dwCount

The number of bytes to be transferred from the buffer. For text-mode files, carriage return–linefeed pairs are counted as single characters.

Remarks

Writes data from a buffer to the file associated with the CFile object. WriteHuge throws an exception in response to several conditions, including the disk-full condition.

This function differs from Write in that more than 64K–1 bytes of data can be written by WriteHuge. This function can be used by any object derived from CFile.

Note WriteHuge is provided only for backward compatibility. WriteHuge and Write have the same semantics under Win32.

CFile Overview | Class Members | Hierarchy Chart

See Also CFile::Read, CFile::ReadHuge, CFile::Write, CStdioFile::WriteString


CFile::m_hFile

Remarks

Contains the operating-system file handle for an open file. m_hFile is a public variable of type UINT. It contains CFile::hFileNull (an operating-system-independent empty file indicator) if the handle has not been assigned.

Use of m_hFile is not recommended because the member’s meaning depends on the derived class. m_hFile is made a public member for convenience in supporting nonpolymorphic use of the class.


CFileDialog

The CFileDialog class encapsulates the Windows common file dialog box. Common file dialog boxes provide an easy way to implement File Open and File Save As dialog boxes (as well as other file-selection dialog boxes) in a manner consistent with Windows standards.

You can use CFileDialog “as is” with the constructor provided, or you can derive your own dialog class from CFileDialog and write a constructor to suit your needs. In either case, these dialog boxes will behave like standard Microsoft Foundation class dialog boxes because they are derived from the CCommonDialog class.

To use a CFileDialog object, first create the object using the CFileDialog constructor. After the dialog box has been constructed, you can set or modify any values in the m_ofn structure to initialize the values or states of the dialog box’s controls. The m_ofn structure is of type OPENFILENAME. For more information, see the OPENFILENAME structure in the Win32 SDK documentation.

After initializing the dialog box’s controls, call the DoModal member function to display the dialog box and allow the user to enter the path and file. DoModal returns whether the user selected the OK (IDOK) or the Cancel (IDCANCEL) button.

If DoModal returns IDOK, you can use one of CFileDialog’s public member functions to retrieve the information input by the user.

CFileDialog includes several protected members that enable you to do custom handling of share violations, filename validation, and list-box change notification. These protected members are callback functions that most applications do not need to use, since default handling is done automatically. Message-map entries for these functions are not necessary because they are standard virtual functions.

You can use the Windows CommDlgExtendedError function to determine whether an error occurred during initialization of the dialog box and to learn more about the error.

The destruction of CFileDialog objects is handled automatically. It is not necessary to call CDialog::EndDialog.

To allow the user to select multiple files, set the OFN_ALLOWMULTISELECT flag before calling DoModal. You need to supply your own filename buffer to accommodate the returned list of multiple filenames. Do this by replacing m_ofn.lpstrFile with a pointer to a buffer you have allocated, after constructing the CFileDialog, but before calling DoModal. Additionally, you must set m_ofn.nMaxFile with the number of characters in the buffer pointed to by m_ofn.lpstrFile.

CFileDialog relies on the COMMDLG.DLL file that ships with Windows versions 3.1 and later.

If you derive a new class from CFileDialog, you can use a message map to handle any messages. To extend the default message handling, derive a class from CWnd, add a message map to the new class, and provide member functions for the new messages. You do not need to provide a hook function to customize the dialog box.

To customize the dialog box, derive a class from CFileDialog, provide a custom dialog template, and add a message map to process the notification messages from the extended controls. Any unprocessed messages should be passed to the base class.

Customizing the hook function is not required.

For more information on using CFileDialog, see Common Dialog Classes in Visual C++ Programmer's Guide.

#include <afxdlgs.h>


CFileDialog Class Members

Data Members

m_ofn The Windows OPENFILENAME structure. Provides access to basic file dialog box parameters.

Construction

CFileDialog Constructs a CFileDialog object.

Operations

DoModal | Displays the dialog box and allows the user to make a selection.
GetPathName | Returns the full path of the selected file.
GetFileName | Returns the filename of the selected file.
GetFileExt | Returns the file extension of the selected file.
GetFileTitle | Returns the title of the selected file.
GetNextPathName | Returns the full path of the next selected file.
GetReadOnlyPref | Returns the read-only status of the selected file.
GetStartPosition | Returns the position of the first element of the filename list.

Overridables

OnShareViolation | Called when a share violation occurs.
OnFileNameOK | Called to validate the filename entered in the dialog box.
OnLBSelChangedNotify | Called when the list box selection changes.
OnInitDone | Called to handle the WM_NOTIFY CDN_INITDONE message.
OnFileNameChange | Called to handle the WM_NOTIFY CDN_SELCHANGE message.
OnFolderChange | Called to handle the WM_NOTIFY CDN_FOLDERCHANGE message.
OnTypeChange | Called to handle the WM_NOTIFY CDN_TYPECHANGE message.


CFileDialog::CFileDialog

CFileDialog( BOOL bOpenFileDialog, LPCTSTR lpszDefExt = NULL, LPCTSTR lpszFileName = NULL, DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, LPCTSTR lpszFilter = NULL, CWnd* pParentWnd = NULL );

Parameters

bOpenFileDialog

Set to TRUE to construct a File Open dialog box or FALSE to construct a File Save As dialog box.

lpszDefExt

The default filename extension. If the user does not include an extension in the Filename edit box, the extension specified by lpszDefExt is automatically appended to the filename. If this parameter is NULL, no file extension is appended.

lpszFileName

The initial filename that appears in the filename edit box. If NULL, no filename initially appears.

dwFlags

A combination of one or more flags that allow you to customize the dialog box. For a description of these flags, see the OPENFILENAME structure in the Win32 SDK documentation. If you modify the m_ofn.Flags structure member, use a bitwise-OR operator in your changes to keep the default behavior intact.

lpszFilter

A series of string pairs that specify filters you can apply to the file. If you specify file filters, only selected files will appear in the Files list box. See the Remarks section for more information on how to work with file filters.

pParentWnd

A pointer to the file dialog-box object’s parent or owner window.

Remarks

Call this function to construct a standard Windows file dialog box-object. Either a File Open or File Save As dialog box is constructed, depending on the value of bOpenFileDialog.

To allow the user to select multiple files, set the OFN_ALLOWMULTISELECT flag before calling DoModal. You need to supply your own filename buffer to accommodate the returned list of multiple filenames. Do this by replacing m_ofn.lpstrFile with a pointer to a buffer you have allocated, after constructing the CFileDialog, but before calling DoModal. Additionally, you must set m_ofn.nMaxFile with the number of characters in the buffer pointed to by m_ofn.lpstrFile.

To allow the user to resize an Explorer-style dialog box using either the mouse or keyboard, set the OFN_ENABLESIZING flag. Setting this flag is necessary only if you provide a hook procedure or custom template. The flag works only with an Explorer-style dialog box; old-style dialog boxes do not permit resizing.

The lpszFilter parameter is used to determine the type of filename a file must have to be displayed in the file list box. The first string in the string pair describes the filter; the second string indicates the file extension to use. Multiple extensions may be specified using ‘;’ as the delimiter. The string ends with two ‘|’ characters, followed by a NULL character. You can also use a CString object for this parameter.

For example, Microsoft Excel permits users to open files with extensions .XLC (chart) or .XLS (worksheet), among others. The filter for Excel could be written as:

static char BASED_CODE szFilter[] = "Chart Files (*.xlc)|*.xlc|Worksheet Files (*.xls)|*.xls|Data Files (*.xlc;*.xls)|*.xlc; *.xls|All Files (*.*)|*.*||";

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::DoModal, ::GetOpenFileName, ::GetSaveFileName, OPENFILENAME


CFileDialog::DoModal

virtual int DoModal( );

Return Value

IDOK or IDCANCEL. If IDCANCEL is returned, call the Windows CommDlgExtendedError function to determine whether an error occurred.

IDOK and IDCANCEL are constants that indicate whether the user selected the OK or Cancel button.

Remarks

Call this function to display the Windows common file dialog box and allow the user to browse files and directories and enter a filename.

If you want to initialize the various file dialog-box options by setting members of the m_ofn structure, you should do this before calling DoModal, but after the dialog object is constructed.

When the user clicks the dialog box’s OK or Cancel buttons, or selects the Close option from the dialog box’s control menu, control is returned to your application. You can then call other member functions to retrieve the settings or information the user inputs into the dialog box.

DoModal is a virtual function overridden from class Cdialog.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::DoModal, CFileDialog::CFileDialog


CFileDialog::GetFileExt

CString GetFileExt( ) const;

Return Value

The extension of the filename.

Remarks

Call this function to retrieve the extension of the filename entered into the dialog box. For example, if the name of the file entered is DATA.TXT, GetFileExt returns "TXT".

If m_ofn.Flags has the OFN_ALLOWMULTISELECT flag set, this string contains a sequence of null-terminated strings, with the first string being the directory path of the file group selected, followed by the names of all files selected by the user. To retrieve file pathnames, use the GetStartPosition and GetNextPathName member functions.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::GetPathName, CFileDialog::GetFileName, CFileDialog::GetFileTitle


CFileDialog::GetFileName

CString GetFileName( ) const;

Return Value

The name of the file.

Remarks

Call this function to retrieve the name of the filename entered in the dialog box. The name of the file includes both the prefix and the extension. For example, GetFileName will return "TEXT.DAT" for the file C:\FILES\TEXT.DAT.

If m_ofn.Flags has the OFN_ALLOWMULTISELECT flag set, you should call GetStartPosition and GetNextPathName to retrieve a file pathname.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::GetPathName, CFileDialog::GetStartPosition, CFileDialog::GetFileTitle


CFileDialog::GetFileTitle

CString GetFileTitle( ) const;

Return Value

The title of the file.

Remarks

Call this function to retrieve the title of the file entered in the dialog box. The title of the file includes only its prefix, without the path or the extension. For example, GetFileTitle will return "TEXT" for the file C:\FILES\TEXT.DAT.

If m_ofn.Flags has the OFN_ALLOWMULTISELECT flag set, this string contains a sequence of null-teminated strings, with the first string being the directory path of the file group selected, followed by the names of all files selected by the user. For this reason, use the GetStartPosition and GetNextPathName member functions to retrieve the next file name in the list.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::GetPathName, CFileDialog::GetFileName, CFileDialog::GetFileExt, ::GetFileTitle


CFileDialog::GetNextPathName

CString GetNextPathName( POSITION& pos ) const;

Parameters

pos

A reference to a POSITION value returned by a previous GetNextPathName or GetStartPosition function call. NULL if the end of the list has been reached.

Return Value

The full path of the file.

Remarks

Call this function to retrieve the next filename from the group selected in the dialog box. The path of the filename includes the file’s title plus the entire directory path. For example, GetNextPathName will return "C:\FILES\TEXT.DAT" for the file C:\FILES\TEXT.DAT. You can use GetNextPathName in a forward iteration loop if you establish the initial position with a call to GetStartPosition.

If the selection consists of only one file, that file name will be returned.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::GetFileName, CFileDialog::GetStartPosition


CFileDialog::GetPathName

CString GetPathName( ) const;

Return Value

The full path of the file.

Remarks

Call this function to retrieve the full path of the file entered in the dialog box. The path of the filename includes the file’s title plus the entire directory path. For example, GetPathName will return "C:\FILES\TEXT.DAT" for the file C:\FILES\TEXT.DAT.

If m_ofn.Flags has the OFN_ALLOWMULTISELECT flag set, this string contains a sequence of null-teminated strings, with the first string being the directory path of the file group selected, followed by the names of all files selected by the user. For this reason, use the GetStartPosition and GetNextPathName member functions to retrieve the next file name in the list.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::GetFileName, CFileDialog::GetFileExt, CFileDialog::GetFileTitle


CFileDialog::GetReadOnlyPref

BOOL GetReadOnlyPref( ) const;

Return Value

Non-zero if the Read Only check box in the dialog box is selected; otherwise 0.

Remarks

Call this function to determine whether the Read Only check box has been selected in the Windows standard File Open and File Save As dialog boxes. The Read Only check box can be hidden by setting the OFN_HIDEREADONLY style in the CFileDialog constructor.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::CFileDialog, CFileDialog::GetPathName, CFileDialog::GetFileExt


CFileDialog::GetStartPosition

POSITION GetStartPosition( ) const;

Return Value

A POSITION value that can be used for iteration; NULL if the list is empty.

Remarks

Call this member function to retrieve the position of the first file pathname in the list, if m_ofn.Flags has the OFN_ALLOWMULTISELECT flag set.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::GetFileName, CFileDialog::GetNextPathName


CFileDialog::OnFileNameChange

virtual void OnFileNameChange( );

Remarks

Override this function to handle the WM_NOTIFY CDN_SELCHANGE message. The notification message is sent when the user selects a new file or folder in the file list of the Open or Save As dialog box.

Notification is sent only if the dialog box was created with the OFN_EXPLORER style. For more information about the notification, see CDN_SELCHANGE. For information about the OFN_EXPLORER style, see the OPENFILENAME structure and Open and Save As Dialog Boxes.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::OnFolderChange


CFileDialog::OnFileNameOK

virtual BOOL OnFileNameOK( );

Return Value

1 if the filename is not a valid filename; otherwise 0.

Remarks

Override this function only if you want to provide custom validation of filenames that are entered into a common file dialog box. This function allows you to reject a filename for any application-specific reason. Normally, you do not need to use this function because the framework provides default validation of filenames and displays a message box if an invalid filename is entered.

If 1 is returned, the dialog box will remain displayed for the user to enter another filename. The dialog procedure dismisses the dialog if the return is 0. Other nonzero return values are currently reserved and should not be used.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also OPENFILENAME


CFileDialog::OnFolderChange

virtual void OnFolderChange( );

Remarks

Override this function to handle the WM_NOTIFY CDN_FOLDERCHANGE message. The notification message is sent when a new folder is opened in the Open or Save As dialog box.

Notification is sent only if the dialog box was created with the OFN_EXPLORER style. For more information about the notification, see CDN_FOLDERCHANGE. For information about the OFN_EXPLORER style, see the OPENFILENAME structure and Open and Save As Dialog Boxes.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::OnFileChange


CFileDialog::OnInitDone

virtual void OnInitDone( );

Remarks

Override this function to handle the WM_NOTIFY CDN_INITDONE message. The notification message is sent when the system has finished arranging controls in the Open or Save As dialog box to make room for the controls of the child dialog box.

Notification is sent only if the dialog box was created with the OFN_EXPLORER style. For more information about the notification, see CDN_INITDONE. For information about the OFN_EXPLORER style, see the OPENFILENAME structure and Open and Save As Dialog Boxes.


CFileDialog::OnLBSelChangedNotify

virtual void OnLBSelChangedNotify( UINT nIDBox, UINT iCurSel, UINT nCode);

Parameters

nIDBox

The ID of the list box or combo box in which the selection occurred.

iCurSel

The index of the current selection.

nCode

The control notification code. This parameter must have one of the following values:

  • CD_LBSELCHANGE Specifies iCurSel is the selected item in a single-selection list box.

  • CD_LBSELSUB Specifies that iCurSel is no longer selected in a multiselection list box.

  • CD_LBSELADD Specifies that iCurSel is selected in a multiselection list box.

  • CD_LBSELNOITEMS Specifies that no selection exists in a multiselection list box.

For more information, see About Common Dialog Boxes in the Win32 SDK documentation.

Remarks

This function is called whenever the current selection in a list box is about to change. Override this function to provide custom handling of selection changes in the list box. For example, you can use this function to display the access rights or date-last-modified of each file the user selects.


CFileDialog::OnShareViolation

virtual UINT OnShareViolation( LPCTSTR lpszPathName );

Return Value

One of the following values:

  • OFN_SHAREFALLTHROUGH The filename is returned from the dialog box.

  • OFN_SHARENOWARN No further action needs to be taken.

  • OFN_SHAREWARN The user receives the standard warning message for this error.

Parameters

lpszPathName

The path of the file on which the share violation occurred.

Remarks

Override this function to provide custom handling of share violations. Normally, you do not need to use this function because the framework provides default checking of share violations and displays a message box if a share violation occurs.

If you want to disable share violation checking, use the bitwise OR operator to combine the flag OFN_SHAREAWARE with m_ofn.Flags.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::OnFileNameOK


CFileDialog::OnTypeChange

virtual void OnInitDone( );

Remarks

Override this function to handle the WM_NOTIFY CDN_TYPECHANGE message. The notification message is sent when the user selects a new file type from the list of file types in the Open or Save As dialog box.

Notification is sent only if the dialog box was created with the OFN_EXPLORER style. For more information about the notification, see CDN_TYPECHANGE. For information about the OFN_EXPLORER style, see the OPENFILENAME structure and Open and Save As Dialog Boxes.

CFileDialog Overview | Class Members | Hierarchy Chart

See Also CFileDialog::OnFileChange


CFileDialog::m_ofn

Remarks

m_ofn is a structure of type OPENFILENAME. Use this structure to initialize the appearance of a File Open or File Save As dialog box after it is constructed but before it is displayed with the DoModal member function. For example, you can set the lpstrTitle member of m_ofn to the caption you want the dialog box to have.

For more information, see the OPENFILENAME structure in the Win32 SDK documentation.


CFileException

A CFileException object represents a file-related exception condition. The CFileException class includes public data members that hold the portable cause code and the operating-system-specific error number. The class also provides static member functions for throwing file exceptions and for returning cause codes for both operating-system errors and C run-time errors.

CFileException objects are constructed and thrown in CFile member functions and in member functions of derived classes. You can access these objects within the scope of a CATCH expression. For portability, use only the cause code to get the reason for an exception. For more information about exceptions, see the article Exceptions in Visual C++ Programmer's Guide.

#include <afx.h>

Class Members | Base Class | Hierarchy Chart

See Also Exception Processing


CFileException Class Members

Data Members

m_cause | Contains portable code corresponding to the exception cause.
m_lOsError | Contains the related operating-system error number.
m_strFileName | Contains the name of the file for this exception.

Construction

CFileException Constructs a CFileException object.

Code Conversion

OsErrorToException | Returns a cause code corresponding to an operating system error code.
ErrnoToException | Returns cause code corresponding to a run-time error number.

Helper Functions

ThrowOsError | Throws a file exception based on an operating-system error number.
ThrowErrno | Throws a file exception based on a run-time error number.


CFileException::CFileException

CFileException( int cause = CFileException::none, LONG lOsError = -1 );

Parameters

cause

An enumerated type variable that indicates the reason for the exception. See CFileException::m_cause for a list of the possible values.

lOsError

An operating-system-specific reason for the exception, if available. The lOsError parameter provides more information than cause does.

Remarks

Constructs a CFileException object that stores the cause code and the operating-system code in the object.

Do not use this constructor directly, but rather call the global function AfxThrowFileException.

Note The variable lOsError applies only to CFile and CStdioFile objects. The CMemFile class does not handle this error code.

CFileException Overview | Class Members | Hierarchy Chart

See Also AfxThrowFileException


CFileException::ErrnoToException

static int PASCAL ErrnoToException( int nErrno );

Return Value

Enumerated value that corresponds to a given run-time library error value.

Parameters

nErrno

An integer error code as defined in the run-time include file ERRNO.H.

Remarks

Converts a given run-time library error value to a CFileException enumerated error value. See CFileException::m_cause for a list of the possible enumerated values.

Example

//example for CFileException::ErrnoToException
#include <errno.h>
ASSERT( CFileException::ErrnoToException( EACCES ) ==
                  CFileException::accessDenied );

CFileException Overview | Class Members | Hierarchy Chart

See Also CFileException::OsErrorToException


CFileException::OsErrorToException

static int PASCAL OsErrorToException( LONG lOsError );

Return Value

Enumerated value that corresponds to a given operating-system error value.

Parameters

lOsError

An operating-system-specific error code.

Remarks

Returns an enumerator that corresponds to a given lOsError value. If the error code is unknown, then the function returns CFileException::generic.

Example

//example for CFileException::OsErrorToException
ASSERT( CFileException::OsErrorToException( 5 ) ==
                  CFileException::accessDenied );

CFileException Overview | Class Members | Hierarchy Chart

See Also CFileException::ErrnoToException


CFileException::ThrowErrno

static void PASCAL ThrowErrno( int nErrno );

Parameters

nErrno

An integer error code as defined in the run-time include file ERRNO.H.

Remarks

Constructs a CFileException object corresponding to a given nErrno value, then throws the exception.

Example

//example for CFileException::ThrowErrno
#include <errno.h>
CFileException::ThrowErrno( EACCES );  // "access denied"

CFileException Overview | Class Members | Hierarchy Chart

See Also CFileException::ThrowOsError


CFileException::ThrowOsError

static void PASCAL ThrowOsError( LONG lOsError, LPCTSTR lpszFileName = NULL );

Parameters

lOsError

An operating-system-specific error code.

lpszFileName

A pointer to the string containing the name of the file that caused the exception, if available.

Remarks

Throws a CFileException corresponding to a given lOsError value. If the error code is unknown, then the function throws an exception coded as CFileException::generic.

Example

//example for CFileException::ThrowOsError
CFileException::ThrowOsError( 5 );  // "access denied"

CFileException Overview | Class Members | Hierarchy Chart

See Also CFileException::ThrowErrno


CFileException::m_cause

Remarks

Contains values defined by a CFileException enumerated type. This data member is a public variable of type int. The enumerators and their meanings are as follows:

  • CFileException::none No error occurred.

  • CFileException::generic An unspecified error occurred.

  • CFileException::fileNotFound The file could not be located.

  • CFileException::badPath All or part of the path is invalid.

  • CFileException::tooManyOpenFiles The permitted number of open files was exceeded.

  • CFileException::accessDenied The file could not be accessed.

  • CFileException::invalidFile There was an attempt to use an invalid file handle.

  • CFileException::removeCurrentDir The current working directory cannot be removed.

  • CFileException::directoryFull There are no more directory entries.

  • CFileException::badSeek There was an error trying to set the file pointer.

  • CFileException::hardIO There was a hardware error.

  • CFileException::sharingViolation SHARE.EXE was not loaded, or a shared region was locked.

  • CFileException::lockViolation There was an attempt to lock a region that was already locked.

  • CFileException::diskFull The disk is full.

  • CFileException::endOfFile The end of file was reached.

Note These CFileException cause enumerators are distinct from the CArchiveException cause enumerators.

Example

//example for CFileException::m_cause
extern char* pFileName;
TRY
{
   CFile f( pFileName, CFile::modeCreate | CFile::modeWrite );
}
CATCH( CFileException, e )
{
    if( e->m_cause == CFileException::fileNotFound )
        printf( "ERROR: File not found\n");
}
END_CATCH


CFileException::m_lOsError

Remarks

Contains the operating-system error code for this exception. See your operating-system technical manual for a listing of error codes. This data member is a public variable of type LONG.


CFileException::m_strFileName

CString m_strFileName;

Remarks

Contains the name of the file for this exception condition.


CFileFind

The MFC class CFileFind performs local file searches and is the base class for CGopherFileFind and CFtpFileFind, which perform Internet file searches. CFileFind includes member functions that begin a search, locate a file, and return the title, name, or path of the file. For Internet searches, the member function GetFileURL returns the file’s URL.

CFileFind is the base class for two other MFC classes designed to search particular server types: CGopherFileFind works specifically with gopher servers, and CFtpFileFind works specifically with FTP servers. Together, these three classes provide a seamless mechanism for the client to find files, regardless of the server protocol, the file type, or location, on either a local machine or a remote server.

The following code will enumerate all the files in the current directory, printing the name of each file:

   CFileFind finder;
   BOOL bWorking = finder.FindFile("*.*");
   while (bWorking)
   {
      bWorking = finder.FindNextFile();
      cout << (LPCTSTR) finder.GetFileName() << endl;
   }

To keep the example simple, this code uses the standard C++ library cout class. The cout line could be replaced with a call to CListBox::AddString, for example, in a program with a graphical user interface.

For more information about how to use CFileFind and the other WinInet classes, see the article Internet Programming with WinInet in Visual C++ Programmer's Guide.

#include <afx.h>

Class Members | Base Class | Hierarchy Chart

See Also CFtpFileFind, CGopherFileFind, CInternetFile, CGopherFile, CHttpFile


CFileFind Class Members

Construction

CFileFind Constructs a CFileFind object.

Attributes

GetLength | Gets the length of the found file, in bytes.
GetFileName | Gets the name, including the extension, of the found file
GetFilePath | Gets the whole path of the found file.
GetFileTitle | Gets the title of the found file. The title does not include the extension.
GetFileURL | Gets the URL, including the file path, of the found file.
GetRoot | Gets the root directory of the found file.
GetCreationTime | Gets the time the file was created.
GetLastAccessTime | Gets the time that the file was last accessed.
GetLastWriteTime | Gets the time the file was last changed and saved.
MatchesMask | Indicates the desired file attributes of the file to be found.
IsDots | Determines if the name of the found file has the name "." or "..", indicating that is actually a directory.
IsReadOnly | Determines if the found file is read-only.
IsDirectory | Determines if the found file is a directory.
IsCompressed | Determines if the found file is compressed.
IsSystem | Determines if the found file is a system file.
IsHidden | Determines if the found file is hidden.
IsTemporary | Determines if the found file is temporary.
IsNormal | Determines if the found file is normal (in other words, has no other attributes).
IsArchived | Determines if the found file is archived.

Operations

Close | Closes the search request.
FindFile | Searches a directory for a specified file name.
FindNextFile | Continues a file search from a previous call to FindFile.


CFileFind::CFileFind

CFileFind( );

Remarks

This member function is called when a CFileFind object is constructed.

CFileFind Overview | Class Members | Hierarchy Chart

See Also CGopherFileFind, CFtpFileFind


CFileFind::Close

void Close( );

Remarks

Call this member function to end the search, reset the context, and release all resources. After calling Close, you do not have to create a new CFileFind instance before calling FindFile to begin a new search.


CFileFind::FindFile

virtual BOOL FindFile( LPCTSTR pstrName = NULL, DWORD dwUnused = 0 );

Return Value

Nonzero if successful; otherwise 0. To get extended error information, call the Win32 function GetLastError.

Parameters

pstrName

A pointer to a string containing the name of the file to find. If you pass NULL for pstrName, FindFile does a wildcard (*.*) search.

dwUnused

Reserved to make FindFile polymorphic with derived classes. Must be 0.

Remarks

Call this member function to open a file search.

After calling FindFile to begin the file search, call FindNextFile to retrieve subsequent files. You must call FindNextFile at least once before calling any of the following attribute member functions:

  • GetCreationTime

  • GetFileName

  • GetFileTitle

  • GetFilePath

  • GetFileURL

  • GetLastAccessTime

  • GetLastWriteTime

  • GetLength

  • GetRoot

CFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::FindNextFile


CFileFind::FindNextFile

virtual BOOL FindNextFile( );

Return Value

Nonzero if there are more files; zero if this is the last file, and the previous call to either FindFile or FindNextFile returned nonzero. To get extended error information, call the Win32 function GetLastError.

Remarks

Call this member function to continue a file search from a previous call to FindFile. You must call FindNextFile at least once before calling any of the following attribute member functions:

  • GetCreationTime

  • GetFileName

  • GetFileTitle

  • GetFilePath

  • GetFileURL

  • GetLastAccessTime

  • GetLastWriteTime

  • GetLength

  • GetRoot

FindNextFile wraps the Win32 function FindNextFile.


CFileFind::GetCreationTime

virtual BOOL GetCreationTime( FILETIME* pFileTime ) const;

virtual BOOL GetCreationTime( CTime& refTime ) const;

Return Value

Nonzero if successful; 0 if unsuccessful. GetCreationTime returns 0 only if FindNextFile has never been called on this CFileFind object.

Parameters

pFileTime

A pointer to a FILETIME structure containing the time the file was created.

refTime

A reference to a CTime object.

Remarks

Call this member function to get the time the specified file was created.

You must call FindNextFile at least once before calling GetCreationTime.

Note Not all file systems use the same semantics to implement the time stamp returned by this function. This function may return the same value returned by other time stamp functions if the underlying file system or server does not support keeping the time attribute. See the Win32_FIND_DATA structure for information about time formats. On some operation systems, the returned time is in the time zone local to the machine were the file is located. See the Win32 FileTimeToLocalFileTime API for more information.


CFileFind::GetFileName

virtual CString GetFileName( ) const;

Return Value

The name of the most-recently-found file.

Remarks

Call this member function to get the name of the found file. You must call FindNextFile at least once before calling GetFileName.

GetFileName is one of three CFileFind member functions that return some form of the file name. The following list describes the three and how they vary:

  • GetFileName returns the file name, including the extension. For example, calling GetFileName to generate a user message about the file c:\myhtml\myfile.txt returns the file name myfile.txt.

  • GetFilePath returns the entire path for the file. For example, calling GetFilePath to generate a user message about the file c:\myhtml\myfile.txt returns the file path c:\myhtml\myfile.txt.

  • GetFileTitle returns the file name, excluding the file extension. For example, calling GetFileTitle to generate a user message about the file c:\myhtml\myfile.txt returns the file title myfile.

CFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::FindFile


CFileFind::GetFilePath

virtual CString GetFilePath( ) const;

Return Value

The path of the specified file.

Remarks

Call this member function to get the full path of the specified file. You must call FindNextFile at least once before calling GetFilePath.

GetFilePath is one of three CFileFind member functions that return some form of the file name. The following list describes the three and how they vary:

  • GetFileName returns the file name, including the extension. For example, calling GetFileName to generate a user message about the file c:\myhtml\myfile.txt returns the file name myfile.txt.

  • GetFilePath returns the entire path for the file. For example, calling GetFilePath to generate a user message about the file c:\myhtml\myfile.txt returns the file path c:\myhtml\myfile.txt.

  • GetFileTitle returns the file name, excluding the file extension. For example, calling GetFileTitle to generate a user message about the file c:\myhtml\myfile.txt returns the file title myfile.

CFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::FindFile


CFileFind::GetFileTitle

virtual CString GetFileTitle( ) const;

Return Value

The title of the file.

Remarks

Call this member function to get the title of the found file. You must call FindNextFile at least once before calling GetFileTitle.

GetFileTitle is one of three CFileFind member functions that return some form of the file name. The following list describes the three and how they vary:

  • GetFileName returns the file name, including the extension. For example, calling GetFileName to generate a user message about the file c:\myhtml\myfile.txt returns the file name myfile.txt.

  • GetFilePath returns the entire path for the file. For example, calling GetFilePath to generate a user message about the file c:\myhtml\myfile.txt returns the file path c:\myhtml\myfile.txt.

  • GetFileTitle returns the file name, excluding the file extension. For example, calling GetFileTitle to generate a user message about the file c:\myhtml\myfile.txt returns the file title myfile.

CFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::FindFile


CFileFind::GetFileURL

virtual CString GetFileURL( ) const;

Return Value

The complete URL.

Remarks

Call this member function to retrieve the specified URL. You must call FindNextFile at least once before calling GetFileURL.

GetFileURL is similar to the member function GetFilePath, except that it returns the URL in the form file://path. For example, calling GetFileURL to get the complete URL for myfile.txt returns the URL file://c:\myhtml\myfile.txt.

CFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::FindFile


CFileFind::GetLastAccessTime

virtual BOOL GetLastAccessTime( CTime& refTime ) const;

virtual BOOL GetLastAccessTime( FILETIME* pFileTime ) const;

Return Value

Nonzero if successful; 0 if unsuccessful. GetLastAccessTime returns 0 only if FindNextFile has never been called on this CFileFind object.

Parameters

pFileTime

A pointer to a FILETIME structure containing the time the file was last accessed.

refTime

A reference to a CTime object.

Remarks

Call this member function to get the time that the specified file was last accessed.

You must call FindNextFile at least once before calling GetLastAccessTime.

Note Not all file systems use the same semantics to implement the time stamp returned by this function. This function may return the same value returned by other time stamp functions if the underlying file system or server does not support keeping the time attribute. See the Win32_FIND_DATA structure for information about time formats. On some operation systems, the returned time is in the time zone local to the machine were the file is located. See the Win32 FileTimeToLocalFileTime API for more information.


CFileFind::GetLastWriteTime

virtual BOOL GetLastWriteTime( FILETIME* pFileTime ) const;

virtual BOOL GetLastWriteTime( CTime& refTime ) const;

Return Value

Nonzero if successful; 0 if unsuccessful. GetLastWriteTime returns 0 only if FindNextFile has never been called on this CFileFind object.

Parameters

pFileTime

A pointer to a FILETIME structure containing the time the file was last written to.

refTime

A reference to a CTime object.

Remarks

Call this member function to get the last time the file was changed.

You must call FindNextFile at least once before calling GetLastWriteTime.

Note Not all file systems use the same semantics to implement the time stamp returned by this function. This function may return the same value returned by other time stamp functions if the underlying file system or server does not support keeping the time attribute. See the Win32_Find_Data structure for information about time formats. On some operation systems, the returned time is in the time zone local to the machine were the file is located. See the Win32 FileTimeToLocalFileTime API for more information.


CFileFind::GetLength

DWORD GetLength( ) const;

Return Value

The length of the found file, in bytes.

Remarks

Call this member function to get the length of the found file, in bytes. You must call FindNextFile at least once before calling GetLength.

GetLength uses the nFileSizeLow member of the Win32 structure, WIN32_FIND_DATA, to get and return the low-order DWORD value of the file size, in bytes. If the file may be more than four gigabytes in size, use the GetLength64 member.


CFileFind::GetRoot

virtual CString GetRoot( ) const;

Return Value

The root of the active search.

Remarks

Call this member function to get the root of the found file. You must call FindNextFile at least once before calling GetRoot.

This member function returns the drive specifier and path name used to start a search. For example, calling FindFile with *.dat results in GetRoot returning an empty string. Passing a path, such as c:\windows\system\*.dll, to FindFile results GetRoot returning c:\windows\system\.


CFileFind::IsArchived

BOOL IsArchived( ) const;

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this member function to determine if the found file is archived. Applications mark an archive file, which is to be backed up or removed, with FILE_ATTRIBUTE_ARCHIVE, a file attribute identified in the WIN32_FIND_DATA structure.

See the member function MatchesMask for a complete list of file attributes.


CFileFind::IsCompressed

BOOL IsCompressed( ) const;

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this member function to determine if the found file is compressed. A compressed file is marked with FILE_ATTRIBUTE_COMPRESSED, a file attribute identified in the WIN32_FIND_DATA structure. For a file, this attribute indicates that all of the data in the file is compressed. For a directory, this attribute indicates that compression is the default for newly created files and subdirectories.

See the member function MatchesMask for a complete list of file attributes.


CFileFind::IsDirectory

BOOL IsDirectory( ) const;

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this member function to determine if the found file is a directory. A file that is a directory is marked with FILE_ATTRIBUTE_DIRECTORY a file attribute identified in the WIN32_FIND_DATA structure.

See the member function MatchesMask for a complete list of file attributes.


CFileFind::IsDots

virtual BOOL IsDots( ) const;

Return Value

Nonzero if the found file has the name "." or "..", which indicates that the found file is actually a diretory. Otherwise 0.

Remarks

Call this member function to test for the current directory and parent directory markers while iterating through files.

CFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::IsDirectory


CFileFind::IsHidden

BOOL IsHidden( ) const;

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this member function to determine if the found file is hidden. Hidden files, which are marked with FILE_ATTRIBUTE_HIDDEN, a file attribute identified in the WIN32_FIND_DATA structure. A hidden file is not included in an ordinary directory listing.

See the member function MatchesMask for a complete list of file attributes.


CFileFind::IsNormal

BOOL IsNormal( ) const;

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this member function to determine if the found file is a normal file. Files marked with FILE_ATTRIBUTE_NORMAL, a file attribute identified in the WIN32_FIND_DATA structure. A normal file has no other attributes set. All other file attributes override this attribute.

See the member function MatchesMask for a complete list of file attributes.


CFileFind::IsReadOnly

BOOL IsReadOnly( ) const;

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this member function to determine if the found file is read-only. A read-only file is marked with FILE_ATTRIBUTE_, a file attribute identified in the WIN32_FIND_DATA structure. Applications can read such a file, but they cannot write to it or delete it.

See the member function MatchesMask for a complete list of file attributes.


CFileFind::IsSystem

BOOL IsSystem( ) const;

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this member function to determine if the found file is a system file. A system file is marked with FILE_ATTRIBUTE_SYSTEM, , a file attribute identified in the WIN32_FIND_DATA structure. A system file is part of, or is used exclusively by, the operating system.

See the member function MatchesMask for a complete list of file attributes.


CFileFind::IsTemporary

BOOL IsTemporary( ) const;

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this member function to determine if the found file is a temporary file. A temporary file is marked with FILE_ATTRIBUTE_TEMPORARY, a file attribute identified in the WIN32_FIND_DATA structure. A temporary file is used for temporary storage. Applications should write to the file only if absolutely necessary. Most of the file’s data remains in memory without being flushed to the media because the file will soon be deleted.

See the member function MatchesMask for a complete list of file attributes.


CFileFind::MatchesMask

virtual BOOL MatchesMask( DWORD dwMask ) const;

Return Value

Nonzero if successful; otherwise 0. To get extended error information, call the Win32 function GetLastError.

Parameters

dwMask

Specifies one or more file attributes, identified in the WIN32_FIND_DATA structure, for the found file. To search for multiple attributes, use the bitwise OR (|) operator. Any combination of the following attributes is acceptable:

  • FILE_ATTRIBUTE_ARCHIVE The file is an archive file. Applications use this attribute to mark files for backup or removal.

  • FILE_ATTRIBUTE_COMPRESSED The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.

  • FILE_ATTRIBUTE_DIRECTORY The file is a directory.

  • FILE_ATTRIBUTE_NORMAL The file has no other attributes set. This attribute is valid only if used alone. All other file attributes override this attribute.

  • FILE_ATTRIBUTE_HIDDEN The file is hidden. It is not to be included in an ordinary directory listing.

  • FILE_ATTRIBUTE_READONLY The file is read only. Applications can read the file but cannot write to it or delete it.

  • FILE_ATTRIBUTE_SYSTEM The file is part of or is used exclusively by the operating system.

  • FILE_ATTRIBUTE_TEMPORARY The file is being used for temporary storage. Applications should write to the file only if absolutely necessary. Most of the file’s data remains in memory without being flushed to the media because the file will soon be deleted.

Remarks

Call this member function to test the file attributes on the found file.

CFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::IsDots, CFileFind::IsReadOnly, CFileFind::IsDirectory, CFileFind::IsCompressed, CFileFind::IsSystem, CFileFind::IsHidden, CFileFind::IsTemporary, CFileFind::IsNormal, CFileFind::IsArchived


CFindReplaceDialog

The CFindReplaceDialog class allows you to implement standard string Find/Replace dialog boxes in your application. Unlike the other Windows common dialog boxes, CFindReplaceDialog objects are modeless, allowing users to interact with other windows while they are on screen. There are two kinds of CFindReplaceDialog objects: Find dialog boxes and Find/Replace dialog boxes. Although the dialog boxes allow the user to input search and search/replace strings, they do not perform any of the searching or replacing functions. You must add these to the application.

To construct a CFindReplaceDialog object, use the provided constructor (which has no arguments). Since this is a modeless dialog box, allocate the object on the heap using the new operator, rather than on the stack.

Once a CFindReplaceDialog object has been constructed, you must call the Create member function to create and display the dialog box.

Use the m_fr structure to initialize the dialog box before calling Create. The m_fr structure is of type FINDREPLACE. For more information on this structure, see the Win32 SDK documentation.

In order for the parent window to be notified of find/replace requests, you must use the Windows RegisterWindowMessage function and use the ON_REGISTERED_MESSAGE message-map macro in your frame window that handles this registered message. You can call any of the member functions listed in the “Operations” section of the CFindReplaceDialog Class Members table from the frame window’s callback function.

You can determine whether the user has decided to terminate the dialog box with the IsTerminating member function.

CFindReplaceDialog relies on the COMMDLG.DLL file that ships with Windows versions 3.1 and later.

To customize the dialog box, derive a class from CFindReplaceDialog, provide a custom dialog template, and add a message map to process the notification messages from the extended controls. Any unprocessed messages should be passed to the base class.

Customizing the hook function is not required.

For more information on using CFindReplaceDialog, see Common Dialog Classes Visual C++ Programmer's Guide.

#include <afxdlgs.h>


CFindReplaceDialog Class Members

Data Members

m_fr A structure used to customize a CFindReplaceDialog object.

Construction

CFindReplaceDialog | Call this function to construct a CFindReplaceDialog object.
Create | Creates and displays a CFindReplaceDialog dialog box.

Operations

FindNext | Call this function to determine whether the user wants to find the next occurrence of the find string.
GetNotifier | Call this function to retrieve the FINDREPLACE structure in your registered message handler.
GetFindString | Call this function to retrieve the current find string.
GetReplaceString | Call this function to retrieve the current replace string.
IsTerminating | Call this function to determine whether the dialog box is terminating.
MatchCase | Call this function to determine whether the user wants to match the case of the find string exactly.
MatchWholeWord | Call this function to determine whether the user wants to match entire words only.
ReplaceAll | Call this function to determine whether the user wants all occurrences of the string to be replaced.
ReplaceCurrent | Call this function to determine whether the user wants the current word to be replaced.
SearchDown | Call this function to determine whether the user wants the search to proceed in a downward direction.


CFindReplaceDialog::CFindReplaceDialog

CFindReplaceDialog( );

Remarks

Constructs a CFindReplaceDialog object. CFindReplaceDialog objects are constructed on the heap with the new operator. For more information on the construction of CFindReplaceDialog objects, see the CFindReplaceDialog overview. Use the Create member function to display the dialog box.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::Create


CFindReplaceDialog::Create

BOOL Create( BOOL bFindDialogOnly, LPCTSTR lpszFindWhat, LPCTSTR lpszReplaceWith = NULL, DWORD dwFlags = FR_DOWN, CWnd* pParentWnd = NULL );

Return Value

Nonzero if the dialog box object was successfully created; otherwise 0.

Parameters

bFindDialogOnly

Set this parameter to TRUE to display the standard Windows Find dialog box. Set it to FALSE to display the Windows Find/Replace dialog box.

lpszFindWhat

Specifies the string for which to search.

lpszReplaceWith

Specifies the default string with which to replace found strings.

dwFlags

One or more flags you can use to customize the settings of the dialog box, combined using the bitwise OR operator. The default value is FR_DOWN, which specifies that the search is to proceed in a downward direction. See the FINDREPLACE structure in the Win32 SDK documentation for more information on these flags.

pParentWnd

A pointer to the dialog box’s parent or owner window. This is the window that will receive the special message indicating that a find/replace action is requested. If NULL, the application’s main window is used.

Remarks

Creates and displays either a Find or Find/Replace dialog box object, depending on the value of bFindDialogOnly.

In order for the parent window to be notified of find/replace requests, you must use the Windows RegisterWindowMessage function whose return value is a message number unique to the application’s instance. Your frame window should have a message map entry that declares the callback function (OnFindReplace in the example that follows) that handles this registered message. The following code fragment is an example of how to do this for a frame window class named CMyFrameWnd:

    class CMyFrameWnd : public CFrameWnd
    {
    protected:
        afx_msg LONG OnFindReplace(WPARAM wParam, LPARAM lParam);

        DECLARE_MESSAGE_MAP()
    };
    static UINT WM_FINDREPLACE = ::RegisterWindowMessage(FINDMSGSTRING);

    BEGIN_MESSAGE_MAP( CMyFrameWnd, CFrameWnd )
       //Normal message map entries here.
       ON_REGISTERED_MESSAGE( WM_FINDREPLACE, OnFindReplace )
    END_MESSAGE_MAP

Within your OnFindReplace function, you interpret the intentions of the user and create the code for the find/replace operations.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::CFindReplaceDialog


CFindReplaceDialog::FindNext

BOOL FindNext( ) const;

Return Value

Nonzero if the user wants to find the next occurrence of the search string; otherwise 0.

Remarks

Call this function from your callback function to determine whether the user wants to find the next occurrence of the search string.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::GetFindString, CFindReplaceDialog::SearchDown


CFindReplaceDialog::GetFindString

CString GetFindString( ) const;

Return Value

The default string to find.

Remarks

Call this function from your callback function to retrieve the default string to find.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::FindNext, CFindReplaceDialog::GetReplaceString


CFindReplaceDialog::GetNotifier

static CFindReplaceDialog* PASCAL GetNotifier( LPARAM lParam );

Return Value

A pointer to the current dialog box.

Parameters

lParam

The lparam value passed to the frame window’s OnFindReplace member function.

Remarks

Call this function to retrieve a pointer to the current Find Replace dialog box. It should be used within your callback function to access the current dialog box, call its member functions, and access the m_fr structure.


CFindReplaceDialog::GetReplaceString

CString GetReplaceString( ) const;

Return Value

The default string with which to replace found strings.

Remarks

Call this function to retrieve the current replace string.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::GetFindString


CFindReplaceDialog::IsTerminating

BOOL IsTerminating( ) const;

Return Value

Nonzero if the user has decided to terminate the dialog box; otherwise 0.

Remarks

Call this function within your callback function to determine whether the user has decided to terminate the dialog box. If this function returns nonzero, you should call the DestroyWindow member function of the current dialog box and set any dialog box pointer variable to NULL. Optionally, you can also store the find/replace text last entered and use it to initialize the next find/replace dialog box.


CFindReplaceDialog::MatchCase

BOOL MatchCase( ) const;

Return Value

Nonzero if the user wants to find occurrences of the search string that exactly match the case of the search string; otherwise 0.

Remarks

Call this function to determine whether the user wants to match the case of the find string exactly.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::MatchWholeWord


CFindReplaceDialog::MatchWholeWord

BOOL MatchWholeWord( ) const;

Return Value

Nonzero if the user wants to match only the entire words of the search string; otherwise 0.

Remarks

Call this function to determine whether the user wants to match entire words only.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::MatchCase


CFindReplaceDialog::ReplaceAll

BOOL ReplaceAll( ) const;

Return Value

Nonzero if the user has requested that all strings matching the replace string be replaced; otherwise 0.

Remarks

Call this function to determine whether the user wants all occurrences of the string to be replaced.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::ReplaceCurrent


CFindReplaceDialog::ReplaceCurrent

BOOL ReplaceCurrent( ) const;

Return Value

Nonzero if the user has requested that the currently selected string be replaced with the replace string; otherwise 0.

Remarks

Call this function to determine whether the user wants the current word to be replaced.

CFindReplaceDialog Overview | Class Members | Hierarchy Chart

See Also CFindReplaceDialog::ReplaceAll


CFindReplaceDialog::SearchDown

BOOL SearchDown( ) const;

Return Value

Nonzero if the user wants the search to proceed in a downward direction; 0 if the user wants the search to proceed in an upward direction.

Remarks

Call this function to determine whether the user wants the search to proceed in a downward direction.


CFindReplaceDialog::m_fr

Remarks

m_fr is a structure of type FINDREPLACE. Its members store the characteristics of the dialog-box object. After constructing a CFindReplaceDialog object, you can use m_fr to modify various values in the dialog box.

For more information on this structure, see the FINDREPLACE structure in the Win32 SDK documentation.


CFont

The CFont class encapsulates a Windows graphics device interface (GDI) font and provides member functions for manipulating the font. To use a CFont object, construct a CFont object and attach a Windows font to it with CreateFont, CreateFontIndirect, CreatePointFont, or CreatePointFontIndirect, and then use the object’s member functions to manipulate the font.

The CreatePointFont and CreatePointFontIndirect functions are often easier to use than CreateFont or CreateFontIndirect since they do the conversion for the height of the font from a point size to logical units automatically.

For more information on CFont, see Graphic Objects in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample HIERSVR


CFont Class Members

Construction

CFont Constructs a CFont object.

Initialization

CreateFontIndirect | Initializes a CFont object with the characteristics given in a LOGFONT structure.
CreateFont | Initializes a CFont with the specified characteristics.
CreatePointFont | Initializes a CFont with the specified height, measured in tenths of a point, and typeface.
CreatePointFontIndirect | Same as CreateFontIndirect except that the font height is measured in tenths of a point rather than logical units.

Operations

FromHandle Returns a pointer to a CFont object when given a Windows HFONT.

Attributes

operator HFONT | Returns the Windows GDI font handle attached to the CFont object.
GetLogFont | Fills a LOGFONT with information about the logical font attached to the CFont object.


CFont::CFont

CFont( );

Remarks

Constructs a CFont object. The resulting object must be initialized with CreateFont, CreateFontIndirect, CreatePointFont, or CreatePointFontIndirect before it can be used.

CFont Overview | Class Members | Hierarchy Chart

See Also CFont::CreateFontIndirect, CFont::CreateFont, CFont::CreatePointFont, CFont::CreatePointFontIndirect, ::EnumFonts


CFont::CreateFont

BOOL CreateFont( int nHeight, int nWidth, int nEscapement, int nOrientation, int nWeight, BYTE bItalic, BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet, BYTE nOutPrecision, BYTE nClipPrecision, BYTE nQuality, BYTE nPitchAndFamily, LPCTSTR lpszFacename );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nHeight

Specifies the desired height (in logical units) of the font. The font height can be specified in the following ways:

  • Greater than 0, in which case the height is transformed into device units and matched against the cell height of the available fonts.

  • Equal to 0, in which case a reasonable default size is used.

  • Less than 0, in which case the height is transformed into device units and the absolute value is matched against the character height of the available fonts.

    The absolute value of nHeight must not exceed 16,384 device units after it is converted. For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size or the smallest font if all the fonts exceed the requested size.

nWidth

Specifies the average width (in logical units) of characters in the font. If nWidth is 0, the aspect ratio of the device will be matched against the digitization aspect ratio of the available fonts to find the closest match, which is determined by the absolute value of the difference.

nEscapement

Specifies the angle (in 0.1-degree units) between the escapement vector and the x-axis of the display surface. The escapement vector is the line through the origins of the first and last characters on a line. The angle is measured counterclockwise from the x-axis.

nOrientation

Specifies the angle (in 0.1-degree units) between the baseline of a character and the x-axis. The angle is measured counterclockwise from the x-axis for coordinate systems in which the y-direction is down and clockwise from the x-axis for coordinate systems in which the y-direction is up.

nWeight

Specifies the font weight (in inked pixels per 1000). Although nWeight can be any integer value from 0 to 1000, the common constants and values are as follows:

Constant | Value
FW_DONTCARE | 0
FW_THIN | 100
FW_EXTRALIGHT | 200
FW_ULTRALIGHT | 200
FW_LIGHT | 300
FW_NORMAL | 400
FW_REGULAR | 400
FW_MEDIUM | 500
FW_SEMIBOLD | 600
FW_DEMIBOLD | 600
FW_BOLD | 700
FW_EXTRABOLD | 800
FW_ULTRABOLD | 800
FW_BLACK | 900
FW_HEAVY | 900

These values are approximate; the actual appearance depends on the typeface. Some fonts have only FW_NORMAL, FW_REGULAR, and FW_BOLD weights. If FW_DONTCARE is specified, a default weight is used.

bItalic

Specifies whether the font is italic.

bUnderline

Specifies whether the font is underlined.

cStrikeOut

Specifies whether characters in the font are struck out. Specifies a strikeout font if set to a nonzero value.

nCharSet

Specifies the font’s character set. The following constants and values are predefined:

Constant | Value
ANSI_CHARSET | 0
DEFAULT_CHARSET | 1
SYMBOL_CHARSET | 2
SHIFTJIS_CHARSET | 128
OEM_CHARSET | 255

The OEM character set is system-dependent.

Fonts with other character sets may exist in the system. An application that uses a font with an unknown character set must not attempt to translate or interpret strings that are to be rendered with that font. Instead, the strings should be passed directly to the output device driver.

The font mapper does not use the DEFAULT_CHARSET value. An application can use this value to allow the name and size of a font to fully describe the logical font. If a font with the specified name does not exist, a font from any character set can be substituted for the specified font. To avoid unexpected results, applications should use the DEFAULT_CHARSET value sparingly.

nOutPrecision

Specifies the desired output precision. The output precision defines how closely the output must match the requested font’s height, width, character orientation, escapement, and pitch. It can be any one of the following values:

OUT_CHARACTER_PRECIS | OUT_STRING_PRECIS
OUT_DEFAULT_PRECIS | OUT_STROKE_PRECIS
OUT_DEVICE_PRECIS | OUT_TT_PRECIS
OUT_RASTER_PRECIS |

Applications can use the OUT_DEVICE_PRECIS, OUT_RASTER_PRECIS, and OUT_TT_PRECIS values to control how the font mapper chooses a font when the system contains more than one font with a given name. For example, if a system contains a font named Symbol in raster and TrueType form, specifying OUT_TT_PRECIS forces the font mapper to choose the TrueType version. (Specifying OUT_TT_PRECIS forces the font mapper to choose a TrueType font whenever the specified font name matches a device or raster font, even when there is no TrueType font of the same name.)

nClipPrecision

Specifies the desired clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. It can be any one of the following values:

CLIP_CHARACTER_PRECIS | CLIP_MASK
CLIP_DEFAULT_PRECIS | CLIP_STROKE_PRECIS
CLIP_ENCAPSULATE | CLIP_TT_ALWAYS
CLIP_LH_ANGLES |

To use an embedded read-only font, an application must specify CLIP_ENCAPSULATE.

To achieve consistent rotation of device, TrueType, and vector fonts, an application can use the OR operator to combine the CLIP_LH_ANGLES value with any of the other nClipPrecision values. If the CLIP_LH_ANGLES bit is set, the rotation for all fonts depends on whether the orientation of the coordinate system is left-handed or right-handed. (For more information about the orientation of coordinate systems, see the description of the nOrientation parameter.) If CLIP_LH_ANGLES is not set, device fonts always rotate counterclockwise, but the rotation of other fonts is dependent on the orientation of the coordinate system.

nQuality

Specifies the font’s output quality, which defines how carefully the GDI must attempt to match the logical-font attributes to those of an actual physical font. It can be one of the following values:

  • DEFAULT_QUALITY Appearance of the font does not matter.

  • DRAFT_QUALITY Appearance of the font is less important than when PROOF_QUALITY is used. For GDI raster fonts, scaling is enabled. Bold, italic, underline, and strikeout fonts are synthesized if necessary.

  • PROOF_QUALITY Character quality of the font is more important than exact matching of the logical-font attributes. For GDI raster fonts, scaling is disabled and the font closest in size is chosen. Bold, italic, underline, and strikeout fonts are synthesized if necessary.

nPitchAndFamily

Specifies the pitch and family of the font. The two low-order bits specify the pitch of the font and can be any one of the following values:

DEFAULT_PITCH VARIABLE_PITCH FIXED_PITCH

Applications can add TMPF_TRUETYPE to the nPitchAndFamily parameter to choose a TrueType font. The four high-order bits of the parameter specify the font family and can be any one of the following values:

  • FF_DECORATIVE Novelty fonts: Old English, for example.

  • FF_DONTCARE Don’t care or don’t know.

  • FF_MODERN Fonts with constant stroke width (fixed-pitch), with or without serifs. Fixed-pitch fonts are usually modern faces. Pica, Elite, and Courier New are examples.

  • FF_ROMAN Fonts with variable stroke width (proportionally spaced) and with serifs. Times New Roman and Century Schoolbook are examples.

  • FF_SCRIPT Fonts designed to look like handwriting. Script and Cursive are examples.

  • FF_SWISS Fonts with variable stroke width (proportionally spaced) and without serifs. MS Sans Serif is an example.

    An application can specify a value for nPitchAndFamily by using the Boolean OR operator to join a pitch constant with a family constant.

    Font families describe the look of a font in a general way. They are intended for specifying fonts when the exact typeface desired is not available.

lpszFacename

A CString or pointer to a null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 30 characters. The Windows EnumFontFamilies function can be used to enumerate all currently available fonts. If lpszFacename is NULL, the GDI uses a device-independent typeface.

Remarks

Initializes a CFont object with the specified characteristics. The font can subsequently be selected as the font for any device context.

The CreateFont function does not create a new Windows GDI font. It merely selects the closest match from the fonts available in the GDI’s pool of physical fonts.

Applications can use the default settings for most of these parameters when creating a logical font. The parameters that should always be given specific values are nHeight and lpszFacename. If nHeight and lpszFacename are not set by the application, the logical font that is created is device-dependent.

When you finish with the CFont object created by the CreateFont function, first select the font out of the device context, then delete the CFont object.

CFont Overview | Class Members | Hierarchy Chart

See Also CFont::CreateFontIndirect, CFont::CreatePointFont, ::CreateFont, ::EnumFontFamilies, ::EnumFonts


CFont::CreateFontIndirect

BOOL CreateFontIndirect(const LOGFONT* lpLogFont );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpLogFont

Points to a LOGFONT structure that defines the characteristics of the logical font.

Remarks

Initializes a CFont object with the characteristics given in a LOGFONT structure pointed to by lpLogFont. The font can subsequently be selected as the current font for any device.

This font has the characteristics specified in the LOGFONT structure. When the font is selected by using the CDC::SelectObject member function, the GDI’s font mapper attempts to match the logical font with an existing physical font. If it fails to find an exact match for the logical font, it provides an alternative whose characteristics match as many of the requested characteristics as possible.

When you finish with the CFont object created by the CreateFontIndirect function, first select the font out of the device context, then delete the CFont object.

CFont Overview | Class Members | Hierarchy Chart

See Also CFont::CreateFont, CFont::CreatePointFontIndirect, CDC::SelectObject, CGdiObject::DeleteObject, ::CreateFontIndirect


CFont::CreatePointFont

BOOL CreatePointFont( int nPointSize, LPCTSTR lpszFaceName, CDC* pDC = NULL );

Return Value

Nonzero if successful, otherwise 0.

Parameters

nPointSize

Requested font height in tenths of a point. (For instance, pass 120 to request a 12-point font.)

lpszFaceName

A CString or pointer to a null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 30 characters. The Windows EnumFontFamilies function can be used to enumerate all currently available fonts. If lpszFaceName is NULL, the GDI uses a device-independent typeface.

pDC

Pointer to the CDC object to be used to convert the height in nPointSize to logical units. If NULL, a screen device context is used for the conversion.

Remarks

This function provides a simple way to create a font of a specified typeface and point size. It automatically converts the height in nPointSize to logical units using the CDC object pointed to by pDC.

When you finish with the CFont object created by the CreatePointFont function, first select the font out of the device context, then delete the CFont object.

CFont Overview | Class Members | Hierarchy Chart

See Also CFont::CreatePointFontIndirect, CFont::CreateFont


CFont::CreatePointFontIndirect

BOOL CreatePointFontIndirect( const LOGFONT* lpLogFont, CDC* pDC = NULL );

Return Value

Nonzero if successful, otherwise 0.

Parameters

lpLogFont

Points to a LOGFONT structure that defines the characteristics of the logical font. The lfHeight member of the LOGFONT structure is measured in tenths of a point rather than logical units. (For instance, set lfHeight to 120 to request a 12-point font.)

pDC

Pointer to the CDC object to be used to convert the height in lfHeight to logical units. If NULL, a screen device context is used for the conversion.

Remarks

This function is the same as CreateFontIndirect except that the lfHeight member of the LOGFONT is interpreted in tenths of a point rather than device units. This function automatically converts the height in lfHeight to logical units using the CDC object pointed to by pDC before passing the LOGFONT structure on to Windows.

When you finish with the CFont object created by the CreatePointFontIndirect function, first select the font out of the device context, then delete the CFont object.

CFont Overview | Class Members | Hierarchy Chart

See Also CFont::CreatePointFont, CFont::CreateFontIndirect


CFont::FromHandle

static CFont* PASCAL FromHandle( HFONT hFont );

Return Value

A pointer to a CFont object if successful; otherwise NULL.

Parameters

hFont

An HFONT handle to a Windows font.

Remarks

Returns a pointer to a CFont object when given an HFONT handle to a Windows GDI font object. If a CFont object is not already attached to the handle, a temporary CFont object is created and attached. This temporary CFont object is valid only until the next time the application has idle time in its event loop, at which time all temporary graphic objects are deleted. Another way of saying this is that the temporary object is valid only during the processing of one window message.


CFont::GetLogFont

int GetLogFont( LOGFONT * pLogFont );

Return Value

Nonzero if the function succeeds, otherwise 0.

Parameters

pLogFont

Pointer to the LOGFONT structure to receive the font information.

Remarks

Call this function to retrieve a copy of the LOGFONT structure for Cfont.

CFont Overview | Class Members | Hierarchy Chart

See Also LOGFONT, ::GetObject


CFont::operator HFONT

operator HFONT( ) const;

Return Value

The handle of the Windows GDI font object attached to CFont if successful; otherwise NULL.

Remarks

Use this operator to get the Windows GDI handle of the font attached to the CFont object.

Since this operator is automatically used for conversions from CFont to Fonts and Text, you can pass CFont objects to functions that expect HFONTs.

For more information about using graphic objects, see Graphic Objects in the Win32 SDK documentation.


CFontDialog

The CFontDialog class allows you to incorporate a font-selection dialog box into your application. A CFontDialog object is a dialog box with a list of fonts that are currently installed in the system. The user can select a particular font from the list, and this selection is then reported back to the application.

To construct a CFontDialog object, use the provided constructor or derive a new subclass and use your own custom constructor.

Once a CFontDialog object has been constructed, you can use the m_cf structure to initialize the values or states of controls in the dialog box. The m_cf structure is of type CHOOSEFONT. For more information on this structure, see the Win32 SDK documentation.

After initializing the dialog object’s controls, call the DoModal member function to display the dialog box and allow the user to select a font. DoModal returns whether the user selected the OK (IDOK) or Cancel (IDCANCEL) button.

If DoModal returns IDOK, you can use one of CFontDialog’s member functions to retrieve the information input by the user.

You can use the Windows CommDlgExtendedError function to determine whether an error occurred during initialization of the dialog box and to learn more about the error. For more information on this function, see the Win32 SDK documentation.

CFontDialog relies on the COMMDLG.DLL file that ships with Windows versions 3.1 and later.

To customize the dialog box, derive a class from CFontDialog, provide a custom dialog template, and add a message-map to process the notification messages from the extended controls. Any unprocessed messages should be passed to the base class.

Customizing the hook function is not required.

For more information on using CFontDialog, see Common Dialog Classes in Visual C++ Programmer's Guide.

#include <afxdlgs.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample HIERSVR


CFontDialog Class Members

Data Members

m_cf A structure used to customize a CFontDialog object.

Construction

CFontDialog Constructs a CFontDialog object.

Operations

DoModal | Displays the dialog and allows the user to make a selection.
GetCurrentFont | Retrieves the name of the currently selected font.
GetFaceName | Returns the face name of the selected font.
GetStyleName | Returns the style name of the selected font.
GetSize | Returns the point size of the selected font.
GetColor | Returns the color of the selected font.
GetWeight | Returns the weight of the selected font.
IsStrikeOut | Determines whether the font is displayed with strikeout.
IsUnderline | Determines whether the font is underlined.
IsBold | Determines whether the font is bold.
IsItalic | Determines whether the font is italic.


CFontDialog::CFontDialog

CFontDialog( LPLOGFONT lplfInitial = NULL, DWORD dwFlags = CF_EFFECTS | CF_SCREENFONTS, CDC* pdcPrinter = NULL, CWnd* pParentWnd = NULL );

Parameters

lplfInitial

A pointer to a LOGFONT data structure that allows you to set some of the font’s characteristics.

dwFlags

Specifies one or more choose-font flags. One or more preset values can be combined using the bitwise OR operator. If you modify the m_cf.Flags structure member, be sure to use a bitwise OR operator in your changes to keep the default behavior intact. For details on each of these flags, see the description of the CHOOSEFONT structure in the Win32 SDK documentation.

pdcPrinter

A pointer to a printer-device context. If supplied, this parameter points to a printer-device context for the printer on which the fonts are to be selected.

pParentWnd

A pointer to the font dialog box’s parent or owner window.

Remarks

Constructs a CFontDialog object. Note that the constructor automatically fills in the members of the CHOOSEFONT structure. You should only change these if you want a font dialog different than the default.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::DoModal


CFontDialog::DoModal

virtual int DoModal( );

Return Value

IDOK or IDCANCEL. If IDCANCEL is returned, call the Windows CommDlgExtendedError function to determine whether an error occurred.

IDOK and IDCANCEL are constants that indicate whether the user selected the OK or Cancel button.

Remarks

Call this function to display the Windows common font dialog box and allow the user to choose a font.

If you want to initialize the various font dialog controls by setting members of the m_cf structure, you should do this before calling DoModal, but after the dialog object is constructed.

If DoModal returns IDOK, you can call other member functions to retrieve the settings or information input by the user into the dialog box.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CDialog::DoModal, CFontDialog::CFontDialog


CFontDialog::GetColor

COLORREF GetColor( ) const;

Return Value

The color of the selected font.

Remarks

Call this function to retrieve the selected font color.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetCurrentFont


CFontDialog::GetCurrentFont

void GetCurrentFont( LPLOGFONT lplf );

Parameters

lplf

A pointer to a LOGFONT structure.

Remarks

Call this function to assign the characteristics of the currently selected font to the members of a LOGFONT structure. Other CFontDialog member functions are provided to access individual characteristics of the current font.

If this function is called during a call to DoModal, it returns the current selection at the time (what the user sees or has changed in the dialog). If this function is called after a call to DoModal (only if DoModal returns IDOK), it returns what the user actually selected.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetFaceName, CFontDialog::GetStyleName


CFontDialog::GetFaceName

CString GetFaceName( ) const;

Return Value

The face name of the font selected in the CFontDialog dialog box.

Remarks

Call this function to retrieve the face name of the selected font.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetCurrentFont, CFontDialog::GetStyleName


CFontDialog::GetSize

int GetSize( ) const;

Return Value

The font’s size, in tenths of a point.

Remarks

Call this function to retrieve the size of the selected font.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetWeight, CFontDialog::GetCurrentFont


CFontDialog::GetStyleName

CString GetStyleName( ) const;

Return Value

The style name of the font.

Remarks

Call this function to retrieve the style name of the selected font.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetFaceName, CFontDialog::GetCurrentFont


CFontDialog::GetWeight

int GetWeight( ) const;

Return Value

The weight of the selected font.

Remarks

Call this function to retrieve the weight of the selected font. For more information on the weight of a font, see CFont::CreateFont.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetCurrentFont, CFontDialog::IsBold


CFontDialog::IsBold

BOOL IsBold( ) const;

Return Value

Nonzero if the selected font has the Bold characteristic enabled; otherwise 0.

Remarks

Call this function to determine if the selected font is bold.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetCurrentFont


CFontDialog::IsItalic

BOOL IsItalic( ) const;

Return Value

Nonzero if the selected font has the Italic characteristic enabled; otherwise 0.

Remarks

Call this function to determine if the selected font is italic.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetCurrentFont


CFontDialog::IsStrikeOut

BOOL IsStrikeOut( ) const;

Return Value

Nonzero if the selected font has the Strikeout characteristic enabled; otherwise 0.

Remarks

Call this function to determine if the selected font is displayed with strikeout.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetCurrentFont


CFontDialog::IsUnderline

BOOL IsUnderline( ) const;

Return Value

Nonzero if the selected font has the Underline characteristic enabled; otherwise 0.

Remarks

Call this function to determine if the selected font is underlined.

CFontDialog Overview | Class Members | Hierarchy Chart

See Also CFontDialog::GetCurrentFont


CFontDialog::m_cf

Remarks

A structure whose members store the characteristics of the dialog object. After constructing a CFontDialog object, you can use m_cf to modify various aspects of the dialog box before calling the DoModal member function. For more information on this structure, see CHOOSEFONT in the Win32 SDK documentation.


CFontHolder

CFontHolder does not have a base class.

The CFontHolder class, which encapsulates the functionality of a Windows font object and the IFont interface, is used to implement the stock Font property.

Use this class to implement custom font properties for your control. For information on creating such properties, see the article ActiveX Controls: Using Fonts in an ActiveX Control in Visual C++ Programmer's Guide.

#include <afxctl.h>

Class Members | Hierarchy Chart

See Also CPropExchange


CFontHolder Class Members

Data Members

m_pFont A pointer to the CFontHolder object’s IFont interface.

Construction/Destruction

CFontHolder Constructs a CFontHolder object.

Operations

GetFontDispatch | Returns the font’s IDispatch interface.
GetDisplayString | Retrieves the string displayed in a container’s property browser.
GetFontHandle | Returns a handle to a Windows font.
InitializeFont | Initializes a CFontHolder object.
ReleaseFont | Disconnects the CFontHolder object from the IFont and IFontNotification interfaces.
Select | Selects a font resource into a device context.
SetFont | Connects the CFontHolder object to an IFont interface.


CFontHolder::CFontHolder

CFontHolder( LPPROPERTYNOTIFYSINK pNotify );

Parameters

pNotify

Pointer to the font’s IPropertyNotifySink interface.

Remarks

Constructs a CFontHolder object. You must call InitializeFont to initialize the resulting object before using it.

CFontHolder Overview | Class Members | Hierarchy Chart

See Also CFontHolder::InitializeFont


CFontHolder::GetDisplayString

BOOL GetDisplayString( CString& strValue );

Return Value

Nonzero if the string is successfully retrieved; otherwise 0.

Parameters

strValue

Reference to the CString that is to hold the display string.

Remarks

Retrieves a string that can be displayed in a container’s property browser.


CFontHolder::GetFontDispatch

LPFONTDISP GetFontDispatch( );

Return Value

A pointer to the CFontHolder object’s IFontDisp interface. Note that the function that calls GetFontDispatch must call IUnknown::Release on this interface pointer when done with it.

Remarks

Call this function to retrieve a pointer to the font’s dispatch interface. Call InitializeFont before calling GetFontDispatch.

CFontHolder Overview | Class Members | Hierarchy Chart

See Also CFontHolder::InitializeFont


CFontHolder::GetFontHandle

HFONT GetFontHandle( );

HFONT GetFontHandle( long cyLogical, long cyHimetric );

Return Value

A handle to the Font object; otherwise NULL.

Parameters

cyLogical

Height, in logical units, of the rectangle in which the control is drawn.

cyHimetric

Height, in MM_HIMETRIC units, of the control.

Remarks

Call this function to get a handle to a Windows font.

The ratio of cyLogical and cyHimetric is used to calculate the proper display size, in logical units, for the font’s point size expressed in MM_HIMETRIC units:

Display size = (cyLogical / cyHimetric) X font size

The version with no parameters returns a handle to a font sized correctly for the screen.


CFontHolder::InitializeFont

void InitializeFont( const FONTDESC FAR* pFontDesc = NULL, LPDISPATCH pFontDispAmbient = NULL );

Parameters

pFontDesc

Pointer to a font description structure ( FONTDESC) that specifies the font’s characteristics.

pFontDispAmbient

Pointer to the container’s ambient Font property.

Remarks

Initializes a CFontHolder object.

If pFontDispAmbient is not NULL, the CFontHolder object is connected to a clone of the IFont interface used by the container’s ambient Font property.

If pFontDispAmbient is NULL, a new Font object is created either from the font description pointed to by pFontDesc or, if pFontDesc is NULL, from a default description.

Call this function after constructing a CFontHolder object.

CFontHolder Overview | Class Members | Hierarchy Chart

See Also CFontHolder::CFontHolder


CFontHolder::ReleaseFont

void ReleaseFont( );

Remarks

This function disconnects the CFontHolder object from its IFont interface.

CFontHolder Overview | Class Members | Hierarchy Chart

See Also CFontHolder::SetFont


CFontHolder::Select

CFont* Select( CDC* pDC, long cyLogical, long cyHimetric );

Return Value

A pointer to the font that is being replaced.

Parameters

pDC

Device context into which the font is selected.

cyLogical

Height, in logical units, of the rectangle in which the control is drawn.

cyHimetric

Height, in MM_HIMETRIC units, of the control.

Remarks

Call this function to select your control’s font into the specified device context.

See GetFontHandle for a discussion of the cyLogical and cyHimetric parameters.


CFontHolder::SetFont

void SetFont( LPFONT pNewFont );

Parameters

pNewFont

Pointer to the new IFont interface.

Remarks

Releases any existing font and connects the CFontHolder object to an IFont interface.

CFontHolder Overview | Class Members | Hierarchy Chart

See Also CFontHolder::ReleaseFont


CFontHolder::m_pFont

Remarks

A pointer to the CFontHolder object’s IFont interface.

CFontHolder Overview | Class Members | Hierarchy Chart

See Also CFontHolder::SetFont


CFormView

The CFormView class is the base class used for form views. A form view is essentially a view that contains controls. These controls are laid out based on a dialog-template resource. Use CFormView if you want forms in your application. These views support scrolling, as needed, using the CScrollView functionality.

When you create an application with the MFC AppWizard, you can base its view class on CFormView, making it a forms-based application.

You can also insert new forms into document-view-based applications. Even if your application did not initially support forms, Visual C++ will add this support when you insert a new form.

The MFC AppWizard and the New Form command are the preferred methods for creating forms-based applications. If you need to create a forms-based application without using these methods, see Forms-Based Applications.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample SNAPVW | MFC Sample VIEWEX

See Also CDialog, CScrollView, CView::OnUpdate, CView::OnInitialUpdate, CView::OnPrint, CWnd::UpdateData, CScrollView::ResizeParentToFit


CFormView Class Members

Construction

CFormView Constructs a CFormView object.


CFormView::CFormView

CFormView( LPCTSTR lpszTemplateName );

CFormView( UINT nIDTemplate );

Parameters

lpszTemplateName

Contains a null-terminated string that is the name of a dialog-template resource.

nIDTemplate

Contains the ID number of a dialog-template resource.

Remarks

When you create an object of a type derived from CFormView, invoke one of the constructors to create the view object and identify the dialog resource on which the view is based. You can identify the resource either by name (pass a string as the argument to the constructor) or by its ID (pass an unsigned integer as the argument).

The form-view window and child controls are not created until CWnd::Create is called. CWnd::Create is called by the framework as part of the document and view creation process, which is driven by the document template.

Note Your derived class must supply its own constructor. In the constructor, invoke the constructor, CFormView::CFormView, with the resource name or ID as an argument as shown in the preceding class overview.

CFormView Overview | Class Members | Hierarchy Chart

See Also CWnd::Create


CFrameWnd

The CFrameWnd class provides the functionality of a Windows single document interface (SDI) overlapped or pop-up frame window, along with members for managing the window.

To create a useful frame window for your application, derive a class from CFrameWnd. Add member variables to the derived class to store data specific to your application. Implement message-handler member functions and a message map in the derived class to specify what happens when messages are directed to the window.

There are three ways to construct a frame window:

  • Directly construct it using Create.

  • Directly construct it using LoadFrame.

  • Indirectly construct it using a document template.

Before you call either Create or LoadFrame, you must construct the frame-window object on the heap using the C++ new operator. Before calling Create, you can also register a window class with the AfxRegisterWndClass global function to set the icon and class styles for the frame.

Use the Create member function to pass the frame’s creation parameters as immediate arguments.

LoadFrame requires fewer arguments than Create, and instead retrieves most of its default values from resources, including the frame’s caption, icon, accelerator table, and menu. To be accessible by LoadFrame, all these resources must have the same resource ID (for example, IDR_MAINFRAME).

When a CFrameWnd object contains views and documents, they are created indirectly by the framework instead of directly by the programmer. The CDocTemplate object orchestrates the creation of the frame, the creation of the containing views, and the connection of the views to the appropriate document. The parameters of the CDocTemplate constructor specify the CRuntimeClass of the three classes involved (document, frame, and view). A CRuntimeClass object is used by the framework to dynamically create new frames when specified by the user (for example, by using the File New command or the multiple document interface (MDI) Window New command).

A frame-window class derived from CFrameWnd must be declared with DECLARE_DYNCREATE in order for the above RUNTIME_CLASS mechanism to work correctly.

A CFrameWnd contains default implementations to perform the following functions of a main window in a typical application for Windows:

  • A CFrameWnd frame window keeps track of a currently active view that is independent of the Windows active window or the current input focus. When the frame is reactivated, the active view is notified by calling CView::OnActivateView.

  • Command messages and many common frame-notification messages, including those handled by the OnSetFocus, OnHScroll, and OnVScroll functions of CWnd, are delegated by a CFrameWnd frame window to the currently active view.

  • The currently active view (or currently active MDI child frame window in the case of an MDI frame) can determine the caption of the frame window. This feature can be disabled by turning off the FWS_ADDTOTITLE style bit of the frame window.

  • A CFrameWnd frame window manages the positioning of the control bars, views, and other child windows inside the frame window’s client area. A frame window also does idle-time updating of toolbar and other control-bar buttons. A CFrameWnd frame window also has default implementations of commands for toggling on and off the toolbar and status bar.

  • A CFrameWnd frame window manages the main menu bar. When a pop-up menu is displayed, the frame window uses the UPDATE_COMMAND_UI mechanism to determine which menu items should be enabled, disabled, or checked. When the user selects a menu item, the frame window updates the status bar with the message string for that command.

  • A CFrameWnd frame window has an optional accelerator table that automatically translates keyboard accelerators.

  • A CFrameWnd frame window has an optional help ID set with LoadFrame that is used for context-sensitive help. A frame window is the main orchestrator of semimodal states such as context-sensitive help (SHIFT+F1) and print-preview modes.

  • A CFrameWnd frame window will open a file dragged from the File Manager and dropped on the frame window. If a file extension is registered and associated with the application, the frame window responds to the dynamic data exchange (DDE) open request that occurs when the user opens a data file in the File Manager or when the ShellExecute Windows function is called.

  • If the frame window is the main application window (that is, CWinThread::m_pMainWnd), when the user closes the application, the frame window prompts the user to save any modified documents (for OnClose and OnQueryEndSession).

  • If the frame window is the main application window, the frame window is the context for running WinHelp. Closing the frame window will shut down WINHELP.EXE if it was launched for help for this application.

Do not use the C++ delete operator to destroy a frame window. Use CWnd::DestroyWindow instead. The CFrameWnd implementation of PostNcDestroy will delete the C++ object when the window is destroyed. When the user closes the frame window, the default OnClose handler will call DestroyWindow.

For more information on CFrameWnd, see Frame Window Topics in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CWnd, CMDIFrameWnd, CMDIChildWnd, CView, CDocTemplate, CRuntimeClass


CFrameWnd Class Members

Data Members

m_bAutoMenuEnable | Controls automatic enable and disable functionality for menu items.
rectDefault | Pass this static CRect as a parameter when creating a CFrameWnd object to allow Windows to choose the window’s initial size and position.

Construction

CFrameWnd Constructs a CFrameWnd object.

Initialization

Create | Call to create and initialize the Windows frame window associated with the CFrameWnd object.
LoadFrame | Call to dynamically create a frame window from resource information.
LoadAccelTable | Call to load an accelerator table.
LoadBarState | Call to restore control bar settings.
SaveBarState | Call to save control bar settings.
ShowControlBar | Call to show the control bar.
SetDockState | Call to dock the frame window in the main window.
GetDockState | Retrieves the dock state of a frame window.

Operations

ActivateFrame | Makes the frame visible and available to the user.
InitialUpdateFrame | Causes the OnInitialUpdate member function belonging to all views in the frame window to be called.
GetActiveFrame | Returns the active CFrameWnd object.
SetActiveView | Sets the active CView object.
GetActiveView | Returns the active CView object.
CreateView | Creates a view within a frame that is not derived from CView.
GetActiveDocument | Returns the active CDocument object.
GetControlBar | Retrieves the control bar.
GetMessageString | Retrieves message corresponding to a command ID.
IsTracking | Determines if splitter bar is currently being moved.
SetMessageText | Sets the text of a standard status bar.
EnableDocking | Allows a control bar to be docked.
DockControlBar | Docks a control bar.
FloatControlBar | Floats a control bar.
BeginModalState | Sets the frame window to modal.
EndModalState | Ends the frame window’s modal state. Enables all of the windows disabled by BeginModalState.
InModalState | Returns a value indicating whether or not a frame window is in a modal state.
ShowOwnedWindows | Shows all windows that are descendants of the CFrameWnd object.
RecalcLayout | Repositions the control bars of the CFrameWnd object.

Overridables

OnCreateClient | Creates a client window for the frame.
OnSetPreviewMode | Sets the application’s main frame window into and out of print-preview mode.
GetMessageBar | Returns a pointer to the status bar belonging to the frame window.
NegotiateBorderSpace | Negotiates border space in the frame window.

Command Handlers

OnContextHelp Handles SHIFT+F1 Help for in-place items.


CFrameWnd::ActivateFrame

virtual void ActivateFrame( int nCmdShow = -1 );

Parameters

nCmdShow

Specifies the parameter to pass to CWnd::ShowWindow. By default, the frame is shown and correctly restored.

Remarks

Call this member function to activate and restore the frame window so that it is visible and available to the user. This member function is usually called after a non-user interface event such as a DDE, OLE, or other event that may show the frame window or its contents to the user.

The default implementation activates the frame and brings it to the top of the Z-order and, if necessary, carries out the same steps for the application’s main frame window.

Override this member function to change how a frame is activated. For example, you can force MDI child windows to be maximized. Add the appropriate functionality, then call the base class version with an explicit nCmdShow.


CFrameWnd::BeginModalState

virtual void BeginModalState( );

Remarks

Call this member function to make a frame window modal.


CFrameWnd::CFrameWnd

CFrameWnd( );

Remarks

Constructs a CFrameWnd object, but does not create the visible frame window. Call Create to create the visible window.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::Create, CFrameWnd::LoadFrame


CFrameWnd::Create

BOOL Create( LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle = WS_OVERLAPPEDWINDOW, const RECT& rect = rectDefault, CWnd* pParentWnd = NULL, LPCTSTR lpszMenuName = NULL, DWORD dwExStyle = 0, CCreateContext* pContext = NULL );

Return Value

Nonzero if initialization is successful; otherwise 0.

Parameters

lpszClassName

Points to a null-terminated character string that names the Windows class. The class name can be any name registered with the AfxRegisterWndClass global function or the RegisterClass Windows function. If NULL, uses the predefined default CFrameWnd attributes.

lpszWindowName

Points to a null-terminated character string that represents the window name. Used as text for the title bar.

dwStyle

Specifies the window style attributes. Include the FWS_ADDTOTITLE style if you want the title bar to automatically display the name of the document represented in the window.

rect

Specifies the size and position of the window. The rectDefault value allows Windows to specify the size and position of the new window.

pParentWnd

Specifies the parent window of this frame window. This parameter should be NULL for top-level frame windows.

lpszMenuName

Identifies the name of the menu resource to be used with the window. Use MAKEINTRESOURCE if the menu has an integer ID instead of a string. This parameter can be NULL.

dwExStyle

Specifies the window extended style attributes.

pContext

Specifies a pointer to a CCreateContext structure. This parameter can be NULL.

Remarks

Construct a CFrameWnd object in two steps. First invoke the constructor, which constructs the CFrameWnd object, then call Create, which creates the Windows frame window and attaches it to the CFrameWnd object. Create initializes the window’s class name and window name and registers default values for its style, parent, and associated menu.

Use LoadFrame rather than Create to load the frame window from a resource instead of specifying its arguments.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::CFrameWnd, CFrameWnd::LoadFrame, CCreateContext, CWnd::Create, CWnd::PreCreateWindow


CFrameWnd::CreateView

CWnd* CreateView( CCreateContext* pContext, UINT nID = AFX_IDW_PANE_FIRST );

Return Value

Pointer to a CWnd object if successful; otherwise NULL.

Parameters

pContext

Specifies the type of view and document.

nID

The ID number of a view.

Remarks

Call CreateView to create a view within a frame. Use this member function to create “views” that are not CView-derived within a frame. After calling CreateView, you must manually set the view to active and set it to be visible; these tasks are not automatically performed by CreateView.

Note The MFC Advanced Concepts sample COLLECT uses CreateView to get correct 3D effects in Windows 95.


CFrameWnd::DockControlBar

void DockControlBar( CControlBar * pBar, UINT nDockBarID = 0, LPCRECT lpRect = NULL );

Parameters

pBar

Points to the control bar to be docked.

nDockBarID

Determines which sides of the frame window to consider for docking. It can be 0, or one or more of the following:

  • AFX_IDW_DOCKBAR_TOP Dock to the top side of the frame window.

  • AFX_IDW_DOCKBAR_BOTTOM Dock to the bottom side of the frame window.

  • AFX_IDW_DOCKBAR_LEFT Dock to the left side of the frame window.

  • AFX_IDW_DOCKBAR_RIGHT Dock to the right side of the frame window.

    If 0, the control bar can be docked to any side enabled for docking in the destination frame window.

lpRect

Determines, in screen coordinates, where the control bar will be docked in the nonclient area of the destination frame window.

Remarks

Causes a control bar to be docked to the frame window. The control bar will be docked to one of the sides of the frame window specified in the calls to both CControlBar::EnableDocking and CFrameWnd::EnableDocking. The side chosen is determined by nDockBarID.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::FloatControlBar


CFrameWnd::EnableDocking

void EnableDocking( DWORD dwDockStyle );

Parameters

dwDockStyle

Specifies which sides of the frame window can serve as docking sites for control bars. It can be one or more of the following:

  • CBRS_ALIGN_TOP Allows docking at the top of the client area.

  • CBRS_ALIGN_BOTTOM Allows docking at the bottom of the client area.

  • CBRS_ALIGN_LEFT Allows docking on the left side of the client area.

  • CBRS_ALIGN_RIGHT Allows docking on the right side of the client area.

  • CBRS_ALIGN_ANY Allows docking on any side of the client area.

Remarks

Call this function to enable dockable control bars in a frame window. By default, control bars will be docked to a side of the frame window in the following order: top, bottom, left, right.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CControlBar::EnableDocking, CFrameWnd::DockControlBar, CFrameWnd::FloatControlBar


CFrameWnd::EndModalState

virtual void EndModalState( );

Remarks

Call this member function to change a frame window from modal to modeless. EndModalState enables all of the windows disabled by BeginModalState.


CFrameWnd::FloatControlBar

CFrameWnd* FloatControlBar( CControlBar * pBar, CPoint point, DWORD dwStyle = CBRS_ALIGN_TOP );

Return Value

Pointer to the current frame window.

Parameters

pBar

Points to the control bar to be floated.

point

The location, in screen coordinates, where the top left corner of the control bar will be placed.

dwStyle

Specifies whether to align the control bar horizontally or vertically within its new frame window. It can be any one of the following:

  • CBRS_ALIGN_TOP Orients the control bar vertically.

  • CBRS_ALIGN_BOTTOM Orients the control bar vertically.

  • CBRS_ALIGN_LEFT Orients the control bar horizontally.

  • CBRS_ALIGN_RIGHT Orients the control bar horizontally.

    If styles are passed specifying both horizontal and vertical orientation, the toolbar will be oriented horizontally.

Remarks

Call this function to cause a control bar to not be docked to the frame window. Typically, this is done at application startup when the program is restoring settings from the previous execution.

This function is called by the framework when the user causes a drop operation by releasing the left mouse button while dragging the control bar over a location that is not available for docking.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::DockControlBar


CFrameWnd::GetActiveDocument

virtual CDocument* GetActiveDocument( );

Return Value

A pointer to the current CDocument. If there is no current document, returns NULL.

Remarks

Call this member function to obtain a pointer to the current CDocument attached to the current active view.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::GetActiveView


CFrameWnd::GetActiveFrame

virtual CFrameWnd* GetActiveFrame( );

Return Value

A pointer to the active MDI child window. If the application is an SDI application, or the MDI frame window has no active document, the implicit this pointer will be returned.

Remarks

Call this member function to obtain a pointer to the active multiple document interface (MDI) child window of an MDI frame window.

If there is no active MDI child or the application is a single document interface (SDI), the implicit this pointer is returned.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::GetActiveView, CFrameWnd::GetActiveDocument, CMDIFrameWnd


CFrameWnd::GetActiveView

CView* GetActiveView( ) const;

Return Value

A pointer to the current CView. If there is no current view, returns NULL.

Remarks

Call this member function to obtain a pointer to the active view (if any) attached to a frame window (CFrameWnd).

This function returns NULL when called for an MDI main frame window (CMDIFrameWnd). In an MDI application, the MDI main frame window does not have a view associated with it. Instead, each individual child window (CMDIChildWnd) has one or more associated views. The active view in an MDI application can be obtained by first finding the active MDI child window and then finding the active view for that child window. The active MDI child window can be found by calling the function MDIGetActive or GetActiveFrame as demonstrated in the following:

CMDIFrameWnd *pFrame =
             (CMDIFrameWnd*)AfxGetApp()->m_pMainWnd;

// Get the active MDI child window.
CMDIChildWnd *pChild =
             (CMDIChildWnd *) pFrame->GetActiveFrame();

// or CMDIChildWnd *pChild = pFrame->MDIGetActive();

// Get the active view attached to the active MDI child
// window.
CMyView *pView = (CMyView *) pChild->GetActiveView();

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::SetActiveView, CFrameWnd::GetActiveDocument


CFrameWnd::GetControlBar

CControlBar* GetControlBar( UINT nID );

Return Value

A pointer to the control bar that is associated with the ID.

Parameters

nID

The ID number of a control bar.

Remarks

Call GetControlBar to gain access to the control bar that is associated with the ID. GetControlBar will return the control bar even if it is floating and thus is not currently a child window of the frame.


CFrameWnd::GetDockState

void GetDockState( CDockState& state ) const;

Parameters

state

Contains the current state of the frame window's control bars upon return.

Remarks

Call this member function to store state information about the frame window's control bars in a CDockState object. You can then write the contents of CDockState to storage using CDockState::SaveState or Serialize. If you later want to restore the control bars to a previous state, load the state with CDockState::LoadState or Serialize, then call SetDockState to apply the previous state to the frame window's control bars.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::SetDockState, CDockState, CDockState::SaveState, CObject::Serialize


CFrameWnd::GetMessageBar

virtual CWnd* GetMessageBar( );

Return Value

Pointer to the status-bar window.

Remarks

Call this member function to get a pointer to the status bar.


CFrameWnd::GetMessageString

virtual void GetMessageString( UINT nID, CString& rMessage ) const;

Parameters

nID

Resource ID of the desired message.

rMessage

CString object into which to place the message.

Remarks

Override this function to provide custom strings for command IDs. The default implementation simply loads the string specified by nID from the resource file. This function is called by the framework when the message string in the status bar needs updating.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::SetMessageText


CFrameWnd::InitialUpdateFrame

void InitialUpdateFrame( CDocument* pDoc, BOOL bMakeVisible );

Parameters

pDoc

Points to the document to which the frame window is associated. Can be NULL.

bMakeVisible

If TRUE, indicates that the frame should become visible and active. If FALSE, no descendants are made visible.

Remarks

Call IntitialUpdateFrame after creating a new frame with Create. This causes all views in that frame window to receive their OnInitialUpdate calls.

Also, if there was not previously an active view, the primary view of the frame window is made active. The primary view is a view with a child ID of AFX_IDW_PANE_FIRST. Finally, the frame window is made visible if bMakeVisible is nonzero. If bMakeVisible is 0, the current focus and visible state of the frame window will remain unchanged. It is not necessary to call this function when using the framework's implementation of File New and File Open.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CView::OnInitialUpdate, CFrameWnd::SetActiveView, CDocTemplate::CreateNewFrame


CFrameWnd::InModalState

BOOL InModalState( ) const;

Return Value

Nonzero if yes; otherwise 0.

Remarks

Call this member function to check if a frame window is modal or modeless.


CFrameWnd::IsTracking

BOOL IsTracking( ) const;

Return Value

Nonzero if a splitter operation is in progress; otherwise 0.

Remarks

Call this member function to determine if the splitter bar in the window is currently being moved.


CFrameWnd::LoadAccelTable

BOOL LoadAccelTable( LPCTSTR lpszResourceName );

Return Value

Nonzero if the accelerator table was successfully loaded; otherwise 0.

Parameters

lpszResourceName

Identifies the name of the accelerator resource. Use MAKEINTRESOURCE if the resource is identified with an integer ID.

Remarks

Call to load the specified accelerator table. Only one table can be loaded at a time.

Accelerator tables loaded from resources are freed automatically when the application terminates.

If you call LoadFrame to create the frame window, the framework loads an accelerator table along with the menu and icon resources, and a subsequent call to this member function is then unnecessary.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::LoadFrame, ::LoadAccelerators


CFrameWnd::LoadBarState

void LoadBarState( LPCTSTR lpszProfileName );

Parameters

lpszProfileName

Name of a section in the initialization file or a key in the Windows registry where state information is stored.

Remarks

Call this function to restore the settings of each control bar owned by the frame window. This information is written to the initialization file using SaveBarState. Information restored includes visibility, horizontal/vertical orientation, docking state, and control-bar position.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::SaveBarState, CWinApp::SetRegistryKey, CWinApp::m_pszProfileName


CFrameWnd::LoadFrame

virtual BOOL LoadFrame( UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL );

Parameters

nIDResource

The ID of shared resources associated with the frame window.

dwDefaultStyle

The frame’s style. Include the FWS_ADDTOTITLE style if you want the title bar to automatically display the name of the document represented in the window.

pParentWnd

A pointer to the frame’s parent.

pContext

A pointer to a CCreateContext structure. This parameter can be NULL.

Remarks

Construct a CFrameWnd object in two steps. First invoke the constructor, which constructs the CFrameWnd object, then call LoadFrame, which loads the Windows frame window and associated resources and attaches the frame window to the CFrameWnd object. The nIDResource parameter specifies the menu, the accelerator table, the icon, and the string resource of the title for the frame window.

Use the Create member function rather than LoadFrame when you want to specify all of the frame window’s creation parameters.

The framework calls LoadFrame when it creates a frame window using a document template object.

The framework uses the pContext argument to specify the objects to be connected to the frame window, including any contained view objects. You can set the pContext argument to NULL when you call LoadFrame.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CDocTemplate, CFrameWnd::Create, CFrameWnd::CFrameWnd, CWnd::PreCreateWindow


CFrameWnd::NegotiateBorderSpace

virtual BOOL NegotiateBorderSpace( UINT nBorderCmd, LPRECT lpRectBorder );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nBorderCmd

Contains one of the following values from the enum BorderCmd:

  • borderGet = 1

  • borderRequest = 2

  • borderSet = 3

lpRectBorder

Pointer to a RECT structure or a CRect object that specifies the coordinates of the border.

Remarks

Call this member function to negotiate border space in a frame window during OLE inplace activation. This member function is the CFrameWnd implementation of OLE border space negotiation.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also IOleInPlaceUIWindow


CFrameWnd::OnContextHelp

afx_msg void OnContextHelp( );

Remarks

To enable context-sensitive help, you must add an

ON_COMMAND( ID_CONTEXT_HELP, OnContextHelp )

statement to your CFrameWnd class message map and also add an accelerator-table entry, typically SHIFT+F1, to enable this member function.

If your application is an OLE Container, OnContextHelp puts all in-place items contained within the frame window object into Help mode. The cursor changes to an arrow and a question mark, and the user can then move the mouse pointer and press the left mouse button to select a dialog box, window, menu, or command button. This member function calls the Windows function WinHelp with the Help context of the object under the cursor.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnHelp, CWinApp::WinHelp


CFrameWnd::OnCreateClient

virtual BOOL OnCreateClient( LPCREATESTRUCT lpcs, CCreateContext* pContext );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpcs

A pointer to a Windows CREATESTRUCT structure.

pContext

A pointer to a CCreateContext structure.

Remarks

Called by the framework during the execution of OnCreate. Never call this function.

The default implementation of this function creates a CView object from the information provided in pContext, if possible.

Override this function to override values passed in the CCreateContext object or to change the way controls in the main client area of the frame window are created. The CCreateContext members you can override are described in the CCreateContext class.

Note Do not replace values passed in the CREATESTRUCT structure. They are for informational use only. If you want to override the initial window rectangle, for example, override the CWnd member function PreCreateWindow.


CFrameWnd::OnSetPreviewMode

virtual void OnSetPreviewMode( BOOL bPreview, CPrintPreviewState* pModeStuff );

Parameters

bPreview

Specifies whether or not to place the application in print-preview mode. Set to TRUE to place in print preview, FALSE to cancel preview mode.

pModeStuff

A pointer to a CPrintPreviewState structure.

Remarks

Call this member function to set the application’s main frame window into and out of print-preview mode.

The default implementation disables all standard toolbars and hides the main menu and the main client window. This turns MDI frame windows into temporary SDI frame windows.

Override this member function to customize the hiding and showing of control bars and other frame window parts during print preview. Call the base class implementation from within the overridden version.


CFrameWnd::RecalcLayout

virtual void RecalcLayout( BOOL bNotify = TRUE );

Parameters

bNotify

Determines whether the active in-place item for the frame window receives notification of the layout change. If TRUE, the item is notified; otherwise FALSE.

Remarks

Called by the framework when the standard control bars are toggled on or off or when the frame window is resized. The default implementation of this member function calls the CWnd member function RepositionBars to reposition all the control bars in the frame as well as in the main client window (usually a CView or MDICLIENT).

Override this member function to control the appearance and behavior of control bars after the layout of the frame window has changed. For example, call it when you turn control bars on or off or add another control bar.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::RepositionBars


CFrameWnd::SaveBarState

void SaveBarState( LPCTSTR lpszProfileName ) const;

Parameters

lpszProfileName

Name of a section in the initialization file or a key in the Windows registry where state information is stored.

Remarks

Call this function to store information about each control bar owned by the frame window. This information can be read from the initialization file using LoadBarState. Information stored includes visibility, horizontal/vertical orientation, docking state, and control bar position.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::LoadBarState, CWinApp::SetRegistryKey, CWinApp::m_pszProfileName


CFrameWnd::SetActiveView

void SetActiveView( CView* pViewNew, BOOL bNotify = TRUE );

Parameters

pViewNew

Specifies a pointer to a CView object, or NULL for no active view.

bNotify

Specifies whether the view is to be notified of activation. If TRUE, OnActivateView is called for the new view; if FALSE, it is not.

Remarks

Call this member function to set the active view. The framework will call this function automatically as the user changes the focus to a view within the frame window. You can explicitly call SetActiveView to change the focus to the specified view.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::GetActiveView, CView::OnActivateView, CFrameWnd::GetActiveDocument


CFrameWnd::SetDockState

void SetDockState( const CDockState& state );

Parameters

state

Apply the stored state to the frame window's control bars.

Remarks

Call this member function to apply state information stored in a CDockState object to the frame window's control bars. To restore a previous state of the control bars, you can load the stored state with CDockState::LoadState or Serialize, then use SetDockState to apply it to the frame window's control bars. The previous state is stored in the CDockState object with GetDockState

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::GetDockState, CDockState, CDockState::LoadState, CObject::Serialize


CFrameWnd::SetMessageText

void SetMessageText( LPCTSTR lpszText );

void SetMessageText( UINT nID );

Parameters

lpszText

Points to the string to be placed on the status bar.

nID

String resource ID of the string to be placed on the status bar.

Remarks

Call this function to place a string in the status-bar pane that has an ID of 0. This is typically the leftmost, and longest, pane of the status bar.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CStatusBar


CFrameWnd::ShowControlBar

void ShowControlBar( CControlBar* pBar, BOOL bShow, BOOL bDelay );

Parameters

pBar

Pointer to the control bar to be shown or hidden.

bShow

If TRUE, specifies that the control bar is to be shown. If FALSE, specifies that the control bar is to be hidden.

bDelay

If TRUE, delay showing the control bar. If FALSE, show the control bar immediately.

Remarks

Call this member function to show or hide the control bar.


CFrameWnd::ShowOwnedWindows

void ShowOwnedWindows( BOOL bShow );

Parameters

bShow

Specifies whether the owned windows are to be shown or hidden.

Remarks

Call this member function to show all windows that are descendants of the CFrameWnd object.


CFrameWnd::m_bAutoMenuEnable

Remarks

When this data member is enabled (which is the default), menu items that do not have ON_UPDATE_COMMAND_UI or ON_COMMAND handlers will be automatically disabled when the user pulls down a menu.

Menu items that have an ON_COMMAND handler but no ON_UPDATE_COMMAND_UI handler will be automatically enabled.

When this data member is set, menu items are automatically enabled in the same way that toolbar buttons are enabled.

This data member simplifies the implementation of optional commands based on the current selection and reduces the need for an application to write ON_UPDATE_COMMAND_UI handlers for enabling and disabling menu items.

CFrameWnd Overview | Class Members | Hierarchy Chart

See Also CCmdUI, CCmdTarget


CFrameWnd::rectDefault

Remarks

Pass this static CRect as a parameter when creating a window to allow Windows to choose the window’s initial size and position.


CFtpConnection

The MFC class CFtpConnection both manages your FTP connection to an Internet server and allows direct manipulation of directories and files on that server. FTP is one of the three Internet services recognized by the MFC WinInet classes.

To communicate with an FTP Internet server, you must first create an instance of CInternetSession, and then create a CFtpConnection object. You never create a CFtpConnection object directly; rather, call CInternetSession::GetFtpConnection, which creates the CFtpConnection object and returns a pointer to it.

To learn more about how CFtpConnection works with the other MFC Internet classes, see the article Internet Programming with WinInet in Visual C++ Programmer's Guide. For more information about communicating with the the other two supported services, HTTP and gopher, see the classes CHttpConnection and CGopherConnection.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample FTPTREE

See Also CInternetConnection, CInternetSession


CFtpConnection Class Members

Construction

CFtpConnection Constructs a CFtpConnection object.

Operations

SetCurrentDirectory | Sets the current FTP directory.
GetCurrentDirectory | Gets the current directory for this connection.
GetCurrentDirectoryAsURL | Gets the current directory for this connection as a URL.
RemoveDirectory | Removes the specified directory from the server.
CreateDirectory | Creates a directory on the server.
Rename | Renames a file on the server.
Remove | Removes a file from the server.
PutFile | Places a file on the server.
GetFile | Gets a file from the connected server
OpenFile | Opens a file on the connected server.
Close | Closes the connection to the server.

CFtpConnection Overview | Base Class Members | Hierarchy Chart

See Also CInternetConnection


CFtpConnection::CFtpConnection

CFtpConnection( );

Remarks

This member function is called to construct a CFtpConnection object. You never create a CFtpConnection object directly. Instead, call CInternetSession::GetFtpConnection, which creates the CFptConnection object.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetSession::GetFtpConnection, CFtpFileFind, CGopherConnection, CHttpConnection, CInternetConnection


CFtpConnection::Close

virtual void Close( );

Remarks

Call this member function to close the connection to the server. The connection will be closed by the CFtpConnection object’s destructor, but you should close the connection explicitly to avoid a diagnostic message.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CFtpFileFind, CGopherConnection, CHttpConnection, CInternetConnection


CFtpConnection::CreateDirectory

BOOL CreateDirectory( LPCTSTR pstrDirName );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Windows function GetLastError may be called to determine the cause of the error.

Parameters

pstrDirName

A pointer to a string containing the name of the directory to create.

Remarks

Call this member function to create a directory on the connected server.

Use GetCurrentDirectory to determine the current working directory for this connection to the server. Do not assume that the remote system has connected you to the root directory.

The pstrDirName parameter can be either a partially or a fully qualified filename relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. CreateDirectory translates the directory name separators to the appropriate characters before they are used.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetConnection


CFtpConnection::GetCurrentDirectory

BOOL GetCurrentDirectory( CString& strDirName ) const;

BOOL GetCurrentDirectory( LPTSTR pstrDirName, LPDWORD lpdwLen ) const;

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

strDirName

A reference to a string that will receive the name of the directory.

pstrDirName

A pointer to a string that will receive the name of the directory.

lpdwLen

A pointer to a DWORD that contains the following information:

On entry | The size of the buffer referenced by pstrDirName.
On return | The number of characters stored to pstrDirName. If the member function fails and ERROR_INSUFFICIENT_BUFFER is returned, then lpdwLen contains the number of bytes that the application must allocate in order to receive the string.

Remarks

Call this member function to get the name of the current directory. To get the directory name as a URL instead, call GetCurrentDirectoryAsURL.

The parameters pstrDirName or strDirName can be either partially qualified filenames relative to the current directory or fully qualified. A backslash (\) or forward slash (/) can be used as the directory separator for either name. GetCurrentDirectory translates the directory name separators to the appropriate characters before they are used.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CFtpConnection::GetCurrentDirectoryAsURL, CInternetConnection


CFtpConnection::GetCurrentDirectoryAsURL

BOOL GetCurrentDirectoryAsURL( CString& strDirName ) const;

BOOL GetCurrentDirectoryAsURL( LPTSTR pstrDirName, LPDWORD lpdwLen ) const;

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

strDirName

A reference to a string that will receive the name of the directory.

pstrDirName

A pointer to a string that will receive the name of the directory.

lpdwLen

A pointer to a DWORD that contains the following information:

On entry | The size of the buffer referenced by pstrDirName.
On return | The number of characters stored to pstrDirName. If the member function fails and ERROR_INSUFFICIENT_BUFFER is returned, then lpdwLen contains the number of bytes that the application must allocate in order to receive the string.

Remarks

Call this member function to get the current directory’s name as a URL. GetCurrentDirectoryAsURL behaves the same as GetCurrentDirectory

The parameter strDirName can be either partially qualified filenames relative to the current directory or fully qualified. A backslash (\) or forward slash (/) can be used as the directory separator for either name. GetCurrentDirectoryAsURL translates the directory name separators to the appropriate characters before they are used.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CFtpConnection::GetCurrentDirectory, CInternetConnection


CFtpConnection::GetFile

BOOL GetFile( LPCTSTR pstrRemoteFile, LPCTSTR pstrLocalFile, BOOL bFailIfExists = TRUE, DWORD dwAttributes = FILE_ATTRIBUTE_NORMAL, DWORD dwFlags = FTP_TRANSFER_TYPE_BINARY, DWORD dwContext = 1 );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

pstrRemoteFile

A pointer to a null-terminated string containing the name of a file to retrieve from the FTP server.

pstrLocalFile

A pointer to a null-terminated string containing the name of the file to create on the local system.

bFailIfExists

Indicates whether the file name may already be used by an existing file. If the local file name already exists, and this parameter is TRUE, GetFile fails. Otherwise, GetFile will erase the existing copy of the file.

dwAttributes

Indicates the attributes of the file. This can be any combination of the following FILE_ATTRIBUTE_* flags.

  • FILE_ATTRIBUTE_ARCHIVE The file is an archive file. Applications use this attribute to mark files for backup or removal.

  • FILE_ATTRIBUTE_COMPRESSED The file or directory is compressed. For a file, compression means that all of the data in the file is compressed. For a directory, compression is the default for newly created files and subdirectories.

  • FILE_ATTRIBUTE_DIRECTORY The file is a directory.

  • FILE_ATTRIBUTE_NORMAL The file has no other attributes set. This attribute is valid only if used alone. All other file attributes override FILE_ATTRIBUTE_NORMAL:

  • FILE_ATTRIBUTE_HIDDEN The file is hidden. It is not to be included in an ordinary directory listing.

  • FILE_ATTRIBUTE_READONLY The file is read only. Applications can read the file but cannot write to it or delete it.

  • FILE_ATTRIBUTE_SYSTEM The file is part of or is used exclusively by the operating system.

  • FILE_ATTRIBUTE_TEMPORARY The file is being used for temporary storage. Applications should write to the file only if absolutely necessary. Most of the file’s data remains in memory without being flushed to the media because the file will soon be deleted.

dwFlags

Specifies the conditions under which the transfer occurs. This parameter can be any of the dwFlags values described in FtpGetFile in the Platform SDK.

dwContext

The context identifier for the file retrieval. See Remarks for more information about dwContext.

Remarks

Call this member function to get a file from an FTP server and store it on the local machine.

GetFile is a high-level routine that handles all of the overhead associated with reading a file from an FTP server and storing it locally. Applications that only retrieve file data, or that require close control over the file transfer, should use OpenFile and CInternetFile::Read instead.

If dwFlags is FILE_TRANSFER_TYPE_ASCII, translation of file data also converts control and formatting characters to Windows equivalents. The default transfer is binary mode, where the file is downloaded in the same format as it is stored on the server.

Both pstrRemoteFile and pstrLocalFile can be either partially qualified filenames relative to the current directory or fully qualified. A backslash (\) or forward slash (/) can be used as the directory separator for either name. GetFile translates the directory name separators to the appropriate characters before they are used.

Override the dwContext default to set the context identifier to a value of your choosing. The context identifier is associated with this specific operation of the CFtpConnection object created by its CInternetSession object. The value is returned to CInternetSession::OnStatusCallback to provide status on the operation with which it is identified. See the article Internet First Steps: WinInet for more information about the context identifier.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetConnection


CFtpConnection::OpenFile

CInternetFile* OpenFile( LPCTSTR pstrFileName, DWORD dwAccess = GENERIC_READ, DWORD dwFlags = FTP_TRANSFER_TYPE_BINARY, DWORD dwContext = 1 );

Return Value

A pointer to a CInternetFile object.

Parameters

pstrFileName

A pointer to a string containing the name of the file to be opened.

dwAccess

Determines how the file will be accessed. Can be either GENERIC_READ or GENERIC_WRITE, but not both.

dwFlags

Specifies the conditions under which subsequent transfers occur. This can be any of the following FTP_TRANSFER_* constants:

  • FTP_TRANSFER_TYPE_ASCII The file transfers using FTP ASCII (Type A) transfer method. Converts control and formatting information to local equivalents.

  • FTP_TRANSFER_TYPE_BINARY The file transfers data using FTP’s Image (Type I) transfer method. The file transfers data exactly as it exists, with no changes. This is the default transfer method.

dwContext

The context identifier for opening the file. See Remarks for more information about dwContext.

Remarks

Call this member function to open a file located on an FTP server for reading or writing. OpenFile should be used in the following situations:

  • An application has data that needs to be sent and created as a file on the FTP server, but that data is not in a local file. Once OpenFile opens a file, the application uses CInternetFile::Write to send the FTP file data to the server.

  • An application must retrieve a file from the server and place it into application-controlled memory, instead of writing it to disk. The application uses CInternetFile::Read after using OpenFile to open the file.

  • An application needs a fine level of control over a file transfer. For example, the application may want to display a progress control indicate the progress of the file transfer status while downloading a file.

After calling OpenFile and until calling Close, the application can only call CInternetFile::Read, CInternetFile::Write, Close, or CFtpFileFind::FindFile. Calls to other FTP functions for the same FTP session will fail and set the error code to FTP_ETRANSFER_IN_PROGRESS.

The pstrFileName parameter can be either a partially qualified filename relative to the current directory or fully qualified. A backslash (\) or forward slash (/) can be used as the directory separator for either name. OpenFile translates the directory name separators to the appropriate characters before using it.

Override the dwContext default to set the context identifier to a value of your choosing. The context identifier is associated with this specific operation of the CFtpConnection object created by its CInternetSession object. The value is returned to CInternetSession::OnStatusCallback to provide status on the operation with which it is identified. See the article Internet First Steps: WinInet for more information about the context identifier.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetConnection, CFtpConnection::GetFile, CGopherConnection::OpenFile, CInternetFile::Write, CInternetFile::Read


CFtpConnection::PutFile

BOOL PutFile( LPCTSTR pstrLocalFile, LPCTSTR pstrRemoteFile, DWORD dwFlags = FTP_TRANSFER_TYPE_BINARY, DWORD dwContext = 1 );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

pstrLocalFile

A pointer to a string containing the name of the file to send from the local system.

pstrRemoteFile

A pointer to a string containing the name of the file to create on the FTP server.

dwFlags

Specifies the conditions under which the transfer of the file occurs. Can be any of the FTP_TRANSFER_* constants described in OpenFile.

dwContext

The context identifier for placing the file. See Remarks for more information about dwContext.

Remarks

Call this member function to store a file on an FTP server.

PutFile is a high-level routine that handles all of the operations associated with storing a file on an FTP server. Applications that only send data, or that require closer control over the file transfer, should use OpenFile and CInternetFile::Write.

Override the dwContext default to set the context identifier to a value of your choosing. The context identifier is associated with this specific operation of the CFtpConnection object created by its CInternetSession object. The value is returned to CInternetSession::OnStatusCallback to provide status on the operation with which it is identified. See the article Internet First Steps: WinInet for more information about the context identifier.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetConnection


CFtpConnection::Remove

BOOL Remove( LPCTSTR pstrFileName );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

pstrFileName

A pointer to a string containing the file name to remove.

Remarks

Call this member function to delete the specified file from the connected server.

The pstrFileName parameter can be either a partially qualified filename relative to the current directory or fully qualified. A backslash (\) or forward slash (/) can be used as the directory separator for either name. The Remove function translates the directory name separators to the appropriate characters before they are used.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetConnection


CFtpConnection::RemoveDirectory

BOOL RemoveDirectory( LPCTSTR pstrDirName );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

pstrDirName

A pointer to a string containing the directory to be removed.

Remarks

Call this member function to remove the specified directory from the connected server.

Use GetCurrentDirectory to determine the server’s current working directory. Do not assume that the remote system has connected you to the root directory.

The pstrDirName parameter can be either a partially or fully qualified filename relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. RemoveDirectory translates the directory name separators to the appropriate characters before they are used.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetConnection


CFtpConnection::Rename

BOOL Rename( LPCTSTR pstrExisting, LPCTSTR pstrNew );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

pstrExisting

A pointer to a string containing the current name of the file to be renamed.

pstrNew

A pointer to a string containing the file’s new name.

Remarks

Call this member function to rename the specified file on the connected server.

The pstrExisting and pstrNew parameters can be either a partially qualified filename relative to the current directory or fully qualified. A backslash (\) or forward slash (/) can be used as the directory separator for either name. Rename translates the directory name separators to the appropriate characters before they are used.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetConnection


CFtpConnection::SetCurrentDirectory

BOOL SetCurrentDirectory( LPCTSTR pstrDirName );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

pstrDirName

A pointer to a string containing the name of the directory.

Remarks

Call this member function to change to a different directory on the FTP server.

The pstrDirName parameter can be either a partially or fully qualified filename relative to the current directory. A backslash (\) or forward slash (/) can be used as the directory separator for either name. SetCurrentDirectory translates the directory name separators to the appropriate characters before they are used.

Use GetCurrentDirectory to determine an FTP server’s current working directory. Do not assume that the remote system has connected you to the root directory.

CFtpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetConnection


CFtpFileFind

Class CFtpFileFind aids in Internet file searches of FTP servers. CFtpFileFind includes member functions that begin a search, locate a file, and return the URL or other descriptive information about the file.

Other MFC classes designed for Internet and local file searched include CGopherFileFind and CFileFind. Together with CFtpFileFind, these classes provide a seamless mechanism for the client to find specific files, regardless of the server protocol or file type (either a local machine or a remote server). Note that there is no MFC class for searching on HTTP servers because HTTP does not support the direct file manipulation required for searches.

For more information about how to use CFtpFileFind and the other WinInet classes, see the article Internet Programming with WinInet in Visual C++ Programmer's Guide.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

See Also CGopherFileFind, CInternetFile, CGopherFile, CHttpFile


CFtpFileFind Class Members

Construction

CFtpFileFind Constructs a CFtpFileFind object.

Operations

FindFile | Finds a file on a FTP server.
FindNextFile | Continues a file search from a previous call to FindFile.
GetFileURL | Gets the URL, including path, of the found file.

CFtpFileFind Overview | Base Class Members | Hierarchy Chart

See Also CFtpFileFind, CGopherFileFind, CInternetFile, CGopherFile, CHttpFile


CFtpFileFind::CFtpFileFind

CFtpFileFind( CFtpConnection* pConnection, DWORD dwContext = 1 );

Parameters

pConnection

A pointer to a CFtpConnection object. You can obtain an FTP connection by calling CInternetSession::GetFtpConnection.

dwContext

The context identifier for the CFtpFileFind object. See Remarks for more information about this parameter.

Remarks

This member function is called to construct a CFtpFileFind object.

The default value for dwContext is sent by MFC to the CFtpFileFind object from the CInternetSession object that created the CFtpFileFind object.You can override the default to set the context identifier to a value of your choosing. The context identifier is returned to CInternetSession::OnStatusCallback to provide status on the object with which it is identified. See the article Internet First Steps: WinInet in the Visual C++ Programmer's Guide for more information about the context identifier.

CFtpFileFind Overview | Class Members | Hierarchy Chart

See Also CGopherFileFind, CFileFind


CFtpFileFind::FindFile

virtual BOOL FindFile( LPCTSTR pstrName = NULL, DWORD dwFlags = INTERNET_FLAG_RELOAD );

Return Value

Nonzero if successful; otherwise 0. To get extended error information, call the Win32 function GetLastError.

Parameters

pstrName

A pointer to a string containing the name of the file to find. If NULL, the call will perform a wildcard search (*).

dwFlags

The flags describing how to handle this session. These flags can be combined with the bitwise OR operator (|) and are as follows:

  • INTERNET_FLAG_RELOAD Get the data from the wire even if it is locally cached. This is the default flag.

  • INTERNET_FLAG_DONT_CACHE Do not cache the data, either locally or in any gateways.

  • INTERNET_FLAG_RAW_DATA Override the default to return the raw data ( WIN32_FIND_DATA structures for FTP).

  • INTERNET_FLAG_SECURE Secures transactions on the wire with Secure Sockets Layer or PCT. This flag is applicable to HTTP requests only.

  • INTERNET_FLAG_EXISTING_CONNECT If possible, reuse the existing connections to the server for new FindFile requests instead of creating a new session for each request.

Remarks

Call this member function to find an FTP file.

After calling FindFile to retrieve the first FTP file, you can call FindNextFile to retrieve subsequent FTP files.

CFtpFileFind Overview | Class Members | Hierarchy Chart

See Also CFtpFileFind::FindNextFile, CFileFind


CFtpFileFind::FindNextFile

virtual BOOL FindNextFile( );

Return Value

Nonzero if there are more files; zero if this is the last file, and the previous call to either FindFile or FindNextFile returned nonzero. To get extended error information, call the Win32 function GetLastError.

Remarks

Call this member function to continue a file search begun with a call to the FindFile member function. You must call this function at least once before calling any attribute function.

FindNextFile wraps the Win32 function FindNextFile.

CFtpFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind


CFtpFileFind::GetFileURL

CString GetFileURL( ) const;

Return Value

The file and path of the Universal Resource Locator (URL) .

Remarks

Call this member function to get the URL of the specified file.

GetFileURL is similar to the member function CFileFind::GetFilePath, except that it returns the URL in the form ftp://moose/dir/file.txt.

CFtpFileFind Overview | Class Members | Hierarchy Chart

See Also CFtpFileFind::FindFile, CFileFind


CGdiObject

The CGdiObject class provides a base class for various kinds of Windows graphics device interface (GDI) objects such as bitmaps, regions, brushes, pens, palettes, and fonts. You never create a CGdiObject directly. Rather, you create an object from one of its derived classes, such as CPen or CBrush.

For more information on CGdiObject, see Graphic Objects in Visual C++ Programmer's Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CBitmap, CBrush, CFont, CPalette, CPen, CRgn


CGdiObject Class Members

Data Members

m_hObject A HANDLE containing the HBITMAP, HPALETTE, HRGN, HBRUSH, HPEN, or HFONT attached to this object.

Construction

CGdiObject Constructs a CGdiObject object.

Operations

GetSafeHandle | Returns m_hObject unless this is NULL, in which case NULL is returned.
FromHandle | Returns a pointer to a CGdiObject object given a handle to a Windows GDI object.
Attach | Attaches a Windows GDI object to a CGdiObject object.
Detach | Detaches a Windows GDI object from a CGdiObject object and returns a handle to the Windows GDI object.
DeleteObject | Deletes the Windows GDI object attached to the CGdiObject object from memory by freeing all system storage associated with the object.
DeleteTempMap | Deletes any temporary CGdiObject objects created by FromHandle.
GetObject | Fills a buffer with data that describes the Windows GDI object attached to the CGdiObject object.
CreateStockObject | Retrieves a handle to one of the Windows predefined stock pens, brushes, or fonts.
UnrealizeObject | Resets the origin of a brush or resets a logical palette.
GetObjectType | Retrieves the type of the GDI object.


CGdiObject::Attach

BOOL Attach( HGDIOBJ hObject );

Return Value

Nonzero if attachment is successful; otherwise 0.

Parameters

hObject

A HANDLE to a Windows GDI object (for example, HPEN or HBRUSH).

Remarks

Attaches a Windows GDI object to a CGdiObject object.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CGdiObject::Detach


CGdiObject::CGdiObject

CGdiObject( );

Remarks

Constructs a CGdiObject object. You never create a CGdiObject directly. Rather, you create an object from one of its derived classes, such as CPen or Cbrush.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CPen, CBrush, CFont, CBitmap, CRgn, CPalette


CGdiObject::CreateStockObject

BOOL CreateStockObject( int nIndex );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nIndex

A constant specifying the type of stock object desired. See the parameter fnObject for GetStockObject in the Win32 SDK for a description of appropriate values.

Remarks

Retrieves a handle to one of the predefined stock Windows GDI pens, brushes, or fonts, and attaches the GDI object to the CGdiObject object. Call this function with one of the derived classes that corresponds to the Windows GDI object type, such as CPen for a stock pen.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CPen::CPen, CBrush::CBrush, CFont::CFont, CPalette::CPalette


CGdiObject::DeleteObject

BOOL DeleteObject( );

Return Value

Nonzero if the GDI object was successfully deleted; otherwise 0.

Remarks

Deletes the attached Windows GDI object from memory by freeing all system storage associated with the Windows GDI object. The storage associated with the CGdiObject object is not affected by this call. An application should not call DeleteObject on a CGdiObject object that is currently selected into a device context.

When a pattern brush is deleted, the bitmap associated with the brush is not deleted. The bitmap must be deleted independently.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CGdiObject::Detach


CGdiObject::DeleteTempMap

static void PASCAL DeleteTempMap( );

Remarks

Called automatically by the CWinApp idle-time handler, DeleteTempMap deletes any temporary CGdiObject objects created by FromHandle. DeleteTempMap detaches the Windows GDI object attached to a temporary CGdiObject object before deleting the CGdiObject object.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CGdiObject::Detach, CGdiObject::FromHandle


CGdiObject::Detach

HGDIOBJ Detach( );

Return Value

A HANDLE to the Windows GDI object detached; otherwise NULL if no GDI object is attached.

Remarks

Detaches a Windows GDI object from a CGdiObject object and returns a handle to the Windows GDI object.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CGdiObject::Attach


CGdiObject::FromHandle

static CGdiObject* PASCAL FromHandle( HGDIOBJ hObject );

Return Value

A pointer to a CGdiObject that may be temporary or permanent.

Parameters

hObject

A HANDLE to a Windows GDI object.

Remarks

Returns a pointer to a CGdiObject object given a handle to a Windows GDI object. If a CGdiObject object is not already attached to the Windows GDI object, a temporary CGdiObject object is created and attached.

This temporary CGdiObject object is only valid until the next time the application has idle time in its event loop, at which time all temporary graphic objects are deleted. Another way of saying this is that the temporary object is only valid during the processing of one window message.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CGdiObject::DeleteTempMap


CGdiObject::GetObject

int GetObject( int nCount, LPVOID lpObject ) const;

Return Value

The number of bytes retrieved; otherwise 0 if an error occurs.

Parameters

nCount

Specifies the number of bytes to copy into the lpObject buffer.

lpObject

Points to a user-supplied buffer that is to receive the information.

Remarks

Fills a buffer with data that defines a specified object. The function retrieves a data structure whose type depends on the type of graphic object, as shown by the following list:

Object | Buffer type
CPen | LOGPEN
CBrush | LOGBRUSH
CFont | LOGFONT
CBitmap | BITMAP
CPalette | WORD
CRgn | Not supported

If the object is a CBitmap object, GetObject returns only the width, height, and color format information of the bitmap. The actual bits can be retrieved by using CBitmap::GetBitmapBits.

If the object is a CPalette object, GetObject retrieves a WORD that specifies the number of entries in the palette. The function does not retrieve the LOGPALETTE structure that defines the palette. An application can get information on palette entries by calling CPalette::GetPaletteEntries.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CBitmap::GetBitmapBits, CPalette::GetPaletteEntries


CGdiObject::GetObjectType

UINT GetObjectType( ) const;

Return Value

The type of the object, if successful; otherwise 0. The value can be one of the following:

  • OBJ_BITMAP Bitmap

  • OBJ_BRUSH Brush

  • OBJ_FONT Font

  • OBJ_PAL Palette

  • OBJ_PEN Pen

  • OBJ_EXTPEN Extended pen

  • OBJ_REGION Region

  • OBJ_DC Device context

  • OBJ_MEMDC Memory device context

  • OBJ_METAFILE Metafile

  • OBJ_METADC Metafile device context

  • OBJ_ENHMETAFILE Enhanced metafile

  • OBJ_ENHMETADC Enhanced-metafile device context

Remarks

Retrieves the type of the GDI object.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CGdiObject::GetObject, CDC::SelectObject


CGdiObject::GetSafeHandle

HGDIOBJ GetSafeHandle( ) const;

Return Value

A HANDLE to the attached Windows GDI object; otherwise NULL if no object is attached.

Remarks

Returns m_hObject unless this is NULL, in which case NULL is returned. This is part of the general handle interface paradigm and is useful when NULL is a valid or special value for a handle.


CGdiObject::UnrealizeObject

BOOL UnrealizeObject( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

Resets the origin of a brush or resets a logical palette. While UnrealizeObject is a member function of the CGdiObject class, it should be invoked only on CBrush or CPalette objects.

For CBrush objects, UnrealizeObject directs the system to reset the origin of the given brush the next time it is selected into a device context. If the object is a CPalette object, UnrealizeObject directs the system to realize the palette as though it had not previously been realized. The next time the application calls the CDC::RealizePalette function for the specified palette, the system completely remaps the logical palette to the system palette.

The UnrealizeObject function should not be used with stock objects. The UnrealizeObject function must be called whenever a new brush origin is set (by means of the CDC::SetBrushOrg function). The UnrealizeObject function must not be called for the currently selected brush or currently selected palette of any display context.

CGdiObject Overview | Class Members | Hierarchy Chart

See Also CDC::RealizePalette, CDC::SetBrushOrg


CGdiObject::m_hObject

Remarks

A HANDLE containing the HBITMAP, HRGN, HBRUSH, HPEN, HPALETTE, or HFONT attached to this object.


CGopherConnection

The MFC class CGopherConnection manages your connection to a gopher Internet server. The gopher service is one of three Internet services recognized by the MFC WinInet classes.

The class CGopherConnection contains a constructor and three additional member functions that manage the gopher service: OpenFile, CreateLocator, and GetAttribute.

To communicate with a gopher Internet server, you must first create an instance of CInternetSession, and then call CInternetSession::GetGopherConnection, which creates the CGopherConnection object and returns a pointer to it. You never create a CGopherConnection object directly.

To learn more about how CGopherConnection works with the other MFC Internet classes, see the article Internet Programming with WinInet in Visual C++ Programmer's Guide. For more information about using the the other two supported Internet services, FTP and HTTP see the classes CHttpConnection and CFtpConnection.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

See Also CFtpConnection, CHttpConnection, CInternetConnection, CGopherLocator, CGopherFile, CInternetSession


CGopherConnection Class Members

Construction

CGopherConnection Constructs a CGopherConnection object.

Operations

OpenFile | Opens a gopher file.
CreateLocator | Creates a CGopherLocator object to find files on a gopher server.
GetAttribute | Retrieves attribute information about the gopher object.

CGopherConnection Overview | Base Class Members | Hierarchy Chart

See Also CFtpConnection, CHttpConnection, CInternetConnection, CGopherFileFind


CGopherConnection::CGopherConnection

CGopherConnection( );

Remarks

This member function is called to construct a CGopherConnection object. You never create a CGopherConnection directly. Rather, call CInternetSession::GetGopherConnection, which creates a CGopherConnection object and returns a pointer to it.

CGopherConnection Overview | Class Members | Hierarchy Chart

See Also CFtpConnection, CHttpConnection, CInternetConnection


CGopherConnection::CreateLocator

CGopherLocator CreateLocator( LPCTSTR pstrDisplayString, LPCTSTR pstrSelectorString, DWORD dwGopherType );

static CGopherLocator CreateLocator(LPCTSTR pstrLocator );

static CGopherLocator CreateLocator( LPCTSTR pstrServerName, LPCTSTR pstrDisplayString, LPCTSTR pstrSelectorString, DWORD dwGopherType, INTERNET_PORT nPort = INTERNET_INVALID_PORT_NUMBER );

Return Value

A CGopherLocator object.

Parameters

pstrDisplayString

A pointer to a string containing the name of the gopher document or directory to be retrieved. If the pstrDisplayString parameter is NULL, the default directory for the gopher server is returned.

pstrSelectorString

A pointer to the selector string to be sent to the gopher server in order to retrieve an item. pstrSelectorString can be NULL.

dwGopherType

This specifies whether pstrSelectorString refers to a directory or document, and whether the request is gopher or gopher+. See the attributes for the structure GOPHER_FIND_DATA in the ActiveX SDK.

pstrLocator

A pointer to a string identifying the file to open. Generally, this string is returned from a call to CGopherFileFind::GetLocator.

pstrServerName

A pointer to a string containing the gopher server name.

nPort

The number identifying the Internet port for this connection.

Remarks

Call this member function to create a gopher locator to find or identify a file on a gopher server. The static version of the member function requires you to specify a server, while the non-static version uses the server name from the connection object.

In order to retrieve information from a gopher server, an application must first get a gopher locator. The application must then treat the locator as an opaque token (that is, the application can use the locator but not directly manipulate or compare it). Normally, the application uses the locator for calls to the CGopherFileFind::FindFile member function to retrieve a specific piece of information.

CGopherConnection Overview | Class Members | Hierarchy Chart

See Also CFtpConnection, CHttpConnection, CInternetConnection, CGopherLocator, CGopherFileFind


CGopherConnection::GetAttribute

BOOL GetAttribute( LPGOPHER_ATTRIBUTE_TYPE& lpType, CString strRequestedAttributes, CGopherLocator& refLocator );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

lpType

A pointer to a GOPHER_ATTRIBUTE_TYPE structure. See the ActiveX SDK for more information about this structure.

strRequestedAttributes

A space-delimited string specifying the names of the requested attributes.

refLocator

A reference to a CGopherLocator object.

Remarks

Call this member function to retrieve specific attribute information about an item from the gopher server.

CGopherConnection Overview | Class Members | Hierarchy Chart

See Also CFtpConnection, CHttpConnection, CInternetConnection, CGopherLocator


CGopherConnection::OpenFile

CGopherFile* OpenFile( CGopherLocator& refLocator, DWORD dwFlags = 0, LPCTSTR pstrView = NULL, DWORD dwContext = 1 );

Return Value

A pointer to the CGopherFile object to be opened.

Parameters

refLocator

A reference to a CGopherLocator object.

dwFlags

Any combination of INTERNET_FLAG_* flags. See CInternetSession::OpenUrl for further information on INTERNET_FLAG_* flags.

pstrView

A pointer to a file-view string. If several views of the file exist at the server, this parameter specifies which file view to open. If pstrView is NULL, the default file view is used.

dwContext

The context ID for the file being opened. See Remarks for more information about dwContext.

Remarks

Call this member function to open a file on a gopher server.

Override the dwContext default to set the context identifier to a value of your choosing. The context identifier is associated with this specific operation of the CGopherConnection object created by its CInternetSession object. The value is returned to CInternetSession::OnStatusCallback to provide status on the operation with which it is identified. See the article Internet First Steps: WinInet in Visual C++ Programmer's Guide for more information about the context identifier.

CGopherConnection Overview | Class Members | Hierarchy Chart

See Also CFtpConnection, CHttpConnection, CInternetConnection, CGopherFile, CGopherLocator, CInternetSession


CGopherFile

The MFC class CGopherFile provides the functionality to find and read files on a gopher server.

The gopher service does not allow users to write data to a gopher file because this service functions mainly as a menu-driven interface for finding information. The CGopherFile member functions Write, WriteString, and Flush are not implemented for CGopherFile. Calling these functions on a CGopherFile object, returns a CNotSupportedException.

To learn more about how CGopherFile works with the other MFC Internet classes, see the article Internet Programming with WinInet in Visual C++ Programmer's Guide.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

See Also CInternetFile, CGopherLocator, CGopherFileFind, CGopherConnection


CGopherFile Class Members

Construction

CGopherFile Constructs a CGopherFile object.

Operations

Close Closes the connection to a gopher server.

CGopherFile Overview | Base Class Members | Hierarchy Chart

See Also CInternetFile, CGopherLocator, CGopherFileFind, CGopherConnection


CGopherFile::CGopherFile

CGopherFile( HINTERNET hFile, CGopherLocator& refLocator, CGopherConnection* pConnection );

Parameters

hFile

A handle to an HINTERNET file.

refLocator

A reference to a CGopherLocator object.

pConnection

A pointer to a CGopherConnection object.

Remarks

This member function is called to construct a CGopherFile object.

You need a CGopherFile object to read from a file during a gopher Internet session.

You never create a CGopherFile object directly. Instead, call CGopherConnection::OpenFile to open a file on a gopher server.

CGopherFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile, CGopherLocator, CGopherFileFind, CGopherConnection


CGopherFile::Close

virtual void Close( );

Remarks

Call this member function to close the gopher file.

CGopherFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile, CGopherLocator, CGopherFileFind, CGopherConnection


CGopherFileFind

Class CGopherFileFind aids in Internet file searches of gopher servers. CGopherFileFind includes member functions that begin a search, locate a file, and return a file’s URL.

Other MFC classes designed for Internet and local file searched include CFtpFileFind and CFileFind. Together with CGopherFileFind, these classes provide a seamless mechanism for the user to find specific files, regardless of the server protocol, file type, or location (either a local machine or a remote server.) Note that there is no MFC class for searching on HTTP servers because HTTP does not support the direct file manipulation required by searches.

Note CGopherFileFind does not support the following member functions of its base class CFileFind:

  • GetRoot

  • GetFileName

  • GetFilePath

  • GetFileTitle

  • GetFileURL

In addition, when used with CGopherFileFind, the CFileFind member function IsDots is always FALSE.

For more information about how to use CGopherFileFind and the other WinInet classes, see the article Internet Programming with WinInet in Visual C++ Programmer's Guide.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

See Also CFtpFileFind, CFileFind, CInternetFile, CGopherFile, CHttpFile


CGopherFileFind Class Members

Construction

CGopherFileFind Constructs a CGopherFileFind object.

Attributes

FindFile | Finds a file on a gopher server.
FindNextFile | Continues a file search from a previous call to FindFile.
GetLocator | Get a CGopherLocator object.
GetScreenName | Gets the name of a gopher screen.
GetLength | Gets the length of the found file, in bytes.

CGopherFileFind Overview | Base Class Members | Hierarchy Chart

See Also CFtpFileFind, CFileFind, CInternetFile, CGopherFile, CHttpFile


CGopherFileFind::CGopherFileFind

CGopherFileFind( CGopherConnection* pConnection, DWORD dwContext = 1 );

Parameters

pConnection

A pointer to a CGopherConnection object.

dwContext

The context identifier for the operation. See Remarks for more information about dwContext.

Remarks

This member function is called to construct a CGopherFileFind object.

The default value for dwContext is sent by MFC to the CGopherFileFind object from the CInternetSession object that created the CGopherFileFind object. When you construct a CGopherFileFind object, you can override the default to set the context identifier to a value of your choosing. The context identifier is returned to CInternetSession::OnStatusCallback to provide status on the object with which it is identified. See the article Internet First Steps: WinInet in Visual C++ Programmer's Guide for more information about the context identifier.

CGopherFileFind Overview | Class Members | Hierarchy Chart

See Also CFtpFileFind, CFileFind


CGopherFileFind::FindFile

virtual BOOL FindFile( CGopherLocator& refLocator, LPCTSTR pstrString, DWORD dwFlags = INTERNET_FLAG_RELOAD );

virtual BOOL FindFile( LPCTSTR pstrString, DWORD dwFlags = INTERNET_FLAG_RELOAD );

Return Value

Nonzero if successful; otherwise 0. To get extended error information, call the Win32 function GetLastError.

Parameters

refLocator

A reference to a CGopherLocator object.

pstrString

A pointer to a string containing the file name.

dwFlags

The flags describing how to handle this session. The valid flags are:

  • INTERNET_FLAG_RELOAD Get the data from the remote server even if it is locally cached.

  • INTERNET_FLAG_DONT_CACHE Do not cache the data, either locally or in any gateways.

  • INTERNET_FLAG_SECURE Request secure transactions on the wire with Secure Sockets Layer or PCT. This flag is applicable to HTTP requests only.

  • INTERNET_FLAG_USE_EXISTING If possible, reuse the existing connections to the server for new FindFile requests, instead of creating a new session for each request.

Remarks

Call this member function to find a gopher file.

After calling FindFile to retrieve the first gopher object, you can call FindNextFile to retrieve subsequent gopher files.

CGopherFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::FindFile


CGopherFileFind::FindNextFile

virtual BOOL FindNextFile( );

Return Value

Nonzero if there are more files; zero if this is the last file, and the previous call to either FindFile or FindNextFile returned nonzero. To get extended error information, call the Win32 function GetLastError.

Remarks

Call this member function to continue a file search begun with a call to CGopherFileFind::FindFile.

CGopherFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind::FindNextFile


CGopherFileFind::GetLength

virtual DWORD GetLength( ) const;

Return Value

The length, in bytes, of the found file.

Remarks

Call this member function to get the length, in bytes, of the found file.

GetLength uses the nFileSizeLow member, of the Win32 structure WIN32_FIND_DATA to get the low-order DWORD value of the file size in bytes. If the file may be more than four gigabytes in size, use the GetLength64 member.

CGopherFileFind Overview | Class Members | Hierarchy Chart

See Also CFileFind


CGopherFileFind::GetLocator

CGopherLocator GetLocator( ) const;

Return Value

A CGopherLocator object.

Remarks

Call this member function to get the CGopherLocator object that FindFile uses to find the gopher file.

CGopherFileFind Overview | Class Members | Hierarchy Chart

See Also CGopherConnection::CreateLocator


CGopherFileFind::GetScreenName

CString GetScreenName( ) const;

Return Value

The name of the gopher screen.

Remarks

Call this member function to get the name of the gopher screen.


CGopherLocator

The class CGopherLocator gets a gopher "locator" from a gopher server, determines the locator’s type, and makes the locator available to CGopherFileFind.

An application must get a gopher server’s locator before it can retrieve information from that server. Once it has the locator, it must treat the locator as an opaque token.

Each gopher locator has attributes that determine the type of file or server found. See GetLocatorType for a list of types of gopher locators.

An application normally uses the locator for calls to CGopherFileFind::FindFile to retrieve a specific piece of information.

To learn more about how CGopherLocator works with the other MFC Internet classes, see the article Internet Programming with WinInet in Visual C++ Programmer's Guide.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

See Also CGopherFileFind


CGopherLocator Class Members

Construction

CGopherLocator Constructs a CGopherLocator object.

Attributes

GetLocatorType Parses a gopher locator and determines its attributes.

Operators

operator LPCTSTR Directly accesses characters stored in a CGopherLocator object as a C-style string.


CGopherLocator::CGopherLocator

CGopherLocator( const CGopherLocator& ref );

Parameters

ref

A reference to a constant CGopherLocator object.

Remarks

This member function is called to create a CGopherLocator object. You never create a CGopherLocator object directly. Instead, call CGopherConnection::CreateLocator to create and return a pointer to the CGopherLocator object.

CGopherLocator Overview | Class Members | Hierarchy Chart

See Also CGopherFileFind, CGopherConnection


CGopherLocator::GetLocatorType

BOOL GetLocatorType( DWORD& dwRef ) const;

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

dwRef

A reference to a DWORD that will receive the locator type. See Remarks for a table of locator types.

Remarks

Call this member function to get the locator type. The possible types are as follows:

Value | Meaning
GOPHER_TYPE_TEXT_FILE | An ASCII text file.
GOPHER_TYPE_DIRECTORY | A directory of additional Gopher items.
GOPHER_TYPE_CSO | A CSO phone book server.
GOPHER_TYPE_ERROR | Indicates an error condition.
GOPHER_TYPE_MAC_BINHEX | A Macintosh file in BINHEX format.
GOPHER_TYPE_DOS_ARCHIVE | A DOS archive file.
GOPHER_TYPE_UNIX_UUENCODED | A UUENCODED file.
GOPHER_TYPE_INDEX_SERVER | An index server.
GOPHER_TYPE_TELNET | A Telnet Server.
GOPHER_TYPE_BINARY | A binary file.
GOPHER_TYPE_REDUNDANT | A duplicated server. The information contained within is a duplicate of the primary server. The primary server is the last directory entry that did not have a GOPHER_TYPE_REDUNDANT type.
GOPHER_TYPE_TN3270 | A TN3270 server.
GOPHER_TYPE_GIF | A GIF graphics file.
GOPHER_TYPE_IMAGE | An image file.
GOPHER_TYPE_BITMAP | A bitmap file.
GOPHER_TYPE_MOVIE | A movie file.
GOPHER_TYPE_SOUND | A sound file.
GOPHER_TYPE_HTML | An HTML document.
GOPHER_TYPE_PDF | A PDF file.
GOPHER_TYPE_CALENDAR | A calendar file.
GOPHER_TYPE_INLINE | An inline file.
GOPHER_TYPE_UNKNOWN | The item type is unknown.
GOPHER_TYPE_ASK | An Ask+ item.
GOPHER_TYPE_GOPHER_PLUS | A Gopher+ item.

CGopherLocator Overview | Class Members | Hierarchy Chart

See Also CGopherFileFind, CGopherConnection


CGopherLocator::operator LPCTSTR

operator LPCTSTR ( ) const;

Return Value

A character pointer to the string’s data.

Remarks

This useful casting operator provides an efficient method to access the null-terminated C string contained in a CGopherLocator object. No characters are copied; only a pointer is returned.


CHeaderCtrl

A “header control” is a window 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 CHeaderCtrl class provides the functionality of the Windows common header control. This control (and therefore the CHeaderCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

Functionality added for Windows 97/Internet Explorer 4.0 common controls includes the following:

  • Header item custom ordering.

  • Header item drag and drop, for reordering of header items. Use the HDS_DRAGDROP style when you create the CHeaderCtrl object.

  • Header column text constantly viewable during column resizing. Use the HDS_FULLDRAG style when you create a CHeaderCtrl object.

  • Header hot tracking, which highlights the header item when the pointer is paused over it. Use the HDS_HOTTRACK style when you create the CHeaderCtrl object.

  • Image list support. Header items can contain images stored in a CImageList object, as well as text.

For more information on using CHeaderCtrl, see Control Topics and Using CHeaderCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample LISTHDR

See Also CTabCtrl, CListCtrl, CImageList


CHeaderCtrl Class Members

Construction

CHeaderCtrl | Constructs a CHeaderCtrl object.
Create | Creates a header control and attaches it to a CHeaderCtrl object.

Attributes

GetItemCount | Retrieves a count of the items in a header control.
GetItem | Retrieves information about an item in a header control.
SetItem | Sets the attributes of the specified item in a header control.
GetImageList | Retrieves the handle of an image list used for drawing header items in a header control.
SetImageList | Assigns an image list to a header control.
GetItemRect | Retrieves the bounding rectangle for a given item in a header control.
GetOrderArray | Retrieves the left-to-right order of items in a header control.
SetOrderArray | Sets the left-to-right order of items in a header control.
OrderToIndex | Retrieves the index value for an item based on its order in the header control.

Operations

InsertItem | Inserts a new item into a header control.
DeleteItem | Deletes an item from a header control.
Layout | Retrieves the size and position of a header control within a given rectangle.
CreateDragImage | Creates a transparent version of an item’s image within a header control.
SetHotDivider | Changes the divider between header items to indicate a manual drag and drop of a header item.

Overridables

DrawItem Draws the specified item of a header control.


CHeaderCtrl::CHeaderCtrl

CHeaderCtrl( );

Remarks

Constructs a CHeaderCtrl object.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::Create


CHeaderCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if initialization was successful; otherwise zero.

Parameters

dwStyle

Specifies the header control’s style. Apply any combination of header control styles needed to the control.

rect

Specifies the header control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the header control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the header control’s ID.

Remarks

You construct a CHeaderCtrl object in two steps. First call the constructor, then call Create, which creates the header control and attaches it to the CHeaderCtrl object.

The following styles can be applied to a header control (see About Header Control Styles for more information):

  • HDS_HOTTRACK A header item is highlighted when the pointer pauses over it.

  • HDS_DRAGDROP Header items can be reordered by dragging and dropping them.

  • HDS_FULLDRAG The header control to displays column contents while the user resizes a column.

  • HDS_BUTTONS Header items behave like buttons.

  • HDS_HORZ The header control is horizontal.

  • HDS_VERT The header control is vertical (this style is not currently implemented).

  • HDS_HIDDEN The header control is not visible in details mode.

In addition, you can use the following common control styles to determine how the header control positions and resizes itself (see Common Control Styles for more information):

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

  • CCS_NODIVIDER Prevents a two-pixel highlight from being drawn at the top of the control.

  • CCS_NOHILITE Prevents a one-pixel highlight from being drawn at the top of the control.

  • CCS_NOMOVEY Causes the control to resize and move itself horizontally, but not vertically, in response to a WM_SIZE message. If the CCS_NORESIZE style is used, this style does not apply. Header controls 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 window. If the CCS_TOP or CCS_BOTTOM style is also used, the height is adjusted to the default, but the position and width remain unchanged.

  • CCS_NORESIZE Prevents the control from using the default width and height when setting its initial size or a new size. Instead, the control uses the width and height specified in the request for creation or sizing.

  • CCS_TOP Causes the control to position itself at the top of the parent window’s client area and sets the width to be the same as the parent window’s width.

You can also apply the following window styles to a header control (see Window Styles for more information):

  • WS_CHILD Creates a child window. Cannot be used with the WS_POPUP style.

  • WS_VISIBLE Creates a window that is initially visible.

  • WS_DISABLED Creates a window that is initially disabled.

  • WS_GROUP Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style after the first control belong to the same group. The next control with the WS_GROUP style ends the style group and starts the next group (that is, one group ends where the next begins).

  • WS_TABSTOP Specifies one of any number of controls through which the user can move by using the TAB key. The TAB key moves the user to the next control specified by the WS_TABSTOP style.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::CHeaderCtrl


CHeaderCtrl::CreateDragImage

CImageList* CreateDragImage( int nIndex );

Return Value

A pointer to a CImageList object if successful; otherwise NULL. The returned list contains only one image.

Parameters

nIndex

The zero-based index of the item within the header control. The image assigned to this item is the basis for the transparent image.

Remarks

This member function implements the behavior of the Win32 message HDM_CREATEDRAGIMAGE, as described in the Platform SDK. It is provided to support header item drag and drop.

The CImageList object to which the returned pointer points is a temporary object, and is deleted in the next idle-time processing.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::GetImageList, CHeaderCtrl::SetImageList


CHeaderCtrl::DeleteItem

BOOL DeleteItem( int nPos );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nPos

Specifies the zero-based index of the item to delete.

Remarks

Deletes an item from a header control.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::InsertItem


CHeaderCtrl::DrawItem

void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A pointer to a DRAWITEMSTRUCT structure describing the item to be painted.

Remarks

Called by the framework when a visual aspect of an owner-draw header control changes. The itemAction member of the DRAWITEMSTRUCT structure defines the drawing action that is to be performed.

By default, this member function does nothing. Override this member function to implement drawing for an owner-draw CHeaderCtrl object.

The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before this member function terminates.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CWnd::OnDrawItem


CHeaderCtrl::GetImageList

CImageList* GetImageList( ) const;

Return Value

A pointer to a CImageList object.

Remarks

This member function implements the behavior of the Win32 message HDM_GETIMAGELIST, as described in the Platform SDK.

The CImageList object to which the returned pointer points is a temporary object, and is deleted in the next idle-time processing.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::SetImageList, CHeaderCtrl::CreateDragImage


CHeaderCtrl::GetItem

BOOL GetItem( int nPos, HDITEM* pHeaderItem ) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

nPos

Specifies the zero-based index of the item to retrieve.

pHeaderItem

Pointer to an HDITEM structure that receives the new item. This structure is used with the InsertItem and SetItem member functions. Any flags set in the mask element ensure that values in the corresponding elements are properly filled in upon return. If the mask element is set to zero, values in the other structure elements are meaningless.

Remarks

Retrieves information about a header control item.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::SetItem


CHeaderCtrl::GetItemCount

int GetItemCount( ) const;

Return Value

Number of header control items if successful; otherwise – 1.

Remarks

Retrieves a count of the items in a header control.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::GetItem, CHeaderCtrl::SetItem


CHeaderCtrl::GetItemRect

BOOL GetItemRect( int nIndex, LPRECT lpRect ) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

nIndex

The zero-based index of the header control item.

lpRect

A pointer to the address of a RECT structure that receives the bounding rectangle information.

Remarks

This member function implements the behavior of the Win32 message HDM_GETITEMRECT, as described in the Platform SDK.


CHeaderCtrl::GetOrderArray

BOOL GetOrderArray( LPINT piArray, int iCount = -1 );

Return Value

Nonzero if successful; otherwise 0.

Parameters

piArray

A pointer to the address of a buffer that receives the index values of the items in the header control, in the order in which they appear from left to right.

iCount

The number of header control items.

Remarks

This member function implements the behavior of the Win32 message HDM_GETORDERARRAY, as described in the Platform SDK. It is provided to support header item ordering.

If you use iCount’s default value, GetOrderArray fills the parameter using GetItemCount.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::SetOrderArray, CHeaderCtrl::OrderToIndex


CHeaderCtrl::InsertItem

int InsertItem( int nPos, HDITEM* phdi );

Return Value

Index of the new item if successful; otherwise – 1.

Parameters

nPos

The zero-based index of the item to be inserted. If the value is zero, the item is inserted at the beginning of the header control. If the value is greater than the maximum value, the item is inserted at the end of the header control.

phdi

Pointer to an HDITEM structure that contains information about the item to be inserted.

Remarks

Inserts a new item into a header control at the specified index.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::DeleteItem, CHeaderCtrl::GetItem


CHeaderCtrl::Layout

BOOL Layout( HDLAYOUT* pHeaderLayout );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pHeaderLayout

Pointer to an HDLAYOUT structure, which contains information used to set the size and position of a header control.

Remarks

Retrieves the size and position of a header control within a given rectangle. This function is used to determine the appropriate dimensions for a new header control that is to occupy the given rectangle.


CHeaderCtrl::OrderToIndex

int OrderToIndex( int nOrder ) const;

Return Value

The index of the item, based on its order in the header control. The index counts from left to right, beginning with 0.

Parameters

nOrder

The zero-based order that the item appears in the header control, from left to right.

Remarks

This member function implements the behavior of the Win32 macro HDM_ORDERTOINDEX, as described in the Platform SDK. It is provided to support header item ordering.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::GetOrderArray, CHeaderCtrl::SetOrderArray


CHeaderCtrl::SetHotDivider

int SetHotDivider( CPoint pt );

int SetHotDivider( int nIndex );

Return Value

The index of the highlighted divider.

Parameters

pt

The position of the pointer. The header control highlights the appropriate divider based on the pointer’s position.

nIndex

The index of the highlighted divider.

Remarks

This member function implements the behavior of the Win32 message HDM_SETHOTDIVIDER, as described in the Platform SDK. It is provided to support header item drag and drop.


CHeaderCtrl::SetImageList

CImageList* SetImageList( CImageList* pImageList );

Return Value

A pointer to the CImageList object previously assigned to the header control.

Parameters

pImageList

A pointer to a CImageList object containing the image list to be assigned to the header control.

Remarks

This member function implements the behavior of the Win32 message HDM_SETIMAGELIST, as described in the Platform SDK.

The CImageList object to which the returned pointer points is a temporary object, and is deleted in the next idle-time processing.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::GetImageList, CHeaderCtrl::CreateDragImage


CHeaderCtrl::SetItem

BOOL SetItem( int nPos, HDITEM* pHeaderItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nPos

The zero-based index of the item to be manipulated.

pHeaderItem

Pointer to an HDITEM structure that contains information about the new item.

Remarks

Sets the attributes of the specified item in a header control.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::GetItem, CHeaderCtrl::GetItemCount


CHeaderCtrl::SetOrderArray

BOOL SetOrderArray( int iCount, LPINT piArray );

Return Value

Nonzero if successful; otherwise 0.

Parameters

iCount

The number of header control items.

piArray

A pointer to the address of a buffer that receives the index values of the items in the header control, in the order in which they appear from left to right.

Remarks

This member function implements the behavior of the Win32 macro HDM_SETORDERARRAY, as described in the Platform SDK. It is provided to support header item ordering.

CHeaderCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl::GetOrderArray, CHeaderCtrl::OrderToIndex


CHotKeyCtrl

A “hot key control” is a window that enables the user to create 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.

The CHotKeyCtrl class provides the functionality of the Windows common hot key control. This control (and therefore the CHotKeyCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

When the user has chosen a key combination, the application can retrieve the specified key combination from the control and use the WM_SETHOTKEY message to set up the hot key in the system. Whenever the user presses the hot key thereafter, from any part of the system, the window specified in the WM_SETHOTKEY message receives a WM_SYSCOMMAND message specifying SC_HOTKEY. This message activates the window that receives it. The hot key remains valid until the application that called WM_SETHOTKEY exits.

This mechanism is different from the hot key support that depends on the WM_HOTKEY message and the Windows RegisterHotKey and UnregisterHotKey functions.

For more information on using CHotKeyCtrl, see Control Topics and Using CHotKeyCtrl in the Visual C++ Programmer's Guide.

#include <afxcmn.h>


CHotKeyCtrl Class Members

Construction

CHotKeyCtrl | Constructs a CHotKeyCtrl object.
Create | Creates a hot key control and attaches it to a CHotKeyCtrl object.

Attributes

SetHotKey | Sets the hot key combination for a hot key control.
GetHotKey | Retrieves the virtual-key code and modifier flags of a hot key from a hot key control.

Operations

SetRules Defines the invalid combinations and the default modifier combination for a hot key control.


CHotKeyCtrl::CHotKeyCtrl

CHotKeyCtrl( );

Remarks

Constructs a CHotKeyCtrl object.

CHotKeyCtrl Overview | Class Members | Hierarchy Chart

See Also CHotKeyCtrl::Create


CHotKeyCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero, if initialization was successful; otherwise 0.

Parameters

dwStyle

Specifies the hot key control’s style. Apply any combination of control styles.

rect

Specifies the hot key control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the hot key control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the hot key control’s ID.

Remarks

You construct a CHotKeyCtrl object in two steps. First call the constructor, then call Create, which creates the hot key control and attaches it to the CHotKeyCtrl object.

CHotKeyCtrl Overview | Class Members | Hierarchy Chart

See Also CHotKeyCtrl::CHotKeyCtrl


CHotKeyCtrl::GetHotKey

DWORD GetHotKey( ) const;

void GetHotKey( WORD &wVirtualKeyCode, WORD &wModifiers ) const;

Return Value

In the first usage above, a DWORD containing the virtual-key code and modifier flags. The low-order word is the virtual-key code, and the high-order word is the modifier flags. The HIWORD and LOWORD of this 32-bit value can be used as the parameters in the SetHotKey member function.

Parameters

wVirtualKeyCode

Virtual-key code of the hot key.

wModifiers

Modifier flags indicating the keys that, when used in combination with wVirtualKeyCode, define a hot key combination.

Remarks

Call this function to retrieve the virtual-key code and modifier flags of a hot key from a hot key control.

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

CHotKeyCtrl Overview | Class Members | Hierarchy Chart

See Also CHotKeyCtrl::SetHotKey


CHotKeyCtrl::SetHotKey

void SetHotKey( WORD wVirtualKeyCode, WORD wModifiers );

Parameters

wVirtualKeyCode

Virtual-key code of the hot key.

wModifiers

Modifier flags indicating the keys that, when used in combination with wVirtualKeyCode, define a hot key combination. For more information on the modifier flags, see GetHotKey.

Remarks

Call this function to set the hot key combination for a hot key control.

CHotKeyCtrl Overview | Class Members | Hierarchy Chart

See Also CHotKeyCtrl::GetHotKey


CHotKeyCtrl::SetRules

void SetRules( WORD wInvalidComb, WORD wModifiers );

Parameters

wInvalidComb

Array of flags that specifies invalid key combinations. It 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

wModifiers

Array of flags that specifies the key combination to use when the user enters an invalid combination. For more information on the modifier flags, see GetHotKey.

Remarks

Call this function to define the invalid combinations and the default modifier combination for a hot key control. When a user enters an invalid key combination, as defined by flags specified in wInvalidComb, the system uses the OR operator to combine the keys entered by the user with the flags specified in wModifiers. The resulting key combination is converted into a string and then displayed in the hot key control.

CHotKeyCtrl Overview | Class Members | Hierarchy Chart

See Also CHotKeyCtrl::GetHotKey, CHotKeyCtrl::SetHotKey


CHtmlStream

CHtmlStream does not have a base class.

CHtmlStream is a class that manages in-memory HTML. HTML memory files are useful for temporarily storing raw bytes or serialized objects prior to their transmission. Although it is not derived from CFile, CHtmlStream behaves like the CFile–derived class CMemFile, except CHtmlStream is used to store data in a temporary buffer prior to sending it out, and the data stored in a CHtmlStream memory file cannot be read.

CHtmlStream objects usually are created automatically and handed to you by CHttpServer::ConstructStream; however, you can override CHttpServer::ConstructStream and provide your own special functionality.

CHtmlStream objects can automatically allocate their own memory or you can attach your own memory block to the CHtmlStream object by calling Attach. In either case, memory for growing the memory file automatically is allocated in nGrowBytes-sized increments if nGrowBytes is not zero. Set nGrowBytes with a parameter to the constructor.

The memory will automatically be deleted upon destruction of the CHtmlStream object if the memory was originally allocated by the CHtmlStream object; otherwise, you are responsible for deallocating the memory you attached to the object.

CHtmlStream uses the run-time library functions malloc, realloc, and free to allocate, reallocate, and deallocate memory; and the intrinsic memcpy to block copy memory when growing the buffer. To change this behavior or the behavior when CHtmlStream grows a file, derive your own class from CHtmlStream and override the appropriate functions.

#include <afxisapi.h>

Class Members | Hierarchy Chart

Sample MFC Sample WWWQUOTE

See Also CHttpServer, CHttpFilter


CHtmlStream Class Members

Data Members

m_nStreamSize Contains the size of the stream.

Construction

CHtmlStream Constructs a CHtmlStream object.

Operations

Attach | Attaches a block of memory to CHtmlStream.
GetStreamSize | Gets the size of the CHtmlStream.
Close | Closes the stream and frees the buffer.
InitStream | Initializes a stream associated with a CHtmlStream object.

Overridables

Abort | Ends a stream and ignores all warnings and errors.
Reset | empties a CHtmlStream object.
Alloc | allocates memory in a CHtmlStream object.
Realloc | reallocates memory in a CHtmlStream object.
Memcpy | Copies memory to grow a CHtmlStream object.
Free | frees memory in a CHtmlStream object.
Detach | closes the CHtmlStream.
GrowStream | Grows a CHtmlStream object.
Write | Writes data from the buffer to the current stream.

Operators

operator << Writes data into a stream.


CHtmlStream::Abort

virtual void Abort( );

Remarks

Called by the framework to end the stream and make the CHtmlStream unavailable for writing.

Use Abort to clean up the stream after a catastrophic error. Use Reset to erase the content of the stream if you plan to write to it again.

Override this member function to implement custom cleanup.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Reset, CHtmlStream::Close


CHtmlStream::Alloc

virtual BYTE* Alloc( DWORD nBytes );

Return Value

A pointer to the memory block that was allocated, or NULL if the allocation failed.

Parameters

nBytes

Number of bytes of memory to be allocated.

Remarks

Called by the framework to allocate memory. Override this function to implement custom memory allocation. If you override this function, override Free, too.

The default implementation uses the run-time library function malloc to allocate memory.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Realloc


CHtmlStream::Attach

void Attach( BYTE* lpBuffer, UINT nBufferSize, UINT nGrowBytes = 0 );

Parameters

lpBuffer

Pointer to the buffer to be attached to CHtmlStream.

nBufferSize

An integer that specifies the size of the buffer in bytes.

nGrowBytes

The memory allocation increment in bytes.

Remarks

Call this function to attach a block of memory to CHtmlStream. This causes CHtmlStream to use the block of memory as the memory file.

If nGrowBytes is 0, CHtmlStream will set the file length to nBufferSize. This means that the data in the memory block before it was attached to CHtmlStream will be used as the file data. Memory files created in this manner cannot be grown.

Because the file cannot be grown, be careful not to cause CHtmlStream to attempt to grow the file. Don’t use operator << to add data.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Detach


CHtmlStream::CHtmlStream

CHtmlStream( UINT nGrowBytes = 4096 );

CHtmlStream( BYTE* lpBuffer, UINT nBufferSize, UINT nGrowBytes = 0 );

Parameters

nGrowBytes

The memory allocation increment in bytes.

lpBuffer

Pointer to a buffer that receives information of the size nBufferSize.

nBufferSize

An integer that specifies the size of the file buffer, in bytes.

Remarks

This member function is called by the framework during the construction of a CHtmlStream object.

Normally, a CHtmlStream object is created automatically and handed to you by CHttpServer::ConstructStream. You can change the behavior of the CHtmlStream object associated with a CHttpServerContext object by overriding CHttpServer::ConstructStream. For example, you might want to set nGrowBytes to a specific value. Use caution if you set nGrowBytes, because it will affect the performance of your code. The nGrowBytes parameter tells MFC how rapidly to increase the memory block associated with the stream. If the value is large, your code will be faster, but it will waste memory. If the value is small, your code will use less memory, but it will waste time by allocating memory more frequently.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::InitStream, CHtmlStream::Attach, CHtmlStream::Alloc


CHtmlStream::Close

virtual void Close( );

Remarks

Called by the framework to close the HTML stream and free the buffer.

Override this member function to perform an action before the HTML stream is closed.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Abort, CHtmlStream::Reset


CHtmlStream::Detach

BYTE* Detach( );

Return Value

A pointer to the memory block that contains the contents of the HTML stream.

Remarks

Call this function to get a pointer to the memory block being used by CHtmlStream.

Calling this function also closes the CHtmlStream. You can reattach the memory block to CHtmlStream by calling Attach. If you want to reattach the file and use the data in it, you should call GetStreamSize to get the length of the file before calling Detach. Note that if you attach a memory block to CHtmlStream so that you can use its data (nGrowBytes == 0), then you will not be able to grow the memory.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Attach


CHtmlStream::Free

virtual void Free( BYTE* lpMem );

Parameters

lpMem

Pointer to the memory to be deallocated.

Remarks

Called by the framework to free memory. Override this function to implement custom memory deallocation. If you override this function, you will probably want to override Alloc and Realloc as well.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Alloc, CHtmlStream::Realloc


CHtmlStream::GetStreamSize

DWORD GetStreamSize( ) const;

Return Value

The length of the file.

Remarks

Call this member function to obtain the size of the HTML stream in bytes.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::m_nStreamSize, CHtmlStream::GrowStream


CHtmlStream::GrowStream

virtual void GrowStream( DWORD dwNewLen );

Parameters

dwNewLen

New size of the memory file.

Remarks

Called by the framework to expand memory. You can override it if you want to change how CHtmlStream expands its memory. The default implementation calls Realloc to increase an existing block (or Alloc to create a memory block), allocating memory in multiples of the nGrowBytes value specified in the constructor or Attach call.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::m_nStreamSize, CHtmlStream::GetStreamSize


CHtmlStream::InitStream

virtual void InitStream( );

Remarks

Called by the framework to initialize a CHtmlStream. Override InitStream to implement per-instance initialization. For example, override this function to specify HTML headers that you always need.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::CHtmlStream


CHtmlStream::Memcpy

virtual BYTE* Memcpy( BYTE* lpMemTarget, const BYTE* lpMemSource, UINT nBytes );

Return Value

A copy of lpMemTarget.

Parameters

lpMemTarget

Pointer to the memory block into which the source memory will be copied.

lpMemSource

Pointer to the source memory block.

nBytes

Number of bytes to be copied.

Remarks

Called by the framework to transfer data to and from the stream. Override this function if you want to change the way that CHtmlStream does these memory copies.


CHtmlStream::Realloc

virtual BYTE* Realloc( BYTE* lpMem, DWORD nBytes );

Return Value

A pointer to the memory block that was reallocated (and possibly moved), or NULL if the reallocation failed.

Parameters

lpMem

A pointer to the memory block to be reallocated.

nBytes

New size for the memory block.

Remarks

Called by the framework to reallocate memory. Override this function to implement custom memory reallocation. If you override this function, you'll probably want to override Alloc and Free as well.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Free, CHtmlStream::Alloc


CHtmlStream::Reset

virtual void Reset( );

Remarks

Called by the framework to empty a previously initialized CHtmlStream object. Override this member function to require a special action before emptying a CHtmlStream object.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Close, CHtmlStream::Abort


CHtmlStream::Write

virtual void Write( const void* lpBuf, UINT nCount );

Parameters

lpBuf

A pointer to the user-supplied buffer that contains the data to be written to the stream.

nCount

The number of bytes to be transferred from the buffer.

Remarks

Called by the framework to write data from a buffer to the stream associated with the CHtmlStream object.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::operator <<


CHtmlStream::operator <<

CHtmlStream& operator<<( LPCTSTR psz );

CHtmlStream& operator<<( short int w );

CHtmlStream& operator<<( long int dw );

CHtmlStream& operator<<( const CHtmlStream& stream );

CHtmlStream& operator<<( double d );

CHtmlStream& operator<<( float f );

CHtmlStream& operator<<( const CByteArray& array );

CHtmlStream& operator<<( const CLongBinary& blob );

Remarks

The CHtmlStream insertion (<<) operator writes the specified string or integer to the HTML stream. The string version of the operator writes the string without modification. The integer override versions of the operator format the value as decimal text before writing it.

You can use the CHtmlStream& override of this function to append the content of one HTML stream to another.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::Write


CHtmlStream::m_nStreamSize

Remarks

Contains the size for an HTML stream. m_nStreamSize is a protected variable of type UINT. Only reference this variable if you want to override functions like Alloc and Free and GrowStream.

CHtmlStream Overview | Class Members | Hierarchy Chart

See Also CHtmlStream::GetStreamSize, CHtmlStream::GrowStream


CHtmlView

The CHtmlView class provides the functionality of the WebBrowser control within the context of MFC's document/view architecture. The WebBrowser control is a window in which the user can browse sites on the World Wide Web, as well as folders in the local file system and on a network. The WebBrowser control supports hyperlinking, Uniform Resource Locator (URL) navigation, and maintains a history list.

Using the CHtmlView Class in an MFC Application

In the standard MFC framework application (either SDI or MDI based), the view object is commonly derived from a specialized set of classes. These classes, all derived from CView, provide specialized functionality beyond that provided by CView.

Basing the application's view class on CHtmlView provides the view with the WebBrowser control. This effectively makes the application a web browser. The preferred method of creating a web browser-style application is to use the MFC AppWizard, and specify CHtmlView as the view class. For more information on implementing and using the WebBrowser control within MFC applications, see Web Browser-Style Applications.

The functionality of CHtmlView is designed for applications that are access the Web (and/or HTML documents). The following CHtmlView member functions apply to the Internet Explorer application only. These functions will succeed on the WebBrowser control, but they will have no visible effect.

  • GetAddressBar

  • GetFullName

  • GetStatusBar

  • SetAddressBar

  • SetFullScreen

  • SetMenuBar

  • SetStatusBar

  • SetToolBar

#include <afxhtml.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MFCIE

See Also IWebBrowser2, in the Platform SDK


CHtmlView Class Members

Attributes

GetType | Retrieves the type name of the document object.
GetLeft | Retrieves the screen coordinate of the left edge of the Internet Explorer main window.
SetLeft | Sets the horizontal position of the Internet Explorer main window.
GetTop | Retrieves the screen coordinate of the top edge of the Internet Explorer main window.
SetTop | Sets the vertical position of the Internet Explorer main window.
GetHeight | Retrieves the height of the Internet Explorer main window.
SetHeight | Sets the height of the Internet Explorer main window.
SetVisible | Sets a value indicating whether the object is visible or hidden.
GetVisible | Retrieves a value indicating whether the object is visible or hidden.
GetLocationName | Retrieves the name of the resource that WebBrowser is currently displaying
GetReadyState | Retrieves the ready state of the web browser object.
GetOffline | Retrieves a value that determines whether the control is offline.
SetOffline | Sets a value to determine whether the control is offline.
GetSilent | Indicates whether any dialog boxes can be shown.
SetSilent | Sets a value to determine whether the control will display dialog boxes.
GetTopLevelContainer | Retrieves a value indicating whether the current object is the top-level container of the WebBrowser control.
GetLocationURL | Retrieves the URL of the resource that WebBrowser is currently displaying.
GetBusy | Retrieves a value indicating whether a download or other activity is still in progress.
GetApplication | Retrieves an application object representing the application that contains the current instance of the Internet Explorer application.
GetParentBrowser | Retrieves a pointer to the IDispatch interface.
GetContainer | Retrieves the container of the WebBrowser control.
GetHtmlDocument | Retrieves the active HTML document.
GetFullName | Retrieves the full name, including the path, of the resource displayed in the web browser. (WebBrowser control ignores; Internet Explorer only.)
GetToolBar | Retrieves a value that determines whether the toolbar is visible.
SetToolBar | Sets a value to determine whether the control's toolbar is visible. (WebBrowser control ignores; Internet Explorer only.)
GetMenuBar | Retrieves a value that determines whether the menu bar is visible.
SetMenuBar | Sets a value to determine whether the control's menu bar is visible. (WebBrowser control ignores; Internet Explorer only.)
GetFullScreen | Indicates whether the WebBrowser control is operating in full-screen mode or in normal window mode.
SetFullScreen | Sets a value to determine whether the control is operating in full-screen mode or in normal window mode. (WebBrowser control ignores; Internet Explorer only.)
QueryStatusWB | Queries the status of a command being processed by the WebBrowser control.
GetRegisterAsBrowser | Indicates whether the WebBrowser control is registered as a top-level browser for target name resolution.
SetRegisterAsBrowser | Sets a value indicating whether the WebBrowser control is registered as a top-level browser for target name resolution.
GetRegisterAsDropTarget | Indicates whether the WebBrowser control is registered as a drop target for navigation.
SetRegisterAsDropTarget | Sets a value indicating whether the WebBrowser control is registered as a drop target for navigation.
GetTheaterMode | Indicates whether the WebBrowser control is in theater mode.
SetTheaterMode | Sets a value indicating whether the WebBrowser control is in theater mode.
GetAddressBar | Determines if the Internet Explorer object's address bar is visible. (WebBrowser control ignores; Internet Explorer only.)
SetAddressBar | Shows or hides the Internet Explorer object's address bar. (WebBrowser control ignores; Internet Explorer only.)
GetStatusBar | Indicates whether the Internet Explorer's status bar is visible. (WebBrowser control ignores; Internet Explorer only.)
SetStatusBar | Sets a value to determine whether the Internet Explorer's status bar is visible. (WebBrowser control ignores; Internet Explorer only.)

Operations

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 the resource identified by a URL.
Navigate2 | Navigates to the resource identified by a URL, or to the file identified by a full path.
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.
PutProperty | Sets the value of a property associated with the given object.
GetProperty | Retrieves the current value of a property associated with the given object.
ExecWB | Executes a command.
LoadFromResource | Loads a resource in the WebBrowser control.

Overrides

OnDraw | Called to render an image of the document for screen display, printing, or print preview. Implementation required.
Create | Creates the WebBrowser control.

Events

OnNavigateComplete2 | Called after a navigation to a hyperlink completes (on either a window or frameset element).
OnBeforeNavigate2 | Called before a navigation occurs in the given WebBrowser (on either a window or frameset element).
OnStatusTextChange | Called to notify an application that the text of the status bar associated with the WebBrowser control has changed.
OnProgressChange | Called to notify an application that the progress of a download operation has been updated.
OnCommandStateChange | Called to notify an application that the enabled state of a web browser command has changed.
OnDownloadBegin | Called to notify an application that a navigation operation is beginning.
OnDownloadComplete | Called when a navigation operation finished, was halted, or failed.
OnTitleChange | Called to notify an application if the title of a document in the WebBrowser control becomes available or changes.
OnPropertyChange | Called to notify an application that the PutProperty method has changed the value of a property.
OnNewWindow2 | Called when a new window is to be created for displaying a resource.
OnDocumentComplete | Called to notify an application that a document has reached the READYSTATE_COMPLETE state.
OnQuit | Called to notify an application that the Internet Explorer application is ready to quit. (Applies to Internet Explorer only)
OnVisible | Called when the window for the WebBrowser control should be shown/hidden.
OnToolBar | Called when the ToolBar property has changed.
OnMenuBar | Called when the MenuBar property has changed.
OnStatusBar | Called when the StatusBar property has changed.
OnFullScreen | Called when the FullScreen property has changed.
OnTheaterMode | Called when the TheaterMode property has changed.


CHtmlView::Create

virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL );

Parameters

lpszClassName

Points to a null-terminated character string that names the Windows class. The class name can be any name registered with the AfxRegisterWndClass global function or the RegisterClass Windows function. If NULL, uses the predefined default CFrameWnd attributes.

lpszWindowName

Points to a null-terminated character string that represents the window name.

dwStyle

Specifies the window style attributes. By default, the WS_VISIBLE and WS_CHILD Windows styles are set.

rect

A reference to a RECT structure specifying the size and position of the window. The rectDefault value allows Windows to specify the size and position of the new window.

pParentWnd

A pointer to the parent window of the control.

nID

The ID number of the view. By default, set to AFX_IDW_PANE_FIRST.

pContext

A pointer to a CCreateContext. NULL by default.

Remarks

Call this member function to create a WebBrowser control or container for the Internet Explorer executable.


CHtmlView::ExecWB

void ExecWB(OLECMDID cmdID, OLECMDEXECOPT cmdexecopt, VARIANT* pvaIn, VARIANT* pvaOut );

Parameters

cmdID

The command to execute.

cmdexecopt

The options set for executing the command.

pvaIn

A variant used for specifying command input arguments.

pvaOut

A variant used for specifying command output arguments.

Remarks

Call this member function to execute a command in the WebBrowser or Internet Explorer.

See IWebBrowser2::ExecWB in the Platform SDK.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::Stop


CHtmlView::GetAddressBar

BOOL GetAddressBar( ) const;

Return Value

Nonzero if the address bar is visible; otherwise zero.

Remarks

Call this member function to retrieve Internet Explorer’s address bar.

Applies to Internet Explorer. If you use this call with a WebBrowser control, it will return no error, but it will ignore this call.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetAddressBar, IWebBrowser2::get_AddressBar


CHtmlView::GetApplication

LPDISPATCH GetApplication( ) const;

Return Value

A pointer to the IDispatch interface of the active document object.

Remarks

Call this member function to retrieve the automation object supported by the application that contains the WebBrowser control.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also IWebBrowser2::get_Application


CHtmlView::GetBusy

BOOL GetBusy( ) const;

Return Value

Nonzero if the web browser is busy; otherwise zero.

Remarks

Call this member function to determine whether the WebBrowser control is engaged in a navigation or downloading operation.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also IWebBrowser2::get_Busy


CHtmlView::GetContainer

LPDISPATCH GetContainer( ) const;

Return Value

A pointer to the IDispatch interface of the active document object.

Remarks

Call this member function to retrieve an object that evaluates to the container of the web browser.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetTopLevelContainer, IWebBrowser2::get_Container


CHtmlView::GetFullName

CString GetFullName( ) const;

Return Value

A CString object containing the path and name of the currently displayed file. If no path and filename exist, GetFullName returns an empty CString.

Remarks

Call this member function to retrieve the full path of the file that Internet Explorer is currently displaying.

Applies to Internet Explorer. If you use this call with a WebBrowser control, it will return no error, but it will ignore this call.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also IWebBrowser2::get_FullName


CHtmlView::GetFullScreen

BOOL GetFullScreen( ) const;

Return Value

Nonzero if the WebBrowser is operating in full-screen mode; otherwise zero.

Remarks

Call this member function to determine whether the WebBrowser control is operating in full-screen mode or 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 Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetFullScreen, IWebBrowser2::get_FullScreen, FullScreen property


CHtmlView::GetHeight

long GetHeight( ) const;

Return Value

The control’s frame window height, in pixels.

Remarks

Call this member function to retrieve the height, in pixels, of the WebBrowser control’s frame window.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetHeight


CHtmlView::GetHtmlDocument

LPDISPATCH GetHtmlDocument( ) const;

Return Value

A pointer to the IDispatch interface of the active document object.

Remarks

Call this member function to retrieve the HTML document for the active document.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also IWebBrowser2::get_Document


CHtmlView::GetLeft

long GetLeft( ) const;

Return Value

The left-edge distance, in pixels.

Remarks

Call this member function to retrieve the distance between the internal left edge of the WebBrowser control and the left edge of its container.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetLeft, IWebBrowser2::get_Left


CHtmlView::GetLocationName

CString GetLocationName( ) const;

Return Value

A CString object containing the name of the resource currently displayed in the WebBrowser.

Remarks

Call this member function to get the name of the resource being displayed in the WebBrowser. 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 and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetLocationURL, IWebBrowser2::get_LocationName


CHtmlView::GetLocationURL

CString GetLocationURL( ) const;

Return Value

A CString object containing the URL of the resource currently displayed in the WebBrowser.

Remarks

Call this member function to retrieve the URL of the resource that the WebBrowser control is currently displaying. 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 and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetLocationName, IWebBrowser2::get_LocationURL


CHtmlView::GetMenuBar

BOOL GetMenuBar( ) const;

Return Value

Nonzero if the menu bar is visible; otherwise zero.

Remarks

Call this member function to determine whether the menu bar is visible.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetMenuBar, IWebBrowser2::get_MenuBar


CHtmlView::GetOffline

BOOL GetOffline( ) const;

Return Value

Nonzero if the web browser is currently offline; otherwise zero.

Remarks

Call this member function to determine whether the web browser is operating offline.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetOffline, IWebBrowser2::get_Offline


CHtmlView::GetParentBrowser

LPDISPATCH GetParentBrowser( ) const;

Return Value

A pointer to the IDispatch interface of the object that is the parent of the WebBrowser control.

Remarks

Call this member function to retrieve a pointer to the parent object of the WebBrowser control.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also IWebBrowser2::get_Parent


CHtmlView::GetProperty

BOOL GetProperty( LPCTSTR lpszProperty, CString& strValue );

COleVariant GetProperty( LPCTSTR lpsz );

Return Value

In the first version, nonzero if completed successfully; otherwise zero. In the second version, a COleVariant object.

Parameters

lpszProperty

A pointer to a string containing the property to retrieve.

strValue

A reference to a CString object that receives the current value of the property.

lpsz

A pointer to a string containing the property to retrieve.

Remarks

Call this member function to get the value of the property currently associated with the control.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::PutProperty, IWebBrowser2::GetProperty


CHtmlView::GetReadyState

READYSTATE GetReadyState( ) const;

Return Value

A READYSTATE value, as described in the Platform SDK.

Remarks

Call this member function to retrieve the ready state of the WebBrowser object.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also IWebBrowser2::get_ReadyState


CHtmlView::GetRegisterAsBrowser

BOOL GetRegisterAsBrowser( ) const;

Return Value

Nonzero if the browser is registered as a top-level browser; otherwise zero.

Remarks

Call this member function to determine whether the WebBrowser object is registered as a top-level browser for target name resolution.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetRegisterAsBrowser, IWebBrowser2::get_RegisterAsBrowser


CHtmlView::GetRegisterAsDropTarget

BOOL GetRegisterAsDropTarget( ) const;

Return Value

Nonzero if the browser is registered as a drop target; otherwise zero.

Remarks

Call this member function to determine whether the WebBrowser control is registered as a drop target for navigation.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetRegisterAsDropTarget, IWebBrowser2::get_RegisterAsDropTarget


CHtmlView::GetSilent

BOOL GetSilent( ) const;

Return Value

Nonzero if dialog boxes cannot be displayed from the WebBrowser control; otherwise zero.

Remarks

Call this member function to determine whether any dialog boxes can be shown in the WebBrowser control.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetSilent, IWebBrowser2::get_Silent


CHtmlView::GetStatusBar

BOOL GetStatusBar( ) const;

Return Value

Nonzero if the status bar can be displayed; otherwise zero.

Remarks

Call this member function to determine whether the WebBrowser control displays a status bar.

Applies to Internet Explorer. If you use this call with a WebBrowser control, it will return no error, but it will ignore this call.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetStatusBar, IWebBrowser2::get_StatusBar


CHtmlView::GetTheaterMode

BOOL GetTheaterMode( ) const;

Return Value

Nonzero if the web browser is in theater mode; otherwise zero.

Remarks

Call this member function to determine whether the web browser is in theater mode. When the web browser is in theater mode, the browser main window fills the entire screen, a toolbar with a minimal set of navigational tools appears, and the status bar appears in the upper right-hand corner of the screen.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetTheaterMode, CHtmlView::SetFullScreen, IWebBrowser2::get_TheaterMode


CHtmlView::GetToolBar

int GetToolBar( ) const;

Return Value

A value indicating whether the toolbar is visible. Nonzero if toolbar is visible; otherwise zero.

Remarks

Call this member function to determine whether the toolbar is visible.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetToolBar, IWebBrowser2::get_ToolBar


CHtmlView::GetTop

long GetTop( ) const;

Return Value

Address of a variable that receives the screen coordinate of the main window's top edge.

Remarks

Call this member function to retrieve the screen coordinate of the top edge of the WebBrowser control’s main window.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetTop


CHtmlView::GetTopLevelContainer

BOOL GetTopLevelContainer( ) const;

Return Value

Nonzero the container is the top-level container; otherwise zero.

Remarks

Call this member function to determine whether Internet Explorer is the top-level container of the WebBrowser control.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetContainer, IWebBrowser2::get_TopLevelContainer


CHtmlView::GetType

CString GetType( ) const;

Return Value

A CString object containing the type name of the contained active document.

Remarks

Call this member function to retrieve the type name of the contained active document.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also IWebBrowser2::get_Type


CHtmlView::GetVisible

BOOL GetVisible( ) const;

Return Value

Nonzero if the object is visible; otherwise zero.

Remarks

Call this member function to determine if the contained object is visible.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetVisible, IWebBrowser2::get_Visible


CHtmlView::GoBack

void GoBack( );

Remarks

Navigates backward one item in the history list.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GoForward, CHtmlView::GoHome, IWebBrowser2::GoBack


CHtmlView::GoForward

void GoForward( );

Remarks

Navigates forward one item in the history list.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GoBack, CHtmlView::GoHome, IWebBrowser2::GoForward


CHtmlView::GoHome

void GoHome( );

Remarks

Navigates to the current home or start page specified in the Internet Explorer Internet Options dialog box or the Internet Properties dialog box, accessed from the Control Panel.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GoForward, CHtmlView::GoBack, IWebBrowser2::GoHome


CHtmlView::GoSearch

void GoSearch( );

Remarks

Navigates to the current search page, as specified in the Internet Explorer Internet Options dialog box or the Internet Properties dialog box, accessed from the Control Panel.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GoHome, IWebBrowser2::GoSearch


CHtmlView::LoadFromResource

BOOL LoadFromResource( LPCTSTR lpszResource );

BOOL LoadFromResource( UINT nRes );

Return Value

Nonzero if successful; otherwise zero.

Parameters

lpszResource

A pointer to a string containing the name of the resource to load.

nRes

The ID of the buffer containing the name of the resource to load.

Remarks

Call this member function to load the specified resource into the WebBrowser control.

Applies to Internet Explorer and WebBrowser.


CHtmlView::Navigate

void Navigate( LPCTSTR URL, DWORD dwFlags = 0, LPCTSTR lpszTargetFrameName = NULL, LPCTSTR lpszHeaders = NULL, LPVOID lpvPostData = NULL, DWORD dwPostDataLen = 0 );

Parameters

URL

A caller-allocated string that contains the URL to navigate to, or the full path of the file to display.

dwFlags

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

lpszTargetFrameName

A pointer to a string that contains the name of the frame in which to display the resource.

lpszHeaders

A pointer to 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 such things as 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.

lpvPostData

A pointer to the 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.

dwPostDataLen

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.

Remarks

Call this member function to navigate to the resource identified by a URL.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::Navigate2, IWebBrowser2::Navigate


CHtmlView::Navigate2

void Navigate2( LPITEMIDLIST pIDL, DWORD dwFlags = 0, LPCTSTR lpszTargetFrameName = NULL );

void Navigate2( LPCTSTR lpszURL, DWORD dwFlags = 0, LPCTSTR lpszTargetFrameName = NULL, LPCTSTR lpszHeaders = NULL, LPVOID lpvPostData = NULL, DWORD dwPostDataLen = 0 );

void Navigate2( LPCTSTR lpszURL, DWORD dwFlags, CByteArray& baPostedData, LPCTSTR lpszTargetFrameName = NULL, LPCTSTR lpszHeader = NULL );

Parameters

pIDL

A pointer to an ITEMIDLIST structure.

dwFlags

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

lpszTargetFrameName

A pointer to a string that contains the name of the frame in which to display the resource.

lpszURL

A pointer to a string containing the URL.

lpvPostData

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, Navigate2 issues an HTTP GET transaction. This parameter is ignored if URL is not an HTTP URL.

dwPostDataLen

Length in bytes of the data pointed to by the lpvPostData parameter.

lpszHeaders

A pointer to 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 such things as 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.

baPostedData

A reference to a CByteArray object.

Remarks

Call this member function to navigate to the resource identified by a URL, or to the file identified by a full path.

This member function extends the Navigate member function by supporting browsing on special folders, such as Desktop and My Computer, that are represented by the parameter pIDL.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::Navigate, IWebBrowser2::Navigate2


CHtmlView::OnBeforeNavigate2

virtual void OnBeforeNavigate2( LPCTSTR lpszURL, DWORD nFlags, LPCTSTR lpszTargetFrameName, CByteArray& baPostedData, LPCTSTR lpszHeaders, BOOL* pbCancel );

Parameters

lpszURL

Pointer to a string containing the URL to navigate to.

nFlags

Reserved for future use.

lpszTargetFrameName

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

baPostedData

A reference to a CByteArray object containing the data to send to the server if the HTTP POST transaction is being used.

lpszHeaders

A pointer to a string containing additional HTTP headers to send to the server (HTTP URLs only). The headers can specify such things as the action required of the server, the type of data being passed to the server, or a status code.

pbCancel

A pointer to a cancel flag. An application can set this parameter to nonzero to cancel the navigation operation, or to zero to allow it to proceed.

Remarks

This member function is called by the framework to cause an event to fire before a navigation occurs in the web browser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::Navigate, CHtmlView::Navigate2, DWebBrowserEvents2::BeforeNavigate2


CHtmlView::OnCommandStateChange

virtual void OnCommandStateChange( long nCommand, BOOL bEnable );

Parameters

nCommand

Identifier of the command whose enabled state has changed.

bEnable

Enabled state. This parameter is nonzero if the command is enabled, or zero if it is disabled.

Remarks

This member function is called by the framework to notify an application that the enabled state of a web browser command has changed.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetReadyState, DWebBrowserEvents2::CommandStateChange


CHtmlView::OnDocumentComplete

virtual void OnDocumentComplete( LPCTSTR lpszURL );

Parameters

lpszURL

A pointer to a string that evaluates to the URL, UNC file name, or a PIDL (a pointer to an item identifier list) that was navigated to.

Remarks

This member function is called by the framework to notify an application that a document has reached the READYSTATE_COMPLETE state.

Not every frame will fire this event, but each frame that fires an OnDownloadBegin event will fire a corresponding OnDocumentComplete event.

The URL indicated by lpszURL can be different from the URL that the browser was told to navigate to, because this URL is the canonicalized and qualified URL. For example, if an application specifies a URL of "www.microsoft.com" in a call to Navigate or Navigate2, the URL passed by OnNavigateComplete2 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.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetHtmlDocument, DWebBrowserEvents2::DocumentComplete


CHtmlView::OnDownloadBegin

virtual void OnDownloadBegin( );

Remarks

This member function is called by the framework to begin downloading a document. This event is fired shortly after the OnBeforeNavigate2 event, unless the navigation is canceled. Any animation or "busy" indication that the container needs to display should be connected to this event.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::OnDownloadComplete, CHtmlView::Navigate, CHtmlView::Navigate2, DWebBrowserEvents2::DownloadBegin


CHtmlView::OnDownloadComplete

virtual void OnDownloadComplete( );

Remarks

This member function is called by the framework to indicate that a navigation operation finished, was halted, or failed.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::OnDownloadBegin, DWebBrowserEvents2::DownloadComplete


CHtmlView::OnDraw

virtual void OnDraw( CDC* pDC );

Parameters

pDC

A pointer to the device context to be used for rendering an image.

Remarks

This member function is called by the framework to draw the view.

Applies to Internet Explorer and WebBrowser.


CHtmlView::OnFullScreen

virtual void OnFullScreen( BOOL bFullScreen );

Parameters

bFullScreen

Nonzero if Internet Explorer is in full screen mode; zero otherwise.

Remarks

This member function is called by the framework when the FullScreen property has changed.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetFullScreen, CHtmlView::SetFullScreen, DWebBrowserEvents2::OnFullScreen


CHtmlView::OnMenuBar

virtual void OnMenuBar( BOOL bMenuBar );

Parameters

bMenuBar

Nonzero if the Internet Explorer menu bar is visible; zero otherwise.

Remarks

This member function is called by the framework when the MenuBar property has changed.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetMenuBar, CHtmlView::SetMenuBar, DWebBrowserEvents2::OnMenuBar


CHtmlView::OnNavigateComplete2

virtual void OnNavigateComplete2( LPCTSTR strURL );

Parameters

strURL

A string expression that evaluates to the URL, UNC file name, or PIDL (a pointer to an item identifier list) that was navigated to.

Remarks

This member function is called by the framework after a navigation to a hyperlink completes (on either a window or frameset element).

The URL parameter can be a PIDL in the case of a shell name space entity for which there is no URL representation.

Note that the URL contained in strURL can be different from the URL that the browser was told to navigate to, because this URL is the canonicalized and qualified URL. For example, if an application specifies a URL of "www.microsoft.com" in a call to Navigate or Navigate2, the URL passed by OnNavigateComplete2 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.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also DWebBrowserEvents2::NavigateComplete2


CHtmlView::OnNewWindow2

virtual void OnNewWindow2( LPDISPATCH* ppDisp, BOOL* Cancel );

Parameters

ppDisp

A pointer to an interface pointer that, optionally, receives the IDispatch interface pointer of a new WebBrowser or Internet Explorer object.

Cancel

A pointer to a cancel flag. An application can set this parameter to nonzero to cancel the navigation operation, or to zero to allow it to proceed.

Remarks

This member function is called by the framework 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.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also DWebBrowserEvents2::NewWindow2


CHtmlView::OnProgressChange

virtual void OnProgressChange( long nProgress, long nProgressMax );

Parameters

nProgress

Amount of total progress to show, or -1 when progress is complete.

nProgressMax

Maximum progress value.

Remarks

This member function is called by the framework to notify an application that the progress of a download operation has been updated.

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.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetBusy, DWebBrowserEvents2::ProgressChange, CProgressCtrl


CHtmlView::OnPropertyChange

virtual void OnPropertyChange( LPCTSTR lpszProperty );

Parameters

lpszProperty

A pointer to a string containing the name of the property.

Remarks

This member function is called by the framework to notify an application that PutProperty has changed the value of a property.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetProperty, DWebBrowserEvents2::PropertyChange


CHtmlView::OnQuit

virtual void OnQuit( );

Remarks

This member function is called by the framework to notify an application that the Internet Explorer application is ready to quit.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also DWebBrowserEvents2::OnQuit


CHtmlView::OnStatusBar

virtual void OnStatusBar( BOOL bStatusBar );

Parameters

bStatusBar

Nonzero if Internet Explorer's status bar is visible or zero otherwise.

Remarks

This member function is called by the framework when the StatusBar property has changed.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetStatusBar, CHtmlView::SetStatusBar, DWebBrowserEvents2::OnStatusBar


CHtmlView::OnStatusTextChange

virtual void OnStatusTextChange( LPCTSTR lpszText );

Parameters

lpszText

A string that contains the new status bar text.

Remarks

This member function is called by the framework to notify an application that the text of the status bar associated with the WebBrowser control has changed.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also DWebBrowserEvents2::StatusTextChange


CHtmlView::OnTheaterMode

virtual void OnTheaterMode( BOOL bTheaterMode );

Parameters

bTheaterMode

Nonzero if Internet Explorer is in theater mode; zero otherwise.

Remarks

This member function is called by the framework when the TheaterMode property has changed.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetTheaterMode, CHtmlView::SetTheaterMode, DWebBrowserEvents2::OnTheaterMode


CHtmlView::OnTitleChange

virtual void OnTitleChange( LPCTSTR lpszText );

Parameters

lpszText

The new document title.

Remarks

This member function is called by the framework to notify an application if the title of a document in the WebBrowser control becomes available or changes.

For HTML, the title might change; while HTML is still downloading, the URL of the document is set as the title. After the real title (if there is one) is parsed from the HTML, the title is changed to reflect the actual title.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also DWebBrowserEvents2::TitleChange


CHtmlView::OnToolBar

virtual void OnToolBar( BOOL bToolBar );

Parameters

bToolBar

Nonzero if Internet Explorer's toolbar is visible or zero otherwise.

Remarks

This member function is called by the framework when the ToolBar property has changed.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetToolBar, CHtmlView::SetToolBar, DWebBrowserEvents2::OnToolBar


CHtmlView::OnVisible

virtual void OnVisible( BOOL bVisible );

Parameters

bVisible

Nonzero if the object is visible or zero otherwise.

Remarks

This member function is called by the framework when the window for the WebBrowser should be shown or hidden. This allows the object control host window to behave the same way the Internet Explorer window would behave.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::SetVisible, CHtmlView::GetVisible, DWebBrowserEvents2::OnVisible


CHtmlView::PutProperty

void PutProperty( LPCTSTR lpszProperty, const VARIANT& vtValue );

void PutProperty( LPCTSTR lpszPropertyName, double dValue );

void PutProperty( LPCTSTR lpszPropertyName, long lValue );

void PutProperty( LPCTSTR lpszPropertyName, LPCTSTR lpszValue );

void PutProperty( LPCTSTR lpszPropertyName, short nValue );

Parameters

lpszProperty

A string containing the property to set.

vtValue

The new value of the property indicated by lpszProperty.

lpszPropertyName

A pointer to a string containing the name of the property to set.

dValue

The new value of the property.

lValue

The new value of the property.

lpszValue

A pointer to a string containing the new value of the property.

nValue

The new value of the property.

Remarks

Call this member function to set the property associated with a given object.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetProperty, IWebBrowser2::PutProperty


CHtmlView::QueryStatusWB

OLECMDF QueryStatusWB( OLECMDID cmdID ) const;

Return Value

The address of the OLECMDF value that receives the status of the command.

Parameters

cmdID

The OLECMDID value of the command for which the caller needs status information.

Remarks

Call this member function to query a command status. QueryStatusWB implements the behavior of the IOleCommandTarget::QueryStatus method.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::ExecWB, IWebBrowser2::QueryStatusWB


CHtmlView::Refresh

void Refresh( );

Remarks

Reloads the URL or file that the web browser is currently displaying. Refresh contains no parameters for setting the refresh level.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::Refresh2, IWebBrowser2::Refresh


CHtmlView::Refresh2

void Refresh2( int nLevel );

Parameters

nLevel

The address of the variable specifying the refresh level. The possible variables are defined in RefreshConstants, in the Platform SDK.

Remarks

Reloads the file that Internet Explorer is currently displaying. Unlike Refresh, Refresh2 contains a parameter that specifies the refresh level.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also IWebBrowser2::Refresh2


CHtmlView::SetAddressBar

void SetAddressBar( BOOL bNewValue );

Parameters

bNewValue

Nonzero to show address bar; otherwise zero.

Remarks

Call this member function to show or hide the Internet Explorer object's address bar.

Applies to Internet Explorer. If you use this call with a WebBrowser control, it will return no error, but it will ignore this call.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetAddressBar, IWebBrowser2::put_AddressBar


CHtmlView::SetFullScreen

void SetFullScreen( BOOL bNewValue );

Parameters

bNewValue

Nonzero for full-screen mode; otherwise zero.

Remarks

Call this member function to set Internet Explorer to either full-screen or 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 Internet Explorer. If you use this call with a WebBrowser control, it will return no error, but it will ignore this call.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetFullScreen, CHtmlView::SetTheaterMode, IWebBrowser2::put_FullScreen, FullScreen property


CHtmlView::SetHeight

void SetHeight( long nNewValue );

Parameters

nNewValue

The height, in pixels, of the main window.

Remarks

Call this member function to set the height of the Internet Explorer main window.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetHeight, IWebBrowser2::put_Height


CHtmlView::SetLeft

void SetLeft( long nNewValue );

Parameters

nNewValue

The screen coordinate of the left edge of the main window.

Remarks

Sets the horizontal position of the Internet Explorer main window.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetLeft, IWebBrowser2::put_Left


CHtmlView::SetMenuBar

void SetMenuBar( BOOL bNewValue );

Parameters

bNewValue

Nonzero to show menu bar; otherwise zero.

Remarks

Call this member function to show or hide the Internet Explorer menu bar.

Applies to Internet Explorer. If you use this call with a WebBrowser control, it will return no error, but it will ignore this call.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetMenuBar, IWebBrowser2::put_MenuBar


CHtmlView::SetOffline

void SetOffline( BOOL bNewValue );

Parameters

bNewValue

Nonzero to read from the local cache; otherwise zero.

Remarks

Call this member function to set a value indicating whether the WebBrowser control is currently operating in offline mode. In offline mode, the browser reads HTML pages from the local cache rather than from the source document.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetOffline, IWebBrowser2::put_Offline


CHtmlView::SetRegisterAsBrowser

void SetRegisterAsBrowser( BOOL bNewValue );

Parameters

bNewValue

Determines whether Internet Explorer is registered as a top-level browser. If nonzero, the web browser is registered as a top-level browser; if zero, it is not a top-level browser. The default value is zero.

Remarks

Call this member function to set a value indicating whether the WebBrowser control is registered as a top-level browser for target name resolution. A top-level browser is the browser set in the registry as the default browser.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetRegisterAsBrowser, IWebBrowser2::put_RegisterAsBrowser


CHtmlView::SetRegisterAsDropTarget

void SetRegisterAsDropTarget( BOOL bNewValue );

Parameters

bNewValue

Determines if the WebBrowser control is registered as a drop target for navigation. If nonzero, the object is registered as a drop target; if zero, it is not a drop target.

Remarks

Call this member function to set a value indicating whether the WebBrowser control is registered as a drop target for navigation.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetRegisterAsDropTarget, IWebBrowser2::put_RegisterAsDropTarget


CHtmlView::SetSilent

void SetSilent( BOOL bNewValue );

Parameters

bNewValue

If nonzero, dialog boxes will not be displayed; if zero, dialog boxes will be displayed. The default value is zero.

Remarks

Call this member function to set a value indicating whether any dialog boxes can be shown.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetSilent, IWebBrowser2::put_Silent


CHtmlView::SetStatusBar

void SetStatusBar( BOOL bNewValue );

Parameters

bNewValue

Nonzero if the status bar is visible; otherwise zero.

Remarks

Call this member function to display the status bar.

Applies to Internet Explorer. If you use this call with a WebBrowser control, it will return no error, but it will ignore this call.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetStatusBar, IWebBrowser2::put_StatusBar


CHtmlView::SetTheaterMode

void SetTheaterMode( BOOL bNewValue );

Parameters

bNewValue

Nonzero to set the WebBrowser control to theater mode; otherwise zero. The default value is zero.

Remarks

Call this member function to set a value indicating whether the WebBrowser control is in theater mode. When the web browser is in theater mode, the browser main window fills the entire screen, a toolbar with a minimal set of navigational tools appears, and the status bar appears in the upper right-hand corner of the screen.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetTheaterMode, CHtmlView::GetFullScreen, CHtmlView::SetFullScreen


CHtmlView::SetToolBar

void SetToolBar( int nNewValue );

Parameters

nNewValue

Indicates whether to display the toolbar. Nonzero if the toolbar is to be displayed; otherwise zero.

Remarks

Call this member function to show or hide the Internet Explorer toolbar.

Applies to Internet Explorer. If you use this call with a WebBrowser control, it will return no error, but it will ignore this call.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetToolBar, IWebBrowser2::put_ToolBar


CHtmlView::SetTop

void SetTop( long nNewValue );

Parameters

nNewValue

The screen coordinate of the top edge of the main window.

Remarks

Call this member function to set the distance between the internal top edge of the WebBrowser control and the top edge of its container

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetTop, IWebBrowser2::put_Top


CHtmlView::SetVisible

void SetVisible( BOOL bNewValue );

Parameters

bNewValue

Nonzero if the control is visible; otherwise zero.

Remarks

Call this member function to set the visibility state of the WebBrowser control.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::GetVisible, IWebBrowser2::put_Visible


CHtmlView::Stop

void Stop( );

Remarks

Call this member function to cancel any pending navigation or download operation and stop any dynamic page elements, such as background sounds and animations.

Applies to Internet Explorer and WebBrowser.

CHtmlView Overview | Class Members | Hierarchy Chart

See Also CHtmlView::ExecWB, IWebBrowser2::Stop


CHttpConnection

The MFC class CHttpConnection manages your connection to an HTTP server. HTTP is one of three Internet server protocols implemented by the MFC WinInet classes.

The class CHttpConnection contains a constructor and one member function, OpenRequest, that manages connections to a server with an HTTP protocol.

To communicate with an HTTP server, you must first create an instance of CInternetSession, and then create a CHttpConnection object. You never create a CHttpConnection object directly; rather, call CInternetSession::GetHttpConnection, which creates the CHttpConnection object and returns a pointer to it.

To learn more about how CHttpConnection works with the other MFC Internet classes, see the article Internet Programming with WinInet in Visual C++ Programmer’s Guide. For more information about connecting to servers using the other two supported Internet protocols, gopher and FTP, see the classes CGopherConnection and CFtpConnection.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample TEAR

See Also CInternetConnection, CHttpFile


CHttpConnection Class Members

Construction

CHttpConnection Creates a CHttpConnection object.

Operations

OpenRequest Opens an HTTP request.

CHttpConnection Overview | Base Class Members | Hierarchy Chart

See Also CFtpConnection, CGopherConnection, CInternetConnection, CHttpFile


CHttpConnection::CHttpConnection

CHttpConnection( );

Remarks

This member function is called to construct a CHttpConnection object. You never create a CHttpConnection directly. Rather, you create an object by calling CInternetSession::GetHttpConnection.

CHttpConnection Overview | Class Members | Hierarchy Chart

See Also CInternetSession::GetHttpConnection, CFtpConnection, CGopherConnection, CInternetConnection


CHttpConnection::OpenRequest

CHttpFile* OpenRequest( LPCTSTR pstrVerb, LPCTSTR pstrObjectName, LPCTSTR pstrReferer = NULL, DWORD dwContext = 1, LPCTSTR* pstrAcceptTypes = NULL, LPCTSTR pstrVersion = NULL, DWORD dwFlags = INTERNET_FLAG_EXISTING_CONNECT );

CHttpFile* OpenRequest( int nVerb, LPCTSTR pstrObjectName, LPCTSTR pstrReferer = NULL, DWORD dwContext = 1, LPCTSTR* pstrAcceptTypes = NULL, LPCTSTR pstrVersion = NULL, DWORD dwFlags = INTERNET_FLAG_EXISTING_CONNECT );

Return Value

A pointer to the CHttpFile object requested.

Parameters

pstrVerb

A pointer to a string containing the verb to use in the request. If NULL, "GET" is used.

pstrObjectName

A pointer to a string containing the target object of the specified verb. This is generally a filename, an executable module, or a search specifier.

pstrReferer

A pointer to a string that specifies the address (URL) of the document from which the URL in the request (pstrObjectName) was obtained. If NULL, no HTTP header is specified.

dwContext

The context identifier for the OpenRequest operation. See Remarks for more information about dwContext.

pstrAcceptTypes

A pointer to a null-terminated string indicating content types accepted by the client. If the string is NULL, the servers interpret that the client only accepts documents of type "text/*" (that is, only text documents and not pictures or other binary files). The content type is equivalent to the CGI variable CONTENT_TYPE, which identifies the type of data for queries that have attached information, such as HTTP POST and PUT.

pstrVersion

A pointer to a string defining the HTTP version. If NULL, "HTTP/1.0" is used.

dwFlags

Any combination of the INTERNET_ FLAG_* flags. See the Remarks for a description of possible dwFlags values.

nVerb

A number associated with the HTTP request type. Can be one of the following:

HTTP request type | nVerb value
HTTP_VERB_POST | 0
HTTP_VERB_GET | 1
HTTP_VERB_HEAD | 2
HTTP_VERB_PUT | 3
HTTP_VERB_LINK | 4
HTTP_VERB_DELETE | 5
HTTP_VERB_UNLINK | 6

Remarks

Call this member function to open an HTTP connection.

dwFlags can be one of the following:

Internet flag | Description
INTERNET_FLAG_RELOAD | Forces a download of the requested file, object, or directory listing from the origin server, not from the cache.
INTERNET_FLAG_DONT_CACHE | Does not add the returned entity to the cache.
INTERNET_FLAG_MAKE_PERSISTENT | Adds the returned entity to the cache as a persistent entity. This means that standard cache cleanup, consistency checking, or garbage collection cannot remove this item from the cache.
INTERNET_FLAG_SECURE | Uses secure transaction semantics. This translates to using SSL/PCT and is only meaningful in HTTP requests
INTERNET_FLAG_NO_AUTO_REDIRECT | Used only with HTTP, specifies that redirections should not be automatically handled in CHttpFile::SendRequest.

Override the dwContext default to set the context identifier to a value of your choosing. The context identifier is associated with this specific operation of the CHttpConnection object created by its CInternetSession object. The value is returned to CInternetSession::OnStatusCallback to provide status on the operation with which it is identified. See the article Internet First Steps: WinInet for more information about the context identifier.

CHttpConnection Overview | Class Members | Hierarchy Chart

See Also CHttpFile, CInternetSession, CFtpConnection, CGopherConnection, CInternetConnection


CHttpFile

The class CHttpFile provides the functionality to request and read files on an HTTP server.

If your Internet session reads data from an HTTP server, you must create an instance of CHttpFile.

To learn more about how CHttpFile works with the other MFC Internet classes, see the article Internet Programming with WinInet in Visual C++ Programmer’s Guide.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample TEAR

See Also CInternetFile, CGopherFile, CHttpConnection


CHttpFile Class Members

Construction

CHttpFile Creates a CHttpFile object.

Operations

AddRequestHeaders | Adds headers to the request sent to an HTTP server.
SendRequest | Sends a request to an HTTP server.
SendRequestEx | Sends a request to an HTTP server using the Write or WriteString methods of CInternetFile.
EndRequest | Ends a request sent to an HTTP server with the SendRequestEx member function.
QueryInfo | Returns the response or request headers from the HTTP server.
QueryInfoStatusCode | Retrieves the status code associated with an HTTP request and places it in the supplied dwStatusCode parameter.
GetVerb | Gets the verb that was used in a request to an HTTP server.
GetObject | Gets the target object of the verb in a request to an HTTP server.
GetFileURL | Gets the URL for the specified file.
Close | Closes the CHttpFile and frees its resources.

CHttpFile Overview | Base Class Members | Hierarchy Chart

See Also CInternetFile, CGopherFile, CHttpConnection


CHttpFile::AddRequestHeaders

BOOL AddRequestHeaders( LPCTSTR pstrHeaders, DWORD dwFlags = HTTP_ADDREQ_FLAG_ADD_IF_NEW, int dwHeadersLen = -1 );

BOOL AddRequestHeaders( CString& str, DWORD dwFlags = HTTP_ADDREQ_FLAG_ADD_IF_NEW );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

pstrHeaders

A pointer to a string containing the header or headers to append to the request. Each header must be terminated by a CR/LF pair.

dwFlags

Modifies the semantics of the new headers. Can be one of the following:

  • HTTP_ADDREQ_FLAG_COALESCE Merges headers of the same name, using the flag to add the first header found to the subsequent header. For example, "Accept: text/*" followed by "Accept: audio/*" results in the formation of the single header "Accept: text/*, audio/*". It is up to the calling application to ensure a cohesive scheme with respect to data received by requests sent with coalesced or separate headers.

  • HTTP_ADDREQ_FLAG_REPLACE Performs a remove and add to replace the current header. The header name will be used to remove the current header, and the full value will be used to add the new header. If the header-value is empty and the header is found, it is removed. If not empty, the header-value is replaced.

  • HTTP_ADDREQ_FLAG_ADD_IF_NEW Only adds the header if it does not already exist. If one exists, an error is returned.

  • HTTP_ADDREQ_FLAG_ADD Used with REPLACE. Adds the header if it doesn’t exist.

dwHeadersLen

The length, in characters, of pstrHeaders. If this is -1L, then pstrHeaders is assumed to be zero-terminated and the length is computed.

str

A reference to a CString object containing the request header or headers to be added.

Remarks

Call this member function to add one or more HTTP request headers to the HTTP request handle.

AddRequestHeaders appends additional, free-format headers to the HTTP request handle. It is intended for use by sophisticated clients who need detailed control over the exact request sent to the HTTP server.

Note The application can pass multiple headers in pstrHeaders or str for an AddRequestHeaders call using HTTP_ADDREQ_FLAG_ADD or HTTP_ADDREQ_FLAG_ADD_IF_NEW. If the application tries to remove or replace a header using HTTP_ADDREQ_FLAG_REMOVE or HTTP_ADDREQ_FLAG_REPLACE, only one header can be supplied in lpszHeaders.

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile


CHttpFile::CHttpFile

CHttpFile( HINTERNET hFile, HINTERNET hSession, LPCTSTR pstrObject, LPCTSTR pstrServer, LPCTSTR pstrVerb, DWORD dwContext );

CHttpFile( HINTERNET hFile, LPCTSTR pstrVerb, LPCTSTR pstrObject, CHttpConnection* pConnection );

Parameters

hFile

A handle to an Internet file.

hSession

A handle to an Internet session.

pstrObject

A pointer to a string containing the CHttpFile object.

pstrServer

A pointer to a string containing the name of the server.

pstrVerb

A pointer to a string containing the method to be used when sending the request. Can be POST, HEAD, or GET.

dwContext

The context identifier for the CHttpFile object. See Remarks for more information about this parameter.

pConnection

A pointer to a CHttpConnection object.

Remarks

This member function is called to construct a CHttpFile object.

You never construct a CHttpFile object directly; rather call CInternetSession::OpenURL or CHttpConnection::OpenRequest instead.

The default value for dwContext is sent by MFC to the CHttpFile object from the CInternetSession object that created the CHttpFile object. When you call CInternetSession::OpenURL or CHttpConnection to construct a CHttpFile object, you can override the default to set the context identifier to a value of your choosing. The context identifier is returned to CInternetSession::OnStatusCallback to provide status on the object with which it is identified. See the article Internet First Steps: WinInet for more information about the context identifier.

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile


CHttpFile::Close

virtual void Close( );

Remarks

Closes a CHttpFile and frees its resources. Use this member function only after a successful call to SendRequest or on a CHttpFile object successfully created by OpenURL.

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile


CHttpFile::EndRequest

BOOL EndRequest( DWORD dwFlags = 0, LPINTERNET_BUFFERS lpBuffIn = NULL, DWORD dwContext = 1 );
throw( CInternetException )

Return Value

Nonzero if successful; otherwise 0. If the call fails, determine the cause of the failure by examining the thrown CInternetException object.

Parameters

dwFlags

Flags describing the operation. For a list of the appropriate flags, see HttpEndRequest in the Platform SDK.

lpBuffIn

Pointer to an initialized INTERNET_BUFFERS that describes the input buffer used for the operation.

dwContext

The context identifier for the CHttpFile operation. See Remarks for more information about this parameter.

Remarks

Call this member function to end a request sent to an HTTP server with the SendRequestEx member function.

The default value for dwContext is sent by MFC to the CHttpFile object from the CInternetSession object that created the CHttpFile object. When you call CInternetSession::OpenURL or CHttpConnection to construct a CHttpFile object, you can override the default to set the context identifier to a value of your choosing. The context identifier is returned to CInternetSession::OnStatusCallback to provide status on the object with which it is identified. See article Internet First Steps: WinInet for more information about the context identifier.

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile


CHttpFile::GetFileURL

virtual CString GetFileURL( ) const;

Return Value

A CString object containing a URL referencing the resource associated with this file.

Remarks

Call this member function to get the name of the HTTP file as a URL. Use this member function only after a successful call to SendRequest or on a CHttpFile object successfully created by OpenURL.

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile


CHttpFile::GetObject

CString GetObject( ) const;

Return Value

A CString object containing the name of the object.

Remarks

Call this member function to get the name of the object associated with this CHttpFile. Use this member function only after a successful call to SendRequest or on a CHttpFile object successfully created by OpenURL.

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile


CHttpFile::GetVerb

CString GetVerb( ) const;

Return Value

A CString object containing the name of the HTTP verb (or method).

Remarks

Call this member function to get the HTTP verb (or method) associated with this CHttpFile. Use this member function only after a successful call to SendRequest or on a CHttpFile object successfully created by OpenURL.

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile


CHttpFile::QueryInfo

BOOL QueryInfo( DWORD dwInfoLevel, LPVOID lpvBuffer, LPDWORD lpdwBufferLength, LPDWORD lpdwIndex = NULL ) const;

BOOL QueryInfo( DWORD dwInfoLevel, CString& str, LPDWORD dwIndex = NULL ) const;

BOOL QueryInfo( DWORD dwInfoLevel, SYSTEMTIME* pSysTime, LPDWORD dwIndex = NULL ) const;

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

dwInfoLevel

A combination of the attribute to query and the following flags that specify the type of information requested:

  • HTTP_QUERY_CUSTOM Finds the header name and returns this value in lpvBuffer on output. HTTP_QUERY_CUSTOM throws an assertion if the header isn’t found.

  • HTTP_QUERY_FLAG_REQUEST_HEADERS Typically, the application queries the response headers, but an application can also query request headers by using this flag.

  • HTTP_QUERY_FLAG_SYSTEMTIME For those headers whose value is a date/time string, such as "Last-Modified-Time," this flag returns the header value as a standard Win32 SYSTEMTIME structure that does not require the application to parse the data. If you use this flag, you may want to use the SYSTEMTIME override of the function.

  • HTTP_QUERY_FLAG_NUMBER For those headers whose value is a number, such as the status code, this flag returns the data as a 32-bit number.

    See the Remarks section for a list of the possible values.

lpvBuffer

A pointer to the buffer that receives the information.

lpdwBufferLength

On entry, this points to a value containing the length of the data buffer, in number of characters or bytes. See the Remarks section for more detailed information about this parameter.

lpdwIndex

A pointer to a zero-based header index. Can be NULL. Use this flag to enumerate multiple headers with the same name. On input, lpdwIndex indicates the index of the specified header to return. On output, lpdwIndex indicates the index of the next header. If the next index cannot be found, ERROR_HTTP_HEADER_NOT_FOUND is returned.

str

A reference to the CString object receiving the returned information.

dwIndex

An index value. See lpdwIndex.

pSysTime

A pointer to a Win32 SYSTEMTIME structure.

Remarks

Call this member function to return response or request headers from an HTTP request. Use this member function only after a successful call to SendRequest or on a CHttpFile object successfully created by OpenURL.

You can retrieve the following types of data from QueryInfo:

  • strings (default)

  • SYSTEMTIME (for “Data:” “Expires:” etc, headers)

  • DWORD (for STATUS_CODE, CONTENT_LENGTH, etc.)

When a string is written to the buffer, and the member function succeeds, lpdwBufferLength contains the length of the string in characters minus 1 for the terminating NULL character.

The possible dwInfoLevel values include:

  • HTTP_QUERY_MIME_VERSION

  • HTTP_QUERY_CONTENT_TYPE

  • HTTP_QUERY_CONTENT_TRANSFER_ENCODING

  • HTTP_QUERY_CONTENT_ID

  • HTTP_QUERY_CONTENT_DESCRIPTION

  • HTTP_QUERY_CONTENT_LENGTH

  • HTTP_QUERY_ALLOWED_METHODS

  • HTTP_QUERY_PUBLIC_METHODS

  • HTTP_QUERY_DATE

  • HTTP_QUERY_EXPIRES

  • HTTP_QUERY_LAST_MODIFIED

  • HTTP_QUERY_MESSAGE_ID

  • HTTP_QUERY_URI

  • HTTP_QUERY_DERIVED_FROM

  • HTTP_QUERY_LANGUAGE

  • HTTP_QUERY_COST

  • HTTP_QUERY_WWW_LINK

  • HTTP_QUERY_PRAGMA

  • HTTP_QUERY_VERSION

  • HTTP_QUERY_STATUS_CODE

  • HTTP_QUERY_STATUS_TEXT

  • HTTP_QUERY_RAW_HEADERS

  • HTTP_QUERY_RAW_HEADERS_CRLF

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile, CHttpConnection::OpenRequest, CFtpConnection, CGopherConnection, CInternetConnection


CHttpFile::QueryInfoStatusCode

BOOL QueryInfoStatusCode( DWORD& dwStatusCode ) const;

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

dwStatusCode

A reference to a status code. Status codes indicate the success or failure of the requested event. See Remarks for a selection of status code descriptions.

Remarks

Call this member function to get the status code associated with an HTTP request and place it in the supplied dwStatusCode parameter. Use this member function only after a successful call to SendRequest or on a CHttpFile object successfully created by OpenURL.

HTTP status codes fall into groups indicating the success or failure of the request. The following tables outline the status code groups and the most common HTTP status codes.

Group | Meaning
200-299 | Success
300-399 | Information
400-499 | Request error
500-599 | Server error

Common HTTP Status Codes:

Status code | Meaning
200 | URL located, transmission follows
400 | Unintelligble request
404 | Requested URL not found
405 | Server does not support requested method
500 | Unknown server error
503 | Server capacity reached

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile


CHttpFile::SendRequest

BOOL SendRequest( LPCTSTR pstrHeaders = NULL, DWORD dwHeadersLen = 0, LPVOID lpOptional = NULL, DWORD dwOptionalLen = 0 );
Throw ( CInternetException )

BOOL SendRequest( CString& strHeaders, LPVOID lpOptional = NULL, DWORD dwOptionalLen = 0 );
Throw ( CInternetException )

Return Value

Nonzero if successful; otherwise 0. If the call fails, determine the cause of the failure by examining the thrown CInternetException object.

Parameters

pstrHeaders

A pointer to a string containing the name of the headers to send.

dwHeadersLen

The length of the headers identified by pstrHeaders.

lpOptional

Any optional data to send immediately after the request headers. This is generally used for POST and PUT operations. This can be NULL if there is no optional data to send.

dwOptionalLen

The length of lpOptional.

strHeaders

A string containing the name of the headers for the request being sent.

Remarks

Call this member function to send a request to an HTTP server.

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile, CHttpFile::SendRequestEx


CHttpFile::SendRequestEx

BOOL SendRequestEx( DWORD dwTotalLen, DWORD dwFlags = HSR_INITIATE, DWORD dwContext = 1);
throw( CInternetException )

BOOL SendRequestEx( LPINTERNET_BUFFERS lpBuffIn, LPINTERNET_BUFFERS lpBuffOut, DWORD dwFlags = HSR_INITIATE, DWORD dwContext = 1 );
throw( CInternetException )

Return Value

Nonzero if successful; otherwise 0. If the call fails, determine the cause of the failure by examining the thrown CInternetException object.

Parameters

dwTotalLen

Number of bytes to be sent in the request.

dwFlags

Flags describing the operation. For a list of appropriate flags, see HttpSendRequestEx in the Platform SDK.

dwContext

The context identifier for the CHttpFile operation. See Remarks for more information about this parameter.

lpBuffIn

Pointer to an initialized INTERNET_BUFFERS that describes the input buffer used for the operation.

lpBuffOut

Pointer to an initialized INTERNET_BUFFERS that describes the output buffer used for the operation.

Remarks

Call this member function to send a request to an HTTP server. This function allows your application to send data using the Write and WriteString methods of CInternetFile. You must know the length of the data to send before calling either override of this function. The first override allows you to specify the length of data you’d like to send. The second override accepts pointers to INTERNET_BUFFERS structures, which can be used to describe the buffer in great detail.

After content is written to the file, call EndRequest to end the operation.

The default value for dwContext is sent by MFC to the CHttpFile object from the CInternetSession object that created the CHttpFile object. When you call CInternetSession::OpenURL or CHttpConnection to construct a CHttpFile object, you can override the default to set the context identifier to a value of your choosing. The context identifier is returned to CInternetSession::OnStatusCallback to provide status on the object with which it is identified. See the article Internet First Steps: WinInet for more information about the context identifier.

Example

This code fragment sends the content of a string to a DLL named ISAPI.DLL on a server named MOOSEBOY. While this example uses only one call to WriteString, using multiple calls to send data in blocks is acceptable.

CString strData = “Some very long data to be POSTed here!”;
pServer = sess.GetHttpConnection("mooseboy");
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, "/isapi.dll?");
pFile->SendRequestEx(strData.GetLength());

pFile->WriteString(strData);
pFile->EndRequest();

CHttpFile Overview | Class Members | Hierarchy Chart

See Also CInternetFile, CHttpFile::SendRequest


CHttpFilter

CHttpFilter does not have a base class.

CHttpFilter creates and manages, with CHttpFilterContext, a Hypertext Transfer Protocol (HTTP) filter object. An HTTP filter is a replaceable dynamic link library (DLL) that the server calls on every HTTP request. When the filter is loaded, it tells the server what sort of notifications it is interested in. After that, whenever the selected events occur, the filter is called and given the opportunity to process that event.

ISAPI (Internet Server API) filters are powerful enough to allow for the following applications:

  1. Custom authentication schemes

  2. Compression

  3. Encryption

  4. Logging

  5. Traffic analysis or other request analysis

Multiple filters can be installed. The notification order is based on the priority specified by the filter and then the load order in the registry for any ties. Consult your filter’s documentation to see exactly how to install your filter.

Note Once a filter begins processing a request, it will receive the data regardless of whether the request is for a file or an ISAPI application.

The filter applications sit between the network connection to the client and the HTTP server. Depending on the options that the filter application chooses, it can act on several server actions, including reading raw data from the client, processing the headers, communications over a secure port (PCT—Personal Communications Technology, SSL—Secure Sockets Layer, and others), or several other stages in the processing of the HTTP request.

To set the filter notifications that your filter will use, see GetFilterVersion.

For more information on Internet filters, see ISAPI Extensions: Filters in Visual C++ Programmer’s Guide. For information about creating an Internet filter with ISAPI Extension Wizard, see Steps to Create a Typical ISAPI Filter in Visual C++ Programmer’s Guide.

#include <afxisapi.h>

Class Members | Hierarchy Chart

Sample MFC Sample MFCUCASE

See Also CHttpFilterContext, CHttpServer, CHttpServerContext


CHttpFilter Class Members

Construction

CHttpFilter Constructs a CHttpFilter object.

Attributes

GetFilterVersion Gets the version of the filter after the CHttpFilter object is constructed.

Overridables

OnReadRawData | Allows the application to see the raw data. The data returned will contain both headers and data.
OnPreprocHeaders | Notifies the client that the server has preprocessed the client headers.
OnAuthentication | Authenticates the client.
OnUrlMap | Notifies a client when a server is mapping a logical URL to a physical path.
OnSendRawData | Sends raw data from the server to the client.
OnLog | Logs information to a server file.
OnEndOfNetSession | Notifies the client that the session is ending.

Operation

HttpFilterProc Returns a message indicating how an event that passed through the filter was processed. Called each time an event occors.

CHttpFilter Overview | Hierarchy Chart

See Also CHttpFilterContext


CHttpFilter::CHttpFilter

CHttpFilter( );

Remarks

This member function is called by the framework during the construction of a CHttpFilter object.


CHttpFilter::GetFilterVersion

virtual BOOL GetFilterVersion( PHTTP_FILTER_VERSION pVer );

Return Value

Nonzero if the filter was properly loaded. If the filter returns 0, then the filter application will be unloaded and it will not receive any notifications.

Parameters

pVer

A pointer to the HTTP_FILTER_VERSION structure containing the server’s version information and fields for the filter to indicate version number and notifications. The filter application also includes space to register a small description of itself. The following two flags are set in the structure by the default implementation:

  • dwFlags The priority notification flag, SF_NOTIFY_ORDER_DEFAULT, is set by default. See Remarks for a list of the notification flags and their descriptions.

  • dwFilterVersion HTTP_FILTER_REVISION is set by default. This flag indicates the version of the specification used by the server.

Remarks

This member function is called by the internet server to get the filter version indicated by pVer. It is called only once, after the CHttpFilter object is constructed.

Use dwFlags to specify the notifications in the pVer member that interest your server. Here is a list of the valid flags for dwFlags:

SF_NOTIFY_ORDER_DEFAULT

Loads the filter at the default priority. This value is recommended because other priority notifications can have a strong impact on performance and scalability.

SF_NOTIFY_ORDER_LOW

Loads the filter at low priority.

SF_NOTIFY_ORDER_MEDIUM

Loads the filter at medium priority.

SF_NOTIFY_ORDER_HIGH

Loads the filter at high priority.

SF_NOTIFY_SECURE_PORT

Notifies the application that it is passing data through a secure port.

SF_NOTIFY_NONSECURE_PORT

Notifies the application that it is passing data through a nonsecure port.

Note If you set neither SF_NOTIFY_NONSECURE_PORT nor SF_NOTIFY_SECURE_PORT, the server defaults to both, which allows processing data through any port.

SF_NOTIFY_READ_RAW_DATA

Allows the application to see the raw data. The data returned to the client will contain both headers and data.

SF_NOTIFY_PREPROC_HEADERS

The server has pre-processed the headers.

SF_NOTIFY_AUTHENTICATION

The server is authenticating the client.

SF_NOTIFY_URL_MAP

The server is mapping a logical URL to a physical path.

SF_NOTIFY_SEND_RAW_DATA

The server is sending raw data back to the client.

SF_NOTIFY_LOG

The server is writing information to the server log.

SF_NOTIFY_END_OF_NET_SESSION

The session with the client is ending.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also HTTP_FILTER_VERSION, CHttpFilter::HttpFilterProc


CHttpFilter::HttpFilterProc

virtual DWORD HttpFilterProc( PHTTP_FILTER_CONTEXT pfc, DWORD NotificationType, LPVOID pvNotification );

Return Value

Indicates how the application handled the event. Indicated by a dwFlags value; see GetFilterVersion Remarks for a list of these values.

Parameters

pfc

A pointer to an HTTP_FILTER_CONTEXT structure. The HTTP_FILTER_CONTEXT structure pointed to by this parameter contains context information. The pfc structure member can be used by the filter to associate any context information with the HTTP request. The SF_NOTIFY_END_OF_NET_SESSION notification can be used to release any such context information.

NotificationType

Indicates the type of event being processed. Valid types are listed in GetFilterVersion.

pvNotification

A notification-specific structure.

Notification Type | pvNotification points to | MFC Calls
SF_NOTIFY_READ_RAW_DATA | HTTP_FILTER_RAW_DATA | OnReadRawData
SF_NOTIFY_SEND_RAW_DATA | HTTP_FILTER_RAW_DATA | OnSendRawData
SF_NOTIFY_PREPROC_HEADERS | HTTP_FILTER_PREPROC_HEADERS | OnPreprocHeaders
SF_NOTIFY_AUTHENTICATION | HTTP_FILTER_AUTHENT | OnAuthentication
SF_NOTIFY_URL_MAP | HTTP_FILTER_URL_MAP | OnUrlMap
SF_NOTIFY_LOG | HTTP_FILTER_LOG | OnLog

Remarks

This member function is called by the framework to process data every time it passes through the filter. HttpFilterProc will call the appropriate CHttpFilter member functions, depending on the notification types given. For example, HttpFilterProc will call OnPreprocHeaders if the notification type is SF_NOTIFY_PREPROC_HEADERS.

HttpFilterProc is where the core work of the ISAPI filter applications is done. The various structures pointed to by pvNotification (listed in the table above) contain data and function pointers specific to these operations. See the structure details for more information about how data is processed by HttpFilterProc.

You can override the individual handlers (listed in the third column, above) to change the way data in their associated structures is processed.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also HTTP_FILTER_CONTEXT, HTTP_FILTER_AUTHENT, HTTP_FILTER_PREPROC_HEADERS, HTTP_FILTER_RAW_DATA, HTTP_FILTER_URL_MAP, HTTP_FILTER_LOG


CHttpFilter::OnAuthentication

virtual DWORD OnAuthentication( CHttpFilterContext* pfc, PHTTP_FILTER_AUTHENT pAuthent );

Return Value

One of the following notification types:

SF_STATUS_REQ_FINISHED

The filter has handled the HTTP request. The server should disconnect the session.

SF_STATUS_REQ_FINISHED_KEEP_CONN

Same as SF_STATUS_REQ_FINISHED except the server should keep the TCP session open if the option was negotiated.

SF_STATUS_REQ_NEXT_NOTIFICATION

The next filter in the notification chain should be called.

SF_STATUS_REQ_HANDLED_NOTIFICATION

This filter handled the notification. No other handlers should be called for this particular notification.

SF_STATUS_REQ_ERROR

An error occurred. The server should use the Win32 API SetLastError to indicate the error to the client.

SF_STATUS_REQ_READ_NEXT

The filter is an opaque stream filter; Negotiate the session parameters. Only valid for raw read notification.

If unsuccessful, the notification type SF_STATUS_REQ_ERROR should be returned. In this case, the server should use the Windows function SetLastError and indicate the error to the client.

Parameters

pfc

A CHttpFilterContext object, which contains context information. The CHttpFilterContext object can be used by the filter to associate any context information with the HTTP request.

pAuthent

A pointer to an HTTP_FILTER_AUTHENT structure.

Remarks

This member function is called by the framework to authenticate the client.

Override this member function to implement your own authentication. The default implementation does nothing.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also CHttpFilter::HttpFilterProc, HTTP_FILTER_AUTHENT, CHttpFilterContext


CHttpFilter::OnEndOfNetSession

virtual DWORD OnEndOfNetSession( CHttpFilterContext* pfc );

Return Value

One of the following notification types:

SF_STATUS_REQ_FINISHED

The filter has handled the HTTP request. The server should disconnect the session.

SF_STATUS_REQ_FINISHED_KEEP_CONN

Same as SF_STATUS_REQ_FINISHED except the server should keep the TCP session open if the option was negotiated.

SF_STATUS_REQ_NEXT_NOTIFICATION

The next filter in the notification chain should be called.

SF_STATUS_REQ_HANDLED_NOTIFICATION

This filter handled the notification. No other handlers should be called for this particular notification.

SF_STATUS_REQ_ERROR

An error occurred. The server should use the Win32 API SetLastError to indicate the error to the client.

SF_STATUS_REQ_READ_NEXT

The filter is an opaque stream filter; Negotiate the session parameters. Only valid for raw read notification.

If unsuccessful, the notification type SF_STATUS_REQ_ERROR should be returned. In this case, the server should use the Windows function SetLastError and indicate the error to the client.

Parameters

pfc

A CHttpFilterContext object, which contains context information and can be used by the filter to associate any context information with the HTTP request.

Remarks

This member function is called by the framework to notify the filter that the session is ending.

Override this member function to provide your own end of session implementation. The default implementation does nothing.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also CHttpFilter::HttpFilterProc, CHttpFilterContext


CHttpFilter::OnLog

virtual DWORD OnLog( CHttpFilterContext* pfc, PHTTP_FILTER_LOG pLog );

Return Value

One of the following notification types:

SF_STATUS_REQ_FINISHED

The filter has handled the HTTP request. The server should disconnect the session.

SF_STATUS_REQ_FINISHED_KEEP_CONN

Same as SF_STATUS_REQ_FINISHED except the server should keep the TCP session open if the option was negotiated.

SF_STATUS_REQ_NEXT_NOTIFICATION

The next filter in the notification chain should be called.

SF_STATUS_REQ_HANDLED_NOTIFICATION

This filter handled the notification. No other handlers should be called for this particular notification.

SF_STATUS_REQ_ERROR

An error occurred. The server should use the Win32 API SetLastError to indicate the error to the client.

SF_STATUS_REQ_READ_NEXT

The filter is an opaque stream filter; Negotiate the session parameters. Only valid for raw read notification.

If unsuccessful, the notification type SF_STATUS_REQ_ERROR should be returned. In this case, the server should use the Windows function SetLastError and indicate the error to the client.

Parameters

pfc

A CHttpFilterContext object, which contains context information, and can be used by the filter to associate any context information with the HTTP request.

pLog

A pointer to an HTTP_FILTER_LOG structure.

Remarks

This member function is called by the framework to inform the filter when the server is writing information to the server log.

Override this member function to provide your own method for logging information to the server file. The default implementation does nothing.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also CHttpFilter::HttpFilterProc, HTTP_FILTER_LOG, CHttpFilterContext


CHttpFilter::OnPreprocHeaders

virtual DWORD OnPreprocHeaders( CHttpFilterContext* pfc, PHTTP_FILTER_PREPROC_HEADERS pHeaders );

Return Value

One of the following notification types:

SF_STATUS_REQ_FINISHED

The filter has handled the HTTP request. The server should disconnect the session.

SF_STATUS_REQ_FINISHED_KEEP_CONN

Same as SF_STATUS_REQ_FINISHED except the server should keep the TCP session open if the option was negotiated.

SF_STATUS_REQ_NEXT_NOTIFICATION

The next filter in the notification chain should be called.

SF_STATUS_REQ_HANDLED_NOTIFICATION

This filter handled the notification. No other handlers should be called for this particular notification.

SF_STATUS_REQ_ERROR

An error occurred. The server should use the Win32 API SetLastError to indicate the error to the client.

SF_STATUS_REQ_READ_NEXT

The filter is an opaque stream filter; Negotiate the session parameters. Only valid for raw read notification.

If unsuccessful, the notification type SF_STATUS_REQ_ERROR should be returned. In this case, the server should use the Windows function SetLastError and indicate the error to the client.

Parameters

pfc

A CHttpFilterContext object, which contains context information. The CHttpFilterContext object can be used by the filter to associate any context information with the HTTP request.

pHeaders

A pointer to a HTTP_FILTER_PREPROC_HEADERS structure.

Remarks

This member function is called by the framework to notify the client that the server has preprocessed the client headers.

Override this member function to provide your own method for processing client headers. The default does nothing.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also CHttpFilter::HttpFilterProc, HTTP_FILTER_PREPROC_HEADERS, CHttpFilterContext


CHttpFilter::OnReadRawData

virtual DWORD OnReadRawData( CHttpFilterContext* pfc, PHTTP_FILTER_RAW_DATA pRawData );

Return Value

One of the following notification types:

SF_STATUS_REQ_FINISHED

The filter has handled the HTTP request. The server should disconnect the session.

SF_STATUS_REQ_FINISHED_KEEP_CONN

Same as SF_STATUS_REQ_FINISHED except the server should keep the TCP session open if the option was negotiated.

SF_STATUS_REQ_NEXT_NOTIFICATION

The next filter in the notification chain should be called.

SF_STATUS_REQ_HANDLED_NOTIFICATION

This filter handled the notification. No other handlers should be called for this particular notification.

SF_STATUS_REQ_ERROR

An error occurred. The server should use the Win32 API SetLastError to indicate the error to the client.

SF_STATUS_REQ_READ_NEXT

The filter is an opaque stream filter; Negotiate the session parameters. Only valid for raw read notification.

If unsuccessful, the notification type SF_STATUS_REQ_ERROR should be returned. In this case, the server should use the Windows function SetLastError and indicate the error to the client.

Parameters

pfc

A CHttpFilterContext object, which contains context information. The CHttpFilterContext object can be used by the filter to associate any context information with the HTTP request.

pRawData

A pointer to an HTTP_FILTER_RAW_DATA structure.

Remarks

This member function is called by the framework to allow the application to see the raw data. The data returned will contain both headers and data.

Override this member function to process raw data differently.The default implementation does nothing.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also CHttpFilter::HttpFilterProc, HTTP_FILTER_RAW_DATA, CHttpFilterContext, CHttpFilter::OnSendRawData


CHttpFilter::OnSendRawData

virtual DWORD OnSendRawData( CHttpFilterContext* pfc, PHTTP_FILTER_RAW_DATA pRawData );

Return Value

If successful, the notification type SF_STATUS_REQ_NEXT_NOTIFICATION. Call the next filter in the notification chain.

If unsuccessful, the notification type SF_STATUS_REQ_ERROR should be returned. In this case, the server should use the Windows function SetLastError and indicate the error to the client.

Parameters

pfc

A CHttpFilterContext object, which contains context information. The CHttpFilterContext object can be used by the filter to associate any context information with the HTTP request. The SF_NOTIFY_END_OF_NET_SESSION notification can be used to release any such context information.

pRawData

A pointer to an HTTP_FILTER_RAW_DATA structure.

Remarks

This member function is called by the framework to notify the client that the server is sending raw data back to the client.

Override this member function only to change the default notification handler used by HttpFilterProc and process raw data differently.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also CHttpFilter::HttpFilterProc, HTTP_FILTER_RAW_DATA, CHttpFilterContext, CHttpFilter::OnReadRawData


CHttpFilter::OnUrlMap

virtual DWORD OnUrlMap( CHttpFilterContext* pfc, PHTTP_FILTER_URL_MAP pUrlMap );

Return Value

One of the following notification types:

SF_STATUS_REQ_FINISHED

The filter has handled the HTTP request. The server should disconnect the session.

SF_STATUS_REQ_FINISHED_KEEP_CONN

Same as SF_STATUS_REQ_FINISHED except the server should keep the TCP session open if the option was negotiated.

SF_STATUS_REQ_NEXT_NOTIFICATION

The next filter in the notification chain should be called.

SF_STATUS_REQ_HANDLED_NOTIFICATION

This filter handled the notification. No other handlers should be called for this particular notification.

SF_STATUS_REQ_ERROR

An error occurred. The server should use the Win32 API SetLastError to indicate the error to the client.

SF_STATUS_REQ_READ_NEXT

The filter is an opaque stream filter; Negotiate the session parameters. Only valid for raw read notification.

If unsuccessful, the notification type SF_STATUS_REQ_ERROR should be returned. In this case, the server should use the Windows function SetLastError and indicate the error to the client.

Parameters

pfc

A CHttpFilterContext object, which contains context information. The CHttpFilterContext object can be used by the filter to associate any context information with the HTTP request.

pUrlMap

A pointer to an HTTP_FILTER_URL_MAP structure.

Remarks

This member function is called by the framework when the server is mapping a logical URL to a physical path.

Override this member function handle URL mapping differently. The default implementation does nothing.

CHttpFilter Overview | Class Members | Hierarchy Chart

See Also CHttpFilter::HttpFilterProc, HTTP_FILTER_URL_MAP, CHttpFilterContext


CHttpFilterContext

CHttpFilterContext does not have a base class.

CHttpFilterContext provides the tools that a CHttpFilter object needs to process data that passes through the filter. When the filter receives a request, a CHttpFilter object is created and initialized, and a CHttpFilterContext object is created. As the filter processes requests, it uses CHttpFilterContext member functions to perform tasks.

A CHttpFilterContext object exists separately from a CHttpFilter object in order to allow multi-threading. Only one CHttpFilter object exists in a module, but a filter might be required to process multiple client requests simultaneously.

CHttpFilter will create a CHttpFilterContext for each request to handle these multiple requests. A CHttpFilter uses multiple CHttpFilterContext objects to run in separate threads. This design allows simultaneous, multiple calls to the CHttpFilter object by different client connections.

When an extension DLL (ISA) is called, the member function ServerSupportFunction prompts the server to provide the general ISA information to the client.

If the filter must communicate something—for example, an error—back to the client immediately, call WriteClient.

#include <afxisapi.h>

Class Members | Hierarchy Chart

Sample MFC Sample MFCUCASE

See Also CHttpServer, CHttpFilter, HTTP_FILTER_CONTEXT


CHttpFilterContext Class Members

Data Members

m_pFC A pointer to an HTTP_FILTER_CONTEXT structure.

Construction

CHttpFilterContext Constructs a CHttpFilterContext object.

Attributes

GetServerVariable | Copies information relating to an HTTP connection, or to the server itself, into a buffer supplied by the caller.
AddResponseHeaders | Adds a header to the HTTP response.
WriteClient | Writes raw data to the client immediately.
AllocMem | Allocates memory in a buffer.
ServerSupportFunction | Provides general ISA information to the client.

CHttpFilterContext Overview | Hierarchy Chart

See Also HTTP_FILTER_CONTEXT


CHttpFilterContext::AddResponseHeaders

BOOL AddResponseHeaders( LPTSTR lpszHeaders, DWORD dwReserved =0 );

Return Value

Nonzero if successful, otherwise 0.

Parameters

lpszHeaders

A pointer to a string containing headers to add.

dwReserved

Reserved for future use. Must be 0.

Remarks

Call this member function to add a header to an HTTP response. The header string is contained in lpszHeaders. See the HSE_REQ_SEND_RESPONSE_HEADER value described in the CHttpServerContext::ServerSupportFunction topic for information about how a CHttpServer object delivers information about an HTTP server response header.


CHttpFilterContext::AllocMem

LPVOID AllocMem( DWORD cbSize, DWORD dwReserved );

Return Value

A pointer to a buffer, or NULL on error.

Parameters

cbSize

Specifies the size of the memory buffer to allocate, in bytes.

dwReserved

Reserved for future use.

Remarks

Call this member function to allocate memory that is automatically freed when the communication with the client is terminated.

When an HTTP filter is registered, usually it will register for the end-of-net-session event. This event is a good time to recycle any buffers used by that client request. For performance reasons, most filters will probably keep a pool of filter buffers and only allocate or free a buffer when the pool becomes empty or too large to save on the overhead of the memory management. Calling AllocMem can have a negative impact on performance, but with careful use, it can be a valuable tool.

Memory blocks allocated with AllocMem cannot be managed with the normal C run-time or Windows API memory management functions.


CHttpFilterContext::CHttpFilterContext

CHttpFilterContext( PHTTP_FILTER_CONTEXT pfc );

Parameters

pfc

A pointer to a HTTP_FILTER_CONTEXT structure.

Remarks

This member function is called by the framework during the construction of a CHttpFilterContext object.

CHttpFilterContext Overview | Class Members | Hierarchy Chart

See Also HTTP_FILTER_CONTEXT


CHttpFilterContext::GetServerVariable

BOOL GetServerVariable( LPTSTR lpszVariableName, LPVOID lpvBuffer, LPDWORD lpdwSize );

Return Value

Nonzero if successful, otherwise 0. The Win32 API call GetLastError can be used to determine why the call failed. Possible error values include:

Value | Meaning
ERROR_INVALID_PARAMETER | Bad connection handle.
ERROR_INVALID_INDEX | Bad or unsupported variable identifier.
ERROR_INSUFFICIENT_BUFFER | Buffer too small; the required size is returned in lpdwSize.
ERROR_MORE_DATA | Buffer too small, only part of data returned. The total size of the data is not returned.
ERROR_NO_DATA | The data requested is not available.

Parameters

lpszVariableName

Null-terminated string indicating which variable is being requested. See the Remarks section below for a selection of possible names. All variable names are as defined in the CGI specification located at http://hoohoo.ncsa.uiuc.edu/cgi/env.html.

lpvBuffer

Pointer to buffer to receive the requested information.

lpdwSize

Pointer to DWORD indicating the number of bytes available in the buffer. On successful completion the DWORD contains the number of bytes transferred into the buffer (including the null-terminating byte).

Remarks

This member function is called by the framework to copy information relating to an HTTP connection, or to the server itself, into a buffer supplied by the caller. Possible lpszVariableNames include:

Value | Meaning
ALL_HTTP | All HTTP headers that were not already parsed into one of the above variables. These variables are of the form HTTP_<header field name>.
AUTH_TYPE | Contains the type of authentication used. For example, if Basic authentication is used, the string will be "Basic". For Windows NT Challenge-response, it will be "NTLM". Other authentication schemes will have other strings. Because new authentication types can be added to Internet Server, it is not possible to list all possible strings. If the string is empty then no authentication is used.
CONTENT_LENGTH | The number of bytes which the script can expect to receive from the client.
CONTENT_TYPE | The content type of the information supplied in the body of a POST request.
GATEWAY_INTERFACE | The revision of the CGI specification to which this server complies. The current version is CGI/1.1.
HTTP_ACCEPT Special case HTTP header. Values of the Accept: fields are concatenated, separated by ", ". For example, if the following lines are part of the HTTP header:
accept: */*; q=0.1
accept: text/html
accept: image/jpeg

then the HTTP_ACCEPT variable will have a value of:

*/*; q=0.1, text/html, image/jpeg
PATH_INFO | Additional path information, as given by the client. This comprises the trailing part of the URL after the script name but before the query string (if any).
PATH_TRANSLATED | This is the value of PATH_INFO, but with any virtual path name expanded into a directory specification.
QUERY_STRING | The information which follows the ? in the URL which referenced this script.
REMOTE_ADDR | The IP address of the client.
REMOTE_HOST | The hostname of the client.
REMOTE_USER | This contains the username supplied by the client and authenticated by the server.
REQUEST_METHOD | The HTTP request method.
SCRIPT_NAME | The name of the script program being executed.
SERVER_NAME | The server's hostname (or IP address) as it should appear in self-referencing URLs.
SERVER_PORT | The TCP/IP port on which the request was received.
SERVER_PROTOCOL | The name and version of the information retrieval protocol relating to this request. Normally HTTP/1.0.
SERVER_SOFTWARE | The name and version of the web server under which the CGI program is running.


CHttpFilterContext::ServerSupportFunction

BOOL ServerSupportFunction(enum SF_REQ_TYPE sfReq, PVOID pvData, LPDWORD lpdwSize, LPDDWORD lpdwDataType )

Return Value

Nonzero if successful, otherwise 0.

Parameters

sfReq

Server request type. See the Remarks section for a list of of the possible values.

pvData

A pointer to a zero-terminated string. Its value is specific to the sfReq extension. When used with SF_REQ_SEND_RESPONSE_HEADER, it is an optional, null-terminated status string (for example, "401 Access Denied") or NULL for the default response of "200 OK". When used with SF_REQ_ADD_HEADERS_ON_DENIAL, it is a null-terminated string pointing to one or more header lines with terminating '\r\n'.

lpdwSize

Null-terminated string. Its value is specific to the extension. When used with SF_REQ_SEND_RESPONSE_HEADER, it is a null-terminated string pointing to optional data to be appended and set with the header. If NULL, the header will be terminated with an empty line. When used with SF_REQ_ADD_HEADERS_ON_DENIAL, it is the size in bytes for the next read.

lpdwDataType

A null-terminated string pointing to optional headers or data to be appended and sent with the header. If NULL, the header will be terminated by a “\r\n” pair.

Remarks

Call this member function to extend the ISA APIs.

The HTTP Server Extension value represented by sfReq, can be one of the following:

SF_REQ_SEND_RESPONSE_HEADER

Sends a complete HTTP server response header including the status, server version, message time, and MIME (Multipurpose Internet Mail Extension) version. Server extensions should append other information at the end, such as Content-type, Content-length, and so forth, followed by an extra '\r\n'.

SF_REQ_ADD_HEADERS_ON_DENIAL

If the server denies the HTTP request, add the specified headers to the server error response. This allows an authentication filter to advertise its services without filtering every request. Generally the headers will be WWW-Authenticate headers with custom authentication schemes, but no restriction is placed on what headers may be specified.

SF_REQ_SET_NEXT_READ_SIZE

Only used by raw data filters that return SF_STATUS_READ_NEXT.


CHttpFilterContext::WriteClient

BOOL WriteClient( LPVOID lpvBuffer, LPDWORD lpdwBytes, DWORD dwReserved = 0 );

Return Value

Nonzero if successful, otherwise 0. If 0, use the Windows function GetLastError to determine the cause of the error.

Parameters

lpvBuffer

A pointer to the buffer containing the data.

lpdwBytes

A pointer to a DWORD containing the number of bytes to write from the buffer.

dwReserved

Reserved for future use. Must be 0.

Remarks

Call this member function to send raw data back to the client immediately.

CHttpFilterContext Overview | Class Members | Hierarchy Chart

See Also HTTP_FILTER_CONTEXT, CHttpServerContext::WriteClient


CHttpFilterContext::m_pFC

Remarks

The m_pFC data member is a pointer to an HTTP_FILTER_CONTEXT structure. The pointer points at the same structure passed to CHttpFilter::HttpFilterProc.

CHttpFilterContext Overview | Class Members | Hierarchy Chart

See Also HTTP_FILTER_CONTEXT


CHttpServer

CHttpServer does not have a base class.

The class CHttpServer, with CHttpServerContext, provides a means to extend the functionality of an ISAPI-compliant HTTP server. The class CHttpServer wraps the Internet Server API (ISAPI) functionality and can process various types of client requests, including extension DLLs. CHttpServer cannot process client requests from Common Gateway Interface (CGI) executables. These extension DLLs are sometimes called Internet Server Applications; however, they are DLLs, rather than EXEs. For brevity’s sake, we refer to an extension DLL as an ISA.

For more information on the difference between CGI and ISA, see Internet Server API (ISAPI) Extensions in Visual C++ Programmer’s Guide.

When an ISAPI HTTP server receives a request from a client browser, a CHttpServer object is created and initialized, and a CHttpServerContext object is created. Only one instance of CHttpServer may exist for each module; however, one CHttpServerContext object is created for each call to the server. A CHttpServer object uses multiple CHttpServerContext objects to run in separate threads. This design allows simultaneous, multiple calls to the CHttpServer object by different client connections. The CHttpServer object communicates with the client or server itself via the CHttpServerContext object.

When the server loads the ISA, it calls the ISA at the entry point GetExtensionVersion to get the version number of the specification on which the extension is based. For every client request, the HttpExtensionProc member function is called. The default (recommended) implementation of HttpExtensionProc will read client data and decide what action is to be taken. You can override this member function to customize the implementation.

Other CHttpServer member functions process the client request, format the responses, and correspond with the client.

When a client command is received by a CHttpServer object, the parse maps associate the command to its class member function and parameters. Only one parse map is created per CHttpServer object.

See Internet Server API (ISAPI) Parse Maps for general information on using the parse map macros. See BEGIN_PARSE_MAP and END_PARSE_MAP for information on how to create a parse map to handle client commands.

See the following macro descriptions for information about how the client commands are mapped to member functions and their arguments:

  • ON_PARSE_COMMAND

  • ON_PARSE_COMMAND_PARAMS

  • DEFAULT_PARSE_COMMAND

For more information on using parse maps to handle client commands, see ISAPI Extensions: Parse Maps in Visual C++ Programmer’s Guide.

For information on debugging internet extension DLLs, see Technical Note 63.

#include <afxisapi.h>

Class Members | Hierarchy Chart

Samples MFC Sample COUNTER | MFC Sample WWWQUOTE

See Also CHtmlStream


CHttpServer Class Members

Constructor

CHttpServer Constructs a CHttpServer object.

Overridables

CallFunction | Finds and executes the appropriate function associated with the command in the URL
OnParseError | Constructs a description of the error to be returned to the client.
OnWriteBody | Writes data back to the client.
HttpExtensionProc | Uses the callback functions to read client data and decide what action to take.
GetExtensionVersion | Gets the version number that the DLL extension is based on.
ConstructStream | Constructs a CHtmlStream object.
TerminateExtension | Provides a safe way to clean up threads and complete other shutdown type activities.

Attributes

StartContent | Inserts opening HTML tags into a CHtmlStream object to be returned to the client. Override to change or omit the default tags.
EndContent | Inserts closing HTML tags into a CHtmlStream object to be returned to the client. Override to change or omit the default tags.
WriteTitle | Inserts the title between the appropriate HTML tags in the CHtmlStream object to be returned to the client. Override to provide a different title.
GetTitle | Gets the title of an HTML document to be sent to the client.
AddHeader | Adds headers to a response before it is sent to the server.
InitInstance | Initializes the CHttpServer object.

CHttpServer Overview | Hierarchy Chart

See Also CHtmlStream, CHttpServerContext


CHttpServer::AddHeader

void AddHeader( CHttpServerContext* pCtxt, LPCTSTR pszString ) const;

Parameters

pCtxt

A pointer to a CHttpServerContext object.

pszString

A pointer to a string.

Remarks

Call this member function to add a header to the response before the response is sent to the server. Use AddHeader to append your own headers to those the server supplies when it receives CHttpServerContext::ServerSupportFunction HSE_REQ_SEND_RESPONSE_HEADERS. The extra header provides the client with more information.

For example, call AddHeader to specify your own "content-type," then call it to specify an encoding, and then call it once more to insert the "content-length" header. After you have called AddHeader as many times as you need, use << to stream your output until you are done.

Note Once you put data in the HTML stream in the server context, do not call AddHeader again. If you do, your HTML stream will not work properly.

Example

Here's an example of a function that creates an on-the-fly web-page:

void CHelloExtension::Default(CHttpServerContext* pCtxt)
{
   AddHeader(pCtxt, "Content-type = text/plain\r\n");
   (*pCtxt) << "Hello world!\r\n";
 }

CHttpServer Overview | Class Members | Hierarchy Chart

See Also CHttpServerContext, CHttpServerContext::ServerSupportFunction


CHttpServer::CallFunction

virtual int CallFunction( CHttpServerContext* pCtxt, LPTSTR pszQuery, LPTSTR pszCommand );

Return Value

A value of one of the following enum types:

Enum value | Description
callOK | The function call was successful.
callParamRequired | A required parameter was missing.
callBadParamCount | There were too many or too few parameters.
callBadCommand | The command name was not found.
callNoStackSpace | No stack space was available.
callNoStream | No CHtmlStream was available.
callMissingQuote | A parameter had a bad format.
callMissingParams | No parameters were available.
callBadParam | A parameter had a bad format (i.e., only one quote).

Parameters

pCtxt

Pointer to a CHttpServerContext object.

pszQuery

A pointer to a query. Specific to the type of command received from the client. See Remarks for more information.

pszCommand

Either a pointer to a query or NULL. Specific to the type of command received from the client. See Remarks for more information.

Remarks

Called by the framework to find and execute the appropriate function associated with the command in the URL.

Below is a breakdown between the types of methods received and the parameters:

Method type | pszQuery | pszCommand
GET | A pointer to the EXTENSION_CONTROL_BLOCK structure query string. | NULL
POST | A pointer to a query sent in the body of the command. | Pointer to the EXTENSION_CONTROL_BLOCK structure query string.

Note Fill-out forms authors are advised to use only the POST method because of browser inconsistencies, and because GET methods are limited to a 1024-byte buffer. When writing forms for ISAPI, either use only the POST method, or design the ISA so that only the default function handles the form.

For example, some browsers sending a form via GET with an action of:

TestLet.DLL?Command

will truncate Command and send:

TestLet.DLL?name=value

instead of the correct command:

TestLet.DLL?Command?name=value

By truncating Command, the browser removes the association to the ISA function needed to map the request. Unless the function Command is the default function, the form will not be handled correctly.

If you want to handle parsing of the EXTENSION_CONTROL_BLOCK structure function lpszQueryString yourself, override CallFunction and do not use the PARSE_MAP macros. See Internet Server API (ISAPI) Parse Maps for more information on using the parse map macros.

CHttpServer Overview | Class Members | Hierarchy Chart

See Also CHttpServerContext, Internet Server API (ISAPI) Parse Maps


CHttpServer::CHttpServer

CHttpServer( TCHAR cDelimiter );

Parameters

cDelimiter

A character identifying the token delimiter. By default, this delimiter is ‘&’.

Remarks

The run-time calls this function when constructing a CHttpServer object. Only one instance of CHttpServer may exist for each module. Once a CHttpServer object is created, it can be initialized with InitInstance.

After the ISA has been initiated by a client command and acted upon by the server, the client receives a response page that reflects the cDelimiter parameter in the URL. The cDelimiter parameter separates the command’s arguments that are parsed by the parse map macros ON_PARSE_COMMAND and ON_PARSE_COMMAND_PARAMS.

Example of cDelimiter

If the client initiates an ISA to view a colorized JPEG image from the URL http://www.jungle.org/, the command sent to the server could look like this:

http://www.Jungle.org/scripts/Apes.dll?Colorize

where Colorize is the command initiating the Colorize function.

The URL that the server returns to the client would look like this:

http://www.jungle.org/scripts/Apes.dll?Colorize?Target=Picture&Format=JPEG

The cDelimiter default delimiter & appears in the client’s URL between the two parameters Picture and Format of the function Colorize.

See ON_PARSE_COMMAND and ON_PARSE_COMMAND_PARAMS for more information about parsing commands.


CHttpServer::ConstructStream

virtual CHtmlStream* ConstructStream( );

Return Value

A pointer to a CHtmlStream object.

Remarks

This member function is called by the framework to construct a CHtmlStream object. Override this member function to create an instance of your own class to give it functionality other than the default.

See the constructor CHtmlStream::CHtmlStream for information about why you might override ConstructStream and provide special functionality for a CHtmlStream object.


CHttpServer::EndContent

virtual void EndContent( CHttpServerContext* pCtxt ) const;

Parameters

pCtxt

A pointer to a CHttpServerContext object. Cannot be NULL.

Remarks

This member function is called by the framework to insert the closing HTML tags “</Body>“ and “</HTML>“ into an HTML document to be returned to the client.

Override this member function to implement a behavior different from the default. For example, override if you are returning a stream type other than an HTML stream (like a JPEG image).

CHttpServer Overview | Class Members | Hierarchy Chart

See Also CHttpServer::StartContent


CHttpServer::GetExtensionVersion

virtual BOOL GetExtensionVersion( HSE_VERSION_INFO *pVer );

Return Value

Nonzero if successful; otherwise zero.

Parameters

pVer

A pointer to the HSE_VERSION_INFO structure containing version information for the server and fields for the client to indicate version number, notifications, and priority desired. There is also a space for the filter application to register a small description of itself.

Remarks

This member function is called by the framework when it loads an ISA. GetExtensionVersion gets the version number of the specification the DLL extension is based on. It also provides a short text description for server administrators.

GetExtensionVersion is one of two necessary entry points for an ISA. The second necessary entry point is the function HttpExtensionProc. Both of these are provided by MFC, with default implementation. Call the default implementation to set the version, and then override to replace the default text string with your own short description.

CHttpServer Overview | Class Members | Hierarchy Chart

See Also HSE_VERSION_INFO, CHttpServer::HttpExtensionProc


CHttpServer::GetTitle

virtual LPCTSTR GetTitle( ) const;

Return Value

A pointer to a string containing the title.

Remarks

This member function is called by the framework to get the title of an HTML document to be sent to the client.

Override to supply your own title.


CHttpServer::HttpExtensionProc

virtual DWORD HttpExtensionProc( EXTENSION_CONTROL_BLOCK *pECB );

Return Value

One of the following HTTP Server Extension messages:

HSE_STATUS_SUCCESS

The ISA has finished processing and the server can disconnect and free up allocated resources.

HSE_STATUS_SUCCESS_AND_KEEP_CONN

The ISA has finished processing and the server should wait for the next HTTP request if the client supports persistent connections. The application should only return this if it was able to send the correct content-length header to the client. The server is not required to keep the session open.

HSE_STATUS_PENDING

The ISA has queued the request for processing and will notify the server when it has finished. See HSE_REQ_DONE_WITH_SESSION under CHttpServerContext::ServerSupportFunction.

HSE_STATUS_ERROR

The ISA has encountered an error while processing the request and the server can disconnect and free up allocated resources.

Parameters

pECB

A pointer to an EXTENSION_CONTROL_BLOCK structure.

Remarks

This member function is called by the framework for each request for an ISA. HttpExtensionProc uses the callback functions to read client data and decide what action to take. Before returning to the server, a properly formatted response must be sent to the client via either the CHttpServerContext::WriteClient or the CHttpServerContext::ServerSupportFunction member function.

The default implementation of HttpExtensionProc is recommended; however you can override this member function to customize the implementation.

CHttpServer Overview | Class Members | Hierarchy Chart

See Also CHttpServerContext::WriteClient, CHttpServerContext::ServerSupportFunction


CHttpServer::InitInstance

virtual BOOL InitInstance(CHttpServerContext* pCtxt );

Return Value

Nonzero if initialization is successful; otherwise 0.

Parameters

pCtxt

A pointer to a CHttpServerContext object.

Remarks

This member function is called by the framework to initialize a CHttpServer object. InitInstance is called in CHttpServer::HttpExtensionProc, which is called by the framework for each request for an ISA.

Override this member function to provide CHttpServer custom initialization.


CHttpServer::OnParseError

virtual BOOL OnParseError( CHttpServerContext* pCtxt, int nCause );

Return Value

Nonzero error is successfully parsed; otherwise 0.

Parameters

pCtxt

A pointer to a CHttpServerContext object that contains an EXTENSION_CONTROL_BLOCK structure function dwHttpStatusCode. These status values are:

  • HTTP_STATUS_BAD_REQUEST

  • HTTP_STATUS_AUTH_REQUIRED

  • HTTP_STATUS_FORBIDDEN

  • HTTP_STATUS_NOT_FOUND

  • HTTP_STATUS_SERVER_ERROR

  • HTTP_STATUS_NOT_IMPLEMENTED

nCause

The cause of the error. Can be one of the following values:

Enum type | Description
callOK | OnParseError handled the error.
callParamRequired | A required parameter was missing.
callBadParamCount | There were too many or too few parameters.
callBadCommand | The command name was not found.
callNoStackSpace | No stack space was available.
callNoStream | No CHtmlStream was available.
callMissingQuote | A parameter is missing a quote mark.
callMissingParams | No parameters were available.
callBadParam | A parameter had a bad format.

Remarks

Called by the framework to parse errors. Once the error is identified, the message associated with the cause of the error is returned to the client either in an HTML stream or in a CHttpServerContext::WriteClient message.

Override this member function to customize the error parsing.


CHttpServer::OnWriteBody

BOOL OnWriteBody( CHttpServerContext* pCtxt, LPBYTE pbData, LPDWORD dwWrite, DWORD dwReserved = 0 );

Return Value

Zero for a failure, and nonzero for success.

Parameters

pCtxt

A pointer to a CHttpServerContext object

pbData

The data to be written to the client.

dwWrite

The number of bytes to be written to the client.

dwReserved

Reserved for future use; must be 0.

Remarks

Override this function to write data back to the server. MFC will call this function only when all of these conditions are true:

  • You have streamed data in the CHtmlStream object associated with the CHttpServerContext object.

  • You have not set CHttpServerContext::m_bSendHeaders to FALSE.

  • No other error has occurred in the processing of the request.

This function writes data back to the client by calling CHttpServerContext::WriteClient. It may make several calls to CHttpServerContext::WriteClient if the CHttpServerContext object has set a chunk size.

CHttpServer Overview | Class Members | Hierarchy Chart

See Also CHttpServerContext::SetChunkSize, CHttpServerContext::GetChunkSize


CHttpServer::StartContent

virtual void StartContent( CHttpServerContext* pCtxt ) const;

Parameters

pCtxt

A pointer to a CHttpServerContext object.

Remarks

This member function is called by the framework to insert the starting HTML tags “<Body>“ and “<HTML>“ into an HTML document to be returned to the client.

Override this member function to implement a behavior different from the default. For example, override if you are returning a stream type other than an HTML stream (like a JPEG image).

CHttpServer Overview | Class Members | Hierarchy Chart

See Also CHttpServer::EndContent


CHttpServer::TerminateExtension

BOOL TerminateExtension( DWORD dwFlags );

Return Value

If dwFlags is set to HSE_TERM_ADVISORY_UNLOAD, your override of this function can return TRUE to indicate that it can safely exit or FALSE to indicate that it is not ready to unload. If dwFlags is set to HSE_TERM_MUST_UNLOAD, the server is forcing the extension out of memory and the return value is ignored.

Parameters

dwFlags

A bitfield consisting of the following values:

  • HSE_TERM_ADVISORY_UNLOAD The server wants to unload the extension. The extension can return TRUE if OK to unload or FALSE if the server should not unload the extension.

  • HSE_TERM_MUST_UNLOAD The server is indicating the extension is about to be unloaded, the extension cannot refuse; the return value should be ignored.

Remarks

TerminateExtension gives you a safe way to clean up threads and complete other shutdown activities.


CHttpServer::WriteTitle

virtual void WriteTitle( CHttpServerContext* pCtxt ) const;

Parameters

pCtxt

A pointer to a CHttpServerContext object.

Remarks

This member function is called by the framework to write the title to insert between the appropriate HTML tags on the document to be transmitted back to the client.

The default implementation writes the title returned from GetTitle between the HTML tags “<Title>“ and “</Title>“. Override this member function to provide a different title.

CHttpServer Overview | Class Members | Hierarchy Chart

See Also CHttpServer::GetTitle


CHttpServerContext

CHttpServerContext does not have a base class.

CHttpServerContext provides the tools that a CHttpServer object needs to process data that a client has sent to the HTTP server. When a Microsoft Internet Information Server (MIIS) receives a request from a client browser, a CHttpServer object is created and initialized, and a CHttpServerContext object is created. As the server extension DLL processes requests, it uses CHttpServerContext member functions to perform tasks.

A CHttpServerContext object exists separately from a CHttpServer object in order to allow multithreading. Only one CHttpServer exists in a module, but a server might be required to process multiple client requests simultaneously.

CHttpServer creates a CHttpServerContext for each request to handle these multiple requests. A CHttpServer uses multiple CHttpServerContext objects to run in separate threads. This design allows simultaneous, multiple calls to the CHttpServer object by different client connections.

When an extension DLL (ISA) is called, the member function ServerSupportFunction provides the ISA with some general-purpose functions as well as functions that are specific to HTTP server implementation.

If the server extension must communicate something—for example, an error—back to the client immediately, call WriteClient. Otherwise, the server should output a message to the client to the m_pStream data member owned by the pCtxt parameter passed to it.

#include <afxisapi.h>

Class Members | Hierarchy Chart

Sample MFC Sample WWWQUOTE


CHttpServerContext Class Members

Data Members

m_bSendHeaders | A flag to control whether headers are automatically included in an HTTP response.
m_pECB | A pointer to an EXTENSION_CONTROL_BLOCK structure.
m_pStream | A pointer to a CHtmlStream.

Construction

CHttpServerContext Constructs a CHttpServerContext object.

Operations

GetServerVariable | Copies information relating to an HTTP connection, or to the server itself, into a supplied buffer.
WriteClient | Sends information to the HTTP client immediately.
ReadClient | Reads information from the body of the Web client's HTTP request into the buffer supplied by the caller.
ServerSupportFunction | Provides ISAs with some general-purpose functions as well as functions that are specific to HTTP server implementation.
TransmitFile | Sends the data from a file from the server to the requester.
GetChunkSize | Retrieve the current chunk size.
SetChunkSize | Set the chunk size for the current context.

Operators

operator << Writes data into a stream.

CHttpServerContext Overview | Hierarchy Chart

See Also CHttpServer


CHttpServerContext::CHttpServerContext

CHttpServerContext( EXTENSION_CONTROL_BLOCK* pECB );

Parameters

pECB

A pointer to an EXTENSION_CONTROL_BLOCK data structure.

Remarks

This member function is called by the framework during the construction of a CHttpServerContext object.


CHttpServerContext::GetChunkSize

DWORD SetChunkSize( ) const;

Return Value

The chunk size.

Remarks

Call this member function to retrieve the current chunk size.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also CHttpServerContext::SetChunkSize, CHttpServer::OnWriteBody


CHttpServerContext::GetServerVariable

BOOL GetServerVariable( LPTSTR lpszVariableName, LPVOID lpvBuffer, LPDWORD lpdwSize );

Return Value

Nonzero if successful, otherwise 0. If the call fails, the Windows function GetLastError may be called to determine the cause of the error. Possible error values include:

Value | Meaning
ERROR_INVALID_PARAMETER | Bad connection handle.
ERROR_INVALID_INDEX | Bad or unsupported variable identifier.
ERROR_INSUFFICIENT_BUFFER | Buffer too small, required size returned in *lpdwSize.
ERROR_MORE_DATA | Buffer too small, only part of data returned. The total size of the data is not returned.
ERROR_NO_DATA | The data requested is not available.

Parameters

lpszVariableName

Null terminated string indicating which variable is being requested. See the Remarks section for a list of current variables.

lpvBuffer

Pointer to buffer to receive the requested information.

lpdwSize

Pointer to DWORD indicating the number of bytes available in the buffer. On successful completion the DWORD contains the number of bytes transferred into the buffer (including the null-terminating byte).

Remarks

This function copies information relating to an HTTP connection, or to the server itself, into a buffer supplied by the caller.

Possible values for lpszVariableNames include:

Value | Meaning
AUTH_TYPE | Contains the type of authentication used. For example, if Basic authentication is used, the string will be "Basic". For Windows NT Challenge-response, it will be "NTLM". Other authentication schemes will have other strings. Because new authentication types can be added to Internet Server, it is not possible to list all possible strings. If the string is empty, then no authentication is used.
CONTENT_LENGTH | The number of bytes which the script can expect to receive from the client.
CONTENT_TYPE | The content type of the information supplied in the body of a POST request.
GATEWAY_INTERFACE | The revision of the CGI specification to which this server complies. The current version is CGI/1.1.
PATH_INFO | Additional path information, as given by the client. This comprises the trailing part of the URL after the extension DLL (script) name but before the query string (if any).
PATH_TRANSLATED | This is the value of PATH_INFO, but with any virtual path name expanded into a directory specification.
QUERY_STRING | The information which follows the ? in the URL which referenced this extension DLL.
REMOTE_ADDR | The IP address of the client.
REMOTE_HOST | The hostname of the client.
REMOTE_USER | This contains the username supplied by the client and authenticated by the server.
REQUEST_METHOD | The HTTP request method.
SCRIPT_NAME | The name of the extension DLL that is being executed.
SERVER_NAME | The server's hostname (or IP address) as it should appear in self-referencing URLs.
SERVER_PORT | The TCP/IP port on which the request was received.
SERVER_PROTOCOL | The name and version of the information retrieval protocol relating to this request. Normally HTTP/1.0.
SERVER_SOFTWARE | The name and version of the web server under which the ISA or server extension DLL program is running.
ALL_HTTP | All HTTP headers that were not already parsed into one of the above variables. These variables are of the form HTTP_<header field name>.
HTTP_ACCEPT Special case HTTP header. Values of the Accept: fields are concatenated, separated by ", ". For example, if the following lines are part of the HTTP header:
accept: */*; q=0.1
accept: text/html
accept: image/jpeg

then the HTTP_ACCEPT variable will have a value of:

*/*; q=0.1, text/html, image/jpeg


CHttpServerContext::ReadClient

BOOL ReadClient( LPVOID lpvBuffer, LPDWORD lpdwSize );

Return Value

Nonzero if successful, otherwise 0. If the socket used by the server to listen to the client is closed, it will return nonzero, but with zero bytes read.

If the call fails, the Windows function GetLastError may be called to determine the cause of the error.

Parameters

lpvBuffer

Pointer to the buffer area to receive the requested information.

lpdwSize

Pointer to DWORD indicating the number of bytes available in the buffer. On return *lpdwSize will contain the number of bytes actually transferred into the buffer.

Remarks

Call this member function to read information from the body of the Web client's HTTP request into the buffer supplied by the caller. ReadClient might be used to read data from an HTML form that uses the POST method. If more than *lpdwSize bytes are immediately available to be read, ReadClient will return after transferring that amount of data into the buffer. Otherwise it will block incoming data and wait for buffer space to become available.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also CHttpServerContext::WriteClient


CHttpServerContext::ServerSupportFunction

BOOL ServerSupportFunction( DWORD dwHSERRequest, LPVOID lpvBuffer, LPDWORD lpdwSize, LPDWORD lpdwDataType );

Return Value

Nonzero if successful, otherwise 0.

Parameters

dwHSERRequest

An HTTP Server Extension value. See the Remarks section for a list of the supported values.

lpvBuffer

When used with HSE_REQ_SEND_RESPONSE_HEADER, it points to a null terminated optional status string (for example, “401 Access Denied"). If this buffer is null, a default response of "200 OK" will be sent by this function. When used with HSE_REQ_DONE_WITH_SESSION, it points to a DWORD indicating the status code of the request.

lpdwSize

When used with HSE_REQ_SEND_RESPONSE_HEADER, it points to the size of the buffer lpdwDataType.

lpdwDataType

When used with HSE_REQ_SEND_RESPONSE_HEADER, this is a null-terminated string pointing to optional headers or data to be appended and sent with the header. If this is NULL, the header will be terminated by a “\r\n” pair.

Note General purpose functions should have a dwHSERequest value larger than HSE_REQ_END_RESERVED. Values up to HSE_REQ_END_RESERVED are reserved for mandatory ServerSupportFunctions and should not be used.

Remarks

Call this member function to provide the ISA with some general purpose functions as well as functions that are specific to HTTP server implementation.

The HTTP Server Extension value represented by dwHSERRequest can be one of the following:

HSE_REQ_SEND_URL_REDIRECT_RESP

Sends a 302(URL Redirect) message to the client. No further processing is needed after the call. This operation is similar to specifying "URI: <URL>" in a CGI script header. The variable lpvBuffer should point to a null terminated URL string. Variable lpdwSize should have the size of lpvBuffer. Variable lpdwDataType is ignored.

HSE_REQ_SEND_URL

Sends the data specified by the URL to the client as if the client had requested that URL. The Null terminated URL pointed to by lpvBuffer MUST be on the server and must not specify protocol information (i.e. it must begin with a '/' ). No further processing is required after this call. Variable lpdwSize points to a DWORD holding the size of lpvBuffer. Variable lpdwDataType is ignored.

HSE_REQ_SEND_RESPONSE_HEADER

Sends a complete HTTP server response header including the status, server version, message time and MIME version. The ISA or server extension should append other HTTP headers at the end such as the Content-Type, Content-Length, and so forth, followed by an extra “\r\n”.

HSE_REQ_DONE_WITH_SESSION

If the ISA or server extension wants to hold onto the session because it has extended processing requirements, it needs to tell the server when the session is finished so the server can close it and free the related structures. Variables lpvBuffer, lpdwSize, and lpdwDataType are all ignored.

HSE_REQ_END_RESERVED

Functions higher than this value are server specific and may not be available on all web servers that support ISAPI.

HSE_REQ_MAP_URL_TO_PATH

The lpvBuffer parameter is a pointer to the buffer that contains the logical path on entry and the physical path on exit. The lpdwSize parameter is a pointer to the DWORD containing the size of the buffer passed in lpvBuffer on entry, and the number of bytes placed in the buffer on exit. The lpdwDataType parameter is ignored). A Microsoft-specific extension.

HSE_REQ_GET_SSPI_INFO

The lpvBuffer is filled in with the context handle and *lpdwDataType is filled in with the credential handle. A context handle specifies a pointer type or a type identifier. A credential handle specifies authentication and authorization.

HSE_REQ_TRANSMIT_FILE

See TransmitFile for an easier method of transmitting a file to a requester.

Note The server does not ensure that the buffers are large enough before filling in the handles, and lpdwSize is not updated to reflect the amount of data copied into the lpvBuffer buffer. Since these are fixed size structures, it is assumed the pointers passed in are pointers to the structure and must be at least as large as the request structures.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also

CHttpFilterContext::ServerSupportFunction, CHttpServerContext::TransmitFile


CHttpServerContext::SetChunkSize

DWORD SetChunkSize( DWORD dwNewSize );

Return Value

The previous chunk size.

Parameters

dwNewSize

New chunk size.

Remarks

Call this member function to set the chunk size for the current context. The chunk size is the number of bytes that MFC will send back in an individual write operation when writing data from the body of the stream within the CHttpServerContext object back to the client. The chunk size is initially zero when the context is created. A chunk size of zero means that MFC will attempt to write the entire stream in one operation. Any other value causes the framework to divide the body of the response into chunks no larger than the specified size.

Setting a chunk size is not always necessary, but it can be required when you use HTTPS, because HTTPS is limited to writing 14 kilobytes per operation at a maximum. HTTPS is a variant of the HTTP protocol that uses the secure-sockets layer for its transport protocol.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also CHttpServerContext::GetChunkSize, CHttpServer::OnWriteBody


CHttpServerContext::TransmitFile

BOOL TransmitFile( HANDLE hFile, DWORD dwFlags = HSE_IO_DISCONNECT_AFTER_SEND, LPVOID pstrHeader = NULL, DWORD dwHeaderLen = 0, LPVOID pstrTrailer = NULL, DWORD dwTrailerLen = 0 );

Return Value

TRUE if the file's data was sent; otherwise, FALSE. To get extended error information, call GetLastError. The function returns FALSE if an overlapped I/O operation is not complete before TransmitFile returns. In that case, GetLastError returns ERROR_IO_PENDING.

Parameters

hFile

A handle to the file containing the data to transmit. The file must have been opened with FILE_FLAG_SEQUENTIAL_SCAN and FILE_FLAG_OVERLAPPED.

dwFlags

The attributes associated with the file. By default, HSE_IO_DISCONNECT_AFTER_SEND. See ServerSupportFunction in the Platform SDK for a list of possible attributes.

pstrHeader

A pointer to the string containing the header to send before transmitting the file's data. The header conveys to the receiving browser the type of data being sent and how it should be displayed. If NULL, the header is not sent.

dwHeaderLen

The length of the header. By default, 0. If pstrHeader is not NULL, and dwHeaderLen is 0, the function will use the Win32 function lstrlen to find the length of the trailer. (In this case, pstrTrailer must be a null-terminated string.)

pstrTrailer

A pointer to the string containing the trailer to send after transmitting the file's data. If NULL, the trailer is not sent.

dwTrailerLen

The length of the trailer. By default, 0. If pstrTrailer is not NULL, and dwTrailerLen is 0, the function will use the Win32 function lstrlen to find the length of the trailer. (In this case, pstrTrailer must be a null-terminated string.)

Remarks

Call this member function to transmit a file to a requester. This member function performs the operations of the ServerSupportFunction command flag HSE_REQ_TRANSMIT_FILE. The server performs this operation asynchronously. The server submits this operation to its internal asynchronous I/O queue and returns to the caller. MFC alters the context object to return HSE_STATUS_PENDING, and will use HSE_DONE_WITH_SESSION when the callback indicates completion of the I/O. MFC also sets m_bSendHeaders in the context object FALSE, because headers are sent automatically.

See the PINBALL sample for a demonstration of this member function.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also

CHttpServerContext::ServerSupportFunction


CHttpServerContext::WriteClient

BOOL WriteClient( LPVOID lpvBuffer, LPDWORD lpdwBytes, DWORD dwReserved = 0 );

Return Value

Nonzero if successful, otherwise 0. If the call fails, the Windows function GetLastError may be called to determine the cause of the error.

Parameters

lpvBuffer

Pointer to the buffer where the data is to be written.

lpdwBytes

Pointer to a DWORD that holds the number of characters to write from the buffer referenced by Buffer.

dwReserved

Reserved for future use.

Remarks

Call this member function to send information to the HTTP client immediately. For example, use WriteClient to send an error message.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also CHttpServerContext::ReadClient


CHttpServerContext::operator <<

void operator<<( LPCTSTR psz );

void operator<<( long int dw );

void operator<<( short int w );

void operator<<( const CHtmlStream& stream );

void operator<<( double d );

void operator<<( float f );

CHttpServerContext& operator<<( const CLongBinary& blob );

CHttpServerContext& operator<<( const CByteArray& array );

Remarks

The CHttpServerContext insertion (<<) operator writes the specified string or integer to the HTML stream owned by the CHttpServerContext object. The string version of the operator writes the string without modification. The integer overrides format the value as decimal text before writing it.

The operator parameters correspond directly to the ITS_ types that you can use in the ISAPI parse map.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also Internet Server API (ISAPI) Parse Maps, ISAPI Extensions: Parse Maps


CHttpServerContext::m_bSendHeaders

Remarks

A boolean flag that controls whether MFC automatically sends headers in an HTTP response. When MFC constructs a CHttpServerContext, it sets m_bSendHeaders to TRUE. If you set m_bSendHeaders to FALSE, no headers are sent. Suppressing automatic headers is useful if you want to keep a connection alive or you want to construct your own headers using CHttpServer::AddHeader.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also CHttpServer::AddHeader


CHttpServerContext::m_pECB

Remarks

A pointer to an EXTENSION_CONTROL_BLOCK structure. This structure contains information describing the connection between the client which issued this server extension command and the server. See the EXTENSION_CONTROL_BLOCK structure for a description of the individual members.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also EXTENSION_CONTROL_BLOCK


CHttpServerContext::m_pStream

Remarks

The m_pStream data member is the pointer to the initialized CHtmlStream, which your server can use to communicate with the client. Most extensions will write data to this stream as they do their work. MFC will write all of the data in this stream to the client when your function returns. If your function takes a long time to execute, you can use the WriteClient function to send data to the client immediately, even before your function ends.

CHttpServerContext Overview | Class Members | Hierarchy Chart

See Also CHtmlStream


CImageList

An “image list” is a collection of same-sized images, each of which can be referred to by its zero-based index. Image lists are used to efficiently manage large sets of icons or bitmaps. All images in an image list are contained in a single, wide bitmap in screen device format. An image list may also include a monochrome bitmap that contains masks used to draw images transparently (icon style). The Microsoft Win32 application programming interface (API) provides image list functions that enable you to draw images, create and destroy image lists, add and remove images, replace images, merge images, and drag images.

The CImageList class provides the functionality of the Windows common image list control. This control (and therefore the CImageList class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

For more information on using CImageList, see Control Topics and Using CImageList in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

See Also CListCtrl, CTabCtrl


CImageList Class Members

Data Members
Construction
Attributes
Operations

Data Members

m_hImageList A handle containing the image list attached to this object.

Construction

CImageList | Constructs a CImageList object.
Create | Initializes an image list and attaches it to a CImageList object.

Attributes

GetSafeHandle | Retrieves m_hImageList.
operator HIMAGELIST | Returns the HIMAGELIST attached to the CImageList.
FromHandle | Returns a pointer to a CImageList object when given a handle to a device context. If a CImageList object is not attached to the handle, a temporary CImageList object is created and attached.
FromHandlePermanent | Returns a pointer to a CImageList object when given a handle to an image list. If a CImageList object is not attached to the handle, NULL is returned.
DeleteTempMap | Called by the CWinApp idle-time handler to delete any temporary CImageList object created by FromHandle.
GetImageCount | Retrieves the number of images in an image list.
SetBkColor | Sets the background color for an image list.
GetBkColor | Retrieves the current background color for an image list.
GetImageInfo | Retrieves information about an image.

Operations

Attach | Attaches an image list to a CImageList object.
Detach | Detaches an image list object from a CImageList object and returns a handle to an image list.
DeleteImageList | Deletes an image list.
SetImageCount | Resets the count of images in an image list.
Add | Adds an image or images to an image list.
Remove | Removes an image from an image list.
Replace | Replaces an image in an image list with a new image.
ExtractIcon | Creates an icon based on an image and mask in an image list.
Draw | Draws the image that is being dragged during a drag-and-drop operation.
SetOverlayImage | Adds the zero-based index of an image to the list of images to be used as overlay masks.
Copy | Copies an image within a CImageList object.
DrawIndirect | Draws an image from an image list.
SetDragCursorImage | Creates a new drag image.
GetDragImage | Gets the temporary image list that is used for dragging.
Read | Reads an image list from an archive.
Write | Writes an image list to an archive.
BeginDrag | Begins dragging an image.
DragEnter | Locks updates during a drag operation and displays the drag image at a specified position.
EndDrag | Ends a drag operation.
DragLeave | Unlocks the window and hides the drag image so that the window can be updated.
DragMove | Moves the image that is being dragged during a drag-and-drop operation.
DragShowNolock | Shows or hides the drag image during a drag operation, without locking the window.


CImageList::Add

int Add( CBitmap* pbmImage, CBitmap* pbmMask );

int Add( CBitmap* pbmImage, COLORREF crMask );

int Add( HICON hIcon );

Return Value

Zero-based index of the first new image if successful; otherwise – 1.

Parameters

pbmImage

Pointer to the bitmap containing the image or images. The number of images is inferred from the width of the bitmap.

pbmMask

Pointer to the bitmap containing the mask. If no mask is used with the image list, this parameter is ignored.

crMask

Color used to generate the mask. Each pixel of this color in the given bitmap is changed to black and the corresponding bit in the mask is set to one.

hIcon

Handle of the icon that contains the bitmap and mask for the new image.

Remarks

Call this function to add one or more images or an icon to an image list.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Remove, CImageList::Replace, COLORREF


CImageList::Attach

BOOL Attach( HIMAGELIST hImageList );

Return Value

Nonzero if the attachment was successful; otherwise 0.

Parameters

hImageList

A handle to an image list object.

Remarks

Call this function to attach an image list to a CImageList object.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Detach, CImageList::GetSafeHandle


CImageList::BeginDrag

BOOL BeginDrag( int nImage, CPoint ptHotSpot );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nImage

Zero-based index of the image to drag.

ptHotSpot

Coordinates of the starting drag position (typically, the cursor position). The coordinates are relative to the upper left corner of the image.

Remarks

Call this function to begin dragging an image. This function creates a temporary image list that is used for dragging. The image combines the specified image and its mask with the current cursor. In response to subsequent WM_MOUSEMOVE messages, you can move the drag image by using the DragMove member function. To end the drag operation, you can use the EndDrag member function.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Draw, CImageList::EndDrag, CImageList::DragMove


CImageList::CImageList

CImageList( );

Remarks

Constructs a CImageList object.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Create


CImageList::Copy

BOOL Copy( int iDst, int iSrc, UINT uFlags = ILCF_MOVE );

BOOL Copy( int iDst, CImageList* pSrc, int iSrc, UINT uFlags = ILCF_MOVE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

iDst

The zero-based index of the image to be used as the destination of the copy operation.

iSrc

The zero-based index of the image to be used as the source of the copy operation.

uFlags

The bit flag value that specifies the type of copy operation to be made. This parameter can be one of the following values:

Value | Meaning
ILCF_MOVE | The source image is copied to the destination image's index. This operation results in multiple instances of a given image. ILCF_MOVE is the default.
ILCF_SWAP | The source and destination images exchange positions within the image list.

pSrc

A pointer to a CImageList object that is the target of the copy operation.

Remarks

This member function implements the behavior of the Win32 function ImageList_Copy, as described in the Platform SDK.


CImageList::Create

BOOL Create( int cx, int cy, UINT nFlags, int nInitial, int nGrow );

BOOL Create( UINT nBitmapID, int cx, int nGrow, COLORREF crMask );

BOOL Create( LPCTSTR lpszBitmapID, int cx, int nGrow, COLORREF crMask );

BOOL Create( CImageList& imagelist1, int nImage1, CImageList& imagelist2, int nImage2, int dx, int dy );

BOOL Create( CImageList* pImageList );

Return Value

Nonzero if successful; otherwise 0.

Parameters

cx

Dimensions of each image, in pixels.

cy

Dimensions of each image, in pixels.

nFlags

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

Value | Meaning
ILC_COLOR | Use the default behavior if none of the other ILC_COLOR* flags is specified. Typically, the default is ILC_COLOR4; but for older display drivers, the default is ILC_COLORDDB.
ILC_COLOR4 | Use a 4-bit (16 color) device-independent bitmap (DIB) section as the bitmap for the image list.
ILC_COLOR8 | Use an 8-bit DIB section. The colors used for the color table are the same colors as the halftone palette.
ILC_COLOR16 | Use a 16-bit (32/64k color) DIB section.
ILC_COLOR24 | Use a 24-bit DIB section.
ILC_COLOR32 | Use a 32-bit DIB section.
ILC_COLORDDB | Use a device-dependent bitmap.
ILC_MASK | Uses a mask. The image list contains two bitmaps, one of which is a monochrome bitmap used as a mask. If this value is not included, the image list contains only one bitmap.

nInitial

Number of images that the image list initially contains.

nGrow

Number of images by which the image list can grow when the system needs to resize the list to make room for new images. This parameter represents the number of new images the resized image list can contain.

nBitmapID

Resource IDs of the bitmap to be associated with the image list.

crMask

Color used to generate a mask. Each pixel of this color in the specified bitmap is changed to black, and the corresponding bit in the mask is set to one.

lpszBitmapID

A string containing the resource IDs of the images.

imagelist1

A reference to a CImageList object.

nImage1

Index of the first existing image.

imagelist2

A reference to a CImageList object.

nImage2

Index of the second existing image.

dx

Offset of the x-axis of the second image in relationship to the first image, in pixels.

dy

Offset of the y-axis of the second image in relationship to the first image, in pixels.

pImageList

A pointer to a CImageList object.

Remarks

You construct a CImageList in two steps. First call the constructor, then call Create, which creates the image list and attaches it to the CImageList object.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::CImageList, COLORREF


CImageList::DeleteImageList

BOOL DeleteImageList( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this function to delete an image list.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Detach


CImageList::DeleteTempMap

static void PASCAL DeleteTempMap( );

Remarks

Called automatically by the CWinApp idle-time handler, DeleteTempMap deletes any temporary CImageList objects created by FromHandle, but does not destroy any handles (hImageList) temporarily associated with the ImageList objects.


CImageList::Detach

HIMAGELIST Detach( );

Return Value

A handle to an image list object.

Remarks

Call this function to detach an image list object from a CImageList object. This function returns a handle to the image list object.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Attach, CImageList::DeleteImageList


CImageList::DragEnter

static BOOL DragEnter( CWnd* pWndLock, CPoint point );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pWndLock

Pointer to the window that owns the drag image.

point

Position at which to display the drag image. Coordinates are relative to the upper left corner of the window (not the client area).

Remarks

During a drag operation, locks updates to the window specified by pWndLock and displays the drag image at the position specified by point.

The coordinates are relative to the window’s upper left corner, so you must compensate for the widths of window elements, such as the border, title bar, and menu bar, when specifying the coordinates.

If pWndLock is NULL, this function draws the image in the display context associated with the desktop window, and coordinates are relative to the upper left corner of the screen.

This function locks all other updates to the given window during the drag operation. If you need to do any drawing during a drag operation, such as highlighting the target of a drag-and-drop operation, you can temporarily hide the dragged image by using the CImageList::DragLeave function.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::BeginDrag, CImageList::EndDrag, CImageList::DragMove, CImageList::DragLeave


CImageList::DragLeave

static BOOL DragLeave( CWnd* pWndLock );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pWndLock

Pointer to the window that owns the drag image.

Remarks

Unlocks the window specified by pWndLock and hides the drag image, allowing the window to be updated.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::BeginDrag, CImageList::EndDrag, CImageList::DragMove, CImageList::DragEnter


CImageList::DragMove

static BOOL DragMove( CPoint pt );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pt

New drag position.

Remarks

Call this function to move the image that is being dragged during a drag-and-drop operation. This function is typically called in response to a WM_MOUSEMOVE message. To begin a drag operation, use the BeginDrag member function.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::BeginDrag, CImageList::EndDrag, CImageList::Draw


CImageList::DragShowNolock

static BOOL DragShowNolock( BOOL bShow );

Return Value

Nonzero if successful; otherwise 0.

Parameters

bShow

Specifies whether the drag image is to be shown.

Remarks

Shows or hides the drag image during a drag operation, without locking the window.

The CImageList::DragEnter function locks all updates to the window during a drag operation. This function, however, does not lock the window.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::BeginDrag, CImageList::EndDrag, CImageList::DragEnter, CImageList::DragLeave, CImageList::Draw


CImageList::Draw

BOOL Draw( CDC* pdc, int nImage, POINT pt, UINT nStyle );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pdc

Pointer to the destination device context.

nImage

Zero-based index of the image to draw.

pt

Location at which to draw within the specified device context.

nStyle

Flag specifying the drawing style. It can be one or more of these values:

Value | Meaning
ILD_BLEND25, ILD_FOCUS | Draws the image, blending 25 percent with the system highlight color. This value has no effect if the image list does not contain a mask.
ILD_BLEND50, ILD_SELECTED, ILD_BLEND | Draws the image, blending 50 percent with the system highlight color. This value has no effect if the image list does not contain a mask.
ILD_MASK | Draws the mask.
ILD_NORMAL | Draws the image using the background color for the image list. If the background color is the CLR_NONE value, the image is drawn transparently using the mask.
ILD_TRANSPARENT | Draws the image transparently using the mask, regardless of the background color.

Remarks

Call this function to draw the image that is being dragged during a drag-and-drop operation.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::BeginDrag, CImageList::EndDrag, CImageList::DragMove


CImageList::DrawIndirect

BOOL DrawIndirect( IMAGELISTDRAWPARAMS* pimldp );

BOOL DrawIndirect( CDC* pDC, int nImage, POINT pt, SIZE sz, POINT ptOrigin, UINT fStyle = ILD_NORMAL, DWORD dwRop = SRCCOPY, COLORREF rgbBack = CLR_DEFAULT, COLORREF rgbFore = CLR_DEFAULT );

Return Value

TRUE if the image is successfully drawn; otherwise FALSE.

Parameters

pimldp

A pointer to an IMAGELISTDRAWPARAMS structure that contains information about the draw operation.

pDC

A pointer to the destination device context. You must delete this CDC object when you are done with it.

nImage

The zero-based index of the image to be drawn.

pt

A POINT structure containing the x– and y– coordinates where the image will be drawn.

sz

A SIZE structure indicating the size of the image to be drawn.

ptOrigin

A POINT structure containing the x– and y–coordinates specifying the upper-left corner of the drawing operation with respect to the image itself. Pixels of the image that are to the left of the x–coordinate and above the y–coordinate are not drawn.

fStyle

Flag specifying the drawing style and, optionally, the overlay image. See the Remarks section for information on the overlay image. MFC’s default implementation, 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 a mask.

Other possible styles are described under the fStyle member of the IMAGELISTDRAWPARAMS structure.

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. MFC’s default implementation, SRCCOPY, copies the source rectangle directly to the destination rectangle. This parameter is ignored if the fStyle parameter does not include the ILD_ROP flag.

Other possible values are described under the dwRop member of the IMAGELISTDRAWPARAMS structure.

rgbBack

The image background color, by default CLR_DEFAULT. This parameter can be an application-defined RGB value or one of the following values:

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

rgbFore

Image foreground color, by default CLR_DEFAULT. This parameter can be an application-defined RGB value or one of the following values:

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

Remarks

Call this member function to draw an image from an image list. Use the first version if you want to fill the Win32 structure yourself. Use the second version if you want to take advantage of one or more of MFC’s default arguments, or avoid managing the structure.

An overlay image is an image that is drawn on top of the primary image, specified in this member function by the nImage parameter. Draw an overlay mask by using the Draw member function with the one-based index of the overlay mask specified by using the INDEXTOOVERLAYMASK macro.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::SetOverlayImage


CImageList::EndDrag

static void EndDrag( );

Remarks

Call this function to end a drag operation. To begin a drag operation, use the BeginDrag member function.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::BeginDrag, CImageList::Draw, CImageList::DragMove


CImageList::ExtractIcon

HICON ExtractIcon( int nImage );

Return Value

Handle of the icon if successful; otherwise NULL.

Parameters

nImage

Zero-based index of the image.

Remarks

Call this function to create an icon based on an image and its related mask in an image list.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Replace


CImageList::FromHandle

static CImageList* PASCAL FromHandle( HIMAGELIST hImageList );

Return Value

A pointer to a CImageList object if successful; otherwise NULL.

Parameters

hImageList

Specifies the image list.

Remarks

Returns a pointer to a CImageList object when given a handle to an image list. If a CImageList is not already attached to the handle, a temporary CImageList object is created and attached. This temporary CImageList object is valid only until the next time the application has idle time in its event loop, at which time all temporary objects are deleted.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::FromHandlePermanent


CImageList::FromHandlePermanent

static CImageList* PASCAL FromHandlePermanent( HIMAGELIST hImageList );

Return Value

A pointer to a CImageList object if successful; otherwise NULL.

Parameters

hImageList

Specifies the image list.

Remarks

Returns a pointer to a CImageList object when given a handle to an image list. If a CImageList object is not attached to the handle, NULL is returned.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::FromHandle


CImageList::GetBkColor

COLORREF GetBkColor( ) const;

Return Value

The RGB color value of the CImageList object background color.

Remarks

Call this function to retrieve the current background color for an image list.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::SetBkColor, COLORREF


CImageList::GetDragImage

static CImageList* GetDragImage( LPPOINT lpPoint, LPPOINT lpPointHotSpot );

Return Value

If successful, a pointer to the temporary image list that is used for dragging; otherwise, NULL.

Parameters

lpPoint

Address of a POINT structure that receives the current drag position.

lpPointHotSpot

Address of a POINT structure that receives the offset of the drag image relative to the drag position.

Remarks

Gets the temporary image list that is used for dragging.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::SetDragCursorImage


CImageList::GetImageCount

int GetImageCount( ) const;

Return Value

The number of images.

Remarks

Call this function to retrieve the number of images in an image list.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::GetImageInfo


CImageList::GetImageInfo

BOOL GetImageInfo( int nImage, IMAGEINFO* pImageInfo ) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

nImage

Zero-based index of the image.

pImageInfo

Pointer to an IMAGEINFO structure that receives information about the image. The information in this structure can be used to directly manipulate the bitmaps for the image.

Remarks

Call this function to retrieve information about an image.

The IMAGEINFO structure contains information about an image in an image list.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::GetImageCount


CImageList::GetSafeHandle

HIMAGELIST GetSafeHandle( ) const;

Return Value

A handle to the attached image list; otherwise NULL if no object is attached.

Remarks

Call this function to retrieve the m_hImageList data member.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Attach, CImageList::Detach, CImageList::m_hImageList


CImageList::operator HIMAGELIST

operator HIMAGELIST( ) const;

Return Value

If successful, a handle to the image list represented by the CImageList object; otherwise NULL.

Remarks

Use this operator to get the attached handle of the CImageList object. This operator is a casting operator, which supports direct use of an HIMAGELIST object.


CImageList::Read

BOOL Read( CArchive* pArchive );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pArchive

A pointer to a CArchive object from which the image list is to be read.

Remarks

Call this function to read an image list from an archive.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Write


CImageList::Remove

BOOL Remove( int nImage );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nImage

Zero-based index of the image to remove.

Remarks

Call this function to remove an image from an image list object.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::DeleteImageList


CImageList::Replace

BOOL Replace( int nImage, CBitmap* pbmImage, CBitmap* pbmMask );

int Replace( int nImage, HICON hIcon );

Return Value

The version returning BOOL returns nonzero if successful; otherwise 0.

The version returning int returns the zero-based index of the image if successful; otherwise – 1.

Parameters

nImage

Zero-based index of the image to replace.

pbmImage

A pointer to the bitmap containing the image.

pbmMask

A pointer to the bitmap containing the mask. If no mask is used with the image list, this parameter is ignored.

hIcon

A handle to the icon that contains the bitmap and mask for the new image.

Remarks

Call this function to replace an image in an image list with a new image.

Call this member function after calling SetImageCount to assign the new, valid images to the placeholder image index numbers.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Remove


CImageList::SetBkColor

COLORREF SetBkColor( COLORREF cr );

Return Value

The previous background color if successful; otherwise CLR_NONE.

Parameters

cr

Background color to set. It can be CLR_NONE. In that case, images are drawn transparently using the mask.

Remarks

Call this function to set the background color for an image list.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::GetBkColor, COLORREF


CImageList::SetDragCursorImage

BOOL SetDragCursorImage( int nDrag, CPoint ptHotSpot );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nDrag

Index of the new image to be combined with the drag image.

ptHotSpot

Position of the hot spot within the new image.

Remarks

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 Windows ShowCursor function to hide the actual mouse cursor after calling CImageList::SetDragCursorImage. Otherwise, the system may appear to have two mouse cursors for the duration of the drag operation.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::BeginDrag, CImageList::EndDrag, CImageList::GetDragImage


CImageList::SetImageCount

BOOL SetImageCount( UINT uNewCount );

Return Value

Nonzero if successful; otherwise zero.

Parameters

uNewCount

The value specifying the new total number of images in the image list.

Remarks

Call this member function to reset the number of images in a CImageList object.

If you call this member function to increase the number of images in the image list, then call Replace for each additional image to to assign the new indexes to valid images. If you fail to assign the indexes to valid images, draw operations that create the new images will be unpredictable.

If you decrease the size of an image list by using this function, the truncated images are freed.


CImageList::SetOverlayImage

BOOL SetOverlayImage( int nImage, int nOverlay );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nImage

Zero-based index of the image to use as an overlay mask.

nOverlay

One-based index of the overlay mask.

Remarks

Call this function to add the zero-based index of an image to the list of images to be used as overlay masks. Up to four indices can be added to the list.

An overlay mask is an image drawn transparently over another image. Draw an overlay mask over an image by using the CImageList::Draw member function with the one-based index of the overlay mask specified by using the INDEXTOOVERLAYMASK macro

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Add


CImageList::Write

BOOL Write( CArchive* pArchive );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pArchive

A pointer to a CArchive object in which the image list is to be stored.

Remarks

Call this function to write an image list object to an archive.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Read


CImageList::m_hImageList

HIMAGELIST m_hImageList;

Remarks

A handle of the image list attached to this object. The m_hImageList data member is a public variable of type HIMAGELIST.

CImageList Overview | Class Members | Hierarchy Chart

See Also CImageList::Attach, CImageList::Detach, CImageList::Attach


CInternetConnection

The MFC class CInternetConnection manages your connection to an Internet server. It is the base class for MFC classes CFtpConnection, CHttpConnection, and CGopherConnection. Each of these classes provides additional functionality for communicating with the respective FTP, HTTP, or gopher server.

To communicate directly with an Internet server, you must have a CInternetSession object and a CInternetConnection object.

To learn more about how the WinInet classes work, see the article Internet Programming with WinInet in Visual C++ Programmer’s Guide.

#include <afxinet.h>


CInternetConnection Class Members

Construction

CInternetConnection Constructs a CInternetConnection object.

Operations

GetContext | Gets the context ID for this connection object.
GetSession | Gets a pointer to the CInternetSession object associated with the connection.
GetServerName | Gets the name of the server associated with the connection.

Operators

operator HINTERNET A handle to an Internet session.


CInternetConnection::CInternetConnection

CInternetConnection( CInternetSession* pSession, LPCTSTR pstrServer, INTERNET_PORT nPort = INTERNET_INVALID_PORT_NUMBER, DWORD dwContext = 1 );

Parameters

pSession

A pointer to a CInternetSession object.

pstrServer

A pointer to a string containing the server name.

nPort

The number that identifies the Internet port for this connection.

dwContext

The context identifier for the CInternetConnection object. See Remarks for more information about dwContext.

Remarks

This member function is called when a CInternetConnection object is created.

You never call CInternetConnection yourself; instead, call the CInternetSession member function for the type of connection you want to establish:

  • CInternetSession::GetFtpConnection

  • CInternetSession::GetHttpConnection

  • CInternetSession::GetGopherConnection

The default value for dwContext is sent by MFC to the CInternetConnection-derived object from the CInternetSession object that created the InternetConnection-derived object. The default is set to 1; however, you can explicitly assign a specific context identifier in the CInternetSession constructor for the connection. The object and any work it does will be associated with that context ID. The context identifier is returned to CInternetSession::OnStatusCallback to provide status on the object with which it is identified. See the article Internet First Steps: WinInet for more information about the context identifier.

CInternetConnection Overview | Class Members | Hierarchy Chart

See Also CInternetSession, CGopherConnection, CFtpConnection, CHttpConnection


CInternetConnection::GetContext

DWORD GetContext( ) const;

Return Value

The application-assigned context ID.

Remarks

Call this member function to get the context ID for this session. The context ID is originally specified in CInternetSession and propagates to CInternetConnection- and CInternetFile-derived classes, unless specified differently in the call to a function that opens the connection. The context ID is associated with any operation of the given object and identifies the operation’s status information returned by CInternetSession::OnStatusCallback.

For more information about how GetContext works with other WinInet classes to give the user status information, see the article Internet First Steps: WinInet for more information about the context identifier.

CInternetConnection Overview | Class Members | Hierarchy Chart

See Also CInternetSession::EnableStatusCallback


CInternetConnection::GetServerName

CString GetServerName( ) const;

Return Value

The name of the server this connection object is working with.

Remarks

Call this member function to get the name of the server associated with this Internet connection.

CInternetConnection Overview | Class Members | Hierarchy Chart

See Also CInternetSession, CGopherConnection, CFtpConnection, CHttpConnection


CInternetConnection::GetSession

CInternetSession* GetSession( ) const;

Return Value

A pointer to a CInternetSession object associated with this Internet connection object.

Remarks

Call this member function to get a pointer to the CInternetSession object that’s associated with this connection.

CInternetConnection Overview | Class Members | Hierarchy Chart

See Also CInternetSession, CGopherConnection, CFtpConnection, CHttpConnection


CInternetConnection::operator HINTERNET

operator HINTERNET( ) const;

Remarks

Use this operator to get the API-level handle for the current Internet session.

CInternetConnection Overview | Class Members | Hierarchy Chart

See Also CInternetSession, CGopherConnection, CFtpConnection, CHttpConnection


CInternetException

The CInternetException object represents an exception condition related to an Internet operation. The CInternetException class includes two public data members: one holds the error code associated with the exception, and the other holds the context identifier of the Internet application associated with the error.

For more information about context identifiers for Internet applications, see the article Internet Programming with WinInet in Visual C++ Programmer’s Guide.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

See Also CException


CInternetException Class Members

Construction

CInternetException Constructs a CInternetException object.

Data Members

m_dwError | The error that caused the exception.
m_dwContext | The context value associated with the operation that caused the exception.

CInternetException Overview | Base Class Members | Hierarchy Chart

See Also CException


CInternetException::CInternetException

CInternetException( DWORD dwError );

Parameters

dwError

The error that caused the exception.

Remarks

This member function is called when a CInternetException object is created. To throw a CInternetException, call the MFC global function AfxThrowInternetException.

CInternetException Overview | Class Members | Hierarchy Chart

See Also CException


CInternetException::m_dwContext

Remarks

The context value associated with the related Internet operation. The context identifier is originally specified in CInternetSession and passed by MFC to CInternetConnection- and CInternetFile-derived classes. You can override this default and assign any dwContext parameter a value of your choosing. dwContext is associated with any operation of the given object. dwContext identifies the operation’s status information returned by CInternetSession::OnStatusCallback.

CInternetException Overview | Class Members | Hierarchy Chart

See Also CException


CInternetException::m_dwError

Remarks

The error that caused the exception. This error value may be a system error code, found in WINERROR.H, or an error value from WININET.H.

For a list of Win32 error codes, see Error Codes in the Win32 SDK. For a list of Internet-specific error codes, see the ActiveX SDK documentation.

CInternetException Overview | Class Members | Hierarchy Chart

See Also CException


CInternetFile

The MFC class CInternetFile provides a base class for the CHttpFile and CGopherFile file classes. CInternetFile and its derived classes allow access to files on remote systems that use Internet protocols. You never create a CInternetFile object directly. Instead, create an object of one of its derived classes by calling CGopherConnection::OpenFile or CHttpConnection::OpenRequest. You also can create a CInternetFile object by calling CFtpConnection::OpenFile.

The CInternetFile member functions Open, LockRange, UnlockRange, and Duplicate are not implemented for CInternetFile. If you call these functions on a CInternetFile object, you will get a CNotSupportedException.

To learn more about how CInternetFile works with the other MFC Internet classes, see the article Internet Programming with WinInet in Visual C++ Programmer’s Guide.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

See Also CInternetConnection


CInternetFile Class Members

Construction

CInternetFile Constructs a CInternetFile object.

Operations

SetWriteBufferSize | Sets the size of the buffer where data will be written.
SetReadBufferSize | Sets the size of the buffer where data will be read.

Overridables

Seek | Repositions the pointer in an open file.
Read | Reads the number of specified bytes.
Write | Writes the number of specified bytes.
Abort | Closes the file, ignoring all warnings and errors.
Flush | Flushes the contents of the write buffer and makes sure the data in memory is written to the target machine.
Close | Closes a CInternetFile and frees its resources.
ReadString | Reads a stream of characters.
WriteString | Writes a null-terminated string to a file.

Data Members

m_hFile A handle to a file.

Operators

operator HINTERNET A casting operator for an Internet handle.


CInternetFile::Abort

virtual void Abort( );

Remarks

Closes the file associated with this object and makes the file unavailable for reading or writing. If you have not closed the file before destroying the object, the destructor closes it for you.

When handling exceptions, Abort differs from Close in two important ways. First, the Abort function does not throw an exception on failures because it ignores failures. Second, Abort does not ASSERT if the file has not been opened or was closed previously.


CInternetFile::CInternetFile

CInternetFile( );

Remarks

This member function is called when a CInternetFile object is created.

You never create a CInternetFile object directly. Instead, create an object of one of its derived classes by calling CGopherConnection::OpenFile or CHttpConnection::OpenRequest. You also can create a CInternetFile object by calling CFtpConnection::OpenFile.

CInternetFile Overview | Class Members | Hierarchy Chart

See Also CInternetConnection, CHttpFile CGopherFile


CInternetFile::Close

virtual void Close( );
Throw ( CInternetException );

Remarks

Closes a CInternetFile and frees any of its resources. If the file was opened for writing, there is an implicit call to Flush to assure that all buffered data is written to the host. You should call Close when you are finished using a file.


CInternetFile::Flush

virtual void Flush( );
Throw ( CInternetException );

Remarks

Call this member function to flush the contents of the write buffer. Use Flush to assure that all data in memory has actually been written to the target machine and to assure your transaction with the host machine has been completed. Flush is only effective on CInternetFile objects opened for writing.


CInternetFile::Read

virtual UINT Read( void* lpBuf, UINT nCount );
throw CInternetException( );

Return Value

The number of bytes transferred to the buffer. The return value may be less than nCount if the end of file was reached.

Parameters

lpBuf

A pointer to a memory address to which file data is read.

nCount

The number of bytes to be written.

Remarks

Call this member function to read into the given memory, starting at lpvBuf, the specified number of bytes, nCount. The function returns the number of bytes actually read—a number that may be less than nCount if the file ends. If an error occurs while reading the file, the function throws a CInternetException object that describes the error. Note that reading past the end of the file is not considered an error and no exception will be thrown.


CInternetFile::ReadString

virtual BOOL ReadString( CString& rString );
throw ( CInternetException );

virtual LPTSTR ReadString( LPTSTR pstr, UINT nMax );
throw ( CInternetException );

Return Value

A pointer to the buffer containing the text data. NULL if end-of-file was reached without reading any data; or, if boolean, FALSE if end-of-file was reached without reading any data.

Parameters

pstr

A pointer to a string which will receive the line being read.

nMax

The maximum number of characters to be read.

rString

A reference to the CString object that receives the read line.

Remarks

Call this member function to read a stream of characters until it finds a newline character. The function places the resulting line into the memory referenced by the pstr parameter. It stops reading characters when it reaches the maximum number of characters, specified by nMax. The buffer always receives a terminating null character.

If you call ReadString without first calling SetReadBufferSize, you will get a buffer of 4096 bytes.


CInternetFile::Seek

virtual LONG Seek( LONG lOffset, UINT nFrom );
throw ( CInternetException );

Return Value

The new byte offset from the beginning of the file if the requested position is legal; otherwise, the value is undefined and a CInternetException object is thrown.

Parameters

lOffset

Offset in bytes to move the read/write pointer in the file.

nFrom

Relative reference for the offset. Must be one of the following values:

  • CFile::begin Move the file pointer lOff bytes forward from the beginning of the file.

  • CFile::current Move the file pointer lOff bytes from the current position in the file.

  • CFile::end Move the file pointer lOff bytes from the end of the file. lOff must be negative to seek into the existing file; positive values will seek past the end of the file.

Remarks

Call this member function to reposition the pointer in a previously opened file. The Seek function permits random access to a file’s contents by moving the pointer a specified amount, absolutely or relatively. No data is actually read during the seek.

At this time, a call to this member function is only supported for data associated with CHttpFile objects. It is not supported for FTP or gopher requests. If you call Seek for one of these unsupported services, it will pass back you to the Win32 error code ERROR_INTERNET_INVALID_OPERATION.

When a file is opened, the file pointer is at offset 0, the beginning of the file.

Note Using Seek may cause an implicit call to Flush.


CInternetFile::SetReadBufferSize

BOOL SetReadBufferSize( UINT nReadSize );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

nReadSize

The desired buffer size in bytes.

Remarks

Call this member function to set the size of the temporary read buffer used by a CInternetFile-derived object. The underlying WinInet APIs do not perform buffering, so choose a buffer size that allows your application to read data efficiently, regardless of the amount of data to be read. If each call to Read normally involves a large aount of data (for example, four or more kilobytes), you should not need a buffer. However, if you call Read to get small chunks of data, or if you use ReadString to read individual lines at a time, then a read buffer improves application performance.

By default, a CInternetFile object does not provide any buffering for reading. If you call this member function, you must be sure that the file has been opened for read access.

You can increase the buffer size at any time, but shrinking the buffer will have no effect. If you call ReadString without first calling SetReadBufferSize, you will get a buffer of 4096 bytes.


CInternetFile::SetWriteBufferSize

BOOL SetWriteBufferSize( UINT nWriteSize );

Return Value

Nonzero if successful; otherwise 0. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

nWriteSize

The size of the buffer in bytes.

Remarks

Call this member function to set the size of the temporary write buffer used by a CInternetFile-derived object. The underlying WinInet APIs don’t perform buffering, so choose a buffer size that allows your application to write data efficiently regardless of the amount of data to be written. If each call to Write normally involves a large amount of data (for example, four or more kilobytes at a time), you should not need a buffer. However, if you call Write to write small chunks of data, a write buffer improves your application’s performance.

By default, a CInternetFile object does not provide any buffering for writing. If you call this member function, you must be sure that the file has been opened for write access. You can change the size of the write buffer at any time, but doing so causes an implicit call to Flush.


CInternetFile::Write

virtual void Write( const void* lpBuf, UINT nCount );
throw CInternetException( );

Parameters

lpvBuf

A pointer to the first byte to be written.

nCount

Specifies the number of bytes to be written.

Remarks

Call this member function to write into the given memory, lpvBuf, the specified number of bytes, nCount. If any error occurs while writing the data, the function throws a CInternetException describing the error.


CInternetFile::WriteString

virtual void WriteString( LPCTSTR pstr );
throw CInternetException( );

Parameters

pstr

A pointer to a string containing the contents to be written.

Remarks

This function writes a null-terminated string to the associated file.


CInternetFile::m_hFile

HINTERNET m_hFile;

Remarks

A handle to the file associated with this object.


CInternetFile::operator HINTERNET

operator HINTERNET( ) const;

Remarks

Use this operator to get the Windows handle for the current Internet session.


CInternetSession

Use class CInternetSession to create and initialize a single or several simultaneous Internet sessions and, if necessary, to describe your connection to a proxy server. If your Internet connection must be maintained for the duration of an application, you can create a CInternetSession member of the class CWinApp.

Once you have established an Internet session, you can call OpenURL. CInternetSession then parses the URL for you by calling the global function AfxParseURL. Regardless of its protocol type, CInternetSession interprets the URL and manages it for you. It can handle requests for local files identified with the URL resource "file://". OpenURL will return a pointer to a CStdioFile object if the name you pass it is a local file.

If you open a URL on an Internet server using OpenURL, you can read information from the site. If you want to perform service-specific (for example, HTTP, FTP, or gopher) actions on files located on a server, you must establish the appropriate connection with that server. To open a particular kind of connection directly to a particular service, use one of the following member functions:

  • GetGopherConnection to open a connection to a gopher service.

  • GetHttpConnection to open a connection to an HTTP service.

  • GetFtpConnection to open a connection to an FTP service.

QueryOption and SetOption allow you to set the query options of your session, such as time-out values, number of retries, and so on.

CInternetSession member functions SetCookie, GetCookie, and GetCookieLength provide the means to manage a Win32 cookie database, through which servers and scripts maintain state information about the client workstation.

During an Internet session, a transaction such as a search or data download can take appreciable time. The user might want to continue working, or might want to have status information about the progress of the transaction. To handle this problem, CInternetSession provides for searches and data transfer to occur asychronously, allowing the user to perform other tasks while waiting for the transfer to complete. If you want to provide the user with status information, or if you want to handle any operations asynchronously, three conditions must be set:

  • In the constructor, dwFlags must include INTERNET_FLAG_ASYNC.

  • In the constructor, dwContext must be set to a nonzero value.

  • You must establish a call back function by calling EnableStatusCallback

Use the overridable member function OnStatusCallback to get status information on asynchronous retrieval. To use this overridable member function, you must derive your own class from CInternetSession.

For more information about asynchronous operations, see the article Internet First Steps: WinInet in Visual C++ Programmer’s Guide. For general information about using the MFC WinInet classes, see the article Internet Programming with WinInet in Visual C++ Programmer’s Guide.

Note CInternetSession will throw an AfxThrowNotSupportedException for unsupported service types. Only the following service types are currently supported: FTP, HTTP, gopher, and file.

#include <afxinet.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample FTPTREE | MFC Sample TEAR

See Also CInternetConnection, CHttpConnection, CFtpConnection, CGopherConnection


CInternetSession Class Members

Construction

CInternetSession Constructs a CInternetSession object.

Attributes

QueryOption | Provides possible asserts for error checking.
SetOption | Sets options for the Internet session.
OpenURL | Parses and opens a URL.
GetFtpConnection | Opens an FTP session with a server. Logs on the user.
GetHttpConnection | Opens an HTTP server for an application that is trying to open a connection.
GetGopherConnection | Opens a gopher server for an application that is trying to open a connection.
EnableStatusCallback | Establishes a status callback routine. EnableStatusCallback is required for asynchronous operations.
ServiceTypeFromHandle | Gets the type of service from the Internet handle.

Operations

GetContext | Gets the context value for an Internet or application session.
Close | Closes the Internet connection when the Internet session is terminated.
SetCookie | Sets a cookie for the specified URL.
GetCookie | Returns cookies for the specified URL and all its parent URLs.
GetCookieLength | Retrieves the variable specifying the length of the cookie stored in the buffer.

Overridables |
OnStatusCallback | Updates the status of an operation when status callback is enabled.

Operators |
operator HINTERNET | A handle to the current Internet session.


CInternetSession::CInternetSession

CInternetSession( LPCTSTR pstrAgent = NULL, DWORD dwContext = 1, DWORD dwAccessType = INTERNET_OPEN_TYPE_PRECONFIG, LPCTSTR pstrProxyName = NULL, LPCTSTR pstrProxyBypass = NULL, DWORD dwFlags = 0 );

Parameters

pstrAgent

A pointer to a string that identifies the name of the application or entity calling the Internet functions (for example, "Microsoft Internet Browser"). If pstrAgent is NULL (the default), the framework calls the global function AfxGetAppName, which returns a null-terminated string containing an application’s name. Some protocols use this string to identify your application to the server.

dwContext

The context identifier for the operation. dwContext identifies the operation’s status information returned by CInternetSession::OnStatusCallback. The default is set to 1; however, you can explicitly assign a specific context ID for the operation. The object and any work it does will be associated with that context ID. If dwFlags includes INTERNET_FLAG_ASYNC, then objects created by this object have asynchronous behavior as long as a status callback routine is registered. In order for a function to be completed synchronously, dwContext has to be set to zero for that call.

dwAccessType

The type of access required. The following are valid values, exactly one of which may be supplied:

  • INTERNET_OPEN_TYPE_PRECONFIG Preconfigured (in the registry). This access type is set as the default.

  • INTERNET_OPEN_TYPE_DIRECT Direct to Internet.

  • INTERNET_OPEN_TYPE_PROXY Through CERN proxy.

pstrProxyName

The name of the preferred CERN proxy if dwAccessType is set as INTERNET_OPEN_TYPE_PROXY. The default is NULL.

pstrProxyBypass

A pointer to a string containing an optional list of server addresses. These addresses may be bypassed when using proxy access. If a NULL value is supplied, the bypass list will be read from the registry. This parameter is meaningful only if dwAccessType is set to INTERNET_OPEN_TYPE_PROXY.

dwFlags

Indicates various options such as caching and asynchronous behavior. The default is set to 0. The possible values include:

  • INTERNET_FLAG_DONT_CACHE Do not cache the data, either locally or in any gateway servers.

  • INTERNET_FLAG_ASYNC Future operations on this object may fail with ERROR_IO_PENDING. A status callback will be made with INTERNET_STATUS_REQUEST_COMPLETE when the operation finishes. This callback is on a thread other than the one for the original request. You must call EnableStatusCallback to establish a status callback routine, or the functions will be completed synchronously.

  • INTERNET_FLAG_OFFLINE Download operations are satisfied through the persistent cache only. If the item does not exist in the cache, an appropriate error code is returned. This flag may be combined with the bitwise OR (|) operator.

Remarks

This member function is called when a CInternetSession object is created. CInternetSession is the first Internet function called by an application. It initializes internal data structures and prepares for future calls from the application.

If dwFlags includes INTERNET_FLAG_ASYNC, then all handles derived from this handle will have asynchronous behavior as long as a status callback routine is registered.

If no Internet connection can be opened, CInternetSession throws an AfxThrowInternetException.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::Close, CInternetSession::EnableStatusCallback, CInternetSession::GetContext


CInternetSession::Close

virtual void Close( );

Remarks

Call this member function when your application has finished using the CInternetSession object.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::CInternetSession


CInternetSession::EnableStatusCallback

BOOL EnableStatusCallback( BOOL bEnable = TRUE );
Throw ( CInternetException );

Return Value

Nonzero if successful; otherwise 0. If the call fails, determine the cause of the failure by examining the thrown CInternetException object.

Parameters

bEnable

Specifies whether callback is enabled or disabled. The default is TRUE.

Remarks

Call this member function to enable status callback. When handling status callback, you can provide status about the progress of the operation (such as resolving name, connecting to server, and so on) in the status bar of the application. Displaying operation status is especially desirable during a long-term operation.

You can set a callback routine for synchronous operations; however, you must establish a callback routine for asynchronous operations because the asynchronous API makes a callback with INTERNET_STATUS_REQUEST_COMPLETE to indicate that the request has completed.

A callback for an asynchronous operation will be on a thread other than the one for the original request. The call can fail with an ERROR_IO_PENDING error if the request is not complete when the status callback occurs. The callback may be callled in a thread context different from the thread which initiated the request.

Because callbacks occur during the request’s processing, the application should spend as little time as possible in the callback to prevent degradation of data throughput to the network. For example, putting up a dialog box in a callback may be such a lengthy operation that the server terminates the request.

The status callback cannot be removed as long as any callbacks or any asynchronous functions are pending.

Note To handle any operations asynchronously, three conditions must be set:

  • In the constructor, dwFlags must include INTERNET_FLAG_ASYNC.

  • In the constructor, dwContext must be set to 1.

  • You must establish a call back function by calling EnableStatusCallback.

For more information about asynchronous operations, see the article Internet First Steps: WinInet in Visual C++ Programmer’s Guide.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::CInternetSession


CInternetSession::GetContext

DWORD GetContext( ) const;

Return Value

The application-defined context Identifier.

Remarks

Call this member function to get the context value for a particular application session. OnStatusCallback uses the context ID returned by GetContext to report the status of a particular application. For example, when a user activates an Internet request that involves returning status information, the status callback uses the context ID to report status on that particular request. If the user activates two separate Internet requests that both involve returning status information, OnStatusCallback uses the context identifiers to return status about their corresponding requests. Consequently, the context identifier is used for all status callback operations, and it is associated with the session until the session is ended.

For more information about asynchronous operations, see the article Internet First Steps: WinInet in Visual C++ Programmer’s Guide.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetConnection, CInternetSession::EnableStatusCallback, CInternetSession::OnStatusCallback


CInternetSession::GetCookie

static BOOL GetCookie( LPCSTR pstrUrl, LPCTSTR pstrCookieName, LPTSTR pstrCookieData, DWORD dwBufLen );

static BOOL GetCookie( LPCSTR pstrUrl, LPCTSTR pstrCookieName, CString& strCookieData );

Return Value

Returns TRUE if successful, or FALSE otherwise. If the call fails, call the Win32 function GetLastError to determine the cause of the error. The following error values apply:

  • ERROR_NO_MORE_ITEMS There is no cookie for the specified URL and all its parents.

  • ERROR_INSUFFICIENT_BUFFER The value passed in dwBufLen is insufficient to copy all the cookie data. The value returned in dwBufLen is the size of the buffer necessary to get all the data.

Parameters

pstrUrl

A pointer to a string containing the URL.

pstrCookieName

A pointer to a string containing the name of the cookie to get for the specified URL.

pstrCookieData

In the first overload, a pointer to a string containing the address of the buffer that receives the cookie data. This value can be NULL. In the second overload, a reference to a CString object to receive the cookie data.

dwBufLen

The variable specifying the size of the pstrCookieData buffer. If the function succeeds, the buffer receives the amount of data copied to the pstrCookieData buffer. If pstrCookieData is NULL, this parameter receives a value that specifies the size of the buffer necessary to copy all the cookie data.

Remarks

This member function implements the behavior of the Win32 function InternetGetCookie , as described in the Platform SDK.

In the second overload, MFC retrieves the cookie data into the supplied CString object.

See Also CInternetSession::GetCookieLength, CInternetSession::SetCookie


CInternetSession::GetCookieLength

static DWORD GetCookieLength( LPCSTR pstrUrl, LPCTSTR pstrCookieName );

Return Value

A DWORD value indicating the length of the cookie, stored in the buffer. Zero if no cookie with the name indicated by pstrCookieName exists.

Parameters

pstrUrl

A pointer to a string containing the URL

pstrCookieName

A pointer to a string containing the name of the cookie.

Remarks

Call this member function to get the length of the cookie stored in the buffer. This value is used by GetCookie.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::SetCookie


CInternetSession::GetFtpConnection

CFtpConnection* GetFtpConnection( LPCTSTR pstrServer, LPCTSTR pstrUserName = NULL, LPCTSTR pstrPassword = NULL, INTERNET_PORT nPort = INTERNET_INVALID_PORT_NUMBER, BOOL bPassive = FALSE );
Throw ( CInternetException );

Return Value

A pointer to a CFtpConnection object. If the call fails, determine the cause of the failure by examining the thrown CInternetException object.

Parameters

pstrServer

A pointer to a string containing the FTP server name.

pstrUserName

Pointer to a null-terminated string that specifies the name of the user to log in. If NULL, the default is anonymous.

pstrPassword

A pointer to a null-terminated string that specifies the password to use to log in. If both pstrPassword and pstrUserName are NULL, the default anonymous password is the user's email name. If pstrPassword is NULL (or an empty string) but pstrUserName is not NULL, a blank password is used. The following table describes the behavior for the four possible settings of pstrUserName and pstrPassword:

pstrUserName | pstrPassword | Username sent to FTP server | Password sent to FTP server
NULL or “ “ | NULL or “ “ | "anonymous" | User's email name
Non-NULL String | NULL or “ “ | pstrUserName | “ “
NULL Non-NULL String | ERROR | ERROR |
Non-NULL String | Non-NULL String | pstrUserName | pstrPassword

nPort

A number that identifies the TCP/IP port to use on the server.

bPassive

Specifies passive or active mode for this FTP session. If set to TRUE, it sets the Win32 API dwFlag to INTERNET_FLAG_PASSIVE.

Remarks

Call this member function to establish an FTP connection and get a pointer to a CFtpConnection object.

GetFtpConnection connects to an FTP server, and creates and returns a pointer to a CFTPConnection object. It does not perform any specific operation on the server. If you intend to read or write to files, for example, you must perform those operations as separate steps. See the classes CFtpConnection and CFtpFileFind for information about searching for files, opening files, and reading or writing to files. See the article Internet Programming with WinInet in Visual C++ Programmer’s Guide for steps in performing common FTP connection tasks.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CFtpConnection CInternetSession::GetGopherConnection, CInternetSession::GetHttpConnection, CInternetSession::OpenURL


CInternetSession::GetGopherConnection

CGopherConnection* GetGopherConnection( LPCTSTR pstrServer, LPCTSTR pstrUserName = NULL, LPCTSTR pstrPassword = NULL, INTERNET_PORT nPort = INTERNET_INVALID_PORT_NUMBER );
Throw ( CInternetException );

Return Value

A pointer to a CGopherConnection object. If the call fails, determine the cause of the failure by examining the thrown CInternetException object.

Parameters

pstrServer

A pointer to a string containing the gopher server name.

pstrUserName

A pointer to a string containing the user name.

pstrPassword

A pointer to a string containing the access password.

nPort

A number that identifies the TCP/IP port to use on the server.

Remarks

Call this member function to establish a new gopher connection and get a pointer to a CGopherConnection object.

GetGopherConnection connects to a gopher server, and creates and returns a pointer to a CGopherConnection object. It does not perform any specific operation on the server. If you intend to read or write data, for example, you must perform those operations as separate steps. See the classes CGopherConnection, CGopherFile, and CGopherFileFind for information about searching for files, opening files, and reading or writing to files. For information about browsing an FTP site, see the member function OpenURL. See the article Internet Programming with WinInet in Visual C++ Programmer’s Guide for steps in performing common gopher connection tasks.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CGopherConnection, CInternetSession::GetFtpConnection, CInternetSession::GetHttpConnection, CInternetSession::OpenURL


CInternetSession::GetHttpConnection

CHttpConnection* GetHttpConnection( LPCTSTR pstrServer, INTERNET_PORT nPort = INTERNET_INVALID_PORT_NUMBER, LPCTSTR pstrUserName = NULL, LPCTSTR pstrPassword = NULL );
Throw ( CInternetException );

CHttpConnection* GetHttpConnection( LPCTSTR pstrServer, DWORD dwflags, INTERNET_PORT nPort = INTERNET_INVALID_PORT_NUMBER, LPCTSTR pstrUserName = NULL, LPCTSTR pstrPassword = NULL );
Throw ( CInternetException );

Return Value

A pointer to a CHttpConnection object. If the call fails, determine the cause of the failure by examining the thrown CInternetException object.

Parameters

pstrServer

A pointer to a string containing the HTTP server name.

nPort

A number that identifies the TCP/IP port to use on the server.

pstrUserName

A pointer to a string containing the user name.

pstrPassword

A pointer to a string containing the access password.

dwflags

The flags describing

Remarks

Call this member function to establish an HTTP connection and get a pointer to a CHttpConnection object.

GetHttpConnection connects to an HTTP server, and creates and returns a pointer to a CHttpConnection object. It does not perform any specific operation on the server. If you intend to query an HTTP header, for example, you must perform this operation as a separate step. See the classes CHttpConnection and CHttpFile for information about operations you can perform by using a connection to an HTTP server. For information about browsing an HTTP site, see the member function OpenURL. See the article Internet Programming with WinInet in Visual C++ Programmer’s Guide for steps in performing common HTTP connection tasks.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CHttpConnection, CInternetSession::GetGopherConnection, CInternetSession::GetFtpConnection, CInternetSession::OpenURL


CInternetSession::OnStatusCallback

virtual void OnStatusCallback( DWORD dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength );

Parameters

dwContext

The context value supplied by the application.

dwInternetStatus

A status code which indicates why the callback is being made. See Remarks for a table of possible values.

lpvStatusInformation

A pointer to a buffer containing information pertinent to this callback.

dwStatusInformationLength

The size of lpvStatusInformation.

Remarks

This member function is called by the framework to update the status when status callback is enabled and an operation is pending. You must first call EnableStatusCallback to take advantage of status callback.

The dwInternetStatus parameter indicates the operation being performed and determines what the contents of lpvStatusInformation will be. dwStatusInformationLength indicates the length of the data included in lpvStatusInformation. The following status values for dwInternetStatus are defined as follows:

Value | Meaning
INTERNET_STATUS_RESOLVING_NAME | Looking up the IP address of the name contained in lpvStatusInformation.
INTERNET_STATUS_NAME_RESOLVED | Successfully found the IP address of the name contained in lpvStatusInformation.
INTERNET_STATUS_CONNECTING_TO_SERVER | Connecting to the socket address (SOCKADDR) pointed to by lpvStatusInformation.
INTERNET_STATUS_CONNECTED_TO_SERVER | Successfully connected to the socket address (SOCKADDR) pointed to by lpvStatusInformation.
INTERNET_STATUS_SENDING_REQUEST | Sending the information request to the server. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_ REQUEST_SENT | Successfully sent the information request to the server. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_RECEIVING_RESPONSE | Waiting for the server to respond to a request. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_RESPONSE_RECEIVED | Successfully received a response from the server. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_CLOSING_CONNECTION | Closing the connection to the server. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_CONNECTION_CLOSED | Successfully closed the connection to the server. The lpvStatusInformation parameter is NULL.
INTERNET_STATUS_HANDLE_CREATED | Used by the Win32 API function InternetConnect to indicate that it has created the new handle. This lets the application call the Win32 function InternetCloseHandle from another thread if the connect is taking too long. See the ActiveX SDK for more information about these functions.
INTERNET_STATUS_HANDLE_CLOSING | Successfully terminated this handle value.
INTERNET_STATUS_REQUEST_COMPLETE | Successfully completed the asynchronous operation. See the CInternetSession constructor for details on INTERNET_FLAG_ASYNC.The lpvStatusInformation parameter points at an INTERNET_ASYNC_RESULT structure, and dwStatusInformationLength 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 the Win32 function InternetGetLastResponseInfo. See the ActiveX SDK for more information about this function.

In the case of INTERNET_STATUS_REQUEST_COMPLETE, lpvStatusInformation points at an INTERNET_ASYNC_RESULT structure, which is defined as:

  • DWORD dwResult; The return code from the operation.

  • DWORD dwError; If dwResult indicates that the operation failed, this member contains the error code. If the operation was successful, this member usually contains ERROR_SUCCESS.

Override this member function to require some action before a status callback routine is performed.

Note Status callbacks need thread-state protection. If you are using MFC in a shared library, add the following line to the beginning of your override:

AFX_MANAGE_STATE( AfxGetAppModuleState( ) );

For more information about asynchronous operations, see the article Internet First Steps: WinInet in Visual C++ Programmer’s Guide.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::EnableStatusCallback, CInternetSession::GetContext


CInternetSession::OpenURL

CStdioFile* OpenURL( LPCTSTR pstrURL, DWORD dwContext = 1, DWORD dwFlags = INTERNET_FLAG_TRANSFER_ASCII, LPCTSTR pstrHeaders = NULL, DWORD dwHeadersLength = 0 );
Throw ( CInternetException );

Return Value

Returns a file handle for FTP, GOPHER, HTTP, and FILE-type Internet services only. Returns NULL if parsing was unsuccessful.

The pointer that OpenURL returns depends on pszURL’s type of service. The table below illustrates the possible pointers OpenURL can return.

URL type | Returns
file:// | CStdioFile*
http:// | CHttpFile*
gopher:// | CGopherFile*
ftp:// | CInternetFile*

Parameters

pstrURL

A pointer to the name of the URL to begin reading. Only URLs beginning with file:, ftp:, gopher:, or http: are supported. ASSERTS if pszURL is NULL.

dwContext

An application-defined value passed with the returned handle in callback.

dwFlags

The flags describing how to handle this connection. See Remarks for more information about the valid flags. The valid flags are:

  • INTERNET_FLAG_TRANSFER_ASCII The default. Transfer the file as ASCII text.

  • INTERNET_FLAG_TRANSFER_BINARY Transfer the file as a binary file.

  • INTERNET_FLAG_RELOAD Get the data from the wire even if it is locally cached.

  • INTERNET_FLAG_DONT_CACHE Do not cache the data, either locally or in any gateways.

  • INTERNET_FLAG_SECURE This flag is applicable to HTTP requests only. It requests secure transactions on the wire with Secure Sockets Layer or PCT.

  • INTERNET_OPEN_FLAG_USE_EXISTING_CONNECT If possible, reuse the existing connections to the server for new requests generated by OpenUrl instead of creating a new session for each connection request.

  • INTERNET_FLAG_PASSIVE Used for an FTP site. Uses passive FTP semantics. Used with CInternetConnection of OpenURL.

pstrHeaders

A pointer to a string containing the headers to be sent to the HTTP server.

dwHeadersLength

The length, in characters, of the additional headers. If this is -1L and pstrHeaders is non-NULL, then pstrHeaders is assumed to be zero terminated and the length is calculated.

Remarks

Call this member function to send the specified request to the HTTP server and allow the client to specify additional RFC822, MIME, or HTTP headers to send along with the request.

The parameter dwFlags must include either INTERNET_FLAG_TRANSFER_ASCII or INTERNET_FLAG_TRANSFER_BINARY, but not both. The remaining flags can be combined with the bitwise OR operator (|).

OpenURL, which wraps the Win32 function InternetOpenURL, allows only downloading, retrieving, and reading the data from an Internet server. OpenURL allows no file manipulation on a remote location, so it requires no CInternetConnection object.

To use connection-specific (that is, protocol-specific) functions, such as writing to a file, you must open a session, then open a particular kind of connection, then use that connection to open a file in the desired mode. See CInternetConnection for more information about connection-specific functions.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetConnection, CGopherConnection, CInternetSession::GetFtpConnection, CInternetSession::GetHttpConnection


CInternetSession::QueryOption

BOOL QueryOption( DWORD dwOption, LPVOID lpBuffer, LPDWORD lpdwBufLen ) const;

BOOL QueryOption( DWORD dwOption, DWORD& dwValue ) const;

Return Value

If the operation was successful, a value of TRUE is returned. If an error occurred, a value of FALSE is returned. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

dwOption

The Internet option to query. See InternetQueryOption in the Platform SDK for a list of the possible options.

lpBuffer

A buffer that receives the option setting.

lpdwBufLen

A pointer to a DWORD containing the length of lpBuffer. On return, this contains the length of the data placed into lpBuffer.

dwValue

Sent to QueryOption in place of lpBuffer.

Remarks

Provides five possible asserts for basic error-checking.

See CInternetSession::SetOption to select and set the specific option to query.

The possible settings for INTERNET_OPTION_HANDLE_TYPE include the following:

  • INTERNET_HANDLE_TYPE_INTERNET

  • INTERNET_HANDLE_TYPE_CONNECT_FTP

  • INTERNET_HANDLE_TYPE_CONNECT_GOPHER

  • INTERNET_HANDLE_TYPE_CONNECT_HTTP

  • INTERNET_HANDLE_TYPE_FTP_FIND

  • INTERNET_HANDLE_TYPE_FTP_FIND_HTML

  • INTERNET_HANDLE_TYPE_FTP_FILE

  • INTERNET_HANDLE_TYPE_FTP_FILE_HTML

  • INTERNET_HANDLE_TYPE_GOPHER_FIND

  • INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML

  • INTERNET_HANDLE_TYPE_GOPHER_FILE

  • INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML

  • INTERNET_HANDLE_TYPE_HTTP_REQUEST

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::ServiceTypeFromHandle, CInternetSession::SetOption


CInternetSession::ServiceTypeFromHandle

DWORD ServiceTypeFromHandle( HINTERNET hQuery );

Return Value

The Internet service type. See Remarks for a list of recognized service types.

Parameters

hQuery

A handle to an Internet query.

Remarks

Call this member function to get the type of service from the Internet handle. The following service types are recognized by MFC:

Service type | Return value
FTP | INTERNET_SERVICE_FTP
HTTP | INTERNET_SERVICE_HTTP
Gopher | INTERNET_SERVICE_GOPHER
File | AFX_INET_SERVICE_FILE

CInternetSession will throw an AfxThrowNotSupportedException for unsupported service types.

Note The return value AFX_INET_SERVICE_FILE is used only by MFC and is not recognized by Win32. This feature allows the client to access local files in the same way he or she would access Internet services.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::QueryOption, CInternetSession::operator HINTERNET


CInternetSession::SetCookie

static BOOL SetCookie( LPCSTR pstrUrl, LPCTSTR pstrCookieName, LPCTSTR pstrCookieData );

Return Value

Returns TRUE if successful, or FALSE otherwise. To get the specific error code, call GetLastError.

Parameters

pstrUrl

A pointer to a null-terminated string that specifies the URL for which the cookie should be set.

pstrCookieName

A pointer to a string containing the name of the cookie.

pstrCookieData

A pointer to a string containing the actual string data to associate with the URL.

Remarks

This member function implements the behavior of the Win32 message InternetSetCookie, as described in the Platform SDK.

See Also CInternetSession::GetCookieLength, CInternetSession::GetCookie


CInternetSession::SetOption

BOOL SetOption( DWORD dwOption, LPVOID lpBuffer, DWORD dwBufferLength );

BOOL SetOption( DWORD dwOption, DWORD dwValue );

Return Value

If the operation was successful, a value of TRUE is returned. If an error occurred, a value of FALSE is returned. If the call fails, the Win32 function GetLastError may be called to determine the cause of the error.

Parameters

dwOption

See CInternetSession::QueryOption for list of possible values.

lpBuffer

A buffer that contains the option setting.

dwBufferLength

The length of lpBuffer or the size of dwValue.

dwValue

A DWORD that contains the option setting.

Remarks

Call this member function to set options for the Internet session.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::ServiceTypeFromHandle, CInternetSession::QueryOption


CInternetSession::operator HINTERNET

operator HINTERNET( ) const;

Remarks

Use this operator to get the Windows handle for the current Internet session.

CInternetSession Overview | Class Members | Hierarchy Chart

See Also CInternetSession::ServiceTypeFromHandle


CIPAddressCtrl

An IP Address control, a control similar to an edit control, allows you to enter and manipulate a numerical address in Internet Protocol (IP) format.

The CIPAddressCtrl class provides the functionality of the Windows common IP Address control. This control (and therefore the CIPAddressCtrl class) is available only to programs running under Microsoft Internet Explorer 4.0 and later. They will also be available under future versions of Windows and Windows NT.

For more general information about the IP Address Control, see About IP Address Controls in the Platform SDK.

#include <afxcmn.h>


CIPAddressCtrl Class Members

Construction

CIPAddressCtrl | Constructs a CIPAddressCtrl object.
Create | Creates an IP Address Control and attaches it to a CIPAddressCtrl object.

Attributes

IsBlank | Determines if all fields in the IP Address Control are empty.
ClearAddress | Clears the contents of the IP Address Control.
GetAddress | Retrieves the address values for all four fields in the IP Address Control.
SetAddress | Sets the address values for all four fields in the IP Address Control.
SetFieldFocus | Sets the keyboard focus to the specified field in the IP Address Control.
SetFieldRange | Sets the range in the specified field in the IP Address Control.


CIPAddressCtrl::CIPAddressCtrl

CIPAddressCtrl( );

Remarks

Creates a CIPAddressCtrl object.

CIPAddressCtrl Overview | Class Members | Hierarchy Chart

See Also CIPAddressCtrl::Create


CIPAddressCtrl::ClearAddress

void ClearAddress( );

Remarks

This member function implements the behavior of the Win32 message IPM_CLEARADDRESS, as described in the Platform SDK.

CIPAddressCtrl Overview | Class Members | Hierarchy Chart

See Also CIPAddressCtrl::GetAddress, CIPAddressCtrl::SetAddress


CIPAddressCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if initialization was successful; otherwise 0.

Parameters

dwStyle

The IP Address Control’s style. Apply a combination of window styles. You must include the WS_CHILD style because the control must be a child window.

rect

A reference to the IP Address Control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

A pointer to the IP Address Control’s parent window. It must not be NULL.

nID

The IP Address Control’s ID.

Remarks

You construct a CIPAddressCtrl object in two steps.

  1. Call the constructor, which creates the CIPAddressCtrl object.

  2. Call Create, which creates the IP Address Control.

CIPAddressCtrl Overview | Class Members | Hierarchy Chart

See Also CIPAddressCtrl::CIPAddressCtrl


CIPAddressCtrl::GetAddress

int GetAddress( BYTE& nField0, BYTE& nField1, BYTE& nField2, BYTE& nField3 );

int GetAddress( DWORD& dwAddress );

Return Value

The number of non-blank fields in the IP Address Control.

Parameters

nField0

A reference to the field 0 value from a packed IP address.

nField1

A reference to the field 1 value from a packed IP address.

nField2

A reference to the field 2 value from a packed IP address.

nField3

A reference to the field 3 value from a packed IP address.

dwAddress

A reference to the address of a DWORD value that receives the IP address. See Remarks for a table that shows how dwAddress is filled.

Remarks

This member function implements the behavior of the Win32 message IPM_GETADDRESS, as described in the Platform SDK.

In the first prototype above, the numbers in fields 0 through 3 of the control, read left to right respectively, populate the four parameters. In the second prototype above, dwAddress is populated as follows.

Field | Bits containing the field value
0 | 24 through 31
1 | 16 through 23
2 | 8 through 15
3 | 0 through 7

CIPAddressCtrl Overview | Class Members | Hierarchy Chart

See Also CIPAddressCtrl::SetAddress


CIPAddressCtrl::IsBlank

BOOL IsBlank( ) const;

Return Value

Nonzero if all of the IP Address Control fields are empty; otherwise 0.

Remarks

This member function implements the behavior of the Win32 message IPM_ISBLANK, as described in the Platform SDK.


CIPAddressCtrl::SetAddress

void SetAddress( BYTE nField0, BYTE nField1, BYTE nField2, BYTE nField3 );

void SetAddress( DWORD dwAddress );

Parameters

nField0

The field 0 value from a packed IP address.

nField1

The field 1 value from a packed IP address.

nField2

The field 2 value from a packed IP address.

nField3

The field 3 value from a packed IP address.

dwAddress

A DWORD value that contains the new IP address. See Remarks for a table that shows how the DWORD value is filled.

Remarks

This member function implements the behavior of the Win32 message IPM_SETADDRESS, as described in the Platform SDK.

In the first prototype above, the numbers in fields 0 through 3 of the control, read left to right respectively, populate the four parameters. In the second prototype above, dwAddress is populated as follows.

Field | Bits containing the field value
0 | 24 through 31
1 | 16 through 23
2 | 8 through 15
3 | 0 through 7

CIPAddressCtrl Overview | Class Members | Hierarchy Chart

See Also CIPAddressCtrl::GetAddress, CIPAddressCtrl::ClearAddress


CIPAddressCtrl::SetFieldFocus

void SetFieldFocus( WORD nField );

Parameters

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 non-blank, focus is set to the first field.

Remarks

This member function implements the behavior of the Win32 message IPM_SETFOCUS, as described in the Platform SDK.

CIPAddressCtrl Overview | Class Members | Hierarchy Chart

See Also CIPAddressCtrl::SetFieldRange


CIPAddressCtrl::SetFieldRange

void SetFieldRange( int nField, BYTE nLower, BYTE nUpper );

Parameters

nField

Zero-based field index to which the range will be applied.

nLower

A reference to an integer receiving the lower limit of the specified field in this IP Address Control.

nUpper

A reference to an integer receiving the upper limit of the specified field in this IP Address Control.

Remarks

This member function implements the behavior of the Win32 message IPM_SETRANGE, as described in the Platform SDK.

Use the two parameters, nLower and nUpper, to indicate the lower and upper limits of the field, instead of the wRange parameter used with the Win32 message.

CIPAddressCtrl Overview | Class Members | Hierarchy Chart

See Also CIPAddressCtrl::SetFieldFocus


CList

template< class TYPE, class ARG_TYPE >
class CList : public CObject

Parameters

TYPE

Type of object stored in the list.

ARG_TYPE

Type used to reference objects stored in the list. Can be a reference.

Remarks

The CList class supports ordered lists of nonunique objects accessible sequentially or by value. CList lists behave like doubly-linked lists.

A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially and as a bookmark to hold a place. A position is not the same as an index, however.

Element insertion is very fast at the list head, at the tail, and at a known POSITION. A sequential search is necessary to look up an element by value or index. This search can be slow if the list is long.

If you need a dump of individual elements in the list, you must set the depth of the dump context to 1 or greater.

Certain member functions of this class call global helper functions that must be customized for most uses of the CList class. See Collection Class Helpers in the “Macros and Globals” section.

For more information on using CList, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxtempl.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample COLLECT

See Also CMap, CArray


CList Class Members

Construction

CList Constructs an empty ordered list.

Head/Tail Access

GetHead | Returns the head element of the list (cannot be empty).
GetTail | Returns the tail element of the list (cannot be empty).

Operations

RemoveHead | Removes the element from the head of the list.
RemoveTail | Removes the element from the tail of the list.
AddHead | Adds an element (or all the elements in another list) to the head of the list (makes a new head).
AddTail | Adds an element (or all the elements in another list) to the tail of the list (makes a new tail).
RemoveAll | Removes all the elements from this list.

Iteration

GetHeadPosition | Returns the position of the head element of the list.
GetTailPosition | Returns the position of the tail element of the list.
GetNext | Gets the next element for iterating.
GetPrev | Gets the previous element for iterating.

Retrieval/Modification

GetAt | Gets the element at a given position.
SetAt | Sets the element at a given position.
RemoveAt | Removes an element from this list, specified by position.

Insertion

InsertBefore | Inserts a new element before a given position.
InsertAfter | Inserts a new element after a given position.

Searching

Find | Gets the position of an element specified by pointer value.
FindIndex | Gets the position of an element specified by a zero-based index.

Status

GetCount | Returns the number of elements in this list.
IsEmpty | Tests for the empty list condition (no elements).


CList::AddHead

POSITION AddHead( ARG_TYPE newElement );

void AddHead( CList* pNewList );

Return Value

The first version returns the POSITION value of the newly inserted element.

Parameters

ARG_TYPE

Template parameter specifying the type of the list element (can be a reference).

newElement

The new element.

pNewList

A pointer to another CList list. The elements in pNewList will be added to this list.

Remarks

Adds a new element or list of elements to the head of this list. The list can be empty before the operation.

CList Overview | Class Members | Hierarchy Chart

See Also CList::GetHead, CList::RemoveHead


CList::AddTail

POSITION AddTail( ARG_TYPE newElement );

void AddTail( CList* pNewList );

Return Value

The first version returns the POSITION value of the newly inserted element.

Parameters

ARG_TYPE

Template parameter specifying the type of the list element (can be a reference).

newElement

The element to be added to this list.

pNewList

A pointer to another CList list. The elements in pNewList will be added to this list.

Remarks

Adds a new element or list of elements to the tail of this list. The list can be empty before the operation.

CList Overview | Class Members | Hierarchy Chart

See Also CObList::GetTail, CObList::RemoveTail


CList::CList

CList( int nBlockSize = 10 );

Parameters

nBlockSize

The memory-allocation granularity for extending the list.

Remarks

Constructs an empty ordered list. As the list grows, memory is allocated in units of nBlockSize entries.


CList::Find

POSITION Find( ARG_TYPE searchValue, POSITION startAfter = NULL) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if the object is not found.

Parameters

ARG_TYPE

Template parameter specifying the type of the list element (can be a reference).

searchValue

The value to be found in the list.

startAfter

The start position for the search.

Remarks

Searches the list sequentially to find the first element matching the specified searchValue. Note that the pointer values are compared, not the contents of the objects.

CList Overview | Class Members | Hierarchy Chart

See Also CList::GetNext, CList::GetPrev


CList::FindIndex

POSITION FindIndex( int nIndex ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if nIndex is negative or too large.

Parameters

nIndex

The zero-based index of the list element to be found.

Remarks

Uses the value of nIndex as an index into the list. It starts a sequential scan from the head of the list, stopping on the nth element.

CList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::GetNext, CObList::GetPrev


CList::GetAt

TYPE& GetAt( POSITION position );

TYPE GetAt( POSITION position ) const;

Return Value

See the return value description for GetHead.

Parameters

TYPE

Template parameter specifying the type of object in the list.

position

A POSITION value returned by a previous GetHeadPosition or Find member function call.

Remarks

A variable of type POSITION is a key for the list. It is not the same as an index, and you cannot operate on a POSITION value yourself. GetAt returns the element (or a reference to the element) associated with a given position.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

CList Overview | Class Members | Hierarchy Chart

See Also CList::Find, CList::SetAt, CList::GetNext, CList::GetPrev, CList::GetHead


CList::GetCount

int GetCount() const;

Return Value

An integer value containing the element count.

Remarks

Gets the number of elements in this list.

CList Overview | Class Members | Hierarchy Chart

See Also CList::IsEmpty


CList::GetHead

TYPE& GetHead( );

TYPE GetHead( ) const;

Return Value

If the list is const, GetHead returns a copy of the element at the head of the list. This allows the function to be used only on the right side of an assignment statement and protects the list from modification.

If the list is not const, GetHead returns a reference to an element of the list. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Parameters

TYPE

Template parameter specifying the type of object in the list.

Remarks

Gets the head element (or a reference to the head element) of this list.

You must ensure that the list is not empty before calling GetHead. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

CList Overview | Class Members | Hierarchy Chart

See Also CList::GetTail, CList::GetTailPosition, CList::AddHead, CList::RemoveHead


CList::GetHeadPosition

POSITION GetHeadPosition( ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if the list is empty.

Remarks

Gets the position of the head element of this list.

CList Overview | Class Members | Hierarchy Chart

See Also CList::GetTailPosition


CList::GetNext

TYPE& GetNext( POSITION& rPosition );

TYPE GetNext( POSITION& rPosition ) const;

Return Value

If the list is const, GetNext returns a copy of the element at the head of the list. This allows the function to be used only on the right side of an assignment statement and protects the list from modification.

If the list is not const, GetNext returns a reference to an element of the list. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Parameters

TYPE

Template parameter specifying the type of the elements in the list.

rPosition

A reference to a POSITION value returned by a previous GetNext, GetHeadPosition, or other member function call.

Remarks

Gets the list element identified by rPosition, then sets rPosition to the POSITION value of the next entry in the list. You can use GetNext in a forward iteration loop if you establish the initial position with a call to GetHeadPosition or Find.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

If the retrieved element is the last in the list, then the new value of rPosition is set to NULL.

CList Overview | Class Members | Hierarchy Chart

See Also CList::Find, CList::GetHeadPosition, CList::GetTailPosition, CList::GetPrev, CList::GetHead


CList::GetPrev

TYPE& GetPrev( POSITION& rPosition );

TYPE GetPrev( POSITION& rPosition ) const;

Return Value

If the list is const, GetPrev returns a copy of the element at the head of the list. This allows the function to be used only on the right side of an assignment statement and protects the list from modification.

If the list is not const, GetPrev returns a reference to an element of the list. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Parameters

TYPE

Template parameter specifying the type of the elements in the list.

rPosition

A reference to a POSITION value returned by a previous GetPrev or other member function call.

Remarks

Gets the list element identified by rPosition, then sets rPosition to the POSITION value of the previous entry in the list. You can use GetPrev in a reverse iteration loop if you establish the initial position with a call to GetTailPosition or Find.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

If the retrieved element is the first in the list, then the new value of rPosition is set to NULL.

CList Overview | Class Members | Hierarchy Chart

See Also CList::Find, CList::GetTailPosition, CList::GetHeadPosition, CList::GetNext, CList::GetHead


CList::GetTail

TYPE& GetTail( );

TYPE GetTail() const;

Return Value

See the return value description for GetHead.

Parameters

TYPE

Template parameter specifying the type of elements in the list.

Remarks

Gets the CObject pointer that represents the tail element of this list.

You must ensure that the list is not empty before calling GetTail. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

CList Overview | Class Members | Hierarchy Chart

See Also CList::AddTail, CList::AddHead, CList::RemoveHead, CList::GetHead


CList::GetTailPosition

POSITION GetTailPosition( ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if the list is empty.

Remarks

Gets the position of the tail element of this list; NULL if the list is empty.

CList Overview | Class Members | Hierarchy Chart

See Also CList::GetHeadPosition, CList::GetTail


CList::InsertAfter

POSITION InsertAfter( POSITION position, ARG_TYPE newElement );

Return Value

A POSITION value that can be used for iteration or list element retrieval.

Parameters

position

A POSITION value returned by a previous GetNext, GetPrev, or Find member function call.

ARG_TYPE

Template parameter specifying the type of the list element.

newElement

The element to be added to this list.

Remarks

Adds an element to this list after the element at the specified position.

CList Overview | Class Members | Hierarchy Chart

See Also CList::Find, CList::InsertBefore


CList::InsertBefore

POSITION InsertBefore( POSITION position, ARG_TYPE newElement );

Return Value

A POSITION value that can be used for iteration or list element retrieval; NULL if the list is empty.

Parameters

position

A POSITION value returned by a previous GetNext, GetPrev, or Find member function call.

ARG_TYPE

Template parameter specifying the type of the list element (can be a reference).

newElement

The element to be added to this list.

Remarks

Adds an element to this list before the element at the specified position.

CList Overview | Class Members | Hierarchy Chart

See Also CList::Find, CList::InsertAfter


CList::IsEmpty

BOOL IsEmpty( ) const;

Return Value

Nonzero if this list is empty; otherwise 0.

Remarks

Indicates whether this list contains no elements.

CList Overview | Class Members | Hierarchy Chart

See Also CList::GetCount


CList::RemoveAll

void RemoveAll( );

Remarks

Removes all the elements from this list and frees the associated memory. No error is generated if the list is already empty.

CList Overview | Class Members | Hierarchy Chart

See Also CList::RemoveAt


CList::RemoveAt

void RemoveAt( POSITION position );

Parameters

position

The position of the element to be removed from the list.

Remarks

Removes the specified element from this list.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

CList Overview | Class Members | Hierarchy Chart

See Also CList::RemoveAll


CList::RemoveHead

TYPE RemoveHead( );

Return Value

The element previously at the head of the list.

Parameters

TYPE

Template parameter specifying the type of elements in the list.

Remarks

Removes the element from the head of the list and returns a pointer to it.

You must ensure that the list is not empty before calling RemoveHead. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

CList Overview | Class Members | Hierarchy Chart

See Also CList::GetHead, CList::AddHead


CList::RemoveTail

TYPE RemoveTail( );

Return Value

The element that was at the tail of the list.

Parameters

TYPE

Template parameter specifying the type of elements in the list.

Remarks

Removes the element from the tail of the list and returns a pointer to it.

You must ensure that the list is not empty before calling RemoveTail. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

CList Overview | Class Members | Hierarchy Chart

See Also CList::GetTail, CList::AddTail


CList::SetAt

void SetAt( POSITION pos, ARG_TYPE newElement );

Parameters

pos

The POSITION of the element to be set.

ARG_TYPE

Template parameter specifying the type of the list element (can be a reference).

newElement

The element to be added to the list.

Remarks

A variable of type POSITION is a key for the list. It is not the same as an index, and you cannot operate on a POSITION value yourself. SetAt writes the element to the specified position in the list.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

CList Overview | Class Members | Hierarchy Chart

See Also CList::Find, CList::GetAt, CList::GetNext, CList::GetPrev


CListBox

The CListBox class provides the functionality of a Windows list box. A list box displays a list of items, such as filenames, that the user can view and select.

In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window.

You can create a list box either from a dialog template or directly in your code. To create it directly, construct the CListBox object, then call the Create member function to create the Windows list-box control and attach it to the CListBox object. To use a list box in a dialog template, declare a list-box variable in your dialog box class, then use DDX_Control in your dialog box class's DoDataExchange function to connect the member variable to the control. (ClassWizard does this for you automatically when you add a control variable to your dialog box class.)

Construction can be a one-step process in a class derived from CListBox. Write a constructor for the derived class and call Create from within the constructor.

If you want to handle Windows notification messages sent by a list box to its parent (usually a class derived from CDialog), add a message-map entry and message-handler member function to the parent class for each message.

Each message-map entry takes the following form:

ON_Notification( id, memberFxn )

where id specifies the child window ID of the list-box control sending the notification and memberFxn is the name of the parent member function you have written to handle the notification.

The parent’s function prototype is as follows:

afx_msg void memberFxn( );

Following is a list of potential message-map entries and a description of the cases in which they would be sent to the parent:

  • ON_LBN_DBLCLK The user double-clicks a string in a list box. Only a list box that has the LBS_NOTIFY style will send this notification message.

  • ON_LBN_ERRSPACE The list box cannot allocate enough memory to meet the request.

  • ON_LBN_KILLFOCUS The list box is losing the input focus.

  • ON_LBN_SELCANCEL The current list-box selection is canceled. This message is only sent when a list box has the LBS_NOTIFY style.

  • ON_LBN_SELCHANGE The selection in the list box is about to change. This notification is not sent if the selection is changed by the CListBox::SetCurSel member function. This notification applies only to a list box that has the LBS_NOTIFY style. The LBN_SELCHANGE notification message is sent for a multiple-selection list box whenever the user presses an arrow key, even if the selection does not change.

  • ON_LBN_SETFOCUS The list box is receiving the input focus.

  • ON_WM_CHARTOITEM An owner-draw list box that has no strings receives a WM_CHAR message.

  • ON_WM_VKEYTOITEM A list box with the LBS_WANTKEYBOARDINPUT style receives a WM_KEYDOWN message.

If you create a CListBox object within a dialog box (through a dialog resource), the CListBox object is automatically destroyed when the user closes the dialog box.

If you create a CListBox object within a window, you may need to destroy the CListBox object. If you create the CListBox object on the stack, it is destroyed automatically. If you create the CListBox object on the heap by using the new function, you must call delete on the object to destroy it when the user closes the parent window.

If you allocate any memory in the CListBox object, override the CListBox destructor to dispose of the allocation.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CTRLTEST

See Also CWnd, CButton, CComboBox, CEdit, CScrollBar, CStatic


CListBox Class Members

Construction
Initialization
General Operations
Single-Selection Operations
Multiple-Selection Operations
String Operations
Overridables

Construction

CListBox Constructs a CListBox object.

Initialization

Create | Creates the Windows list box and attaches it to the CListBox object.
InitStorage | Preallocates blocks of memory for list box items and strings.

General Operations

GetCount | Returns the number of strings in a list box.
GetHorizontalExtent | Returns the width in pixels that a list box can be scrolled horizontally.
SetHorizontalExtent | Sets the width in pixels that a list box can be scrolled horizontally.
GetTopIndex | Returns the index of the first visible string in a list box.
SetTopIndex | Sets the zero-based index of the first visible string in a list box.
GetItemData | Returns the 32-bit value associated with the list-box item.
GetItemDataPtr | Returns a pointer to a list-box item.
SetItemData | Sets the 32-bit value associated with the list-box item.
SetItemDataPtr | Sets a pointer to the list-box item.
GetItemRect | Returns the bounding rectangle of the list-box item as it is currently displayed.
ItemFromPoint | Returns the index of the list-box item nearest a point.
SetItemHeight | Sets the height of items in a list box.
GetItemHeight | Determines the height of items in a list box.
GetSel | Returns the selection state of a list-box item.
GetText | Copies a list-box item into a buffer.
GetTextLen | Returns the length in bytes of a list-box item.
SetColumnWidth | Sets the column width of a multicolumn list box.
SetTabStops | Sets the tab-stop positions in a list box.
GetLocale | Retrieves the locale identifier for a list box.
SetLocale | Sets the locale identifier for a list box.

Single-Selection Operations

GetCurSel | Returns the zero-based index of the currently selected string in a list box.
SetCurSel | Selects a list-box string.

Multiple-Selection Operations

SetSel | Selects or deselects a list-box item in a multiple-selection list box.
GetCaretIndex | Determines the index of the item that has the focus rectangle in a multiple-selection list box.
SetCaretIndex | Sets the focus rectangle to the item at the specified index in a multiple-selection list box.
GetSelCount | Returns the number of strings currently selected in a multiple-selection list box.
GetSelItems | Returns the indices of the strings currently selected in a list box.
SelItemRange | Selects or deselects a range of strings in a multiple-selection list box.
SetAnchorIndex | Sets the anchor in a multiple-selection list box to begin an extended selection.
GetAnchorIndex | Retrieves the zero-based index of the current anchor item in a list box.

String Operations

AddString | Adds a string to a list box.
DeleteString | Deletes a string from a list box.
InsertString | Inserts a string at a specific location in a list box.
ResetContent | Clears all the entries from a list box.
Dir | Adds filenames from the current directory to a list box.
FindString | Searches for a string in a list box.
FindStringExact | Finds the first list-box string that matches a specified string.
SelectString | Searches for and selects a string in a single-selection list box.

Overridables

DrawItem | Called by the framework when a visual aspect of an owner-draw list box changes.
MeasureItem | Called by the framework when an owner-draw list box is created to determine list-box dimensions.
CompareItem | Called by the framework to determine the position of a new item in a sorted owner-draw list box.
DeleteItem | Called by the framework when the user deletes an item from an owner-draw list box.
VKeyToItem | Override to provide custom WM_KEYDOWN handling for list boxes with the LBS_WANTKEYBOARDINPUT style set.
CharToItem | Override to provide custom WM_CHAR handling for owner-draw list boxes which don't have strings.


CListBox::AddString

int AddString( LPCTSTR lpszItem );

Return Value

The zero-based index to the string in the list box. The return value is LB_ERR if an error occurs; the return value is LB_ERRSPACE if insufficient space is available to store the new string.

Parameters

lpszItem

Points to the null-terminated string that is to be added.

Remarks

Call this member function to add a string to a list box. If the list box was not created with the LBS_SORT style, the string is added to the end of the list. Otherwise, the string is inserted into the list, and the list is sorted. If the list box was created with the LBS_SORT style but not the LBS_HASSTRINGS style, the framework sorts the list by one or more calls to the CompareItem member function.

Use InsertString to insert a string into a specific location within the list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::InsertString, CListBox::CompareItem, LB_ADDSTRING


CListBox::CharToItem

virtual int CharToItem( UINT nKey, UINT nIndex );

Return Value

Returns – 1 or – 2 for no further action or a nonnegative number to specify an index of a list-box item on which to perform the default action for the keystroke. The default implementation returns – 1.

Parameters

nKey

The ANSI code of the character the user typed.

nIndex

The current position of the list-box caret.

Remarks

This function is called by the framework when the list box's parent window receives a WM_CHARTOITEM message from the list box. The WM_CHARTOITEM message is sent by the list box when it receives a WM_CHAR message, but only if the list box meets all of these criteria:

  • Is an owner-draw list box.

  • Does not have the LBS_HASSTRINGS style set.

  • Has at least one item.

You should never call this function yourself. Override this function to provide your own custom handling of keyboard messages.

In your override, you must return a value to tell the framework what action you performed. A return value of – 1 or – 2 indicates that you handled all aspects of selecting the item and requires no further action by the list box. Before returning – 1 or – 2, you could set the selection or move the caret or both. To set the selection, use SetCurSel or SetSel. To move the caret, use SetCaretIndex.

A return value of 0 or greater specifies the index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::VKeyToItem, CListBox::SetCurSel, CListBox::SetSel, CListBox::SetCaretIndex, WM_CHARTOITEM


CListBox::CListBox

CListBox( );

Remarks

You construct a CListBox object in two steps. First call the constructor CListBox, then call Create, which initializes the Windows list box and attaches it to the CListBox.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::Create


CListBox::CompareItem

virtual int CompareItem( LPCOMPAREITEMSTRUCT lpCompareItemStruct );

Return Value

Indicates the relative position of the two items described in the COMPAREITEMSTRUCT structure. It may be any of the following values:

Value | Meaning
–1 | Item 1 sorts before item 2.
0 | Item 1 and item 2 sort the same.
1 | Item 1 sorts after item 2.

See CWnd::OnCompareItem for a description of the COMPAREITEMSTRUCT structure.

Parameters

lpCompareItemStruct

A long pointer to a COMPAREITEMSTRUCT structure.

Remarks

Called by the framework to determine the relative position of a new item in a sorted owner-draw list box. By default, this member function does nothing. If you create an owner-draw list box with the LBS_SORT style, you must override this member function to assist the framework in sorting new items added to the list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also WM_COMPAREITEM, CWnd::OnCompareItem, CListBox::DrawItem, CListBox::MeasureItem, CListBox::DeleteItem


CListBox::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise 0.

Parameters

dwStyle

Specifies the style of the list box. Apply any combination of list-box styles to the box.

rect

Specifies the list-box size and position. Can be either a CRect object or a RECT structure.

pParentWnd

Specifies the list box’s parent window (usually a CDialog object). It must not be NULL.

nID

Specifies the list box’s control ID.

Remarks

You construct a CListBox object in two steps. First call the constructor, then call Create, which initializes the Windows list box and attaches it to the CListBox object.

When Create executes, Windows sends the WM_NCCREATE, WM_CREATE, WM_NCCALCSIZE, and WM_GETMINMAXINFO messages to the list-box control.

These messages are handled by default by the OnNcCreate, OnCreate, OnNcCalcSize, and OnGetMinMaxInfo member functions in the CWnd base class. To extend the default message handling, derive a class from CListBox, add a message map to the new class, and override the preceding message-handler member functions. Override OnCreate, for example, to perform needed initialization for a new class.

Apply the following window styles to a list-box control.

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

  • WS_VSCROLL To add a vertical scroll bar

  • WS_HSCROLL To add a horizontal scroll bar

  • WS_GROUP To group controls

  • WS_TABSTOP To allow tabbing to this control

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::CListBox


CListBox::DeleteItem

virtual void DeleteItem( LPDELETEITEMSTRUCT lpDeleteItemStruct );

Parameters

lpDeleteItemStruct

A long pointer to a Windows DELETEITEMSTRUCT structure that contains information about the deleted item.

Remarks

Called by the framework when the user deletes an item from an owner-draw CListBox object or destroys the list box. The default implementation of this function does nothing. Override this function to redraw an owner-draw list box as needed.

See CWnd::OnDeleteItem for a description of the DELETEITEMSTRUCT structure.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::CompareItem, CWnd::OnDeleteItem, CListBox::DrawItem, CListBox::MeasureItem, ::DeleteItem


CListBox::DeleteString

int DeleteString( UINT nIndex );

Return Value

A count of the strings remaining in the list. The return value is LB_ERR if nIndex specifies an index greater than the number of items in the list.

Parameters

nIndex

Specifies the zero-based index of the string to be deleted.

Remarks

Deletes an item in a list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_DELETESTRING, CListBox::AddString, CListBox::InsertString


CListBox::Dir

int Dir( UINT attr, LPCTSTR lpszWildCard );

Return Value

The zero-based index of the last filename added to the list. The return value is LB_ERR if an error occurs; the return value is LB_ERRSPACE if insufficient space is available to store the new strings.

Parameters

attr

Can be any combination of the enum values described in CFile::GetStatu s, or any combination of the following values:

Value | Meaning
0x0000 | File can be read from or written to.
0x0001 | File can be read from but not written to.
0x0002 | File is hidden and does not appear in a directory listing.
0x0004 | File is a system file.
0x0010 | The name specified by lpszWildCard specifies a directory.
0x0020 | File has been archived.
0x4000 | Include all drives that match the name specified by lpszWildCard.
0x8000 | Exclusive flag. If the exclusive flag is set, only files of the specified type are listed. Otherwise, files of the specified type are listed in addition to “normal” files.

lpszWildCard

Points to a file-specification string. The string can contain wildcards (for example, *.*).

Remarks

Adds a list of filenames and/or drives to a list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also CWnd::DlgDirList, LB_DIR, CFile::GetStatus


CListBox::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A long pointer to a DRAWITEMSTRUCT structure that contains information about the type of drawing required.

Remarks

Called by the framework when a visual aspect of an owner-draw list box changes. The itemAction and itemState members of the DRAWITEMSTRUCT structure define the drawing action that is to be performed.

By default, this member function does nothing. Override this member function to implement drawing for an owner-draw CListBox object. The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before this member function terminates.

See CWnd::OnDrawItem for a description of the DRAWITEMSTRUCT structure.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::CompareItem, CWnd::OnDrawItem, WM_DRAWITEM, CListBox::MeasureItem, CListBox::DeleteItem


CListBox::FindString

int FindString( int nStartAfter, LPCTSTR lpszItem ) const;

Return Value

The zero-based index of the matching item, or LB_ERR if the search was unsuccessful.

Parameters

nStartAfter

Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If nStartAfter is –1, the entire list box is searched from the beginning.

lpszItem

Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string may contain any combination of uppercase and lowercase letters.

Remarks

Finds the first string in a list box that contains the specified prefix without changing the list-box selection. Use the SelectString member function to both find and select a string.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SelectString, CListBox::AddString, CListBox::InsertString, LB_FINDSTRING


CListBox::FindStringExact

int FindStringExact( int nIndexStart, LPCTSTR lpszFind ) const;

Return Value

The index of the matching item, or LB_ERR if the search was unsuccessful.

Parameters

nIndexStart

Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nIndexStart. If nIndexStart is –1, the entire list box is searched from the beginning.

lpszFind

Points to the null-terminated string to search for. This string can contain a complete filename, including the extension. The search is not case sensitive, so the string can contain any combination of uppercase and lowercase letters.

Remarks

An application calls the FindStringExact member function to find the first list-box string that matches the string specified in lpszFind. If the list box was created with an owner-draw style but without the LBS_HASSTRINGS style, the FindStringExact member function attempts to match the doubleword value against the value of lpszFind.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::FindString, LB_FINDSTRING, LB_FINDSTRINGEXACT


CListBox::GetAnchorIndex

int GetAnchorIndex( ) const;

Return Value

The index of the current anchor item, if successful; otherwise LB_ERR.

Remarks

Retrieves the zero-based index of the current anchor item in the list box. In a multiple-selection list box, the anchor item is the first or last item in a block of contiguous selected items.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetAnchorIndex


CListBox::GetCaretIndex

int GetCaretIndex( ) const;

Return Value

The zero-based index of the item that has the focus rectangle in a list box. If the list box is a single-selection list box, the return value is the index of the item that is selected, if any.

Remarks

An application calls the GetCaretIndex member function to determine the index of the item that has the focus rectangle in a multiple-selection list box. The item may or may not be selected.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetCaretIndex, LB_GETCARETINDEX


CListBox::GetCount

int GetCount( ) const;

Return Value

The number of items in the list box, or LB_ERR if an error occurs.

Remarks

Retrieves the number of items in a list box.

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

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_GETCOUNT


CListBox::GetCurSel

int GetCurSel( ) const;

Return Value

The zero-based index of the currently selected item. It is LB_ERR if no item is currently selected or if the list box is a multiple-selection list box.

Remarks

Retrieves the zero-based index of the currently selected item, if any, in a single-selection list box.

GetCurSel should not be called for a multiple-selection list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_GETCURSEL, CListBox::SetCurSel


CListBox::GetHorizontalExtent

int GetHorizontalExtent( ) const;

Return Value

The scrollable width of the list box, in pixels.

Remarks

Retrieves from the list box the width in pixels by which it can be scrolled horizontally. This is applicable only if the list box has a horizontal scroll bar.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetHorizontalExtent, LB_GETHORIZONTALEXTENT


CListBox::GetItemData

DWORD GetItemData( int nIndex ) const;

Return Value

The 32-bit value associated with the item, or LB_ERR if an error occurs.

Parameters

nIndex

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

Remarks

Retrieves the application-supplied doubleword value associated with the specified list-box item.

The doubleword value was the dwItemData parameter of a SetItemData call.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::AddString, CListBox::GetItemDataPtr, CListBox::SetItemDataPtr, CListBox::InsertString, CListBox::SetItemData, LB_GETITEMDATA


CListBox::GetItemDataPtr

void* GetItemDataPtr( int nIndex ) const;

Return Value

Retrieves a pointer, or –1 if an error occurs.

Parameters

nIndex

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

Remarks

Retrieves the application-supplied 32-bit value associated with the specified list-box item as a pointer (void*).

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::AddString, CListBox::GetItemData, CListBox::InsertString, CListBox::SetItemData, LB_GETITEMDATA


CListBox::GetItemHeight

int GetItemHeight( int nIndex ) const;

Return Value

The height, in pixels, of the items in the list box. If the list box has the LBS_OWNERDRAWVARIABLE style, the return value is the height of the item specified by nIndex. If an error occurs, the return value is LB_ERR.

Parameters

nIndex

Specifies the zero-based index of the item in the list box. This parameter is used only if the list box has the LBS_OWNERDRAWVARIABLE style; otherwise, it should be set to 0.

Remarks

An application calls the GetItemHeight member function to determine the height of items in a list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_GETITEMHEIGHT, CListBox::SetItemHeight


CListBox::GetItemRect

int GetItemRect( int nIndex, LPRECT lpRect ) const;

Return Value

LB_ERR if an error occurs.

Parameters

nIndex

Specifies the zero-based index of the item.

lpRect

Specifies a long pointer to a RECT tructure that receives the list-box client coordinates of the item.

Remarks

Retrieves the dimensions of the rectangle that bounds a list-box item as it is currently displayed in the list-box window.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_GETITEMRECT


CListBox::GetLocale

LCID GetLocale( ) const;

Return Value

The locale identifier (LCID) value for the strings in the list box.

Remarks

Retrieves the locale used by the list box. The locale is used, for example, to determine the sort order of the strings in a sorted list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetLocale, ::GetStringTypeW, ::GetSystemDefaultLCID, ::GetUserDefaultLCID


CListBox::GetSel

int GetSel( int nIndex ) const;

Return Value

A positive number if the specified item is selected; otherwise, it is 0. The return value is LB_ERR if an error occurs.

Parameters

nIndex

Specifies the zero-based index of the item.

Remarks

Retrieves the selection state of an item. This member function works with both single- and multiple-selection list boxes.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_GETSEL, CListBox::SetSel


CListBox::GetSelCount

int GetSelCount( ) const;

Return Value

The count of selected items in a list box. If the list box is a single-selection list box, the return value is LB_ERR.

Remarks

Retrieves the total number of selected items in a multiple-selection list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetSel, LB_GETSELCOUNT


CListBox::GetSelItems

int GetSelItems( int nMaxItems, LPINT rgIndex ) const;

Return Value

The actual number of items placed in the buffer. If the list box is a single-selection list box, the return value is LB_ERR.

Parameters

nMaxItems

Specifies the maximum number of selected items whose item numbers are to be placed in the buffer.

rgIndex

Specifies a long pointer to a buffer large enough for the number of integers specified by nMaxItems.

Remarks

Fills a buffer with an array of integers that specifies the item numbers of selected items in a multiple-selection list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_GETSELITEMS


CListBox::GetText

int GetText( int nIndex, LPTSTR lpszBuffer ) const;

void GetText( int nIndex, CString& rString ) const;

Return Value

The length (in bytes) of the string, excluding the terminating null character. If nIndex does not specify a valid index, the return value is LB_ERR.

Parameters

nIndex

Specifies the zero-based index of the string to be retrieved.

lpszBuffer

Points to the buffer that receives the string. The buffer must have sufficient space for the string and a terminating null character. The size of the string can be determined ahead of time by calling the GetTextLen member function.

rString

A reference to a CString object.

Remarks

Gets a string from a list box. The second form of this member function fills a CString object with the string text.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetTextLen, LB_GETTEXT


CListBox::GetTextLen

int GetTextLen( int nIndex ) const;

Return Value

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

Parameters

nIndex

Specifies the zero-based index of the string.

Remarks

Gets the length of a string in a list-box item.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetText, LB_GETTEXTLEN


CListBox::GetTopIndex

int GetTopIndex( ) const;

Return Value

The zero-based index of the first visible item in a list box if successful, LB_ERR otherwise.

Remarks

Retrieves the zero-based index of the first visible item in a list box. Initially, item 0 is at the top of the list box, but if the list box is scrolled, another item may be at the top.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetTopIndex, LB_GETTOPINDEX


CListBox::InitStorage

int InitStorage( int nItems, UINT nBytes );

Return Value

If successful, the maximum number of items that the list box can store before a memory reallocation is needed, otherwise LB_ERRSPACE, meaning not enough memory is available.

Parameters

nItems

Specifies the number of items to add.

nBytes

Specifies the amount of memory, in bytes, to allocate for item strings.

Remarks

Allocates memory for storing list-box items. Call this function before adding a large number of items to a CListBox.

This function helps speed up the initialization of list boxes that have a large number of items (more than 100). It preallocates the specified amount of memory so that subsequent AddString, InsertString, and Dir functions take the shortest possible time. You can use estimates for the parameters. If you overestimate, some extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the preallocated amount.

Windows 95 only: The nItems parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size of the items in a list box is limited only by available memory.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::CListBox, CListBox::Create, CListBox::ResetContent, LB_INITSTORAGE


CListBox::InsertString

int InsertString( int nIndex, LPCTSTR lpszItem );

Return Value

The zero-based index of the position at which the string was inserted. The return value is LB_ERR if an error occurs; the return value is LB_ERRSPACE if insufficient space is available to store the new string.

Parameters

nIndex

Specifies the zero-based index of the position to insert the string. If this parameter is –1, the string is added to the end of the list.

lpszItem

Points to the null-terminated string that is to be inserted.

Remarks

Inserts a string into the list box. Unlike the AddString member function, InsertString does not cause a list with the LBS_SORT style to be sorted.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::AddString, LB_INSERTSTRING


CListBox::ItemFromPoint

UINT ItemFromPoint( CPoint pt, BOOL& bOutside ) const;

Return Value

The index of the nearest item to the point specified in pt.

Parameters

pt

Point for which to find the nearest item, specified relative to the upper-left corner of the client area of the list box.

bOutside

Reference to a BOOL variable which will be set to TRUE if pt is outside the client area of the list box, FALSE if pt is inside the client area of the list box.

Remarks

Call this function to determine the list-box item nearest the point specified in pt. You could use this function to determine which list-box item the mouse cursor moves over.

Note Because the Win32 message LB_ITEMFROMPOINT works only with Windows 95, ItemFromPoint, which wraps the Win32 message also works only with Windows 95.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetItemRect, LB_ITEMFROMPOINT


CListBox::MeasureItem

virtual void MeasureItem( LPMEASUREITEMSTRUCT lpMeasureItemStruct );

Parameters

lpMeasureItemStruct

A long pointer to a MEASUREITEMSTRUCT structure.

Remarks

Called by the framework when a list box with an owner-draw style is created.

By default, this member function does nothing. Override this member function and fill in the MEASUREITEMSTRUCT structure to inform Windows of the list-box dimensions. If the list box is created with the LBS_OWNERDRAWVARIABLE style, the framework calls this member function for each item in the list box. Otherwise, this member is called only once.

For further information about using the LBS_OWNERDRAWFIXED style in an owner-draw list box created with the SubclassDlgItem member function of CWnd, see the discussion in Technical Note 14.

See CWnd::OnMeasureItem for a description of the MEASUREITEMSTRUCT structure.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::CompareItem, CWnd::OnMeasureItem, CListBox::DrawItem, CListBox::DeleteItem


CListBox::ResetContent

void ResetContent( );

Remarks

Removes all items from a list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_RESETCONTENT


CListBox::SelectString

int SelectString( int nStartAfter, LPCTSTR lpszItem );

Return Value

The index of the selected item if the search was successful. If the search was unsuccessful, the return value is LB_ERR and the current selection is not changed.

Parameters

nStartAfter

Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If nStartAfter is –1, the entire list box is searched from the beginning.

lpszItem

Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string may contain any combination of uppercase and lowercase letters.

Remarks

Searches for a list-box item that matches the specified string, and if a matching item is found, it selects the item.

The list box is scrolled, if necessary, to bring the selected item into view.

This member function cannot be used with a list box that has the LBS_MULTIPLESEL style.

An item is selected only if its initial characters (from the starting point) match the characters in the string specified by lpszItem.

Use the FindString member function to find a string without selecting the item.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::FindString, LB_SELECTSTRING


CListBox::SelItemRange

int SelItemRange( BOOL bSelect, int nFirstItem, int nLastItem );

Return Value

LB_ERR if an error occurs.

Parameters

bSelect

Specifies how to set the selection. If bSelect is TRUE, the string is selected and highlighted; if FALSE, the highlight is removed and the string is no longer selected.

nFirstItem

Specifies the zero-based index of the first item to set.

nLastItem

Specifies the zero-based index of the last item to set.

Remarks

Selects multiple consecutive items in a multiple-selection list box.

Use this member function only with multiple-selection list boxes. If you need to select only one item in a multiple-selection list box — that is, if nFirstIem is equal to nLastItem — call the SetSel member function instead.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_SELITEMRANGE, CListBox::GetSelItems


CListBox::SetAnchorIndex

void SetAnchorIndex( int nIndex );

Parameters

nIndex

Specifies the zero-based index of the list-box item that will be the anchor.

Remarks

Sets the anchor in a multiple-selection list box to begin an extended selection. In a multiple-selection list box, the anchor item is the first or last item in a block of contiguous selected items.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetAnchorIndex


CListBox::SetCaretIndex

int SetCaretIndex( int nIndex, BOOL bScroll = TRUE );

Return Value

LB_ERR if an error occurs.

Parameters

nIndex

Specifies the zero-based index of the item to receive the focus rectangle in the list box.

bScroll

If this value is 0, the item is scrolled until it is fully visible. If this value is not 0, the item is scrolled until it is at least partially visible.

Remarks

An application calls the SetCaretIndex member function to set the focus rectangle to the item at the specified index in a multiple-selection list box. If the item is not visible, it is scrolled into view.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetCaretIndex, LB_SETCARETINDEX


CListBox::SetColumnWidth

void SetColumnWidth( int cxWidth );

Parameters

cxWidth

Specifies the width in pixels of all columns.

Remarks

Sets the width in pixels of all columns in a multicolumn list box (created with the LBS_MULTICOLUMN style).

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_SETCOLUMNWIDTH


CListBox::SetCurSel

int SetCurSel( int nSelect );

Return Value

LB_ERR if an error occurs.

Parameters

nSelect

Specifies the zero-based index of the string to be selected. If nSelect is –1, the list box is set to have no selection.

Remarks

Selects a string and scrolls it into view, if necessary. When the new string is selected, the list box removes the highlight from the previously selected string.

Use this member function only with single-selection list boxes. It cannot be used to set or remove a selection in a multiple-selection list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_SETCURSEL, CListBox::GetCurSel


CListBox::SetHorizontalExtent

void SetHorizontalExtent( int cxExtent );

Parameters

cxExtent

Specifies the number of pixels by which the list box can be scrolled horizontally.

Remarks

Sets the width, in pixels, by which a list box can be scrolled horizontally. If the size of the list box is smaller than this value, the horizontal scroll bar will horizontally scroll items in the list box. If the list box is as large or larger than this value, the horizontal scroll bar is hidden.

To respond to a call to SetHorizontalExtent, the list box must have been defined with the WS_HSCROLL style.

This member function is not useful for multicolumn list boxes. For multicolumn list boxes, call the SetColumnWidth member function.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetHorizontalExtent, CListBox::SetColumnWidth, LB_SETHORIZONTALEXTENT


CListBox::SetItemData

int SetItemData( int nIndex, DWORD dwItemData );

Return Value

LB_ERR if an error occurs.

Parameters

nIndex

Specifies the zero-based index of the item.

dwItemData

Specifies the value to be associated with the item.

Remarks

Sets a 32-bit value associated with the specified item in a list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetItemDataPtr, CListBox::GetItemData, LB_SETITEMDATA


CListBox::SetItemDataPtr

int SetItemDataPtr( int nIndex, void* pData );

Return Value

LB_ERR if an error occurs.

Parameters

nIndex

Specifies the zero-based index of the item.

pData

Specifies the pointer to be associated with the item.

Remarks

Sets the 32-bit value associated with the specified item in a list box to be the specified pointer (void*). This pointer remains valid for the life of the list box, even though the item’s relative position within the list box might change as items are added or removed. Hence, the item’s index within the box can change, but the pointer remains reliable.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::SetItemData, CListBox::GetItemData, CListBox::GetItemDataPtr, LB_SETITEMDATA


CListBox::SetItemHeight

int SetItemHeight( int nIndex, UINT cyItemHeight );

Return Value

LB_ERR if the index or height is invalid.

Parameters

nIndex

Specifies the zero-based index of the item in the list box. This parameter is used only if the list box has the LBS_OWNERDRAWVARIABLE style; otherwise, it should be set to 0.

cyItemHeight

Specifies the height, in pixels, of the item.

Remarks

An application calls the SetItemHeight member function to set the height of items in a list box. If the list box has the LBS_OWNERDRAWVARIABLE style, this function sets the height of the item specified by nIndex. Otherwise, this function sets the height of all items in the list box.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetItemHeight, LB_SETITEMHEIGHT


CListBox::SetLocale

LCID SetLocale( LCID nNewLocale );

Return Value

The previous locale identifier (LCID) value for this list box.

Parameters

nNewLocale

The new locale identifier (LCID) value to set for the list box.

Remarks

Sets the locale identifier for this list box. If SetLocale is not called, the default locale is obtained from the system. This system default locale can be modified by using Control Panel’s Regional (or International) application.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetLocale


CListBox::SetSel

int SetSel( int nIndex, BOOL bSelect = TRUE );

Return Value

LB_ERR if an error occurs.

Parameters

nIndex

Contains the zero-based index of the string to be set. If –1, the selection is added to or removed from all strings, depending on the value of bSelect.

bSelect

Specifies how to set the selection. If bSelect is TRUE, the string is selected and highlighted; if FALSE, the highlight is removed and the string is no longer selected. The specified string is selected and highlighted by default.

Remarks

Selects a string in a multiple-selection list box.

Use this member function only with multiple-selection list boxes.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetSel, LB_SETSEL


CListBox::SetTabStops

void SetTabStops( );

BOOL SetTabStops( const int& cxEachStop );

BOOL SetTabStops( int nTabStops, LPINT rgTabStops );

Return Value

Nonzero if all the tabs were set; otherwise 0.

Parameters

cxEachStop

Tab stops are set at every cxEachStop dialog units. See rgTabStops for a description of a dialog unit.

nTabStops

Specifies the number of tab stops to have in the list box.

rgTabStops

Points to the first member of an array of integers containing the tab-stop positions in dialog units. A dialog unit is a horizontal or vertical distance. One horizontal dialog unit is equal to one-fourth of the current dialog base width unit, and one vertical dialog unit is equal to one-eighth of the current dialog base height unit. The dialog base units are computed based on the height and width of the current system font. The GetDialogBaseUnits Windows function returns the current dialog base units in pixels. The tab stops must be sorted in increasing order; back tabs are not allowed.

Remarks

Sets the tab-stop positions in a list box.

To set tab stops to the default size of 2 dialog units, call the parameterless version of this member function. To set tab stops to a size other than 2, call the version with the cxEachStop argument.

To set tab stops to an array of sizes, use the version with the rgTabStops and nTabStops arguments. A tab stop will be set for each value in rgTabStops, up to the number specified by nTabStops.

To respond to a call to the SetTabStops member function, the list box must have been created with the LBS_USETABSTOPS style.

CListBox Overview | Class Members | Hierarchy Chart

See Also LB_SETTABSTOPS, ::GetDialogBaseUnits


CListBox::SetTopIndex

int SetTopIndex( int nIndex );

Return Value

Zero if successful, or LB_ERR if an error occurs.

Parameters

nIndex

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

Remarks

Ensures that a particular list-box item is visible.

The system scrolls the list box until either the item specified by nIndex appears at the top of the list box or the maximum scroll range has been reached.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::GetTopIndex, LB_SETTOPINDEX


CListBox::VKeyToItem

virtual int VKeyToItem( UINT nKey, UINT nIndex );

Return Value

Returns – 2 for no further action, – 1 for default action, or a nonnegative number to specify an index of a list box item on which to perform the default action for the keystroke.

Parameters

nKey

The virtual-key code of the key the user pressed.

nIndex

The current position of the list-box caret.

Remarks

This function is called by the framework when the list box’s parent window receives a WM_VKEYTOITEM message from the list box. The WM_VKEYTOITEM message is sent by the list box when it receives a WM_KEYDOWN message, but only if the list box meets both of the following:

  • Has the LBS_WANTKEYBOARDINPUT style set.

  • Has at least one item.

You should never call this function yourself. Override this function to provide your own custom handling of keyboard messages.

You must return a value to tell the framework what action your override performed. A return value of – 2 indicates that the application handled all aspects of selecting the item and requires no further action by the list box. Before returning – 2, you could set the selection or move the caret or both. To set the selection, use SetCurSel or SetSel. To move the caret, use SetCaretIndex.

A return value of – 1 indicates that the list box should perform the default action in response to the keystroke.The default implementation returns – 1.

A return value of 0 or greater specifies the index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

CListBox Overview | Class Members | Hierarchy Chart

See Also CListBox::CharToItem, CListBox::SetCurSel, CListBox::SetSel, CListBox::SetCaretIndex


CListCtrl

The CListCtrl class encapsulates the functionality of a “list view control,” which displays a collection of items each consisting of an icon (from an image list) and a label. In addition to an icon and label, each item can have information displayed in colums to the right of the icon and label. This control (and therefore the CListCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

The following is a brief overview of the CListCtrl class. For a detailed, conceptual discussion, see Using CListCtrl and Control Topics in the Visual C++ Programmer’s Guide.

Views

List view controls can display their contents in four different ways, called “views.”

  • Icon view

    Each item appears as a full-sized icon (32 x 32 pixels) with a label below it. The user can drag the items to any location in the list view window.

  • Small icon view

    Each item appears as a small icon (16 x 16 pixels) with the label to the right of it. The user can drag the items to any location in the list view window.

  • List view

    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 location in the list view window.

  • Report view

    Each item appears on its own line, with additional information arranged in columns to the right. The leftmost column contains the small icon and label, and subsequent columns contain subitems as specified by the application. An embedded header control (class CHeaderCtrl) implements these columns. For more information on the header control and columns in a report view, see Using CListCtrl: Adding Columns to the Control (Report View).

The style of the control’s current list view determines the current view. For more information on these these styles and their usage, see Using CListCtrl: Changing List Control Styles.

Extended Styles

In addition to the standard list styles, class CListCtrl supports a large set of extended styles, providing enriched functionality. Some examples of this functionality include:

  • Hover selection

    When enabled, allows automatic selection of an item when the cursor remains over the item for a certain period of time.

  • Virtual list views

    When enabled, allows the control to support up to DWORD items. This is possible by placing the overhead of managing item data on the application. Except for the item selection and focus information, all item information must be managed by the application. For more information, see Using CListCtrl: Virtual List Controls.

  • One– and two– click activation

    When enabled, allows hot tracking (automatic highlighting of the item text) and one– or two– click activation of the highlighted item.

  • Drag and drop column ordering

    When enabled, allows drag-and-drop reordering of columns in a list view control. Only available in report view.

For information on using these new extended styles, see Using CListCtrl: Changing List Control Styles.

Items and Subitems

Each item in a list view control consists of an icon (from an image list), a label, a current state, and an application-defined value (referred to as “item data”). One or more subitems can also be associated with each item. A “subitem” is a string that, in report view, can be displayed in a column to the right of an item’s icon and label. All items in a list view control must have the same number of subitems.

Class CListCtrl provides several functions for inserting, deleting, finding, and modifying these items. For more information, see CListCtrl::GetItem, CListCtrl::InsertItem, and CListCtrl::FindItem, Using CListCtrl: Adding Items to the Control, and Using CListCtrl: Scrolling, Arranging, Sorting, and Finding in List Controls.

By default, the list view control is responsible for storing an item's icon and text attributes. However, in addition to these item types, class CListCtrl supports “callback items.” A “callback item” is a list view item for which the application — rather than the control — stores the text, icon, or both. A callback mask is used to specify which item attributes (text and/or icon) are supplied by the application. If an application uses callback items, it must be able to supply the text and/or icon attributes on demand. Callback items are helpful when your application already maintains some of this information. For more information, see CListCtrl::GetCallBackMask and Using CListCtrl: Callback Items and the Callback Mask.

Image Lists

The icons, header item images, and application– defined states for list view items are contained in several image lists (implemented by class CImageList), which you create and assign to the list view control. Each list view control can have up to four different types of image lists:

  • Large icon

    Used in the icon view for full-sized icons.

  • Small icon

    Used in the small icon, list, and report views for smaller versions of the icons used in the icon view.

  • Application-defined state

    Contains state images, which are displayed next to an item’s icon to indicate an application-defined state.

  • Header item

    Used in the report view for small images that appear in each header control item.

By default, a list view control destroys the image lists assigned to it when it is destroyed; however, the developer can customize this behavior by destroying each image list when it is no longer used, as determined by the application. For more information, see Using CListCtrl: List Items and Image Lists and Using CListCtrl: List Items and Image Lists.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample DAOTABLE | MFC Sample HTTPSVR | MFC Sample LISTHDR | MFC Sample ROWLIST | MFC Sample DBVLIST

See Also CImageList


CListCtrl Class Members

Construction
Attributes
Operations
Overridables

Construction

CListCtrl | Constructs a CListCtrl object.
Create | Creates a list control and attaches it to a CListCtrl object.

Attributes

GetBkColor | Retrieves the background color of a list view control.
SetBkColor | Sets the background color of the list view control.
GetImageList | Retrieves the handle of an image list used for drawing list view items.
SetImageList | Assigns an image list to a list view control.
GetItemCount | Retrieves the number of items in a list view control.
GetItem | Retrieves a list view item’s attributes.
SetItem | Sets some or all of a list view item’s attributes.
GetCallbackMask | Retrieves the callback mask for a list view control.
SetCallbackMask | Sets the callback mask for a list view control.
GetNextItem | Searches for a list view item with specified properties and with specified relationship to a given item.
GetFirstSelectedItemPosition | Retrieves the position of the first selected list view item in a list view control.
GetNextSelectedItem | Retrieves the next selected list view item for iterating.
GetItemRect | Retrieves the bounding rectangle for an item.
SetItemPosition | Moves an item to a specified position in a list view control.
GetItemPosition | Retrieves the position of a list view item.
GetStringWidth | Determines the minimum column width necessary to display all of a given string.
GetEditControl | Retrieves the handle of the edit control used to edit an item’s text.
GetColumn | Retrieves the attributes of a control’s column.
SetColumn | Sets the attributes of a list view column.
GetColumnWidth | Retrieves the width of a column in report view or list view.
SetColumnWidth | Changes the width of a column in report view or list view.
GetCheck | Retrieves the current display status of the state image associated with an item.
SetCheck | Sets the the current display status of the state image associated with an item.
GetViewRect | Retrieves the bounding rectangle of all items in the list view control.
GetTextColor | Retrieves the text color of a list view control.
SetTextColor | Sets the text color of a list view control.
GetTextBkColor | Retrieves the text background color of a list view control.
SetTextBkColor | Sets the background color of text in a list view control.
GetTopIndex | Retrieves the index of the topmost visible item.
GetCountPerPage | Calculates the number of items that can fit vertically in a list view control.
GetOrigin | Retrieves the current view origin for a list view control.
SetItemState | Changes the state of an item in a list view control.
GetItemState | Retrieves the state of a list view item.
GetItemText | Retrieves the text of a list view item or subitem.
SetItemText | Changes the text of a list view item or subitem.
SetItemCount | Prepares a list view control for adding a large number of items.
SetItemData | Sets the item’s application-specific value.
GetItemData | Retrieves the application-specific value associated with an item.
GetSelectedCount | Retrieves the number of selected items in the list view control.
SetColumnOrderArray | Sets the column order (left to right) of a list view control.
GetColumnOrderArray | Retrieves the column order (left to right) of a list view control.
SetIconSpacing | Sets the spacing between icons in a list view control.
GetHeaderCtrl | Retrieves the header control of a list view control.
GetHotCursor | Retrieves the cursor used when hot tracking is enabled for a list view control.
SetHotCursor | Sets the cursor used when hot tracking is enabled for a list view control.
GetSubItemRect | Retrieves the bounding rectangle of an item in a list view control.
GetHotItem | Retrieves the list view item currently under the cursor.
SetHotItem | Sets the current hot item of a list view control.
GetSelectionMark | Retrieves the selection mark of a list view control.
SetSelectionMark | Sets the selection mark of a list view control.
GetExtendedStyle | Retrieves the current extended styles of a list view control.
SetExtendedStyle | Sets the current extended styles of a list view control.
SubItemHitTest | Determines which list view item, if any, is at a given position.
GetWorkAreas | Retrieves the current working areas of a list view control.
GetNumberOfWorkAreas | Retrieves the current number of working areas for a list view control.
SetItemCountEx | Sets the item count for a virtual list view control.
SetWorkAreas | Sets the area where icons can be displayed in a list view control.
ApproximateViewRect | Determines the width and height required to display the items of a list view control.
GetBkImage | Retreives the current background image of a list view control.
SetBkImage | Sets the current background image of a list view control.
GetHoverTime | Retrieves the current hover time of a list view control.
SetHoverTime | Sets the current hover time of a list view control.

Operations

InsertItem | Inserts a new item in a list view control.
DeleteItem | Deletes an item from the control.
DeleteAllItems | Deletes all items from the control.
FindItem | Searches for a list view item having specified characteristics.
SortItems | Sorts list view items using an application-defined comparison function.
HitTest | Determines which list view item is at a specified position.
EnsureVisible | Ensures that an item is visible.
Scroll | Scrolls the content of a list view control.
RedrawItems | Forces a list view control to repaint a range of items.
Update | Forces the control to repaint a specified item.
Arrange | Aligns items on a grid.
EditLabel | Begins in-place editing of an item’s text.
InsertColumn | Inserts a new column in a list view control.
DeleteColumn | Deletes a column from the list view control.
CreateDragImage | Creates a drag image list for a specified item.

Overridables

DrawItem Called when a visual aspect of an owner-draw control changes.


CListCtrl::ApproximateViewRect

CSize ApproximateViewRect( CSize sz = CSize(-1, -1), int iCount = -1 ) const;

Return Value

A CSize object that contains the approximate width and height needed to display the items, in pixels.

Parameters

sz

The proposed dimensions of the control, in pixels. If dimensions are not specified, the framework uses the current width or height values of the control.

iCount

Number of items to be displayed in the control. If this parameter is -1, the framework uses the total number of items currently in the control.

Remarks

This member function implements the behavior of the Win32 macro, ListView_ApproximateViewRect, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetViewRect


CListCtrl::Arrange

BOOL Arrange( UINT nCode );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nCode

Specifies the alignment style for the items. It 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’s current alignment styles (the default value).

  • LVA_SNAPTOGRID Snaps all icons to the nearest grid position.

Remarks

Call this function to reposition items in an icon view so that they align on a grid. The nCode parameter specifies the alignment style.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::EnsureVisible


CListCtrl::CListCtrl

CListCtrl( );

Remarks

Constructs a CListCtrl object.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::Create


CListCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise zero.

Parameters

dwStyle

Specifies the list control’s style. Apply any combination of list control styles to the control. See the Remarks section for a list of possible styles.

rect

Specifies the list control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the list control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the list control’s ID.

Remarks

You construct a CListCtrl in two steps. First call the constructor, then call Create, which creates the list view control and attaches it to the CListCtrl object.

The dwStyle parameter can be a combination of the following values:

  • LVS_ALIGNLEFT Specifies that items are left-aligned in icon and small icon view.

  • LVS_ALIGNTOP Specifies that items are aligned with the top of the control in icon and small icon view.

  • LVS_AUTOARRANGE Specifies that icons are automatically kept arranged in icon view and small icon view.

  • LVS_EDITLABELS Allows item text to be edited in place. The parent window must process the LVN_ENDLABELEDIT notification message.

  • LVS_ICON Specifies icon view.

  • LVS_LIST Specifies list view.

  • LVS_NOCOLUMNHEADER Specifies that a column header is not displayed in report view. By default, columns have headers in report view.

  • LVS_NOLABELWRAP Displays item text on a single line in icon view. By default, item text can wrap in icon view.

  • LVS_NOSCROLL Disables scrolling. All items must be within the client area.

  • LVS_NOSORTHEADER Specifies that column headers do not work like buttons. This style is useful if clicking a column header in report view does not carry out an action, such as sorting.

  • LVS_OWNERDRAWFIXED Enables the owner window to paint items in report view. The list view control sends a WM_DRAWITEM message to paint each item; it does not send separate messages for each subitem. The itemData member of the DRAWITEMSTRUCT structure contains the item data for the specified list view item.

  • LVS_REPORT Specifies report view.

  • LVS_SHAREIMAGELISTS Specifies that the control does not take ownership of the image lists assigned to it (that is, it does not destroy the image lists when it is destroyed). This style enables the same image lists to be used with multiple list view controls.

  • LVS_SHOWSELALWAYS Always show the selection, if any, even if the control does not have the focus.

  • LVS_SINGLESEL Allows only one item at a time to be selected. By default, multiple items can be selected.

  • LVS_SMALLICON Specifies small icon view.

  • LVS_SORTASCENDING Sorts items based on item text in ascending order.

  • LVS_SORTDESCENDING Sorts items based on item text in descending order.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::CListCtrl


CListCtrl::CreateDragImage

CImageList* CreateDragImage( int nItem, LPPOINT lpPoint );

Return Value

A pointer to the drag image list if successful; otherwise NULL.

Parameters

nItem

Index of the item whose drag image list is to be created.

lpPoint

Address of a POINT structure that receives the initial location of the upper-left corner of the image, in view coordinates.

Remarks

Call this function to create a drag image list for the item specified by nItem. The CImageList object is permanent, and you must delete it when finished. For example:

CImageList* pImageList = MyListCtrl.CreateDragImage(nItem, &point);
   ...
   ...
   delete pImageList;

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CImageList, CListCtrl::GetImageList


CListCtrl::DeleteAllItems

BOOL DeleteAllItems( );

Return Value

Nonzero if successful; otherwise zero.

Remarks

Call this function to delete all items from the list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::InsertItem, CListCtrl::DeleteItem


CListCtrl::DeleteColumn

BOOL DeleteColumn( int nCol );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nCol

Index of the column to be deleted.

Remarks

Call this function to delete a column from the list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::InsertColumn, CListCtrl::DeleteAllItems


CListCtrl::DeleteItem

BOOL DeleteItem( int nItem );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nItem

Specifies the index of the item to be deleted.

Remarks

Call this function to delete an item from a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::InsertItem, CListCtrl::DeleteAllItems


CListCtrl::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A long pointer to a DRAWITEMSTRUCT structure that contains information about the type of drawing required.

Remarks

Called by the framework when a visual aspect of an owner-draw list view control changes. The itemAction member of the DRAWITEMSTRUCT structure defines the drawing action that is to be performed.

By default, this member function does nothing. Override this member function to implement drawing for an owner-draw CListCtrl object.

The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before this member function terminates.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CWnd::OnDrawItem


CListCtrl::EditLabel

CEdit* EditLabel( int nItem );

Return Value

If successful, a pointer to the CEdit object that is used to edit the item text; otherwise NULL.

Parameters

nItem

Index of the list view item that is to be edited.

Remarks

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.

Use this function to begin in-place editing of the specified list view item’s text.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetEditControl


CListCtrl::EnsureVisible

BOOL EnsureVisible( int nItem, BOOL bPartialOK );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nItem

Index of the list view item that is to be visible.

bPartialOK

Specifies whether partial visibility is acceptable.

Remarks

Call this function to ensure that a list view item is at least partially visible. The list view control is scrolled if necessary. If the bPartialOK parameter is nonzero, no scrolling occurs if the item is partially visible.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::Scroll


CListCtrl::FindItem

int FindItem( LVFINDINFO* pFindInfo, int nStart = -1 ) const;

Return Value

The index of the item if successful or -1 otherwise.

Parameters

pFindInfo

A pointer to a LVFINDINFO structure containing information about the item to be searched for.

nStart

Index of the item to begin the search with, or -1 to start from the beginning. The item at nStart is excluded from the search if nStart is not equal to -1.

Remarks

Use this function to search for a list view item having specified characteristics.

The pFindInfo parameter points to an LVFINDINFO structure, which contains information used to search for a list view item.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SortItems


CListCtrl::GetBkColor

COLORREF GetBkColor( ) const;

Return Value

A 32-bit value used to specify an RGB color.

Remarks

Retrieves the background color of a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetBkColor COLORREF


CListCtrl::GetBkImage

BOOL GetBkImage( LVBKIMAGE* plvbkImage ) const;

Return Value

Returns nonzero if successful, or zero otherwise.

Parameters

plvbkImage

A pointer to an LVBKIMAGE structure containing the current background image of the list view.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetBkImage, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetBkImage


CListCtrl::GetCallbackMask

UINT GetCallbackMask( ) const;

Return Value

The list view control’s callback mask.

Remarks

Retrieves the callback mask for a list view control.

A “callback item” is a list view item for which the application — rather than the control — stores the text, icon, or both. Although a list view control can store these attributes for you, you may want to use callback items if your application already maintains some of this information. The callback mask specifies which item state bits are maintained by the application, and it applies to the whole control rather than to a specific item. The callback mask is zero by default, meaning that the control tracks all item states. If an application uses callback items or specifies a nonzero callback mask, it must be able to supply list view item attributes on demand.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetCallbackMask


CListCtrl::GetCheck

BOOL GetCheck( int nItem ) const;

Return Value

Nonzero if the item is selected, otherwise 0.

Parameters

nItem

The zero-based index of a list control item.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetCheckState, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetCheck


CListCtrl::GetColumn

BOOL GetColumn( int nCol, LVCOLUMN* pColumn ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

nCol

Index of the column whose attributes are to be retrieved.

pColumn

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.

Remarks

Retrieves the attributes of a list view control’s column.

The LVCOLUMN structure contains information about a column in report view.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetColumn, CListCtrl::GetColumnWidth


CListCtrl::GetColumnOrderArray

BOOL GetColumnOrderArray( LPINT piArray, int iCount = -1 );

Return Value

Nonzero if successful; otherwise zero.

Parameters

piArray

A pointer to a buffer that will contain the index values of the columns in the list view control. The buffer must be large enough to contain the total number of columns in the list view control.

iCount

Number of columns in the list view control. If this parameter is -1, the number of columns is automatically retrieved by the framework.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetColumnOrderArray, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetColumnOrderArray


CListCtrl::GetColumnWidth

int GetColumnWidth( int nCol ) const;

Return Value

The width, in pixels, of the column specified by nCol.

Parameters

nCol

Specifies the index of the column whose width is to be retrieved.

Remarks

Retrieves the width of a column in report view or list view.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetColumnWidth, CListCtrl::GetColumn


CListCtrl::GetCountPerPage

int GetCountPerPage( ) const;

Return Value

The number of items that can fit vertically in the visible area of a list view control when in list view or report view.

Remarks

Calculates the number of items that can fit vertically in the visible area of a list view control when in list view or report view.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetTopIndex


CListCtrl::GetEditControl

CEdit* GetEditControl( ) const;

Return Value

If successful, a pointer to the CEdit object that is used to edit the item text; otherwise NULL.

Remarks

Retrieves the handle of the edit control used to edit a list view item’s text.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::EditLabel


CListCtrl::GetExtendedStyle

DWORD GetExtendedStyle( );

Return Value

A combination of the extended styles currently in use by the list view control. For a descriptive list of these extended styles, see the Extended List View Styles topic in the Platform SDK.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetExtendedListViewStyle, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetExtendedStyle


CListCtrl::GetFirstSelectedItemPosition

POSITION GetFirstSelectedItemPosition( ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if no items are selected.

Remarks

Gets the position of the first selected item in the list view control.

Example

The following code sample demonstrates the usage of this function.

CListCtrl* pListCtrl = (CListCtrl*) GetDlgItem(IDC_YOURLISTCONTROL);
ASSERT(pListCtrl != NULL);

POSITION pos = pList->GetFirstSelectedItemPosition();
if (pos == NULL)
   TRACE0("No items were selected!\n");
else
{
   while (pos)
   {
      int nItem = pList->GetNextSelectedItem(pos);
      TRACE1("Item %d was selected!\n", nItem);
      // you could do your own processing on nItem here
   }
}

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CImageList, CListCtrl::GetNextSelectedItem


CListCtrl::GetHeaderCtrl

CHeaderCtrl* GetHeaderCtrl( );

Return Value

A pointer to the header control, used by the list view control.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetHeader, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CHeaderCtrl


CListCtrl::GetHotCursor

HCURSOR GetHotCursor( )

Return Value

The handle to the current hot cursor resource being used by the list view control.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetHotCursor, as described in the Platform SDK.

The hot cursor, only visible when hover selection is enabled, appears when the cursor passes over any list view item. Hover selection is enabled by setting the LVS_EX_TRACKSELECT extended style.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetHotCursor, CListCtrl::GetHotItem


CListCtrl::GetHotItem

int GetHotItem( );

Return Value

The index of the current hot item of the list view control.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetHotItem, as described in the Platform SDK.

The hot item is defined as the currently selected item when hot tracking (and hover selection) is enabled.

If hot tracking is enabled, when a user pauses over a list view item, the item label is automatically highlited without the use of a mouse button.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetHotCursor


CListCtrl::GetHoverTime

DWORD GetHoverTime( ) const;

Return Value

Returns the delay, in milliseconds, which the mouse cursor must hover over an item before it is selected. If the return value is -1, then the hover time is the default hover time.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetHoverTime, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetHoverTime, CListCtrl::GetHotCursor


CListCtrl::GetImageList

CImageList* GetImageList( int nImageList ) const;

Return Value

A pointer to the image list used for drawing list view items.

Parameters

nImageList

Value specifying which image list to retrieve. It can be one of these values:

  • LVSIL_NORMAL Image list with large icons.

  • LVSIL_SMALL Image list with small icons.

  • LVSIL_STATE Image list with state images.

Remarks

Retrieves the handle of an image list used for drawing list view items.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CImageList, CListCtrl::SetImageList


CListCtrl::GetItem

BOOL GetItem( LVITEM* pItem ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

pItem

Pointer to an LVITEM structure that receives the item’s attributes.

Remarks

Retrieves some or all of a list view item’s attributes.

The LVITEM structure specifies or receives the attributes of a list view item.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetItem


CListCtrl::GetItemCount

int GetItemCount( );

Return Value

The number of items in the list view control.

Remarks

Retrieves the number of items in a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetItemCount, CListCtrl::GetSelectedCount


CListCtrl::GetItemData

DWORD GetItemData( int nItem ) const;

Return Value

A 32-bit application-specific value associated with the specified item.

Parameters

nItem

Index of the list item whose data is to be retrieved.

Remarks

This function retrieves the 32-bit application-specific value associated with the item specified by nItem. This value is the lParam member of the LVITEM structure, as described in the Platform SDK

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetItemData


CListCtrl::GetItemPosition

BOOL GetItemPosition( int nItem, LPPOINT lpPoint ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

nItem

The index of the item whose position is to be retrieved.

lpPoint

Address of a POINT structure that receives the position of the item’s upper-left corner, in view coordinates.

Remarks

Retrieves the position of a list view item.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetItemPosition, CListCtrl::GetOrigin


CListCtrl::GetItemRect

BOOL GetItemRect( int nItem, LPRECT lpRect, UINT nCode ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

nItem

The index of the item whose position is to be retrieved.

lpRect

Address of a RECT structure that receives the bounding rectangle.

nCode

Portion of the list view item for which to retrieve the bounding rectangle. It can be one of these 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.

Remarks

Retrieves the bounding rectangle for all or part of an item in the current view.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItemPosition, CListCtrl::SetItemPosition, CListCtrl::GetOrigin


CListCtrl::GetItemState

UINT GetItemState( int nItem, UINT nMask ) const;

Return Value

The state flags for the specified list view item.

Parameters

nItem

The index of the item whose state is to be retrieved.

nMask

Mask specifying which of the item’s state flags to return.

Remarks

Retrieves the state of a list view item.

An item’s state is specified by the state member of the LVITEM structure, as described in the Platform SDK. When you specify or change an item’s state, the stateMask member specifies which state bits you want to change.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetItemState, CListCtrl::GetItem


CListCtrl::GetItemText

int GetItemText( int nItem, int nSubItem, LPTSTR lpszText, int nLen ) const;

CString GetItemText( int nItem, int nSubItem ) const;

Return Value

The version returning int returns the length of the retrieved string.

The version returning a CString returns the item text.

Parameters

nItem

The index of the item whose text is to be retrieved.

nSubItem

Specifies the subitem whose text is to be retrieved.

lpszText

Pointer to a string that is to receive the item text.

nLen

Length of the buffer pointed to by lpszText.

Remarks

Retrieves the text of a list view item or subitem. If nSubItem is zero, this function retrieves the item label; if nSubItem is nonzero, it retrieves the text of the subitem. For more information on the subitem argument, see the discussion of the LVITEM structure in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItem


CListCtrl::GetNextItem

int GetNextItem( int nItem, int nFlags ) const;

Return Value

The index of the next item if successful, or -1 otherwise.

Parameters

nItem

Index of the item to begin the searching with, or -1 to find the first item that matches the specified flags. The specified item itself is excluded from the search.

nFlags

Geometric relation of the requested item to the specified item, and the state of the requested item. The geometric relation can be one of these values:

  • LVNI_ABOVE Searches for an item that is above the specified item.

  • LVNI_ALL Searches for a subsequent item by index (the default value).

  • LVNI_BELOW Searches for an item that is below the specified item.

  • LVNI_TOLEFT Searches for an item to the left of the specified item.

  • LVNI_TORIGHT Searches for an item to the right of the specified item.

The state can be zero, or it can be one or more of these values:

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

Remarks

Searches for a list view item that has the specified properties and that bears the specified relationship to a given item.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItem


CListCtrl::GetNextSelectedItem

int GetNextSelectedItem( POSITION& pos ) const;

Return Value

The index of the next selected item in the list view control.

Parameters

pos

A reference to a POSITION value returned by a previous call to GetNextSelectedItem or GetFirstSelectedItemPosition. The value is updated to the next position by this call.

Remarks

Gets the index of the list item identified by pos, then sets pos to the POSITION value. You can use GetNextSelectedItem in a forward iteration loop if you establish the initial position with a call to GetFirstSelectedItemPosition.

You must ensure that your POSITION value is valid. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

Example

The following code sample demonstrates the usage of this function.

CListCtrl* pListCtrl = (CListCtrl*) GetDlgItem(IDC_YOURLISTCONTROL);
ASSERT(pListCtrl != NULL);

POSITION pos = pList->GetFirstSelectedItemPosition();
if (pos == NULL)
   TRACE0("No items were selected!\n");
else
{
   while (pos)
   {
      int nItem = pList->GetNextSelectedItem(pos);
      TRACE1("Item %d was selected!\n", nItem);
      // you could do your own processing on nItem here
   }
}

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CImageList, CListCtrl::GetFirstSelectedItemPosition


CListCtrl::GetNumberOfWorkAreas

UINT GetNumberOfWorkAreas( ) const;

Return Value

Not used at this time.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetNumberOfWorkAreas, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetWorkAreas


CListCtrl::GetOrigin

BOOL GetOrigin( LPPOINT lpPoint ) const;

Return Value

Nonzero if successful; otherwise zero. However, if the control is in report view, the return value is always zero.

Parameters

lpPoint

Address of a POINT structure that receives the view origin.

Remarks

Retrieves the current view origin for a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItemPosition, CListCtrl::SetItemPosition


CListCtrl::GetSelectedCount

UINT GetSelectedCount( ) const;

Return Value

The number of selected items in the list view control.

Remarks

Retrieves the number of selected items in the list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetItemCount, CListCtrl::GetItemCount


CListCtrl::GetSelectionMark

int GetSelectionMark( );

Return Value

The zero-based selection mark, or -1 if there is no selection mark.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetSelectionMark, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetSelectionMark


CListCtrl::GetStringWidth

int GetStringWidth( LPCTSTR lpsz ) const;

Return Value

The width, in pixels, of the string pointed to by lpsz.

Parameters

lpsz

Address of a null-terminated string whose width is to be determined.

Remarks

Determines the minimum column width necessary to display all of a given string.

The returned width takes into account the control’s current font and column margins, but not the width of a small icon.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetColumnWidth


CListCtrl::GetSubItemRect

BOOL GetSubItemRect( int iItem, int iSubItem, int nArea, CRect& ref );

Return Value

Nonzero if successful; otherwise zero.

Parameters

iItem

Index of the subitem’s parent item.

iSubItem

The one-based index of the subitem.

nArea

Determines the portion of the bounding rectangle (of the list view subitem) to be retrieved. The portion (icon, label, or both) of the bounding rectangle is specified by applying the bitwise OR operator to one or more 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 entire item, including the icon and label. This is identical to LVIR_BOUNDS.

ref

Reference to a CRect object that contains the coordinates of the subitem’s bounding rectangle.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetSubItemRect, as described in the Platform SDK.


CListCtrl::GetTextBkColor

COLORREF GetTextBkColor( ) const;

Return Value

A 32-bit value used to specify an RGB color.

Remarks

Retrieves the text background color of a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetTextBkColor, CListCtrl::GetTextColor COLORREF


CListCtrl::GetTextColor

COLORREF GetTextColor( ) const;

Return Value

A 32-bit value used to specify an RGB color.

Remarks

Retrieves the text color of a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetTextColor, CListCtrl::GetTextBkColor COLORREF


CListCtrl::GetTopIndex

int GetTopIndex( ) const;

Return Value

The index of the topmost visible item.

Remarks

Retrieves the index of the topmost visible item when in list view or report view.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetCountPerPage


CListCtrl::GetViewRect

BOOL GetViewRect( LPRECT lpRect ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

lpRect

Address of a RECT structure.

Remarks

Retrieves the bounding rectangle of all items in the list view control. The list view must be in icon view or small icon view.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetTopIndex


CListCtrl::GetWorkAreas

void GetWorkAreas( int nWorkAreas, LPRECT prc ) const;

Parameters

nWorkAreas

The number of RECT structures contained in the prc array.

prc

A pointer to an array of RECT structures (or CRect objects) that receive the working areas of the list view control. Values in these structures are in client coordinates.

Remarks

This member function implements the behavior of the Win32 macro, ListView_GetWorkAreas, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetNumberOfWorkAreas


CListCtrl::HitTest

int HitTest( LVHITTESTINFO* pHitTestInfo ) const;

int HitTest( CPoint pt, UINT* pFlags = NULL ) const;

Return Value

The index of the item at the position specified by pHitTestInfo, if any, or -1 otherwise.

Parameters

pHitTestInfo

Address of a LVHITTESTINFO structure that contains the position to hit test and that receives information about the results of the hit test.

pt

Point to be tested.

pFlags

Pointer to an integer that receives information about the results of the test. See the explanation of the flags member of the LVHITTESTINFO structure in the Platform SDK.

Remarks

Determines which list view item, if any, is at a specified position.

You can use the LVHT_ABOVE, LVHT_BELOW, LVHT_TOLEFT, and LVHT_TORIGHT values of the structure's flag member to determine whether to scroll the contents of a list view control. Two of these flags can be combined, for example, if the position is above and to the left of the client area.

You can test for the LVHT_ONITEM value of the structure's flag member to determine whether a given position is over a list view item. This value is a bitwise-OR operation on the LVHT_ONITEMICON, LVHT_ONITEMLABEL, and LVHT_ONITEMSTATEICON values of the structure's flag member.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItemPosition


CListCtrl::InsertColumn

int InsertColumn( int nCol, const LVCOLUMN* pColumn );

int InsertColumn( int nCol, LPCTSTR lpszColumnHeading, int nFormat = LVCFMT_LEFT, int nWidth = -1, int nSubItem = -1 );

Return Value

The index of the new column if successful or -1 otherwise.

Parameters

nCol

The index of the new column.

pColumn

Address of an LVCOLUMN structure that contains the attributes of the new column.

lpszColumnHeading

Address of a string containing the column’s heading.

nFormat

Integer specifying the alignment of the column. It can be one of these values: LVCFMT_LEFT, LVCFMT_RIGHT, or LVCFMT_CENTER.

nWidth

Width of the column, in pixels. If this parameter is -1, the column width is not set.

nSubItem

Index of the subitem associated with the column. If this parameter is -1, no subitem is associatied with the column.

Remarks

Inserts a new column in a list view control.

The LVCOLUMN structure contains the attributes of a column in report view. It is also used to receive information about a column. This structure is described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::DeleteColumn


CListCtrl::InsertItem

int InsertItem( const LVITEM* pItem );

int InsertItem( int nItem, LPCTSTR lpszItem );

int InsertItem( int nItem, LPCTSTR lpszItem, int nImage );

int InsertItem( UINT nMask, int nItem, LPCTSTR lpszItem, UINT nState, UINT nStateMask, int nImage, LPARAM lParam );

Return Value

The index of the new item if successful or -1 otherwise.

Parameters

pItem

Pointer to an LVITEM structure that specifies the item’s attributes, as described in the Platform SDK.

nItem

Index of the item to be inserted.

lpszItem

Address of a string containing the item’s label, or LPSTR_TEXTCALLBACK if the item is a callback item. For information on callback items, see CListCtrl::GetCallbackMask.

nImage

Index of the item’s image, or I_IMAGECALLBACK if the item is a callback item. For information on callback items, see CListCtrl::GetCallbackMask.

nMask

The nMask parameter specifies which item attributes passed as parameters are valid. It can be one or more of the mask values described in LVITEM structure in the Platform SDK. The valid values can be combined with the bitwise OR operator.

nState

Indicates the item's state, state image, and overlay image. See the Platform SDK topics LVITEM for more information and List View Item States for a list of valid flags.

nStateMask

Indicates which bits of the state member will be retrieved or modified. See LVITEM in the Platform SDK for more information.

nImage

Index of the item’s image within the image list.

lParam

A 32-bit application-specific value associated with the item. If this parameter is specified, you must set the nMask attribute LVIF_PARAM.

Remarks

Inserts an item into the list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::DeleteItem, CListCtrl::DeleteAllItems


CListCtrl::RedrawItems

BOOL RedrawItems( int nFirst, int nLast );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nFirst

Index of the first item to be repainted.

nLast

Index of the last item to be repainted.

Remarks

Forces a list view control to repaint a range of items.

The specified items are not actually repainted until the list view window receives a WM_PAINT message. To repaint immediately, call the Windows UpdateWindow function after using this function.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::DrawItem


CListCtrl::Scroll

BOOL Scroll( CSize size );

Return Value

Nonzero if successful; otherwise zero.

Parameters

size

A CSize object specifying the amount of horizontal and vertical scrolling, in pixels. The y member of size is divided by the height, in pixels, of the list view control’s line, and the control is scrolled by the resulting number of lines.

Remarks

Scrolls the content of a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::EnsureVisible


CListCtrl::SetBkColor

BOOL SetBkColor( COLORREF cr );

Return Value

Nonzero if successful; otherwise zero.

Parameters

cr

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. For information, see COLORREF in the Platform SDK.

Remarks

Sets the background color of the list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetBkColor


CListCtrl::SetBkImage

BOOL SetBkImage( LVBKIMAGE* plvbkImage );

BOOL SetBkImage( HBITMAP hbm, BOOL fTile = TRUE, int xOffsetPercent = 0, int yOffsetPercent = 0);

BOOL SetBkImage( LPTSTR pszUrl, BOOL fTile = TRUE, int xOffsetPercent = 0, int yOffsetPercent = 0 );

Return Value

Returns nonzero if successful, or zero otherwise.

Parameters

plvbkImage

Address of a LVBKIMAGE structure, containing the new background image information.

hbm

Handle to a bitmap.

pszUrl

A NULL-terminated string that contains the URL of the background image.

fTile

Nonzero if the image is to be tiled in the background of the list view control; otherwise 0.

xOffsetPercent

The offset, in pixels, of the image’s left edge, from origin of the list view control.

yOffsetPercent

The offset, in pixels, of the image’s top edge, from origin of the list view control.

Remarks

Call this function to set the background image of a list view control.

Note Because CListCtrl::SetBkImage makes use of OLE COM functionality, the OLE libraries must be initialized before using SetBkImage. It is best to initialize the COM libraries when the application is initialized and uninitialize the libraries when the application terminates. This is automatically done in MFC applications that make use of ActiveX technology, OLE Automation, OLE Linking/Embedding, or ODBC/DAO operations.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetBkImage


CListCtrl::SetCallbackMask

BOOL SetCallbackMask( UINT nMask );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nMask

New value of the callback mask.

Remarks

Sets the callback mask for a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetCallbackMask


CListCtrl::SetCheck

BOOL SetCheck( int nItem, BOOL fCheck = TRUE );

Return Value

Nonzero if the item is checked, otherwise 0.

Parameters

nItem

The zero-based index of a list control item.

fCheck

Specifies whether the state image of the item should be visible or not. By default, fCheck is TRUE and the state image is visible. If fCheck is FALSE, it is not visible.

Remarks

This member function determines if the state image of a list control item is visible or not.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetCheck


CListCtrl::SetColumn

BOOL SetColumn( int nCol, const LVCOLUMN* pColumn );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nCol

Index of the column whose attributes are to be set.

pColumn

Address of an LVCOLUMN structure that contains the new column attributes, as described in the Platform SDK. The structure's mask member specifies which column attributes to set. If the mask member specifies the LVCF_TEXT value, the structure's pszText member is the address of a null-terminated string and the structure's cchTextMax member is ignored.

Remarks

Sets the attributes of a list view column.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetColumn


CListCtrl::SetColumnOrderArray

BOOL SetColumnOrderArray( int iCount, LPINT piArray );

Return Value

Nonzero if successful; otherwise zero.

Parameters

piArray

A pointer to a buffer containing the index values of the columns in the list view control (from left to right). The buffer must be large enough to contain the total number of columns in the list view control.

iCount

Number of columns in the list view control.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetColumnOrderArray, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetColumnOrderArray


CListCtrl::SetColumnWidth

BOOL SetColumnWidth( int nCol, int cx );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nCol

Index of the column whose width is to be set. In list view, this parameter must be -1.

cx

The new width of the column. Can be either LVSCW_AUTOSIZE or LVSCW_AUTOSIZE_USE_HEADER, as described in LVM_SETCOLUMNWIDTH in the Platform SDK.

Remarks

Changes the width of a column in report view or list view.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetColumnWidth, CListCtrl::GetStringWidth


CListCtrl::SetExtendedStyle

DWORD SetExtendedStyle( DWORD dwNewStyle );

Return Value

A combination of the previous extended styles used by the list view control.

Parameters

dwNewStyle

A combination of extended styles to be used by the list view control. For a descriptive list of these styles, see the Extended List View Styles topic in the Platform SDK.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetExtendedListViewStyle, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetExtendedStyle


CListCtrl::SetHotCursor

HCURSOR SetHotCursor( HCURSOR hc );

Return Value

The handle to the previous hot cursor resource being used by the list view control.

Parameters

hc

A handle to a cursor resource, used to represent the hot cursor.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetHotCursor, as described in the Platform SDK.

The hot cursor, only visible when hover selection is enabled, appears as the cursor passes over any list view item. Hover selection is enabled by setting the LVS_EX_TRACKSELECT extended style.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetHotCursor, CListCtrl::GetHotItem


CListCtrl::SetHotItem

int SetHotItem( int iIndex );

Return Value

The zero-based index of the previously hot item.

Parameters

iIndex

Zero-based index of the item to be set as the hot item.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetHotItem, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetHotCursor, CListCtrl::GetHotItem


CListCtrl::SetHoverTime

DWORD SetHoverTime( DWORD dwHoverTime = (DWORD)-1 );

Return Value

The previous hover time, in milliseconds.

Parameters

dwHoverTime

The new delay, in milliseconds, which the mouse cursor must hover over an item before it is selected. If the default value is passed, the time is set to the default hover time.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetHoverTime, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetHoverTime


CListCtrl::SetIconSpacing

CSize SetIconSpacing( int cx, int cy );

CSize SetIconSpacing( CSize size );

Return Value

A CSize object containing the previous values for icon spacing.

Parameters

cx

The distance (in pixels) between icons on the x-axis.

cy

The distance (in pixels) between icons on the y-axis.

size

A CSize object specifying the distance (in pixels) between icons on the x- and y-axes.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetIconSpacing, as described in the Platform SDK.


CListCtrl::SetImageList

CImageList* SetImageList( CImageList* pImageList, int nImageList );

Return Value

A pointer to the previous image list.

Parameters

pImageList

Pointer to the image list to assign.

nImageList

Type of image list. It can be one of these values:

  • LVSIL_NORMAL Image list with large icons.

  • LVSIL_SMALL Image list with small icons.

  • LVSIL_STATE Image list with state images.

Remarks

Assigns an image list to a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CImageList, CListCtrl::GetImageList


CListCtrl::SetItem

BOOL SetItem( const LVITEM* pItem );

BOOL SetItem( int nItem, int nSubItem, UINT nMask, LPCTSTR lpszItem, int nImage, UINT nState, UINT nStateMask, LPARAM lParam );

Return Value

Nonzero if successful; otherwise zero.

Parameters

pItem

Address of an LVITEM structure that contains the new item attributes, as described in the Platform SDK. The structure's iItem and iSubItem members identify the item or subitem, and the structure's mask member specifies which attributes to set. For more information on the mask member, see the Remarks.

nItem

Index of the item whose attributes are to be set.

nSubItem

Index of the subitem whose attributes are to be set.

nMask

Specifies which attributes are to be set (see the Remarks).

lpszItem

Address of a null-terminated string specifying the item’s label.

nImage

Index of the item’s image within the image list.

nState

Specifies values for states to be changed (see the Remarks).

nStateMask

Specifies which states are to be changed (see the Remarks).

lParam

A 32-bit application-specific value to be associated with the item.

Remarks

Sets some or all of a list view item’s attributes.

The iItem and iSubItem members of the LVITEM structure and the nItem and nSubItem parameters identify the item and subitem whose attributes are to be set.

The mask member of the LVITEM structure and the nMask parameter specify which item attributes are to be set:

  • LVIF_TEXT The pszText member or the lpszItem parameter is the address of a null-terminated string; the cchTextMax member is ignored.

  • LVIF_STATE The stateMask member or nStateMask parameter specifies which item states to change and the state member or nState parameter contains the values for those states.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItem


CListCtrl::SetItemCount

void SetItemCount( int iCount );

Parameters

nItems

Number of items that the control will ultimately contain.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetItemCount, as described in the Platform SDK.

To set the item count for a virtual list view control, see CListCtrl::SetItemCountEx.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItemCount, CListCtrl::GetSelectedCount


CListCtrl::SetItemCountEx

void SetItemCountEx( int iCount, DWORD dwFlags = LVSICF_NOINVALIDATEALL );

Parameters

nItems

Number of items that the control will ultimately contain.

dwFlags

Specifies 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. This is the default value.

  • LVSICF_NOSCROLL The list view control will not change the scroll position when the item count changes.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetItemCountEx, as described in the Platform SDK and should only be called for virtual list views.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetItemCount,


CListCtrl::SetItemData

BOOL SetItemData( int nItem, DWORD dwData );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nItem

Index of the list item whose data is to be set.

dwData

A 32-bit value to be associated with the item.

Remarks

This function sets the 32-bit application-specific value associated with the item specified by nItem. This value is the lParam member of the LVITEM structure, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItemData


CListCtrl::SetItemPosition

BOOL SetItemPosition( int nItem, POINT pt );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nItem

Index of the item whose position is to be set.

pt

A POINT structure specifying the new position, in view coordinates, of the item’s upper-left corner.

Remarks

Moves an item to a specified position in a list view control. The control must be in icon or small icon view.

If the list view control has the LVS_AUTOARRANGE style, the list view is arranged after the position of the item is set.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItemPosition, CListCtrl::GetOrigin


CListCtrl::SetItemState

BOOL SetItemState( int nItem, LVITEM* pItem );

BOOL SetItemState( int nItem, UINT nState, UINT nMask );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nItem

Index of the item whose state is to be set.

pItem

Address of an LVITEM structure, as described in the Platform SDK. The structure's stateMask member specifies which state bits to change, and the structure's state member contains the new values for those bits. The other members are ignored.

nState

New values for the state bits.

nMask

Mask specifying which state bits to change.

Remarks

Changes the state of an item in a list view control.

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.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItemState


CListCtrl::SetItemText

BOOL SetItemText( int nItem, int nSubItem, LPTSTR lpszText );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nItem

Index of the item whose text is to be set.

nSubItem

Index of the subitem, or zero to set the item label.

lpszText

Pointer to a string that contains the new item text.

Remarks

Changes the text of a list view item or subitem.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetItemText


CListCtrl::SetSelectionMark

int SetSelectionMark( int iIndex );

Return Value

The previous selection mark, or -1 if there was no selection mark.

Parameters

iIndex

The zero-based index of the first item in a multiple selection.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetSelectionMark, as described in the Platform SDK.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetSelectionMark


CListCtrl::SetTextBkColor

BOOL SetTextBkColor( COLORREF cr );

Return Value

Nonzero if successful; otherwise zero.

Parameters

cr

A COLORREF specifying the new text background color. For information, see COLORREF in the Platform SDK.

Remarks

Sets the background color of text in a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::GetTextBkColor


CListCtrl::SetTextColor

BOOL SetTextColor( COLORREF cr );

Return Value

Nonzero if successful; otherwise zero.

Parameters

cr

A COLORREF specifying the new text color. For information, see COLORREF in the Platform SDK.

Remarks

Sets the text color of a list view control.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::SetTextBkColor


CListCtrl::SetWorkAreas

void SetWorkAreas( int nWorkAreas, LPRECT lpRect );

Parameters

nWorkAreas

The number of RECT structures (or CRect objects) in the array pointed to by lpRect.

lpRect

The address of an array of RECT structures (or CRect objects) that specify the new work areas of the list view control. These areas must be specified in client coordinates. If this parameter is NULL, the working area will be set to the client area of the control.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SetWorkAreas, as described in the Platform SDK.


CListCtrl::SortItems

BOOL SortItems( PFNLVCOMPARE pfnCompare, DWORD dwData );

Return Value

Nonzero if successful; otherwise zero.

Parameters

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 must be either a static member of a class or a stand alone function that is not a member of any class.

dwData

Application-defined value that is passed to the comparison function.

Remarks

Sorts list view items using an application-defined comparison function. The index of each item changes to reflect the new sequence.

The comparison function has the following form:

int CALLBACK CompareFunc(LPARAM lParam1, LPARAM lParam2,
   LPARAM lParamSort);

The comparison function must return a negative value if the first item should precede the second, a positive value if the first item should follow the second, or zero if the two items are equivalent.

The lParam1 and lParam2 parameters specify the item data for the two items being compared. The lParamSort parameter is the same as the dwData value.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::FindItem


CListCtrl::SubItemHitTest

int SubItemHitTest( LPLVHITTESTINFO pInfo );

Return Value

The one-based index of the item, or subitem, being tested (if any), or -1 otherwise.

Parameters

pInfo

A pointer to the LVHITTESTINFO structure.

Remarks

This member function implements the behavior of the Win32 macro, ListView_SubItemHitTest, as described in the Platform SDK.


CListCtrl::Update

BOOL Update( int nItem );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nItem

Index of the item to be updated.

Remarks

Call this function to force the list view control to repaint the item specified by nItem. This function also arranges the list view control if it has the LVS_AUTOARRANGE style.

CListCtrl Overview | Class Members | Hierarchy Chart

See Also CListCtrl::DrawItem


CListView

The CListView class simplifies use of the list control and of CListCtrl, the class that encapsulates list-control functionality, with MFC’s document-view architecture. For more information on this architecture, see the overview for the CView class and the cross-references cited there.

#include <afxcview.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample DBFETCH | MFC Sample HTTPSVR | MFC Sample ROWLIST | MFC Sample DBVLIST

See Also CCtrlView


CListView Class Members

Construction

CListView Constructs a CListView object.

Attributes

GetListCtrl Returns the list control associated with the view.


CListView::CListView

CListView( );

Remarks

Constructs a CListView object.


CListView::GetListCtrl

CListCtrl& GetListCtrl( ) const;

Return Value

A reference to the list control associated with the view.

Remarks

Call this member function to get a reference to the list control associated with the view.

CListView Overview | Class Members | Hierarchy Chart

See Also CListCtrl


CLongBinary

Class CLongBinary simplifies working with very large binary data objects (often called BLOBs, or “binary large objects”) in a database. For example, a record field in an SQL table might contain a bitmap representing a picture. A CLongBinary object stores such an object and keeps track of its size.

Note In general, it is better practice now to use CByteArray in conjunction with the DFX_Binary function. You can still use CLongBinary, but in general CByteArray provides more functionality under Win32, since there is no longer the size limitation encountered with 16-bit CByteArray. This advice applies to programming with Data Access Objects (DAO) as well as Open Database Connectivity (ODBC).

To use a CLongBinary object, declare a field data member of type CLongBinary in your recordset class. This member will be an embedded member of the recordset class and will be constructed when the recordset is constructed. After the CLongBinary object is constructed, the record field exchange (RFX) mechanism loads the data object from a field in the current record on the data source and stores it back to the record when the record is updated. RFX queries the data source for the size of the binary large object, allocates storage for it (via the CLongBinary object’s m_hData data member), and stores an HGLOBAL handle to the data in m_hData. RFX also stores the actual size of the data object in the m_dwDataLength data member. Work with the data in the object through m_hData, using the same techniques you would normally use to manipulate the data stored in a Windows HGLOBAL handle.

When you destroy your recordset, the embedded CLongBinary object is also destroyed, and its destructor deallocates the HGLOBAL data handle.

For more information about large objects and the use of CLongBinary, see the articles Recordset (ODBC) and Recordset: Working with Large Data Items (ODBC) in Visual C++ Programmer’s Guide.

#include <afxdb.h>

Class Members | Base Class | Hierarchy Chart

See Also CRecordset


CLongBinary Class Members

Data Members

m_dwDataLength | Contains the actual size in bytes of the data object whose handle is stored in m_hData.
m_hData | Contains a Windows HGLOBAL handle to the actual image object.

Construction

CLongBinary Constructs a CLongBinary object.


CLongBinary::CLongBinary

CLongBinary( );

Remarks

Constructs a CLongBinary object.


CLongBinary::m_dwDataLength

Remarks

Stores the actual size in bytes of the data stored in the HGLOBAL handle in m_hData. This size may be smaller than the size of the memory block allocated for the data. Call ::GlobalSize to get the allocated size.


CLongBinary::m_hData

Remarks

Stores a Windows HGLOBAL handle to the actual binary large object data.


CMap

template< class KEY, class ARG_KEY, class VALUE, class ARG_VALUE >class CMap : public CObject

Parameters

KEY

Class of the object used as the key to the map.

ARG_KEY

Data type used for KEY arguments; usually a reference to KEY.

VALUE

Class of the object stored in the map.

ARG_VALUE

Data type used for VALUE arguments; usually a reference to VALUE.

Remarks

CMap is a dictionary collection class that maps unique keys to values. Once you have inserted a key-value pair (element) into the map, you can efficiently retrieve or delete the pair using the key to access it. You can also iterate over all the elements in the map.

A variable of type POSITION is used for alternate access to entries. You can use a POSITION to “remember” an entry and to iterate through the map. You might think that this iteration is sequential by key value; it is not. The sequence of retrieved elements is indeterminate.

Certain member functions of this class call global helper functions that must be customized for most uses of the CMap class. See Collection Class Helpers in the Macros and Globals section of the MFC Reference.

CMap incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. Each element is serialized in turn if a map is stored to an archive, either with the overloaded insertion (<<) operator or with the Serialize member function.

If you need a diagnostic dump of the individual elements in the map (the keys and the values), you must set the depth of the dump context to 1 or greater.

When a CMap object is deleted, or when its elements are removed, the keys and values both are removed.

Map class derivation is similar to list derivation. See the article Collections in Visual C++ Programmer’s Guide for an illustration of the derivation of a special-purpose list class.

#include <afxtempl.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample COLLECT


CMap Class Members

Construction

CMap Constructs a collection that maps keys to values.

Operations

Lookup | Looks up the value mapped to a given key.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.
operator [] | Inserts an element into the map — operator substitution for SetAt.
RemoveKey | Removes an element specified by a key.
RemoveAll | Removes all the elements from this map.
GetStartPosition | Returns the position of the first element.
GetNextAssoc | Gets the next element for iterating.
GetHashTableSize | Returns the size (number of elements) of the hash table.
InitHashTable | Initializes the hash table and specifies its size.

Status

GetCount | Returns the number of elements in this map.
IsEmpty | Tests for the empty-map condition (no elements).


CMap::CMap

CMap( int nBlockSize = 10 );

Parameters

nBlockSize

Specifies the memory-allocation granularity for extending the map.

Remarks

Constructs an empty map. As the map grows, memory is allocated in units of nBlockSize entries.


CMap::GetCount

int GetCount( ) const;

Return Value

The number of elements.

Remarks

Call this member function to retrieve the number of elements in the map.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::IsEmpty


CMap::GetHashTableSize

UINT GetHashTableSize( ) const;

Return Value

The number of elements in the hash table.

Remarks

Call this member function to determine the number of elements in the hash table for the map.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::InitHashTable


CMap::GetNextAssoc

void GetNextAssoc( POSITION& rNextPosition, KEY& rKey, VALUE& rValue ) const;

Parameters

rNextPosition

Specifies a reference to a POSITION value returned by a previous GetNextAssoc or GetStartPosition call.

KEY

Template parameter specifying the type of the map’s key.

rKey

Specifies the returned key of the retrieved element.

VALUE

Template parameter specifying the type of the map’s value.

rValue

Specifies the returned value of the retrieved element.

Remarks

Retrieves the map element at rNextPosition, then updates rNextPosition to refer to the next element in the map. This function is most useful for iterating through all the elements in the map. Note that the position sequence is not necessarily the same as the key value sequence.

If the retrieved element is the last in the map, then the new value of rNextPosition is set to NULL.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::GetStartPosition


CMap::GetStartPosition

POSITION GetStartPosition( ) const;

Return Value

A POSITION value that indicates a starting position for iterating the map; or NULL if the map is empty.

Remarks

Starts a map iteration by returning a POSITION value that can be passed to a GetNextAssoc call. The iteration sequence is not predictable; therefore, the “first element in the map” has no special significance.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::GetNextAssoc


CMap::InitHashTable

void InitHashTable( UINT hashSize );

Parameters

hashSize

Number of entries in the hash table.

Remarks

Initializes the hash table. For best performance, the hash table size should be a prime number. To minimize collisions the size should be roughly 20 percent larger than the largest anticipated data set.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::GetHashTableSize


CMap::IsEmpty

BOOL IsEmpty( ) const;

Return Value

Nonzero if this map contains no elements; otherwise 0.

Remarks

Call this member function to determine whether the map is empty.

Example

See the example for CMapStringToOB::RemoveAll.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::GetCount


CMap::Lookup

BOOL Lookup( ARG_KEY key, VALUE& rValue ) const;

Return Value

Nonzero if the element was found; otherwise 0.

Parameters

ARG_KEY

Template parameter specifying the type of the key value.

key

Specifies the key that identifies the element to be looked up.

VALUE

Specifies the type of the value to be looked up.

rValue

Receives the looked-up value.

Remarks

Lookup uses a hashing algorithm to quickly find the map element with a key that exactly matches the given key.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::operator []


CMap::RemoveAll

void RemoveAll( );

Remarks

Removes all the values from this map by calling the global helper function DestructElements.

The function works correctly if the map is already empty.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::RemoveKey, DestructElements


CMap::RemoveKey

BOOL RemoveKey( ARG_KEY key );

Return Value

Nonzero if the entry was found and successfully removed; otherwise 0.

Parameters

ARG_KEY

Template parameter specifying the type of the key.

key

Key for the element to be removed.

Remarks

Looks up the map entry corresponding to the supplied key; then, if the key is found, removes the entry.

The DestructElements helper function is used to remove the entry.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::RemoveAll


CMap::SetAt

void SetAt( ARG_KEY key, ARG_VALUE newValue );

Parameters

ARG_KEY

Template parameter specifying the type of the key parameter.

key

Specifies the key of the new element.

ARG_VALUE

Template parameter specifying the type of the newValue parameter.

newValue

Specifies the value of the new element.

Remarks

The primary means to insert an element in a map. First, the key is looked up. If the key is found, then the corresponding value is changed; otherwise a new key-value pair is created.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::Lookup, CMap::operator []


CMap::operator [ ]

VALUE& operator[]( ARG_KEY key );

Parameters

VALUE

Template parameter specifying the type of the map value.

ARG_KEY

Template parameter specifying the type of the key value.

key

The key used to retrieve the value from the map.

Remarks

This operator is a convenient substitute for the SetAt member function. Thus it can be used only on the left side of an assignment statement (an l-value). If there is no map element with the specified key, then a new element is created.

There is no “right side” (r-value) equivalent to this operator because there is a possibility that a key may not be found in the map. Use the Lookup member function for element retrieval.

CMap Overview | Class Members | Hierarchy Chart

See Also CMap::SetAt, CMap::Lookup


CMapPtrToPtr

The CMapPtrToPtr class supports maps of void pointers keyed by void pointers.

The member functions of CMapPtrToPtr are similar to the member functions of class CMapStringToOb. Because of this similarity, you can use the CMapStringToOb reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a pointer to void. Wherever you see a CString or a const pointer to char as a function parameter or return value, substitute a pointer to void.

BOOL CMapStringToOb::Lookup( const char* <key>,
                             CObject*& <rValue> ) const;

for example, translates to

BOOL CMapPtrToPtr::Lookup( void* <key>, void*& <rValue> ) const;

CMapPtrToPtr incorporates the IMPLEMENT_DYNAMIC macro to support run-time type access and dumping to a CDumpContext object. If you need a dump of individual map elements (pointer values), you must set the depth of the dump context to 1 or greater.

Pointer-to-pointer maps may not be serialized.

When a CMapPtrToPtr object is deleted, or when its elements are removed, only the pointers are removed, not the entities they reference.

For more information on CMapPtrToPtr, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>


CMapPtrToPtr Class Members

Construction

CMapPtrToPtr Constructs a collection that maps void pointers to void pointers.

Operations

Lookup | Looks up a void pointer based on the void pointer key. The pointer value, not the entity it points to, is used for the key comparison.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.
operator [ ] | Inserts an element into the map — operator substitution for SetAt.
RemoveKey | Removes an element specified by a key.
RemoveAll | Removes all the elements from this map.
GetStartPosition | Returns the position of the first element.
GetNextAssoc | Gets the next element for iterating.

Status

GetCount | Returns the number of elements in this map.
IsEmpty | Tests for the empty-map condition (no elements).


CMapPtrToWord

The CMapPtrToWord class supports maps of 16-bit words keyed by void pointers.

The member functions of CMapPtrToWord are similar to the member functions of class CMapStringToOb. Because of this similarity, you can use the CMapStringToOb reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute WORD. Wherever you see a CString or a const pointer to char as a function parameter or return value, substitute a pointer to void.

BOOL CMapStringToOb::Lookup( const char* <key>,
                             CObject*& <rValue> ) const;

for example, translates to

BOOL CMapPtrToWord::Lookup( const void* <key>, WORD& <rValue> ) const;

CMapWordToPtr incorporates the IMPLEMENT_DYNAMIC macro to support run-time type access and dumping to a CDumpContext object. If you need a dump of individual map elements, you must set the depth of the dump context to 1 or greater.

Pointer-to-word maps may not be serialized.

When a CMapPtrToWord object is deleted, or when its elements are removed, the pointers and the words are removed. The entities referenced by the key pointers are not removed.

For more information on CMapPtrToWord, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>


CMapPtrToWord Class Members

Construction

CMapPtrToWord Constructs a collection that maps void pointers to 16-bit words.

Operations

Lookup | Returns a WORD using a void pointer as a key. The pointer value, not the entity it points to, is used for the key comparison.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.
operator [] | Inserts an element into the map — operator substitution for SetAt.
RemoveKey | Removes an element specified by a key.
RemoveAll | Removes all the elements from this map.
GetStartPosition | Returns the position of the first element.
GetNextAssoc | Gets the next element for iterating.

Status

GetCount | Returns the number of elements in this map.
IsEmpty | Tests for the empty-map condition (no elements).


CMapStringToOb

CMapStringToOb is a dictionary collection class that maps unique CString objects to CObject pointers. Once you have inserted a CString-CObject* pair (element) into the map, you can efficiently retrieve or delete the pair using a string or a CString value as a key. You can also iterate over all the elements in the map.

A variable of type POSITION is used for alternate entry access in all map variations. You can use a POSITION to “remember” an entry and to iterate through the map. You might think that this iteration is sequential by key value; it is not. The sequence of retrieved elements is indeterminate.

CMapStringToOb incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. Each element is serialized in turn if a map is stored to an archive, either with the overloaded insertion (<<) operator or with the Serialize member function.

If you need a diagnostic dump of the individual elements in the map (the CString value and the CObject contents), you must set the depth of the dump context to 1 or greater.

When a CMapStringToOb object is deleted, or when its elements are removed, the CString objects and the CObject pointers are removed. The objects referenced by the CObject pointers are not destroyed.

Map class derivation is similar to list derivation. See the article Collections in Visual C++ Programmer’s Guide for an illustration of the derivation of a special-purpose list class.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

See Also CMapPtrToPtr, CMapPtrToWord, CMapStringToPtr, CMapStringToString, CMapWordToOb, CMapWordToPtr


CMapStringToOb Class Members

Construction

CMapStringToOb Constructs a collection that maps CString values to CObject pointers.

Operations

Lookup | Returns a CObject pointer based on a CString value.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.
operator [] | Inserts an element into the map — operator substitution for SetAt.
RemoveKey | Removes an element specified by a key.
RemoveAll | Removes all the elements from this map.
GetStartPosition | Returns the position of the first element.
GetNextAssoc | Gets the next element for iterating.

Status

GetCount | Returns the number of elements in this map.
IsEmpty | Tests for the empty-map condition (no elements).


CMapStringToOb::CMapStringToOb

CMapStringToOb( int nBlockSize = 10 );

Parameters

nBlockSize

Specifies the memory-allocation granularity for extending the map.

Remarks

Constructs an empty CString-to-CObject* map. As the map grows, memory is allocated in units of nBlockSize entries.

Example

// example for CMapStringToOb::CMapStringToOb
CMapStringToOb map(20);  // Map on the stack with blocksize of 20

CMapStringToOb* pm = new CMapStringToOb;  // Map on the heap
                                          // with default blocksize

See CObList::CObList for a listing of the CAge class used in all collection examples.


CMapStringToOb::GetCount

int GetCount( ) const;

Return Value

The number of elements in this map.

Remarks

Call this member function to determine how many elements are in the map.

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CMapStringToOb::GetCount
CMapStringToOb map;

map.SetAt( "Bart", new CAge( 13 ) );
map.SetAt( "Homer", new CAge( 36 ) );
ASSERT( map.GetCount() == 2 );

CMapStringToOb Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::IsEmpty


CMapStringToOb::GetNextAssoc

void GetNextAssoc( POSITION& rNextPosition, CString& rKey, CObject*& rValue ) const;

Parameters

rNextPosition

Specifies a reference to a POSITION value returned by a previous GetNextAssoc or GetStartPosition call.

rKey

Specifies the returned key of the retrieved element (a string).

rValue

Specifies the returned value of the retrieved element (a CObject pointer). See Remarks for more about this parameter.

Remarks

Retrieves the map element at rNextPosition, then updates rNextPosition to refer to the next element in the map. This function is most useful for iterating through all the elements in the map. Note that the position sequence is not necessarily the same as the key value sequence.

If the retrieved element is the last in the map, then the new value of rNextPosition is set to NULL.

For the rValue parameter, be sure to cast your object type to CObject*&, which is what the compiler requires, as shown in the following example:

CMyObject* ob;
map.GetNextAssoc(pos, key, (CObject*&)ob);

This is not true of GetNextAssoc for maps based on templates.

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CMapStringToOb::GetNextAssoc and CMapStringToOb::GetStartPosition
   CMapStringToOb map;
   POSITION pos;
   CString key;
   CAge* pa;

   map.SetAt( "Bart", new CAge( 13 ) );
   map.SetAt( "Lisa", new CAge( 11 ) );
   map.SetAt( "Homer", new CAge( 36 ) );
   map.SetAt( "Marge", new CAge( 35 ) );
   // Iterate through the entire map, dumping both name and age.
   for( pos = map.GetStartPosition(); pos != NULL; )
   {
   map.GetNextAssoc( pos, key, (CObject*&)pa );
#ifdef _DEBUG
      afxDump << key << " : " << pa << "\n";
#endif
   }

The results from this program are as follows:

Lisa : a CAge at $4724 11
Marge : a CAge at $47A8 35
Homer : a CAge at $4766 36
Bart : a CAge at $45D4 13

CMapStringToOb Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::GetStartPosition


CMapStringToOb::GetStartPosition

POSITION GetStartPosition( ) const;

Return Value

A POSITION value that indicates a starting position for iterating the map; or NULL if the map is empty.

Remarks

Starts a map iteration by returning a POSITION value that can be passed to a GetNextAssoc call. The iteration sequence is not predictable; therefore, the “first element in the map” has no special significance.


CMapStringToOb::IsEmpty

BOOL IsEmpty( ) const;

Return Value

Nonzero if this map contains no elements; otherwise 0.

Remarks

Call this member function to determine whether the map is empty.

Example

See the example for RemoveAll.


CMapStringToOb::Lookup

BOOL Lookup( LPCTSTR key, CObject*& rValue ) const;

Return Value

Nonzero if the element was found; otherwise 0.

Parameters

key

Specifies the string key that identifies the element to be looked up.

rValue

Specifies the returned value from the looked-up element.

Remarks

Lookup uses a hashing algorithm to quickly find the map element with a key that matches exactly (CString value).

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CMapStringToOb::LookUp

CMapStringToOb map;
CAge* pa;

map.SetAt( "Bart", new CAge( 13 ) );
map.SetAt( "Lisa", new CAge( 11 ) );
map.SetAt( "Homer", new CAge( 36 ) );
map.SetAt( "Marge", new CAge( 35 ) );
ASSERT( map.Lookup( "Lisa", ( CObject*& ) pa ) ); // Is "Lisa" in the map?
ASSERT( *pa ==  CAge( 11 ) ); // Is she 11?

CMapStringToOb Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::operator []


CMapStringToOb::RemoveAll

void RemoveAll( );

Remarks

Removes all the elements from this map and destroys the CString key objects. The CObject objects referenced by each key are not destroyed. The RemoveAll function can cause memory leaks if you do not ensure that the referenced CObject objects are destroyed.

The function works correctly if the map is already empty.

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CMapStringToOb::RemoveAll
{
   CMapStringToOb map;

   CAge age1( 13 ); // Two objects on the stack
   CAge age2( 36 );
   map.SetAt( "Bart", &age1 );
   map.SetAt( "Homer", &age2 );
   ASSERT( map.GetCount() == 2 );
   map.RemoveAll(); // CObject pointers removed; objects not removed.
   ASSERT( map.GetCount() == 0 );
   ASSERT( map.IsEmpty() );
} // The two CAge objects are deleted when they go out of scope.

CMapStringToOb Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::RemoveKey


CMapStringToOb::RemoveKey

BOOL RemoveKey( LPCTSTR key );

Return Value

Nonzero if the entry was found and successfully removed; otherwise 0.

Parameters

key

Specifies the string used for map lookup.

Remarks

Looks up the map entry corresponding to the supplied key; then, if the key is found, removes the entry. This can cause memory leaks if the CObject object is not deleted elsewhere.

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CMapStringToOb::RemoveKey
   CMapStringToOb map;

   map.SetAt( "Bart", new CAge( 13 ) );
   map.SetAt( "Lisa", new CAge( 11 ) );
   map.SetAt( "Homer", new CAge( 36 ) );
   map.SetAt( "Marge", new CAge( 35 ) );
   map.RemoveKey( "Lisa" ); // Memory leak: CAge object not
                            // deleted.
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "RemoveKey example: " << &map << "\n";
#endif

The results from this program are as follows:

RemoveKey example: A CMapStringToOb with 3 elements
    [Marge] = a CAge at $49A0 35
    [Homer] = a CAge at $495E 36
    [Bart] = a CAge at $4634 13

CMapStringToOb Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::RemoveAll


CMapStringToOb::SetAt

void SetAt( LPCTSTR key, CObject* newValue );
throw( CMemoryException );

Parameters

key

Specifies the string that is the key of the new element.

newValue

Specifies the CObject pointer that is the value of the new element.

Remarks

The primary means to insert an element in a map. First, the key is looked up. If the key is found, then the corresponding value is changed; otherwise a new key-value element is created.

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CMapStringToOb::SetAt
   CMapStringToOb map;
   CAge* pa;

   map.SetAt( "Bart", new CAge( 13 ) );
   map.SetAt( "Lisa", new CAge( 11 ) ); // Map contains 2
                                        // elements.
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "before Lisa's birthday: " << &map << "\n";
#endif
   if( map.Lookup( "Lisa", (CObject *&)pa ) )
   { // CAge 12 pointer replaces CAge 11 pointer.
      map.SetAt( "Lisa", new CAge( 12 ) );
      delete pa;  // Must delete CAge 11 to avoid memory leak.
   }
#ifdef _DEBUG
   afxDump << "after Lisa's birthday: " << &map << "\n";
#endif

The results from this program are as follows:

before Lisa's birthday: A CMapStringToOb with 2 elements
    [Lisa] = a CAge at $493C 11
    [Bart] = a CAge at $4654 13
after Lisa's birthday: A CMapStringToOb with 2 elements
    [Lisa] = a CAge at $49C0 12
    [Bart] = a CAge at $4654 13

CMapStringToOb Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::Lookup, CMapStringToOb::operator []


CMapStringToOb::operator [ ]

CObject*& operator [ ]( LPCTSTR key );

Return Value

A reference to a pointer to a CObject object; or NULL if the map is empty or key is out of range.

Remarks

This operator is a convenient substitute for the SetAt member function. Thus it can be used only on the left side of an assignment statement (an l-value). If there is no map element with the specified key, then a new element is created.

There is no “right side” (r-value) equivalent to this operator because there is a possibility that a key may not be found in the map. Use the Lookup member function for element retrieval.

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CMapStringToOb::operator[]
   CMapStringToOb map;

   map["Bart"] = new CAge( 13 );
   map["Lisa"] = new CAge( 11 );
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "Operator [] example: " << &map << "\n";
#endif

The results from this program are as follows:

Operator [] example: A CMapStringToOb with 2 elements
    [Lisa] = a CAge at $4A02 11
    [Bart] = a CAge at $497E 13

CMapStringToOb Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::SetAt, CMapStringToOb::Lookup


CMapStringToPtr

The CMapStringToPtr class supports maps of void pointers keyed by CString objects.

The member functions of CMapStringToPtr are similar to the member functions of class CMapStringToOb. Because of this similarity, you can use the CMapStringToOb reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a pointer to void.

BOOL CMapStringToOb::Lookup( const char* <key>,
                             CObject*& <rValue> ) const;

for example, translates to

BOOL CMapStringToPtr::Lookup( LPCTSTR <key>, void*& <rValue> )
                              const;

CMapStringToPtr incorporates the IMPLEMENT_DYNAMIC macro to support run-time type access and dumping to a CDumpContext object. If you need a dump of individual map elements, you must set the depth of the dump context to 1 or greater.

String-to-pointer maps may not be serialized.

When a CMapStringToPtr object is deleted, or when its elements are removed, the CString key objects and the words are removed.

#include <afxcoll.h>


CMapStringToPtr Class Members

Construction

CMapStringToPtr Constructs a collection that maps CString objects to void pointers.

Operations

Lookup | Returns a void pointer based on a CString value.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.
operator [] | Inserts an element into the map — operator substitution for SetAt.
RemoveKey | Removes an element specified by a key.
RemoveAll | Removes all the elements from this map.
GetStartPosition | Returns the position of the first element.
GetNextAssoc | Gets the next element for iterating.

Status

GetCount | Returns the number of elements in this map.
IsEmpty | Tests for the empty-map condition (no elements).


CMapStringToString

The CMapStringToString class supports maps of CString objects keyed by CString objects.

The member functions of CMapStringToString are similar to the member functions of class CMapStringToOb. Because of this similarity, you can use the CMapStringToOb reference documentation for member function specifics. Wherever you see a CObject pointer as a return value or “output” function parameter, substitute a pointer to char. Wherever you see a CObject pointer as an “input” function parameter, substitute a pointer to char.

BOOL CMapStringToOb::Lookup( const char* <key>,
                             CObject*& <rValue> ) const;

for example, translates to

BOOL CMapStringToString::Lookup( LPCTSTR <key>,
                                 CString& <rValue> ) const;

CMapStringToString incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. Each element is serialized in turn if a map is stored to an archive, either with the overloaded insertion (<<) operator or with the Serialize member function.

If you need a dump of individual CString-CString elements, you must set the depth of the dump context to 1 or greater.

When a CMapStringToString object is deleted, or when its elements are removed, the CString objects are removed as appropriate.

For more information on CMapStringToString, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample COLLECT


CMapStringToString Class Members

Construction

CMapStringToString Constructs a collection that maps CString objects to CString objects.

Operations

Lookup | Returns a CString using a CString value as a key.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.
operator [] | Inserts an element into the map — operator substitution for SetAt.
RemoveKey | Removes an element specified by a key.
RemoveAll | Removes all the elements from this map.
GetStartPosition | Returns the position of the first element.
GetNextAssoc | Gets the next element for iterating.

Status

GetCount | Returns the number of elements in this map.
IsEmpty | Tests for the empty-map condition (no elements).


CMapWordToOb

The CMapWordToOb class supports maps of CObject pointers keyed by 16-bit words.

The member functions of CMapWordToOb are similar to the member functions of class CMapStringToOb. Because of this similarity, you can use the CMapStringToOb reference documentation for member function specifics. Wherever you see a CString or a const pointer to char as a function parameter or return value, substitute WORD.

BOOL CMapStringToOb::Lookup( const char* <key>,
                             CObject*& <rValue> ) const;

for example, translates to

BOOL CMapWordToOb::Lookup( WORD <key>, CObject*& <rValue> ) const;

CMapWordToOb incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. Each element is serialized in turn if a map is stored to an archive, either with the overloaded insertion (<<) operator or with the Serialize member function.

If you need a dump of individual WORD-CObject elements, you must set the depth of the dump context to 1 or greater.

When a CMapWordToOb object is deleted, or when its elements are removed, the CObject objects are deleted as appropriate.

For more information on CMapWordToOb, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>


CMapWordToOb Class Members

Construction

CMapWordToOb Constructs a collection that maps words to CObject pointers.

Operations

Lookup | Returns a CObject pointer using a word value as a key.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.
operator [] | Inserts an element into the map — operator substitution for SetAt.
RemoveKey | Removes an element specified by a key.
RemoveAll | Removes all the elements from this map.
GetStartPosition | Returns the position of the first element.
GetNextAssoc | Gets the next element for iterating.

Status

GetCount | Returns the number of elements in this map.
IsEmpty | Tests for the empty-map condition (no elements).


CMapWordToPtr

The CMapWordToPtr class supports maps of void pointers keyed by 16-bit words.

The member functions of CMapWordToPtr are similar to the member functions of class CMapStringToOb. Because of this similarity, you can use the CMapStringToOb reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a pointer to void. Wherever you see a CString or a const pointer to char as a function parameter or return value, substitute WORD.

BOOL CMapStringToOb::Lookup( const char* <key>,
                             CObject*& <rValue> ) const;

for example, translates to

BOOL CMapWordToPtr::Lookup( WORD <key>, void*& <rValue> ) const;

CMapWordToPtr incorporates the IMPLEMENT_DYNAMIC macro to support run-time type access and dumping to a CDumpContext object. If you need a dump of individual map elements, you must set the depth of the dump context to 1 or greater.

Word-to-pointer maps may not be serialized.

When a CMapWordToPtr object is deleted, or when its elements are removed, the words and the pointers are removed. The entities referenced by the pointers are not removed.

For more information on CMapWordToPtr, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>


CMapWordToPtr Class Members

Construction

CMapWordToPtr Constructs a collection that maps words to void pointers.

Operations

Lookup | Returns a void pointer using a word value as a key.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.
operator [] | Inserts an element into the map — operator substitution for SetAt.
RemoveKey | Removes an element specified by a key.
RemoveAll | Removes all the elements from this map.
GetStartPosition | Returns the position of the first element.
GetNextAssoc | Gets the next element for iterating.

Status

GetCount | Returns the number of elements in this map.
IsEmpty | Tests for the empty-map condition (no elements).


CMDIChildWnd

The CMDIChildWnd class provides the functionality of a Windows multiple document interface (MDI) child window, along with members for managing the window.

An MDI child window looks much like a typical frame window, except that the MDI child window appears inside an MDI frame window rather than on the desktop. An MDI child window does not have a menu bar of its own, but instead shares the menu of the MDI frame window. The framework automatically changes the MDI frame menu to represent the currently active MDI child window.

To create a useful MDI child window for your application, derive a class from CMDIChildWnd. Add member variables to the derived class to store data specific to your application. Implement message-handler member functions and a message map in the derived class to specify what happens when messages are directed to the window.

There are three ways to construct an MDI child window:

  • Directly construct it using Create.

  • Directly construct it using LoadFrame.

  • Indirectly construct it through a document template.

Before you call Create or LoadFrame, you must construct the frame-window object on the heap using the C++ new operator. Before calling Create you can also register a window class with the AfxRegisterWndClass global function to set the icon and class styles for the frame.

Use the Create member function to pass the frame’s creation parameters as immediate arguments.

LoadFrame requires fewer arguments than Create, and instead retrieves most of its default values from resources, including the frame’s caption, icon, accelerator table, and menu. To be accessible by LoadFrame, all these resources must have the same resource ID (for example, IDR_MAINFRAME).

When a CMDIChildWnd object contains views and documents, they are created indirectly by the framework instead of directly by the programmer. The CDocTemplate object orchestrates the creation of the frame, the creation of the containing views, and the connection of the views to the appropriate document. The parameters of the CDocTemplate constructor specify the CRuntimeClass of the three classes involved (document, frame, and view). A CRuntimeClass object is used by the framework to dynamically create new frames when specified by the user (for example, by using the File New command or the MDI Window New command).

A frame-window class derived from CMDIChildWnd must be declared with DECLARE_DYNCREATE in order for the above RUNTIME_CLASS mechanism to work correctly.

The CMDIChildWnd class inherits much of its default implementation from CFrameWnd. For a detailed list of these features, please refer to the CFrameWnd class description. The CMDIChildWnd class has the following additional features:

  • In conjunction with the CMultiDocTemplate class, multiple CMDIChildWnd objects from the same document template share the same menu, saving Windows system resources.

  • The currently active MDI child window menu entirely replaces the MDI frame window’s menu, and the caption of the currently active MDI child window is added to the MDI frame window’s caption. For further examples of MDI child window functions that are implemented in conjunction with an MDI frame window, see the CMDIFrameWnd class description.

Do not use the C++ delete operator to destroy a frame window. Use CWnd::DestroyWindow instead. The CFrameWnd implementation of PostNcDestroy will delete the C++ object when the window is destroyed. When the user closes the frame window, the default OnClose handler will call DestroyWindow.

For more information on CMDIChildWnd, see Frame Window Topics in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample MDI | MFC Sample MDIBIND | MFC Sample MDIDOCVW | MFC Sample SNAPVW

See Also CWnd, CMDIFrameWnd


CMDIChildWnd Class Members

Construction

CMDIChildWnd Constructs a CMDIChildWnd object.

Initialization

Create Creates the Windows MDI child window associated with the CMDIChildWnd object.

Operations

MDIDestroy | Destroys this MDI child window.
MDIActivate | Activates this MDI child window.
MDIMaximize | Maximizes this MDI child window.
MDIRestore | Restores this MDI child window from maximized or minimized size.
GetMDIFrame | Returns the parent MDI frame of the MDI client window.


CMDIChildWnd::CMDIChildWnd

CMDIChildWnd( );

Remarks

Call to construct a CMDIChildWnd object. Call Create to create the visible window.

CMDIChildWnd Overview | Class Members | Hierarchy Chart

See Also CMDIChildWnd::Create


CMDIChildWnd::Create

BOOL Create( LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_OVERLAPPEDWINDOW, const RECT& rect = rectDefault, CMDIFrameWnd* pParentWnd = NULL, CCreateContext* pContext = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszClassName

Points to a null-terminated character string that names the Windows class (a WNDCLASS structure). The class name can be any name registered with the AfxRegisterWndClass global function. Should be NULL for a standard CMDIChildWnd.

lpszWindowName

Points to a null-terminated character string that represents the window name. Used as text for the title bar.

dwStyle

Specifies the window style attributes. The WS_CHILD style is required.

rect

Contains the size and position of the window. The rectDefault value allows Windows to specify the size and position of the new CMDIChildWnd.

pParentWnd

Specifies the window’s parent. If NULL, the main application window is used.

pContext

Specifies a CCreateContext structure. This parameter can be NULL.

Remarks

Call this member function to create a Windows MDI child window and attach it to the CMDIChildWnd object.

The currently active MDI child frame window can determine the caption of the parent frame window. This feature is disabled by turning off the FWS_ADDTOTITLE style bit of the child frame window.

The framework calls this member function in response to a user command to create a child window, and the framework uses the pContext parameter to properly connect the child window to the application. When you call Create, pContext can be NULL.

CMDIChildWnd Overview | Class Members | Hierarchy Chart

See Also CMDIChildWnd::CMDIChildWnd, CWnd::PreCreateWindow


CMDIChildWnd::GetMDIFrame

CMDIFrameWnd* GetMDIFrame( );

Return Value

A pointer to the MDI parent frame window.

Remarks

Call this function to return the MDI parent frame. The frame returned is two parents removed from the CMDIChildWnd and is the parent of the window of type MDICLIENT that manages the CMDIChildWnd object. Call the GetParent member function to return the CMDIChildWnd object’s immediate MDICLIENT parent as a temporary CWnd pointer.

CMDIChildWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetParent


CMDIChildWnd::MDIActivate

void MDIActivate( );

Remarks

Call this member function to activate an MDI child window independently of the MDI frame window. When the frame becomes active, the child window that was last activated will be activated as well.

CMDIChildWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDIGetActive, CWnd::OnNcActivate, CMDIFrameWnd::MDINext, WM_MDIACTIVATE


CMDIChildWnd::MDIDestroy

void MDIDestroy( );

Remarks

Call this member function to destroy an MDI child window.

The member function removes the title of the child window from the frame window and deactivates the child window.

CMDIChildWnd Overview | Class Members | Hierarchy Chart

See Also WM_MDIDESTROY, CMDIChildWnd::Create


CMDIChildWnd::MDIMaximize

void MDIMaximize( );

Remarks

Call this member function to maximize an MDI child window. When a child window is maximized, Windows resizes it to make its client area fill the client area of the frame window. Windows places the child window’s Control menu in the frame’s menu bar so that the user can restore or close the child window and adds the title of the child window to the frame-window title.

CMDIChildWnd Overview | Class Members | Hierarchy Chart

See Also WM_MDIMAXIMIZE, CMDIChildWnd::MDIRestore


CMDIChildWnd::MDIRestore

void MDIRestore( );

Remarks

Call this member function to restore an MDI child window from maximized or minimized size.

CMDIChildWnd Overview | Class Members | Hierarchy Chart

See Also CMDIChildWnd::MDIMaximize, WM_MDIRESTORE


CMDIFrameWnd

The CMDIFrameWnd class provides the functionality of a Windows multiple document interface (MDI) frame window, along with members for managing the window.

To create a useful MDI frame window for your application, derive a class from CMDIFrameWnd. Add member variables to the derived class to store data specific to your application. Implement message-handler member functions and a message map in the derived class to specify what happens when messages are directed to the window.

You can construct an MDI frame window by calling the Create or LoadFrame member function of CFrameWnd.

Before you call Create or LoadFrame, you must construct the frame window object on the heap using the C++ new operator. Before calling Create you can also register a window class with the AfxRegisterWndClass global function to set the icon and class styles for the frame.

Use the Create member function to pass the frame’s creation parameters as immediate arguments.

LoadFrame requires fewer arguments than Create, and instead retrieves most of its default values from resources, including the frame’s caption, icon, accelerator table, and menu. To be accessed by LoadFrame, all these resources must have the same resource ID (for example, IDR_MAINFRAME).

Though MDIFrameWnd is derived from CFrameWnd, a frame window class derived from CMDIFrameWnd need not be declared with DECLARE_DYNCREATE.

The CMDIFrameWnd class inherits much of its default implementation from CFrameWnd. For a detailed list of these features, refer to the CFrameWnd class description. The CMDIFrameWnd class has the following additional features:

  • An MDI frame window manages the MDICLIENT window, repositioning it in conjunction with control bars. The MDI client window is the direct parent of MDI child frame windows. The WS_HSCROLL and WS_VSCROLL window styles specified on a CMDIFrameWnd apply to the MDI client window rather than the main frame window so the user can scroll the MDI client area (as in the Windows Program Manager, for example).

  • An MDI frame window owns a default menu that is used as the menu bar when there is no active MDI child window. When there is an active MDI child, the MDI frame window’s menu bar is automatically replaced by the MDI child window menu.

  • An MDI frame window works in conjunction with the current MDI child window, if there is one. For instance, command messages are delegated to the currently active MDI child before the MDI frame window.

  • An MDI frame window has default handlers for the following standard Window menu commands:
    • ID_WINDOW_TILE_VERT

    • ID_WINDOW_TILE_HORZ

    • ID_WINDOW_CASCADE

    • ID_WINDOW_ARRANGE
  • An MDI frame window also has an implementation of ID_WINDOW_NEW, which creates a new frame and view on the current document. An application can override these default command implementations to customize MDI window handling.

Do not use the C++ delete operator to destroy a frame window. Use CWnd::DestroyWindow instead. The CFrameWnd implementation of PostNcDestroy will delete the C++ object when the window is destroyed. When the user closes the frame window, the default OnClose handler will call DestroyWindow.

For more information on CMDIFrameWnd, see Frame Window Topics in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample MDI | MFC Sample MDIDOCVW | MFC Sample SNAPVW

See Also CWnd, CMDIChildWnd


CMDIFrameWnd Class Members

Construction

CMDIFrameWnd Constructs a CMDIFrameWnd.

Operations

MDIActivate | Activates a different MDI child window.
MDIGetActive | Retrieves the currently active MDI child window, along with a flag indicating whether or not the child is maximized.
MDIIconArrange | Arranges all minimized document child windows.
MDIMaximize | Maximizes an MDI child window.
MDINext | Activates the child window immediately behind the currently active child window and places the currently active child window behind all other child windows.
MDIRestore | Restores an MDI child window from maximized or minimized size.
MDISetMenu | Replaces the menu of an MDI frame window, the Window pop-up menu, or both.
MDITile | Arranges all child windows in a tiled format.
MDICascade | Arranges all child windows in a cascaded format.

Overridables

CreateClient | Creates a Windows MDICLIENT window for this CMDIFrameWnd. Called by the OnCreate member function of CWnd.
GetWindowMenuPopup | Returns the Window pop-up menu.


CMDIFrameWnd::CMDIFrameWnd

CMDIFrameWnd( );

Remarks

Call this member function to construct a CMDIFrameWnd object. Call the Create or LoadFrame member function to create the visible MDI frame window.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::Create, CFrameWnd::LoadFrame


CMDIFrameWnd::CreateClient

virtual BOOL CreateClient( LPCREATESTRUCT lpCreateStruct, CMenu* pWindowMenu );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpCreateStruct

A long pointer to a CREATESTRUCT structure.

pWindowMenu

A pointer to the Window pop-up menu.

Remarks

Creates the MDI client window that manages the CMDIChildWnd objects.

This member function should be called if you override the OnCreate member function directly.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::CMDIFrameWnd


CMDIFrameWnd::GetWindowMenuPopup

virtual HMENU GetWindowMenuPopup( HMENU hMenuBar );

Return Value

The Window pop-up menu if one exists; otherwise NULL.

Parameters

hMenuBar

The current menu bar.

Remarks

Call this member function to obtain a handle to the current pop-up menu named “Window” (the pop-up menu with menu items for MDI window management).

The default implementation looks for a pop-up menu containing standard Window menu commands such as ID_WINDOW_NEW and ID_WINDOW_TILE_HORZ.

Override this member function if you have a Window menu that does not use the standard menu command IDs.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDIGetActive


CMDIFrameWnd::MDIActivate

void MDIActivate( CWnd* pWndActivate );

Parameters

pWndActivate

Points to the MDI child window to be activated.

Remarks

Call this member function to activate a different MDI child window. This member function sends the WM_MDIACTIVATE message to both the child window being activated and the child window being deactivated.

This is the same message that is sent if the user changes the focus to an MDI child window by using the mouse or keyboard.

Note An MDI child window is activated independently of the MDI frame window. When the frame becomes active, the child window that was last activated is sent a WM_NCACTIVATE message to draw an active window frame and caption bar, but it does not receive another WM_MDIACTIVATE message.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDIGetActive, CMDIFrameWnd::MDINext, WM_ACTIVATE, WM_NCACTIVATE


CMDIFrameWnd::MDICascade

void MDICascade( );

void MDICascade( int nType );

Parameters

nType

Specifies a cascade flag. Only the following flag can be specified: MDITILE_SKIPDISABLED, which prevents disabled MDI child windows from being cascaded.

Remarks

Call this member function to arrange all the MDI child windows in a cascade format.

The first version of MDICascade, with no parameters, cascades all MDI child windows, including disabled ones. The second version optionally does not cascade disabled MDI child windows if you specify MDITILE_SKIPDISABLED for the nType parameter.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDIIconArrange, CMDIFrameWnd::MDITile, WM_MDICASCADE


CMDIFrameWnd::MDIGetActive

CMDIChildWnd* MDIGetActive( BOOL* pbMaximized = NULL ) const;

Return Value

A pointer to the active MDI child window.

Parameters

pbMaximized

A pointer to a BOOL return value. Set to TRUE on return if the window is maximized; otherwise FALSE.

Remarks

Retrieves the current active MDI child window, along with a flag indicating whether the child window is maximized.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDIActivate, WM_MDIGETACTIVE


CMDIFrameWnd::MDIIconArrange

void MDIIconArrange( );

Remarks

Arranges all minimized document child windows. It does not affect child windows that are not minimized.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDICascade, CMDIFrameWnd::MDITile, WM_MDIICONARRANGE


CMDIFrameWnd::MDIMaximize

void MDIMaximize( CWnd* pWnd );

Parameters

pWnd

Points to the window to maximize.

Remarks

Call this member function to maximize the specified MDI child window. When a child window is maximized, Windows resizes it to make its client area fill the client window. Windows places the child window’s Control menu in the frame’s menu bar so the user can restore or close the child window. It also adds the title of the child window to the frame-window title.

If another MDI child window is activated when the currently active MDI child window is maximized, Windows restores the currently active child and maximizes the newly activated child window.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also WM_MDIMAXIMIZE, CMDIFrameWnd::MDIRestore


CMDIFrameWnd::MDINext

void MDINext( );

Remarks

Activates the child window immediately behind the currently active child window and places the currently active child window behind all other child windows.

If the currently active MDI child window is maximized, the member function restores the currently active child and maximizes the newly activated child.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDIActivate, CMDIFrameWnd::MDIGetActive, WM_MDINEXT


CMDIFrameWnd::MDIRestore

void MDIRestore( CWnd* pWnd );

Parameters

pWnd

Points to the window to restore.

Remarks

Restores an MDI child window from maximized or minimized size.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDIMaximize, WM_MDIRESTORE


CMDIFrameWnd::MDISetMenu

CMenu* MDISetMenu( CMenu* pFrameMenu, CMenu* pWindowMenu );

Return Value

A pointer to the frame-window menu replaced by this message. The pointer may be temporary and should not be stored for later use.

Parameters

pFrameMenu

Specifies the menu of the new frame-window menu. If NULL, the menu is not changed.

pWindowMenu

Specifies the menu of the new Window pop-up menu. If NULL, the menu is not changed.

Remarks

Call this member function to replace the menu of an MDI frame window, the Window pop-up menu, or both.

After calling MDISetMenu, an application must call the DrawMenuBar member function of CWnd to update the menu bar.

If this call replaces the Window pop-up menu, MDI child-window menu items are removed from the previous Window menu and added to the new Window pop-up menu.

If an MDI child window is maximized and this call replaces the MDI frame-window menu, the Control menu and restore controls are removed from the previous frame-window menu and added to the new menu.

Do not call this member function if you use the framework to manage your MDI child windows.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DrawMenuBar, WM_MDISETMENU


CMDIFrameWnd::MDITile

void MDITile( );

void MDITile( int nType );

Parameters

nType

Specifies a tiling flag. This parameter can be any one of the following flags:

  • MDITILE_HORIZONTAL Tiles MDI child windows so that one window appears above another.

  • MDITILE_SKIPDISABLED Prevents disabled MDI child windows from being tiled.

  • MDITILE_VERTICAL Tiles MDI child windows so that one window appears beside another.

Remarks

Call this member function to arrange all child windows in a tiled format.

The first version of MDITile, without parameters, tiles the windows vertically under Windows versions 3.1 and later. The second version tiles windows vertically or horizontally, depending on the value of the nType parameter.

CMDIFrameWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDICascade, CMDIFrameWnd::MDIIconArrange, WM_MDITILE


CMemFile

CMemFile is the CFile-derived class that supports memory files. These memory files behave like disk files except that the file is stored in RAM rather than on disk. A memory file is useful for fast temporary storage or for transferring raw bytes or serialized objects between independent processes.

CMemFile objects can automatically allocate their own memory or you can attach your own memory block to the CMemFile object by calling Attach. In either case, memory for growing the memory file automatically is allocated in nGrowBytes-sized increments if nGrowBytes is not zero.

The memory block will automatically be deleted upon destruction of the CMemFile object if the memory was originally allocated by the CMemFile object; otherwise, you are responsible for deallocating the memory you attached to the object.

You can access the memory block through the pointer supplied when you detach it from the CMemFile object by calling Detach.

The most common use of CMemFile is to create a CMemFile object and use it by calling CFile member functions. Note that creating a CMemFile automatically opens it: you do not call CFile::Open, which is only used for disk files. Because CMemFile doesn't use a disk file, the data member CFile::m_hFile is not used and has no meaning.

The CFile member functions Duplicate, LockRange, and UnlockRange are not implemented for CMemFile. If you call these functions on a CMemFile object, you will get a CNotSupportedException.

CMemFile uses the run-time library functions malloc, realloc, and free to allocate, reallocate, and deallocate memory; and the intrinsic memcpy to block copy memory when reading and writing. If you’d like to change this behavior or the behavior when CMemFile grows a file, derive your own class from CMemFile and override the appropriate functions.

For more information on CMemFile, see the articles Files in MFC and Memory Management Topics (MFC) in the Visual C++ Programmer's Guide and see File Handling in the Run-Time Library Reference.

#include <afx.h>


CMemFile Class Members

Construction

CMemFile Constructs a memory file object.

Operations

Attach | Attaches a block of memory to CMemFile.
Detach | Detaches the block of memory from CMemFile and returns a pointer to the block of memory detached.

Advanced Overridables

Alloc | Override to modify memory allocation behavior.
Free | Override to modify memory deallocation behavior.
Realloc | Override to modify memory reallocation behavior.
Memcpy | Override to modify memory copy behavior when reading and writing files.
GrowFile | Override to modify behavior when growing a file.


CMemFile::Alloc

BYTE * Alloc( DWORD nBytes );

Return Value

A pointer to the memory block that was allocated, or NULL if the allocation failed.

Parameters

nBytes

Number of bytes of memory to be allocated.

Remarks

This function is called by CMemFile member functions. Override this function to implement custom memory allocation. If you override this function, you'll probably want to override Free and Realloc as well.

The default implementation uses the run-time library function malloc to allocate memory.

CMemFile Overview | Class Members | Hierarchy Chart

See Also CMemFile::Free, CMemFile::Realloc, malloc


CMemFile::Attach

void Attach( BYTE* lpBuffer, UINT nBufferSize, UINT nGrowBytes = 0 );

Parameters

lpBuffer

Pointer to the buffer to be attached to CMemFile.

nBufferSize

An integer that specifies the size of the buffer in bytes.

nGrowBytes

The memory allocation increment in bytes.

Remarks

Call this function to attach a block of memory to CMemFile. This causes CMemFile to use the block of memory as the memory file.

If nGrowBytes is 0, CMemFile will set the file length to nBufferSize. This means that the data in the memory block before it was attached to CMemFile will be used as the file. Memory files created in this manner cannot be grown.

Since the file cannot be grown, be careful not to cause CMemFile to attempt to grow the file. For example, don’t call the CMemFile overrides of CFile:Write to write past the end or don’t call CFile:SetLength with a length longer than nBufferSize.

If nGrowBytes is greater than 0, CMemFile will ignore the contents of the memory block you've attached. You'll have to write the contents of the memory file from scratch using the CMemFile override of CFile::Write. If you attempt to write past the end of the file or grow the file by calling the CMemFile override of CFile::SetLength, CMemFile will grow the memory allocation in increments of nGrowBytes. Growing the memory allocation will fail if the memory block you pass to Attach wasn't allocated with a method compatible with Alloc. To be compatible with the default implementation of Alloc, you must allocate the memory with the run-time library function malloc or calloc.

CMemFile Overview | Class Members | Hierarchy Chart

See Also CMemFile::CMemFile, CMemFile::Detach, CMemFile::Alloc, CFile::Write, CFile::SetLength


CMemFile::CMemFile

CMemFile( UINT nGrowBytes = 1024 );

CMemFile( BYTE* lpBuffer, UINT nBufferSize, UINT nGrowBytes = 0 );

Parameters

nGrowBytes

The memory allocation increment in bytes.

lpBuffer

Pointer to a buffer that receives information of the size nBufferSize.

nBufferSize

An integer that specifies the size of the file buffer, in bytes.

Remarks

The first overload opens an empty memory file. Note that the file is opened by the constructor and that you should not call CFile::Open.

The second overload acts the same as if you used the first constructor and immediately called Attach with the same parameters. See Attach for details.

Example

// example for CMemFile::CMemFile
CMemFile f; // Ready to use - no Open necessary.

BYTE * pBuf = (BYTE *)new char [1024];
CMemFile g( pBuf, 1024, 256 );
// same as CMemFile g; g.Attach( pBuf, 1024, 256 );

CMemFile Overview | Class Members | Hierarchy Chart

See Also CMemFile::Attach


CMemFile::Detach

BYTE * Detach( );

Return Value

A pointer to the memory block that contains the contents of the memory file.

Remarks

Call this function to get a pointer to the memory block being used by CMemFile.

Calling this function also closes the CMemFile. You can reattach the memory block to CMemFile by calling Attach. If you want to reattach the file and use the data in it, you should call CFile::GetLength to get the length of the file before calling Detach. Note that if you attach a memory block to CMemFile so that you can use its data (nGrowBytes == 0), then you won't be able to grow the memory file.

CMemFile Overview | Class Members | Hierarchy Chart

See Also CMemFile::Attach, CFile::GetLength


CMemFile::Free

void Free( BYTE * lpMem );

Parameters

lpMem

Pointer to the memory to be deallocated.

Remarks

This function is called by CMemFile member functions. Override this function to implement custom memory deallocation. If you override this function, you'll probably want to override Alloc and Realloc as well.

CMemFile Overview | Class Members | Hierarchy Chart

See Also CMemFile::Alloc, CMemFile::Realloc


CMemFile::GrowFile

void GrowFile( DWORD dwNewLen );

Parameters

dwNewLen

New size of the memory file.

Remarks

This function is called by several of the CMemFile member functions. You can override it if you want to change how CMemFile grows its file. The default implementation calls Realloc to grow an existing block (or Alloc to create a memory block), allocating memory in multiples of the nGrowBytes value specified in the constructor or Attach call.

CMemFile Overview | Class Members | Hierarchy Chart

See Also CMemFile::Alloc, CMemFile::Realloc, CMemFile::CMemFile, CMemFile::Attach


CMemFile::Memcpy

BYTE * Memcpy( BYTE* lpMemTarget, BYTE* lpMemSource, UINT nBytes );

Return Value

A copy of lpMemTarget.

Parameters

lpMemTarget

Pointer to the memory block into which the source memory will be copied.

lpMemSource

Pointer to the source memory block.

nBytes

Number of bytes to be copied.

Remarks

This function is called by the CMemFile overrides of CFile::Read and CFile::Write to transfer data to and from the memory file. Override this function if you want to change the way that CMemFile does these memory copies.

CMemFile Overview | Class Members | Hierarchy Chart

See Also CFile::Read, CFile::Write


CMemFile::Realloc

BYTE * Realloc( BYTE* lpMem, DWORD nBytes );

Return Value

A pointer to the memory block that was reallocated (and possibly moved), or NULL if the reallocation failed.

Parameters

lpMem

A pointer to the memory block to be reallocated.

nBytes

New size for the memory block.

Remarks

This function is called by CMemFile member functions. Override this function to implement custom memory reallocation. If you override this function, you'll probably want to override Alloc and Free as well.

CMemFile Overview | Class Members | Hierarchy Chart

See Also CMemFile::Alloc, CMemFile::Free


CMemoryException

A CMemoryException object represents an out-of-memory exception condition. No further qualification is necessary or possible. Memory exceptions are thrown automatically by new. If you write your own memory functions, using malloc, for example, then you are responsible for throwing memory exceptions.

For more information on CMemoryException, see the article Exceptions in Visual C++ Programmer’s Guide.

#include <afx.h>


CMemoryException Class Members

Construction

CMemoryException Constructs a CMemoryException object.


CMemoryException::CMemoryException

CMemoryException( );

Remarks

Constructs a CMemoryException object. Do not use this constructor directly, but rather call the global function AfxThrowMemoryException. This global function can succeed in an out-of-memory situation because it constructs the exception object in previously allocated memory. For more information about exception processing, see the article Exceptions in Visual C++ Programmer’s Guide.

CMemoryException Overview | Class Members | Hierarchy Chart

See Also Exception Processing


CMemoryState

CMemoryState does not have a base class.

CMemoryState provides a convenient way to detect memory leaks in your program. A “memory leak” occurs when memory for an object is allocated on the heap but not deallocated when it is no longer required. Such memory leaks can eventually lead to out-of-memory errors. There are several ways to allocate and deallocate memory in your program:

  • Using the malloc/free family of functions from the run-time library.

  • Using the Windows API memory management functions, LocalAlloc/LocalFree and GlobalAlloc/GlobalFree.

  • Using the C++ new and delete operators.

The CMemoryState diagnostics only help detect memory leaks caused when memory allocated using the new operator is not deallocated using delete. The other two groups of memory-management functions are for non-C++ programs, and mixing them with new and delete in the same program is not recommended. An additional macro, DEBUG_NEW, is provided to replace the new operator when you need file and line-number tracking of memory allocations. DEBUG_NEW is used whenever you would normally use the new operator.

As with other diagnostics, the CMemoryState diagnostics are only available in debug versions of your program. A debug version must have the _DEBUG constant defined.

If you suspect your program has a memory leak, you can use the Checkpoint, Difference, and DumpStatistics functions to discover the difference between the memory state (objects allocated) at two different points in program execution. This information can be useful in determining whether a function is cleaning up all the objects it allocates.

If simply knowing where the imbalance in allocation and deallocation occurs does not provide enough information, you can use the DumpAllObjectsSince function to dump all objects allocated since the previous call to Checkpoint. This dump shows the order of allocation, the source file and line where the object was allocated (if you are using DEBUG_NEW for allocation), and the derivation of the object, its address, and its size. DumpAllObjectsSince also calls each object’s Dump function to provide information about its current state.

For more information about how to use CMemoryState and other diagnostics, see MFC Debugging Support in Visual C++ Programmer’s Guide.

Note Declarations of objects of type CMemoryState and calls to member functions should be bracketed by #if defined(_DEBUG)/#endif directives. This causes memory diagnostics to be included only in debugging builds of your program.


CMemoryState Class Members

Construction

CMemoryState | Constructs a class-like structure that controls memory checkpoints.
Checkpoint | Obtains a snapshot or “checkpoint” of the current memory state.

Operations

Difference | Computes the difference between two objects of type CMemoryState.
DumpAllObjectsSince | Dumps a summary of all currently allocated objects since a previous checkpoint.
DumpStatistics | Prints memory allocation statistics for a CMemoryState object.


CMemoryState::Checkpoint

void Checkpoint( );

Remarks

Takes a snapshot summary of memory and stores it in this CMemoryState object. The CMemoryState member functions Difference and DumpAllObjectsSince use this snapshot data.

Example

See the example for the CMemoryState constructor.


CMemoryState::CMemoryState

CMemoryState( );

Remarks

Constructs an empty CMemoryState object that must be filled in by the Checkpoint or Difference member function.

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CMemoryState::CMemoryState
// Includes all CMemoryState functions
CMemoryState msOld, msNew, msDif;
msOld.Checkpoint();
CAge* page1 = new CAge( 21 );
CAge* page2 = new CAge( 22 );
msOld.DumpAllObjectsSince();
msNew.Checkpoint();
msDif.Difference( msOld, msNew );
msDif.DumpStatistics();

The results from this program are as follows:

Dumping objects ->
{2} a CObject at $190A
{1} a CObject at $18EA
Object dump complete.
0 bytes in 0 Free Blocks
8 bytes in 2 Object Blocks
0 bytes in 0 Non-Object Blocks
Largest number used: 8 bytes
Total allocations: 8 bytes


CMemoryState::Difference

BOOL Difference( const CMemoryState& oldState, const CMemoryState& newState );

Return Value

Nonzero if the two memory states are different; otherwise 0.

Parameters

oldState

The initial memory state as defined by a CMemoryState checkpoint.

newState

The new memory state as defined by a CMemoryState checkpoint.

Remarks

Compares two CMemoryState objects, then stores the difference into this CMemoryState object. Checkpoint must have been called for each of the two memory-state parameters.

Example

See the example for the CMemoryState constructor.


CMemoryState::DumpAllObjectsSince

void DumpAllObjectsSince( ) const;

Remarks

Calls the Dump function for all objects of a type derived from class CObject that were allocated (and are still allocated) since the last Checkpoint call for this CMemoryState object.

Calling DumpAllObjectsSince with an uninitialized CMemoryState object will dump out all objects currently in memory.

Example

See the example for the CMemoryState constructor.


CMemoryState::DumpStatistics

void DumpStatistics( ) const;

Remarks

Prints a concise memory statistics report from a CMemoryState object that is filled by the Difference member function. The report, which is printed on the afxDump device, shows the following:

  • Number of “object” blocks (blocks of memory allocated using CObject::operator new) still allocated on the heap.

  • Number of nonobject blocks still allocated on the heap.

  • The maximum memory used by the program at any one time (in bytes).

  • The total memory currently used by the program (in bytes).

A sample report looks like this:

0 bytes in 0 Free Blocks
8 bytes in 2 Object Blocks
0 bytes in 0 Non-Object Blocks
Largest number used: 8 bytes
Total allocations: 8 bytes
  • The first line describes the number of blocks whose deallocation was delayed if afxMemDF was set to delayFreeMemDF. For more information, see afxMemDF, in the “Macros and Globals” section.

  • The second line describes how many object blocks still remain allocated on the heap.

  • The third line describes how many nonobject blocks (arrays or structures allocated with new) were allocated on the heap and not deallocated.

  • The fourth line gives the maximum memory used by your program at any one time.

  • The last line lists the total amount of memory used by your program.

Example

See the example for the CMemoryState constructor.


CMenu

The CMenu class is an encapsulation of the Windows HMENU. It provides member functions for creating, tracking, updating, and destroying a menu.

Create a CMenu object on the stack frame as a local, then call CMenu’s member functions to manipulate the new menu as needed. Next, call CWnd::SetMenu to set the menu to a window, followed immediately by a call to the CMenu object’s Detach member function. The CWnd::SetMenu member function sets the window’s menu to the new menu, causes the window to be redrawn to reflect the menu change, and also passes ownership of the menu to the window. The call to Detach detaches the HMENU from the CMenu object, so that when the local CMenu variable passes out of scope, the CMenu object destructor does not attempt to destroy a menu it no longer owns. The menu itself is automatically destroyed when the window is destroyed.

You can use the LoadMenuIndirect member function to create a menu from a template in memory, but a menu created from a resource by a call to LoadMenu is more easily maintained, and the menu resource itself can be created and modified by the menu editor.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CTRLTEST | MFC Sample DYNAMENU

See Also CObject


CMenu Class Members

Data Members
Construction/Destruction
Initialization
Menu Operations
Menu Item Operations
Overridables

Data Members

m_hMenu Specifies the handle to the Windows menu attached to the CMenu object.

Construction

CMenu Constructs a CMenu object.

Initialization

Attach | Attaches a Windows menu handle to a CMenu object.
Detach | Detaches a Windows menu handle from a CMenu object and returns the handle.
FromHandle | Returns a pointer to a CMenu object given a Windows menu handle.
GetSafeHmenu | Returns the m_hMenu wrapped by this CMenu object.
DeleteTempMap | Deletes any temporary CMenu objects created by the FromHandle member function.
CreateMenu | Creates an empty menu and attaches it to a CMenu object.
CreatePopupMenu | Creates an empty pop-up menu and attaches it to a CMenu object.
LoadMenu | Loads a menu resource from the executable file and attaches it to a CMenu object.
LoadMenuIndirect | Loads a menu from a menu template in memory and attaches it to a CMenu object.
DestroyMenu | Destroys the menu attached to a CMenu object and frees any memory that the menu occupied.

Menu Operations

DeleteMenu | Deletes a specified item from the menu. If the menu item has an associated pop-up menu, destroys the handle to the pop-up menu and frees the memory used by it.
TrackPopupMenu | Displays a floating pop-up menu at the specified location and tracks the selection of items on the pop-up menu.

Menu Item Operations

AppendMenu | Appends a new item to the end of this menu.
CheckMenuItem | Places a check mark next to or removes a check mark from a menu item in the pop-up menu.
CheckMenuRadioItem | Places a radio button next to a menu item and removes the radio button from all of the other menu items in the group.
SetDefaultItem | Sets the default menu item for the specified menu.
GetDefaultItem | Determines the default menu item on the specified menu.
EnableMenuItem | Enables, disables, or dims (grays) a menu item.
GetMenuItemCount | Determines the number of items in a pop-up or top-level menu.
GetMenuItemID | Obtains the menu-item identifier for a menu item located at the specified position.
GetMenuState | Returns the status of the specified menu item or the number of items in a pop-up menu.
GetMenuString | Retrieves the label of the specified menu item.
GetMenuItemInfo | Retrieves information about a menu item.
GetSubMenu | Retrieves a pointer to a pop-up menu.
InsertMenu | Inserts a new menu item at the specified position, moving other items down the menu.
ModifyMenu | Changes an existing menu item at the specified position.
RemoveMenu | Deletes a menu item with an associated pop-up menu from the specified menu.
SetMenuItemBitmaps | Associates the specified check-mark bitmaps with a menu item.
GetMenuContextHelpId | Retrieves the help context ID associated with the menu.
SetMenuContextHelpId | Sets the help context ID to be associated with the menu.

Overridables

DrawItem | Called by the framework when a visual aspect of an owner-drawn menu changes.
MeasureItem | Called by the framework to determine menu dimensions when an owner-drawn menu is created.


CMenu::AppendMenu

BOOL AppendMenu( UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL );

BOOL AppendMenu( UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nFlags

Specifies information about the state of the new menu item when it is added to the menu. It consists of one or more of the values listed in the Remarks section.

nIDNewItem

Specifies either the command ID of the new menu item or, if nFlags is set to MF_POPUP, the menu handle (HMENU) of a pop-up menu. The nIDNewItem parameter is ignored (not needed) if nFlags is set to MF_SEPARATOR.

lpszNewItem

Specifies the content of the new menu item. The nFlags parameter is used to interpret lpszNewItem in the following way:

nFlags | Interpretation of lpszNewItem
MF_OWNERDRAW | Contains an application-supplied 32-bit value that the application can use to maintain additional data associated with the menu item. This 32-bit value is available to the application when it processes WM_MEASUREITEM and WM_DRAWITEM messages. The value is stored in the itemData member of the structure supplied with those messages.
MF_STRING | Contains a pointer to a null-terminated string. This is the default interpretation.
MF_SEPARATOR | The lpszNewItem parameter is ignored (not needed).

pBmp

Points to a CBitmap object that will be used as the menu item.

Remarks

Appends a new item to the end of a menu. The application can specify the state of the menu item by setting values in nFlags. When nIDNewItem specifies a pop-up menu, it becomes part of the menu to which it is appended. If that menu is destroyed, the appended menu will also be destroyed. An appended menu should be detached from a CMenu object to avoid conflict. Note that MF_STRING and MF_OWNERDRAW are not valid for the bitmap version of AppendMenu.

The following list describes the flags that may be set in nFlags:

  • MF_CHECKED Acts as a toggle with MF_UNCHECKED to place the default check mark next to the item. When the application supplies check-mark bitmaps (see the SetMenuItemBitmaps member function), the “check mark on” bitmap is displayed.

  • MF_UNCHECKED Acts as a toggle with MF_CHECKED to remove a check mark next to the item. When the application supplies check-mark bitmaps (see the SetMenuItemBitmaps member function), the “check mark off” bitmap is displayed.

  • MF_DISABLED Disables the menu item so that it cannot be selected but does not dim it.

  • MF_ENABLED Enables the menu item so that it can be selected and restores it from its dimmed state.

  • MF_GRAYED Disables the menu item so that it cannot be selected and dims it.

  • MF_MENUBARBREAK Places the item on a new line in static menus or in a new column in pop-up menus. The new pop-up menu column will be separated from the old column by a vertical dividing line.

  • MF_MENUBREAK Places the item on a new line in static menus or in a new column in pop-up menus. No dividing line is placed between the columns.

  • MF_OWNERDRAW Specifies that the item is an owner-draw item. When the menu is displayed for the first time, the window that owns the menu receives a WM_MEASUREITEM message, which retrieves the height and width of the menu item. The WM_DRAWITEM message is the one sent whenever the owner must update the visual appearance of the menu item. This option is not valid for a top-level menu item.

  • MF_POPUP Specifies that the menu item has a pop-up menu associated with it. The ID parameter specifies a handle to a pop-up menu that is to be associated with the item. This is used for adding either a top-level pop-up menu or a hierarchical pop-up menu to a pop-up menu item.

  • MF_SEPARATOR Draws a horizontal dividing line. Can only be used in a pop-up menu. This line cannot be dimmed, disabled, or highlighted. Other parameters are ignored.

  • MF_STRING Specifies that the menu item is a character string.

Each of the following groups lists flags that are mutually exclusive and cannot be used together:

  • MF_DISABLED, MF_ENABLED, and MF_GRAYED

  • MF_STRING, MF_OWNERDRAW, MF_SEPARATOR, and the bitmap version

  • MF_MENUBARBREAK and MF_MENUBREAK

  • MF_CHECKED and MF_UNCHECKED

Whenever a menu that resides in a window is changed (whether or not the window is displayed), the application should call CWnd::DrawMenuBar.

CMenu Overview | Class Members | Hierarchy Chart

See Also CWnd::DrawMenuBar, CMenu::InsertMenu, CMenu::RemoveMenu, CMenu::SetMenuItemBitmaps, CMenu::Detach, ::AppendMenu


CMenu::Attach

BOOL Attach( HMENU hMenu );

Return Value

Nonzero if the operation was successful; otherwise 0.

Parameters

hMenu

Specifies a handle to a Windows menu.

Remarks

Attaches an existing Windows menu to a CMenu object. This function should not be called if a menu is already attached to the CMenu object. The menu handle is stored in the m_hMenu data member.

If the menu you want to manipulate is already associated with a window, you can use the CWnd::GetMenu function to get a handle to the menu.

Example

CMenu mnu;
HMENU hmnu = pWnd->GetMenu( );
mnu.Attach( hmnu );
// Now you can manipulate the window's menu as a CMenu
// object...

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::Detach, CMenu::CMenu, CWnd::GetMenu


CMenu::CheckMenuItem

UINT CheckMenuItem( UINT nIDCheckItem, UINT nCheck );

Return Value

The previous state of the item: MF_CHECKED or MF_UNCHECKED, or 0xFFFFFFFF if the menu item did not exist.

Parameters

nIDCheckItem

Specifies the menu item to be checked, as determined by nCheck.

nCheck

Specifies how to check the menu item and how to determine the item’s position in the menu. The nCheck parameter can be a combination of MF_CHECKED or MF_UNCHECKED with MF_BYPOSITION or MF_BYCOMMAND flags. These flags can be combined by using the bitwise OR operator. They have the following meanings:

  • MF_BYCOMMAND Specifies that the parameter gives the command ID of the existing menu item. This is the default.

  • MF_BYPOSITION Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

  • MF_CHECKED Acts as a toggle with MF_UNCHECKED to place the default check mark next to the item.

  • MF_UNCHECKED Acts as a toggle with MF_CHECKED to remove a check mark next to the item.

Remarks

Adds check marks to or removes check marks from menu items in the pop-up menu. The nIDCheckItem parameter specifies the item to be modified.

The nIDCheckItem parameter may identify a pop-up menu item as well as a menu item. No special steps are required to check a pop-up menu item. Top-level menu items cannot be checked. A pop-up menu item must be checked by position since it does not have a menu-item identifier associated with it.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::GetMenuState, ::CheckMenuItem, CMenu::CheckMenuRadioItem


CMenu::CheckMenuRadioItem

BOOL CheckMenuRadioItem( UINT nIDFirst, UINT nIDLast, UINT nIDItem, UINT nFlags );

Return Value

Nonzero if successful; otherwise 0

Parameters

nIDFirst

Specifies (as an ID or offset, depending on the value of nFlags) the first menu item in the radio button group.

nIDLast

Specifies (as an ID or offset, depending on the value of nFlags) the last menu item in the radio button group.

nIDItem

Specifies (as an ID or offset, depending on the value of nFlags) the item in the group which will be checked with a radio button.

nFlags

Specifies interpretation of nIDFirst, nIDLast, and nIDItem in the following way:

nFlags | Interpretation
MF_BYCOMMAND | Specifies that the parameter gives the command ID of the existing menu item. This is the default if neither MF_BYCOMMAND nor MF_BYPOSITION is set.
MF_BYPOSITION | Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

Remarks

Checks a specified menu item and makes it a radio item. At the same time, the function unchecks all other menu items in the associated group and clears the radio-item type flag for those items. The checked item is displayed using a radio button (or bullet) bitmap instead of a check mark bitmap.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::CheckMenuItem, CMenu::GetMenuState, ::CheckMenuRadioItem


CMenu::CMenu

CMenu( );

Remarks

The menu is not created until you call one of the create or load member functions of CMenu:

  • CreateMenu

  • CreatePopupMenu

  • LoadMenu

  • LoadMenuIndirect

  • Attach

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::CreateMenu, CMenu::CreatePopupMenu, CMenu::LoadMenu, CMenu::LoadMenuIndirect, CMenu::Attach


CMenu::CreateMenu

BOOL CreateMenu( );

Return Value

Nonzero if the menu was created successfully; otherwise 0.

Remarks

Creates a menu and attaches it to the CMenu object.

The menu is initially empty. Menu items can be added by using the AppendMenu or InsertMenu member function.

If the menu is assigned to a window, it is automatically destroyed when the window is destroyed.

Before exiting, an application must free system resources associated with a menu if the menu is not assigned to a window. An application frees a menu by calling the DestroyMenu member function.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::CMenu, CMenu::DestroyMenu, CMenu::InsertMenu, CWnd::SetMenu, ::CreateMenu, CMenu::AppendMenu


CMenu::CreatePopupMenu

BOOL CreatePopupMenu( );

Return Value

Nonzero if the pop-up menu was successfully created; otherwise 0.

Remarks

Creates a pop-up menu and attaches it to the CMenu object.

The menu is initially empty. Menu items can be added by using the AppendMenu or InsertMenu member function. The application can add the pop-up menu to an existing menu or pop-up menu. The TrackPopupMenu member function may be used to display this menu as a floating pop-up menu and to track selections on the pop-up menu.

If the menu is assigned to a window, it is automatically destroyed when the window is destroyed. If the menu is added to an existing menu, it is automatically destroyed when that menu is destroyed.

Before exiting, an application must free system resources associated with a pop-up menu if the menu is not assigned to a window. An application frees a menu by calling the DestroyMenu member function.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::CreateMenu, CMenu::InsertMenu, CWnd::SetMenu, CMenu::TrackPopupMenu, ::CreatePopupMenu, CMenu::AppendMenu


CMenu::DeleteMenu

BOOL DeleteMenu( UINT nPosition, UINT nFlags );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nPosition

Specifies the menu item that is to be deleted, as determined by nFlags.

nFlags

Is used to interpret nPosition in the following way:

nFlags | Interpretation of nPosition
MF_BYCOMMAND | Specifies that the parameter gives the command ID of the existing menu item. This is the default if neither MF_BYCOMMAND nor MF_BYPOSITION is set.
MF_BYPOSITION | Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

Remarks

Deletes an item from the menu. If the menu item has an associated pop-up menu, DeleteMenu destroys the handle to the pop-up menu and frees the memory used by the pop-up menu.

Whenever a menu that resides in a window is changed (whether or not the window is displayed), the application must call CWnd::DrawMenuBar.

CMenu Overview | Class Members | Hierarchy Chart

See Also CWnd::DrawMenuBar, ::DeleteMenu


CMenu::DeleteTempMap

static void PASCAL DeleteTempMap( );

Remarks

Called automatically by the CWinApp idle-time handler, DeleteTempMap deletes any temporary CMenu objects created by the FromHandle member function. DeleteTempMap detaches the Windows menu object attached to a temporary CMenu object before deleting the CMenu object.


CMenu::DestroyMenu

BOOL DestroyMenu( );

Return Value

Nonzero if the menu is destroyed; otherwise 0.

Remarks

Destroys the menu and any Windows resources that were used. The menu is detached from the CMenu object before it is destroyed. The Windows DestroyMenu function is automatically called in the CMenu destructor.

CMenu Overview | Class Members | Hierarchy Chart

See Also ::DestroyMenu


CMenu::Detach

HMENU Detach( );

Return Value

The handle, of type HMENU, to a Windows menu, if successful; otherwise NULL.

Remarks

Detaches a Windows menu from a CMenu object and returns the handle. The m_hMenu data member is set to NULL.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::Attach


CMenu::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A pointer to a DRAWITEMSTRUCT structure that contains information about the type of drawing required.

Remarks

Called by the framework when a visual aspect of an owner-drawn menu changes. The itemAction member of the DRAWITEMSTRUCT structure defines the drawing action that is to be performed. Override this member function to implement drawing for an owner-draw CMenu object. The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before the termination of this member function.

See CWnd::OnDrawItem for a description of the DRAWITEMSTRUCT structure.


CMenu::EnableMenuItem

UINT EnableMenuItem( UINT nIDEnableItem, UINT nEnable );

Return Value

Previous state (MF_DISABLED, MF_ENABLED, or MF_GRAYED) or –1 if not valid.

Parameters

nIDEnableItem

Specifies the menu item to be enabled, as determined by nEnable. This parameter can specify pop-up menu items as well as standard menu items.

nEnable

Specifies the action to take. It can be a combination of MF_DISABLED, MF_ENABLED, or MF_GRAYED, with MF_BYCOMMAND or MF_BYPOSITION. These values can be combined by using the bitwise OR operator. These values have the following meanings:

  • MF_BYCOMMAND Specifies that the parameter gives the command ID of the existing menu item. This is the default.

  • MF_BYPOSITION Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

  • MF_DISABLED Disables the menu item so that it cannot be selected but does not dim it.

  • MF_ENABLED Enables the menu item so that it can be selected and restores it from its dimmed state.

  • MF_GRAYED Disables the menu item so that it cannot be selected and dims it.

Remarks

Enables, disables, or dims a menu item. The CreateMenu, InsertMenu, ModifyMenu, and LoadMenuIndirect member functions can also set the state (enabled, disabled, or dimmed) of a menu item.

Using the MF_BYPOSITION value requires an application to use the correct CMenu. If the CMenu of the menu bar is used, a top-level menu item (an item in the menu bar) is affected. To set the state of an item in a pop-up or nested pop-up menu by position, an application must specify the CMenu of the pop-up menu.

When an application specifies the MF_BYCOMMAND flag, Windows checks all pop-up menu items that are subordinate to the CMenu; therefore, unless duplicate menu items are present, using the CMenu of the menu bar is sufficient.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::GetMenuState, ::EnableMenuItem


CMenu::FromHandle

static CMenu* PASCAL FromHandle( HMENU hMenu );

Return Value

A pointer to a CMenu that may be temporary or permanent.

Parameters

hMenu

A Windows handle to a menu.

Remarks

Returns a pointer to a CMenu object given a Windows handle to a menu. If a CMenu object is not already attached to the Windows menu object, a temporary CMenu object is created and attached.

This temporary CMenu object is only valid until the next time the application has idle time in its event loop, at which time all temporary objects are deleted.


CMenu::GetDefaultItem

UINT GetDefaultItem( UINT gmdiFlags, BOOL fByPos = FALSE );

Return Value

If the function succeeds, the return value is the identifier or position of the menu item. If the function fails, the return value is - 1.

Parameters

gmdiFlags

Value specifying how the function searches for menu items. This parameter can be none, one, or a combination of the following values:

Value | Meaning
GMDI_GOINTOPOPUPS | Specifies that, if the default item is one that opens a submenu, the function is to search in the corresponding submenu recursively. If the submenu has no default item, the return value identifies the item that opens the submenu. By default, the function returns the first default item on the specified menu, regardless of whether it is an item that opens a submenu.
GMDI_USEDISABLED | Specifies that the function is to return a default item, even if it is disabled. By default, the function skips disabled or grayed items.

fByPos

Value specifying whether to retrieve the menu item’s identifier or its position. If this parameter is FALSE, the identifier is returned. Otherwise, the position is returned.

Remarks

This member function implements the behavior of the Win32 function GetMenuDefaultItem, as described in the Platform SDK.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::SetDefaultItem


CMenu::GetMenuContextHelpId

DWORD GetMenuContextHelpId( ) const;

Return Value

The context help ID currently associated with CMenu if it has one; zero otherwise.

Remarks

Call this function to retrieve the context help ID associated with CMenu.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::SetMenuContextHelpID, ::GetMenuContextHelpId


CMenu::GetMenuItemCount

UINT GetMenuItemCount( ) const;

Return Value

The number of items in the menu if the function is successful; otherwise –1.

Remarks

Determines the number of items in a pop-up or top-level menu.

CMenu Overview | Class Members | Hierarchy Chart

See Also CWnd::GetMenu, CMenu::GetMenuItemID, CMenu::GetSubMenu, ::GetMenuItemCount


CMenu::GetMenuItemID

UINT GetMenuItemID( int nPos ) const;

Return Value

The item ID for the specified item in a pop-up menu if the function is successful. If the specified item is a pop-up menu (as opposed to an item within the pop-up menu), the return value is –1. If nPos corresponds to a SEPARATOR menu item, the return value is 0.

Parameters

nPos

Specifies the position (zero-based) of the menu item whose ID is being retrieved.

Remarks

Obtains the menu-item identifier for a menu item located at the position defined by nPos.

CMenu Overview | Class Members | Hierarchy Chart

See Also CWnd::GetMenu, CMenu::GetMenuItemCount, CMenu::GetSubMenu, ::GetMenuItemID


CMenu::GetMenuItemInfo

BOOL CMenu::GetMenuItemInfo( UINT nIDItem, LPMENUITEMINFO lpMenuItemInfo, BOOL ByPos = FALSE );

Return Value

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, use the Win32 function GetLastError, as described in the Platform SDK.

Parameters

nIDItem

Identifier or position of the menu item to get information about. The meaning of this parameter depends on the value of ByPos.

lpMenuItemInfo

A pointer to a MENUITEMINFO, as described in the Platform SDK, that contains information about the menu.

ByPos

Value specifying the meaning of nIDItem. By default, ByPos is FALSE, which indicates that uItem is a menu item identifier. If ByPos is not set to FALSE, it indicates a menu item position.

Remarks

This member function implements the behavior of the of the Win32 function GetMenuItemInfo, as described in the Platform SDK.

Note that in the MFC implementation of GetMenuItemInfo, you do not use a handle to a menu.

CMenu Overview | Class Members | Hierarchy Chart

See Also CWnd::GetMenu, CMenu::GetMenuItemCount, CMenu::GetMenuItemID


CMenu::GetMenuState

UINT GetMenuState( UINT nID, UINT nFlags ) const;

Return Value

The value 0xFFFFFFFF if the specified item does not exist. If nId identifies a pop-up menu, the high-order byte contains the number of items in the pop-up menu and the low-order byte contains the menu flags associated with the pop-up menu. Otherwise the return value is a mask (Boolean OR) of the values from the following list (this mask describes the status of the menu item that nId identifies):

  • MF_CHECKED Acts as a toggle with MF_UNCHECKED to place the default check mark next to the item. When the application supplies check-mark bitmaps (see the SetMenuItemBitmaps member function), the “check mark on” bitmap is displayed.

  • MF_DISABLED Disables the menu item so that it cannot be selected but does not dim it.

  • MF_ENABLED Enables the menu item so that it can be selected and restores it from its dimmed state. Note that the value of this constant is 0; an application should not test against 0 for failure when using this value.

  • MF_GRAYED Disables the menu item so that it cannot be selected and dims it.

  • MF_MENUBARBREAK Places the item on a new line in static menus or in a new column in pop-up menus. The new pop-up menu column will be separated from the old column by a vertical dividing line.

  • MF_MENUBREAK Places the item on a new line in static menus or in a new column in pop-up menus. No dividing line is placed between the columns.

  • MF_SEPARATOR Draws a horizontal dividing line. Can only be used in a pop-up menu. This line cannot be dimmed, disabled, or highlighted. Other parameters are ignored.

  • MF_UNCHECKED Acts as a toggle with MF_CHECKED to remove a check mark next to the item. When the application supplies check-mark bitmaps (see the SetMenuItemBitmaps member function), the “check mark off” bitmap is displayed. Note that the value of this constant is 0; an application should not test against 0 for failure when using this value.

Parameters

nID

Specifies the menu item ID, as determined by nFlags.

nFlags

Specifies the nature of nID. It can be one of the following values:

  • MF_BYCOMMAND Specifies that the parameter gives the command ID of the existing menu item. This is the default.

  • MF_BYPOSITION Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

Remarks

Returns the status of the specified menu item or the number of items in a pop-up menu.

CMenu Overview | Class Members | Hierarchy Chart

See Also ::GetMenuState, CMenu::CheckMenuItem, CMenu::EnableMenuItem


CMenu::GetMenuString

int GetMenuString( UINT nIDItem, LPTSTR lpString, int nMaxCount, UINT nFlags ) const;

int GetMenuString( UINT nIDItem, CString& rString, UINT nFlags ) const;

Return Value

Specifies the actual number of bytes copied to the buffer, not including the null terminator.

Parameters

nIDItem

Specifies the integer identifier of the menu item or the offset of the menu item in the menu, depending on the value of nFlags.

lpString

Points to the buffer that is to receive the label.

rString

A reference to a CString object that is to receive the copied menu string.

nMaxCount

Specifies the maximum length (in bytes) of the label to be copied. If the label is longer than the maximum specified in nMaxCount, the extra characters are truncated.

nFlags

Specifies the interpretation of the nIDItem parameter. It can be one of the following values:

nFlags | Interpretation of nIDItem
MF_BYCOMMAND | Specifies that the parameter gives the command ID of the existing menu item. This is the default if neither MF_BYCOMMAND nor MF_BYPOSITION is set.
MF_BYPOSITION | Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

Remarks

Copies the label of the specified menu item to the specified buffer.

The nMaxCount parameter should be one larger than the number of characters in the label to accommodate the null character that terminates a string.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::GetMenuState, CMenu::ModifyMenu, ::GetMenuString


CMenu::GetSubMenu

CMenu* GetSubMenu( int nPos ) const;

Return Value

A pointer to a CMenu object whose m_hMenu member contains a handle to the pop-up menu if a pop-up menu exists at the given position; otherwise NULL. If a CMenu object does not exist, then a temporary one is created. The CMenu pointer returned should not be stored.

Parameters

nPos

Specifies the position of the pop-up menu contained in the menu. Position values start at 0 for the first menu item. The pop-up menu’s identifier cannot be used in this function.

Remarks

Retrieves the CMenu object of a pop-up menu.

CMenu Overview | Class Members | Hierarchy Chart

See Also CWnd::GetMenu, CMenu::GetMenuItemID, ::GetMenuString


CMenu::GetSafeHmenu

HMENU GetSafeHmenu( ) const;

Remarks

Returns the HMENU wrapped by this CMenu object, or a NULL CMenu pointer.

CMenu Overview | Class Members | Hierarchy Chart

See Also ::GetSubMenu


CMenu::InsertMenu

BOOL InsertMenu( UINT nPosition, UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL );

BOOL InsertMenu( UINT nPosition, UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nPosition

Specifies the menu item before which the new menu item is to be inserted. The nFlags parameter can be used to interpret nPosition in the following ways:

nFlags | Interpretation of nPosition
MF_BYCOMMAND | Specifies that the parameter gives the command ID of the existing menu item. This is the default if neither MF_BYCOMMAND nor MF_BYPOSITION is set.
MF_BYPOSITION | Specifies that the parameter gives the position of the existing menu item. The first item is at position 0. If nPosition is –1, the new menu item is appended to the end of the menu.

nFlags

Specifies how nPosition is interpreted and specifies information about the state of the new menu item when it is added to the menu. For a list of the flags that may be set, see the AppendMenu member function. To specify more than one value, use the bitwise OR operator to combine them with the MF_BYCOMMAND or MF_BYPOSITION flag.

nIDNewItem

Specifies either the command ID of the new menu item or, if nFlags is set to MF_POPUP, the menu handle (HMENU) of the pop-up menu. The nIDNewItem parameter is ignored (not needed) if nFlags is set to MF_SEPARATOR.

lpszNewItem

Specifies the content of the new menu item. nFlags can be used to interpret lpszNewItem in the following ways:

nFlags | Interpretation of lpszNewItem
MF_OWNERDRAW | Contains an application-supplied 32-bit value that the application can use to maintain additional data associated with the menu item. This 32-bit value is available to the application in the itemData member of the structure supplied by the WM_MEASUREITEM and WM_DRAWITEM messages. These messages are sent when the menu item is initially displayed or is changed.
MF_STRING | Contains a long pointer to a null-terminated string. This is the default interpretation.
MF_SEPARATOR | The lpszNewItem parameter is ignored (not needed).

pBmp

Points to a CBitmap object that will be used as the menu item.

Remarks

Inserts a new menu item at the position specified by nPosition and moves other items down the menu. The application can specify the state of the menu item by setting values in nFlags.

Whenever a menu that resides in a window is changed (whether or not the window is displayed), the application should call CWnd::DrawMenuBar.

When nIDNewItem specifies a pop-up menu, it becomes part of the menu in which it is inserted. If that menu is destroyed, the inserted menu will also be destroyed. An inserted menu should be detached from a CMenu object to avoid conflict.

If the active multiple document interface (MDI) child window is maximized and an application inserts a pop-up menu into the MDI application’s menu by calling this function and specifying the MF_BYPOSITION flag, the menu is inserted one position farther left than expected. This happens because the Control menu of the active MDI child window is inserted into the first position of the MDI frame window’s menu bar. To position the menu properly, the application must add 1 to the position value that would otherwise be used. An application can use the WM_MDIGETACTIVE message to determine whether the currently active child window is maximized.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::AppendMenu, CWnd::DrawMenuBar, CMenu::SetMenuItemBitmaps, CMenu::Detach, ::InsertMenu


CMenu::LoadMenu

BOOL LoadMenu( LPCTSTR lpszResourceName );

BOOL LoadMenu( UINT nIDResource );

Return Value

Nonzero if the menu resource was loaded successfully; otherwise 0.

Parameters

lpszResourceName

Points to a null-terminated string that contains the name of the menu resource to load.

nIDResource

Specifies the menu ID of the menu resource to load.

Remarks

Loads a menu resource from the application’s executable file and attaches it to the CMenu object.

Before exiting, an application must free system resources associated with a menu if the menu is not assigned to a window. An application frees a menu by calling the DestroyMenu member function.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::AppendMenu, CMenu::DestroyMenu, CMenu::LoadMenuIndirect, ::LoadMenu


CMenu::LoadMenuIndirect

BOOL LoadMenuIndirect( const void* lpMenuTemplate );

Return Value

Nonzero if the menu resource was loaded successfully; otherwise 0.

Parameters

lpMenuTemplate

Points to a menu template (which is a single MENUITEMTEMPLATEHEADER structure and a collection of one or more MENUITEMTEMPLATE structures). For more information on these two structures, see the Win32 SDK documentation.

Remarks

Loads a resource from a menu template in memory and attaches it to the CMenu object. A menu template is a header followed by a collection of one or more MENUITEMTEMPLATE structures, each of which may contain one or more menu items and pop-up menus.

The version number should be 0.

The mtOption flags should include MF_END for the last item in a pop-up list and for the last item in the main list. See the AppendMenu member function for other flags. The mtId member must be omitted from the MENUITEMTEMPLATE structure when MF_POPUP is specified in mtOption.

The space allocated for the MENUITEMTEMPLATE structure must be large enough for mtString to contain the name of the menu item as a null-terminated string.

Before exiting, an application must free system resources associated with a menu if the menu is not assigned to a window. An application frees a menu by calling the DestroyMenu member function.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::DestroyMenu, CMenu::LoadMenu, ::LoadMenuIndirect, CMenu::AppendMenu


CMenu::MeasureItem

virtual void MeasureItem( LPMEASUREITEMSTRUCT lpMeasureItemStruct );

Parameters

lpMeasureItemStruct

A pointer to a MEASUREITEMSTRUCT structure.

Remarks

Called by the framework when a menu with the owner-draw style is created. By default, this member function does nothing. Override this member function and fill in the MEASUREITEMSTRUCT structure to inform Windows of the menu’s dimensions.

See CWnd::OnMeasureItem for a description of the MEASUREITEMSTRUCT structure.


CMenu::ModifyMenu

BOOL ModifyMenu( UINT nPosition, UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL );

BOOL ModifyMenu( UINT nPosition, UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nPosition

Specifies the menu item to be changed. The nFlags parameter can be used to interpret nPosition in the following ways:

nFlags | Interpretation of nPosition
MF_BYCOMMAND | Specifies that the parameter gives the command ID of the existing menu item. This is the default if neither MF_BYCOMMAND nor MF_BYPOSITION is set.
MF_BYPOSITION | Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

nFlags

Specifies how nPosition is interpreted and gives information about the changes to be made to the menu item. For a list of flags that may be set, see the AppendMenu member function.

nIDNewItem

Specifies either the command ID of the modified menu item or, if nFlags is set to MF_POPUP, the menu handle (HMENU) of a pop-up menu. The nIDNewItem parameter is ignored (not needed) if nFlags is set to MF_SEPARATOR.

lpszNewItem

Specifies the content of the new menu item. The nFlags parameter can be used to interpret lpszNewItem in the following ways:

nFlags | Interpretation of lpszNewItem
MF_OWNERDRAW | Contains an application-supplied 32-bit value that the application can use to maintain additional data associated with the menu item. This 32-bit value is available to the application when it processes MF_MEASUREITEM and MF_DRAWITEM.
MF_STRING | Contains a long pointer to a null-terminated string or to a CString.
MF_SEPARATOR | The lpszNewItem parameter is ignored (not needed).

pBmp

Points to a CBitmap object that will be used as the menu item.

Remarks

Changes an existing menu item at the position specified by nPosition. The application specifies the new state of the menu item by setting values in nFlags. If this function replaces a pop-up menu associated with the menu item, it destroys the old pop-up menu and frees the memory used by the pop-up menu.

When nIDNewItem specifies a pop-up menu, it becomes part of the menu in which it is inserted. If that menu is destroyed, the inserted menu will also be destroyed. An inserted menu should be detached from a CMenu object to avoid conflict.

Whenever a menu that resides in a window is changed (whether or not the window is displayed), the application should call CWnd::DrawMenuBar. To change the attributes of existing menu items, it is much faster to use the CheckMenuItem and EnableMenuItem member functions.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::AppendMenu, CMenu::InsertMenu, CMenu::CheckMenuItem, CWnd::DrawMenuBar, CMenu::EnableMenuItem, CMenu::SetMenuItemBitmaps, CMenu::Detach, ::ModifyMenu


CMenu::RemoveMenu

BOOL RemoveMenu( UINT nPosition, UINT nFlags );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nPosition

Specifies the menu item to be removed. The nFlags parameter can be used to interpret nPosition in the following ways:

nFlags | Interpretation of nPosition
MF_BYCOMMAND | Specifies that the parameter gives the command ID of the existing menu item. This is the default if neither MF_BYCOMMAND nor MF_BYPOSITION is set.
MF_BYPOSITION | Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

nFlags

Specifies how nPosition is interpreted.

Remarks

Deletes a menu item with an associated pop-up menu from the menu. It does not destroy the handle for a pop-up menu, so the menu can be reused. Before calling this function, the application may call the GetSubMenu member function to retrieve the pop-up CMenu object for reuse.

Whenever a menu that resides in a window is changed (whether or not the window is displayed), the application must call CWnd::DrawMenuBar.

CMenu Overview | Class Members | Hierarchy Chart

See Also CWnd::DrawMenuBar, CMenu::GetSubMenu, ::RemoveMenu


CMenu::SetDefaultItem

BOOL SetDefaultItem( UINT uItem, BOOL fByPos = FALSE );

Return Value

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, use the Win32 function GetLastError, as described in the Platform SDK.

Parameters

uItem

Identifier or position of the new default menu item or - 1 for no default item. The meaning of this parameter depends on the value of fByPos.

fByPos

Value specifying the meaning of uItem. If this parameter is FALSE, uItem is a menu item identifier. Otherwise, it is a menu item position.

Remarks

This member function implements the behavior of the Win32 function SetMenuDefaultItem, as described in the Platform SDK.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::GetDefaultItem


CMenu::SetMenuContextHelpId

BOOL SetMenuContextHelpId( DWORD dwContextHelpId );

Return Value

Nonzero if successful; otherwise 0

Parameters

dwContextHelpId

Context help ID to associate with CMenu.

Remarks

Call this function to associate a context help ID with CMenu. All items in the menu share this identifier—it is not possible to attach a help context identifier to the individual menu items.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::GetMenuContextHelpID, ::SetMenuContextHelpId


CMenu::SetMenuItemBitmaps

BOOL SetMenuItemBitmaps( UINT nPosition, UINT nFlags, const CBitmap* pBmpUnchecked, const CBitmap* pBmpChecked );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nPosition

Specifies the menu item to be changed. The nFlags parameter can be used to interpret nPosition in the following ways:

nFlags | Interpretation of nPosition
MF_BYCOMMAND | Specifies that the parameter gives the command ID of the existing menu item. This is the default if neither MF_BYCOMMAND nor MF_BYPOSITION is set.
MF_BYPOSITION | Specifies that the parameter gives the position of the existing menu item. The first item is at position 0.

nFlags

Specifies how nPosition is interpreted.

pBmpUnchecked

Specifies the bitmap to use for menu items that are not checked.

pBmpChecked

Specifies the bitmap to use for menu items that are checked.

Remarks

Associates the specified bitmaps with a menu item. Whether the menu item is checked or unchecked, Windows displays the appropriate bitmap next to the menu item.

If either pBmpUnchecked or pBmpChecked is NULL, then Windows displays nothing next to the menu item for the corresponding attribute. If both parameters are NULL, Windows uses the default check mark when the item is checked and removes the check mark when the item is unchecked.

When the menu is destroyed, these bitmaps are not destroyed; the application must destroy them.

The Windows GetMenuCheckMarkDimensions function retrieves the dimensions of the default check mark used for menu items. The application uses these values to determine the appropriate size for the bitmaps supplied with this function. Get the size, create your bitmaps, then set them.

CMenu Overview | Class Members | Hierarchy Chart

See Also ::GetMenuCheckMarkDimensions, ::SetMenuItemBitmaps


CMenu::TrackPopupMenu

BOOL TrackPopupMenu( UINT nFlags, int x, int y, CWnd* pWnd, LPCRECT lpRect = NULL );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nFlags

Specifies a screen-position flag and a mouse-button flag. The screen-position flag can be one of the following:

  • TPM_CENTERALIGN Centers the pop-up menu horizontally relative to the coordinate specified by x.

  • TPM_LEFTALIGN Positions the pop-up menu so that its left side is aligned with the coordinate specified by x.

  • TPM_RIGHTALIGN Positions the pop-up menu so that its right side is aligned with the coordinate specified by x.

    The mouse-button flag can be either of the following:

  • TPM_LEFTBUTTON Causes the pop-up menu to track the left mouse button.

  • TPM_RIGHTBUTTON Causes the pop-up menu to track the right mouse button.

x

Specifies the horizontal position in screen coordinates of the pop-up menu. Depending on the value of the nFlags parameter, the menu can be left-aligned, right-aligned, or centered relative to this position.

y

Specifies the vertical position in screen coordinates of the top of the menu on the screen.

pWnd

Identifies the window that owns the pop-up menu. This window receives all WM_COMMAND messages from the menu. In Windows versions 3.1 and later, the window does not receive WM_COMMAND messages until TrackPopupMenu returns. In Windows 3.0, the window receives WM_COMMAND messages before TrackPopupMenu returns.

lpRect

Points to a RECT structure or CRect object that contains the screen coordinates of a rectangle within which the user can click without dismissing the pop-up menu. If this parameter is NULL, the pop-up menu is dismissed if the user clicks outside the pop-up menu. This must be NULL for Windows 3.0.

For Windows 3.1 and later, you can use the following constants:

  • TPM_CENTERALIGN

  • TPM_LEFTALIGN

  • TPM_RIGHTALIGN

  • TPM_RIGHTBUTTON

Remarks

Displays a floating pop-up menu at the specified location and tracks the selection of items on the pop-up menu. A floating pop-up menu can appear anywhere on the screen.

CMenu Overview | Class Members | Hierarchy Chart

See Also CMenu::CreatePopupMenu, CMenu::GetSubMenu, ::TrackPopupMenu


CMenu::m_hMenu

Remarks

Specifies the HMENU handle of the Windows menu attached to the CMenu object.


CMetaFileDC

A Windows metafile contains a sequence of graphics device interface (GDI) commands that you can replay to create a desired image or text.

To implement a Windows metafile, first create a CMetaFileDC object. Invoke the CMetaFileDC constructor, then call the Create member function, which creates a Windows metafile device context and attaches it to the CMetaFileDC object.

Next send the CMetaFileDC object the sequence of CDC GDI commands that you intend for it to replay. Only those GDI commands that create output, such as MoveTo and LineTo, can be used.

After you have sent the desired commands to the metafile, call the Close member function, which closes the metafile device contexts and returns a metafile handle. Then dispose of the CMetaFileDC object.

CDC::PlayMetaFile can then use the metafile handle to play the metafile repeatedly. The metafile can also be manipulated by Windows functions such as CopyMetaFile, which copies a metafile to disk.

When the metafile is no longer needed, delete it from memory with the DeleteMetaFile Windows function.

You can also implement the CMetaFileDC object so that it can handle both output calls and attribute GDI calls such as GetTextExtent. Such a metafile is more flexible and can more easily reuse general GDI code, which often consists of a mix of output and attribute calls. The CMetaFileDC class inherits two device contexts, m_hDC and m_hAttribDC, from CDC. The m_hDC device context handles all CDC GDI output calls and the m_hAttribDC device context handles all CDC GDI attribute calls. Normally, these two device contexts refer to the same device. In the case of CMetaFileDC, the attribute DC is set to NULL by default.

Create a second device context that points to the screen, a printer, or device other than a metafile, then call the SetAttribDC member function to associate the new device context with m_hAttribDC. GDI calls for information will now be directed to the new m_hAttribDC. Output GDI calls will go to m_hDC, which represents the metafile.

For more information on CMetaFileDC, see Device Contexts in Visual C++ Programmer’s Guide.

#include <afxext.h>


CMetaFileDC Class Members

Construction

CMetaFileDC Constructs a CMetaFileDC object.

Initialization

Create | Creates the Windows metafile device context and attaches it to the CMetaFileDC object.
CreateEnhanced | Creates a metafile device context for an enhanced-format metafile.

Operations

Close | Closes the device context and creates a metafile handle.
CloseEnhanced | Closes an enhanced-metafile device context and creates an enhanced-metafile handle.


CMetaFileDC::Close

HMETAFILE Close( );

Return Value

A valid HMETAFILE if the function is successful; otherwise NULL.

Remarks

Closes the metafile device context and creates a Windows metafile handle that can be used to play the metafile by using the CDC::PlayMetaFile member function. The Windows metafile handle can also be used to manipulate the metafile with Windows functions such as CopyMetaFile.

Delete the metafile after use by calling the Windows DeleteMetaFile function.

CMetaFileDC Overview | Class Members | Hierarchy Chart

See Also CDC::PlayMetaFile, ::CloseMetaFile, ::CopyMetaFile, ::DeleteMetaFile


CMetaFileDC::CloseEnhanced

HENHMETAFILE CloseEnhanced( );

Return Value

A handle of an enhanced metafile, if successful; otherwise NULL.

Remarks

Closes an enhanced-metafile device context and returns a handle that identifies an enhanced-format metafile. An application can use the enhanced-metafile handle returned by this function to perform the following tasks:

  • Display a picture stored in an enhanced metafile

  • Create copies of the enhanced metafile

  • Enumerate, edit, or copy individual records in the enhanced metafile

  • Retrieve an optional description of the metafile contents from the enhanced-metafile header

  • Retrieve a copy of the enhanced-metafile header

  • Retrieve a binary copy of the enhanced metafile

  • Enumerate the colors in the optional palette

  • Convert an enhanced-format metafile into a Windows-format metafile

When the application no longer needs the enhanced metafile handle, it should release the handle by calling the ::DeleteEnhMetaFile function.

CMetaFileDC Overview | Class Members | Hierarchy Chart

See Also CDC::PlayMetaFile, CMetaFileDC::CreateEnhanced, ::DeleteEnhMetaFile


CMetaFileDC::CMetaFileDC

CMetaFileDC( );

Remarks

Construct a CMetaFileDC object in two steps. First, call CMetaFileDC, then call Create, which creates the Windows metafile device context and attaches it to the CMetaFileDC object.

CMetaFileDC Overview | Class Members | Hierarchy Chart

See Also CMetaFileDC::Create


CMetaFileDC::Create

BOOL Create( LPCTSTR lpszFilename = NULL );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpszFilename

Points to a null-terminated character string. Specifies the filename of the metafile to create. If lpszFilename is NULL, a new in-memory metafile is created.

Remarks

Construct a CMetaFileDC object in two steps. First, call the constructor CMetaFileDC, then call Create, which creates the Windows metafile device context and attaches it to the CMetaFileDC object.

CMetaFileDC Overview | Class Members | Hierarchy Chart

See Also CMetaFileDC::CMetaFileDC, CDC::SetAttribDC, ::CreateMetaFile


CMetaFileDC::CreateEnhanced

BOOL CreateEnhanced( CDC* pDCRef, LPCTSTR lpszFileName, LPCRECT lpBounds, LPCTSTR lpszDescription );

Return Value

A handle of the device context for the enhanced metafile, if successful; otherwise NULL.

Parameters

pDCRef

Identifies a reference device for the enhanced metafile.

lpszFileName

Points to a null-terminated character string. Specifies the filename for the enhanced metafile to be created. If this parameter is NULL, the enhanced metafile is memory based and its contents lost when the object is destroyed or when the ::DeleteEnhMetaFile function is called.

lpBounds

Points to a RECT data structure or a CRect object that specifies the dimensions in HIMETRIC units (in .01-millimeter increments) of the picture to be stored in the enhanced metafile.

lpszDescription

Points to a zero-terminated string that specifies the name of the application that created the picture, as well as the picture’s title.

Remarks

Creates a device context for an enhanced-format metafile. This DC can be used to store a device-independent picture.

Windows uses the reference device identified by the pDCRef parameter to record the resolution and units of the device on which a picture originally appeared. If the pDCRef parameter is NULL, it uses the current display device for reference.

The left and top members of the RECT data structure pointed to by the lpBounds parameter must be smaller than the right and bottom members, respectively. Points along the edges of the rectangle are included in the picture. If lpBounds is NULL, the graphics device interface (GDI) computes the dimensions of the smallest rectangle that can enclose the picture drawn by the application. The lpBounds parameter should be supplied where possible.

The string pointed to by the lpszDescription parameter must contain a null character between the application name and the picture name and must terminate with two null characters —for example, “XYZ Graphics Editor\0Bald Eagle\0\0,” where \0 represents the null character. If lpszDescription is NULL, there is no corresponding entry in the enhanced-metafile header.

Applications use the DC created by this function to store a graphics picture in an enhanced metafile. The handle identifying this DC can be passed to any GDI function.

After an application stores a picture in an enhanced metafile, it can display the picture on any output device by calling the CDC::PlayMetaFile function. When displaying the picture, Windows uses the rectangle pointed to by the lpBounds parameter and the resolution data from the reference device to position and scale the picture. The device context returned by this function contains the same default attributes associated with any new DC.

Applications must use the ::GetWinMetaFileBits function to convert an enhanced metafile to the older Windows metafile format.

The filename for the enhanced metafile should use the .EMF extension.

CMetaFileDC Overview | Class Members | Hierarchy Chart

See Also CMetaFileDC::CloseEnhanced, CDC::PlayMetaFile, ::CloseEnhMetaFile, ::DeleteEnhMetaFile, ::GetEnhMetaFileDescription, ::GetEnhMetaFileHeader, ::GetWinMetaFileBits, ::PlayEnhMetaFile


CMiniFrameWnd

A CMiniFrameWnd object represents a half-height frame window typically seen around floating toolbars. These mini-frame windows behave like normal frame windows, except that they do not have minimize/maximize buttons or menus and you only have to single-click on the system menu to dismiss them.

To use a CMiniFrameWnd object, first define the object. Then call the Create member function to display the mini-frame window.

For more information on how to use CMiniFrameWnd objects, see the article Toolbars: Docking and Floating in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CFrameWnd


CMiniFrameWnd Class Members

Construction

CMiniFrameWnd | Constructs a CMiniFrameWnd object.
Create | Creates a CMiniFrameWnd object after construction.


CMiniFrameWnd::CMiniFrameWnd

CMiniFrameWnd( );

Remarks

Constructs a CMiniFrameWnd object, but does not create the window. To create the window, call CMiniFrameWnd::Create.

CMiniFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd


CMiniFrameWnd::Create

BOOL Create( LPCTSTR lpClassName, LPCTSTR lpWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd = NULL, UINT nID = 0);

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpClassName

Points to a null-terminated character string that names the Windows class. The class name can be any name registered with the global AfxRegisterWndClass function. If NULL, the window class will be registered for you by the framework. MFC gives the default class the following styles and attributes:

  • Sets style bit CS_DBLCLKS, which sends double-click messages to the window procedure when the user double-clicks the mouse.

  • Sets style bits CS_HREDRAW and CS_VREDRAW, which direct the contents of the client area to be redrawn when the window changes size.

  • Sets the class cursor to the Windows standard IDC_ARROW.

  • Sets the class background brush to NULL, so the window will not erase its background.

  • Sets the class icon to the standard, waving-flag Windows logo icon.

  • Sets the window to the default size and position, as indicated by Windows.

lpWindowName

Points to a null-terminated character string that contains the window name.

dwStyle

Specifies the window style attributes. These can include standard window styles and one or more of the following special styles:

  • MFS_MOVEFRAME Allows the mini-frame window to be moved by clicking on any edge of the window, not just the caption.

  • MFS_4THICKFRAME Disables resizing of the mini-frame window.

  • MFS_SYNCACTIVE Synchronizes the activation of the mini-frame window to the activation of its parent window.

  • MFS_THICKFRAME Allows the mini-frame window to be sized as small as the contents of the client area allow.

  • MFS_BLOCKSYSMENU Disables access to the system menu and the control menu, and converts them to part of the caption (title bar).

    See CWnd::Create for a description of possible window style values. The typical combination used for mini-frame windows is WS_POPUP|WS_CAPTION|WS_SYSMENU.

rect

A RECT structure specifying the desired dimensions of the window.

pParentWnd

Points to the parent window. Use NULL for top-level windows.

nID

If the mini-frame window is created as a child window, this is the identifier of the child control; otherwise 0.

Remarks

Creates the Windows mini-frame window and attaches it to the CMiniFrameWnd object. Create initializes the window’s class name and window name and registers default values for its style and parent.

CMiniFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::Create, CWnd::Create, CWnd::CreateEx, CFrameWnd


CMonikerFile

A CMonikerFile object represents a stream of data ( IStream) named by an IMoniker.

A moniker contains information much like a pathname to a file. If you have a pointer to a moniker object's IMoniker interface, you can get access to the identified file without having any other specific information about where the file is actually located.

Derived from COleStreamFile, CMonikerFile takes a moniker or a string representation it can make into a moniker and binds to the stream for which the moniker is a name. You can then read and write to that stream. The real purpose of CMonikerFile is to provide simple access to IStreams named by IMonikers so that you do not have to bind to a stream yourself, yet have CFile functionality to the stream.

CMonikerFile cannot be used to bind to anything other than a stream. If you want to bind to storage or an object, you must use the IMoniker interface directly.

For more information on streams and monikers, see COleStreamFile in the MFC Class Library Reference and IStream and IMoniker in the OLE Programmer’s Reference.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

See Also CAsyncMonikerFile


CMonikerFile Class Members

Construction

CMonikerFile Constructs a CMonikerFile object.

Operations

Close | Detaches and releases the stream and releases the moniker.
Detach | Detaches the IMoniker from this CMonikerFile object.
GetMoniker | Returns the current moniker.

Overridables

CreateBindContext | Obtains the bind context or creates a default initialized bind context.
Open | Opens the specified file to obtain a stream.


CMonikerFile::Close

void Close( );

Remarks

Call this function to detach and release the stream and to release the moniker. Can be called on unopened or already closed streams.

CMonikerFile Overview | Class Members | Hierarchy Chart

See Also CMonikerFile::Open


CMonikerFile::CMonikerFile

CMonikerFile( );

Remarks

Constructs a CMonikerFile object.

CMonikerFile Overview | Class Members | Hierarchy Chart

See Also CAsyncMonikerFile, CMonikerFile::Open


CMonikerFile::CreateBindContext

virtual IBindCtx* CreateBindContext( CFileException* pError );

Return Value

A pointer to the bind context IBindCtx to bind with if successful; otherwise NULL. If the instance was opened with an IBindHost interface, the bind context is retrieved from the IBindHost. If there is no IBindHost interface or the interface fails to return a bind context, a bind context is created. For a description of the IBindHost interface, see the ActiveX SDK.

Parameters

pError

A pointer to a file exception. In the event of an error, it will be set to the cause.

Remarks

Call this function to create a default initialized bind context. A bind context is an object that stores information about a particular moniker binding operation. You can override this function to provide a custom bind context.


CMonikerFile::Detach

BOOL Detach( CFileException* pError = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pError

A pointer to a file exception. In the event of an error, it will be set to the cause.

Remarks

Call this function to close the stream.

CMonikerFile Overview | Class Members | Hierarchy Chart

See Also CMonikerFile::Close, CMonikerFile::Open


CMonikerFile::GetMoniker

IMoniker* GetMoniker( ) const;

Return Value

A pointer to the current moniker interface ( IMoniker).

Remarks

Call this function to retrieve a pointer to the current moniker. Since CMonikerFile is not an interface, the pointer returned does not increment the reference count (through AddRef), and the moniker is released when the CMonikerFile object is released. If you want to hold onto the moniker or release it yourself, you must AddRef it.


CMonikerFile::Open

BOOL Open( LPCTSTR lpszURL, CFileException* pError = NULL );

BOOL Open( IMoniker* pMoniker, CFileException* pError = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszURL

A URL or filename of the file to be opened.

pError

A pointer to a file exception. In the event of an error, it will be set to the cause.

pMoniker

A pointer to the moniker interface IMoniker to be used to obtain a stream.

Remarks

Call this member function to open a file or moniker object.

The lpszURL parameter cannot be used on a Macintosh. Only the pMoniker form of Open can be used on a Macintosh.

You can use a URL or a filename for the lpszURL parameter. For example:

CMyMonFile  mymonf;
mymonf.Open(_T("http://www.microsoft.com"));

– or –

CMyMonFile  mymonf;
mymonf.Open(_T("file:c:\mydata.dat"));

CMonikerFile Overview | Class Members | Hierarchy Chart

See Also CMonikerFile::CMonikerFile, CAsyncMonikerFile::Open


CMonthCalCtrl

A CMonthCalCtrl object encapsulates the functionality of a month calendar control. The month calendar control provides the user with a simple calendar interface, from which the user can select a date. The user can change the display by:

  • Scrolling backward and forward, from month to month.

  • Clicking the Today text to display the current day (if the MCS_NOTODAY style is not used).

  • Picking a month or a year from a pop-up menu.

You can customize the month calendar control by applying a variety of styles to the object when you create it. These styles are described in Month Calendar Control Styles in the Platform SDK.

The month calendar control can display more than one month, and it can indicate special days (such as holidays) by bolding the date.

For more information on using the month calendar control, see Using CMonthCalCtrl in the Visual C++ Programmer’s Guide.

#include <afxdtctl.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CMNCTRL1

See Also CDateTimeCtrl


CMonthCalCtrl Class Members

Construction

CMonthCalCtrl | Constructs a CMonthCalCtrl object.
Create | Creates a month calendar control and attaches it to the CMonthCalCtrl object.

Attributes

GetMinReqRect | Retrieves the minimum size required to show a full month in a month calendar control.
SetMonthDelta | Sets the scroll rate for a month calendar control.
GetMonthDelta | Retrieves the scroll rate for a month calendar control.
SetFirstDayOfWeek | Sets the day of week to be displayed in the leftmost column of the calendar.
GetFirstDayOfWeek | Gets the first day of the week to be displayed in the leftmost column of the calendar.
GetColor | Gets the color of a specified area of a month calendar control.
SetColor | Sets the color of a specified area of a month calendar control.

Operations

SizeMinReq | Repaints the month calendar control to its minimum, one-month size.
SetToday | Sets the calendar control for the current day.
GetToday | Retrieves the date information for the date specified as "today" for a month calendar control.
SetCurSel | Sets the currently-selected date for a month calendar control.
GetCurSel | Retrieves the system time as indicated by the currently-selected date.
SetDayState | Sets the display for days in a month calendar control.
SetMaxSelCount | Sets the maximum number of days that can be selected in a month calendar control.
GetMaxSelCount | Retrieves the current maximum number of days that can be selected in a month calendar control.
SetRange | Sets the minimum and maximum allowable dates for a month calendar control.
GetRange | Retrieves the current minimum and maximum dates set in a month calendar control.
GetMonthRange | Retrieves date information representing the high and low limits of a month calendar control's display.
SetSelRange | Sets the selection for a month calendar control to a given date range.
GetSelRange | Retrieves date information representing the upper and lower limits of the date range currently selected by the user.
HitTest | Determines which portion of a month calendar control is at a given point on the screen.


CMonthCalCtrl::CMonthCalCtrl

CMonthCalCtrl( );

Remarks

Call this member function to construct a CMonthCalCtrl object. You must call Create after you construct the object.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::Create


CMonthCalCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

BOOL Create( DWORD dwStyle, const POINT& pt, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if initialization was successful; otherwise 0.

Parameters

dwStyle

Specifies the combination of Windows styles applied to the month calendar control. See Month Calendar Control Styles in the Platform SDK for more information about the styles.

rect

A reference to a RECT structure. Contains the position and size of the month calendar control.

pt

A reference to a POINT structure that identifies the location of the month calendar control.

pParentWnd

A pointer to a CWnd object that is the parent window of the month calendar control. It must not be NULL.

nID

Specifies the month calendar control’s control ID.

Remarks

Create a month calendar control in two steps:

  1. Call CMonthCalCtrl to construct a CMonthCalCtrl object.

  2. Call this member function, which creates a month calendar control and attaches it to the CMonthCalCtrl object.

When you call Create, the common controls are initialized. The version of Create you call determines how it is sized:

  • To have MFC automatically size the control to one month, call the override that uses the pt parameter.

  • To size the control yourself, call the override of this function that uses the rect parameter.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::CMonthCalCtrl


CMonthCalCtrl::GetColor

COLORREF GetColor( int nRegion ) const;

Return Value

A COLORREF value specifying the color associated with the portion of the month calendar control, if successful. Otherwise, this member function returns -1.

Parameters

nRegion

The region of the month calendar control from which the color is retrieved. For a list of values, see the nRegion parameter of SetColor.

Remarks

Call this member function to retrieve the color of an area of the month calendar control specified by nRegion.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SetColor


CMonthCalCtrl::GetCurSel

BOOL GetCurSel( COleDateTime& refDateTime ) const;

BOOL GetCurSel( CTime& refDateTime ) const;

BOOL GetCurSel( LPSYSTEMTIME pDateTime ) const;

Return Value

Nonzero if successful; otherwize 0.

Parameters

refDateTime

A reference to a COleDateTime object or a CTime object. Receives the current time.

pDateTime

A pointer to a SYSTEMTIME structure that will receive the currently-selected date information. This parameter must be a valid address and cannot be NULL.

Remarks

This member function implements the behavior of the Win32 message MCM_GETCURSEL, as described in the Platform SDK.

Note This member function fails if the style MCS_MULTISELECT is set.

In MFC's implementation of GetCurSel, you can specify a COleDateTime usage, a CTime usage, or a SYSTEMTIME structure usage.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SetCurSel


CMonthCalCtrl::GetFirstDayOfWeek

int GetFirstDayOfWeek( BOOL* pbLocal = NULL ) const;

Return Value

An integer value that represents the first day of the week. See Remarks for more information on what these integers represent.

Parameters

pbLocal

A pointer to a BOOL value. If the value is non-zero, the control's setting does not match the setting in the control panel.

Remarks

This member function implements the behavior of the Win32 message MCM_GETFIRSTDAYOFWEEK, as described in the Platform SDK.

The days of the week are represented as integers, as follows.

Value | Day of the Week
0 | Monday
1 | Tuesday
2 | Wednesday
3 | Thursday
4 | Friday
5 | Saturday
6 | Sunday

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SetFirstDayOfWeek


CMonthCalCtrl::GetMaxSelCount

int GetMaxSelCount( ) const;

Return Value

An integer value that represents the total number of days that can be selected for the control.

Remarks

This member function implements the behavior of the Win32 message MCM_GETMAXSELCOUNT, as described in the Platform SDK.

Use this member function for controls with the MCS_MULTISELECT style set.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SetMaxSelCount


CMonthCalCtrl::GetMinReqRect

BOOL GetMinReqRect( RECT* pRect ) const;

Return Value

If successful, this member function returns nonzero and lpRect receives the applicable bounding information. If unsuccessful, the member function returns 0.

Parameters

pRect

A pointer to a RECT structure that will receive bounding rectangle information. This parameter must be a valid address and cannot be NULL.

Remarks

This member function implements the behavior of the Win32 message MCM_GETMINREQRECT, as described in the Platform SDK.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SizeMinReq


CMonthCalCtrl::GetMonthDelta

int GetMonthDelta( ) const;

Return Value

The scroll rate for the month calendar control. The scroll rate is the number of months that the control moves its display when the user clicks a scroll button once.

Remarks

This member function implements the behavior of the Win32 message MCM_GETMONTHDELTA, as described in the Platform SDK.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SetMonthDelta


CMonthCalCtrl::GetMonthRange

int GetMonthRange( COleDateTime& refMinRange, COleDateTime& refMaxRange, DWORD dwFlags ) const;

int GetMonthRange( CTime& refMinRange, CTime& refMaxRange, DWORD dwFlags ) const;

int GetMonthRange( LPSYSTEMTIME pMinRange, LPSYSTEMTIME pMaxRange, DWORD dwFlags ) const;

Return Value

An integer that represents the range, in months, spanned by the two limits indicated by refMinRange and refMaxRange in the first and second versions, or pMinRange and pMaxRange in the third version.

Parameters

refMinRange

A reference to a COleDateTime or CTime object containing the minimum date allowed.

refMaxRange

A reference to a COleDateTime or CTime object containing the maximum date allowed.

pMinRange

A pointer to a SYSTEMTIME structure containing the date at the lowest end of the range.

pMaxRange

A pointer to a SYSTEMTIME structure containing the date at the highest end of the range.

dwFlags

Value specifying the scope of the range limits to be retrieved. This value must be one of the following.

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

Remarks

This member function implements the behavior of the Win32 message MCM_GETMONTHRANGE, as described in the Platform SDK.

In MFC's implementation of GetMonthRange, you can specify COleDateTime usage, a CTime usage, or a SYSTEMTIME structure usage.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetRange


CMonthCalCtrl::GetRange

DWORD GetRange( COleDateTime* pMinRange, COleDateTime* pMaxRange ) const;

DWORD GetRange( CTime* pMinRange, CTime* pMaxRange ) const;

DWORD GetRange( LPSYSTEMTIME pMinRange, LPSYSTEMTIME pMaxRange ) const;

Return Value

A DWORD that can be zero (no limits are set) or a combination of the following values that specify limit information.

Value | Meaning
GDTR_MAX | A maximum limit is set for the control; pMaxRange is valid and contains the applicable date information.
GDTR_MIN | A minimum limit is set for the control; pMinRange is valid and contains the applicable date information.

Parameters

pMinRange

A pointer to a COleDateTime object, a CTime object, or SYSTEMTIME structure containing the date at the lowest end of the range.

pMaxRange

A pointer to a COleDateTime object, a CTime object, or SYSTEMTIME structure containing the date at the highest end of the range.

Remarks

This member function implements the behavior of the Win32 message MCM_GETRANGE, as described in the Platform SDK.

In MFC's implementation of GetRange, you can specify a COleDateTime usage, a CTime usage, or a SYSTEMTIME structure usage.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SetRange


CMonthCalCtrl::GetSelRange

BOOL GetSelRange( COleDateTime& refMinRange, COleDateTime& refMaxRange ) const;

BOOL GetSelRange( CTime& refMinRange, CTime& refMaxRange ) const;

BOOL GetSelRange( LPSYSTEMTIME pMinRange, LPSYSTEMTIME pMaxRange ) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

refMinRange

A reference to a COleDateTime or CTime object containing the minimum date allowed.

refMaxRange

A reference to a COleDateTime or CTime object containing the maximum date allowed.

pMinRange

A pointer to a SYSTEMTIME structure containing the date at the lowest end of the range.

pMaxRange

A pointer to a SYSTEMTIME structure containing the date at the highest end of the range.

Remarks

This member function implements the behavior of the Win32 message MCM_GETSELRANGE, as described in the Platform SDK.

GetSelRange will fail if applied to a month calendar control that does not use the MCS_MULTISELECT style.

In MFC's implementation of GetSelRange, you can specify COleDateTime usage, a CTime usage, or a SYSTEMTIME structure usage.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SetSelRange


CMonthCalCtrl::GetToday

BOOL CMonthCalCtrl::GetToday( COleDateTime& refDateTime ) const;

BOOL CMonthCalCtrl::GetToday( CTime& refDateTime ) const;

BOOL GetToday( LPSYSTEMTIME pDateTime ) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

refDateTime

A reference to a COleDateTime or CTime object indicating the current day.

pDateTime

A pointer to a SYSTEMTIME structure that will receive the date information. This parameter must be a valid address and cannot be NULL.

Remarks

This member function implements the behavior of the Win32 message MCM_GETTODAY, as described in the Platform SDK.

In MFC's implementation of GetToday, you can specify a COleDateTime usage, a CTime usage, or a SYSTEMTIME structure usage.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::SetToday


CMonthCalCtrl::HitTest

DWORD HitTest( PMCHITTESTINFO pMCHitTest );

Return Value

A DWORD value. Equal to the uHit member of the MCHITTESTINFO structure.

Parameters

pMCHitTest

A pointer to a MCHITTESTINFO structure containing hit testing points for the month calendar control.

Remarks

Call this member function to determine which month calendar control, if any, is at a specified position.

HitTest uses the MCHITTESTINFO structure, which contains information about the hit test.


CMonthCalCtrl::SetColor

COLORREF SetColor( int nRegion, COLORREF ref );

Return Value

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.

Parameters

nRegion

An integer value specifying which month calendar color to set. This value can be one of the following.

Value | Meaning
MCSC_BACKGROUND | The background color displayed between months.
MCSC_MONTHBK | The background color displayed within the month.
MCSC_TEXT | The color used to display text within a month.
MCSC_TITLEBK | The background color displayed in the calendar's title.
MCSC_TITLETEXT | The color used to display text within the calendar's title.
MCSC_TRAILINGTEXT | The color used to display header and trailing-day text. Header and trailing days are the days from the previous and following months that appear on the current calendar.

ref

A COLORREF value for the new color setting for the specified portion of the month calendar control.

Remarks

This member function implements the behavior of the Win32 message MCM_SETCOLOR, as described in the Platform SDK.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetColor


CMonthCalCtrl::SetCurSel

BOOL SetCurSel( const COleDateTime& refDateTime );

BOOL SetCurSel( const CTime& refDateTime );

BOOL SetCurSel( const LPSYSTEMTIME pDateTime );

Return Value

Nonzero if successful; otherwise 0.

Parameters

refDateTime

A reference to a COleDateTime or CTime object indicating the currently-selected month calendar control.

pDateTime

Pointer to a SYSTEMTIME structure that contains the date to be set as the current selection.

Remarks

This member function implements the behavior of the Win32 message MCM_SETCURSEL, as described in the Platform SDK.

In MFC's implementation of SetCurSel, you can specify a COleDateTime usage, a CTime usage, or a SYSTEMTIME structure usage.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetCurSel


CMonthCalCtrl::SetDayState

BOOL SetDayState( int nMonths, LPMONTHDAYSTATE pStates );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nMonths

Value indicating how many elements are in the array that pStates points to.

pStates

A pointer to a MONTHDAYSTATE array of values that define how the month calendar control will draw each day in its display. The MONTHDAYSTATE data 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.

Remarks

This member function implements the behavior of the Win32 message MCM_SETDAYSTATE, as described in the Platform SDK.


CMonthCalCtrl::SetFirstDayOfWeek

BOOL SetFirstDayOfWeek( int iDay, int* lpnOld = NULL );

Return Value

Nonzero if the previous first day of the week is set to a value other than that of LOCALE_IFIRSTDAYOFWEEK, which is the day indicated in the control panel setting. Otherwise, this function returns 0.

Parameters

iDay

An integer value representing which day is to be set as the first day of the week. This value must be one of the day numbers. See GetFirstDayOfWeek for a description of the day numbers.

lpnOld

A pointer to an integer indicating the first day of the week previously set.

Remarks

This member function implements the behavior of the Win32 message MCM_SETFIRSTDAYOFWEEK, as described in the Platform SDK.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetFirstDayOfWeek


CMonthCalCtrl::SetMaxSelCount

BOOL SetMaxSelCount( int nMax );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nMax

The value that will be set to represent the maximum number of selectable days.

Remarks

This member function implements the behavior of the Win32 message MCM_SETMAXSELCOUNT, as described in the Platform SDK.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetMaxSelCount


CMonthCalCtrl::SetMonthDelta

int SetMonthDelta( int iDelta );

Return Value

The previous scroll rate. If the scroll rate has not been previously set, the return value is 0.

Parameters

iDelta

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.

Remarks

This member function implements the behavior of the Win32 message MCM_SETMONTHDELTA, as described in the Platform SDK.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetMonthDelta


CMonthCalCtrl::SetRange

BOOL SetRange( const COleDateTime* pMinRange, const COleDateTime* pMaxRange );

BOOL SetRange( const CTime* pMinRange, const CTime* pMaxRange );

BOOL SetRange( const LPSYSTEMTIME pMinRange, const LPSYSTEMTIME pMaxRange );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pMinRange

A pointer to a COleDateTime object, a CTime object, or SYSTEMTIME structure containing the date at the lowest end of the range.

pMaxRange

A pointer to a COleDateTime object, a CTime object, or SYSTEMTIME structure containing the date at the highest end of the range.

Remarks

This member function implements the behavior of the Win32 message MCM_SETRANGE, as described in the Platform SDK.

In MFC's implementation of SetRange, you can specify COleDateTime usage, a CTime usage, or a SYSTEMTIME structure usage.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetRange


CMonthCalCtrl::SetSelRange

BOOL SetSelRange( const COleDateTime& pMinRange, const COleDateTime& pMaxRange );

BOOL SetSelRange( const CTime& pMinRange, const CTime& pMaxRange );

BOOL SetSelRange( const LPSYSTEMTIME pMinRange, const LPSYSTEMTIME pMaxRange );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pMinRange

A pointer to a COleDateTime object, a CTime object, or SYSTEMTIME structure containing the date at the lowest end of the range.

pMaxRange

A pointer to a COleDateTime object, a CTime object, or SYSTEMTIME structure containing the date at the highest end of the range.

Remarks

This member function implements the behavior of the Win32 message MCM_SETSELRANGE, as described in the Platform SDK.

In MFC's implementation of SetSelRange, you can specify COleDateTime usage, a CTime usage, or a SYSTEMTIME structure usage.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetSelRange


CMonthCalCtrl::SetToday

void SetToday( const COleDateTime& refDateTime );

void SetToday( const CTime* pDateTime );

void SetToday( const LPSYSTEMTIME pDateTime );

Parameters

refDateTime

A reference to a COleDateTime object that contains the current date.

pDateTime

In the second version, a pointer to a CTime object containing the current date information. In the third version, a pointer to a SYSTEMTIME structure that contains the current date information.

Remarks

This member function implements the behavior of the Win32 message MCM_SETTODAY, as described in the Platform SDK.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetToday


CMonthCalCtrl::SizeMinReq

BOOL SizeMinReq( BOOL bRepaint = TRUE );

Return Value

Nonzero if the month calendar control is sized to its minimum; otherwise 0.

Parameters

bRepaint

Specifies whether the control is to be repainted. By default, TRUE. If FALSE, no repainting occurs.

Remarks

Call this member function to display the month calendar control to the minimum size that displays one month. Calling SizeMinReq successfully displays the entire month calendar control for one month's calendar.

CMonthCalCtrl Overview | Class Members | Hierarchy Chart

See Also CMonthCalCtrl::GetMinReqRect


CMultiDocTemplate

The CMultiDocTemplate class defines a document template that implements the multiple document interface (MDI). An MDI application uses the main frame window as a workspace in which the user can open zero or more document frame windows, each of which displays a document. For a more detailed description of the MDI, see Windows Interface Guidelines for Software Design.

A document template defines the relationships among three types of classes:

  • A document class, which you derive from CDocument.

  • A view class, which displays data from the document class listed above. You can derive this class from CView, CScrollView, CFormView, or CEditView. (You can also use CEditView directly.)

  • A frame window class, which contains the view. For an MDI document template, you can derive this class from CMDIChildWnd, or, if you don’t need to customize the behavior of the document frame windows, you can use CMDIChildWnd directly without deriving your own class.

An MDI application can support more than one type of document, and documents of different types can be open at the same time. Your application has one document template for each document type that it supports. For example, if your MDI application supports both spreadsheets and text documents, the application has two CMultiDocTemplate objects.

The application uses the document template(s) when the user creates a new document. If the application supports more than one type of document, then the framework gets the names of the supported document types from the document templates and displays them in a list in the File New dialog box. Once the user has selected a document type, the application creates a document class object, a frame window object, and a view object and attaches them to each other.

You do not need to call any member functions of CMultiDocTemplate except the constructor. The framework handles CMultiDocTemplate objects internally.

For more information on CMultiDocTemplate, see Document Templates and the Document/View Creation Process in Visual C++ Programmer’s Guide.

include# <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MULTIPAD

See Also CDocTemplate, CSingleDocTemplate, CWinApp


CMultiDocTemplate Class Members

Construction

CMultiDocTemplate Constructs a CMultiDocTemplate object.


CMultiDocTemplate::CMultiDocTemplate

CMultiDocTemplate( UINT nIDResource, CRuntimeClass* pDocClass, CRuntimeClass* pFrameClass, CRuntimeClass* pViewClass );

Parameters

nIDResource

Specifies the ID of the resources used with the document type. This may include menu, icon, accelerator table, and string resources.

The string resource consists of up to seven substrings separated by the ‘\n’ character (the ‘\n’ character is needed as a place holder if a substring is not included; however, trailing ‘\n’ characters are not necessary); these substrings describe the document type. For information on the substrings, see CDocTemplate::GetDocString. This string resource is found in the application’s resource file. For example:

// MYCALC.RC
STRINGTABLE PRELOAD DISCARDABLE
BEGIN
    IDR_SHEETTYPE "\nSheet\nWorksheet\nWorksheets (*.myc)\n.myc\n MyCalcSheet\nMyCalc Worksheet"
END

Note that the string begins with a ‘\n’ character; this is because the first substring is not used for MDI applications and so is not included. You can edit this string using the string editor; the entire string appears as a single entry in the String Editor, not as seven separate entries.

For more information about these resource types, see Resource Editors in the Visual C++ User’s Guide.

pDocClass

Points to the CRuntimeClass object of the document class. This class is a CDocument-derived class you define to represent your documents.

pFrameClass

Points to the CRuntimeClass object of the frame-window class. This class can be a CMDIChildWnd-derived class, or it can be CMDIChildWnd itself if you want default behavior for your document frame windows.

pViewClass

Points to the CRuntimeClass object of the view class. This class is a CView-derived class you define to display your documents.

Remarks

Constructs a CMultiDocTemplate object. Dynamically allocate one CMultiDocTemplate object for each document type that your application supports and pass each one to CWinApp::AddDocTemplate from the InitInstance member function of your application class.

Example

//example for CMultiDocTemplate
BOOL CMyApp::InitInstance()
{
        // ...
        // Establish all of the document types
        // supported by the application

        AddDocTemplate( new CMultiDocTemplate( IDR_SHEETTYPE,
                            RUNTIME_CLASS( CSheetDoc ),
                            RUNTIME_CLASS( CMDIChildWnd ),
                            RUNTIME_CLASS( CSheetView ) ) );

        AddDocTemplate( new CMultiDocTemplate( IDR_NOTETYPE,
                            RUNTIME_CLASS( CNoteDoc ),
                            RUNTIME_CLASS( CMDIChildWnd ),
                            RUNTIME_CLASS( CNoteView ) ) );
        // ...
}

CMultiDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::GetDocString, CWinApp::AddDocTemplate, CWinApp::InitInstance, CRuntimeClass


CMultiLock

CMultiLock does not have a base class.

An object of class CMultiLock represents the access-control mechanism used in controlling access to resources in a multithreaded program. To use the synchronization classes CSemaphore, CMutex, and CEvent, you can create either a CMultiLock or CSingleLock object to wait on and release the synchronization object. Use CMultiLock when there are multiple objects that you could use at a particular time. Use CSingleLock when you only need to wait on one object at a time.

To use a CMultiLock object, first create an array of the synchronization objects that you wish to wait on. Next, call the CMultiLock object’s constructor inside a member function in the controlled resource’s class. Then call the Lock member function to determine if a resource is available (signaled). If one is, continue with the remainder of the member function. If no resource is available, either wait for a specified amount of time for a resource to be released, or return failure. After use of a resource is complete, either call the Unlock function if the CMultiLock object is to be used again, or allow the CMultiLock object to be destroyed.

CMultiLock objects are most useful when a thread has a large number of CEvent objects it can respond to. Create an array containing all the CEvent pointers, and call Lock. This will cause the thread to wait until one of the events is signaled.

For more information on how to use CMultiLock objects, see the article Multithreading: How to Use the Synchronization Classes in Visual C++ Programmer’s Guide.

#include <afxmt.h>


CMultiLock Class Members

Construction

CMultiLock Constructs a CMultiLock object.

Methods

IsLocked | Determines if a specific synchronization object in the array is locked.
Lock | Waits on the array of synchronization objects.
Unlock | Releases any owned synchronization objects.


CMultiLock::CMultiLock

CMultiLock( CSyncObject* ppObjects[ ], DWORD dwCount, BOOL bInitialLock = FALSE );

Parameters

ppObjects

Array of pointers to the synchronization objects to be waited on. Cannot be NULL.

dwCount

Number of objects in ppObjects. Must be greater than 0.

bInitialLock

Specifies whether to initially attempt to access any of the supplied objects.

Remarks

Constructs a CMultiLock object. This function is called after creating the array of synchronization objects to be waited on. It is usually called from within the thread that must wait for one of the synchronization objects to become available.


CMultiLock::IsLocked

BOOL IsLocked( DWORD dwObject );

Return Value

Nonzero if the specified object is locked; otherwise 0.

Parameters

dwObject

The index in the array of objects corresponding to the object whose state is being queried.

Remarks

Determines if the specified object is nonsignaled (unavailable).


CMultiLock::Lock

DWORD Lock( DWORD dwTimeOut = INFINITE, BOOL bWaitForAll = TRUE, DWORD dwWakeMask = 0 );

Return Value

If Lock fails, it returns – 1. If successful, it returns one of the following values:

  • Between WAIT_OBJECT_0 and WAIT_OBJECT_0 + (number of objects – 1)

    If bWaitForAll is TRUE, all objects are signaled (available). If bWaitForAll is FALSE, the return value – WAIT_OBJECT_0 is the index in the array of objects of the object that is signaled (available).

  • WAIT_OBJECT_0 + (number of objects)

    An event specified in dwWakeMask is available in the thread’s input queue.

  • Between WAIT_ABANDONED_0 and WAIT_ABANDONED_0 + (number of objects – 1)

    If bWaitForAll is TRUE, all objects are signaled, and at least one of the objects is an abandoned mutex object. If bWaitForAll is FALSE, the return value – WAIT_ABANDONED_0 is the index in the array of objects of the abandoned mutex object that satisfied the wait.

  • WAIT_TIMEOUT

    The timeout interval specified in dwTimeOut expired without the wait succeeding.

Parameters

dwTimeOut

Specifies the amount of time to wait for the synchronization object to be available (signaled). If INFINITE, Lock will wait until the object is signaled before returning.

bWaitForAll

Specifies whether all objects waited on must become signaled at the same time before returning. If FALSE, Lock will return when any one of the objects waited on is signaled.

dwWakeMask

Specifies other conditions that are allowed to abort the wait. For a full list of the available options for this parameter, see MsgWaitForMultipleObjects in the Win32 Programmer’s Reference.

Remarks

Call this function to gain access to one or more of the resources controlled by the synchronization objects supplied to the CMultiLock constructor. If bWaitForAll is TRUE, Lock will return successfully as soon as all the synchronization objects become signaled simultaneously. If bWaitForAll is FALSE, Lock will return as soon as one or more of the synchronization objects becomes signaled.

If Lock is not able to return immediately, it will wait for no more than the number of milliseconds specified in the dwTimeOut parameter before returning. If dwTimeOut is INFINITE, Lock will not return until access to an object is gained or a condition specified in dwWakeMask was met. Otherwise, if Lock was able to acquire a synchronization object, it will return successfully; if not, it will return failure.


CMultiLock::Unlock

BOOL Unlock( );

BOOL Unlock( LONG lCount, LPLONG lPrevCount = NULL );

Return Value

Nonzero if the function was successful; otherwise 0.

Parameters

lCount

Number of reference counts to release. Must be greater than 0. If the specified amount would cause the object’s count to exceed its maximum, the count is not changed and the function returns FALSE.

lPrevCount

Points to a variable to receive the previous count for the synchronization object. If NULL, the previous count is not returned.

Remarks

Releases the synchronization object owned by CMultiLock. This function is called by CMultiLock’s destructor.

The first form of Unlock tries to unlock the synchronization object managed by CMultiLock. The second form of Unlock tries to unlock the CSemaphore objects owned by CMultiLock. If CMultiLock does not own any locked CSemaphore object, the function returns FALSE; otherwise, it returns TRUE. lCount and lpPrevCount are exactly the same as the parameters of CSingleLock::Unlock. The second form of Unlock is rarely applicable to multilock situations.


CMutex

An object of class CMutex represents a “mutex” — a synchronization object that allows one thread mutually exclusive access to a resource. Mutexes are useful when only one thread at a time can be allowed to modify data or some other controlled resource. For example, adding nodes to a linked list is a process that should only be allowed by one thread at a time. By using a CMutex object to control the linked list, only one thread at a time can gain access to the list.

To use a CMutex object, construct the CMutex object when it is needed. Specify the name of the mutex you wish to wait on, and that your application should initially own it. You can then access the mutex when the constructor returns. Call CSyncObject::Unlock when you are done accessing the controlled resource.

An alternative method for using CMutex objects is to add a variable of type CMutex as a data member to the class you wish to control. During construction of the controlled object, call the constructor of the CMutex data member specifying if the mutex is initially owned, the name of the mutex (if it will be used across process boundaries), and desired security attributes.

To access resources controlled by CMutex objects in this manner, first create a variable of either type CSingleLock or type CMultiLock in your resource’s access member function. Then call the lock object’s Lock member function (for example, CSingleLock::Lock). At this point, your thread will either gain access to the resource, wait for the resource to be released and gain access, or wait for the resource to be released and time out, failing to gain access to the resource. In any case, your resource has been accessed in a thread-safe manner. To release the resource, use the lock object’s Unlock member function (for example, CSingleLock::Unlock), or allow the lock object to fall out of scope.

For more information on using CMutex objects, see the article Multithreading: How to Use the Synchronization Classes in Visual C++ Programmer’s Guide.

#include <afxmt.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MUTEXES


CMutex Class Members

Construction

CMutex Constructs a CMutex object.


CMutex::CMutex

CMutex( BOOL bInitiallyOwn = FALSE, LPCTSTR lpszName = NULL, LPSECURITY_ATTRIBUTES lpsaAttribute = NULL );

Parameters

bInitiallyOwn

Specifies if the thread creating the CMutex object initially has access to the resource controlled by the mutex.

lpszName

Name of the CMutex object. If another mutex with the same name exists, lpszName must be supplied if the object will be used across process boundaries. If NULL, the mutex will be unnamed. If the name matches an existing mutex, the constructor builds a new CMutex object which references the mutex of that name. If the name matches an existing synchronization object that is not a mutex, the construction will fail.

lpsaAttribute

Security attributes for the mutex object. For a full description of this structure, see SECURITY_ATTRIBUTES in the Win32 Programmer’s Reference.

Remarks

Constructs a named or unnamed CMutex object. To access or release a CMutex object, create a CMultiLock or CSingleLock object and call its Lock and Unlock member functions. If the CMutex object is being used stand-alone, call its Unlock member function to release it.


CNotSupportedException

A CNotSupportedException object represents an exception that is the result of a request for an unsupported feature. No further qualification is necessary or possible.

For more information on using CNotSupportedException, see the article Exceptions in Visual C++ Programmer’s Guide.

#include <afx.h>


CNotSupportedException Class Members

Construction

CNotSupportedException Constructs a CNotSupportedException object.


CNotSupportedException::CNotSupportedException

CNotSupportedException( );

Remarks

Constructs a CNotSupportedException object.

Do not use this constructor directly, but rather call the global function AfxThrowNotSupportedException. For more information about exception processing, see the article Exceptions in Visual C++ Programmer’s Guide.

CNotSupportedException Overview | Class Members | Hierarchy Chart

See Also AfxThrowNotSupportedException


CObArray

The CObArray class supports arrays of CObject pointers. These object arrays are similar to C arrays, but they can dynamically shrink and grow as necessary.

Array indexes always start at position 0. You can decide whether to fix the upper bound or allow the array to expand when you add elements past the current bound. Memory is allocated contiguously to the upper bound, even if some elements are null.

Under Win32, the size of a CObArray object is limited only to available memory.

As with a C array, the access time for a CObArray indexed element is constant and is independent of the array size.

CObArray incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. If an array of CObject pointers is stored to an archive, either with the overloaded insertion operator or with the Serialize member function, each CObject element is, in turn, serialized along with its array index.

If you need a dump of individual CObject elements in an array, you must set the depth of the CDumpContext object to 1 or greater.

When a CObArray object is deleted, or when its elements are removed, only the CObject pointers are removed, not the objects they reference.

Note Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

Array class derivation is similar to list derivation. For details on the derivation of a special-purpose list class, see the article Collections in Visual C++ Programmer’s Guide.

Note You must use the IMPLEMENT_SERIAL macro in the implementation of your derived class if you intend to serialize the array.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

See Also CStringArray, CPtrArray, CByteArray, CWordArray, CDWordArray


CObArray Class Members

Construction

CObArray Constructs an empty array for CObject pointers.

Bounds

GetSize | Gets the number of elements in this array.
GetUpperBound | Returns the largest valid index.
SetSize | Sets the number of elements to be contained in this array.

Operations

FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.

Element Access

GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; array not allowed to grow.
ElementAt | Returns a temporary reference to the element pointer within the array.
GetData | Allows access to elements in the array. Can be NULL.

Growing the Array

SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds an element to the end of the array; grows the array if necessary.
Append | Appends another array to the array; grows the array if necessary.
Copy | Copies another array to the array; grows the array if necessary.

Insertion/Removal

InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.

Operators

operator [] Sets or gets the element at the specified index.


CObArray::Add

int Add( CObject* newElement );
throw( CMemoryException );

Return Value

The index of the added element.

Parameters

newElement

The CObject pointer to be added to this array.

Remarks

Adds a new element to the end of an array, growing the array by 1. If SetSize has been used with an nGrowBy value greater than 1, then extra memory may be allocated. However, the upper bound will increase by only 1.

The following table shows other member functions that are similar to CObArray::Add.

Class Member Function
CByteArray int Add( BYTE newElement );
 throw( CMemoryException );
CDWordArray int Add( DWORD newElement );
 throw( CMemoryException );
CPtrArray int Add( void* newElement );
 throw( CMemoryException );
CStringArray int Add( LPCTSTR newElement );
 throw( CMemoryException );
CUIntArray int Add( UINT newElement );
 throw( CMemoryException );
CWordArray int Add( WORD newElement );
 throw( CMemoryException );

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::Add

    CObArray array;

    array.Add( new CAge( 21 ) ); // Element 0
    array.Add( new CAge( 40 ) ); // Element 1
#ifdef _DEBUG
    afxDump.SetDepth( 1 );
    afxDump << "Add example: " << &array << "\n";
#endif

The results from this program are as follows:

Add example: A CObArray with 2 elements
    [0] = a CAge at $442A 21
    [1] = a CAge at $4468 40

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::SetAt, CObArray::SetAtGrow, CObArray::InsertAt, CObArray::operator []


CObArray::Append

int Append( const CObArray& src );

Return Value

The index of the first appended element.

Parameters

src

Source of the elements to be appended to the array.

Remarks

Call this member function to add the contents of another array to the end of the given array. The arrays must be of the same type.

If necessary, Append may allocate extra memory to accommodate the elements appended to the array.

The following table shows other member functions that are similar to CObArray::Append.

Class | Member Function
CByteArray | int Append( const CByteArray& src );
CDWordArray | int Append( const CDWordArray& src );
CPtrArray | int Append( const CPtrArray& src );
CStringArray | int Append( const CStringArray& src );
CUIntArray | int Append( const CUIntArray& src );
CWordArray | int Append( const CWordArray& src );

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::Copy


CObArray::Copy

void Copy( const CObArray& src );

Parameters

src

Source of the elements to be copied to the array.

Remarks

Call this member function to overwrite the elements of the given array with the elements of another array of the same type.

Copy does not free memory; however, if necessary, Copy may allocate extra memory to accommodate the elements copied to the array.

The following table shows other member functions that are similar to CObArray::Copy.

Class | Member Function
CByteArray | void Copy( const CByteArray& src );
CDWordArray | void Copy( const CDWordArray& src );
CPtrArray | void Copy( const CPtrArray& src );
CStringArray | void Copy( const CStringArray& src );
CUIntArray | void Copy( const CUIntArray& src );
CWordArray | void Copy( const CWordArray& src );

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::Append


CObArray::CObArray

CObArray( );

Remarks

Constructs an empty CObject pointer array. The array grows one element at a time.

The following table shows other constructors that are similar to CObArray::CObArray.

Class | Constructor
CByteArray | CByteArray( );
CDWordArray | CDWordArray( );
CPtrArray | CPtrArray( );
CStringArray | CStringArray( );
CUIntArray | CUIntArray( );
CWordArray | CWordArray( );

Example

CObArray array; //Array with default blocksize
CObArray* pArray = new CObArray; //Array on the heap with default blocksize

CObArray Overview | Class Members | Hierarchy Chart

See Also CObList::CObList


CObArray::ElementAt

CObject*& ElementAt( int nIndex );

Return Value

A reference to a CObject pointer.

Parameters

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

Remarks

Returns a temporary reference to the element pointer within the array. It is used to implement the left-side assignment operator for arrays. Note that this is an advanced function that should be used only to implement special array operators.

The following table shows other member functions that are similar to CObArray::ElementAt.

Class | Member Function
CByteArray | BYTE& ElementAt( int nIndex );
CDWordArray | DWORD& ElementAt( int nIndex );
CPtrArray | void*& ElementAt( int nIndex );
CStringArray | CString& ElementAt( int nIndex );
CUIntArray | UINT& ElementAt( int nIndex );
CWordArray | WORD& ElementAt( int nIndex );

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::operator []


CObArray::FreeExtra

void FreeExtra( );

Remarks

Frees any extra memory that was allocated while the array was grown. This function has no effect on the size or upper bound of the array.

The following table shows other member functions that are similar to CObArray::FreeExtra.

Class | Member Function
CByteArray | void FreeExtra( );
CDWordArray | void FreeExtra( );
CPtrArray | void FreeExtra( );
CStringArray | void FreeExtra( );
CUIntArray | void FreeExtra( );
CWordArray | void FreeExtra( );


CObArray::GetAt

CObject* GetAt( int nIndex ) const;

Return Value

The CObject pointer element currently at this index.

Parameters

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

Remarks

Returns the array element at the specified index.

Note Passing a negative value or a value greater than the value returned by GetUpperBound will result in a failed assertion.

The following table shows other member functions that are similar to CObArray::GetAt.

Class | Member Function
CByteArray | BYTE GetAt( int nIndex ) const;
CDWordArray | DWORD GetAt( int nIndex ) const;
CPtrArray | void* GetAt( int nIndex ) const;
CStringArray | CString GetAt( int nIndex ) const;
CUIntArray | UINT GetAt( int nIndex ) const;
CWordArray | WORD GetAt( int nIndex ) const;

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::GetAt

CObArray array;

array.Add( new CAge( 21 ) ); // Element 0
array.Add( new CAge( 40 ) ); // Element 1
ASSERT( *(CAge*) array.GetAt( 0 ) == CAge( 21 ) );

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::SetAt, CObArray::operator []


CObArray::GetData

const CObject** GetData( ) const;

CObject** GetData( );

Return Value

A pointer to the array of CObject pointers.

Remarks

Use this member function to gain direct access to the elements in the array. If no elements are available, GetData returns a null value.

While direct access to the elements of an array can help you work more quickly, use caution when calling GetData; any errors you make directly affect the elements of your array.

The following table shows other member functions that are similar to CObArray::GetData.

Class Member Function
CByteArray const BYTE* GetData( ) const;
BYTE* GetData( );
CDWordArray const DWORD* GetData( ) const;
DWORD* GetData( );
CPtrArray const void** GetData( ) const;
void** GetData( );
CStringArray const CString* GetData( ) const;
CString* GetData( );
CUIntArray const UINT* GetData( ) const;
UINT* GetData( );
CWordArray const WORD* GetData( ) const;
WORD* GetData( );

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::GetAt, CObArray::SetAt, CObArray::ElementAt


CObArray::GetSize

int GetSize( ) const;

Remarks

Returns the size of the array. Since indexes are zero-based, the size is 1 greater than the largest index.

The following table shows other member functions that are similar to CObArray::GetSize.

Class | Member Function
CByteArray | int GetSize( ) const;
CDWordArray | int GetSize( ) const;
CPtrArray | int GetSize( ) const;
CStringArray | int GetSize( ) const;
CUIntArray | int GetSize( ) const;
CWordArray | int GetSize( ) const;

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::GetUpperBound, CObArray::SetSize


CObArray::GetUpperBound

int GetUpperBound( ) const;

Return Value

The index of the upper bound (zero-based).

Remarks

Returns the current upper bound of this array. Because array indexes are zero-based, this function returns a value 1 less than GetSize.

The condition GetUpperBound( ) = –1 indicates that the array contains no elements.

The following table shows other member functions that are similar to CObArray::GetUpperBound.

Class | Member Function
CByteArray | int GetUpperBound( ) const;
CDWordArray | int GetUpperBound( ) const;
CPtrArray | int GetUpperBound( ) const;
CStringArray | int GetUpperBound( ) const;
CUIntArray | int GetUpperBound( ) const;
CWordArray | int GetUpperBound( ) const;

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::GetUpperBound

CObArray array;

array.Add( new CAge( 21 ) ); // Element 0
array.Add( new CAge( 40 ) ); // Element 1
ASSERT( array.GetUpperBound() == 1 ); // Largest index

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::GetSize, CObArray::SetSize


CObArray::InsertAt

void InsertAt( int nIndex, CObject* newElement, int nCount = 1 );
throw( CMemoryException );

void InsertAt( int nStartIndex, CObArray* pNewArray );
throw( CMemoryException );

Parameters

nIndex

An integer index that may be greater than the value returned by GetUpperBound.

newElement

The CObject pointer to be placed in this array. A newElement of value NULL is allowed.

nCount

The number of times this element should be inserted (defaults to 1).

nStartIndex

An integer index that may be greater than the value returned by GetUpperBound.

pNewArray

Another array that contains elements to be added to this array.

Remarks

The first version of InsertAt inserts one element (or multiple copies of an element) at a specified index in an array. In the process, it shifts up (by incrementing the index) the existing element at this index, and it shifts up all the elements above it.

The second version inserts all the elements from another CObArray collection, starting at the nStartIndex position.

The SetAt function, in contrast, replaces one specified array element and does not shift any elements.

The following table shows other member functions that are similar to CObArray::InsertAt.

Class Member Function
CByteArray void InsertAt( int nIndex, BYTE newElement, int nCount = 1 );
 throw( CMemoryException );

void InsertAt( int nStartIndex, CByteArray* pNewArray );
 throw( CMemoryException );
CDWordArray void InsertAt( int nIndex, DWORD newElement, int nCount = 1 );
 throw( CMemoryException );

void InsertAt( int nStartIndex, CDWordArray* pNewArray );
 throw( CMemoryException );
CPtrArray void InsertAt( int nIndex, void* newElement, int nCount = 1 );
 throw( CMemoryException );

void InsertAt( int nStartIndex, CPtrArray* pNewArray );
 throw( CMemoryException );
CStringArray void InsertAt( int nIndex, LPCTSTR newElement, int nCount = 1 );
 throw( CMemoryException );

void InsertAt( int nStartIndex, CStringArray* pNewArray );
 throw( CMemoryException );
CUIntArray void InsertAt( int nIndex, UINT newElement, int nCount = 1 );
 throw( CMemoryException );

void InsertAt( int nStartIndex, CUIntArray* pNewArray );
 throw( CMemoryException );
CWordArray void InsertAt( int nIndex, WORD newElement, int nCount = 1 );
 throw( CMemoryException );

void InsertAt( int nStartIndex, CWordArray* pNewArray );
 throw( CMemoryException );

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::InsertAt

    CObArray array;

    array.Add( new CAge( 21 ) ); // Element 0
    array.Add( new CAge( 40 ) ); // Element 1 (will become 2).
    array.InsertAt( 1, new CAge( 30 ) );  // New element 1
#ifdef _DEBUG
    afxDump.SetDepth( 1 );
    afxDump << "InsertAt example: " << &array << "\n";
#endif

The results from this program are as follows:

InsertAt example: A CObArray with 3 elements
    [0] = a CAge at $45C8 21
    [1] = a CAge at $4646 30
    [2] = a CAge at $4606 40

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::SetAt, CObArray::RemoveAt


CObArray::RemoveAll

void RemoveAll( );

Remarks

Removes all the pointers from this array but does not actually delete the CObject objects. If the array is already empty, the function still works.

The RemoveAll function frees all memory used for pointer storage.

The following table shows other member functions that are similar to CObArray::RemoveAll.

Class | Member Function
CByteArray | void RemoveAll( );
CDWordArray | void RemoveAll( );
CPtrArray | void RemoveAll( );
CStringArray | void RemoveAll( );
CUIntArray | void RemoveAll( );
CWordArray | void RemoveAll( );

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::RemoveAll

CObArray array;
CAge* pa1;
CAge* pa2;

array.Add( pa1 = new CAge( 21 ) ); // Element 0
array.Add( pa2 = new CAge( 40 ) ); // Element 1
ASSERT( array.GetSize() == 2 );
array.RemoveAll(); // Pointers removed but objects not deleted.
ASSERT( array.GetSize() == 0 );
delete pa1;
delete pa2;  // Cleans up memory.


CObArray::RemoveAt

void RemoveAt( int nIndex, int nCount = 1 );

Parameters

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

nCount

The number of elements to remove.

Remarks

Removes one or more elements starting at a specified index in an array. In the process, it shifts down all the elements above the removed element(s). It decrements the upper bound of the array but does not free memory.

If you try to remove more elements than are contained in the array above the removal point, then the Debug version of the library asserts.

The RemoveAt function removes the CObject pointer from the array, but it does not delete the object itself.

The following table shows other member functions that are similar to CObArray::RemoveAt.

Class | Member Function
CByteArray | void RemoveAt( int nIndex, int nCount = 1 );
CDWordArray | void RemoveAt( int nIndex, int nCount = 1 );
CPtrArray | void RemoveAt( int nIndex, int nCount = 1 );
CStringArray | void RemoveAt( int nIndex, int nCount = 1 );
CUIntArray | void RemoveAt( int nIndex, int nCount = 1 );
CWordArray | void RemoveAt( int nIndex, int nCount = 1 );

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::RemoveAt

   CObArray array;
   CObject* pa;

   array.Add( new CAge( 21 ) ); // Element 0
   array.Add( new CAge( 40 ) ); // Element 1
   if( ( pa = array.GetAt( 0 ) ) != NULL )
   {
       array.RemoveAt( 0 );  // Element 1 moves to 0.
       delete pa; // Delete the original element at 0.
   }
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "RemoveAt example: " << &array << "\n";
#endif

The results from this program are as follows:

RemoveAt example: A CObArray with 1 elements
    [0] = a CAge at $4606 40

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::SetAt, CObArray::SetAtGrow, CObArray::InsertAt


CObArray::SetAt

void SetAt( int nIndex, CObject* newElement );

Parameters

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

newElement

The object pointer to be inserted in this array. A NULL value is allowed.

Remarks

Sets the array element at the specified index. SetAt will not cause the array to grow. Use SetAtGrow if you want the array to grow automatically.

You must ensure that your index value represents a valid position in the array. If it is out of bounds, then the Debug version of the library asserts.

The following table shows other member functions that are similar to CObArray::SetAt.

Class | Member Function
CByteArray | void SetAt( int nIndex, BYTE newElement );
CDWordArray | void SetAt( int nIndex, DWORD newElement );
CPtrArray | void SetAt( int nIndex, void* newElement );
CStringArray | void SetAt( int nIndex, LPCTSTR newElement );
CUIntArray | void SetAt( int nIndex, UINT newElement );
CWordArray | void SetAt( int nIndex, WORD newElement );

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::SetAt

   CObArray array;
   CObject* pa;

   array.Add( new CAge( 21 ) ); // Element 0
   array.Add( new CAge( 40 ) ); // Element 1
   if( ( pa = array.GetAt( 0 ) ) != NULL )
   {
       array.SetAt( 0, new CAge( 30 ) );  // Replace element 0.
       delete pa; // Delete the original element at 0.
   }
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "SetAt example: " << &array << "\n";
#endif

The results from this program are as follows:

SetAt example: A CObArray with 2 elements
    [0] = a CAge at $47E0 30
    [1] = a CAge at $47A0 40

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::GetAt, CObArray::SetAtGrow, CObArray::ElementAt, CObArray::operator []


CObArray::SetAtGrow

void SetAtGrow( int nIndex, CObject* newElement );
throw( CMemoryException );

Parameters

nIndex

An integer index that is greater than or equal to 0.

newElement

The object pointer to be added to this array. A NULL value is allowed.

Remarks

Sets the array element at the specified index. The array grows automatically if necessary (that is, the upper bound is adjusted to accommodate the new element).

The following table shows other member functions that are similar to CObArray::SetAtGrow.

Class Member Function
CByteArray void SetAtGrow( int nIndex, BYTE newElement );
 throw( CMemoryException );
CDWordArray void SetAtGrow( int nIndex, DWORD newElement );
 throw( CMemoryException );
CPtrArray void SetAtGrow( int nIndex, void* newElement );
 throw( CMemoryException );
CStringArray void SetAtGrow( int nIndex, LPCTSTR newElement );
 throw( CMemoryException );
CUIntArray void SetAtGrow( int nIndex, UINT newElement );
 throw( CMemoryException );
CWordArray void SetAtGrow( int nIndex, WORD newElement );
 throw( CMemoryException );

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::SetAtGrow

   CObArray array;

   array.Add( new CAge( 21 ) ); // Element 0
   array.Add( new CAge( 40 ) ); // Element 1
   array.SetAtGrow( 3, new CAge( 65 ) ); // Element 2 deliberately
                                         // skipped.
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "SetAtGrow example: " << &array << "\n";
#endif

The results from this program are as follows:

SetAtGrow example: A CObArray with 4 elements
    [0] = a CAge at $47C0 21
    [1] = a CAge at $4800 40
    [2] = NULL
    [3] = a CAge at $4840 65

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::GetAt, CObArray::SetAt, CObArray::ElementAt, CObArray::operator []


CObArray::SetSize

void SetSize( int nNewSize, int nGrowBy = -1 );
throw( CMemoryException );

Parameters

nNewSize

The new array size (number of elements). Must be greater than or equal to 0.

nGrowBy

The minimum number of element slots to allocate if a size increase is necessary.

Remarks

Establishes the size of an empty or existing array; allocates memory if necessary. If the new size is smaller than the old size, then the array is truncated and all unused memory is released. For efficiency, call SetSize to set the size of the array before using it. This prevents the need to reallocate and copy the array each time an item is added.

The nGrowBy parameter affects internal memory allocation while the array is growing. Its use never affects the array size as reported by GetSize and GetUpperBound.

The following table shows other member functions that are similar to CObArray::SetSize.

Class Member Function
CByteArray void SetSize( int nNewSize, int nGrowBy = -1 );
 throw( CMemoryException );
CDWordArray void SetSize( int nNewSize, int nGrowBy = -1 );
 throw( CMemoryException );
CPtrArray void SetSize( int nNewSize, int nGrowBy = -1 );
 throw( CMemoryException );
CStringArray void SetSize( int nNewSize, int nGrowBy = -1 );
 throw( CMemoryException );
CUIntArray void SetSize( int nNewSize, int nGrowBy = -1 );
 throw( CMemoryException );
CWordArray void SetSize( int nNewSize, int nGrowBy = -1 );
 throw( CMemoryException );


CObArray::operator [ ]

CObject*& operator []( int nIndex );

CObject* operator []( int nIndex ) const;

Remarks

These subscript operators are a convenient substitute for the SetAt and GetAt functions.

The first operator, called for arrays that are not const, may be used on either the right (r-value) or the left (l-value) of an assignment statement. The second, called for const arrays, may be used only on the right.

The Debug version of the library asserts if the subscript (either on the left or right side of an assignment statement) is out of bounds.

The following table shows other operators that are similar to CObArray::operator [].

Class Operator
CByteArray BYTE& operator []( int nIndex );
BYTE operator []( int nIndex ) const;
CDWordArray DWORD& operator []( int nIndex );
DWORD operator []( int nIndex ) const;
CPtrArray void*& operator []( int nIndex );
void* operator []( int nIndex ) const;
CStringArray CString& operator []( int nIndex );
CString operator []( int nIndex ) const;
CUIntArray UINT& operator []( int nIndex );
UINT operator []( int nIndex ) const;
CWordArray WORD& operator []( int nIndex );
WORD operator []( int nIndex ) const;

Example

See CObList::CObList for a listing of the CAge class used in all collection examples.

// example for CObArray::operator []

CObArray array;
CAge* pa;

array.Add( new CAge( 21 ) ); // Element 0
array.Add( new CAge( 40 ) ); // Element 1
pa = (CAge*)array[0]; // Get element 0
ASSERT( *pa == CAge( 21 ) ); // Get element 0
array[0] = new CAge( 30 ); // Replace element 0
delete pa;
ASSERT( *(CAge*) array[0] == CAge( 30 ) ); // Get new element 0

CObArray Overview | Class Members | Hierarchy Chart

See Also CObArray::GetAt, CObArray::SetAt


CObject

CObject is the principal base class for the Microsoft Foundation Class Library. It serves as the root not only for library classes such as CFile and CObList, but also for the classes that you write. CObject provides basic services, including

  • Serialization support

  • Run-time class information

  • Object diagnostic output

  • Compatibility with collection classes

Note that CObject does not support multiple inheritance. Your derived classes can have only one CObject base class, and that CObject must be leftmost in the hierarchy. It is permissible, however, to have structures and non-CObject-derived classes in right-hand multiple-inheritance branches.

You will realize major benefits from CObject derivation if you use some of the optional macros in your class implementation and declarations.

The first-level macros, DECLARE_DYNAMIC and IMPLEMENT_DYNAMIC, permit run-time access to the class name and its position in the hierarchy. This, in turn, allows meaningful diagnostic dumping.

The second-level macros, DECLARE_SERIAL and IMPLEMENT_SERIAL, include all the functionality of the first-level macros, and they enable an object to be “serialized” to and from an “archive.”

For information about deriving Microsoft Foundation classes and C++ classes in general and using CObject, see CObject Class Topics and Serialization (Object Persistence) in Visual C++ Programmer’s Guide.

#include <afx.h>


CObject Class Members

Construction

CObject | Default constructor.
CObject | Copy constructor.
operator new | Special new operator.
operator delete | Special delete operator.
operator = | Assignment operator.

Diagnostics

AssertValid | Validates this object’s integrity.
Dump | Produces a diagnostic dump of this object.

Serialization

IsSerializable | Tests to see whether this object can be serialized.
Serialize | Loads or stores an object from/to an archive.

Miscellaneous

GetRuntimeClass | Returns the CRuntimeClass structure corresponding to this object’s class.
IsKindOf | Tests this object’s relationship to a given class.


CObject::AssertValid

virtual void AssertValid( ) const;

Remarks

AssertValid performs a validity check on this object by checking its internal state. In the Debug version of the library, AssertValid may assert and thus terminate the program with a message that lists the line number and filename where the assertion failed.

When you write your own class, you should override the AssertValid function to provide diagnostic services for yourself and other users of your class. The overridden AssertValid usually calls the AssertValid function of its base class before checking data members unique to the derived class.

Because AssertValid is a const function, you are not permitted to change the object state during the test. Your own derived class AssertValid functions should not throw exceptions but rather should assert whether they detect invalid object data.

The definition of “validity” depends on the object’s class. As a rule, the function should perform a “shallow check.” That is, if an object contains pointers to other objects, it should check to see whether the pointers are not null, but it should not perform validity testing on the objects referred to by the pointers.

Example

See CObList::CObList for a listing of the CAge class used in all CObject examples.

// example for CObject::AssertValid
void CAge::AssertValid() const
{
    CObject::AssertValid();
    ASSERT( m_years > 0 );
    ASSERT( m_years < 105 );
}


CObject::CObject

CObject( );

CObject( constCObject& objectSrc );

Parameters

objectSrc

A reference to another CObject

Remarks

These functions are the standard CObject constructors. The default version is automatically called by the constructor of your derived class.

If your class is serializable (it incorporates the IMPLEMENT_SERIAL macro), then you must have a default constructor (a constructor with no arguments) in your class declaration. If you do not need a default constructor, declare a private or protected “empty” constructor. For more information, see CObject Class Topics in Visual C++ Programmer’s Guide.

The standard C++ default class copy constructor does a member-by-member copy. The presence of the private CObject copy constructor guarantees a compiler error message if the copy constructor of your class is needed but not available. You must therefore provide a copy constructor if your class requires this capability.


CObject::Dump

virtual void Dump( CDumpContext& dc ) const;

Parameters

dc

The diagnostic dump context for dumping, usually afxDump.

Remarks

Dumps the contents of your object to a CDumpContext object.

When you write your own class, you should override the Dump function to provide diagnostic services for yourself and other users of your class. The overridden Dump usually calls the Dump function of its base class before printing data members unique to the derived class. CObject::Dump prints the class name if your class uses the IMPLEMENT_DYNAMIC or IMPLEMENT_SERIAL macro.

Note Your Dump function should not print a newline character at the end of its output.

Dump calls make sense only in the Debug version of the Microsoft Foundation Class Library. You should bracket calls, function declarations, and function implementations with #ifdef _DEBUG/#endif statements for conditional compilation.

Since Dump is a const function, you are not permitted to change the object state during the dump.

The CDumpContext insertion (<<) operator calls Dump when a CObject pointer is inserted.

Dump permits only “acyclic” dumping of objects. You can dump a list of objects, for example, but if one of the objects is the list itself, you will eventually overflow the stack.

Example

See CObList::CObList for a listing of the CAge class used in all CObject examples.

// example for CObject::Dump
void CAge::Dump( CDumpContext &dc ) const
 {
 CObject::Dump( dc );
 dc << "Age = " << m_years;
 }


CObject::GetRuntimeClass

virtual CRuntimeClass* GetRuntimeClass( ) const;

Return Value

A pointer to the CRuntimeClass structure corresponding to this object’s class; never NULL.

Remarks

There is one CRuntimeClass structure for each CObject-derived class. The structure members are as follows:

  • LPCSTR m_lpszClassName A null-terminated string containing the ASCII class name.

  • int m_nObjectSize The size of the object, in bytes. If the object has data members that point to allocated memory, the size of that memory is not included.

  • UINT m_wSchema The schema number ( – 1 for nonserializable classes). See the IMPLEMENT_SERIAL macro for a description of schema number.

  • CObject* ( PASCAL* m_pfnCreateObject )( ) A function pointer to the default constructor that creates an object of your class (valid only if the class supports dynamic creation; otherwise, returns NULL).

  • CRuntimeClass* ( PASCAL* m_pfn_GetBaseClass )( ) If your application is dynamically linked to the AFXDLL version of MFC, a pointer to a function that returns the CRuntimeClass structure of the base class.

  • CRuntimeClass* m_pBaseClass If your application is statically linked to MFC, a pointer to the CRuntimeClass structure of the base class.

Feature Only in Professional and Enterprise Editions Static linking to MFC is supported only in Visual C++ Professional and Enterprise Editions. For more information, see Visual C++ Editions.

This function requires use of the IMPLEMENT_DYNAMIC or IMPLEMENT_SERIAL macro in the class implementation. You will get incorrect results otherwise.

Example

See CObList::CObList for a listing of the CAge class used in all CObject examples.

// example for CObject::GetRuntimeClass
CAge a(21);
CRuntimeClass* prt = a.GetRuntimeClass();
ASSERT( strcmp( prt->m_lpszClassName, "CAge" )  == 0 );

CObject Overview | Class Members | Hierarchy Chart

See Also CObject::IsKindOf, RUNTIME_CLASS


CObject::IsKindOf

BOOL IsKindOf( const CRuntimeClass* pClass ) const;

Return Value

Nonzero if the object corresponds to the class; otherwise 0.

Parameters

pClass

A pointer to a CRuntimeClass structure associated with your CObject-derived class.

Remarks

Tests pClass to see if (1) it is an object of the specified class or (2) it is an object of a class derived from the specified class. This function works only for classes declared with the DECLARE_DYNAMIC or DECLARE_SERIAL macro.

Do not use this function extensively because it defeats the C++ polymorphism feature. Use virtual functions instead.

Example

See CObList::CObList for a listing of the CAge class used in all CObject examples.

// example for CObject::IsKindOf
CAge a(21); // Must use IMPLEMENT_DYNAMIC or IMPLEMENT_SERIAL
ASSERT( a.IsKindOf( RUNTIME_CLASS( CAge ) ) );
ASSERT( a.IsKindOf( RUNTIME_CLASS( CObject ) ) );

CObject Overview | Class Members | Hierarchy Chart

See Also CObject::GetRuntimeClass, RUNTIME_CLASS, CObject Class: Accessing Run-Time Class Information


CObject::IsSerializable

BOOL IsSerializable( ) const;

Return Value

Nonzero if this object can be serialized; otherwise 0.

Remarks

Tests whether this object is eligible for serialization. For a class to be serializable, its declaration must contain the DECLARE_SERIAL macro, and the implementation must contain the IMPLEMENT_SERIAL macro.

Note Do not override this function.

Example

See CObList::CObList for a listing of the CAge class used in all CObject examples.

// example for CObject::IsSerializable
CAge a(21);
ASSERT( a.IsSerializable() );

CObject Overview | Class Members | Hierarchy Chart

See Also CObject::Serialize


CObject::Serialize

virtual void Serialize( CArchive& ar );
throw( CMemoryException );
throw( CArchiveException );
throw( CFileException );

Parameters

ar

A CArchive object to serialize to or from.

Remarks

Reads or writes this object from or to an archive.

You must override Serialize for each class that you intend to serialize. The overridden Serialize must first call the Serialize function of its base class.

You must also use the DECLARE_SERIAL macro in your class declaration, and you must use the IMPLEMENT_SERIAL macro in the implementation.

Use CArchive::IsLoading or CArchive::IsStoring to determine whether the archive is loading or storing.

Serialize is called by CArchive::ReadObject and CArchive::WriteObject. These functions are associated with the CArchive insertion operator (<<) and extraction operator (>>).

For serialization examples, see the article Serialization (Object Persistence) in Visual C++ Programmer’s Guide.

Example

See CObList::CObList for a listing of the CAge class used in all CObject examples.

// example for CObject::Serialize
void CAge::Serialize( CArchive& ar )
 {
 CObject::Serialize( ar );
     if( ar.IsStoring() )
     ar << m_years;
     else
     ar >> m_years;
 }


CObject::operator =

void operator =( const CObject& src );

Remarks

The standard C++ default class assignment behavior is a member-by-member copy. The presence of this private assignment operator guarantees a compiler error message if you assign without the overridden operator. You must therefore provide an assignment operator in your derived class if you intend to assign objects of your derived class.


CObject::operator delete

void operator delete( void* p );

Remarks

For the Release version of the library, operator delete simply frees the memory allocated by operator new. In the Debug version, operator delete participates in an allocation-monitoring scheme designed to detect memory leaks. If you override operators new and delete, you forfeit the diagnostic capability.

CObject Overview | Class Members | Hierarchy Chart

See Also CObject::operator new


CObject::operator new

void* operator new( size_t nSize );
throw( CMemoryException );

void* operator new( size_t nSize, LPCSTR lpszFileName, int nLine );
throw( CMemoryException );

Remarks

For the Release version of the library, operator new performs an optimal memory allocation in a manner similar to malloc. In the Debug version, operator new participates in an allocation-monitoring scheme designed to detect memory leaks.

If you use the code line

#define new DEBUG_NEW

before any of your implementations in a .CPP file, then the second version of new will be used, storing the filename and line number in the allocated block for later reporting. You do not have to worry about supplying the extra parameters; a macro takes care of that for you.

Even if you do not use DEBUG_NEW in Debug mode, you still get leak detection, but without the source-file line-number reporting described above.

Note If you override this operator, you must also override delete. Do not use the standard library _new_handler function.

CObject Overview | Class Members | Hierarchy Chart

See Also CObject::operator delete


CObList

The CObList class supports ordered lists of nonunique CObject pointers accessible sequentially or by pointer value. CObList lists behave like doubly-linked lists.

A variable of type POSITION is a key for the list. You can use a POSITION variable both as an iterator to traverse a list sequentially and as a bookmark to hold a place. A position is not the same as an index, however.

Element insertion is very fast at the list head, at the tail, and at a known POSITION. A sequential search is necessary to look up an element by value or index. This search can be slow if the list is long.

CObList incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. If a list of CObject pointers is stored to an archive, either with an overloaded insertion operator or with the Serialize member function, each CObject element is serialized in turn.

If you need a dump of individual CObject elements in the list, you must set the depth of the dump context to 1 or greater.

When a CObList object is deleted, or when its elements are removed, only the CObject pointers are removed, not the objects they reference.

You can derive your own classes from CObList. Your new list class, designed to hold pointers to objects derived from CObject, adds new data members and new member functions. Note that the resulting list is not strictly type safe, because it allows insertion of any CObject pointer.

Note You must use the IMPLEMENT_SERIAL macro in the implementation of your derived class if you intend to serialize the list.

For more information on using CObList, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

See Also CStringList, CPtrList


CObList Class Members

Construction

CObList Constructs an empty list for CObject pointers.

Head/Tail Access

GetHead | Returns the head element of the list (cannot be empty).
GetTail | Returns the tail element of the list (cannot be empty).

Operations

RemoveHead | Removes the element from the head of the list.
RemoveTail | Removes the element from the tail of the list.
AddHead | Adds an element (or all the elements in another list) to the head of the list (makes a new head).
AddTail | Adds an element (or all the elements in another list) to the tail of the list (makes a new tail).
RemoveAll | Removes all the elements from this list.

Iteration

GetHeadPosition | Returns the position of the head element of the list.
GetTailPosition | Returns the position of the tail element of the list.
GetNext | Gets the next element for iterating.
GetPrev | Gets the previous element for iterating.

Retrieval/Modification

GetAt | Gets the element at a given position.
SetAt | Sets the element at a given position.
RemoveAt | Removes an element from this list, specified by position.

Insertion

InsertBefore | Inserts a new element before a given position.
InsertAfter | Inserts a new element after a given position.

Searching

Find | Gets the position of an element specified by pointer value.
FindIndex | Gets the position of an element specified by a zero-based index.

Status

GetCount | Returns the number of elements in this list.
IsEmpty | Tests for the empty list condition (no elements).


CObList::AddHead

POSITION AddHead( CObject* newElement );
throw( CMemoryException );

void AddHead( CObList* pNewList );
throw( CMemoryException );

Return Value

The first version returns the POSITION value of the newly inserted element.

Parameters

newElement

The CObject pointer to be added to this list.

pNewList

A pointer to another CObList list. The elements in pNewList will be added to this list.

Remarks

Adds a new element or list of elements to the head of this list. The list can be empty before the operation.

Example

   CObList list;
   list.AddHead( new CAge( 21 ) ); // 21 is now at head.
   list.AddHead( new CAge( 40 ) ); // 40 replaces 21 at head.
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "AddHead example: " << &list << "\n";
#endif

The results from this program are as follows:

AddHead example: A CObList with 2 elements
    a CAge at $44A8 40
    a CAge at $442A 21

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetHead, CObList::RemoveHead


CObList::AddTail

POSITION AddTail( CObject* newElement );
throw( CMemoryException );

void AddTail( CObList* pNewList );
throw( CMemoryException );

Return Value

The first version returns the POSITION value of the newly inserted element.

Parameters

newElement

The CObject pointer to be added to this list.

pNewList

A pointer to another CObList list. The elements in pNewList will be added to this list.

Remarks

Adds a new element or list of elements to the tail of this list. The list can be empty before the operation.

Example

   CObList list;
   list.AddTail( new CAge( 21 ) );
   list.AddTail( new CAge( 40 ) ); // List now contains (21, 40).
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "AddTail example: " << &list << "\n";
#endif

The results from this program are as follows:

AddTail example: A CObList with 2 elements
     a CAge at $444A 21
     a CAge at $4526 40

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetTail, CObList::RemoveTail


CObList::CObList

CObList( int nBlockSize = 10 );

Parameters

nBlockSize

The memory-allocation granularity for extending the list.

Remarks

Constructs an empty CObject pointer list. As the list grows, memory is allocated in units of nBlockSize entries. If a memory allocation fails, a CMemoryException is thrown.

Example

Below is a listing of the CObject-derived class CAge used in all the collection examples:

// Simple CObject-derived class for CObList examples
class CAge : public CObject
{
    DECLARE_SERIAL( CAge )
private:
    int   m_years;
public:
    CAge() { m_years = 0; }
    CAge( int age ) { m_years = age; }
    CAge( const CAge& a ) { m_years = a.m_years; } // Copy constructor
    void Serialize( CArchive& ar);
    void AssertValid() const;
    const CAge& operator=( const CAge& a )
    {
        m_years = a.m_years; return *this;
    }
    BOOL operator==(CAge a)
    {
        return m_years == a.m_years;
    }
 #ifdef _DEBUG
    void Dump( CDumpContext& dc ) const
    {
        CObject::Dump( dc );
        dc << m_years;
    }
 #endif
};

Below is an example of CObList constructor usage:

CObList list( 20 );  // List on the stack with blocksize = 20.

CObList* plist = new CObList; // List on the heap with default
                              // blocksize.


CObList::Find

POSITION Find( CObject* searchValue, POSITION startAfter = NULL ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if the object is not found.

Parameters

searchValue

The object pointer to be found in this list.

startAfter

The start position for the search.

Remarks

Searches the list sequentially to find the first CObject pointer matching the specified CObject pointer. Note that the pointer values are compared, not the contents of the objects.

Example

CObList list;
CAge* pa1;
CAge* pa2;
POSITION pos;
list.AddHead( pa1 = new CAge( 21 ) );
list.AddHead( pa2 = new CAge( 40 ) );    // List now contains (40, 21).
if( ( pos = list.Find( pa1 ) ) != NULL ) // Hunt for pa1
{                                        // starting at head by default.
    ASSERT( *(CAge*) list.GetAt( pos ) == CAge( 21 ) );
}

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetNext, CObList::GetPrev


CObList::FindIndex

POSITION FindIndex( int nIndex ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if nIndex is too large. (The framework generates an assertion if nIndex is negative.)

Parameters

nIndex

The zero-based index of the list element to be found.

Remarks

Uses the value of nIndex as an index into the list. It starts a sequential scan from the head of the list, stopping on the nth element.

Example

CObList list;
POSITION pos;

list.AddHead( new CAge( 21 ) );
list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
if( ( pos = list.FindIndex( 0 )) != NULL )
{
    ASSERT( *(CAge*) list.GetAt( pos ) == CAge( 40 ) );
}

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::GetNext, CObList::GetPrev


CObList::GetAt

CObject*& GetAt( POSITION position );

CObject* GetAt( POSITION position ) const;

Return Value

See the return value description for GetHead.

Parameters

position

A POSITION value returned by a previous GetHeadPosition or Find member function call.

Remarks

A variable of type POSITION is a key for the list. It is not the same as an index, and you cannot operate on a POSITION value yourself. GetAt retrieves the CObject pointer associated with a given position.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

Example

See the example for FindIndex.

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::SetAt, CObList::GetNext, CObList::GetPrev, CObList::GetHead


CObList::GetCount

int GetCount( ) const;

Return Value

An integer value containing the element count.

Remarks

Gets the number of elements in this list.

Example

CObList list;

list.AddHead( new CAge( 21 ) );
list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
ASSERT( list.GetCount() == 2 );

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::IsEmpty


CObList::GetHead

CObject*& GetHead( );

CObject* GetHead( ) const;

Return Value

If the list is accessed through a pointer to a const CObList, then GetHead returns a CObject pointer. This allows the function to be used only on the right side of an assignment statement and thus protects the list from modification.

If the list is accessed directly or through a pointer to a CObList, then GetHead returns a reference to a CObject pointer. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Remarks

Gets the CObject pointer that represents the head element of this list.

You must ensure that the list is not empty before calling GetHead. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

Example

The following example illustrates the use of GetHead on the left side of an assignment statement.

   const CObList* cplist;

   CObList* plist = new CObList;
   CAge* page1 = new CAge( 21 );
   CAge* page2 = new CAge( 30 );
   CAge* page3 = new CAge( 40 );
   plist->AddHead( page1 );
   plist->AddHead( page2 );  // List now contains (30, 21).
   // The following statement REPLACES the head element.
   plist->GetHead() = page3; // List now contains (40, 21).
   ASSERT( *(CAge*) plist->GetHead() == CAge( 40 ) );
   cplist = plist;  // cplist is a pointer to a const list.
// cplist->GetHead() = page3; // Error: can't assign a pointer to a const list
   ASSERT( *(CAge*) plist->GetHead() == CAge( 40 ) ); // OK

   delete page1;
   delete page2;
   delete page3;
   delete plist; // Cleans up memory.

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetTail, CObList::GetTailPosition, CObList::AddHead, CObList::RemoveHead


CObList::GetHeadPosition

POSITION GetHeadPosition( ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if the list is empty.

Remarks

Gets the position of the head element of this list.

Example

CObList list;
POSITION pos;

list.AddHead( new CAge( 21 ) );
list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
if( ( pos = list.GetHeadPosition() ) != NULL )
{
    ASSERT( *(CAge*) list.GetAt( pos ) == CAge( 40 ) );
}

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetTailPosition


CObList::GetNext

CObject*& GetNext( POSITION& rPosition );

CObject* GetNext( POSITION& rPosition ) const;

Return Value

See the return value description for GetHead.

Parameters

rPosition

A reference to a POSITION value returned by a previous GetNext, GetHeadPosition, or other member function call.

Remarks

Gets the list element identified by rPosition, then sets rPosition to the POSITION value of the next entry in the list. You can use GetNext in a forward iteration loop if you establish the initial position with a call to GetHeadPosition or Find.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

If the retrieved element is the last in the list, then the new value of rPosition is set to NULL.

It is possible to remove an element during an iteration. See the example for RemoveAt.

Example

   CObList list;
   POSITION pos;
   list.AddHead( new CAge( 21 ) );
   list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
   // Iterate through the list in head-to-tail order.
#ifdef _DEBUG
   for( pos = list.GetHeadPosition(); pos != NULL; )
   {
    afxDump << list.GetNext( pos ) << "\n";
   }
#endif

The results from this program are as follows:

a CAge at $479C 40
a CAge at $46C0 21

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::GetHeadPosition, CObList::GetTailPosition, CObList::GetPrev, CObList::GetHead


CObList::GetPrev

CObject*& GetPrev( POSITION& rPosition );

CObject* GetPrev( POSITION& rPosition ) const;

Return Value

See the return value description for GetHead.

Parameters

rPosition

A reference to a POSITION value returned by a previous GetPrev or other member function call.

Remarks

Gets the list element identified by rPosition, then sets rPosition to the POSITION value of the previous entry in the list. You can use GetPrev in a reverse iteration loop if you establish the initial position with a call to GetTailPosition or Find.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

If the retrieved element is the first in the list, then the new value of rPosition is set to NULL.

Example

   CObList list;
   POSITION pos;

   list.AddHead( new CAge(21) );
   list.AddHead( new CAge(40) ); // List now contains (40, 21).
   // Iterate through the list in tail-to-head order.
   for( pos = list.GetTailPosition(); pos != NULL; )
   {
#ifdef _DEBUG
    afxDump << list.GetPrev( pos ) << "\n";
#endif
   }

The results from this program are as follows:

a CAge at $421C 21
a CAge at $421C 40

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::GetTailPosition, CObList::GetHeadPosition, CObList::GetNext, CObList::GetHead


CObList::GetTail

CObject*& GetTail( );

CObject* GetTail( ) const;

Return Value

See the return value description for GetHead.

Remarks

Gets the CObject pointer that represents the tail element of this list.

You must ensure that the list is not empty before calling GetTail. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

Example

CObList list;

list.AddHead( new CAge( 21 ) );
list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
ASSERT( *(CAge*) list.GetTail() == CAge( 21 ) );

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::AddTail, CObList::AddHead, CObList::RemoveHead, CObList::GetHead


CObList::GetTailPosition

POSITION GetTailPosition( ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if the list is empty.

Remarks

Gets the position of the tail element of this list; NULL if the list is empty.

Example

CObList list;
POSITION pos;

list.AddHead( new CAge( 21 ) );
list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
if( ( pos = list.GetTailPosition() ) != NULL )
{
    ASSERT( *(CAge*) list.GetAt( pos ) == CAge( 21 ) );
}

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetHeadPosition, CObList::GetTail


CObList::InsertAfter

POSITION InsertAfter( POSITION position, CObject* newElement );
throw ( CMemoryException );

Parameters

position

A POSITION value returned by a previous GetNext, GetPrev, or Find member function call.

newElement

The object pointer to be added to this list.

Remarks

Adds an element to this list after the element at the specified position.

Example

   CObList list;
   POSITION pos1, pos2;
   list.AddHead( new CAge( 21 ) );
   list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
   if( ( pos1 = list.GetHeadPosition() ) != NULL )
   {
       pos2 = list.InsertAfter( pos1, new CAge( 65 ) );
   }
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "InsertAfter example: " << &list << "\n";
#endif

The results from this program are as follows:

InsertAfter example: A CObList with 3 elements
     a CAge at $4A44 40
     a CAge at $4A64 65
     a CAge at $4968 21

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::InsertBefore


CObList::InsertBefore

POSITION InsertBefore( POSITION position, CObject* newElement );
throw ( CMemoryException );

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if the list is empty.

Parameters

position

A POSITION value returned by a previous GetNext, GetPrev, or Find member function call.

newElement

The object pointer to be added to this list.

Remarks

Adds an element to this list before the element at the specified position.

Example

   CObList list;
   POSITION pos1, pos2;
   list.AddHead( new CAge( 21 ) );
   list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
   if( ( pos1 = list.GetTailPosition() ) != NULL )
   {
       pos2 = list.InsertBefore( pos1, new CAge( 65 ) );
   }
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "InsertBefore example: " << &list << "\n";
#endif

The results from this program are as follows:

InsertBefore example: A CObList with 3 elements
    a CAge at $4AE2 40
    a CAge at $4B02 65
    a CAge at $49E6 21

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::InsertAfter


CObList::IsEmpty

BOOL IsEmpty( ) const;

Return Value

Nonzero if this list is empty; otherwise 0.

Remarks

Indicates whether this list contains no elements.

Example

See the example for RemoveAll.

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetCount


CObList::RemoveAll

void RemoveAll( );

Remarks

Removes all the elements from this list and frees the associated CObList memory. No error is generated if the list is already empty.

When you remove elements from a CObList, you remove the object pointers from the list. It is your responsibility to delete the objects themselves.

Example

CObList list;
CAge* pa1;
CAge* pa2;
ASSERT( list.IsEmpty()); // Yes it is.
list.AddHead( pa1 = new CAge( 21 ) );
list.AddHead( pa2 = new CAge( 40 ) ); // List now contains (40, 21).
ASSERT( !list.IsEmpty()); // No it isn't.
list.RemoveAll(); // CAge's aren't destroyed.
ASSERT( list.IsEmpty()); // Yes it is.
delete pa1;     // Now delete the CAge objects.
delete pa2;


CObList::RemoveAt

void RemoveAt( POSITION position );

Parameters

position

The position of the element to be removed from the list.

Remarks

Removes the specified element from this list.

When you remove an element from a CObList, you remove the object pointer from the list. It is your responsibility to delete the objects themselves.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

Example

Be careful when removing an element during a list iteration. The following example shows a removal technique that guarantees a valid POSITION value for GetNext.

   CObList list;
   POSITION pos1, pos2;
   CObject* pa;

   list.AddHead( new CAge( 21 ) );
   list.AddHead( new CAge( 40 ) );
   list.AddHead( new CAge( 65 ) ); // List now contains (65 40, 21).
   for( pos1 = list.GetHeadPosition(); ( pos2 = pos1 ) != NULL; )
   {
       if( *(CAge*) list.GetNext( pos1 ) == CAge( 40 ) )
       {
           pa = list.GetAt( pos2 ); // Save the old pointer for
                                  //deletion.
           list.RemoveAt( pos2 );
           delete pa; // Deletion avoids memory leak.
       }
   }
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "RemoveAt example: " << &list << "\n";
#endif

The results from this program are as follows:

RemoveAt example: A CObList with 2 elements
    a CAge at $4C1E 65
    a CAge at $4B22 21


CObList::RemoveHead

CObject* RemoveHead( );

Return Value

The CObject pointer previously at the head of the list.

Remarks

Removes the element from the head of the list and returns a pointer to it.

You must ensure that the list is not empty before calling RemoveHead. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

Example

CObList list;
CAge* pa1;
CAge* pa2;

list.AddHead( pa1 = new CAge( 21 ) );
list.AddHead( pa2 = new CAge( 40 ) ); // List now contains (40, 21).
ASSERT( *(CAge*) list.RemoveHead() == CAge( 40 ) );  // Old head
ASSERT( *(CAge*) list.GetHead() == CAge( 21 ) );  // New head
delete pa1;
delete pa2;

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetHead, CObList::AddHead


CObList::RemoveTail

CObject* RemoveTail( );

Return Value

A pointer to the object that was at the tail of the list.

Remarks

Removes the element from the tail of the list and returns a pointer to it.

You must ensure that the list is not empty before calling RemoveTail. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

Example

CObList list;
CAge* pa1;
CAge* pa2;

list.AddHead( pa1 = new CAge( 21 ) );
list.AddHead( pa2 = new CAge( 40 ) ); // List now contains (40, 21).
ASSERT( *(CAge*) list.RemoveTail() == CAge( 21 ) );  // Old tail
ASSERT( *(CAge*) list.GetTail() == CAge( 40 ) );  // New tail
delete pa1;
delete pa2; // Clean up memory.

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::GetTail, CObList::AddTail


CObList::SetAt

void SetAt( POSITION pos, CObject* newElement );

Parameters

pos

The POSITION of the element to be set.

newElement

The CObject pointer to be written to the list.

Remarks

A variable of type POSITION is a key for the list. It is not the same as an index, and you cannot operate on a POSITION value yourself. SetAt writes the CObject pointer to the specified position in the list.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

Example

   CObList list;
   CObject* pa;
   POSITION pos;

   list.AddHead( new CAge( 21 ) );
   list.AddHead( new CAge( 40 ) ); // List now contains (40, 21).
   if( ( pos = list.GetTailPosition()) != NULL )
   {
       pa = list.GetAt( pos ); // Save the old pointer for
                             //deletion.
       list.SetAt( pos, new CAge( 65 ) );  // Replace the tail
                                         //element.
       delete pa;  // Deletion avoids memory leak.
   }
#ifdef _DEBUG
   afxDump.SetDepth( 1 );
   afxDump << "SetAt example: " << &list << "\n";
#endif

The results from this program are as follows:

SetAt example: A CObList with 2 elements
    a CAge at $4D98 40
    a CAge at $4DB8 65

CObList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::GetAt, CObList::GetNext, CObList::GetPrev


COleBusyDialog

The COleBusyDialog class is used for the OLE Server Not Responding or Server Busy dialog boxes. Create an object of class COleBusyDialog when you want to call these dialog boxes. After a COleBusyDialog object has been constructed, you can use the m_bz structure to initialize the values or states of controls in the dialog box. The m_bz structure is of type OLEUIBUSY. For more information about using this dialog class, see the DoModal member function.

Note AppWizard-generated container code uses this class.

For more information, see the OLEUIBUSY structure in the OLE 2.01 User Interface Library.

For more information on OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

See Also COleDialog


COleBusyDialog Class Members

Data Members

m_bz Structure of type OLEUIBUSY that controls the behavior of the dialog box.

Construction

COleBusyDialog Constructs a COleBusyDialog object.

Operations

DoModal | Displays the OLE Server Busy dialog box.
GetSelectionType | Determines the choice made in the dialog box.


COleBusyDialog::COleBusyDialog

COleBusyDialog( HTASK htaskBusy, BOOL bNotResponding = FALSE, DWORD dwFlags = 0, CWnd* pParentWnd = NULL );

Parameters

htaskBusy

Handle to the server task that is busy.

bNotResponding

If TRUE, call the Not Responding dialog box instead of the Server Busy dialog box. The wording in the Not Responding dialog box is slightly different than the wording in the Server Busy dialog box, and the Cancel button is disabled.

dwFlags

Creation flag. Can contain zero or more of the following values combined with the bitwise-OR operator:

  • BZ_DISABLECANCELBUTTON Disable the Cancel button when calling the dialog box.

  • BZ_DISABLESWITCHTOBUTTON Disable the Switch To button when calling the dialog box.

  • BZ_DISABLERETRYBUTTON Disable the Retry button when calling the dialog box.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the parent window of the dialog object is set to the main application window.

Remarks

This function only constructs a COleBusyDialog object. To display the dialog box, call DoModal.

For more information, see the OLEUIBUSY structure in the OLE 2.01 User Interface Library.

COleBusyDialog Overview | Class Members | Hierarchy Chart

See Also COleBusyDialog::DoModal


COleBusyDialog::DoModal

virtual int DoModal( ) const;

Return Value

Completion status for the dialog box. One of the following values:

  • IDOK if the dialog box was successfully displayed.

  • IDCANCEL if the user canceled the dialog box.

  • IDABORT if an error occurred. If IDABORT is returned, call the COleDialog::GetLastError member function to get more information about the type of error that occurred. For a listing of possible errors, see the OleUIBusy function in the OLE 2.01 User Interface Library.

Remarks

Call this function to display the OLE Server Busy or Server Not Responding dialog box.

If you want to initialize the various dialog box controls by setting members of the m_bz structure, you should do this before calling DoModal, but after the dialog object is constructed.

If DoModal returns IDOK, you can call other member functions to retrieve the settings or information that was input by the user into the dialog box.

COleBusyDialog Overview | Class Members | Hierarchy Chart

See Also COleDialog::GetLastError, CDialog::DoModal, COleBusyDialog::GetSelectionType, COleBusyDialog::m_bz


COleBusyDialog::GetSelectionType

UINT GetSelectionType( );

Return Value

Type of selection made.

Remarks

Call this function to get the selection type chosen by the user in the Server Busy dialog box.

The return type values are specified by the Selection enumeration type declared in the COleBusyDialog class.

enum Selection
{
   switchTo,
   retry,
   callUnblocked
};

Brief descriptions of these values follow:

  • COleBusyDialog::switchTo Switch To button was pressed.

  • COleBusyDialog::retry Retry button was pressed.

  • COleBusyDialog::callUnblocked Call to activate the server is now unblocked.

COleBusyDialog Overview | Class Members | Hierarchy Chart

See Also COleBusyDialog::DoModal


COleBusyDialog::m_bz

Remarks

Structure of type OLEUIBUSY used to control the behavior of the Server Busy dialog box. Members of this structure can be modified directly or through member functions.

For more information, see the OLEUIBUSY structure in the OLE 2.01 User Interface Library.

COleBusyDialog Overview | Class Members | Hierarchy Chart

See Also COleBusyDialog::COleBusyDialog, COleBusyDialog::DoModal


COleChangeIconDialog

The COleChangeIconDialog class is used for the OLE Change Icon dialog box. Create an object of class COleChangeIconDialog when you want to call this dialog box. After a COleChangeIconDialog object has been constructed, you can use the m_ci structure to initialize the values or states of controls in the dialog box. The m_ci structure is of type OLEUICHANGEICON. For more information about using this dialog class, see the DoModal member function.

For more information, see the OLEUICHANGEICON structure in the OLE 2.01 User Interface Library.

For more information about OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

See Also COleDialog


COleChangeIconDialog Class Members

Data Members

m_ci A structure that controls the behavior of the dialog box.

Construction

COleChangeIconDialog Constructs a COleChangeIconDialog object.

Operations and Attributes

DoModal | Displays the OLE 2 Change Icon dialog box.
DoChangeIcon | Performs the change specified in the dialog box.
GetIconicMetafile | Gets a handle to the metafile associated with the iconic form of this item.


COleChangeIconDialog::COleChangeIconDialog

COleChangeIconDialog ( COleClientItem* pItem, DWORD dwFlags = CIF_SELECTCURRENT, CWnd* pParentWnd = NULL );

Parameters

pItem

Points to the item to be converted.

dwFlags

Creation flag, which contains any number of the following values combined using the bitwise-or operator:

  • CIF_SELECTCURRENT Specifies that the Current radio button will be selected initially when the dialog box is called. This is the default.

  • CIF_SELECTDEFAULT Specifies that the Default radio button will be selected initially when the dialog box is called.

  • CIF_SELECTFROMFILE Specifies that the From File radio button will be selected initially when the dialog box is called.

  • CIF_SHOWHELP Specifies that the Help button will be displayed when the dialog box is called.

  • CIF_USEICONEXE Specifies that the icon should be extracted from the executable specified in the szIconExe field of m_ci instead of retrieved from the type. This is useful for embedding or linking to non-OLE files.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the parent window of the dialog box will be set to the main application window.

Remarks

This function constructs only a COleChangeIconDialog object. To display the dialog box, call the DoModal function.

For more information, see the OLEUICHANGEICON structure in the OLE 2.01 User Interface Library.

COleChangeIconDialog Overview | Class Members | Hierarchy Chart

See Also COleClientItem, COleChangeIconDialog::DoModal


COleChangeIconDialog::DoChangeIcon

BOOL DoChangeIcon( COleClientItem* pItem );

Return Value

Nonzero if change is successful; otherwise 0.

Parameters

pItem

Points to the item whose icon is changing.

Remarks

Call this function to change the icon representing the item to the one selected in the dialog box after DoModal returns IDOK.

COleChangeIconDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeIconDialog::DoModal


COleChangeIconDialog::DoModal

virtual int DoModal( );

Return Value

Completion status for the dialog box. One of the following values:

  • IDOK if the dialog box was successfully displayed.

  • IDCANCEL if the user canceled the dialog box.

  • IDABORT if an error occurred. If IDABORT is returned, call the COleDialog::GetLastError member function to get more information about the type of error that occurred. For a listing of possible errors, see the OleUIChangeIcon function in the OLE 2.01 User Interface Library.

Remarks

Call this function to display the OLE Change Icon dialog box.

If you want to initialize the various dialog box controls by setting members of the m_ci structure, you should do this before calling DoModal, but after the dialog object is constructed.

If DoModal returns IDOK, you can call other member functions to retrieve the settings or information that was input by the user into the dialog box.

COleChangeIconDialog Overview | Class Members | Hierarchy Chart

See Also COleDialog::GetLastError, CDialog::DoModal, COleChangeIconDialog::m_ci, COleChangeIconDialog::DoChangeIcon, COleChangeIconDialog::GetIconicMetafile


COleChangeIconDialog::GetIconicMetafile

HGLOBAL GetIconicMetafile( ) const;

Return Value

The handle to the metafile containing the iconic aspect of the new icon, if the dialog box was dismissed by choosing OK; otherwise, the icon as it was before the dialog was displayed.

Remarks

Call this function to get a handle to the metafile that contains the iconic aspect of the selected item.

COleChangeIconDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeIconDialog::DoModal, COleChangeIconDialog::COleChangeIconDialog, COleChangeIconDialog::DoChangeIcon


COleChangeIconDialog::m_ci

Remarks

Structure of type OLEUICHANGEICON used to control the behavior of the Change Icon dialog box. Members of this structure can be modified either directly or through member functions.

For more information, see the OLEUICHANGEICON structure in the OLE 2.01 User Interface Library.

COleChangeIconDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeIconDialog::COleChangeIconDialog


COleChangeSourceDialog

The COleChangeSourceDialog class is used for the OLE Change Source dialog box. Create an object of class COleChangeSourceDialog when you want to call this dialog box. After a COleChangeSourceDialog object has been constructed, you can use the m_cs structure to initialize the values or states of controls in the dialog box. The m_cs structure is of type OLEUICHANGESOURCE. For more information about using this dialog class, see the DoModal member function.

For more information, see the OLEUICHANGESOURCE structure in OLE 2.01 User Interface Library.

For more information about OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

See Also COleDialog


COleChangeSourceDialog Class Members

Constructor

COleChangeSourceDialog Constructs a COleChangeSourceDialog object.

Operations

DoModal Displays the OLE Change Source dialog box.

Attributes

IsValidSource | Indicates if the source is valid.
GetFileName | Gets the filename from the source name.
GetDisplayName | Gets the complete source display name.
GetItemName | Gets the item name from the source name.
GetFromPrefix | Gets the prefix of the previous source.
GetToPrefix | Gets the prefix of the new source

Data Member

m_cs A structure that controls the behavior of the dialog box.


COleChangeSourceDialog::COleChangeSourceDialog

COleChangeSourceDialog( COleClientItem* pItem, CWnd* pParentWnd = NULL );

Parameters

pItem

Pointer to the linked COleClientItem whose source is to be updated.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the parent window of the dialog box will be set to the main application window.

Remarks

This function constructs a COleChangeSourceDialog object. To display the dialog box, call the DoModal function.

For more information, see the OLEUICHANGESOURCE structure and OleUIChangeSource function in OLE 2.01 User Interface Library.


COleChangeSourceDialog::DoModal

virtual int DoModal( );

Return Value

Completion status for the dialog box. One of the following values:

  • IDOK if the dialog box was successfully displayed.

  • IDCANCEL if the user canceled the dialog box.

  • IDABORT if an error occurred. If IDABORT is returned, call the COleDialog::GetLastError member function to get more information about the type of error that occurred. For a listing of possible errors, see the OleUIChangeSource function in OLE 2.01 User Interface Library.

Remarks

Call this function to display the OLE Change Source dialog box.

If you want to initialize the various dialog box controls by setting members of the m_cs structure, you should do this before calling DoModal, but after the dialog object is constructed.

If DoModal returns IDOK, you can call member functions to retrieve user-entered settings or information from the dialog box. The following list names typical query functions:

  • GetFileName

  • GetDisplayName

  • GetItemName

COleChangeSourceDialog Overview | Class Members Hierarchy Chart

See Also COleChangeSourceDialog::COleChangeSourceDialog


COleChangeSourceDialog::GetDisplayName

CString GetDisplayName( );

Return Value

The complete source display name (moniker) for the COleClientItem specified in the constructor.

Remarks

Call this function to retrieve the complete display name for the linked client item.

COleChangeSourceDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeSourceDialog::GetFileName, COleChangeSourceDialog::GetItemName


COleChangeSourceDialog::GetFileName

CString GetFileName( );

Return Value

The file moniker portion of the source display name for the COleClientItem specified in the constructor.

Remarks

Call this function to retrieve the file moniker portion of the display name for the linked client item. The file moniker together with the item moniker gives the complete display name.

COleChangeSourceDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeSourceDialog::GetDisplayName, COleChangeSourceDialog::GetItemName


COleChangeSourceDialog::GetFromPrefix

CString GetFromPrefix( );

Return Value

The previous prefix string of the source.

Remarks

Call this function to get the previous prefix string for the source. Call this function only after DoModal returns IDOK.

This value comes directly from the lpszFrom member of the OLEUICHANGESOURCE structure.

For more information, see the OLEUICHANGESOURCE structure in OLE 2.01 User Interface Library.

COleChangeSourceDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeSourceDialog::GetToPrefix


COleChangeSourceDialog::GetItemName

CString GetItemName( );

Return Value

The item moniker portion of the source display name for the COleClientItem specified in the constructor.

Remarks

Call this function to retrieve the item moniker portion of the display name for the linked client item. The file moniker together with the item moniker gives the complete display name.

COleChangeSourceDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeSourceDialog::GetFileName, COleChangeSourceDialog::GetDisplayName


COleChangeSourceDialog::GetToPrefix

CString GetToPrefix( );

Return Value

The new prefix string of the source.

Remarks

Call this function to get the new prefix string for the source. Call this function only after DoModal returns IDOK.

This value comes directly from the lpszTo member of the OLEUICHANGESOURCE structure.

For more information, see the OLEUICHANGESOURCE structure in OLE 2.01 User Interface Library.

COleChangeSourceDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeSourceDialog::GetFromPrefix


COleChangeSourceDialog::IsValidSource

BOOL IsValidSource( );

Return Value

Nonzero if the new source is valid, otherwise 0.

Remarks

Call this function to determine if the new source is valid. Call this function only after DoModal returns IDOK.

For more information, see the OLEUICHANGESOURCE structure in OLE 2.01 User Interface Library.

COleChangeSourceDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeSourceDialog::DoModal


COleChangeSourceDialog::m_cs

Remarks

This data member is a structure of type OLEUICHANGESOURCE. OLEUICHANGESOURCE is used to control the behavior of the OLE Change Source dialog box. Members of this structure can be modified directly.

For more information, see the OLEUICHANGESOURCE structure in OLE 2.01 User Interface Library.

COleChangeSourceDialog Overview | Class Members | Hierarchy Chart

See Also COleChangeSourceDialog::COleChangeSourceDialog


COleClientItem

The COleClientItem class defines the container interface to OLE items. An OLE item represents data, created and maintained by a server application, which can be “seamlessly” incorporated into a document so that it appears to the user to be a single document. The result is a “compound document” made up of the OLE item and a containing document.

An OLE item can be either embedded or linked. If it is embedded, its data is stored as part of the compound document. If it is linked, its data is stored as part of a separate file created by the server application, and only a link to that file is stored in the compound document. All OLE items contain information specifying the server application that should be called to edit them.

COleClientItem defines several overridable functions that are called in response to requests from the server application; these overridables usually act as notifications. This allows the server application to inform the container of changes the user makes when editing the OLE item, or to retrieve information needed during editing.

COleClientItem can be used with either the COleDocument, COleLinkingDoc, or COleServerDoc class. To use COleClientItem, derive a class from it and implement the OnChange member function, which defines how the container responds to changes made to the item. To support in-place activation, override the OnGetItemPosition member function. This function provides information about the displayed position of the OLE item.

For more information about using the container interface, see the articles Containers: Implementing a Container and Activation in Visual C++ Programmer’s Guide.

Note The OLE documentation refers to embedded and linked items as “objects” and refers to types of items as “classes.” This reference uses the term “item” to distinguish the OLE entity from the corresponding C++ object and the term “type” to distinguish the OLE category from the C++ class.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample MFCBIND | MFC Sample OCLIENT

See Also COleServerItem


COleClientItem Class Members

Creation
Status
Data Access
Object Conversion
Clipboard Operations
General Operations
Activation
Embedded Object Operations
Linked Object Operations and Status
Overridables

Construction

COleClientItem Constructs a COleClientItem object.

Creation

CreateFromClipboard | Creates an embedded item from the Clipboard.
CreateFromData | Creates an embedded item from a data object.
CanCreateFromData | Indicates whether a container application can create an embedded object.
CreateFromFile | Creates an embedded item from a file.
CreateStaticFromClipboard | Creates a static item from the Clipboard.
CreateStaticFromData | Creates a static item from a data object.
CreateLinkFromClipboard | Creates a linked item from the Clipboard.
CreateLinkFromData | Creates a linked item from a data object.
CanCreateLinkFromData | Indicates whether a container application can create a linked object.
CreateLinkFromFile | Creates a linked item from a file.
CreateNewItem | Creates a new embedded item by launching the server application.
CreateCloneFrom | Creates a duplicate of an existing item.

Status

GetLastStatus | Returns the status of the last OLE operation.
GetIconFromRegistry | Retrives a handle to an icon associated with the server of a particular CLSID.
GetType | Returns the type (embedded, linked, or static) of the OLE item.
GetExtent | Returns the bounds of the OLE item’s rectangle.
GetCachedExtent | Returns the bounds of the OLE item’s rectangle.
GetClassID | Gets the present item’s class ID.
GetUserType | Gets a string describing the item’s type.
GetIconicMetafile | Gets the metafile used for drawing the item’s icon.
SetIconicMetafile | Caches the metafile used for drawing the item’s icon.
GetDrawAspect | Gets the item’s current view for rendering.
SetDrawAspect | Sets the item’s current view for rendering.
GetItemState | Gets the item’s current state.
GetActiveView | Gets the view on which the item is activated in place.
IsModified | Returns TRUE if the item has been modified since it was last saved.
IsRunning | Returns TRUE if the item’s server application is running.
IsInPlaceActive | Returns TRUE if the item is in-place active.
IsOpen | Returns TRUE if the item is currently open in the server application.

Data Access

GetDocument | Returns the COleDocument object that contains the present item.
AttachDataObject | Accesses the data in the OLE object.

Object Conversion

ConvertTo | Converts the item to another type.
ActivateAs | Activates the item as another type.
Reload | Reloads the item after a call to ActivateAs.

Clipboard Operations

CanPaste | Indicates whether the Clipboard contains an embeddable or static OLE item.
CanPasteLink | Indicates whether the Clipboard contains a linkable OLE item.
DoDragDrop | Performs a drag-and-drop operation.
CopyToClipboard | Copies the OLE item to the Clipboard.
GetClipboardData | Gets the data that would be placed on the Clipboard by calling the CopyToClipboard member function.

General Operations

Close | Closes a link to a server but does not destroy the OLE item.
Release | Releases the connection to an OLE linked item and closes it if it was open. Does not destroy the client item.
Delete | Deletes or closes the OLE item if it was a linked item.
Draw | Draws the OLE item.
Run | Runs the application associated with the item.
SetPrintDevice | Sets the print-target device for this client item.

Activation

Activate | Opens the OLE item for an operation and then executes the specified verb.
DoVerb | Executes the specified verb.
Deactivate | Deactivates the item.
DeactivateUI | Restores the container application’s user interface to its original state.
ReactivateAndUndo | Reactivates the item and undoes the last in-place editing operation.
SetItemRects | Sets the item’s bounding rectangle.
GetInPlaceWindow | Returns a pointer to the item’s in-place editing window.

Embedded Object Operations

SetHostNames | Sets the names the server displays when editing the OLE item.
SetExtent | Sets the bounding rectangle of the OLE item.

Linked Object Operations and Status

GetLinkUpdateOptions | Returns the update mode for a linked item (advanced feature).
SetLinkUpdateOptions | Sets the update mode for a linked item (advanced feature).
UpdateLink | Updates the presentation cache of an item.
IsLinkUpToDate | Returns TRUE if a linked item is up to date with its source document.

Overridables

OnChange | Called when the server changes the OLE item. Implementation required.
OnGetClipboardData | Called by the framework to get the data to be copied to the Clipboard.
OnInsertMenus | Called by the framework to create a composite menu.
OnSetMenu | Called by the framework to install and remove a composite menu.
OnRemoveMenus | Called by the framework to remove the container’s menus from a composite menu.
OnUpdateFrameTitle | Called by the framework to update the frame window’s title bar.
OnShowControlBars | Called by the framework to show and hide control bars.
OnGetItemPosition | Called by the framework to get the item’s position relative to the view.
OnScrollBy | Called by the framework to scroll the item into view.
OnDeactivateUI | Called by the framework when the server has removed its in-place user interface.
OnDiscardUndoState | Called by the framework to discard the item’s undo state information.
OnDeactivateAndUndo | Called by the framework to undo after activation.
OnShowItem | Called by the framework to display the OLE item.
OnGetClipRect | Called by the framework to get the item’s clipping-rectangle coordinates.
CanActivate | Called by the framework to determine whether in-place activation is allowed.
OnActivate | Called by the framework to notify the item that it is activated.
OnActivateUI | Called by the framework to notify the item that it is activated and should show its user interface.
OnGetWindowContext | Called by the framework when an item is activated in place.
OnDeactivate | Called by the framework when an item is deactivated.
OnChangeItemPosition | Called by the framework when an item’s position changes.


COleClientItem::Activate

void Activate( LONG nVerb, CView* pView, LPMSG lpMsg = NULL );

Parameters

nVerb

Specifies the verb to execute. It can be one of the following:

Value | Meaning | Symbol
– 0 | Primary verb | OLEIVERB_PRIMARY
– 1 | Secondary verb | (None)
– 1 | Display item for editing | OLEIVERB_SHOW
– 2 | Edit item in separate window | OLEIVERB_OPEN
– 3 | Hide item | OLEIVERB_HIDE

The –1 value is typically an alias for another verb. If open editing is not supported, –2 has the same effect as –1. For additional values, see IOleObject::DoVerb in the OLE documentation.

pView

Pointer to the container view window that contains the OLE item; this is used by the server application for in-place activation. This parameter should be NULL if the container does not support in-place activation.

lpMsg

Pointer to the message that caused the item to be activated.

Remarks

Call this function to execute the specified verb instead of DoVerb so that you can do your own processing when an exception is thrown.

If the server application was written using the Microsoft Foundation Class Library, this function causes the OnDoVerb member function of the corresponding COleServerItem object to be executed.

If the primary verb is Edit and zero is specified in the nVerb parameter, the server application is launched to allow the OLE item to be edited. If the container application supports in-place activation, editing can be done in place. If the container does not support in-place activation (or if the Open verb is specified), the server is launched in a separate window and editing can be done there. Typically, when the user of the container application double-clicks the OLE item, the value for the primary verb in the nVerb parameter determines which action the user can take. However, if the server supports only one action, it takes that action, no matter which value is specified in the nVerb parameter.

For more information, see IOleObject::DoVerb in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::DoVerb, COleServerItem::OnDoVerb


COleClientItem::ActivateAs

BOOL ActivateAs( LPCTSTR lpszUserType, REFCLSID clsidOld, REFCLSID clsidNew );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszUserType

Pointer to a string representing the target user type, such as “Word Document.”

clsidOld

A reference to the item’s current class ID. The class ID should represent the type of the actual object, as stored, unless it is a link. In that case, it should be the CLSID of the item to which the link refers. The COleConvertDialog automatically provides the correct class ID for the item.

clsidNew

A reference to the target class ID.

Remarks

Uses OLE’s object conversion facilities to activate the item as though it were an item of the type specified by clsidNew. This is called automatically by COleConvertDialog::DoConvert. It is not usually called directly.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleConvertDialog, COleClientItem::ConvertTo, COleClientItem::Reload


COleClientItem::AttachDataObject

void AttachDataObject( COleDataObject& rDataObject ) const;

Parameters

rDataObject

Reference to a COleDataObject object that will be initialized to allow access to the data in the OLE item.

Remarks

Call this function to initialize a COleDataObject for accessing the data in the OLE item.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataObject


COleClientItem::CanActivate

virtual BOOL CanActivate( );

Return Value

Nonzero if in-place activation is allowed; otherwise 0.

Remarks

Called by the framework when the user requests in-place activation of the OLE item; this function’s return value determines whether in-place activation is allowed. The default implementation allows in-place activation if the container has a valid window. Override this function to implement special logic for accepting or refusing the activation request. For example, an activation request can be refused if the OLE item is too small or not currently visible.

For more information, see IOleInPlaceSite::CanInPlaceActivate in the OLE documentation.


COleClientItem::CanCreateFromData

static BOOL PASCAL CanCreateFromData( const COleDataObject* pDataObject );

Return Value

Nonzero if the container can create an embedded object from the COleDataObject object; otherwise 0.

Parameters

pDataObject

Pointer to the COleDataObject object from which the OLE item is to be created.

Remarks

Checks whether a container application can create an embedded object from the given COleDataObject object. The COleDataObject class is used in data transfers for retrieving data in various formats from the Clipboard, through drag and drop, or from an embedded OLE item.

Containers can use this function to decide to enable or disable their Edit Paste and Edit Paste Special commands.

For more information, see the article Data Objects and Data Sources (OLE) in Visual C++ Programmer’s Guide.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataObject


COleClientItem::CanCreateLinkFromData

static BOOL PASCAL CanCreateLinkFromData( const COleDataObject* pDataObject );

Return Value

Nonzero if the container can create a linked object from the COleDataObject object.

Parameters

pDataObject

Pointer to the COleDataObject object from which the OLE item is to be created.

Remarks

Checks whether a container application can create a linked object from the given COleDataObject object. The COleDataObject class is used in data transfers for retrieving data in various formats from the Clipboard, through drag and drop, or from an embedded OLE item.

Containers can use this function to decide to enable or disable their Edit Paste Special and Edit Paste Link commands.

For more information, see the article Data Objects and Data Sources (OLE) in Visual C++ Programmer’s Guide.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataObject


COleClientItem::CanPaste

static BOOL PASCAL CanPaste( );

Return Value

Nonzero if an embedded OLE item can be pasted from the Clipboard; otherwise 0.

Remarks

Call this function to see whether an embedded OLE item can be pasted from the Clipboard.

For more information, see OleGetClipboard and OleQueryCreateFromData in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::CanPasteLink, COleClientItem::CreateFromClipboard, COleClientItem::CreateStaticFromClipboard, COleDocument


COleClientItem::CanPasteLink

static BOOL PASCAL CanPasteLink( );

Return Value

Nonzero if a linked OLE item can be pasted from the Clipboard; otherwise 0.

Remarks

Call this function to see whether a linked OLE item can be pasted from the Clipboard.

For more information, see OleGetClipboard and OleQueryLinkFromData in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::CanPaste, COleClientItem::CreateLinkFromClipboard


COleClientItem::Close

void Close( OLECLOSE dwCloseOption = OLECLOSE_SAVEIFDIRTY );

Parameters

dwCloseOption

Flag specifying under what circumstances the OLE item is saved when it returns to the loaded state. It can have one of the following values:

  • OLECLOSE_SAVEIFDIRTY Save the OLE item.

  • OLECLOSE_NOSAVE Do not save the OLE item.

  • OLECLOSE_PROMPTSAVE Prompt the user on whether to save the OLE item.

Remarks

Call this function to change the state of an OLE item from the running state to the loaded state, that is, loaded with its handler in memory but with the server not running. This function has no effect when the OLE item is not running.

For more information, see IOleObject::Close in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::UpdateLink


COleClientItem::COleClientItem

COleClientItem( COleDocument* pContainerDoc = NULL );

Parameters

pContainerDoc

Pointer to the container document that will contain this item. This can be any COleDocument derivative.

Remarks

Constructs a COleClientItem object and adds it to the container document’s collection of document items, which constructs only the C++ object and does not perform any OLE initialization. If you pass a NULL pointer, no addition is made to the container document. You must explicitly call COleDocument::AddItem.

You must call one of the following creation member functions before you use the OLE item:

  • CreateFromClipboard

  • CreateFromData

  • CreateFromFile

  • CreateStaticFromClipboard

  • CreateStaticFromData

  • CreateLinkFromClipboard

  • CreateLinkFromData

  • CreateLinkFromFile

  • CreateNewItem

  • CreateCloneFrom

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDocument, COleDocument::AddItem


COleClientItem::ConvertTo

BOOL ConvertTo( REFCLSID clsidNew );

Return Value

Nonzero if successful; otherwise 0.

Parameters

clsidNew

The class ID of the target type.

Remarks

Call this member function to convert the item to the type specified by clsidNew. This is called automatically by COleConvertDialog. It is not necessary to call it directly.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::ActivateAs, COleConvertDialog


COleClientItem::CopyToClipboard

void CopyToClipboard( BOOL bIncludeLink = FALSE );

Parameters

bIncludeLink

TRUE if link information should be copied to the Clipboard, allowing a linked item to be pasted; otherwise FALSE.

Remarks

Call this function to copy the OLE item to the Clipboard. Typically, you call this function when writing message handlers for the Copy or Cut commands from the Edit menu. You must implement item selection in your container application if you want to implement the Copy or Cut commands.

For more information, see OleSetClipboard in the OLE documentation.


COleClientItem::CreateCloneFrom

BOOL CreateCloneFrom( const COleClientItem* pSrcItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pSrcItem

Pointer to the OLE item to be duplicated.

Remarks

Call this function to create a copy of the specified OLE item. The copy is identical to the source item. You can use this function to support undo operations.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::CreateNewItem


COleClientItem::CreateFromClipboard

BOOL CreateFromClipboard( OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create an embedded item from the contents of the Clipboard. You typically call this function from the message handler for the Paste command on the Edit menu. (The Paste command is enabled by the framework if the CanPaste member function returns nonzero.)

For more information, see OLERENDER and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataObject::AttachClipboard, COleClientItem::CreateFromData, COleClientItem::CanPaste


COleClientItem::CreateFromData

BOOL CreateFromData( COleDataObject* pDataObject, OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDataObject

Pointer to the COleDataObject object from which the OLE item is to be created.

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create an embedded item from a COleDataObject object. Data transfer operations, such as pasting from the Clipboard or drag-and-drop operations, provide COleDataObject objects containing the information offered by a server application. It is usually used in your override of CView::OnDrop.

For more information, see OleCreateFromData, OLERENDER, and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataObject::AttachClipboard, COleClientItem::CreateFromClipboard, COleDataObject


COleClientItem::CreateFromFile

BOOL CreateFromFile( LPCTSTR lpszFileName, REFCLSID clsid = CLSID_NULL, OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszFileName

Pointer to the name of the file from which the OLE item is to be created.

clsid

Reserved for future use.

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create an embedded OLE item from a file. The framework calls this function from COleInsertDialog::CreateItem if the user chooses OK from the Insert Object dialog box when the Create from File button is selected.

For more information, see OleCreateFromFile, OLERENDER, and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::CreateItem


COleClientItem::CreateLinkFromClipboard

BOOL CreateLinkFromClipboard( OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create a linked item from the contents of the Clipboard. You typically call this function from the message handler for the Paste Link command on the Edit menu. (The Paste Link command is enabled in the default implementation of COleDocument if the Clipboard contains an OLE item that can be linked to.)

For more information, see OLERENDER and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::CanPasteLink, COleClientItem::CreateLinkFromData, COleDataObject::AttachClipboard


COleClientItem::CreateLinkFromData

BOOL CreateLinkFromData( COleDataObject* pDataObject, OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDataObject

Pointer to the COleDataObject object from which the OLE item is to be created.

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create a linked item from a COleDataObject object. Call this during a drop operation when the user indicates a link should be created. It can also be used to handle the Edit Paste command. It is called by the framework in COleClientItem::CreateLinkFromClipboard and in COlePasteSpecialDialog::CreateItem when the Link option has been selected.

For more information, see OleCreateLinkFromData, OLERENDER, and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataObject::AttachClipboard, COleDataObject, COleClientItem::CreateLinkFromClipboard


COleClientItem::CreateLinkFromFile

BOOL CreateLinkFromFile( LPCTSTR lpszFileName, OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszFileName

Pointer to the name of the file from which the OLE item is to be created.

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create a linked OLE item from a file. The framework calls this function if the user chooses OK from the Insert Object dialog box when the Create from File button is selected and the Link check box is checked. It is called from COleInsertDialog::CreateItem.

For more information, see OleCreateLinkToFile, OLERENDER, and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::CreateItem


COleClientItem::CreateNewItem

BOOL CreateNewItem( REFCLSID clsid, OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

clsid

ID that uniquely identifies the type of OLE item to create.

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create an embedded item; this function launches the server application that allows the user to create the OLE item. The framework calls this function if the user chooses OK from the Insert Object dialog box when the Create New button is selected.

For more information, see OleCreate, OLERENDER, and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::CreateItem


COleClientItem::CreateStaticFromClipboard

BOOL CreateStaticFromClipboard( OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create a static item from the contents of the Clipboard. A static item contains the presentation data but not the native data; consequently it cannot be edited. You typically call this function if the CreateFromClipboard member function fails.

For more information, see OLERENDER and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataObject::AttachClipboard, COleClientItem::CanPaste, COleClientItem::CreateStaticFromData


COleClientItem::CreateStaticFromData

BOOL CreateStaticFromData( COleDataObject* pDataObject, OLERENDER render = OLERENDER_DRAW, CLIPFORMAT cfFormat = 0, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDataObject

Pointer to the COleDataObject object from which the OLE item is to be created.

render

Flag specifying how the server will render the OLE item. For the possible values, see OLERENDER in the OLE documentation.

cfFormat

Specifies the Clipboard data format to be cached when creating the OLE item.

lpFormatEtc

Pointer to a FORMATETC structure used if render is OLERENDER_FORMAT or OLERENDER_DRAW. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If you omit this parameter, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create a static item from a COleDataObject object. A static item contains the presentation data but not the native data; consequently, it cannot be edited. This is essentially the same as CreateStaticFromClipboard except that a static item can be created from an arbitrary COleDataObject, not just from the Clipboard.

Used in COlePasteSpecialDialog::CreateItem when Static is selected.

For more information, see OleCreateStaticFromData, OLERENDER, and FORMATETC in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataObject::AttachClipboard, COleDataObject


COleClientItem::Deactivate

void Deactivate( );

Remarks

Call this function to deactivate the OLE item and free any associated resources. You typically deactivate an in-place active OLE item when the user clicks the mouse on the client area outside the bounds of the item. Note that deactivating the OLE item will discard its undo state, making it impossible to call the ReactivateAndUndo member function.

If your application supports undo, do not call Deactivate; instead, call DeactivateUI.

For more information, see IOleInPlaceObject::InPlaceDeactivate in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::ReactivateAndUndo, COleClientItem::DeactivateUI


COleClientItem::DeactivateUI

void DeactivateUI( );

Remarks

Call this function when the user deactivates an item that was activated in place. This function restores the container application’s user interface to its original state, hiding any menus and other controls that were created for in-place activation.

This function does not flush the undo state information for the item. That information is retained so that ReactivateAndUndo can later be used to execute an undo command in the server application, in case the container’s undo command is chosen immediately after deactivating the item.

For more information, see IOleInPlaceObject::InPlaceDeactivate in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::ReactivateAndUndo, COleClientItem::Activate


COleClientItem::Delete

void Delete( BOOL bAutoDelete = TRUE );

Parameters

bAutoDelete

Specifies whether the item is to be removed from the document.

Remarks

Call this function to delete the OLE item from the container document. This function calls the Release member function, which in turn deletes the C++ object for the item, permanently removing the OLE item from the document. If the OLE item is embedded, the native data for the item is deleted. It always closes a running server; therefore, if the item is an open link, this function closes it.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::Release


COleClientItem::DoDragDrop

DROPEFFECT DoDragDrop( LPCRECT lpItemRect, CPoint ptOffset, BOOL bIncludeLink = FALSE, DWORD dwEffects = DROPEFFECT_COPY | DROPEFFECT_MOVE, LPCRECT lpRectStartDrag = NULL );

Return Value

A DROPEFFECT value. If it is DROPEFFECT_MOVE, the original data should be removed.

Parameters

lpItemRect

The item’s rectangle on screen in client coordinates (pixels).

ptOffset

The offset from lpItemRect where the mouse position was at the time of the drag.

bIncludeLink

Set this to TRUE if the link data should be copied to the Clipboard. Set it to FALSE if your server application does not support links.

dwEffects

Determines the effects that the drag source will allow in the drag operation.

lpRectStartDrag

Pointer to the rectangle that defines where the drag actually starts. For more information, see the following Remarks section.

Remarks

Call the DoDragDrop member function to perform a drag-and-drop operation. The drag-and-drop operation does not start immediately. It waits until the mouse cursor leaves the rectangle specified by lpRectStartDrag or until a specified number of milliseconds have passed. If lpRectStartDrag is NULL, the size of the rectangle is one pixel.

The delay time is specified by a registry key setting. You can change the delay time by calling CWinApp::WriteProfileString or CWinApp::WriteProfileInt. If you do not specify the delay time, a default value of 200 milliseconds is used. Drag delay time is stored as follows:

  • Windows NT Drag delay time is stored in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\NT\CurrentVersion\IniFileMapping\win.ini\Windows\DragDelay.

  • Windows 3.x Drag delay time is stored in the WIN.INI file, under the [Windows} section.

  • Windows 95 Drag delay time is stored in a cached version of WIN.INI.

For more information about how drag delay information is stored in either the registry or the .INI file, see ::WriteProfileString in the Platform SDK.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource::DoDragDrop, COleClientItem::CopyToClipboard


COleClientItem::DoVerb

virtual BOOL DoVerb( LONG nVerb, CView* pView, LPMSG lpMsg = NULL );

Return Value

Nonzero if the verb was successfully executed; otherwise 0.

Parameters

nVerb

Specifies the verb to execute. It can include one of the following:

Value | Meaning | Symbol
– 0 | Primary verb | OLEIVERB_PRIMARY
– 1 | Secondary verb | (None)
– 1 | Display item for editing | OLEIVERB_SHOW
– 2 | Edit item in separate window | OLEIVERB_OPEN
– 3 | Hide item | OLEIVERB_HIDE

The –1 value is typically an alias for another verb. If open editing is not supported, –2 has the same effect as –1. For additional values, see IOleObject::DoVerb in the OLE documentation.

pView

Pointer to the view window; this is used by the server for in-place activation. This parameter should be NULL if the container application does not allow in-place activation.

lpMsg

Pointer to the message that caused the item to be activated.

Remarks

Call DoVerb to execute the specified verb. This function calls the Activate member function to execute the verb. It also catches exceptions and displays a message box to the user if one is thrown.

If the primary verb is Edit and zero is specified in the nVerb parameter, the server application is launched to allow the OLE item to be edited. If the container application supports in-place activation, editing can be done in place. If the container does not support in-place activation (or if the Open verb is specified), the server is launched in a separate window and editing can be done there. Typically, when the user of the container application double-clicks the OLE item, the value for the primary verb in the nVerb parameter determines which action the user can take. However, if the server supports only one action, it takes that action, no matter which value is specified in the nVerb parameter.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::Activate


COleClientItem::Draw

BOOL Draw( CDC* pDC, LPCRECT lpBounds, DVASPECT nDrawAspect = (DVASPECT)-1 );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDC

Pointer to a CDC object used for drawing the OLE item.

lpBounds

Pointer to a CRect object or RECT structure that defines the bounding rectangle in which to draw the OLE item (in logical units determined by the device context).

nDrawAspect

Specifies the aspect of the OLE item, that is, how it should be displayed. If nDrawAspect is –1, the last aspect set by using SetDrawAspect is used. For more information about possible values for this flag, see SetDrawAspect.

Remarks

Call this function to draw the OLE item into the specified bounding rectangle using the specified device context. The function may use the metafile representation of the OLE item created by the OnDraw member function of COleServerItem.

Typically you use Draw for screen display, passing the screen device context as pDC. In this case, you need to specify only the first two parameters.

The lpBounds parameter identifies the rectangle in the target device context (relative to its current mapping mode). Rendering may involve scaling the picture and can be used by container applications to impose a view that scales between the displayed view and the final printed image.

For more information, see IViewObject::Draw in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::SetExtent, COleServerItem::OnDraw


COleClientItem::GetActiveView

CView* GetActiveView( ) const;

Return Value

A pointer to the view; otherwise NULL if the item is not in-place activated.

Remarks

Returns the view on which the item is in-place activated.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::IsInPlaceActive, COleClientItem::GetDocument


COleClientItem::GetCachedExtent

BOOL GetCachedExtent( LPSIZE lpSize, DVASPECT nDrawAspect = (DVASPECT)-1 );

Return Value

Nonzero if successful; 0 if the OLE item is blank.

Parameters

lpSize

Pointer to a SIZE structure or a CSize object that will receive the size information.

nDrawAspect

Specifies the aspect of the OLE item whose bounds are to be retrieved. For possible values, see SetDrawAspect.

Remarks

Call this function to retrieve the OLE item’s size. This function provides the same information as GetExtent. However, you can call GetCachedExtent to get extent information during the processing of other OLE handlers, such as OnChange. The dimensions are in MM_HIMETRIC units.

This is possible because GetCachedExtent uses the IViewObject2 interface rather than use the IOleObject interface to get the extent of this item. The IViewObject2 COM object caches the extent information used in the previous call to IViewObject::Draw.

For more information, see IViewObject2::GetExtent in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetExtent, COleClientItem::SetExtent, COleServerItem::OnGetExtent


COleClientItem::GetClassID

void GetClassID( CLSID* pClassID ) const;

Parameters

pClassID

Pointer to an identifier of type CLSID to retrieve the class ID. For information on CLSID, see the OLE documentation.

Remarks

Returns the class ID of the item into the memory pointed to by pClassID. The class ID is a 128-bit number that uniquely identifies the application that edits the item.

For more information, see IPersist::GetClassID in the OLE documentation.


COleClientItem::GetClipboardData

void GetClipboardData( COleDataSource* pDataSource, BOOL bIncludeLink = FALSE, LPPOINT lpOffset = NULL, LPSIZE lpSize = NULL );

Parameters

pDataSource

Pointer to a COleDataSource object that will receive the data contained in the OLE item.

bIncludeLink

TRUE if link data should be included; otherwise FALSE.

lpOffset

The offset of the mouse cursor from the origin of the object in pixels.

lpSize

The size of the object in pixels.

Remarks

Call this function to get a COleDataSource object containing all the data that would be placed on the Clipboard by a call to the CopyToClipboard member function.

GetClipboardData is called as the default implementation of OnGetClipboardData. Override OnGetClipboardData only if you want to offer data formats in addition to those offered by CopyToClipboard. Place those formats in the COleDataSource object before or after calling CopyToClipboard, and then pass the COleDataSource object to the COleDataSource::SetClipboard function. For example, if you want the OLE item’s position in its container document to accompany it on the Clipboard, you would define your own format for passing that information and place it in the COleDataSource before calling CopyToClipboard.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource, COleClientItem::CopyToClipboard, COleDataSource::SetClipboard


COleClientItem::GetDocument

COleDocument* GetDocument( ) const;

Return Value

A pointer to the document that contains the OLE item. NULL if the item is not part of a document.

Remarks

Call this function to get a pointer to the document that contains the OLE item. This pointer allows access to the COleDocument object that you passed as an argument to the COleClientItem constructor.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::COleClientItem, COleDocument, COleLinkingDoc


COleClientItem::GetDrawAspect

DVASPECT GetDrawAspect( ) const;

Return Value

A value from the DVASPECT enumeration, whose values are listed in the reference for SetDrawAspect.

Remarks

Call the GetDrawAspect member function to determine the current “aspect,” or view, of the item. The aspect specifies how the item is to be rendered.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::SetDrawAspect, COleClientItem::Draw


COleClientItem::GetExtent

BOOL GetExtent( LPSIZE lpSize, DVASPECT nDrawAspect = (DVASPECT)-1 );

Return Value

Nonzero if successful; 0 if the OLE item is blank.

Parameters

lpSize

Pointer to a SIZE structure or a CSize object that will receive the size information.

nDrawAspect

Specifies the aspect of the OLE item whose bounds are to be retrieved. For possible values, see SetDrawAspect.

Remarks

Call this function to retrieve the OLE item’s size.

If the server application was written using the Microsoft Foundation Class Library, this function causes the OnGetExtent member function of the corresponding COleServerItem object to be called. Note that the retrieved size may differ from the size last set by the SetExtent member function; the size specified by SetExtent is treated as a suggestion. The dimensions are in MM_HIMETRIC units.

Note Do not call GetExtent during the processing of an OLE handler, such as OnChange. Call GetCachedExtent instead.

For more information, see IOleObject::GetExtent in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::SetExtent, COleClientItem::GetCachedExtent, COleServerItem::OnGetExtent


COleClientItem::GetIconFromRegistry

HICON GetIconFromRegistry( ) const;

static HICON GetIconFromRegistry( CLSID& clsid );

Return Value

A valid handle to the icon resource, or NULL if the server's icon, or a default icon, can't be found.

Parameters

clsid

A reference to the CLSID for the server associated with the icon.

Remarks

Call this member function to retrieve a handle to an icon resource associated with the server of a particular CLSID.

This member function will not start the server or obtain an icon dynamically, even if the server is already running. Instead, this member function opens the server's executable image and retrieves the static icon associated with the server as it was registered.


COleClientItem::GetIconicMetafile

HGLOBAL GetIconicMetafile( );

Return Value

A handle to the metafile if successful; otherwise NULL.

Remarks

Retrieves the metafile used for drawing the item’s icon. If there is no current icon, a default icon is returned. This is called automatically by the MFC/OLE dialogs and is usually not called directly.

This function also calls SetIconicMetafile to cache the metafile for later use.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::SetIconicMetafile


COleClientItem::GetInPlaceWindow

CWnd* GetInPlaceWindow( );

Return Value

A pointer to the item’s in-place editing window; NULL if the item is not active or if its server is unavailable.

Remarks

Call the GetInPlaceWindow member function to get a pointer to the window in which the item has been opened for in-place editing. This function should be called only for items that are in-place active.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::Activate, COleClientItem::Deactivate, COleClientItem::SetItemRects


COleClientItem::GetItemState

UINT GetItemState( ) const;

Return Value

A COleClientItem::ItemState enumerated value, which can be one of the following: emptyState, loadedState, openState, activeState, activeUIState. For information about these states, see the article Containers: Client-Item States in Visual C++ Programmer’s Guide.

Remarks

Call this function to get the OLE item’s current state. To be notified when the OLE item’s state changes, use the OnChange member function.

For more information, see the article Containers: Client-Item States in Visual C++ Programmer’s Guide.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnChange


COleClientItem::GetLastStatus

SCODE GetLastStatus( ) const;

Return Value

An SCODE value.

Remarks

Returns the status code of the last OLE operation. For member functions that return a BOOL value of FALSE, or other member functions that return NULL, GetLastStatus returns more detailed failure information. Be aware that most OLE member functions throw exceptions for more serious errors. The specific information on the interpretation of the SCODE depends on the underlying OLE call that last returned an SCODE value.

For more information on SCODE, see Structure of COM Error Codes in the Platform SDK documentation.


COleClientItem::GetLinkUpdateOptions

OLEUPDATE GetLinkUpdateOptions( );

Return Value

One of the following values:

  • OLEUPDATE_ALWAYS Update the linked item whenever possible. This option supports the Automatic link-update radio button in the Links dialog box.

  • OLEUPDATE_ONCALL Update the linked item only on request from the container application (when the UpdateLink member function is called). This option supports the Manual link-update radio button in the Links dialog box.

Remarks

Call this function to get the current value of the link-update option for the OLE item. This is an advanced operation.

This function is called automatically by the COleLinksDialog class.

For more information, see IOleLink::GetUpdateOptions in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::SetLinkUpdateOptions, COleLinksDialog


COleClientItem::GetType

OLE_OBJTYPE GetType( ) const;

Return Value

An unsigned integer with one of the following values:

  • OT_LINK The OLE item is a link.

  • OT_EMBEDDED The OLE item is embedded.

  • OT_STATIC The OLE item is static, that is, it contains only presentation data, not native data, and thus cannot be edited.

Remarks

Call this function to determine whether the OLE item is embedded or linked, or static.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetUserType


COleClientItem::GetUserType

void GetUserType( USERCLASSTYPE nUserClassType, CString& rString );

Parameters

nUserClassType

A value indicating the desired variant of the string describing the OLE item’s type. This can have one of the following values:

  • USERCLASSTYPE_FULL The full type name displayed to the user.

  • USERCLASSTYPE_SHORT A short name (15 characters maximum) for use in pop-up menus and the Edit Links dialog box.

  • USERCLASSTYPE_APPNAME Name of the application servicing the class.

rString

A reference to a CString object to which the string describing the OLE item’s type is to be returned.

Remarks

Call this function to get the user-visible string describing the OLE item’s type, such as “Word document.” This is often the entry in the system registration database.

If the full type name is requested but not available, the short name is used instead. If no entry for the type of OLE item is found in the registration database, or if there are no user types registered for the type of OLE item, then the user type currently stored in the OLE item is used. If that user type name is an empty string, “Unknown Object” is used.

For more information, see IOleObject::GetUserType in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetType


COleClientItem::IsInPlaceActive

BOOL IsInPlaceActive( ) const;

Return Value

Nonzero if the OLE item is in-place active; otherwise 0.

Remarks

Call this function to see whether the OLE item is in-place active. It is common to execute different logic depending on whether the item is being edited in place. The function checks whether the current item state is equal to either the activeState or the activeUIState.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetItemState


COleClientItem::IsLinkUpToDate

BOOL IsLinkUpToDate( ) const;

Return Value

Nonzero if the OLE item is up to date; otherwise 0.

Remarks

Call this function to see whether the OLE item is up to date. A linked item can be out of date if its source document has been updated. An embedded item that contains links within it can similarly become out of date. The function does a recursive check of the OLE item. Note that determining whether an OLE item is out of date can be as expensive as actually performing an update.

This is called automatically by the COleLinksDialog implementation.

For more information, see IOleObject::IsUpToDate in the OLE documentation.


COleClientItem::IsModified

BOOL IsModified( ) const;

Return Value

Nonzero if the OLE item is dirty; otherwise 0.

Remarks

Call this function to see whether the OLE item is dirty (modified since it was last saved).

For more information, see IPersistStorage::IsDirty in the OLE documentation.


COleClientItem::IsOpen

BOOL IsOpen( ) const;

Return Value

Nonzero if the OLE item is open; otherwise 0.

Remarks

Call this function to see whether the OLE item is open; that is, opened in an instance of the server application running in a separate window. It is used to determine when to draw the object with a hatching pattern. An open object should have a hatch pattern drawn on top of the object. You can use a CRectTracker object to accomplish this.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetItemState, CRectTracker


COleClientItem::IsRunning

BOOL IsRunning( ) const;

Return Value

Nonzero if the OLE item is running; otherwise 0.

Remarks

Call this function to see whether the OLE item is running; that is, whether the item is loaded and running in the server application.

For more information, see OleIsRunning in the OLE documentation.


COleClientItem::OnActivate

virtual void OnActivate( );

Remarks

Called by the framework to notify the item that it has just been activated in place. Note that this function is called to indicate that the server is running, not to indicate that its user interface has been installed in the container application. At this point, the object does not have an active user interface (is not activeUIState). It has not installed its menus or toolbar. The OnActivateUI member function is called when that happens.

The default implementation calls the OnChange member function with OLE_CHANGEDSTATE as a parameter. Override this function to perform custom processing when an item becomes in-place active.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnDeactivate, COleClientItem::OnDeactivateUI, COleClientItem::OnActivateUI, COleClientItem::CanActivate


COleClientItem::OnActivateUI

virtual void OnActivateUI( );

Remarks

The framework calls OnActivateUI when the object has entered the active UI state. The object has now installed its tool bar and menus.

The default implementation remembers the server’s HWND for later GetServerWindow calls.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnDeactivate, COleClientItem::OnDeactivateUI, COleClientItem::OnActivate, COleClientItem::CanActivate


COleClientItem::OnChange

virtual void OnChange( OLE_NOTIFICATION nCode, DWORD dwParam );

Parameters

nCode

The reason the server changed this item. It can have one of the following values:

  • OLE_CHANGED The OLE item’s appearance has changed.

  • OLE_SAVED The OLE item has been saved.

  • OLE_CLOSED The OLE item has been closed.

  • OLE_CHANGED_STATE The OLE item has changed from one state to another.

dwParam

If nCode is OLE_SAVED or OLE_CLOSED, this parameter is not used. If nCode is OLE_CHANGED, this parameter specifies the aspect of the OLE item that has changed. For possible values, see the dwParam parameter of COleClientItem::Draw. If nCode is OLE_CHANGED_STATE, this parameter is a COleClientItem::ItemState enumerated value and describes the state being entered. It can have one of the following values: emptyState, loadedState, openState, activeState, or activeUIState.

Remarks

Called by the framework when the user modifies, saves, or closes the OLE item. (If the server application is written using the Microsoft Foundation Class Library, this function is called in response to the Notify member functions of COleServerDoc or COleServerItem.) The default implementation marks the container document as modified if nCode is OLE_CHANGED or OLE_SAVED.

For OLE_CHANGED_STATE, the current state returned from GetItemState will still be the old state, meaning the state that was current prior to this state change.

Override this function to respond to changes in the OLE item’s state. Typically you update the item’s appearance by invalidating the area in which the item is displayed. Call the base class implementation at the beginning of your override.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetItemState, COleServerItem::NotifyChanged, COleServerDoc::NotifyChanged, COleServerDoc::NotifyClosed, COleServerDoc::NotifySaved


COleClientItem::OnChangeItemPosition

virtual BOOL OnChangeItemPosition( const CRect& rectPos );

Return Value

Nonzero if the item’s position is successfully changed; otherwise 0.

Parameters

rectPos

Indicates the item’s position relative to the container application’s client area.

Remarks

Called by the framework to notify the container that the OLE item’s extent has changed during in-place activation. The default implementation determines the new visible rectangle of the OLE item and calls SetItemRects with the new values. The default implementation calculates the visible rectangle for the item and passes that information to the server.

Override this function to apply special rules to the resize/move operation. If the application is written in MFC, this call results because the server called COleServerDoc::RequestPositionChange.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::RequestPositionChange


COleClientItem::OnDeactivate

virtual void OnDeactivate( );

Remarks

Called by the framework when the OLE item transitions from the in-place active state (activeState) to the loaded state, meaning that it is deactivated after an in-place activation. Note that this function is called to indicate that the OLE item is closed, not that its user interface has been removed from the container application. When that happens, the OnDeactivateUI member function is called.

The default implementation calls the OnChange member function with OLE_CHANGEDSTATE as a parameter. Override this function to perform custom processing when an in-place active item is deactivated. For example, if you support the undo command in your container application, you can override this function to discard the undo state, indicating that the last operation performed on the OLE item cannot be undone once the item is deactivated.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnGetWindowContext, COleClientItem::OnDeactivateUI, COleClientItem::OnActivateUI, COleClientItem::OnActivate, COleClientItem::CanActivate, CDocTemplate::SetContainerInfo


COleClientItem::OnDeactivateAndUndo

virtual void OnDeactivateAndUndo( );

Remarks

Called by the framework when the user invokes the undo command after activating the OLE item in place. The default implementation calls DeactivateUI to deactivate the server’s user interface. Override this function if you are implementing the undo command in your container application. In your override, call the base class version of the function and then undo the last command executed in your application.

For more information, see IOleInPlaceSite::DeactivateAndUndo in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::DeactivateUI


COleClientItem::OnDeactivateUI

virtual void OnDeactivateUI( BOOL bUndoable );

Parameters

bUndoable

Specifies whether the editing changes are undoable.

Remarks

Called when the user deactivates an item that was activated in place. This function restores the container application’s user interface to its original state, hiding any menus and other controls that were created for in-place activation.

If bUndoable is FALSE, the container should disable the undo command, in effect discarding the undo state of the container, because it indicates that the last operation performed by the server is not undoable.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnActivateUI, COleClientItem::OnDeactivateAndUndo, COleClientItem::OnDeactivate


COleClientItem::OnDiscardUndoState

virtual void OnDiscardUndoState( );

Remarks

Called by the framework when the user performs an action that discards the undo state while editing the OLE item. The default implementation does nothing. Override this function if you are implementing the undo command in your container application. In your override, discard the container application’s undo state.

If the server was written with the Microsoft Foundation Class Library, the server can cause this function to be called by calling COleServerDoc::DiscardUndoState.

For more information, see IOleInPlaceSite::DiscardUndoState in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::DiscardUndoState


COleClientItem::OnGetClipboardData

virtual COleDataSource* OnGetClipboardData( BOOL bIncludeLink, LPPOINT lpOffset, LPSIZE lpSize );

Return Value

A pointer to a COleDataSource object containing the Clipboard data.

Parameters

bIncludeLink

Set this to TRUE if link data should be copied to the Clipboard. Set this to FALSE if your server application does not support links.

lpOffset

Pointer to the offset of the mouse cursor from the origin of the object in pixels.

lpSize

Pointer to the size of the object in pixels.

Remarks

Called by the framework to get a COleDataSource object containing all the data that would be placed on the Clipboard by a call to either the CopyToClipboard or the DoDragDrop member function. The default implementation of this function calls GetClipboardData.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource, COleClientItem::CopyToClipboard, COleClientItem::GetClipboardData, COleDataSource::SetClipboard


COleClientItem::OnGetClipRect

virtual void OnGetClipRect( CRect& rClipRect );

Parameters

rClipRect

Pointer to an object of class CRect that will hold the clipping-rectangle coordinates of the item.

Remarks

The framework calls the OnGetClipRect member function to get the clipping-rectangle coordinates of the item that is being edited in place. Coordinates are in pixels relative to the container application window’s client area.

The default implementation simply returns the client rectangle of the view on which the item is in-place active.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnActivate


COleClientItem::OnGetItemPosition

virtual void OnGetItemPosition( CRect& rPosition );

Parameters

rPosition

Reference to the CRect object that will contain the item’s position coordinates.

Remarks

The framework calls the OnGetItemPosition member function to get the coordinates of the item that is being edited in place. Coordinates are in pixels relative to the container application window’s client area.

The default implementation of this function does nothing. Applications that support in-place editing require its implementation.

OleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnActivate, COleClientItem::OnActivateUI


COleClientItem::OnGetWindowContext

virtual BOOL OnGetWindowContext( CFrameWnd** ppMainFrame, CFrameWnd** ppDocFrame, LPOLEINPLACEFRAMEINFO lpFrameInfo );

Return Value

Nonzero if successful; otherwise 0.

Parameters

ppMainFrame

Pointer to a pointer to the main frame window.

ppDocFrame

Pointer to a pointer to the document frame window.

lpFrameInfo

Pointer to an OLEINPLACEFRAMEINFO structure that will receive frame window information.

Remarks

Called by the framework when an item is activated in place. This function is used to retrieve information about the OLE item’s parent window.

If the container is an MDI application, the default implementation returns a pointer to the CMDIFrameWnd object in ppMainFrame and a pointer to the active CMDIChildWnd object in ppDocFrame. If the container is an SDI application, the default implementation returns a pointer to the CFrameWnd object in ppMainFrame and returns NULL in ppDocFrame. The default implementation also fills in the members of lpFrameInfo.

Override this function only if the default implementation does not suit your application; for example, if your application has a user-interface paradigm that differs from SDI or MDI. This is an advanced overridable.

For more information, see IOleInPlaceSite::GetWindowContext and the OLEINPLACEFRAMEINFO structure in the OLE documentation.


COleClientItem::OnInsertMenus

virtual void OnInsertMenus( CMenu* pMenuShared, LPOLEMENUGROUPWIDTHS lpMenuWidths );

Parameters

pMenuShared

Points to an empty menu.

lpMenuWidths

Points to an array of six LONG values indicating how many menus are in each of the following menu groups: File, Edit, Container, Object, Window, Help. The container application is responsible for the File, Container, and Window menu groups, corresponding to elements 0, 2, and 4 of this array.

Remarks

Called by the framework during in-place activation to insert the container application’s menus into an empty menu. This menu is then passed to the server, which inserts its own menus, creating a composite menu. This function can be called repeatedly to build several composite menus.

The default implementation inserts into pMenuShared the in-place container menus; that is, the File, Container, and Window menu groups. CDocTemplate::SetContainerInfo is used to set this menu resource. The default implementation also assigns the appropriate values to elements 0, 2, and 4 in lpMenuWidths, depending on the menu resource. Override this function if the default implementation is not appropriate for your application; for example, if your application does not use document templates for associating resources with document types. If you override this function, you should also override OnSetMenu and OnRemoveMenus. This is an advanced overridable.

For more information, see IOleInPlaceFrame::InsertMenus in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnRemoveMenus, COleClientItem::OnSetMenu


COleClientItem::OnRemoveMenus

virtual void OnRemoveMenus( CMenu* pMenuShared );

Parameters

pMenuShared

Points to the composite menu constructed by calls to the OnInsertMenus member function.

Remarks

Called by the framework to remove the container’s menus from the specified composite menu when in-place activation ends.

The default implementation removes from pMenuShared the in-place container menus, that is, the File, Container, and Window menu groups. Override this function if the default implementation is not appropriate for your application; for example, if your application does not use document templates for associating resources with document types. If you override this function, you should probably override OnInsertMenus and OnSetMenu as well. This is an advanced overridable.

The submenus on pMenuShared may be shared by more than one composite menu if the server has repeatedly called OnInsertMenus. Therefore you should not delete any submenus in your override of OnRemoveMenus; you should only detach them.

For more information, see IOleInPlaceFrame::RemoveMenus in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnInsertMenus, COleClientItem::OnSetMenu


COleClientItem::OnScrollBy

virtual BOOL OnScrollBy( CSize sizeExtent );

Return Value

Nonzero if the item was scrolled; 0 if the item could not be scrolled.

Parameters

sizeExtent

Specifies the distances, in pixels, to scroll in the x and y directions.

Remarks

Called by the framework to scroll the OLE item in response to requests from the server. For example, if the OLE item is partially visible and the user moves outside the visible region while performing in-place editing, this function is called to keep the cursor visible. The default implementation does nothing. Override this function to scroll the item by the specified amount. Note that as a result of scrolling, the visible portion of the OLE item can change. Call SetItemRects to update the item’s visible rectangle.

For more information, see IOleInPlaceSite::Scroll in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::SetItemRects


COleClientItem::OnSetMenu

virtual void OnSetMenu( CMenu* pMenuShared, HOLEMENU holemenu, HWND hwndActiveObject );

Parameters

pMenuShared

Pointer to the composite menu constructed by calls to the OnInsertMenus member function and the ::InsertMenu function.

holemenu

Handle to the menu descriptor returned by the ::OleCreateMenuDescriptor function, or NULL if the dispatching code is to be removed.

hwndActiveObject

Handle to the editing window for the OLE item. This is the window that will receive editing commands from OLE.

Remarks

Called by the framework two times when in-place activation begins and ends; the first time to install the composite menu and the second time (with holemenu equal to NULL) to remove it. The default implementation installs or removes the composite menu and then calls the OleSetMenuDescriptor function to install or remove the dispatching code. Override this function if the default implementation is not appropriate for your application. If you override this function, you should probably override OnInsertMenus and OnRemoveMenus as well. This is an advanced overridable.

For more information, see OleCreateMenuDescriptor, OleSetMenuDescriptor, and IOleInPlaceFrame::SetMenu in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnInsertMenus, COleClientItem::OnRemoveMenus


COleClientItem::OnShowControlBars

virtual BOOL OnShowControlBars( CFrameWnd* pFrameWnd, BOOL bShow );

Return Value

Nonzero if the function call causes a change in the control bars’ state; 0 if the call causes no change, or if pFrameWnd does not point to the container’s frame window.

Parameters

pFrameWnd

Pointer to the container application’s frame window. This can be either a main frame window or an MDI child window.

bShow

Specifies whether control bars are to be shown or hidden.

Remarks

Called by the framework to show and hide the container application’s control bars. This function returns 0 if the control bars are already in the state specified by bShow. This would occur, for example, if the control bars are hidden and bShow is FALSE.

The default implementation removes the toolbar from the top-level frame window.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnInsertMenus, COleClientItem::OnSetMenu, COleClientItem::OnRemoveMenus, COleClientItem::OnUpdateFrameTitle


COleClientItem::OnShowItem

virtual void OnShowItem( );

Remarks

Called by the framework to display the OLE item, making it totally visible during editing. It is used when your container application supports links to embedded items (that is, if you have derived your document class from COleLinkingDoc). This function is called during in-place activation or when the OLE item is a link source and the user wants to edit it. The default implementation activates the first view on the container document. Override this function to scroll the document so that the OLE item is visible.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleLinkingDoc


COleClientItem::OnUpdateFrameTitle

virtual BOOL OnUpdateFrameTitle( );

Return Value

Nonzero if this function successfully updated the frame title, otherwise zero.

Remarks

Called by the framework during in-place activation to update the frame window’s title bar. The default implementation does not change the frame window title. Override this function if you want a different frame title for your application, for example “server app - item in docname” (as in, “Microsoft Excel - spreadsheet in REPORT.DOC”). This is an advanced overridable.


COleClientItem::ReactivateAndUndo

BOOL ReactivateAndUndo( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this function to reactivate the OLE item and undo the last operation performed by the user during in-place editing. If your container application supports the undo command, call this function if the user chooses the undo command immediately after deactivating the OLE item.

If the server application is written with the Microsoft Foundation Class Libraries, this function causes the server to call COleServerDoc::OnReactivateAndUndo.

For more information, see IOleInPlaceObject::ReactivateAndUndo in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::OnReactivateAndUndo, COleClientItem::OnDeactivateAndUndo


COleClientItem::Release

virtual void Release( OLECLOSE dwCloseOption = OLECLOSE_NOSAVE );

Parameters

dwCloseOption

Flag specifying under what circumstances the OLE item is saved when it returns to the loaded state. For a list of possible values, see COleClientItem::Close.

Remarks

Call this function to clean up resources used by the OLE item. Release is called by the COleClientItem destructor.

For more information, see IUnknown::Release in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::Close, COleClientItem::Delete


COleClientItem::Reload

BOOL Reload( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

Closes and reloads the item. Call the Reload function after activating the item as an item of another type by a call to ActivateAs.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::ActivateAs


COleClientItem::Run

void Run( );

Remarks

Runs the application associated with this item.

Call the Run member function to launch the server application before activating the item. This is done automatically by Activate and DoVerb, so it is usually not necessary to call this function. Call this function if it is necessary to run the server in order to set an item attribute, such as SetExtent, before executing DoVerb.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::IsRunning


COleClientItem::SetDrawAspect

void SetDrawAspect( DVASPECT nDrawAspect );

Parameters

nDrawAspect

A value from the DVASPECT enumeration. This parameter can have one of the following values:

  • DVASPECT_CONTENT Item is represented in such a way that it can be displayed as an embedded object inside its container.

  • DVASPECT_THUMBNAIL Item is rendered in a “thumbnail” representation so that it can be displayed in a browsing tool.

  • DVASPECT_ICON Item is represented by an icon.

  • DVASPECT_DOCPRINT Item is represented as if it were printed using the Print command from the File menu.

Remarks

Call the SetDrawAspect member function to set the “aspect,” or view, of the item. The aspect specifies how the item is to be rendered by Draw when the default value for that function’s nDrawAspect argument is used.

This function is called automatically by the Change Icon (and other dialogs that call the Change Icon dialog directly) to enable the iconic display aspect when requested by the user.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetDrawAspect, COleClientItem::Draw


COleClientItem::SetExtent

void SetExtent( const CSize& size, DVASPECT nDrawAspect = DVASPECT_CONTENT );

Parameters

size

A CSize object that contains the size information.

nDrawAspect

Specifies the aspect of the OLE item whose bounds are to be set. For possible values, see SetDrawAspect.

Remarks

Call this function to specify how much space is available to the OLE item. If the server application was written using the Microsoft Foundation Class Library, this causes the OnSetExtent member function of the corresponding COleServerItem object to be called. The OLE item can then adjust its display accordingly. The dimensions must be in MM_HIMETRIC units. Call this function when the user resizes the OLE item or if you support some form of layout negotiation.

For more information, see IOleObject::SetExtent in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetExtent, COleClientItem::GetCachedExtent, COleServerItem::OnSetExtent


COleClientItem::SetHostNames

void SetHostNames( LPCTSTR lpszHost, LPCTSTR lpszHostObj );

Parameters

lpszHost

Pointer to the user-visible name of the container application.

lpszHostObj

Pointer to an identifying string of the container that contains the OLE item.

Remarks

Call this function to specify the name of the container application and the container’s name for an embedded OLE item. If the server application was written using the Microsoft Foundation Class Library, this function calls the OnSetHostNames member function of the COleServerDoc document that contains the OLE item. This information is used in window titles when the OLE item is being edited. Each time a container document is loaded, the framework calls this function for all the OLE items in the document. SetHostNames is applicable only to embedded items. It is not necessary to call this function each time an embedded OLE item is activated for editing.

This is also called automatically with the application name and document name when an object is loaded or when a file is saved under a different name. Accordingly, it is not usually necessary to call this function directly.

For more information, see IOleObject::SetHostNames in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::OnSetHostNames


COleClientItem::SetIconicMetafile

BOOL SetIconicMetafile( HGLOBAL hMetaPict );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hMetaPict

A handle to the metafile used for drawing the item’s icon.

Remarks

Caches the metafile used for drawing the item’s icon. Use GetIconicMetafile to retrieve the metafile.

The hMetaPict parameter is copied into the item; therefore, hMetaPict must be freed by the caller.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetIconicMetafile


COleClientItem::SetItemRects

BOOL SetItemRects( LPCRECT lpPosRect = NULL, LPCRECT lpClipRect = NULL );

Return Value

Nonzero if successful; otherwise, 0.

Parameters

lprcPosRect

Pointer to the rectangle containing the bounds of the OLE item relative to its parent window, in client coordinates.

lprcClipRect

Pointer to the rectangle containing the bounds of the visible portion of the OLE item relative to its parent window, in client coordinates.

Remarks

Call this function to set the bounding rectangle or the visible rectangle of the OLE item. This function is called by the default implementation of the OnChangeItemPosition member function. You should call this function whenever the position or visible portion of the OLE item changes. Usually this means that you call it from your view’s OnSize and OnScrollBy member functions.

For more information, see IOleInPlaceObject::SetObjectRects in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnChangeItemPosition, COleClientItem::OnGetItemPosition


COleClientItem::SetLinkUpdateOptions

void SetLinkUpdateOptions( OLEUPDATE dwUpdateOpt );

Parameters

dwUpdateOpt

The value of the link-update option for this item. This value must be one of the following:

  • OLEUPDATE_ALWAYS Update the linked item whenever possible. This option supports the Automatic link-update radio button in the Links dialog box.

  • OLEUPDATE_ONCALL Update the linked item only on request from the container application (when the UpdateLink member function is called). This option supports the Manual link-update radio button in the Links dialog box.

Remarks

Call this function to set the link-update option for the presentation of the specified linked item. Typically, you should not change the update options chosen by the user in the Links dialog box.

For more information, see IOleLink::SetUpdateOptions in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::GetLinkUpdateOptions, COleLinksDialog


COleClientItem::SetPrintDevice

BOOL SetPrintDevice( const DVTARGETDEVICE* ptd );

BOOL SetPrintDevice( const PRINTDLG* ppd );

Return Value

Nonzero if the function was successful; otherwise 0.

Parameters

ptd

Pointer to a DVTARGETDEVICE data structure, which contains information about the new print-target device. Can be NULL.

ppd

Pointer to a PRINTDLG data structure, which contains information about the new print-target device. Can be NULL.

Remarks

Call this function to change the print-target device for this item. This function updates the print-target device for the item but does not refresh the presentation cache. To update the presentation cache for an item, call UpdateLink.

The arguments to this function contain information that the OLE system uses to identify the target device. The PRINTDLG structure contains information that Windows uses to initialize the common Print dialog box. After the user closes the dialog box, Windows returns information about the user’s selections in this structure. The m_pd member of a CPrintDialog object is a PRINTDLG structure.

For more information about this structure, see PRINTDLG in the Win32 documentation.

For more information, see DVTARGETDEVICE in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::UpdateLink, CPrintDialog


COleClientItem::UpdateLink

BOOL UpdateLink( );

Return Value

Nonzero on success; otherwise 0.

Remarks

Call this function to update the presentation data of the OLE item immediately. For linked items, the function finds the link source to obtain a new presentation for the OLE item. This process may involve running one or more server applications, which could be time-consuming. For embedded items, the function operates recursively, checking whether the embedded item contains links that might be out of date and updating them. The user can also manually update individual links using the Links dialog box.

For more information, see IOleLink::Update in the OLE documentation.

COleClientItem Overview | Class Members | Hierarchy Chart

See Also COleLinksDialog


COleCmdUI

The COleCmdUI class implements a method for MFC to update the state of user-interface objects related to the IOleCommandTarget-driven features of your application. In an application that is not enabled for DocObjects, when the user views a menu in the application, MFC processes UPDATE_COMMAND_UI notifcations. Each notification is given a CCmdUI object that can be manipulated to reflect the state of a particular command. However, when your application is enabled for DocObjects, MFC processes UPDATE_OLE_COMMAND_UI notifications and assigns COleCmdUI objects.

COleCmdUI allows a DocObject to receive commands that originate in its container's user interface (such as FileNew, Open, Print, and so on), and allows a container to receive commands that originate in the DocObject's user interface. Although IDispatch could be used to dispatch the same commands, IOleCommandTarget provides a simpler way to query and execute because it relies on a standard set of commands, usually without arguments, and no type information is involved. COleCmdUI can be used to enable, update, and set other properties of DocObject user interface commands. When you want to invoke the command, call COleServerDoc::OnExecOleCmd.

For further information on DocObjects, see CDocObjectServer and CDocObjectServerItem. Also see Internet First Steps: Active Documents and Active Documents in Visual C++ Programmer’s Guide.

#include <afxdocobj.h>


COleCmdUI Class Members

Constructors

COleCmdUI Constructs a COleCmdUI object.

Overridables

Enable | Sets or clears the enable command flag.
SetCheck | Sets the state of an on/off toggle command.
SetText | Returns a text name or status string for a command.


COleCmdUI::COleCmdUI

COleCmdUI( OLECMD* rgCmds, ULONG cCmds, const GUID* pGroup );

Parameters

rgCmds

A list of supported commands associated with the given GUID. The OLECMD structure associates commands with command flags.

cCmds

The count of commands in rgCmds.

pGroup

A pointer to a GUID that identifies a set of commands.

Remarks

Constructs a COleCmdUI object associated with a particular user-interface command. The COleCmdUI object provides a programmatic interface for updating DocObject user-interface objects such as menu items or control-bar buttons. The user-interface objects can be enabled, disabled, checked, and/or cleared through the COleCmdUI object.


COleCmdUI::Enable

virtual void Enable( BOOL bOn = TRUE );

Parameters

bOn

Indicates whether the command associated with the COleCmdUI object should be enabled or disabled. Nonzero enables the command; 0 disables the command.

Remarks

Call this function to set the command flag of the COleCmdUI object to OLECOMDF_ENABLED, which tells the interface the command is available and enabled, or to clear the command flag.


COleCmdUI::SetCheck

virtual void SetCheck( int nCheck = 1 );

Parameters

nCheck

A value determining the state to set an on/off toggle command. Values are:

Value | Description
1 | Sets the command to on.
2 | Sets the command to indeterminate; the state cannot be determined because the attribute of this command is in both on and off states in the relevant selection.
any other value | Sets the command to off.

Remarks

Call this function to set the state of an on/off toggle command.

COleCmdUI Overview | Class Members | Hierarchy Chart

See Also COleCmdUI::SetText


COleCmdUI::SetText

virtual void SetText( LPCTSTR lpszText );

Parameters

lpszText

A pointer to the text to be used with the command.

Remarks

Call this function to return a text name or status string for a command.

COleCmdUI Overview | Class Members | Hierarchy Chart

See Also COleCmdUI::SetCheck


COleControl

The COleControl class is a powerful base class for developing OLE controls. Derived from CWnd, this class inherits all the functionality of a Windows window object plus additional functionality specific to OLE, such as event firing and the ability to support methods and properties.

OLE controls can be inserted into OLE container applications and communicate with the container by using a two-way system of event firing and exposing methods and properties to the container. Note that standard OLE containers only support the basic functionality of an OLE control. They are unable to support extended features of an OLE control. Event firing occurs when events are sent to the container as a result of certain actions taking place in the control. In turn, the container communicates with the control by using an exposed set of methods and properties analogous to the member functions and data members of a C++ class. This approach allows the developer to control the appearance of the control and notify the container when certain actions occur.

Windowless Controls

OLE controls can be used in-place active without a window. Windowless controls have significant advantages:

  • Windowless controls can be transparent and non-rectangular

  • Windowless controls reduce instance size and creation time of the object

Controls do not need a window. Services that a window offers can easily be provided via a single shared window (usually the container’s) and a bit of dispatching code. Having a window is mostly an unnecessary complication on the object.

When windowless activation is used, the container (which does have a window) is responsible for providing services that would otherwise have been provided by the control’s own window. For example, if your control needs to query the keyboard focus, query the mouse capture, or obtain a device context, these operations are managed by the container. The COleControl windowless-operation member functions invoke these operations on the container.

When windowless activation is enabled, the container delegates input messages to the control’s IOleInPlaceObjectWindowless interface (an extension of IOleInPlaceObject for windowless support). COleControl’s implementation of this interface will dispatch these messages through your control’s message map, after adjusting the mouse coordinates appropriately. You can process these messages like ordinary window messages, by adding the corresponding entries to the message map.

In a windowless control, you should always use the COleControl member functions instead of the corresponding CWnd member functions or their related Windows API functions.

OLE control objects can also create a window only when they become active, but the amount of work needed for the inactive-active transition goes up and the speed of the transition goes down. There are cases when this is a problem: as an example, consider a grid of text boxes. When cursoring up and down through the column, each control must be in-place activated and then deactivated. The speed of the inactive/active transition will directly affect the scrolling speed.

For more information on developing an OLE control framework, see the articles ActiveX Controls and Create a Program with the ActiveX ControlWizard in Visual C++ Programmer's Guide. For more information on adding functionality beyond the basic framework, see Building an ActiveX Control (the Circle tutorial) in Visual C++ Tutorials. For information on optimizing OLE controls, including windowless and flicker-free controls, see ActiveX Controls: Optimization in Visual C++ Programmer's Guide.

#include <afxctl.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CIRC3 | MFC Sample DRAWPIC | MFC Sample TESTHELP

See Also COlePropertyPage, CFontHolder, CPictureHolder


COleControl Class Members

Construction/Destruction
Initialization
Control Modification Functions
Persistence
Update/Painting Functions
Dispatch Exceptions
Ambient Property Functions
Event Firing Functions
Stock Methods/Properties
OLE Control Sizing Functions
OLE Data Binding Functions
Simple Frame Functions
OLE Control Site Functions
Modal Dialog Functions
Windowless Operations
Inactive Pointer Handling Functions
Asynchronous Control Functions
Overridables
Change Notification Functions
OLE Interface Notification Functions
IViewObject Interface Notification Overridables
In-Place Activation Functions
Property Browsing Functions

Construction/Destruction

COleControl | Creates a COleControl object.
RecreateControlWindow | Destroys and re-creates the control’s window.

Initialization

InitializeIIDs | Informs the base class of the IIDs the control will use.
ResetStockProps | Initializes COleControl stock properties to their default values.
ResetVersion | Initializes the version number to a given value.
SetInitialSize | Sets the size of an OLE control when first displayed in a container.

Control Modification Functions

GetControlFlags | Retrieves the control flag settings.
IsModified | Determines if the control state has changed.
SetModifiedFlag | Changes the modified state of a control.

Persistence

ExchangeExtent | Serializes the control’s width and height.
ExchangeStockProps | Serializes the control’s stock properties.
ExchangeVersion | Serializes the control’s version number.
IsConvertingVBX | Allows specialized loading of an OLE control.
SerializeExtent | Serializes or initializes the display space for the control.
SerializeStockProps | Serializes or initializes the COleControl stock properties.
SerializeVersion | Serializes or initializes the control's version information.
SetModifiedFlag | Changes the modified state of a control.
WillAmbientsBeValidDuringLoad | Determines whether ambient properties will be available the next time the control is loaded.

Update/Painting Functions

DoSuperclassPaint | Redraws an OLE control that has been subclassed from a Windows control.
InvalidateControl | Invalidates an area of the displayed control, causing it to be redrawn.
IsOptimizedDraw | Indicates whether the container supports optimized drawing for the current drawing operation.
SelectFontObject | Selects a custom Font property into a device context.
SelectStockFont | Selects the stock Font property into a device context.
TranslateColor | Converts an OLE_COLOR value to a COLORREF value.

Dispatch Exceptions

GetNotSupported | Prevents access to a control’s property value by the user.
SetNotPermitted | Indicates that an edit request has failed.
SetNotSupported | Prevents modification to a control’s property value by the user.
ThrowError | Signals that an error has occurred in an OLE control.

Ambient Property Functions

AmbientBackColor | Returns the value of the ambient BackColor property.
AmbientDisplayName | Returns the name of the control as specified by the container.
AmbientForeColor | Returns the value of the ambient ForeColor property.
AmbientFont | Returns the value of the ambient Font property.
AmbientLocaleID | Returns the container’s locale ID.
AmbientScaleUnits | Returns the type of units used by the container.
AmbientShowGrabHandles | Determines if grab handles should be displayed.
AmbientShowHatching | Determines if hatching should be displayed.
AmbientTextAlign | Returns the type of text alignment specified by the container.
AmbientUIDead | Determines if the control should respond to user-interface actions.
AmbientUserMode | Determines the mode of the container.
GetAmbientProperty | Returns the value of the specified ambient property.

Event Firing Functions

FireClick | Fires the stock Click event.
FireDblClick | Fires the stock DblClick event.
FireError | Fires the stock Error event.
FireEvent | Fires a custom event.
FireKeyDown | Fires the stock KeyDown event.
FireKeyPress | Fires the stock KeyPress event.
FireKeyUp | Fires the stock KeyUp event.
FireMouseDown | Fires the stock MouseDown event.
FireMouseMove | Fires the stock MouseMove event.
FireMouseUp | Fires the stock MouseUp event.
FireReadyStateChange | Fires an event when the control's ready state changes.

Stock Methods/Properties

DoClick | Implementation of the stock DoClick method.
Refresh | Forces a repaint of a control’s appearance.
GetAppearance | Returns the value of the stock Appearance property.
SetAppearance | Sets the value of the stock Appearance property.
GetBackColor | Returns the value of the stock BackColor property.
SetBackColor | Sets the value of the stock BackColor property.
GetBorderStyle | Returns the value of the stock BorderStyle property.
SetBorderStyle | Sets the value of the stock BorderStyle property.
GetEnabled | Returns the value of the stock Enabled property.
SetEnabled | Sets the value of the stock Enabled property.
GetForeColor | Returns the value of the stock ForeColor property.
SetForeColor | Sets the value of the stock ForeColor property.
GetFont | Returns the value of the stock Font property.
GetFontTextMetrics | Returns the metrics of a CFontHolder object.
GetStockTextMetrics | Returns the metrics of the stock Font property.
InternalGetFont | Returns a CFontHolder object for the stock Font property.
SetFont | Sets the value of the stock Font property.
SelectStockFont | Selects the control’s stock Font property into a device context.
GetHwnd | Returns the value of the stock hWnd property.
GetText | Returns the value of the stock Text or Caption property.
InternalGetText | Retrieves the stock Caption or Text property.
SetText | Sets the value of the stock Text or Caption property.

OLE Control Sizing Functions

GetControlSize | Returns the position and size of the OLE control.
SetControlSize | Sets the position and size of the OLE control.
GetRectInContainer | Returns the control’s rectangle relative to its container.
SetRectInContainer | Sets the control’s rectangle relative to its container.

OLE Data Binding Functions

BoundPropertyChanged | Notifies the container that a bound property has been changed.
BoundPropertyRequestEdit | Requests permission to edit the property value.

Simple Frame Functions

EnableSimpleFrame Enables simple frame support for a control.

OLE Control Site Functions

ControlInfoChanged | Call this function after the set of mnemonics handled by the control has changed.
GetClientSite | Queries an object for the pointer to its current client site within its container.
GetExtendedControl | Retrieves a pointer to an extended control object belonging to the container.
LockInPlaceActive | Determines if your control can be deactivated by the container.
TransformCoords | Transforms coordinate values between a container and the control.

Modal Dialog Functions

PreModalDialog | Notifies the container that a modal dialog box is about to be displayed.
PostModalDialog | Notifies the container that a modal dialog box has been closed.

Windowless Operations

ClipCaretRect | Adjusts a caret rectangle if it is overlapped by a control.
GetCapture | Determines whether a windowless, activated control object has the mouse capture.
GetClientRect | Retrieves the size of the control's client area.
GetDC | Provides a means for a windowless control to get a device context from its container.
GetFocus | Determines whether the control has the focus.
GetWindowlessDropTarget | Override to allow a windowless control to be the target of drag and drop operations.
InvalidateRgn | Invalidates the container window's client area within the given region. Can be used to redraw windowless controls in the region.
OnWindowlessMessage | Processes window messages (other than mouse and keyboard messages) for windowless controls.
ReleaseCapture | Releases mouse capture.
ReleaseDC | Releases the display device context of a container of a windowless control.
ScrollWindow | Allows a windowless control to scroll an area within its in-place active image on the display.
SetCapture | Causes the control’s container window to take possession of the mouse capture on the control’s behalf.
SetFocus | Causes the control’s container window to take possession of the input focus on the control’s behalf.

Inactive Pointer Handling Functions

ClientToParent | Translates a point relative to the control's origin to a point relative to its container's origin.
GetActivationPolicy | Alters the default activation behavior of a control that supports the IPointerInactive interface.
GetClientOffset | Retrieves the difference between the upper left corner of the control's rectangular area and the upper left corner of its client area.
OnInactiveMouseMove | Override to have the container for the inactive control under the mouse pointer dispatch WM_MOUSEMOVE messages to the control.
OnInactiveSetCursor | Override to have the container for the inactive control under the mouse pointer dispatch WM_SETCURSOR messages to the control.
ParentToClient | Translates a point relative to the container's origin to a point relative to the control's origin.

Asynchronous Control Functions

GetReadyState | Returns the control's readiness state.
InternalSetReadyState | Sets the control's readiness state and fires the ready-state-change event.
Load | Resets any previous asynchronous data and initiates a new load of the control's asynchronous property.

Overridables

DisplayError | Displays stock Error events to the control’s user.
DoPropExchange | Serializes the properties of a COleControl object.
GetClassID | Retrieves the OLE class ID of the control.
GetMessageString | Provides status bar text for a menu item.
IsSubclassedControl | Called to determine if the control subclasses a Windows control.
OnClick | Called to fire the stock Click event.
OnDoVerb | Called after a control verb has been executed.
OnDraw | Called when a control is requested to redraw itself.
OnDrawMetafile | Called by the container when a control is requested to redraw itself using a metafile device context.
OnEdit | Called by the container to UI Activate an OLE control.
OnEnumVerbs | Called by the container to enumerate a control’s verbs.
OnEventAdvise | Called when event handlers are connected or disconnected from a control.
OnKeyDownEvent | Called after the stock KeyDown event has been fired.
OnKeyPressEvent | Called after the stock KeyPress event has been fired.
OnKeyUpEvent | Called after the stock KeyUp event has been fired.
OnProperties | Called when the control’s “Properties” verb has been invoked.
OnResetState | Resets a control’s properties to the default values.

Change Notification Functions

OnAppearanceChanged | Called when the stock Appearance property is changed.
OnBackColorChanged | Called when the stock BackColor property is changed.
OnBorderStyleChanged | Called when the stock BorderStyle property is changed.
OnEnabledChanged | Called when the stock Enabled property is changed.
OnFontChanged | Called when the stock Font property is changed.
OnForeColorChanged | Called when the stock ForeColor property is changed.
OnTextChanged | Called when the stock Text or Caption property is changed.

OLE Interface Notification Functions

OnAmbientPropertyChange | Called when an ambient property is changed.
OnClose | Notifies the control that IOleControl::Close has been called.
OnFreezeEvents | Called when a control’s events are frozen or unfrozen.
OnGetControlInfo | Provides mnemonic information to the container.
OnMnemonic | Called when a mnemonic key of the control has been pressed.
OnRenderData | Called by the framework to retrieve data in the specified format.
OnRenderFileData | Called by the framework to retrieve data from a file in the specified format.
OnRenderGlobalData | Called by the framework to retrieve data from global memory in the specified format.
OnSetClientSite | Notifies the control that IOleControl::SetClientSite has been called.
OnSetData | Replaces the control’s data with another value.
OnSetExtent | Called after the control’s extent has changed.
OnSetObjectRects | Called after the control’s dimensions have been changed.

IViewObject Interface Notification Overridables

OnGetColorSet | Notifies the control that IOleObject::GetColorSet has been called.
OnGetNaturalExtent | Override to retrieve the control's display size closest to the proposed size and extent mode.
OnGetViewExtent | Override to retrieve the size of the control's display areas (can be used to enable two-pass drawing).
OnGetViewRect | Override to convert control's size into a rectangle starting at a specific position.
OnGetViewStatus | Override to retrieve the control's view status.
OnQueryHitPoint | Override to query whether a control's display overlaps a given point.
OnQueryHitRect | Override to query whether a control's display overlaps any point in a given rectangle.

In-Place Activation Functions

OnGetInPlaceMenu | Requests the handle of the control’s menu that will be merged with the container menu.
OnHideToolBars | Called by the container when the control is UI deactivated.
OnShowToolBars | Called when the control has been UI activated.

Property Browsing Functions

OnGetDisplayString | Called to obtain a string to represent a property value.
OnGetPredefinedStrings | Returns strings representing possible values for a property.
OnGetPredefinedValue | Returns the value corresponding to a predefined string.
OnMapPropertyToPage | Indicates which property page to use for editing a property.


COleControl::AmbientBackColor

OLE_COLOR AmbientBackColor( );

Return Value

The current value of the container’s ambient BackColor property, if any. If the property is not supported, this function returns the system-defined Windows background color.

Remarks

The ambient BackColor property is available to all controls and is defined by the container. Note that the container is not required to support this property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::TranslateColor, COleControl::GetBackColor, COleControl::AmbientForeColor


COleControl::AmbientDisplayName

CString AmbientDisplayName( );

Return Value

The name of the OLE control. The default is a zero-length string.

Remarks

The name the container has assigned to the control can be used in error messages displayed to the user. Note that the container is not required to support this property.


COleControl::AmbientFont

LPFONTDISP AmbientFont( );

Return Value

A pointer to the container’s ambient Font dispatch interface. The default value is NULL. If the return is not equal to NULL, you are responsible for releasing the font by calling its IUnknown::Release member function.

Remarks

The ambient Font property is available to all controls and is defined by the container. Note that the container is not required to support this property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetFont, COleControl::SetFont


COleControl::AmbientForeColor

OLE_COLOR AmbientForeColor( );

Return Value

The current value of the container’s ambient ForeColor property, if any. If not supported, this function returns the system-defined Windows text color.

Remarks

The ambient ForeColor property is available to all controls and is defined by the container. Note that the container is not required to support this property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientBackColor, COleControl::GetForeColor, COleControl::TranslateColor


COleControl::AmbientLocaleID

LCID AmbientLocaleID( );

Return Value

The value of the container’s LocaleID property, if any. If this property is not supported, this function returns 0.

Remarks

The control can use the LocaleID to adapt its user interface for specific locales. Note that the container is not required to support this property.


COleControl::AmbientScaleUnits

CString AmbientScaleUnits( );

Return Value

A string containing the ambient ScaleUnits of the container. If this property is not supported, this function returns a zero-length string.

Remarks

The container’s ambient ScaleUnits property can be used to display positions or dimensions, labeled with the chosen unit, such as twips or centimeters. Note that the container is not required to support this property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::TransformCoords


COleControl::AmbientShowGrabHandles

BOOL AmbientShowGrabHandles( );

Return Value

Nonzero if grab handles should be displayed; otherwise 0. If this property is not supported, this function returns nonzero.

Remarks

Call this function to determine whether the container allows the control to display grab handles for itself when active. Note that the container is not required to support this property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientShowHatching


COleControl::AmbientShowHatching

BOOL AmbientShowHatching( );

Return Value

Nonzero if the hatched pattern should be shown; otherwise 0. If this property is not supported, this function returns nonzero.

Remarks

Call this function to determine whether the container allows the control to display itself with a hatched pattern when UI active. Note that the container is not required to support this property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientShowGrabHandles


COleControl::AmbientTextAlign

short AmbientTextAlign( );

Return Value

The status of the container’s ambient TextAlign property. If this property is not supported, this function returns 0.

The following is a list of valid return values:

Return Value | Meaning
0 | General alignment (numbers to the right, text to the left).
1 | Left justify
2 | Center
3 | Right justify

Remarks

Call this function to determine the ambient text alignment preferred by the control container. This property is available to all embedded controls and is defined by the container. Note that the container is not required to support this property.


COleControl::AmbientUIDead

BOOL AmbientUIDead( );

Return Value

Nonzero if the control should respond to user-interface actions; otherwise 0. If this property is not supported, this function returns 0.

Remarks

Call this function to determine if the container wants the control to respond to user-interface actions. For example, a container might set this to TRUE in design mode.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientUserMode


COleControl::AmbientUserMode

BOOL AmbientUserMode( );

Return Value

Nonzero if the container is in user mode; otherwise 0 (in design mode). If this property is not supported, this function returns 0.

Remarks

Call this function to determine if the container is in design mode or user mode. For example, a container might set this to FALSE in design mode.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientUIDead


COleControl::BoundPropertyChanged

void BoundPropertyChanged( DISPID dispid );

Parameters

dispid

The dispatch ID of a bound property of the control.

Remarks

Call this function to signal that the bound property value has changed. This must be called every time the value of the property changes, even in cases where the change was not made through the property Set method. Be particularly aware of bound properties that are mapped to member variables. Any time such a member variable changes, BoundPropertyChanged must be called.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::BoundPropertyRequestEdit


COleControl::BoundPropertyRequestEdit

BOOL BoundPropertyRequestEdit( DISPID dispid );

Return Value

Nonzero if the change is permitted; otherwise 0. The default value is nonzero.

Parameters

dispid

The dispatch ID of a bound property of the control.

Remarks

Call this function to request permission from the IPropertyNotifySink interface to change a bound property value provided by the control. If permission is denied, the control must not let the value of the property change. This can be done by ignoring or failing the action that attempted to change the property value.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::BoundPropertyChanged


COleControl::ClientToParent

virtual void ClientToParent( LPCRECT lprcBounds, LPPOINT pPoint ) const;

Parameters

lprcBounds

Pointer to the bounds of the OLE control within the container. Not the client area but the area of the entire control including borders and scroll bars.

pPoint

Pointer to the OLE client area point to be translated into the coordinates of the parent (container).

Remarks

Call this function to translate the coordinates of pPoint into parent coordinates. On input pPoint is relative to the origin of the client area of the OLE control (upper left corner of the client area of the control). On output pPoint is relative to the origin of the parent (upper left corner of the container).

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::ParentToClient, COleControl::GetClientOffset


COleControl::ClipCaretRect

BOOL ClipCaretRect( LPRECT lpRect );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpRect

On input, a pointer to a RECT structure that contains the caret area to be adjusted. On output, the adjusted caret area, or NULL if the caret rectangle is completely covered.

Remarks

Call this function to adjust a caret rectangle if it is entirely or partially covered by overlapping, opaque objects. A caret is a flashing line, block, or bitmap that typically indicates where text or graphics will be inserted.

A windowless object cannot safely show a caret without first checking whether the caret is partially or totally hidden by overlapping objects. In order to make that possible, an object can use ClipCaretRect to get the caret adjusted (reduced) to ensure it fits in the clipping region.

Objects creating a caret should submit the caret rectangle to ClipCaretRect and use the adjusted rectangle for the caret. If the caret is entirely hidden, this method will return FALSE and the caret should not be shown at all in this case.


COleControl::COleControl

COleControl( );

Remarks

Constructs a COleControl object. This function is normally not called directly. Instead the OLE control is usually created by its class factory.


COleControl::ControlInfoChanged

void ControlInfoChanged( );

Remarks

Call this function when the set of mnemonics supported by the control has changed. Upon receiving this notification, the control’s container obtains the new set of mnemonics by making a call to IOleControl::GetControlInfo. Note that the container is not required to respond to this notification.


COleControl::DisplayError

virtual void DisplayError( SCODE scode, LPCTSTR lpszDescription, LPCTSTR lpszSource, LPCTSTR lpszHelpFile, UINT nHelpID );

Parameters

scode

The status code value to be reported. For a complete list of possible codes, see the article ActiveX Controls: Advanced Topics in Visual C++ Programmer’s Guide.

lpszDescription

The description of the error being reported.

lpszSource

The name of the module generating the error (typically, the name of the OLE control module).

lpszHelpFile

The name of the help file containing a description of the error.

nHelpID

The Help Context ID of the error being reported.

Remarks

Called by the framework after the stock Error event has been handled (unless the event handler has suppressed the display of the error). The default behavior displays a message box containing the description of the error, contained in lpszDescription.

Override this function to customize how errors are displayed.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireError


COleControl::DoClick

void DoClick( );

Remarks

Call this function to simulate a mouse click action on the control. The overridable COleControl::OnClick member function will be called, and a stock Click event will be fired, if supported by the control.

This function is supported by the COleControl base class as a stock method, called DoClick. For more information, see the article ActiveX Controls: Methods in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnClick


COleControl::DoPropExchange

virtual void DoPropExchange( CPropExchange* pPX );

Parameters

pPX

A pointer to a CPropExchange object. The framework supplies this object to establish the context of the property exchange, including its direction.

Remarks

Called by the framework when loading or storing a control from a persistent storage representation, such as a stream or property set. This function normally makes calls to the PX_ family of functions to load or store specific user-defined properties of an OLE control.

If Control Wizard has been used to create the OLE control project, the overridden version of this function will serialize the stock properties supported by COleControl with a call to the base class function, COleControl::DoPropExchange. As you add user-defined properties to your OLE control you will need to modify this function to serialize your new properties. For more information on serialization, see the article ActiveX Controls: Serializing in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also PX_Bool, PX_Short


COleControl::DoSuperclassPaint

void DoSuperclassPaint( CDC* pDC, const CRect& rcBounds );

Parameters

pDC

A pointer to the device context of the control container.

rcBounds

The area in which the control is to be drawn.

Remarks

Call this function to properly handle the painting of a nonactive OLE control. This function should only be used if the OLE control subclasses a Windows control and should be called in the OnDraw function of your control.

For more information on this function and subclassing a Windows control, see the article ActiveX Controls: Subclassing a Windows Control in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnDraw


COleControl::DrawContent

void DrawContent( CDC* pDC, CRect& rc );

Parameters

pDC

Pointer to the device context.

rc

Rectangular area to be drawn in.

Remarks

Called by the framework when the control’s appearance needs to be updated. This function directly calls the overridable OnDraw function.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnDraw, COleControl::DrawMetafile, COleControl::OnDrawMetafile


COleControl::DrawMetafile

void DrawMetafile(CDC* pDC, CRect& rc);

Parameters

pDC

Pointer to the metafile device context.

rc

Rectangular area to be drawn in.

Remarks

Called by the framework when the metafile device context is being used.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnDraw, COleControl::DrawContent, COleControl::OnDrawMetafile


COleControl::EnableSimpleFrame

void EnableSimpleFrame( );

Remarks

Call this function to enable the simple frame characteristic for an OLE control. This characteristic allows a control to support visual containment of other controls, but not true OLE containment. An example would be a group box with several controls inside. These controls are not OLE contained, but they are in the same group box.


COleControl::ExchangeExtent

BOOL ExchangeExtent( CPropExchange* pPX );

Return Value

Nonzero if the function succeeded; 0 otherwise.

Parameters

pPX

A pointer to a CPropExchange object. The framework supplies this object to establish the context of the property exchange, including its direction.

Remarks

Call this function to serialize or initialize the state of the control’s extent (its dimensions in HIMETRIC units). This function is normally called by the default implementation of COleControl::DoPropExchange.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange


COleControl::ExchangeStockProps

void ExchangeStockProps( CPropExchange* pPX );

Parameters

pPX

A pointer to a CPropExchange object. The framework supplies this object to establish the context of the property exchange, including its direction.

Remarks

Call this function to serialize or initialize the state of the control’s stock properties. This function is normally called by the default implementation of COleControl::DoPropExchange.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange


COleControl::ExchangeVersion

BOOL ExchangeVersion( CPropExchange* pPX, DWORD dwVersionDefault, BOOL bConvert = TRUE );

Return Value

Nonzero of the function succeeded; 0 otherwise.

Parameters

pPX

A pointer to a CPropExchange object. The framework supplies this object to establish the context of the property exchange, including its direction.

dwVersionDefault

The current version number of the control.

bConvert

Indicates whether persistent data should be converted to the latest format when saved, or maintained in the same format that was loaded.

Remarks

Call this function to serialize or initialize the state of a control’s version information. Typically, this will be the first function called by a control’s override of COleControl::DoPropExchange. When loading, this function reads the version number of the persistent data, and sets the version attribute of the CPropExchange object accordingly. When saving, this function writes the version number of the persistent data.

For more information on persistence and versioning, see the article ActiveX Controls: Serializing in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange


COleControl::FireClick

void FireClick( );

Remarks

Called by the framework when the mouse is clicked over an active control. If this event is defined as a custom event, you determine when the event is fired.

For automatic firing of a Click event to occur, the control’s Event map must have a stock Click event defined.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireDblClick, COleControl::FireMouseDown, COleControl::FireMouseUp


COleControl::FireDblClick

void FireDblClick( );

Remarks

Called by the framework when the mouse is double-clicked over an active control. If this event is defined as a custom event, you determine when the event is fired.

For automatic firing of a DblClick event to occur, the control’s Event map must have a stock DblClick event defined.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireClick, COleControl::FireMouseDown, COleControl::FireMouseUp


COleControl::FireError

void FireError( SCODE scode, LPCTSTR lpszDescription, UINT nHelpID = 0 );

Parameters

scode

The status code value to be reported. For a complete list of possible codes, see the article ActiveX Controls: Advanced Topics in Visual C++ Programmer’s Guide.

lpszDescription

The description of the error being reported.

nHelpID

The Help ID of the error being reported.

Remarks

Call this function to fire the stock Error event. This event provides a way of signalling, at appropriate places in your code, that an error has occurred within your control. Unlike other stock events, such as Click or MouseMove, Error is never fired by the framework.

To report an error that occurs during a property get function, property set function, or automation method, call COleControl::ThrowError.

The implementation of an OLE control's Stock Error event uses an SCODE value. If your control uses this event, and is intended to be used in Visual Basic 4.0, you will receive errors because the SCODE value is not supported in Visual Basic.

To fix this, manually change the SCODE parameter in the control's .ODL file to a long. In addition, any custom event, method, or property that uses an SCODE parameter also causes the same problem.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::DisplayError


COleControl::FireEvent

void FireEvent( DISPID dispid, BYTE FAR* pbParams, ... );

Parameters

dispid

The dispatch ID of the event to be fired.

pbParams

A descriptor for the event’s parameter types.

Remarks

Call this function, with any number of optional arguments, to fire a user-defined event from your control. Usually this function should not be called directly. Instead you will call the event-firing functions generated by ClassWizard in the event map section of your control’s class declaration.

The pbParams argument is a space-separated list of VTS_. One or more of these values, separated by spaces (not commas), specifies the function’s parameter list. Possible values are as follows:

Symbol | Parameter Type
VTS_COLOR | OLE_COLOR
VTS_FONT | IFontDisp*
VTS_HANDLE | HWND
VTS_PICTURE | IPictureDisp*
VTS_OPTEXCLUSIVE | OLE_OPTEXCLUSIVE*
VTS_TRISTATE | OLE_TRISTATE
VTS_XPOS_HIMETRIC | OLE_XPOS_HIMETRIC
VTS_YPOS_HIMETRIC | OLE_YPOS_HIMETRIC
VTS_XPOS_PIXELS | OLE_XPOS_PIXELS
VTS_YPOS_PIXELS | OLE_YPOS_PIXELS
VTS_XSIZE_PIXELS | OLE_XSIZE_PIXELS
VTS_YSIZE_PIXELS | OLE_XSIZE_PIXELS
VTS_XSIZE_HIMETRIC | OLE_XSIZE_HIMETRIC
VTS_YSIZE_HIMETRIC | OLE_XSIZE_HIMETRIC

Note Additional variant constants have been defined for all variant types, with the exception of VTS_FONT and VTS_PICTURE, that provide a pointer to the variant data constant. These constants are named using the VTS_P constantname convention. For example, VTS_PCOLOR is a pointer to a VTS_COLOR constant.


COleControl::FireKeyDown

void FireKeyDown( USHORT* pnChar, short nShiftState );

Parameters

pnChar

Pointer to the virtual-key code value of the pressed key.

nShiftState

Contains a combination of the following flags:

  • SHIFT_MASK The SHIFT key was pressed during the action.

  • CTRL_MASK The CTRL key was pressed during the action.

  • ALT_MASK The ALT key was pressed during the action.

Remarks

Called by the framework when a key is pressed while the control is UI active. If this event is defined as a custom event, you determine when the event is fired.

For automatic firing of a KeyDown event to occur, the control’s Event map must have a stock KeyDown event defined.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireKeyUp, COleControl::FireKeyPress, COleControl::OnKeyPressEvent


COleControl::FireKeyPress

void FireKeyPress( USHORT* pnChar );

Parameters

pnChar

A pointer to the character value of the key pressed.

Remarks

Called by the framework when a key is pressed and released while the custom control is UI Active within the container. If this event is defined as a custom event, you determine when the event is fired.

The recipient of the event may modify pnChar, for example, convert all lowercase characters to uppercase. If you want to examine the modified character, override OnKeyPressEvent.

For automatic firing of a KeyPress event to occur, the control’s Event map must have a stock KeyPress event defined.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnKeyPressEvent, COleControl::FireKeyDown, COleControl::FireKeyUp


COleControl::FireKeyUp

void FireKeyUp( USHORT* pnChar, short nShiftState );

Parameters

pnChar

Pointer to the virtual-key code value of the released key.

nShiftState

Contains a combination of the following flags:

  • SHIFT_MASK The SHIFT key was pressed during the action.

  • CTRL_MASK The CTRL key was pressed during the action.

  • ALT_MASK The ALT key was pressed during the action.

Remarks

Called by the framework when a key is released while the custom control is UI Active within the container. If this event is defined as a custom event, you determine when the event is fired.

For automatic firing of a KeyUp event to occur, the control’s Event map must have a stock KeyUp event defined.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireKeyDown, COleControl::FireKeyPress, COleControl::OnKeyUpEvent


COleControl::FireMouseDown

void FireMouseDown( short nButton, short nShiftState, OLE_XPOS_PIXELS x, OLE_YPOS_PIXEL y );

Parameters

nButton

The numeric value of the mouse button pressed. It can contain one of the following values:

  • LEFT_BUTTON The left mouse button was pressed down.

  • MIDDLE_BUTTON The middle mouse button was pressed down.

  • RIGHT_BUTTON The right mouse button was pressed down.

nShiftState

Contains a combination of the following flags:

  • SHIFT_MASK The SHIFT key was pressed during the action.

  • CTRL_MASK The CTRL key was pressed during the action.

  • ALT_MASK The ALT key was pressed during the action.

x

The x-coordinate of the cursor when a mouse button was pressed down. The coordinate is relative to the upper-left corner of the control window.

y

The y-coordinate of the cursor when a mouse button was pressed down. The coordinate is relative to the upper-left corner of the control window.

Remarks

Called by the framework when a mouse button is pressed over an active custom control. If this event is defined as a custom event, you determine when the event is fired.

For automatic firing of a MouseDown event to occur, the control’s Event map must have a stock MouseDown event defined.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireMouseUp, COleControl::FireMouseMove, COleControl::FireClick


COleControl::FireMouseMove

void FireMouseMove( short nButton, short nShiftState, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y );

Parameters

nButton

The numeric value of the mouse buttons pressed. Contains a combination of the following values:

  • LEFT_BUTTON The left mouse button was pressed down during the action.

  • MIDDLE_BUTTON The middle mouse button was pressed down during the action.

  • RIGHT_BUTTON The right mouse button was pressed down during the action.

nShiftState

Contains a combination of the following flags:

  • SHIFT_MASK The SHIFT key was pressed during the action.

  • CTRL_MASK The CTRL key was pressed during the action.

  • ALT_MASK The ALT key was pressed during the action.

x

The x-coordinate of the cursor. The coordinate is relative to the upper-left corner of the control window.

y

The y-coordinate of the cursor. The coordinate is relative to the upper-left corner of the control window.

Remarks

Called by the framework when the cursor is moved over an active custom control. If this event is defined as a custom event, you determine when the event is fired.

For automatic firing of a MouseMove event to occur, the control’s Event map must have a stock MouseMove event defined.


COleControl::FireMouseUp

void FireMouseUp( short nButton, short nShiftState, OLE_XPOS_PIXELS x, OLE_YPOS_PIXELS y );

Parameters

nButton

The numeric value of the mouse button released. It can have one of the following values:

  • LEFT_BUTTON The left mouse button was released.

  • MIDDLE_BUTTON The middle mouse button was released.

  • RIGHT_BUTTON The right mouse button was released.

nShiftState

Contains a combination of the following flags:

  • SHIFT_MASK The SHIFT key was pressed during the action.

  • CTRL_MASK The CTRL key was pressed during the action.

  • ALT_MASK The ALT key was pressed during the action.

x

The x-coordinate of the cursor when a mouse button was released. The coordinate is relative to the upper-left corner of the control window.

y

The y-coordinate of a cursor when a mouse button was released. The coordinate is relative to the upper-left corner of the control window.

Remarks

Called by the framework when a mouse button is released over an active custom control. If this event is defined as a custom event, you determine when the event is fired.

For automatic firing of a MouseUp event to occur, the control’s Event map must have a stock MouseUp event defined.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireMouseDown, COleControl::FireClick, COleControl::FireDblClick


COleControl::FireReadyStateChange

void FireReadyStateChange( );

Remarks

Call this function to fire an event with the current value of the ready state of control. The ready state can be one of the following values:

READYSTATE_UNINITIALIZED

Default initialization state

READYSTATE_LOADING

Control is currently loading its properties

READYSTATE_LOADED

Control has been initialized

READYSTATE_INTERACTIVE

Control has enough data to be interactive but not all asynchronous data is yet loaded

READYSTATE_COMPLETE

Control has all its data

Use GetReadyState to determine the control's current readiness.

InternalSetReadyState changes the ready state to the value supplied, then calls FireReadyStateChange.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetReadyState, COleControl::InternalSetReadyState


COleControl::GetActivationPolicy

virtual DWORD GetActivationPolicy( );

Return Value

A combination of flags from the POINTERINACTIVE enumeration. Possible flags are:

POINTERINACTIVE_ACTIVATEONENTRY

The object should be in-place activated when the mouse enters it during a mouse move operation.

POINTERINACTIVE_DEACTIVATEONLEAVE

The object should be deactivated when the mouse leaves the object during a mouse move operation.

POINTERINACTIVE_ACTIVATEONDRAG

The object should be in-place activated when the mouse is dragged over it during a drag and drop operation.

Remarks

Override this function to alter the default activation behavior of a control that supports the IPointerInactive interface.

When the IPointerInactive interface is enabled, the container will delegate WM_SETCURSOR and WM_MOUSEMOVE messages to it. COleControl’s implementation of this interface will dispatch these messages through your control’s message map, after adjusting the mouse coordinates appropriately.

Whenever the container receives a WM_SETCURSOR or WM_MOUSEMOVE message with the mouse pointer over an inactive object supporting IPointerInactive, it should call GetActivationPolicy on the interface and return flags from the POINTERINACTIVE enumeration.

You can process these messages just like ordinary window messages, by adding the corresponding entries to the message map. In your handlers, avoid using the m_hWnd member variable (or any member functions that uses it) without first checking that its value is non-NULL.

Any object intended to do more than set the mouse cursor and/or fire a mouse move event, such as give special visual feedback, should return the POINTERINACTIVE_ACTIVATEONENTRY flag and draw the feedback only when active. If the object returns this flag, the container should activate it in-place immediately and then forward it the same message that triggered the call to GetActivationPolicy.

If both the POINTERINACTIVE_ACTIVATEONENTRY and POINTERINACTIVE_DEACTIVATEONLEAVE flags are returned, then the object will only be activated when the mouse is over the object. If only the POINTERINACTIVE_ACTIVATEONENTRY flag is returned, then the object will only be activated once when the mouse first enters the object.

You may also want an inactive control to be the target of an OLE drag and drop operation. This requires activating the control at the moment the user drags an object over it, so that the control’s window can be registered as a drop target. To cause activation to occur during a drag, return the POINTERINACTIVE_ACTIVATEONDRAG flag:

DWORD CMyCtrl::GetActivationPolicy()
{
    return POINTERINACTIVE_ACTIVATEONDRAG;
}

The information communicated by GetActivationPolicy should not be cached by a container. Instead, this method should be called every time the mouse enters an inactive object.

If an inactive object does not request to be in-place activated when the mouse enters it, its container should dispatch subsequent WM_SETCURSOR messages to this object by calling OnInactiveSetCursor as long as the mouse pointer stays over the object.

Enabling the IPointerInactive interface typically means that you want the control to be capable of processing mouse messages at all times. To get this behaviour in a container that doesn’t support the IPointerInactive interface, you will need to have your control always activated when visible, which means the control should have the OLEMISC_ACTIVATEWHENVISIBLE flag among its miscellaneous flags. However, to prevent this flag from taking effect in a container that does support IPointerInactive, you can also specify the OLEMISC_IGNOREACTIVATEWHENVISIBLE flag:

static const DWORD BASED_CODE _dwMyOleMisc =
    OLEMISC_ACTIVATEWHENVISIBLE |
    OLEMISC_IGNOREACTIVATEWHENVISIBLE |
    OLEMISC_SETCLIENTSITEFIRST |
    OLEMISC_INSIDEOUT |
    OLEMISC_CANTLINKINSIDE |
    OLEMISC_RECOMPOSEONRESIZE;

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnInactiveSetCursor, COleControl::OnInactiveMouseMove


COleControl::GetAmbientProperty

BOOL GetAmbientProperty( DISPID dwDispid, VARTYPE vtProp, void* pvProp );

Return Value

Nonzero if the ambient property is supported; otherwise 0.

Parameters

dwDispid

The dispatch ID of the desired ambient property.

vtProp

A variant type tag that specifies the type of the value to be returned in pvProp.

pvProp

A pointer to the address of the variable that will receive the property value or return value. The actual type of this pointer must match the type specified by vtProp.

vtProp | Type of pvProp
VT_BOOL | BOOL*
VT_BSTR | CString*
VT_I2 | short*
VT_I4 | long*
VT_R4 | float*
VT_R8 | double*
VT_CY | CY*
VT_COLOR | OLE_COLOR*
VT_DISPATCH | LPDISPATCH*
VT_FONT | LPFONTDISP*

Remarks

Call this function to get the value of an ambient property of the container. If you use GetAmbientProperty to retrieve the ambient DisplayName and ScaleUnits properties, set vtProp to VT_BSTR and pvProp to CString*. If you are retrieving the ambient Font property, set vtProp to VT_FONT and pvProp to LPFONTDISP*.

Note that functions have already been provided for common ambient properties, such as AmbientBackColor and AmbientFont.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientForeColor, COleControl::AmbientScaleUnits, COleControl::AmbientShowGrabHandles


COleControl::GetAppearance

short GetAppearance ( );

Return Value

The return value specifies the current appearance setting as a short (VT_I2) value, if successful. This value is zero if the control's appearance is flat and 1 if the control's appearance is 3D.

Remarks

This function implements the Get function of your control’s stock Appearance property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetAppearance, COleControl::OnAppearanceChanged


COleControl::GetBackColor

OLE_COLOR GetBackColor( );

Return Value

The return value specifies the current background color as a OLE_COLOR value, if successful. This value can be translated to a COLORREF value with a call to TranslateColor.

Remarks

This function implements the Get function of your control’s stock BackColor property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientBackColor, COleControl::TranslateColor, COleControl::SetBackColor, COleControl::GetForeColor


COleControl::GetBorderStyle

short GetBorderStyle( );

Return Value

1 if the control has a normal border; 0 if the control has no border.

Remarks

This function implements the Get function of your control’s stock BorderStyle property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetBorderStyle, COleControl::OnBorderStyleChanged


COleControl::GetCapture

CWnd* GetCapture( );

Return Value

If the control is activated and windowless, returns this if the control currently has the mouse capture (as determined by the control’s container), or NULL if it does not have the capture.

Otherwise, returns the CWnd object that has the mouse capture (same as CWnd::GetCapture).

Remarks

Call this function to determine whether the COleControl object has the mouse capture. An activated windowless control receives the mouse capture when SetCapture is called.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetCapture, COleControl::ReleaseCapture


COleControl::GetClassID

virtual HRESULT GetClassID( LPCLSID pclsid ) = 0;

Return Value

Nonzero if the call was not successful; otherwise 0.

Parameters

pclsid

Pointer to the location of the class ID.

Remarks

Called by the framework to retrieve the OLE class ID of the control. Usually implemented by the IMPLEMENT_OLECREATE_EX macro.


COleControl::GetClientOffset

virtual void GetClientOffset( long* pdxOffset, long* pdyOffset ) const;

Parameters

pdxOffset

Pointer to the horizontal offset of the OLE control's client area.

pdyOffset

Pointer to the vertical offset of the OLE control's client area.

Remarks

The OLE control has a rectangular area within its container. The client area of the control is the control area excluding borders and scroll bars. The offset retrieved by GetClientOffset is the difference between the upper left corner of the control's rectangular area and the upper left corner of its client area. If your control has non-client elements other than the standard borders and scrollbars, override this member function to specify the offset.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::ParentToClient, COleControl::ClientToParent


COleControl::GetClientRect

virtual void GetClientRect( LPRECT lpRect ) const;

Parameters

lpRect

Pointer to a RECT structure containing the dimensions of the windowless control's client area; that is, the control's size minus window borders, frames, scroll bars, and so on. The lpRect parameter indicates the size of the control's client rectangle, not its position.

Remarks

Call this function to retrieve the size of the control's client area.


COleControl::GetClientSite

LPOLECLIENTSITE GetClientSite( );

Return Value

A pointer to the control's current client site in its container.

Remarks

Call this function to query an object for the pointer to its current client site within its container.

The returned pointer points to an instance of IOleClientSite. The IOleClientSite interface, implemented by containers, is the object’s view of its context: where it is anchored in the document, where it gets its storage, user interface, and other resources.


COleControl::GetControlFlags

virtual DWORD GetControlFlags( );

Return Value

An ORed combination of the flags in the ControlFlags enumeration:

enum ControlFlags {
   fastBeginPaint = 0x0001,
   clipPaintDC = 0x0002,
   pointerInactive = 0x0004,
   noFlickerActivate = 0x0008,
   windowlessActivate = 0x0010,
   canOptimizeDraw = 0x0020,
};

Remarks

Override this function to specify the control flag settings. By default, GetControlFlags returns fastBeginPaint | clipPaintDC.

fastBeginPaint

If set, uses a begin-paint function tailored for OLE controls instead of the BeginPaint API (set by default).

clipPaintDC

If not set, disables the call to IntersectClipRect made by COleControl and gains a small speed advantage. If you are using windowless activation, the flag has no effect.

pointerInactive

If set, provides mouse interaction while your control is inactive by enabling COleControl's implementation of the IPointerInactive interface, which is disabled by default.

noFlickerActivate

If set, eliminates extra drawing operations and the accompanying visual flicker. Use when your control draws itself identically in the inactive and active states. If you are using windowless activation, the flag has no effect.

windowlessActivate

If set, indicates your control uses windowless activation.

canOptimizeDraw

If set, indicates that the control will perform optimized drawing, if the container supports it.

For more information about GetControlFlags and other optimizations of OLE controls, see ActiveX Controls: Optimization.

COleControl Overview | Class Members | Hierarchy Chart

See Also CDC::IntersectClipRect, COleControl::SetControlSize


COleControl::GetControlSize

void GetControlSize( int* pcx, int* pcy );

Parameters

pcx

Specifies the width of the control in pixels.

pcy

Specifies the height of the control in pixels.

Remarks

Call this function to retrieve the size of the OLE control window.

Note that all coordinates for control windows are relative to the upper-left corner of the control.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetRectInContainer, COleControl::SetControlSize


COleControl::GetDC

CDC* GetDC( LPCRECT lprcRect = NULL, DWORD dwFlags = OLEDC_PAINTBKGND );

Return Value

Pointer to the display device context for the container CWnd client area if successful; otherwise, the return value is NULL. The display device context can be used in subsequent GDI functions to draw in the client area of the container's window.

Parameters

lprcRect

A pointer to the rectangle the windowless control wants to redraw, in client coordinates of the control. NULL means the full object’s extent.

dwFlags

Drawing attributes of the device context. Choices are:

  • OLEDC_NODRAW Indicates that the object won’t use the device context to perform any drawing but merely to get information about the display device. The container should simply pass the window’s DC without further processing.

  • OLEDC_PAINTBKGND Requests that the container paint the background before returning the DC. An object should use this flag if it is requesting a DC for redrawing an area with transparent background.

  • OLEDC_OFFSCREEN Informs the container that the object wishes to render into an off-screen bitmap that should then be copied to the screen. An object should use this flag when the drawing operation it is about to perform generates a lot of flicker. The container is free to honor this request or not. However, if this flag is not set, the container must hand back an on-screen DC. This allows objects to perform direct screen operations such as showing a selection (via an XOR operation).

Remarks

Call this function to provide a means for a windowless object to get a screen (or compatible) device context from its container. The ReleaseDC member function must be called to release the context after painting. When calling GetDC, objects pass the rectangle they wish to draw into in their own client coordinates. GetDC translates these to coordinates of the container client area. The object should not request a desired drawing rectangle larger than its own client area rectangle, the size of which can be retrieved with GetClientRect. This prevents objects from inadvertently drawing where they are not supposed to.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::ReleaseDC


COleControl::GetEnabled

BOOL GetEnabled( );

Return Value

Nonzero if the control is enabled; otherwise 0.

Remarks

This function implements the Get function of your control’s stock Enabled property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetEnabled, COleControl::OnEnabledChanged


COleControl::GetExtendedControl

LPDISPATCH GetExtendedControl( );

Return Value

A pointer to the container’s extended control object. If there is no object available, the value is NULL.

This object may be manipulated through its IDispatch interface. You can also use QueryInterface to obtain other available interfaces provided by the object. However, the object is not required to support a specific set of interfaces. Note that relying on the specific features of a container’s extended control object limits the portability of your control to other arbitrary containers.

Remarks

Call this function to obtain a pointer to an object maintained by the container that represents the control with an extended set of properties. The function that calls this function is responsible for releasing the pointer when finished with the object. Note that the container is not required to support this object.


COleControl::GetFocus

CWnd* GetFocus( );

Return Value

If the control is activated and windowless, returns this if the control currently has the keyboard focus (as determined by the control’s container), or NULL if it does not have the focus.

Otherwise, returns the CWnd object that has the focus (same as CWnd::GetFocus).

Remarks

Call this function to determine whether the COleControl object has the focus. An activated windowless control receives the focus when SetFocus is called.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetFocus


COleControl::GetFont

LPFONTDISP GetFont( );

Return Value

A pointer to the font dispatch interface of the control’s stock Font property.

Remarks

This function implements the Get function of the stock Font property. Note that the caller must release the object when finished. Within the implementation of the control, use InternalGetFont to access the control’s stock Font object. For more information on using fonts in your control, see the article ActiveX Controls: Using Fonts in an ActiveX Control in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetFont, COleControl::AmbientFont, COleControl::InternalGetFont


COleControl::GetFontTextMetrics

void GetFontTextMetrics( LPTEXTMETRIC lptm, CFontHolder& fontHolder );

Parameters

lptm

Pointer to a TEXTMETRIC structure.

fontHolder

Reference to a CFontHolder object.

Remarks

Call this function to measure the text metrics for any CFontHolder object owned by the control. Such a font can be selected with the COleControl::SelectFontObject function. GetFontTextMetrics will initialize the TEXTMETRIC structure pointed to by lptm with valid metrics information about fontHolder's font if successful, or fill the structure with zeros if not successful. You should use this function instead of ::GetTextMetrics when painting your control because controls, like any embedded OLE object, may be required to render themselves into a metafile.

The TEXTMETRIC structure for the default font is refreshed when the SelectFontObject function is called. You should call GetFontTextMetrics only after selecting the stock Font property to assure the information it provides is valid.


COleControl::GetForeColor

OLE_COLOR GetForeColor( );

Return Value

The return value specifies the current foreground color as a OLE_COLOR value, if successful. This value can be translated to a COLORREF value with a call to TranslateColor.

Remarks

This function implements the Get function of the stock ForeColor property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientForeColor, COleControl::TranslateColor, COleControl::GetBackColor, COleControl::SetForeColor


COleControl::GetHwnd

OLE_HANDLE GetHwnd( );

Return Value

The OLE control’s window handle, if any; otherwise NULL.

Remarks

This function implements the Get function of the stock hWnd property.


COleControl::GetMessageString

virtual void GetMessageString( UINT nID, CString& rMessage ) const;

Parameters

nID

A menu item ID.

rMessage

A reference to a CString object through which a string will be returned.

Remarks

Called by the framework to obtain a short string that describes the purpose of the menu item identified by nID. This can be used to obtain a message for display in a status bar while the menu item is highlighted. The default implementation attempts to load a string resource identified by nID.


COleControl::GetNotSupported

void GetNotSupported( );

Remarks

Call this function in place of the Get function of any property where retrieval of the property by the control’s user is not supported. One example would be a property that is write-only.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetNotSupported


COleControl::GetReadyState

long GetReadyState( );

Return Value

The readiness state of the control, one of the following values:

READYSTATE_UNINITIALIZED

Default initialization state

READYSTATE_LOADING

Control is currently loading its properties

READYSTATE_LOADED

Control has been initialized

READYSTATE_INTERACTIVE

Control has enough data to be interactive but not all asynchronous data is yet loaded

READYSTATE_COMPLETE

Control has all its data

Remarks

Call this function to return the readiness state of the control.

Most simple controls never need to differentiate between LOADED and INTERACTIVE. However, controls that support data path properties may not be ready to be interactive until at least some data is received asynchronously. A control should attempt to become interactive as soon as possible.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireReadyStateChange, COleControl::InternalSetReadyState


COleControl::GetRectInContainer

BOOL GetRectInContainer( LPRECT lpRect );

Return Value

Nonzero if the control is in-place active; otherwise 0.

Parameters

lpRect

A pointer to the rectangle structure into which the control’s coordinates will be copied.

Remarks

Call this function to obtain the coordinates of the control’s rectangle relative to the container, expressed in device units. The rectangle is only valid if the control is in-place active.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetRectInContainer, COleControl::GetControlSize


COleControl::GetStockTextMetrics

void GetStockTextMetrics( LPTEXTMETRIC lptm );

Parameters

lptm

A pointer to a TEXTMETRIC structure.

Remarks

Call this function to measure the text metrics for the control's stock Font property, which can be selected with the SelectStockFont function. The GetStockTextMetrics function will initialize the TEXTMETRIC structure pointed to by lptm with valid metrics information if successful, or fill the structure with zeros if not successful. Use this function instead of ::GetTextMetrics when painting your control because controls, like any embedded OLE object, may be required to render themselves into a metafile.

The TEXTMETRIC structure for the default font is refreshed when the SelectStockFont function is called. You should call this function only after selecting the stock font to assure the information it provides is valid.


COleControl::GetText

BSTR GetText( );

Return Value

The current value of the control text string or a zero-length string if no string is present.

Note For more information on the BSTR data type, see Data Types in the Macros and Globals section.

Remarks

This function implements the Get function of the stock Text or Caption property. Note that the caller of this function must call SysFreeString on the string returned in order to free the resource. Within the implementation of the control, use InternalGetText to access the control’s stock Text or Caption property.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::InternalGetText, COleControl::SetText


COleControl::GetWindowlessDropTarget

virtual IDropTarget* GetWindowlessDropTarget( );

Return Value

Pointer to the object's IDropTarget interface. Since it does not have a window, a windowless object cannot register an IDropTarget interface. However, to participate in drag and drop, a windowless object can still implement the interface and return it in GetWindowlessDropTarget.

Remarks

Override GetWindowlessDropTarget when you want a windowless control to be the target of an OLE drag and drop operation. Normally, this would require that the control’s window be registered as a drop target. But since the control has no window of its own, the container will use its own window as a drop target. The control simply needs to provide an implementation of the IDropTarget interface to which the container can delegate calls at the appropriate time. For example:

IDropTarget* CMyCtrl::GetWindowlessDropTarget()
{
    m_xDropTarget.AddRef();
    return &m_xDropTarget;
}


COleControl::InitializeIIDs

void InitializeIIDs( const IID* piidPrimary, const IID* piidEvents );

Parameters

piidPrimary

Pointer to the interface ID of the control’s primary dispatch interface.

piidEvents

Pointer to the interface ID of the control’s event interface.

Remarks

Call this function in the control’s constructor to inform the base class of the interface IDs your control will be using.


COleControl::InternalGetFont

CFontHolder& InternalGetFont( );

Return Value

A reference to a CFontHolder object that contains the stock Font object.

Remarks

Call this function to access the stock Font property of your control

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetFont, COleControl::SetFont


COleControl::InternalGetText

const CString& InternalGetText( );

Return Value

A reference to the control text string.

Remarks

Call this function to access the stock Text or Caption property of your control.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetText, COleControl::SetText


COleControl::InternalSetReadyState

void InternalSetReadyState( long lNewReadyState );

Parameters

lNewReadyState

The readiness state to set for the control, one of the following values:

READYSTATE_UNINITIALIZED

Default initialization state

READYSTATE_LOADING

Control is currently loading its properties

READYSTATE_LOADED

Control has been initialized

READYSTATE_INTERACTIVE

Control has enough data to be interactive but not all asynchronous data is yet loaded

READYSTATE_COMPLETE

Control has all its data

Remarks

Call this function to set the readiness state of the control.

Most simple controls never need to differentiate between LOADED and INTERACTIVE. However, controls that support data path properties may not be ready to be interactive until at least some data is received asynchronously. A control should attempt to become interactive as soon as possible.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireReadyStateChange, COleControl::GetReadyState


COleControl::InvalidateControl

void InvalidateControl( LPCRECT lpRect = NULL );

Parameters

lpRect

A pointer to the region of the control to be invalidated.

Remarks

Call this function to force the control to redraw itself. If lpRect has a NULL value, the entire control will be redrawn. If lpRect is not NULL, this indicates the portion of the control’s rectangle that is to be invalidated. In cases where the control has no window, or is currently not active, the rectangle is ignored, and a call is made to the client site’s IAdviseSink::OnViewChange member function. Use this function instead of CWnd::InvalidateRect or ::InvalidateRect.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::Refresh


COleControl::InvalidateRgn

void InvalidateRgn( CRgn* pRgn, BOOL bErase = TRUE );

Parameters

pRgn

A pointer to a CRgn object that identifies the display region of the OLE object to invalidate, in client coordinates of the containing window. If this parameter is NULL, the extent is the entire object.

bErase

Specifies whether the background within the invalidated region is to be erased. If TRUE, the background is erased. If FALSE, the background remains unchanged.

Remarks

Call this function to invalidate the container window's client area within the given region. This can be used to redraw windowless controls within the container. The invalidated region, along with all other areas in the update region, is marked for painting when the next WM_PAINT message is sent.

If bErase is TRUE for any part of the update region, the background in the entire region, not just in the given part, is erased.


COleControl::IsConvertingVBX

BOOL IsConvertingVBX( );

Return Value

Nonzero if the control is being converted; otherwise 0.

Remarks

When converting a form that uses VBX controls to one that uses OLE controls, special loading code for the OLE controls may be required. For example, if you are loading an instance of your OLE control, you might have a call to PX_Font in your DoPropExchange:

PX_Font(pPx, "Font", m_MyFont, pDefaultFont);

However, VBX controls did not have a Font object; each font property was saved individually. In this case, you would use IsConvertingVBX to distinguish between these two cases:

if (IsConvertingVBX()==FALSE)
    PX_Font(pPX, "Font", m_MyFont, pDefaultFont);
else
{
    PX_String(pPX, "FontName", tempString, DefaultName);
    m_MyFont->put_Name(tempString);
    PX_Bool(pPX, "FontUnderline", tempBool, DefaultValue);
    m_MyFont->put_Underline(tempBool);
...
}

Another case would be if your VBX control saved proprietary binary data (in its VBM_SAVEPROPERTY message handler), and your OLE control saves its binary data in a different format. If you want your OLE control to be backward-compatible with the VBX control, you could read both the old and new formats using the IsConvertingVBX function by distinguishing whether the VBX control or the OLE control was being loaded.

In your control’s DoPropExchange function, you can check for this condition and if true, execute load code specific to this conversion (such as the previous examples). If the control is not being converted, you can execute normal load code. This ability is only applicable to controls being converted from VBX counterparts.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange


COleControl::IsModified

BOOL IsModified( );

Return Value

Nonzero if the control’s state has been modified since it was last saved; otherwise 0.

Remarks

Call this function to determine if the control’s state has been modified. The state of a control is modified when a property changes value.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetModifiedFlag


COleControl::IsOptimizedDraw

BOOL IsOptimizedDraw( );

Return Value

TRUE if the container supports optimized drawing for the current drawing operation; otherwise FALSE.

Remarks

Call this function to determine whether the container supports optimized drawing for the current drawing operation. If optimized drawing is supported, then the control need not select old objects (pens, brushes, fonts, etc.) into the device context when drawing is finished.


COleControl::IsSubclassedControl

virtual BOOL IsSubclassedControl( );

Return Value

Nonzero if the control is subclassed; otherwise 0.

Remarks

Called by the framework to determine if the control subclasses a Windows control. You must override this function and return TRUE if your OLE control subclasses a Windows control.


COleControl::Load

void Load( LPCTSTR strNewPath, CDataPathProperty& prop );

Parameters

strNewPath

A pointer to a string containing the path that references the absolute location of the asynchronous control property.

prop

A CDataPathProperty object implementing an asynchronous control property.

Remarks

Call this function to reset any previous data loaded asynchronously and to initiate a new loading of the control's asynchronous property.

COleControl Overview | Class Members | Hierarchy Chart

See Also CDataPathProperty


COleControl::LockInPlaceActive

BOOL LockInPlaceActive( BOOL bLock );

Return Value

Nonzero if the lock was successful; otherwise 0.

Parameters

bLock

TRUE if the in-place active state of the control is to be locked; FALSE if it is to be unlocked.

Remarks

Call this function to prevent the container from deactivating your control. Note that every locking of the control must be paired with an unlocking of the control when finished. You should only lock your control for short periods, such as while firing an event.


COleControl::OnAmbientPropertyChange

virtual void OnAmbientPropertyChange( DISPID dispID );

Parameters

dispID

The dispatch ID of the ambient property that changed, or DISPID_UNKNOWN if multiple properties have changed.

Remarks

Called by the framework when an ambient property of the container has changed value.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetAmbientProperty


COleControl::OnAppearanceChanged

virtual void OnAppearanceChanged ( );

Remarks

Called by the framework when the stock Appearance property value has changed.

Override this function if you want notification after this property changes. The default implementation calls InvalidateControl.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetAppearance, COleControl::SetAppearance, COleControl::InvalidateControl


COleControl::OnBackColorChanged

virtual void OnBackColorChanged( );

Remarks

Called by the framework when the stock BackColor property value has changed.

Override this function if you want notification after this property changes. The default implementation calls InvalidateControl.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetBackColor, COleControl::InvalidateControl


COleControl::OnBorderStyleChanged

virtual void OnBorderStyleChanged( );

Remarks

Called by the framework when the stock BorderStyle property value has changed. The default implementation calls InvalidateControl.

Override this function if you want notification after this property changes.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetBorderStyle, COleControl::InvalidateControl


COleControl::OnClick

virtual void OnClick( USHORT iButton );

Parameters

iButton

Index of a mouse button. Can have one of the following values:

  • LEFT_BUTTON The left mouse button was clicked.

  • MIDDLE_BUTTON The middle mouse button was clicked.

  • RIGHT_BUTTON The right mouse button was clicked.

Remarks

Called by the framework when a mouse button has been clicked or the DoClick stock method has been invoked. The default implementation calls COleControl::FireClick.

Override this member function to modify or extend the default handling.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::DoClick, COleControl::FireClick


COleControl::OnClose

virtual void OnClose( DWORD dwSaveOption );

Parameters

dwSaveOption

Flag that indicates whether the object should be saved before loading. Valid values are:

  • OLECLOSE_SAVEIFDIRTY

  • OLECLOSE_NOSAVE

  • OLECLOSE_PROMPTSAVE

Remarks

Called by the framework when the container has called the control’s IOleControl::Close function. By default, OnClose saves the control object if it has been modified and dwSaveOption is either OLECLOSE_SAVEIFDIRTY or OLECLOSE_PROMPTSAVE.


COleControl::OnDoVerb

virtual BOOL OnDoVerb( LONG iVerb, LPMSG lpMsg, HWND hWndParent, LPCRECT lpRect );

Return Value

Nonzero if call was successful; otherwise 0.

Parameters

iVerb

The index of the control verb to be invoked.

lpMsg

A pointer to the Windows message that caused the verb to be invoked.

hWndParent

The handle to the parent window of the control. If the execution of the verb creates a window (or windows), hWndParent should be used as the parent.

lpRect

A pointer to a RECT structure into which the coordinates of the control, relative to the container, will be copied.

Remarks

Called by the framework when the container calls the IOleObject::DoVerb member function. The default implementation uses the ON_OLEVERB and ON_STDOLEVERB message map entries to determine the proper function to invoke.

Override this function to change the default handling of verb.

COleControl Overview | Class Members | Hierarchy Chart

See Also ON_OLEVERB, ON_STDOLEVERB, COleControl::OnEnumVerbs


COleControl::OnDraw

virtual void OnDraw( CDC* pDC, const CRect& rcBounds, const CRect& rcInvalid );

Parameters

pDC

The device context in which the drawing occurs.

rcBounds

The rectangular area of the control, including the border.

rcInvalid

The rectangular area of the control that is invalid.

Remarks

Called by the framework to draw the OLE control in the specified bounding rectangle using the specified device context.

OnDraw is typically called for screen display, passing a screen device context as pDC. The rcBounds parameter identifies the rectangle in the target device context (relative to its current mapping mode). The rcInvalid parameter is the actual rectangle that is invalid. In some cases this will be a smaller area than rcBounds.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnDrawMetafile, COleControl::DrawContent, COleControl::DrawMetafile


COleControl::OnDrawMetafile

virtual void OnDrawMetafile( CDC* pDC, const CRect& rcBounds );

Parameters

pDC

The device context in which the drawing occurs.

rcBounds

The rectangular area of the control, including the border.

Remarks

Called by the framework to draw the OLE control in the specified bounding rectangle using the specified metafile device context. The default implementation calls the OnDraw function.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnDraw, COleControl::DrawContent, COleControl::DrawMetafile


COleControl::OnEdit

virtual BOOL OnEdit( LPMSG lpMsg, HWND hWndParent, LPCRECT lpRect );

Return Value

Nonzero if the call is successful; otherwise 0.

Parameters

lpMsg

A pointer to the Windows message that invoked the verb.

hWndParent

A handle to the parent window of the control.

lpRect

A pointer to the rectangle used by the control in the container.

Remarks

Call this function to cause the control to be UI activated. This has the same effect as invoking the control's OLEIVERB_UIACTIVATE verb.

This function is typically used as the handler function for an ON_OLEVERB message map entry. This makes an “Edit” verb available on the control's “Object” menu. For example:

ON_OLEVERB(AFX_IDS_VERB_EDIT, OnEdit)


COleControl::OnEnabledChanged

virtual void OnEnabledChanged( );

Remarks

Called by the framework when the stock Enabled property value has changed.

Override this function if you want notification after this property changes. The default implementation calls InvalidateControl.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetEnabled, COleControl::GetEnabled


COleControl::OnEnumVerbs

virtual BOOL OnEnumVerbs( LPENUMOLEVERB FAR* ppenumOleVerb );

Return Value

Nonzero if verbs are available; otherwise 0.

Parameters

ppenumOleVerb

A pointer to the IEnumOLEVERB object that enumerates the control’s verbs.

Remarks

Called by the framework when the container calls the IOleObject::EnumVerbs member function. The default implementation enumerates the ON_OLEVERB entries in the message map.

Override this function to change the default way of enumerating verbs.

COleControl Overview | Class Members | Hierarchy Chart

See Also ON_OLEVERB, ON_STDOLEVERB


COleControl::OnEventAdvise

virtual void OnEventAdvise( BOOL bAdvise );

Parameters

bAdvise

TRUE indicates that an event handler has been connected to the control. FALSE indicates that an event handler has been disconnected from the control.

Remarks

Called by the framework when an event handler is connected to or disconnected from an OLE control.


COleControl::OnFontChanged

virtual void OnFontChanged( );

Remarks

Called by the framework when the stock Font property value has changed. The default implementation calls COleControl::InvalidateControl. If the control is subclassing a Windows control, the default implementation also sends a WM_SETFONT message to the control’s window.

Override this function if you want notification after this property changes.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetFont, COleControl::InternalGetFont, COleControl::InvalidateControl


COleControl::OnForeColorChanged

virtual void OnForeColorChanged( );

Remarks

Called by the framework when the stock ForeColor property value has changed. The default implementation calls InvalidateControl.

Override this function if you want notification after this property changes.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetForeColor, COleControl::InvalidateControl


COleControl::OnFreezeEvents

virtual void OnFreezeEvents( BOOL bFreeze );

Parameters

bFreeze

TRUE if the control’s event handling is frozen; otherwise FALSE.

Remarks

Called by the framework after the container calls IOleControl::FreezeEvents. The default implementation does nothing.

Override this function if you want additional behavior when event handling is frozen or unfrozen.


COleControl::OnGetColorSet

virtual BOOL OnGetColorSet( DVTARGETDEVICE FAR* ptd, HDC hicTargetDev, LPLOGPALETTE FAR* ppColorSet );

Return Value

Nonzero if a valid color set is returned; otherwise 0.

Parameters

ptd

Points to the target device for which the picture should be rendered. If this value is NULL, the picture should be rendered for a default target device, usually a display device.

hicTargetDev

Specifies the information context on the target device indicated by ptd. This parameter can be a device context, but is not one necessarily. If ptd is NULL, hicTargetDev should also be NULL.

ppColorSet

A pointer to the location into which the set of colors that would be used should be copied. If the function does not return the color set, NULL is returned.

Remarks

Called by the framework when the container calls the IOleObject::GetColorSet member function. The container calls this function to obtain all the colors needed to draw the OLE control. The container can use the color sets obtained in conjunction with the colors it needs to set the overall color palette. The default implementation returns FALSE.

Override this function to do any special processing of this request.


COleControl::OnGetControlInfo

virtual void OnGetControlInfo( LPCONTROLINFO pControlInfo );

Parameters

pControlInfo

Pointer to a CONTROLINFO structure to be filled in.

Remarks

Called by the framework when the control’s container has requested information about the control. This information consists primarily of a description of the control’s mnemonic keys. The default implementation fills pControlInfo with default information.

Override this function if your control needs to process mnemonic keys.


COleControl::OnGetDisplayString

virtual BOOL OnGetDisplayString( DISPID dispid, CString& strValue );

Return Value

Nonzero if a string has been returned in strValue; otherwise 0.

Parameters

dispid

The dispatch ID of a property of the control.

strValue

A reference to a CString object through which a string will be returned.

Remarks

Called by the framework to obtain a string that represents the current value of the property identified by dispid.

Override this function if your control has a property whose value cannot be directly converted to a string and you want the property’s value to be displayed in a container-supplied property browser.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnMapPropertyToPage


COleControl::OnGetInPlaceMenu

virtual HMENU OnGetInPlaceMenu( );

Return Value

The handle of the control’s menu, or NULL if the control has none. The default implementation returns NULL.

Remarks

Called by the framework when the control is UI activated to obtain the menu to be merged into the container’s existing menu.

For more information on merging OLE resources, see the article Menus and Resources (OLE) in Visual C++ Programmer’s Guide.


COleControl::OnGetNaturalExtent

virtual BOOL OnGetNaturalExtent( DWORD dwAspect, LONG lindex, DVTARGETDEVICE* ptd, HDC hicTargetDev, DVEXTENTINFO* pExtentInfo, LPSIZEL psizel );

Return Value

Nonzero if it successfully returns or adjusts the size; otherwise 0.

Parameters

dwAspect

Specifies how the object is to be represented. Representations include content, an icon, a thumbnail, or a printed document. Valid values are taken from the enumeration DVASPECT or DVASPECT2.

lindex

The portion of the object that is of interest. Currently only -1 is valid.

ptd

Points to the DVTARGETDEVICE structure defining the target device for which the object's size should be returned.

hicTargetDev

Specifies the information context for the target device indicated by the ptd parameter from which the object can extract device metrics and test the device's capabilities. If ptd is NULL, the object should ignore the value in the hicTargetDev parameter.

pExtentInfo

Points to the DVEXTENTINFO structure that specifies sizing data. The DVEXTENTINFO structure is:

typedef struct  tagExtentInfo
    {
    UINT cb;
    DWORD dwExtentMode;
    SIZEL sizelProposed;
    }   DVEXTENTINFO;

The structure member dwExtentMode can take one of two values:

  • DVEXTENT_CONTENT Inquire how big the control should be to exactly fit content (snap-to-size)

  • DVEXTENT_INTEGRAL When resizing, pass proposed size to control

psizel

Points to sizing data returned by control. The returned sizing data is set to -1 for any dimension that was not adjusted.

Remarks

Called by the framework in response to a container’s IViewObjectEx::GetNaturalExtent request. Override this function to return the object's display size closest to the proposed size and extent mode in the DVEXTENTINFO structure. The default implementation returns FALSE and makes no adjustments to the size.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnGetViewExtent


COleControl::OnGetPredefinedStrings

virtual BOOL OnGetPredefinedStrings( DISPID dispid, CStringArray* pStringArray, CDWordArray* pCookieArray );

Return Value

Nonzero if elements have been added to pStringArray and pCookieArray.

Parameters

dispid

The dispatch ID of a property of the control.

pStringArray

A string array to be filled in with return values.

pCookieArray

A DWORD array to be filled in with return values.

Remarks

Called by the framework to obtain a set of predefined strings representing the possible values for a property.

Override this function if your control has a property with a set of possible values that can be represented by strings. For each element added to pStringArray, you should add a corresponding “cookie” element to pCookieArray. These “cookie” values may later be passed by the framework to the COleControl::OnGetPredefinedValue function.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnGetPredefinedValue, COleControl::OnGetDisplayString


COleControl::OnGetPredefinedValue

virtual BOOL OnGetPredefinedValue( DISPID dispid, DWORD dwCookie, VARIANT FAR* lpvarOut );

Return Value

Nonzero if a value has been returned in lpvarOut; otherwise 0.

Parameters

dispid

The dispatch ID of a property of the control.

dwCookie

A cookie value previously returned by an override of COleControl::OnGetPredefinedStrings.

lpvarOut

Pointer to a VARIANT structure through which a property value will be returned.

Remarks

Called by the framework to obtain the value corresponding to one of the predefined strings previously returned by an override of COleControl::OnGetPredefinedStrings.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnGetPredefinedStrings, COleControl::OnGetDisplayString


COleControl::OnGetViewExtent

virtual BOOL OnGetViewExtent( DWORD dwDrawAspect, LONG lindex, DVTARGETDEVICE* ptd, LPSIZEL lpsizel );

Return Value

Nonzero if extent information is successfully returned; otherwise 0.

Parameters

dwDrawAspect

DWORD describing which form, or aspect, of an object is to be displayed. Valid values are taken from the enumeration DVASPECT or DVASPECT2.

lindex

The portion of the object that is of interest. Currently only –1 is valid.

ptd

Points to the DVTARGETDEVICE structure defining the target device for which the object's size should be returned.

lpsizel

Points to the location where the object's size is returned.

Remarks

Called by the framework in response to a container’s IViewObject2::GetExtent request. Override this function if your control uses two-pass drawing, and its opaque and transparent parts have different dimensions.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnGetViewRect


COleControl::OnGetViewRect

virtual BOOL OnGetViewRect( DWORD dwAspect, LPRECTL pRect );

Return Value

Nonzero if the rectangle sized to the object is successfully returned; otherwise 0.

Parameters

dwAspect

DWORD describing which form, or aspect, of an object is to be displayed. Valid values are taken from the enumeration DVASPECT or DVASPECT2:

  • DVASPECT_CONTENT Bounding rectangle of the whole object. Top-left corner at the object’s origin and size equal to the extent returned by GetViewExtent.

  • DVASPECT_OPAQUE Objects with a rectangular opaque region return that rectangle. Others fail.

  • DVASPECT_TRANSPARENT Rectangle covering all transparent or irregular parts.

pRect

Points to the RECTL structure specifying the rectangle in which the object should be drawn. This parameter controls the positioning and stretching of the object.

Remarks

Called by the framework in response to a container’s IViewObjectEx::GetRect request. The object's size is converted by OnGetViewRect into a rectangle starting at a specific position (the default is the upper left corner of the display). Override this function if your control uses two-pass drawing, and its opaque and transparent parts have different dimensions.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnGetViewExtent


COleControl::OnGetViewStatus

virtual DWORD OnGetViewStatus( );

Return Value

One of the values of the VIEWSTATUS enumeration if successful; otherwise 0. Possible values are any combination of the following:

VIEWSTATUS_OPAQUE

Object is completely opaque. If this bit is not set, the object contains transparent parts. This bit applies only to content-related aspects and not to DVASPECT_ICON or DVASPECT_DOCPRINT.

VIEWSTATUS_SOLIDBKGND

Object has a solid background (consisting in a solid color, not a brush pattern). This bit is meaningful only if VIEWSTATUS_OPAQUE is set and applies only to content-related aspects and not to DVASPECT_ICON or DVASPECT_DOCPRINT.

VIEWSTATUS_DVASPECTOPAQUE

Object supports DVASPECT_OPAQUE. All IViewObjectEx methods that take a drawing aspect as a parameter can be called with this aspect.

VIEWSTATUS_DVASPECTTRANSPARENT

Object supports DVASPECT_TRANSPARENT. All IViewObjectEx methods that take a drawing aspect as a parameter can be called with this aspect.

Remarks

Called by the framework in response to a container’s IViewObjectEx::GetViewStatus request. Override this function if your control uses two-pass drawing. The default implementation returns VIEWSTATUS_OPAQUE.

COleControl Overview | Class Members | Hierarchy Chart

See Also DVASPECT


COleControl::OnHideToolBars

virtual void OnHideToolBars( );

Remarks

Called by the framework when the control is UI deactivated. The implementation should hide all toolbars displayed by OnShowToolbars.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnShowToolbars


COleControl::OnInactiveMouseMove

virtual void OnInactiveMouseMove( LPCRECT lprcBounds, long x, long y, DWORD dwKeyState );

Parameters

lprcBounds

The object bounding rectangle, in client coordinates of the containing window. Tells the object its exact position and size on the screen when the WM_MOUSEMOVE message was received.

x

The x coordinate of the mouse location in client coordinates of the containing window.

y

The y coordinate of the mouse location in client coordinates of the containing window.

dwKeyState

Identifies the current state of the keyboard modifier keys on the keyboard. Valid values can be a combination of any of the flags MK_CONTROL, MK_SHIFT, MK_ALT, MK_BUTTON, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.

Remarks

Called by the container for the inactive object under the mouse pointer on receipt of a WM_MOUSEMOVE message. Note that window client coordinates (pixels) are used to pass the mouse cursor position. This is made possible by also passing the bounding rectangle of the object in the same coordinate system.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetActivationPolicy, COleControl::OnInactiveSetCursor


COleControl::OnInactiveSetCursor

virtual BOOL OnInactiveSetCursor( LPCRECT lprcBounds, long x, long y, DWORD dwMouseMsg, BOOL bSetAlways );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lprcBounds

The object bounding rectangle, in client coordinates of the containing window. Tells the object its exact position and size on the screen when the WM_SETCURSOR message was received.

x

The x coordinate of the mouse location in client coordinates of the containing window.

y

The y coordinate of the mouse location in client coordinates of the containing window.

dwMouseMsg

The identifier of the mouse message for which a WM_SETCURSOR occurred.

bSetAlways

Specifies whether or not the object must set the cursor. If TRUE, the object must set the cursor; if FALSE, the cursor is not obligated to set the cursor, and should return S_FALSE in that case.

Remarks

Called by the container for the inactive object under the mouse pointer on receipt of a WM_SETCURSOR message. Note that window client coordinates (pixels) are used to pass the mouse cursor position. This is made possible by also passing the bounding rectangle of the object in the same coordinate system.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetActivationPolicy, COleControl::OnInactiveMouseMove


COleControl::OnKeyDownEvent

virtual void OnKeyDownEvent( USHORT nChar, USHORT nShiftState );

Parameters

nChar

The virtual-key code value of the pressed key.

nShiftState

Contains a combination of the following flags:

  • SHIFT_MASK The SHIFT key was pressed during the action.

  • CTRL_MASK The CTRL key was pressed during the action.

  • ALT_MASK The ALT key was pressed during the action.

Remarks

Called by the framework after a stock KeyDown event has been processed.

Override this function if your control needs access to the key information after the event has been fired.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnKeyUpEvent, COleControl::OnKeyPressEvent


COleControl::OnKeyPressEvent

virtual void OnKeyPressEvent( USHORT nChar );

Parameters

nChar

Contains the virtual-key code value of the key pressed.

Remarks

Called by the framework after the stock KeyPress event has been fired. Note that the nChar value may have been modified by the container.

Override this function if you want notification after this event occurs.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireKeyPress


COleControl::OnKeyUpEvent

virtual void OnKeyUpEvent( USHORT nChar, USHORT nShiftState );

Parameters

nChar

The virtual-key code value of the pressed key.

nShiftState

Contains a combination of the following flags:

  • SHIFT_MASK The SHIFT key was pressed during the action.

  • CTRL_MASK The CTRL key was pressed during the action.

  • ALT_MASK The ALT key was pressed during the action.

Remarks

Called by the framework after a stock KeyDown event has been processed.

Override this function if your control needs access to the key information after the event has been fired.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnKeyDownEvent, COleControl::OnKeyPressEvent


COleControl::OnMapPropertyToPage

virtual BOOL OnMapPropertyToPage( DISPID dispid, LPCLSID lpclsid, BOOL* pbPageOptional );

Return Value

Nonzero if a class ID has been returned in lpclsid; otherwise 0.

Parameters

dispid

The dispatch ID of a property of the control.

lpclsid

Pointer to a CLSID structure through which a class ID will be returned.

pbPageOptional

Returns an indicator of whether use of the specified property page is optional.

Remarks

Called by the framework to obtain the class ID of a property page that implements editing of the specified property.

Override this function to provide a way to invoke your control’s property pages from the container’s property browser.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnGetDisplayString


COleControl::OnMnemonic

virtual void OnMnemonic( LPMSG pMsg );

Parameters

pMsg

Pointer to the Windows message generated by a mnemonic key press.

Remarks

Called by the framework when the container has detected that a mnemonic key of the OLE control has been pressed.


COleControl::OnProperties

virtual BOOL OnProperties( LPMSG lpMsg, HWND hWndParent, LPCRECT lpRect );

Return Value

Nonzero if the call is successful; otherwise 0.

Parameters

lpMsg

A pointer to the Windows message that invoked the verb.

hWndParent

A handle to the parent window of the control.

lpRect

A pointer to the rectangle used by the control in the container.

Remarks

Called by the framework when the control’s properties verb has been invoked by the container. The default implementation displays a modal property dialog box.


COleControl::OnQueryHitPoint

virtual BOOL OnQueryHitPoint( DWORD dwAspect, LPCRECT pRectBounds, POINT ptlLoc, LONG lCloseHint, DWORD* pHitResult );

Return Value

Nonzero if a hit result is successfully returned; otherwise 0. A hit is an overlap with the OLE control display area.

Parameters

dwAspect

Specifies how the object is represented. Valid values are taken from the enumeration DVASPECT or DVASPECT2.

pRectBounds

Pointer to a RECT structure specifying the bounding rectangle of the OLE control client area.

ptlLoc

Pointer to the POINT structure specifying the point to be checked for a hit. The point is specified in OLE client area coordinates.

lCloseHint

The distance that defines "close" to the point checked for a hit.

pHitResult

Pointer to the result of the hit query. One of the following values:

  • HITRESULT_OUTSIDE ptlLoc is outside the OLE object and not close.

  • HITRESULT_TRANSPARENT ptlLoc is within the bounds of the OLE object, but not close to the image. For example, a point in the middle of a transparent circle could be HITRESULT_TRANSPARENT.

  • HITRESULT_CLOSE ptlLoc is inside or outside the OLE object but close enough to the object to be considered inside. Small, thin, or detailed objects may use this value. Even if a point is outside the bounding rectangle of an object it may still be close (this is needed for hitting small objects).

  • HITRESULT_HIT ptlLoc is within the image of the object.

Remarks

Called by the framework in response to a container’s IViewObjectEx::QueryHitPoint request. Queries whether an object's display rectangle overlaps the given point (hits the point). QueryHitPoint can be overridden to test hits for non-rectangular objects.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnQueryHitRect


COleControl::OnQueryHitRect

virtual BOOL OnQueryHitRect( DWORD dwAspect, LPCRECT pRectBounds, LPCRECT prcLoc, LONG lCloseHint, DWORD* pHitResult );

Return Value

Nonzero if a hit result is successfully returned; otherwise 0.

Parameters

dwAspect

Specifies how the object is to be represented. Valid values are taken from the enumeration DVASPECT or DVASPECT2.

pRectBounds

Pointer to a RECT structure specifying the bounding rectangle of the OLE control client area.

prcLoc

Pointer to the RECT structure specifying the rectangle to be checked for a hit (overlap with the object rectangle), relative to the upper left corner of the object.

lCloseHint

Not used.

pHitResult

Pointer to the result of the hit query. One of the following values:

  • HITRESULT_OUTSIDE no point in the rectangle is hit by the OLE object.

  • HITRESULT_HIT at least one point in the rectangle would be a hit on the object.

Remarks

Called by the framework in response to a container’s IViewObjectEx::QueryHitRect request. Queries whether an object's display rectangle overlaps any point in the given rectangle (hits the rectangle). QueryHitRect can be overridden to test hits for non-rectangular objects.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnQueryHitPoint


COleControl::OnRenderData

virtual BOOL OnRenderData( LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

lpStgMedium

Points to a STGMEDIUM structure in which the data is to be returned.

Remarks

Called by the framework to retrieve data in the specified format. The specified format is one previously placed in the control object using the DelayRenderData or DelayRenderFileData member functions for delayed rendering. The default implementation of this function calls OnRenderFileData or OnRenderGlobalData, respectively, if the supplied storage medium is either a file or memory. If the requested format is CF_METAFILEPICT or the persistent property set format, the default implementation renders the appropriate data and returns nonzero. Otherwise, it returns 0 and does nothing.

If lpStgMedium->tymed is TYMED_NULL, the STGMEDIUM should be allocated and filled as specified by lpFormatEtc->tymed. If not TYMED_NULL, the STGMEDIUM should be filled in place with the data.

Override this function to provide your data in the requested format and medium. Depending on your data, you may want to override one of the other versions of this function instead. If your data is small and fixed in size, override OnRenderGlobalData. If your data is in a file, or is of variable size, override OnRenderFileData.

For more information, see the FORMATETC and STGMEDIUM structures in the OLE documentation.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnRenderFileData, COleControl::OnRenderGlobalData


COleControl::OnRenderFileData

virtual BOOL OnRenderFileData( LPFORMATETC lpFormatEtc, CFile* pFile );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

pFile

Points to a CFile object in which the data is to be rendered.

Remarks

Called by the framework to retrieve data in the specified format when the storage medium is a file. The specified format is one previously placed in the control object using the DelayRenderData member function for delayed rendering. The default implementation of this function simply returns FALSE.

Override this function to provide your data in the requested format and medium. Depending on your data, you might want to override one of the other versions of this function instead. If you want to handle multiple storage mediums, override OnRenderData. If your data is in a file, or is of variable size, override OnRenderFileData.

For more information, see the FORMATETC structure in the OLE documentation.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnRenderData, COleControl::OnRenderGlobalData


COleControl::OnRenderGlobalData

virtual BOOL OnRenderGlobalData( LPFORMATETC lpFormatEtc, HGLOBAL* phGlobal );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

phGlobal

Points to a handle to global memory in which the data is to be returned. If no memory has been allocated, this parameter can be NULL.

Remarks

Called by the framework to retrieve data in the specified format when the specified storage medium is global memory. The specified format is one previously placed in the control object using the DelayRenderData member function for delayed rendering. The default implementation of this function simply returns FALSE.

If phGlobal is NULL, then a new HGLOBAL should be allocated and returned in phGlobal. Otherwise, the HGLOBAL specified by phGlobal should be filled with the data. The amount of data placed in the HGLOBAL must not exceed the current size of the memory block. Also, the block cannot be reallocated to a larger size.

Override this function to provide your data in the requested format and medium. Depending on your data, you may want to override one of the other versions of this function instead. If you want to handle multiple storage mediums, override OnRenderData. If your data is in a file, or is of variable size, override OnRenderFileData.

For more information, see the FORMATETC structure in the OLE documentation.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnRenderFileData, COleControl::OnRenderData


COleControl::OnResetState

virtual void OnResetState( );

Remarks

Called by the framework when the control’s properties should be set to their default values. The default implementation calls DoPropExchange, passing a CPropExchange object that causes properties to be set to their default values.

The control writer can insert initialization code for the OLE control in this overridable. This function is called when IPersistStream::Load or IPersistStorage::Load fails, or IPersistStreamInit::InitNew or IPersistStorage::InitNew is called, without first calling either IPersistStream::Load or IPersistStorage::Load.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnSetClientSite


COleControl::OnSetClientSite

virtual void OnSetClientSite( );

Remarks

Called by the framework when the container has called the control’s IOleControl::SetClientSite function. By default, OnSetClientSite checks whether data path properties are loaded and, if they are, calls DoDataPathPropExchange.

Override this function to do any special processing of this notification. In particular, overrides of this function should call the base class.


COleControl::OnSetData

virtual BOOL OnSetData( LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium, BOOL bRelease );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Pointer to a FORMATETC structure specifying the format of the data.

lpStgMedium

Pointer to a STGMEDIUM structure in which the data resides.

bRelease

TRUE if the control should free the storage medium; FALSE if if the control should not free the storage medium.

Remarks

Called by the framework to replace the control’s data with the specified data. If the data is in the persistent property set format, the default implementation modifies the control’s state accordingly. Otherwise, the default implementation does nothing. If bRelease is TRUE, then a call to ReleaseStgMedium is made; otherwise not.

Override this function to replace the control’s data with the specified data.

For more information, see the FORMATETC and STGMEDIUM structures in the OLE documentation.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange


COleControl::OnSetExtent

virtual BOOL OnSetExtent( LPSIZEL lpSizeL );

Return Value

Nonzero if the size change was accepted; otherwise 0.

Parameters

lpSizeL

A pointer to the SIZEL structure that uses long integers to represent the width and height of the control, expressed in HIMETRIC units.

Remarks

Called by the framework when the control’s extent needs to be changed, as a result of a call to IOleObject::SetExtent. The default implementation handles the resizing of the control’s extent. If the control is in-place active, a call to the container’s OnPosRectChanged is then made.

Override this function to alter the default resizing of your control.


COleControl::OnSetObjectRects

virtual BOOL OnSetObjectRects( LPCRECT lpRectPos, LPCRECT lpRectClip );

Return Value

Nonzero if the repositioning was accepted; otherwise 0.

Parameters

lpRectPos

A pointer to a RECT structure indicating the control’s new position and size relative to the container.

lpRectClip

A pointer to a RECT structure indicating a rectangular area to which the control is to be clipped.

Remarks

Called by the framework to implement a call to IOleInPlaceObject::SetObjectRects. The default implementation automatically handles the repositioning and resizing of the control window and returns TRUE.

Override this function to alter the default behavior of this function.


COleControl::OnShowToolBars

virtual void OnShowToolBars( );

Remarks

Called by the framework when the control has been UI activated. The default implementation does nothing.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::OnHideToolbars


COleControl::OnTextChanged

virtual void OnTextChanged( );

Remarks

Called by the framework when the stock Caption or Text property value has changed. The default implementation calls InvalidateControl.

Override this function if you want notification after this property changes.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetText, COleControl::InternalGetText, COleControl::InvalidateControl


COleControl::OnWindowlessMessage

virtual BOOL OnWindowlessMessage( UINT msg, WPARAM wParam, LPARAM lParam, LRESULT* plResult );

Return Value

Nonzero if successful; otherwise 0.

Parameters

msg

Message identifier as passed by Windows.

wParam

As passed by Windows. Specifies additional message-specific information. The contents of this parameter depend on the value of the msg parameter.

lParam

As passed by Windows. Specifies additional message-specific information. The contents of this parameter depend on the value of the msg parameter.

plResult

Windows result code. Specifies the result of the message processing and depends on the message sent.

Remarks

Called by the framework in response to a container’s IOleInPlaceObjectWindowless::OnWindowMessage request. Processes window messages for windowless controls. COleControl's OnWindowlessMessage should be used for window messages other than mouse messages and keyboard messages. COleControl provides SetCapture and SetFocus specifically to get mouse capture and keyboard focus for windowless OLE objects.

Since windowless objects do not have a window, they need a mechanism to let the container dispatch messages to them. A windowless OLE object gets messages from its container, via the OnWindowMessage method on the IOleInPlaceObjectWindowless interface (an extension of IOleInPlaceObject for windowless support). OnWindowMessage does not take an HWND parameter.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetCapture, COleControl::SetFocus, COleControl::GetWindowlessDropTarget


COleControl::ParentToClient

virtual UINT ParentToClient( LPCRECT lprcBounds, LPPOINT pPoint, BOOL bHitTest = FALSE ) const;

Return Value

If bHitTest is FALSE, returns HTNOWHERE. If bHitTest is TRUE, returns the location in which the parent (container) point landed in the client area of the OLE control and is one of the following mouse hit-test values:

  • HTBORDER In the border of a window that does not have a sizing border.

  • HTBOTTOM In the lower horizontal border of the window.

  • HTBOTTOMLEFT In the lower-left corner of the window border.

  • HTBOTTOMRIGHT In the lower-right corner of the window border.

  • HTCAPTION In a title-bar area.

  • HTCLIENT In a client area.

  • HTERROR On the screen background or on a dividing line between windows (same as HTNOWHERE except that the DefWndProc Windows function produces a system beep to indicate an error).

  • HTGROWBOX In a size box.

  • HTHSCROLL In the horizontal scroll bar.

  • HTLEFT In the left border of the window.

  • HTMAXBUTTON In a Maximize button.

  • HTMENU In a menu area.

  • HTMINBUTTON In a Minimize button.

  • HTNOWHERE On the screen background or on a dividing line between windows.

  • HTREDUCE In a Minimize button.

  • HTRIGHT In the right border of the window.

  • HTSIZE In a size box (same as HTGROWBOX).

  • HTSYSMENU In a Control menu or in a Close button in a child window.

  • HTTOP In the upper horizontal border of the window.

  • HTTOPLEFT In the upper-left corner of the window border.

  • HTTOPRIGHT In the upper-right corner of the window border.

  • HTTRANSPARENT In a window currently covered by another window.

  • HTVSCROLL In the vertical scroll bar.

  • HTZOOM In a Maximize button.

Parameters

lprcBounds

Pointer to the bounds of the OLE control within the container. Not the client area but the area of the entire control including borders and scroll bars.

pPoint

Pointer to the parent (container) point to be translated into the coordinates of the client area of the control.

bHitTest

Specifies whether or not hit testing is to be done on the point.

Remarks

Call this function to translate the coordinates of pPoint into client coordinates. On input pPoint is relative to the origin of the parent (upper left corner of the container). On output pPoint is relative to the origin of the client area of the OLE control (upper left corner of the client area of the control).

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::ClientToParent, COleControl::GetClientOffset


COleControl::PostModalDialog

void PostModalDialog( );

Remarks

Call this function after displaying any modal dialog box. You must call this function so that the container can enable any top-level windows disabled by PreModalDialog. This function should be paired with a call to PreModalDialog.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::PreModalDialog


COleControl::PreModalDialog

void PreModalDialog( );

Remarks

Call this function prior to displaying any modal dialog box. You must call this function so that the container can disable all its top-level windows. After the modal dialog box has been displayed, you must then call PostModalDialog.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::PostModalDialog


COleControl::RecreateControlWindow

void RecreateControlWindow( );

Remarks

Call this function to destroy and re-create the control’s window. This may be necessary if you need to change the window’s style bits.


COleControl::Refresh

void Refresh( );

Remarks

Call this function to force a repaint of the OLE control.

This function is supported by the COleControl base class as a stock method, called Refresh. This allows users of your OLE control to repaint the control at a specific time. For more information on this method, see the article ActiveX Controls: Methods in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::InvalidateControl


COleControl::ReleaseCapture

BOOL ReleaseCapture( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this function to release mouse capture. If the control currently has the mouse capture, the capture is released. Otherwise, this function has no effect.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetCapture, COleControl::GetCapture


COleControl::ReleaseDC

int ReleaseDC( CDC* pDC );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDC

Identifies the container device context to be released.

Remarks

Call this function to release the display device context of a container of a windowless control, freeing the device context for use by other applications. The application must call ReleaseDC for each call to GetDC.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetDC


COleControl::ResetStockProps

void ResetStockProps( );

Remarks

Call this function to initialize the state of the COleControl stock properties to their default values. The properties are: Appearance, BackColor, BorderStyle, Caption, Enabled, Font, ForeColor, hWnd, and Text. For a description of stock properties, see ActiveX Controls: Adding Stock Properties.

You can improve a control's binary initialization performance by using ResetStockProps and ResetVersion to override COleControl::OnResetState. See the example below. For further information on optimizing initialization, see ActiveX Controls: Optimization.

Example

void CMyCtrl::OnResetState()
{
    ResetVersion(MAKELONG(_wVerMinor, _wVerMajor));
    ResetStockProps();

    // initialize custom properties here
}

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::ResetVersion, COleControl::SerializeStockProps


COleControl::ResetVersion

void ResetVersion( DWORD dwVersionDefault );

Parameters

dwVersionDefault

The version number to be assigned to the control.

Remarks

Call this function to initialize the version number to specified value.

You can improve a control's binary initialization performance by using ResetVersion and ResetStockProps to override COleControl::OnResetState. See the example at ResetStockProps. For further information on optimizing initialization, see ActiveX Controls: Optimization.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::ResetStockProps, COleControl::SerializeVersion


COleControl::ScrollWindow

void ScrollWindow( int xAmount, int yAmount, LPCRECT lpRect = NULL, LPCRECT lpClipRect = NULL );

Parameters

xAmount

Specifies the amount, in device units, of horizontal scrolling. This parameter must be a negative value to scroll to the left.

yAmount

Specifies the amount, in device units, of verticall scrolling. This parameter must be a negative value to scroll upward.

lpRect

Points to a CRect object or RECT structure that specifies the portion of the OLE object's client area to scroll, in client coordinates of the containing window. If lpRect is NULL, the entire OLE object's client area is scrolled.

lpClipRect

Points to a CRect object or RECT structure that specifies the rectangle to clip to. Only pixels inside the rectangle are scrolled. Bits outside the rectangle are not affected even if they are in the lpRect rectangle. If lpClipRect is NULL, no clipping is performed on the scroll rectangle.

Remarks

Call this function to allow a windowless OLE object to scroll an area within its in-place active image on the screen.


COleControl::SelectFontObject

CFont* SelectFontObject( CDC* pDC, CFontHolder& fontHolder );

Return Value

A pointer to the previously selected font. When the caller has finished all drawing operations that use fontHolder, it should reselect the previously selected font by passing it as a parameter to CDC::SelectObject.

Parameters

pDC

Pointer to a device context object.

fontHolder

Reference to the CFontHolder object representing the font to be selected.

Remarks

Call this function to select a font into a device context.


COleControl::SelectStockFont

CFont* SelectStockFont( CDC* pDC );

Return Value

A pointer to the previously selected CFont object. You should use CDC::SelectObject to select this font back into the device context when you are finished.

Parameters

pDC

The device context into which the font will be selected.

Remarks

Call this function to select the stock Font property into a device context.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetFont, COleControl::SetFont


COleControl::SerializeExtent

void SerializeExtent( CArchive& ar );

Parameters

ar

A CArchive object to serialize to or from.

Remarks

Call this function to serialize or initialize the state of the display space allotted to the control.

You can improve a control's binary persistence performance by using SerializeExtent, SerializeStockProps, and SerializeVersion to override COleControl::Serialize. See the example below. For further information on optimizing initialization, see ActiveX Controls: Optimization.

Example

void CMyCtrl::Serialize(CArchive& ar)
{
    DWORD dwVersion =
        SerializeVersion(ar, MAKELONG(_wVerMinor, _wVerMajor));
    SerializeExtent(ar);
    SerializeStockProps(ar);

    if (ar.IsLoading())
    {
        // load custom properties here
    }
    else
    {
        // save custom properties here
    }
}

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SerializeStockProps, COleControl::SerializeVersion


COleControl::SerializeStockProps

void SerializeStockProps( CArchive& ar );

Parameters

ar

A CArchive object to serialize to or from.

Remarks

Call this function to serialize or initialize the state of the COleControl stock properties: Appearance, BackColor, BorderStyle, Caption, Enabled, Font, ForeColor, and Text. For a description of stock properties, see ActiveX Controls: Adding Stock Properties.

You can improve a control's binary persistence performance by using SerializeStockProps, SerializeExtent, and SerializeVersion to override COleControl::Serialize. For an example, see the code at SerializeExtent. For further information on optimizing initialization, see ActiveX Controls: Optimization.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SerializeExtent, COleControl::SerializeVersion, COleControl::ResetStockProps


COleControl::SerializeVersion

DWORD SerializeVersion( CArchive& ar, DWORD dwVersionDefault, BOOL bConvert = TRUE );

Return Value

The version number of the control. If the specified archive is loading, SerializeVersion returns the version loaded from that archive. Otherwise, it returns the currently loaded version.

Parameters

ar

A CArchive object to serialize to or from.

dwVersionDefault

The current version number of the control.

bConvert

Indicates whether persistent data should be converted to the latest format when it is saved, or maintained in the same format it had when it was loaded.

Remarks

Call this function to serialize or initialize the state of a control’s version information.

You can improve a control's binary persistence performance by using SerializeVersion, SerializeExtent, and SerializeStockProps to override COleControl::Serialize. For an example, see the code at SerializeExtent. For further information on optimizing initialization, see ActiveX Controls: Optimization.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SerializeExtent, COleControl::SerializeStockProps, COleControl::ResetVersion


COleControl::SetAppearance

void SetAppearance ( short sAppearance );

Parameters

sAppearance

A short (VT_I2) value to be used for the appearance of your control. A value of zero sets the control's appearance to flat and a value of 1 sets the control's appearance to 3D.

Remarks

Call this function to set the stock Appearance property value of your control. For more about stock properties, see ActiveX Controls: Properties in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetAppearance, COleControl::OnAppearanceChanged


COleControl::SetBackColor

void SetBackColor( OLE_COLOR dwBackColor );

Parameters

dwBackColor

An OLE_COLOR value to be used for background drawing of your control.

Remarks

Call this function to set the stock BackColor property value of your control. For more information on using this property and other related properties, see Adding a Custom Notification Property in the Circle Sample Tutorial in Visual C++ Tutorials and the article ActiveX Controls: Properties in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetForeColor, COleControl::GetBackColor, COleControl::OnBackColorChanged


COleControl::SetBorderStyle

void SetBorderStyle( short sBorderStyle );

Parameters

sBorderStyle

The new border style for the control; 0 indicates no border and 1 indicates a normal border.

Remarks

Call this function to set the stock BorderStyle property value of your control. The control window will then be re-created and OnBorderStyleChanged called.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetBorderStyle, COleControl::OnBorderStyleChanged


COleControl::SetCapture

CWnd* SetCapture( );

Return Value

A pointer to the CWnd window object that previously received mouse input.

Remarks

If the control is activated and windowless, this function causes the control’s container window to take possession of the mouse capture, on the control’s behalf.

Otherwise, this function causes the control itself to take possession of the mouse capture (same as CWnd::SetCapture).

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetCapture, COleControl::ReleaseCapture


COleControl::SetControlSize

BOOL SetControlSize( int cx, int cy );

Return Value

Nonzero if the call was successful; otherwise 0.

Parameters

cx

Specifies the new width of the control in pixels.

cy

Specifies the new height of the control in pixels.

Remarks

Call this function to set the size of the OLE control window and notify the container that the control site is changing. This function should not be used in your control’s constructor.

Note that all coordinates for control windows are relative to the upper-left corner of the control.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetControlSize, COleControl::GetRectInContainer


COleControl::SetEnabled

void SetEnabled( BOOL bEnabled );

Parameters

bEnabled

TRUE if the control is to be enabled; otherwise FALSE.

Remarks

Call this function to set the stock Enabled property value of your control. After setting this property, OnEnabledChange is called.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetEnabled, COleControl::OnEnabledChanged


COleControl::SetFocus

CWnd* SetFocus( );

Return Value

A pointer to the CWnd window object that previously had the input focus, or NULL if there is no such window.

Remarks

If the control is activated and windowless, this function causes the control’s container window to take possession of the input focus, on the control’s behalf. The input focus directs keyboard input to the container’s window, and the container dispatches all subsequent keyboard messages to the OLE object that calls SetFocus. Any window that previously had the input focus loses it.

If the control is not windowless, this function causes the control itself to take possession of the input focus (same as CWnd::SetFocus).

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetFocus


COleControl::SetFont

void SetFont( LPFONTDISP pFontDisp );

Parameters

pFontDisp

A pointer to a Font dispatch interface.

Remarks

Call this function to set the stock Font property of your control.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetFont, COleControl::InternalGetText, COleControl::OnFontChanged


COleControl::SetForeColor

void SetForeColor( OLE_COLOR dwForeColor );

Parameters

dwForeColor

An OLE_COLOR value to be used for foreground drawing of your control.

Remarks

Call this function to set the stock ForeColor property value of your control. For more information on using this property and other related properties, see Adding a Custom Notification Property, in the Circle Sample Tutorial in Visual C++ Tutorials and the article ActiveX Controls: Properties in Visual C++ Programmer’s Guide.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::SetBackColor, COleControl::GetForeColor, COleControl::OnForeColorChanged


COleControl::SetInitialDataFormats

virtual void SetInitialDataFormats( );

Remarks

Called by the framework to initialize the list of data formats supported by the control.

The default implementation specifies two formats: CF_METAFILEPICT and the persistent property set.


COleControl::SetInitialSize

void SetInitialSize( int cx, int cy );

Parameters

cx

The initial width of the OLE control in pixels.

cy

The initial height of the OLE control in pixels.

Remarks

Call this function in your constructor to set the initial size of your control. The initial size is measured in device units, or pixels. It is recommended that this call be made in your control’s constructor.


COleControl::SetModifiedFlag

void SetModifiedFlag( BOOL bModified = TRUE );

Parameters

bModified

The new value for the control’s modified flag. TRUE indicates that the control’s state has been modified; FALSE indicates that the control’s state has just been saved.

Remarks

Call this function whenever a change occurs that would affect your control’s persistent state. For example, if the value of a persistent property changes, call this function with bModified TRUE.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::IsModified


COleControl::SetNotPermitted

void SetNotPermitted( );

Remarks

Call this function when BoundPropertyRequestEdit fails. This function throws an exception of type COleDispScodeException to indicate that the set operation was not permitted.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::BoundPropertyRequestEdit


COleControl::SetNotSupported

void SetNotSupported( );

Remarks

Call this function in place of the Set function of any property where modification of the property value by the control’s user is not supported. One example would be a property that is read-only.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetNotSupported


COleControl::SetRectInContainer

BOOL SetRectInContainer( LPRECT lpRect );

Return Value

Nonzero if the call was successful; otherwise 0.

Parameters

lpRect

A pointer to a rectangle containing the control’s new coordinates relative to the container.

Remarks

Call this function to set the coordinates of the control’s rectangle relative to the container, expressed in device units. If the control is open, it is resized; otherwise the container’s OnPosRectChanged function is called.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetRectInContainer, COleControl::GetControlSize


COleControl::SetText

void SetText( LPCTSTR pszText );

Parameters

pszText

A pointer to a character string.

Remarks

Call this function to set the value of your control’s stock Caption or Text property.

Note that the stock Caption and Text properties are both mapped to the same value. This means that any changes made to either property will automatically change both properties. In general, a control should support either the stock Caption or Text property, but not both.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetText, COleControl::InternalGetText, COleControl::OnTextChanged


COleControl::ThrowError

void ThrowError( SCODE sc, UINT nDescriptionID, UINT nHelpID = -1 );

void ThrowError( SCODE sc, LPCTSTR pszDescription = NULL, UINT nHelpID = 0 );

Parameters

sc

The status code value to be reported. For a complete list of possible codes, see the article ActiveX Controls: Advanced Topics in Visual C++ Programmer’s Guide.

nDescriptionID

The string resource ID of the exception to be reported.

nHelpID

The help ID of the topic to be reported on.

pszDescription

A string containing an explanation of the exception to be reported.

Remarks

Call this function to signal the occurrence of an error in your control. This function should only be called from within a Get or Set function for an OLE property, or the implementation of an OLE automation method. If you need to signal errors that occur at other times, you should fire the stock Error event.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::FireError, COleControl::DisplayError


COleControl::TransformCoords

void TransformCoords( POINTL FAR* lpptlHimetric, POINTF FAR* lpptfContainer, DWORD flags );

Parameters

lpptlHimetric

Pointer to a POINTL structure containing coordinates in HIMETRIC units.

lpptfContainer

Pointer to a POINTF structure containing coordinates in the container’s unit size.

flags

A combination of the following values:

  • XFORMCOORDS_POSITION A position in the container.

  • XFORMCOORDS_SIZE A size in the container.

  • XFORMCOORDS_HIMETRICTOCONTAINER Transform HIMETRIC units to the container’s units.

  • XFORMCOORDS_CONTAINERTOHIMETRIC Transform the container’s units to HIMETRIC units.

Remarks

Call this function to transform coordinate values between HIMETRIC units and the container’s native units.

The first two flags, XFORMCOORDS_POSITION and XFORMCOORDS_SIZE, indicate whether the coordinates should be treated as a position or a size. The remaining two flags indicate the direction of transformation.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::AmbientScaleUnits


COleControl::TranslateColor

COLORREF TranslateColor( OLE_COLOR clrColor, HPALETTE hpal = NULL );

Return Value

An RGB (red, green, blue) 32-bit color value that defines the solid color closest to the clrColor value that the device can represent.

Parameters

clrColor

A OLE_COLOR data type. For more information, see the Windows OleTranslateColor function.

hpal

A handle to an optional palette; can be NULL.

Remarks

Call this function to convert a color value from the OLE_COLOR data type to the COLORREF data type. This function is useful to translate the stock ForeColor and BackColor properties to COLORREF types used by CDC member functions.

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::GetForeColor, COleControl::GetBackColor


COleControl::WillAmbientsBeValidDuringLoad

BOOL WillAmbientsBeValidDuringLoad( );

Return Value

Nonzero indicates that ambient properties will be valid; otherwise ambient properties will not be valid.

Remarks

Call this function to determine whether your control should use the values of ambient properties as default values, when it is subsequently loaded from its persistent state.

In some containers, your control may not have access to its ambient properties during the initial call to the override of COleControl::DoPropExchange. This is the case if the container calls IPersistStreamInit::Load or IPersistStorage::Load prior to calling IOleObject::SetClientSite (that is, if it does not honor the OLEMISC_SETCLIENTSITEFIRST status bit).

COleControl Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange, COleControl::GetAmbientProperty


COleControlModule

The COleControlModule class is the base class from which you derive an OLE control module object. This class provides member functions for initializing your control module. Each OLE control module that uses the Microsoft Foundation classes can only contain one object derived from COleControlModule. This object is constructed when other C++ global objects are constructed. Declare your derived COleControlModule object at the global level.

For more information on using the COleControlModule class, see the CWinApp class and the article ActiveX Controls in Visual C++ Programmer’s Guide.

#include <afxctl.h>

Base Class Members | Hierarchy Chart

Samples MFC Sample DRAWPIC | MFC Sample TESTHELP


COleConvertDialog

The COleConvertDialog class is used for the OLE Convert dialog box. Create an object of class COleConvertDialog when you want to call this dialog box. After a COleConvertDialog object has been constructed, you can use the m_cv structure to initialize the values or states of controls in the dialog box. The m_cv structure is of type OLEUICONVERT. For more information about using this dialog class, see the DoModal member function.

Note AppWizard-generated container code uses this class.

For more information, see the OLEUICONVERT structure in the OLE documentation.

For more information about OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

See Also COleDialog


COleConvertDialog Class Members

Data Members

m_cv A structure that controls the behavior of the dialog box.

Construction

COleConvertDialog Constructs a COleConvertDialog object.

Operations and Attributes

DoModal | Displays the OLE Change Item dialog box.
DoConvert | Performs the conversion specified in the dialog box.
GetSelectionType | Gets the type of selection chosen.
GetClassID | Gets the CLSID associated with the chosen item.
GetDrawAspect | Specifies whether to draw item as an icon.
GetIconicMetafile | Gets a handle to the metafile associated with the iconic form of this item.


COleConvertDialog::COleConvertDialog

COleConvertDialog ( COleClientItem* pItem, DWORD dwFlags = CF_SELECTCONVERTTO, CLSID FAR* pClassID = NULL, CWnd* pParentWnd = NULL );

Parameters

pItem

Points to the item to be converted or activated.

dwFlags

Creation flag, which contains any number of the following values combined using the bitwise-or operator:

  • CF_SELECTCONVERTTO Specifies that the Convert To radio button will be selected initially when the dialog box is called. This is the default.

  • CF_SELECTACTIVATEAS Specifies that the Activate As radio button will be selected initially when the dialog box is called.

  • CF_SETCONVERTDEFAULT Specifies that the class whose CLSID is specified by the clsidConvertDefault member of the m_cv structure will be used as the default selection in the class list box when the Convert To radio button is selected.

  • CF_SETACTIVATEDEFAULT Specifies that the class whose CLSID is specified by the clsidActivateDefault member of the m_cv structure will be used as the default selection in the class list box when the Activate As radio button is selected.

  • CF_SHOWHELPBUTTON Specifies that the Help button will be displayed when the dialog box is called.

pClassID

Points to the CLSID of the item to be converted or activated. If NULL, the CLSID associated with pItem will be used.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the parent window of the dialog box is set to the main application window.

Remarks

Constructs only a COleConvertDialog object. To display the dialog box, call the DoModal function.

For more information, see CLSID Key and the OLEUICONVERT structure.

COleConvertDialog Overview | Class Members | Hierarchy Chart

See Also COleConvertDialog::DoModal, COleConvertDialog::m_cv


COleConvertDialog::DoConvert

BOOL DoConvert( COleClientItem* pItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pItem

Points to the item to be converted or activated. Cannot be NULL.

Remarks

Call this function, after returning successfully from DoModal, either to convert or to activate an object of type COleClientItem. The item is converted or activated according to the information selected by the user in the Convert dialog box.

COleConvertDialog Overview | Class Members | Hierarchy Chart

See Also COleClientItem, COleConvertDialog::DoModal, COleConvertDialog::GetSelectionType, COleClientItem::ConvertTo, COleClientItem::ActivateAs


COleConvertDialog::DoModal

virtual int DoModal( );

Return Value

Completion status for the dialog box. One of the following values:

  • IDOK if the dialog box was successfully displayed.

  • IDCANCEL if the user canceled the dialog box.

  • IDABORT if an error occurred. If IDABORT is returned, call the COleDialog::GetLastError member function to get more information about the type of error that occurred. For a listing of possible errors, see the OleUIConvert function in the OLE documentation.

Remarks

Call this function to display the OLE Convert dialog box.

If you want to initialize the various dialog box controls by setting members of the m_cv structure, you should do this before calling DoModal, but after the dialog object is constructed.

If DoModal returns IDOK, you can call other member functions to retrieve the settings or information that was input by the user into the dialog box.

COleConvertDialog Overview | Class Members | Hierarchy Chart

See Also COleDialog::GetLastError, CDialog::DoModal, COleConvertDialog::m_cv, COleConvertDialog::DoConvert, COleConvertDialog::GetSelectionType, COleConvertDialog::GetClassID, COleConvertDialog::GetDrawAspect, COleConvertDialog::GetIconicMetafile


COleConvertDialog::GetClassID

const CLSID& GetClassID( ) const;

Return Value

The CLSID associated with the item that was selected in the Convert dialog box.

Remarks

Call this function to get the CLSID associated with the item the user selected in the Convert dialog box. Call this function only after DoModal returns IDOK.

For more information, see CLSID Key in the OLE documentation.

COleConvertDialog Overview | Class Members | Hierarchy Chart

See Also COleConvertDialog::DoModal


COleConvertDialog::GetDrawAspect

DVASPECT GetDrawAspect( ) const;

Return Value

The method needed to render the object.

  • DVASPECT_CONTENT Returned if the Display As Icon check box was not checked.

  • DVASPECT_ICON Returned if the Display As Icon check box was checked.

Remarks

Call this function to determine whether the user chose to display the selected item as an icon. Call this function only after DoModal returns IDOK.

For more information on drawing aspect, see the FORMATETC data structure in the OLE documentation.

COleConvertDialog Overview | Class Members | Hierarchy Chart

See Also COleConvertDialog::DoModal, COleConvertDialog::COleConvertDialog


COleConvertDialog::GetIconicMetafile

HGLOBAL GetIconPicture( ) const;

Return Value

The handle to the metafile containing the iconic aspect of the selected item, if the Display As Icon check box was checked when the dialog was dismissed by choosing OK; otherwise NULL.

Remarks

Call this function to get a handle to the metafile that contains the iconic aspect of the selected item.

COleConvertDialog Overview | Class Members | Hierarchy Chart

See Also COleConvertDialog::DoModal, COleConvertDialog::COleConvertDialog, COleConvertDialog::GetDrawAspect


COleConvertDialog::GetSelectionType

UINT GetSelectionType( ) const;

Return Value

Type of selection made.

Remarks

Call this function to determine the type of conversion selected in the Convert dialog box.

The return type values are specified by the Selection enumeration type declared in the COleConvertDialog class.

enum Selection
{
   noConversion,
   convertItem,
   activateAs
};

Brief descriptions of these values follow:

  • COleConvertDialog::noConversion Returned if either the dialog box was canceled or the user selected no conversion. If COleConvertDialog::DoModal returned IDOK, it is possible that the user selected a different icon than the one previously selected.

  • COleConvertDialog::convertItem Returned if the Convert To radio button was checked, the user selected a different item to convert to, and DoModal returned IDOK.

  • COleConvertDialog::activateAs Returned if the Activate As radio button was checked, the user selected a different item to activate, and DoModal returned IDOK.

COleConvertDialog Overview | Class Members | Hierarchy Chart

See Also COleConvertDialog::DoModal, COleConvertDialog::COleConvertDialog


COleConvertDialog::m_cv

Remarks

Structure of type OLEUICONVERT used to control the behavior of the Convert dialog box. Members of this structure can be modified either directly or through member functions.

For more information, see the OLEUICONVERT structure in the OLE documentation.

COleConvertDialog Overview | Class Members | Hierarchy Chart

See Also COleConvertDialog::COleConvertDialog, COleConvertDialog::DoModal


COleCurrency

COleCurrency does not have a base class.

A COleCurrency object encapsulates the CURRENCY data type of OLE automation. CURRENCY is implemented as an 8-byte, two’s-complement integer value scaled by 10,000. This gives a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right. The CURRENCY data type is extremely useful for calculations involving money, or for any fixed-point calculation where accuracy is important. It is one of the possible types for the VARIANT data type of OLE automation.

COleCurrency also implements some basic arithmetic operations for this fixed-point type. The supported operations have been selected to control the rounding errors which occur during fixed-point calculations.

For more information, see the CURRENCY and VARIANT entries in the Win32 SDK OLE Programmer’s Reference.

#include <afxdisp.h>

Class Members | Hierarchy Chart

See Also COleVariant


COleCurrency Class Members

Construction

COleCurrency Constructs a COleCurrency object.

Attributes

GetStatus | Gets the status (validity) of this COleCurrency object.
SetStatus | Sets the status (validity) for this COleCurrency object.

Operations

SetCurrency | Sets the value of this COleCurrency object.
Format | Generates a formatted string representation of a COleCurrency object.
ParseCurrency | Reads a CURRENCY value from a string and sets the value of COleCurrency.

Operators

operator CURRENCY | Converts a COleCurrency value into a CURRENCY.
operator = | Copies a COleCurrency value.
operator +, - | Adds, subtracts, and changes sign of COleCurrency values.
operator +=, -= | Adds and subtracts a COleCurrency value from this COleCurrency object.
operator *, / | Scales a COleCurrency value by an integer value.
operator *=, /= | Scales this COleCurrency value by an integer value.
operator ==, <, <=, etc. | Compares two COleCurrency values.

Data Members

m_cur | Contains the underlying CURRENCY for this COleCurrency object.
m_status | Contains the status of this COleCurrency object.

Archive/Dump

operator << | Outputs a COleCurrency value to CArchive or CDumpContext.
operator >> | Inputs a COleCurrency object from CArchive.


COleCurrency::COleCurrency

COleCurrency( );

COleCurrency( CURRENCY cySrc );

COleCurrency( const COleCurrency& curSrc );

COleCurrency( const VARIANT& varSrc );

COleCurrency( long nUnits, long nFractionalUnits );

Parameters

cySrc

A CURRENCY value to be copied into the new COleCurrency object.

curSrc

An existing COleCurrency object to be copied into the new COleCurrency object.

varSrc

An existing VARIANT data structure (possibly a COleVariant object) to be converted to a currency value (VT_CY) and copied into the new COleCurrency object.

nUnits, nFractionalUnits

Indicate the units and fractional part (in 1/10,000’s) of the value to be copied into the new COleCurrency object.

Remarks

All of these constructors create new COleCurrency objects initialized to the specified value. A brief description of each of these constructors follows. Unless otherwise noted, the status of the new COleCurrency item is set to valid.

  • COleCurrency( ) Constructs a COleCurrency object initialized to 0 (zero).

  • COleCurrency( cySrc ) Constructs a COleCurrency object from a CURRENCY value.

  • COleCurrency( curSrc ) Constructs a COleCurrency object from an existing COleCurrency object. The new object has the same status as the source object.

  • COleCurrency( varSrc ) Constructs a COleCurrency object. Attempts to convert a VARIANT structure or COleVariant object to a currency (VT_CY) value. If this conversion is successful, the converted value is copied into the new COleCurrency object. If it is not, the value of the COleCurrency object is set to zero (0) and its status to invalid.

  • COleCurrency( nUnits, nFractionalUnits ) Constructs a COleCurrency object from the specified numerical components. If the absolute value of the fractional part is greater than 10,000, the appropriate adjustment is made to the units. Note that the units and fractional part are specified by signed long values.

For more information, see the CURRENCY and VARIANT entries in the Win32 SDK OLE Programmer’s Reference.

Example

The following examples show the effects of the zero-parameter and two-parameter constructors:

COleCurrency curZero;         // value: 0.0000
COleCurrency curA(4, 500);    // value: 4.0500
COleCurrency curB(2, 11000);  // value: 3.1000
COleCurrency curC(2, -50);    // value: 1.9950

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::SetCurrency, COleCurrency::operator =, COleCurrency::GetStatus, COleCurrency::m_cur, COleCurrency::m_status


COleCurrency::Format

CString Format( DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT );

Return Value

A CString that contains the formatted currency value.

Parameters

dwFlags

Indicates flags for locale settings, possibly the following flag:

  • LOCALE_NOUSEROVERRIDE Use the system default locale settings, rather than custom user settings.

lcid

Indicates locale ID to use for the conversion.

Remarks

Call this member function to create a formatted representation of the currency value. It formats the value using the national language specifications (locale IDs). A currency symbol is not included in the value returned. If the status of this COleCurrency object is null, the return value is an empty string. If the status is invalid, the return string is specified by the string resource IDS_INVALID_CURRENCY.

Example

COleCurrency curA;           // value: 0.0000
curA.SetCurrency(4, 500);    // value: 4.0500

// value returned: 4.05
curA.Format(0, MAKELCID(MAKELANGID(LANG_CHINESE,
     SUBLANG_CHINESE_SINGAPORE), SORT_DEFAULT));
// value returned: 4,05
curA.Format(0, MAKELCID(MAKELANGID(LANG_GERMAN,
     SUBLANG_GERMAN_AUSTRIAN), SORT_DEFAULT));

Note For a discussion of locale ID values, see the section Supporting Multiple National Languages in the Win32 SDK OLE Programmer’s Reference.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::ParseCurrency, COleCurrency::GetStatus


COleCurrency::GetStatus

CurrencyStatus GetStatus( ) const;

Return Value

Returns the status of this COleCurrency value.

Remarks

Call this member function to get the status (validity) of a given COleCurrency object.

The return value is defined by the CurrencyStatus enumerated type which is defined within the COleCurrency class.

enum CurrencyStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleCurrency::valid Indicates that this COleCurrency object is valid.

  • COleCurrency::invalid Indicates that this COleCurrency object is invalid; that is, its value may be incorrect.

  • COleCurrency::null Indicates that this COleCurrency object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

The status of a COleCurrency object is invalid in the following cases:

  • If its value is set from a VARIANT or COleVariant value that could not be converted to a currency value.

  • If this object has experienced an overflow or underflow during an arithmetic assignment operation, for example += or *=.

  • If an invalid value was assigned to this object.

  • If the status of this object was explicitly set to invalid using SetStatus.

For more information on operations that may set the status to invalid, see the following member functions:

  • COleCurrency

  • operator =

  • operator +, -

  • operator +=, -=

  • operator *, /

  • operator *=, /=

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::SetStatus, COleCurrency::m_status


COleCurrency::ParseCurrency

BOOL ParseCurrency( LPCTSTR lpszCurrency, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT );
throw( CMemoryException );
throw( COleException );

Return Value

Nonzero if the string was successfully converted to a currency value, otherwise 0.

Parameters

lpszCurrency

A pointer to the null-terminated string which is to be parsed.

dwFlags

Indicates flags for locale settings, possibly the following flag:

  • LOCALE_NOUSEROVERRIDE Use the system default locale settings, rather than custom user settings.

lcid

Indicates locale ID to use for the conversion.

Remarks

Call this member function to parse a string to read a currency value. It uses national language specifications (locale IDs) for the meaning of nonnumeric characters in the source string.

For a discussion of locale ID values, see the section Supporting Multiple National Languages in the Win32 SDK OLE Programmer’s Reference.

If the string was successfully converted to a currency value, the value of this COleCurrency object is set to that value and its status to valid.

If the string could not be converted to a currency value or if there was a numerical overflow, the status of this COleCurrency object is invalid.

If the string conversion failed due to memory allocation errors, this function throws a CMemoryException. In any other error state, this function throws a COleException.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::Format, COleCurrency::GetStatus


COleCurrency::SetCurrency

void SetCurrency( long nUnits, long nFractionalUnits );

Parameters

nUnits, nFractionalUnits

Indicate the units and fractional part (in 1/10,000’s) of the value to be copied into this COleCurrency object.

Remarks

Call this member function to set the units and fractional part of this COleCurrency object.

If the absolute value of the fractional part is greater than 10,000, the appropriate adjustment is made to the units, as shown in the third of the following examples.

Note that the units and fractional part are specified by signed long values. The fourth of the following examples shows what happens when the parameters have different signs.

Example

COleCurrency curA;           // value: 0.0000
curA.SetCurrency(4, 500);    // value: 4.0500
curA.SetCurrency(2, 11000);  // value: 3.1000
curA.SetCurrency(2, -50);    // value: 1.9950

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::COleCurrency, COleCurrency::operator =, COleCurrency::m_cur


COleCurrency::SetStatus

void SetStatus( CurrencyStatus nStatus );

Parameters

nStatus

The new status for this COleCurrency object.

Remarks

Call this member function to set the status (validity) of this COleCurrency object. The nStatus parameter value is defined by the CurrencyStatus enumerated type, which is defined within the COleCurrency class.

enum CurrencyStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleCurrency::valid Indicates that this COleCurrency object is valid.

  • COleCurrency::invalid Indicates that this COleCurrency object is invalid; that is, its value may be incorrect.

  • COleCurrency::null Indicates that this COleCurrency object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

Caution This function is for advanced programming situations. This function does not alter the data in this object. It will most often be used to set the status to null or invalid. Note that the assignment operator (operator =) and SetCurrency do set the status to of the object based on the source value(s).

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::GetStatus, COleCurrency::operator =, COleCurrency::SetCurrency, COleCurrency::m_status


COleCurrency::operator =

const COleCurrency& operator =( CURRENCY cySrc );

const COleCurrency& operator =( const COleCurrency& curSrc );

const COleCurrency& operator =( const VARIANT& varSrc );

Remarks

These overloaded assignment operators copy the source currency value into this COleCurrency object. A brief description of each operator follows:

  • operator =( cySrc ) The CURRENCY value is copied into the COleCurrency object and its status is set to valid.

  • operator =( curSrc ) The value and status of the operand, an existing COleCurrency object are copied into this COleCurrency object.

  • operator =( varSrc ) If the conversion of the VARIANT value (or COleVariant object) to a currency (VT_CY) is successful, the converted value is copied into this COleCurrency object and its status is set to valid. If the conversion is not successful, the value of the COleCurrency object is set to 0 and its status to invalid.

For more information, see the CURRENCY and VARIANT entries in the Win32 SDK OLE Programmer’s Reference.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::COleCurrency, COleCurrency::SetCurrency, COleCurrency::GetStatus


COleCurrency::operator +, -

COleCurrency operator +( const COleCurrency& cur ) const;

COleCurrency operator -( const COleCurrency& cur ) const;

COleCurrency operator -( ) const;

Remarks

These operators allow you to add and subtract two COleCurrency values to and from each other and to change the sign of a COleCurrency value.

If either of the operands is null, the status of the resulting COleCurrency value is null.

If the arithmetic operation overflows, the resulting COleCurrency value is invalid.

If the operands is invalid and the other is not null, the status of the resulting COleCurrency value is invalid.

For more information on the valid, invalid, and null status values, see the m_status member variable.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also OleCurrency::operator +=, -=, COleCurrency::GetStatus


COleCurrency::operator +=, -=

const COleCurrency& operator +=( const COleCurrency& cur );

const COleCurrency& operator -=( const COleCurrency& cur );

Remarks

These operators allow you to add and subtract a COleCurrency value to and from this COleCurrency object.

If either of the operands is null, the status of this COleCurrency object is set to null.

If the arithmetic operation overflows, the status of this COleCurrency object is set to invalid.

If either of the operands is invalid and the other is not null, the status of this COleCurrency object is set to invalid.

For more information on the valid, invalid, and null status values, see the m_status member variable.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::operator +, -, COleCurrency::GetStatus


COleCurrency::operator *, /

COleCurrency operator *( long nOperand ) const;

COleCurrency operator /( long nOperand ) const;

Remarks

These operators allow you to scale a COleCurrency value by an integral value.

If the COleCurrency operand is null, the status of the resulting COleCurrency value is null.

If the arithmetic operation overflows or underflows, the status of the resulting COleCurrency value is invalid.

If the COleCurrency operand is invalid, the status of the resulting COleCurrency value is invalid.

For more information on the valid, invalid, and null status values, see the m_status member variable.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::operator *=, /=, COleCurrency::GetStatus


COleCurrency::operator *=, /=

const COleCurrency& operator *=( long nOperand );

const COleCurrency& operator /=( long nOperand );

Remarks

These operators allow you to scale this COleCurrency value by an integral value.

If the COleCurrency operand is null, the status of this COleCurrency object is set to null.

If the arithmetic operation overflows, the status of this COleCurrency object is set to invalid.

If the COleCurrency operand is invalid, the status of this COleCurrency object is set to invalid.

For more information on the valid, invalid, and null status values, see the m_status member variable.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::operator *, /, COleCurrency::GetStatus


COleCurrency::operator CURRENCY

operator CURRENCY( ) const;

Remarks

This operator returns a CURRENCY structure whose value is copied from this COleCurrency object.

For more information, see the CURRENCY entry in the Win32 SDK OLE Programmer’s Reference.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::m_cur, COleCurrency::SetCurrency


COleCurrency Relational Operators

BOOL operator ==( const COleCurrency& cur ) const;

BOOL operator !=( const COleCurrency& cur ) const;

BOOL operator <( const COleCurrency& cur ) const;

BOOL operator >( const COleCurrency& cur ) const;

BOOL operator <=( const COleCurrency& cur ) const;

BOOL operator >=( const COleCurrency& cur ) const;

Remarks

These operators compare two currency values and return nonzero if the condition is true; otherwise 0.

Note The return value of the ordering operations (<, <=, >, >=) is undefined if the status of either operand is null or invalid. The equality operators (==, !=) consider the status of the operands.

Example

COleCurrency curOne(3, 5000);             // 3.5
COleCurrency curTwo(curOne);              // 3.5
BOOL b;
b = curOne == curTwo;                     // TRUE

curTwo.SetStatus(COleCurrency::invalid);
b = curOne == curTwo;                     // FALSE, different status
b = curOne != curTwo;                     // TRUE, different status
b = curOne < curTwo;                      // FALSE, same value
b = curOne > curTwo;                      // FALSE, same value
b = curOne <= curTwo;                     // TRUE, same value
b = curOne >= curTwo;                     // TRUE, same value

Note The last four lines of the preceding example will ASSERT in debug mode.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::GetStatus


COleCurrency::operator <<, >>

friend CDumpContext& operator <<( CDumpContext& dc, COleCurrency curSrc );

friend CArchive& operator <<( CArchive& ar, COleCurrency curSrc );

friend CArchive& operator >>( CArchive& ar, COleCurrency& curSrc );

Remarks

The COleCurrency insertion (<<) operator supports diagnostic dumping and storing to an archive. The extraction (>>) operator supports loading from an archive.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also CDumpContext, CArchive


COleCurrency::m_cur

Remarks

The underlying CURRENCY structure for this COleCurrency object.

Caution Changing the value in the CURRENCY structure accessed by the pointer returned by this function will change the value of this COleCurrency object. It does not change the status of this COleCurrency object.

For more information, see the CURRENCY entry in the Win32 SDK OLE Programmer’s Reference.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::COleCurrency, COleCurrency::operator CURRENCY, COleCurrency::SetCurrency


COleCurrency::m_status

Remarks

The type of this data member is the enumerated type CurrencyStatus, which is defined within the COleCurrency class.

enum CurrencyStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleCurrency::valid Indicates that this COleCurrency object is valid.

  • COleCurrency::invalid Indicates that this COleCurrency object is invalid; that is, its value may be incorrect.

  • COleCurrency::null Indicates that this COleCurrency object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

The status of a COleCurrency object is invalid in the following cases:

  • If its value is set from a VARIANT or COleVariant value that could not be converted to a currency value.

  • If this object has experienced an overflow or underflow during an arithmetic assignment operation, for example += or *=.

  • If an invalid value was assigned to this object.

  • If the status of this object was explicitly set to invalid using SetStatus.

For more information on operations that may set the status to invalid, see the following member functions:

  • COleCurrency

  • operator =

  • operator +, -

  • operator +=, -=

  • operator *, /

  • operator *=, /=

Caution This data member is for advanced programming situations. You should use the inline member functions GetStatus and SetStatus. See SetStatus for further cautions regarding explicitly setting this data member.

COleCurrency Overview | Class Members | Hierarchy Chart

See Also COleCurrency::GetStatus, COleCurrency::SetStatus


COleDataObject

COleDataObject does not have a base class.

The COleDataObject class is used in data transfers for retrieving data in various formats from the Clipboard, through drag and drop, or from an embedded OLE item. These kinds of data transfers include a source and a destination. The data source is implemented as an object of the COleDataSource class. Whenever a destination application has data dropped in it or is asked to perform a paste operation from the Clipboard, an object of the COleDataObject class must be created.

This class enables you to determine whether the data exists in a specified format. You can also enumerate the available data formats or check whether a given format is available and then retrieve the data in the preferred format. Object retrieval can be accomplished in several different ways, including the use of a CFile, an HGLOBAL, or an STGMEDIUM structure.

For more information, see the STGMEDIUM structure in the OLE 2 Programmer’s Reference, Volume 1.

For more information about using data objects in your application, see the article Data Objects and Data Sources (OLE) in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Hierarchy Chart

Samples MFC Sample HIERSVR | MFC Sample OCLIENT

See Also COleDataSource, COleClientItem, COleServerItem, COleDataSource::DoDragDrop, CView::OnDrop


COleDataObject Class Members

Construction

COleDataObject Constructs a COleDataObject object.

Operations

AttachClipboard | Attaches the data object that is on the Clipboard.
IsDataAvailable | Checks whether data is available in a specified format.
GetData | Copies data from the attached OLE data object in a specified format.
GetFileData | Copies data from the attached OLE data object into a CFile pointer in the specified format.
GetGlobalData | Copies data from the attached OLE data object into an HGLOBAL in the specified format.
BeginEnumFormats | Prepares for one or more subsequent GetNextFormat calls.
GetNextFormat | Returns the next data format available.
Attach | Attaches the specified OLE data object to the COleDataObject.
Release | Detaches and releases the associated IDataObject object.
Detach | Detaches the associated IDataObject object.


COleDataObject::Attach

void Attach( LPDATAOBJECT lpDataObject, BOOL bAutoRelease = TRUE );

Parameters

lpDataObject

Points to an OLE data object.

bAutoRelease

TRUE if the OLE data object should be released when the COleDataObject object is destroyed; otherwise FALSE.

Remarks

Call this function to associate the COleDataObject object with an OLE data object.

For more information, see IDataObject in the OLE 2 Programmer's Reference, Volume 1.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::AttachClipboard, COleDataObject::Detach, COleDataObject::Release


COleDataObject::AttachClipboard

BOOL AttachClipboard( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this function to attach the data object that is currently on the Clipboard to the COleDataObject object.

Note Calling this function locks the Clipboard until this data object is released. The data object is released in the destructor for the COleDataObject. For more information, see OpenClipboard and CloseClipboard in the Win32 documention.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::Attach, COleDataObject::Detach, COleDataObject::Release


COleDataObject::BeginEnumFormats

void BeginEnumFormats( );

Remarks

Call this function to prepare for subsequent calls to GetNextFormat for retrieving a list of data formats from the item.

After a call to BeginEnumFormats, the position of the first format supported by this data object is stored. Successive calls to GetNextFormat will enumerate the list of available formats in the data object.

To check on the availability of data in a given format, use COleDataObject::IsDataAvailable.

For more information, see IDataObject::EnumFormatEtc in the OLE 2 Programmer’s Reference, Volume 1.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::GetNextFormat, COleDataObject::IsDataAvailable


COleDataObject::COleDataObject

COleDataObject( );

Remarks

Constructs a COleDataObject object. A call to COleDataObject::Attach or COleDataObject::AttachClipboard must be made before calling other COleDataObject functions.

Note Since one of the parameters to the drag-and-drop handlers is a pointer to a COleDataObject, there is no need to call this constructor to support drag and drop.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::Attach, COleDataObject::AttachClipboard, COleDataObject::Release


COleDataObject::Detach

LPDATAOBJECT Detach( );

Return Value

A pointer to the OLE data object that was detached.

Remarks

Call this function to detach the COleDataObject object from its associated OLE data object without releasing the data object.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::Attach, COleDataObject::Release


COleDataObject::GetData

BOOL GetData( CLIPFORMAT cfFormat, LPSTGMEDIUM lpStgMedium, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

cfFormat

The format in which data is to be returned. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

lpStgMedium

Points to a STGMEDIUM structure that will receive data.

lpFormatEtc

Points to a FORMATETC structure describing the format in which data is to be returned. Provide a value for this parameter if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, the default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to retrieve data from the item in the specified format.

For more information, see IDataObject::GetData, STGMEDIUM, and FORMATETC in the OLE 2 Programmer's Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::GetFileData, COleDataObject::GetGlobalData, COleDataObject::IsDataAvailable


COleDataObject::GetFileData

CFile* GetFileData( CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc = NULL );

Return Value

Pointer to the new CFile or CFile-derived object containing the data if successful; otherwise NULL.

Parameters

cfFormat

The format in which data is to be returned. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

lpFormatEtc

Points to a FORMATETC structure describing the format in which data is to be returned. Provide a value for this parameter if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, the default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to create a CFile or CFile-derived object and to retrieve data in the specified format into a CFile pointer. Depending on the medium the data is stored in, the actual type pointed to by the return value may be CFile, CSharedFile, or COleStreamFile.

Note The CFile object accessed by the return value of this function is owned by the caller. It is the responsibility of the caller to delete the CFile object, thereby closing the file.

For more information, see FORMATETC in the OLE 2 Programmer's Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::GetData, COleDataObject::GetGlobalData, COleDataObject::IsDataAvailable


COleDataObject::GetGlobalData

HGLOBAL GetGlobalData( CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc = NULL );

Return Value

The handle of the global memory block containing the data if successful; otherwise NULL.

Parameters

cfFormat

The format in which data is to be returned. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

lpFormatEtc

Points to a FORMATETC structure describing the format in which data is to be returned. Provide a value for this parameter if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, the default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to allocate a global memory block and to retrieve data in the specified format into an HGLOBAL.

For more information, see FORMATETC in the OLE 2 Programmer's Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::GetData, COleDataObject::GetFileData, COleDataObject::IsDataAvailable


COleDataObject::GetNextFormat

BOOL GetNextFormat( LPFORMATETC lpFormatEtc );

Return Value

Nonzero if another format is available; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure that receives the format information when the function call returns.

Remarks

Call this function repeatedly to obtain all the formats available for retrieving data from the item.

After a call to COleDataObject::BeginEnumFormats, the position of the first format supported by this data object is stored. Successive calls to GetNextFormat will enumerate the list of available formats in the data object. Use these functions to list the available formats.

To check for the availability of a given format, call COleDataObject::IsDataAvailable.

For more information, see IEnumXXXX::Next in the OLE 2 Programmer's Reference, Volume 1.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::BeginEnumFormats, COleDataObject::GetData, COleDataObject::GetFileData, COleDataObject::GetGlobalData


COleDataObject::IsDataAvailable

BOOL IsDataAvailable( CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc = NULL );

Return Value

Nonzero if data is available in the specified format; otherwise 0.

Parameters

cfFormat

The Clipboard data format to be used in the structure pointed to by lpFormatEtc. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

lpFormatEtc

Points to a FORMATETC structure describing the format desired. Provide a value for this parameter only if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, the default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to determine if a particular format is available for retrieving data from the OLE item. This function is useful before calling GetData, GetFileData, or GetGlobalData.

For more information, see IDataObject::QueryGetData and FORMATETC in the OLE 2 Programmer's Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::BeginEnumFormats, COleDataObject::GetData, COleDataObject::GetFileData, COleDataObject::GetGlobalData, COleDataObject::GetNextFormat


COleDataObject::Release

void Release( );

Remarks

Call this function to release ownership of the IDataObject object that was previously associated with the COleDataObject object. The IDataObject was associated with the COleDataObject by calling Attach or AttachClipboard explicitly or by the framework. If the bAutoRelease parameter of Attach is FALSE, the IDataObject object will not be released. In this case, the caller is responsible for releasing the IDataObject by calling IUnknown::Release.

COleDataObject Overview | Class Members | Hierarchy Chart

See Also COleDataObject::Attach, COleDataObject::COleDataObject, COleDataObject::Detach


COleDataSource

The COleDataSource class acts as a cache into which an application places the data that it will offer during data transfer operations, such as Clipboard or drag-and-drop operations.

You can create OLE data sources directly. Alternately, the COleClientItem and COleServerItem classes create OLE data sources in response to their CopyToClipboard and DoDragDrop member functions. See COleServerItem::CopyToClipboard for a brief description. Override the OnGetClipboardData member function of your client item or server item class to add additional Clipboard formats to the data in the OLE data source created for the CopyToClipboard or DoDragDrop member function.

Whenever you want to prepare data for a transfer, you should create an object of this class and fill it with your data using the most appropriate method for your data. The way it is inserted into a data source is directly affected by whether the data is supplied immediately (immediate rendering) or on demand (delayed rendering). For every Clipboard format in which you are providing data by passing the Clipboard format to be used (and an optional FORMATETC structure), call DelayRenderData.

For more information about data sources and data transfer, see the article Data Objects and Data Sources (OLE). In addition, the article Clipboard Topics describes the OLE Clipboard mechanism.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HIERSVR | MFC Sample OCLIENT

See Also COleDataObject


COleDataSource Class Members

Construction

COleDataSource Constructs a COleDataSource object.

Operations

CacheData | Offers data in a specified format using a STGMEDIUM structure.
CacheGlobalData | Offers data in a specified format using an HGLOBAL.
DoDragDrop | Performs drag-and-drop operations with a data source.
SetClipboard | Places a COleDataSource object on the Clipboard.
Empty | Empties the COleDataSource object of data.
FlushClipboard | Renders all data to the Clipboard.
GetClipboardOwner | Verifies that the data placed on the Clipboard is still there.
OnRenderData | Retrieves data as part of delayed rendering.
OnRenderFileData | Retrieves data into a CFile as part of delayed rendering.
OnRenderGlobalData | Retrieves data into an HGLOBAL as part of delayed rendering.
OnSetData | Called to replace the data in the COleDataSource object.
DelayRenderData | Offers data in a specified format using delayed rendering.
DelayRenderFileData | Offers data in a specified format in a CFile pointer.
DelaySetData | Called for every format that is supported in OnSetData.


COleDataSource::CacheData

void CacheData( CLIPFORMAT cfFormat, LPSTGMEDIUM lpStgMedium, LPFORMATETC lpFormatEtc = NULL );

Parameters

cfFormat

The Clipboard format in which the data is to be offered. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

lpStgMedium

Points to a STGMEDIUM structure containing the data in the format specified.

lpFormatEtc

Points to a FORMATETC structure describing the format in which the data is to be offered. Provide a value for this parameter if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to specify a format in which data is offered during data transfer operations. You must supply the data, because this function provides it by using immediate rendering. The data is cached until needed.

Supply the data using a STGMEDIUM structure. You can also use the CacheGlobalData member function if the amount of data you are supplying is small enough to be transferred efficiently using an HGLOBAL.

After the call to CacheData the ptd member of lpFormatEtc and the contents of lpStgMedium are owned by the data object, not by the caller.

To use delayed rendering, call the DelayRenderData or DelayRenderFileData member function. For more information on delayed rendering as handled by MFC, see the article Data Objects and Data Sources: Manipulation in Visual C++ Programmer’s Guide.

For more information, see the STGMEDIUM and FORMATETC structures in the OLE 2 Programmer’s Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::CacheGlobalData, COleDataSource::DelayRenderData, COleDataSource::DelayRenderFileData, COleDataSource::SetClipboard, COleDataSource::DoDragDrop


COleDataSource::CacheGlobalData

void CacheGlobalData( CLIPFORMAT cfFormat, HGLOBAL hGlobal, LPFORMATETC lpFormatEtc = NULL );

Parameters

cfFormat

The Clipboard format in which the data is to be offered. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

hGlobal

Handle to the global memory block containing the data in the format specified.

lpFormatEtc

Points to a FORMATETC structure describing the format in which the data is to be offered. Provide a value for this parameter if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to specify a format in which data is offered during data transfer operations. This function provides the data using immediate rendering, so you must supply the data when calling the function; the data is cached until needed. Use the CacheData member function if you are supplying a large amount of data or if you require a structured storage medium.

To use delayed rendering, call the DelayRenderData or DelayRenderFileData member function. For more information on delayed rendering as handled by MFC, see the article Data Objects and Data Sources: Manipulation in Visual C++ Programmer’s Guide.

For more information, see the FORMATETC structure in the OLE 2 Programmer’s Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::CacheData, COleDataSource::DelayRenderData, COleDataSource::DelayRenderFileData


COleDataSource::COleDataSource

COleDataSource( );

Remarks

Constructs a COleDataSource object.


COleDataSource::DelayRenderData

void DelayRenderData( CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc = NULL );

Parameters

cfFormat

The Clipboard format in which the data is to be offered. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

lpFormatEtc

Points to a FORMATETC structure describing the format in which the data is to be offered. Provide a value for this parameter if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to specify a format in which data is offered during data transfer operations. This function provides the data using delayed rendering, so the data is not supplied immediately. The OnRenderData or OnRenderGlobalData member function is called to request the data.

Use this function if you are not going to supply your data through a CFile object. If you are going to supply the data through a CFile object, call the DelayRenderFileData member function. For more information on delayed rendering as handled by MFC, see the article Data Objects and Data Sources: Manipulation in Visual C++ Programmer’s Guide.

To use immediate rendering, call the CacheData or CacheGlobalData member function.

For more information, see the FORMATETC structure in the OLE 2 Programmer’s Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::CacheData, COleDataSource::CacheGlobalData, COleDataSource::DelayRenderFileData, COleDataSource::OnRenderData, COleDataSource::OnRenderGlobalData


COleDataSource::DelayRenderFileData

void DelayRenderFileData( CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc = NULL );

Parameters

cfFormat

The Clipboard format in which the data is to be offered. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

lpFormatEtc

Points to a FORMATETC structure describing the format in which the data is to be offered. Provide a value for this parameter if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to specify a format in which data is offered during data transfer operations. This function provides the data using delayed rendering, so the data is not supplied immediately. The OnRenderFileData member function is called to request the data.

Use this function if you are going to use a CFile object to supply the data. If you are not going to use a CFile object, call the DelayRenderData member function. For more information on delayed rendering as handled by MFC, see the article Data Objects and Data Sources: Manipulation in Visual C++ Programmer’s Guide.

To use immediate rendering, call the CacheData or CacheGlobalData member function.

For more information, see the FORMATETC structure in the OLE 2 Programmer’s Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::CacheData, COleDataSource::CacheGlobalData, COleDataSource::DelayRenderData, COleDataSource::OnRenderFileData


COleDataSource::DelaySetData

void DelaySetData( CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc = NULL ) const;

Parameters

cfFormat

The Clipboard format in which the data is to be placed. This parameter can be one of the predefined Clipboard formats or the value returned by the native Windows RegisterClipboardFormat function.

lpFormatEtc

Points to a FORMATETC structure describing the format in which the data is to be replaced. Provide a value for this parameter if you want to specify additional format information beyond the Clipboard format specified by cfFormat. If it is NULL, default values are used for the other fields in the FORMATETC structure.

Remarks

Call this function to support changing the contents of the data source. OnSetData will be called by the framework when this happens. This is only used when the framework returns the data source from COleServerItem::GetDataSource. If DelaySetData is not called, your OnSetData function will never be called. DelaySetData should be called for each Clipboard or FORMATETC format you support.

For more information, see the FORMATETC structure in the OLE 2 Programmer’s Reference, Volume 1.

For more information, see RegisterClipboardFormat in the Win32 documentation.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleServerItem::GetDataSource, COleDataSource::OnSetData


COleDataSource::DoDragDrop

DROPEFFECT DoDragDrop( DWORD dwEffects = DROPEFFECT_COPY|DROPEFFECT_MOVE|DROPEFFECT_LINK, LPCRECT lpRectStartDrag = NULL, COleDropSource* pDropSource = NULL );

Return Value

Drop effect generated by the drag-and-drop operation; otherwise DROPEFFECT_NONE if the operation never begins because the user released the mouse button before leaving the supplied rectangle.

Parameters

dwEffects

Drag-and-drop operations that are allowed on this data source. Can be one or more of the following:

  • DROPEFFECT_COPY A copy operation could be performed.

  • DROPEFFECT_MOVE A move operation could be performed.

  • DROPEFFECT_LINK A link from the dropped data to the original data could be established.

  • DROPEFFECT_SCROLL Indicates that a drag scroll operation could occur.

lpRectStartDrag

Pointer to the rectangle that defines where the drag actually starts. For more information, see the following Remarks section.

pDropSource

Points to a drop source. If NULL then a default implementation of COleDropSource will be used.

Remarks

Call the DoDragDrop member function to perform a drag-and-drop operation for this data source, typically in an CWnd::OnLButtonDown handler.

The drag-and-drop operation does not start immediately. It waits until the mouse cursor leaves the rectangle specified by lpRectStartDrag or until a specified number of milliseconds have passed. If lpRectStartDrag is NULL, the size of the rectangle is one pixel.

The delay time is specified by a registry key setting. You can change the delay time by calling CWinApp::WriteProfileString or CWinApp::WriteProfileInt. If you do not specify the delay time, a default value of 200 milliseconds is used. Drag delay time is stored as follows:

  • Windows NT Drag delay time is stored in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\NT\CurrentVersion\IniFileMapping\win.ini\Windows\DragDelay.

  • Windows 3.x Drag delay time is stored in the WIN.INI file, under the [Windows} section.

  • Windows 95 Drag delay time is stored in a cached version of WIN.INI.

For more information about how drag delay information is stored in either the registry or the .INI file, see ::WriteProfileString in the Platform SDK.

For more information, see the article Drag and Drop: Implementing a Drop Source in Visual C++ Programmer’s Guide.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDropSource::OnBeginDrag, COleDropSource


COleDataSource::Empty

void Empty( );

Remarks

Call this function to empty the COleDataSource object of data. Both cached and delay render formats are emptied so they can be reused.

For more information, see ReleaseStgMedium in the OLE 2 Programmer's Reference, Volume 1.


COleDataSource::FlushClipboard

static void FlushClipboard( );

Remarks

Removes data from the Clipboard that was placed there by a previous call to SetClipboard. This function also causes any data still on the Clipboard to be immediately rendered. Call this function when it is necessary to delete the data object last placed on the Clipboard from memory. Calling this function ensures that OLE will not require the original data source to perform Clipboard rendering.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::GetClipboardOwner, COleDataSource::SetClipboard


COleDataSource::GetClipboardOwner

static COleDataSource* GetClipboardOwner( );

Return Value

The data source currently on the Clipboard, or NULL if there is nothing on the Clipboard or if the Clipboard is not owned by the calling application.

Remarks

Determines whether the data on the Clipboard has changed since SetClipboard was last called and, if so, identifies the current owner.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::FlushClipboard, COleDataSource::SetClipboard


COleDataSource::OnRenderData

virtual BOOL OnRenderData( LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

lpStgMedium

Points to a STGMEDIUM structure in which the data is to be returned.

Remarks

Called by the framework to retrieve data in the specified format. The specified format is one previously placed in the COleDataSource object using the DelayRenderData or DelayRenderFileData member function for delayed rendering. The default implementation of this function will call OnRenderFileData or OnRenderGlobalData if the supplied storage medium is either a file or memory, respectively. If neither of these formats are supplied, then the default implementation will return 0 and do nothing. For more information on delayed rendering as handled by MFC, see the article Data Objects and Data Sources: Manipulation in Visual C++ Programmer’s Guide.

If lpStgMedium->tymed is TYMED_NULL, the STGMEDIUM should be allocated and filled as specified by lpFormatEtc->tymed. If it is not TYMED_NULL, the STGMEDIUM should be filled in place with the data.

This is an advanced overridable. Override this function to supply your data in the requested format and medium. Depending on your data, you may want to override one of the other versions of this function instead. If your data is small and fixed in size, override OnRenderGlobalData. If your data is in a file, or is of variable size, override OnRenderFileData.

For more information, see the STGMEDIUM and FORMATETC structures, the TYMED enumeration type, and IDataObject::GetData in the OLE 2 Programmer’s Reference, Volume 1.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::DelayRenderData, COleDataSource::DelayRenderFileData, COleDataSource::OnRenderFileData, COleDataSource::OnRenderGlobalData, COleDataSource::OnSetData


COleDataSource::OnRenderFileData

virtual BOOL OnRenderFileData( LPFORMATETC lpFormatEtc, CFile* pFile );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

pFile

Points to a CFile object in which the data is to be rendered.

Remarks

Called by the framework to retrieve data in the specified format when the specified storage medium is a file. The specified format is one previously placed in the COleDataSource object using the DelayRenderData member function for delayed rendering. The default implementation of this function simply returns FALSE.

This is an advanced overridable. Override this function to supply your data in the requested format and medium. Depending on your data, you might want to override one of the other versions of this function instead. If you want to handle multiple storage media, override OnRenderData. If your data is in a file, or is of variable size, override OnRenderFileData. For more information on delayed rendering as handled by MFC, see the article Data Objects and Data Sources: Manipulation in Visual C++ Programmer’s Guide.

For more information, see the FORMATETC structure and IDataObject::GetData in the OLE 2 Programmer’s Reference, Volume 1.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::DelayRenderData, COleDataSource::DelayRenderFileData, COleDataSource::OnRenderData, COleDataSource::OnRenderGlobalData, COleDataSource::OnSetData, CFile


COleDataSource::OnRenderGlobalData

virtual BOOL OnRenderGlobalData( LPFORMATETC lpFormatEtc, HGLOBAL* phGlobal );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

phGlobal

Points to a handle to global memory in which the data is to be returned. If one has not yet been allocated, this parameter can be NULL.

Remarks

Called by the framework to retrieve data in the specified format when the specified storage medium is global memory. The specified format is one previously placed in the COleDataSource object using the DelayRenderData member function for delayed rendering. The default implementation of this function simply returns FALSE.

If phGlobal is NULL, then a new HGLOBAL should be allocated and returned in phGlobal. Otherwise, the HGLOBAL specified by phGlobal should be filled with the data. The amount of data placed in the HGLOBAL must not exceed the current size of the memory block. Also, the block cannot be reallocated to a larger size.

This is an advanced overridable. Override this function to supply your data in the requested format and medium. Depending on your data, you may want to override one of the other versions of this function instead. If you want to handle multiple storage media, override OnRenderData. If your data is in a file, or is of variable size, override OnRenderFileData. For more information on delayed rendering as handled by MFC, see the article Data Objects and Data Sources: Manipulation in Visual C++ Programmer’s Guide.

For more information, see the FORMATETC structure and IDataObject::GetData in the OLE 2 Programmer’s Reference, Volume 1.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::DelayRenderData, COleDataSource::DelayRenderFileData, COleDataSource::OnRenderData, COleDataSource::OnRenderFileData, COleDataSource::OnSetData


COleDataSource::OnSetData

virtual BOOL OnSetData( LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium, BOOL bRelease );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which data is being replaced.

lpStgMedium

Points to the STGMEDIUM structure containing the data that will replace the current contents of the COleDataSource object.

bRelease

Indicates who has ownership of the storage medium after completing the function call. The caller decides who is responsible for releasing the resources allocated on behalf of the storage medium. The caller does this by setting bRelease. If bRelease is nonzero, the data source takes ownership, freeing the medium when it has finished using it. When bRelease is 0, the caller retains ownership and the data source can use the storage medium only for the duration of the call.

Remarks

Called by the framework to set or replace the data in the COleDataSource object in the specified format. The data source does not take ownership of the data until it has successfully obtained it. That is, it does not take ownership if OnSetData returns 0. If the data source takes ownership, it frees the storage medium by calling the ReleaseStgMedium function.

The default implementation does nothing. Override this function to replace the data in the specified format. This is an advanced overridable.

For more information, see the STGMEDIUM and FORMATETC structures and the ReleaseStgMedium and IDataObject::GetData functions in the OLE 2 Programmer’s Reference, Volume 1.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::DelaySetData, COleDataSource::OnRenderData, COleDataSource::OnRenderFileData, COleDataSource::OnRenderGlobalData, COleServerItem::OnSetData


COleDataSource::SetClipboard

void SetClipboard( );

Remarks

Puts the data contained in the COleDataSource object on the Clipboard after calling one of the following functions: CacheData, CacheGlobalData, DelayRenderData, or DelayRenderFileData.

COleDataSource Overview | Class Members | Hierarchy Chart

See Also COleDataSource::GetClipboardOwner, COleDataSource::FlushClipboard


COleDateTime

COleDateTime does not have a base class.

A COleDateTime object encapsulates the DATE data type used in OLE automation. It is one of the possible types for the VARIANT data type of OLE automation. A COleDateTime value represents an absolute date and time value.

The DATE type is implemented as a floating-point value, measuring days from midnight, 30 December 1899. So, midnight, 31 December 1899 is represented by 1.0. Similarly, 6 AM, 1 January 1900 is represented by 2.25, and midnight, 29 December 1899 is – 1.0. However, 6 AM, 29 December 1899 is – 1.25.

Note To interpret the time portion, take the absolute value of the fractional part of the number.

The COleDateTime class handles dates from 1 January 100 – 31 December 9999.

Note COleDateTime ignores Daylight Saving Time. See Date and Time: Automation Support in Visual C++ Programmer's Guide for details.

This type is also used to represent date-only or time-only values. By convention, the date 0 (30 December 1899) is used for time-only values. Similarly, the time 0:00 (midnight) is used for date-only values.

If you create a COleDateTime object with a date less than 100, the date will be accepted, but subsequent calls to GetYear, GetMonth, GetDay, GetHour, GetMinute, and GetSecond will fail and return -1. Previously, you could use two-digit dates, but dates must be 100 or greater in MFC 4.2 and later.

To avoid problems, specify a four-digit date. For example:

COleDateTime.mytime(1996,1,1,0,0,0);

Basic arithmetic operations for the COleDateTime values use the companion class COleDateTimeSpan. COleDateTimeSpan values represent relative time, an interval. The relation between these classes is analogous to the one between CTime and CTimeSpan.

For more information on the COleDateTime and COleDateTimeSpan classes, see the article Date and Time: Automation Support in Visual C++ Programmer's Guide

#include <afxdisp.h>

Class Members | Hierarchy Chart

See Also COleVariant


COleDateTime Class Members

Construction

COleDateTime | Constructs a COleDateTime object.
GetCurrentTime | Creates a COleDateTime object that represents the current time (static member function).

Attributes

GetStatus | Gets the status (validity) of this COleDateTime object.
SetStatus | Sets the status (validity) of this COleDateTime object.
GetAsSystemTime | Converts the time in the COleDateTime object to be represented as a SYSTEMTIME data structure.
GetYear | Returns the year this COleDateTime object represents.
GetMonth | Returns the month this COleDateTime object represents (1 – 12).
GetDay | Returns the day this COleDateTime object represents (1 – 31).
GetHour | Returns the hour this COleDateTime object represents (0 – 23).
GetMinute | Returns the minute this COleDateTime object represents (0 – 59).
GetSecond | Returns the second this COleDateTime object represents (0 – 59).
GetDayOfWeek | Returns the day of the week this COleDateTime object represents (Sunday = 1).
GetDayOfYear | Returns the day of the year this COleDateTime object represents (Jan 1 = 1).

Operations

SetDateTime | Sets the value of this COleDateTime object to the specified date/time value.
SetDate | Sets the value of this COleDateTime object to the specified date-only value.
SetTime | Sets the value of this COleDateTime object to the specified time-only value.
Format | Generates a formatted string representation of a COleDateTime object.
ParseDateTime | Reads a date/time value from a string and sets the value of COleDateTime.

Operators

operator DATE | Converts a ColeDateTime value into a DATE.
operator DATE* | Converts a ColeDateTime value into a DATE*.
operator = | Copies a COleDateTime value.
operator +, - | Add and subtract ColeDateTime values.
operator +=, -= | Add and subtract a ColeDateTime value from this COleDateTime object.
operator ==, <, <=, etc. | Compare two ColeDateTime values.

Data Members

m_dt | Contains the underlying DATE for this COleDateTime object.
m_status | Contains the status of this COleDateTime object.

Archive/Dump

operator << | Outputs a COleDateTime value to Carchive or CDumpContext.
operator >> | Inputs a ColeDateTime object from CArchive.


COleDateTime::COleDateTime

COleDateTime( );
COleDateTime( const COleDateTime& dateSrc );
COleDateTime( const VARIANT& varSrc );
COleDateTime( DATE dtSrc );
COleDateTime( time_t timeSrc );
COleDateTime( const SYSTEMTIME& systimeSrc );
COleDateTime( const FILETIME& filetimeSrc );
COleDateTime( int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec );
COleDateTime( WORD wDosDate, WORD wDosTime );

Parameters

dateSrc

An existing COleDateTime object to be copied into the new COleDateTime object.

varSrc

An existing VARIANT data structure (possibly a COleVariant object) to be converted to a date/time value (VT_DATE) and copied into the new COleDateTime object.

dtSrc

A date/time (DATE) value to be copied into the new COleDateTime object.

timeSrc

A time_t value to be converted to a date/time value and copied into the new COleDateTime object.

systimeSrc

A SYSTEMTIME structure to be converted to a date/time value and copied into the new COleDateTime object.

filetimeSrc

A FILETIME structure to be converted to a date/time value and copied into the new COleDateTime object.

nYear, nMonth, nDay, nHour, nMin, nSec

Indicate the date and time values to be copied into the new COleDateTime object.

wDosDate, wDosTime

MS-DOS date and time values to be converted to a date/time value and copied into the new COleDateTime object.

Remarks

All of these constructors create new COleDateTime objects initialized to the specified value. The following table shows valid ranges for each date and time component:

Date/Time Component | Valid Range
year | 100 – 9999
month | 0 – 12
day | 0 – 31
hour | 0 – 23
minute | 0 – 59
second | 0 – 59

Note that the actual upper bound for the day component varies based on the month and year components. For details, see the SetDate or SetDateTime member functions.

Following is a brief description of each constructor:

  • COleDateTime( ) Constructs a COleDateTime object initialized to 0 (midnight, 30 December 1899).

  • COleDateTime( dateSrc ) Constructs a COleDateTime object from an existing COleDateTime object.

  • COleDateTime( varSrc ) Constructs a COleDateTime object. Attempts to convert a VARIANT structure or COleVariant object to a date/time (VT_DATE) value. If this conversion is successful, the converted value is copied into the new COleDateTime object. If it is not, the value of the COleDateTime object is set to 0 (midnight, 30 December 1899) and its status to invalid.

  • COleDateTime( dtSrc ) Constructs a COleDateTime object from a DATE value.

  • COleDateTime( timeSrc ) Constructs a COleDateTime object from a time_t value.

  • COleDateTime( systimeSrc ) Constructs a COleDateTime object from a SYSTEMTIME value.

  • COleDateTime( filetimeSrc ) Constructs a COleDateTime object from a FILETIME value.

  • COleDateTime( nYear, nMonth, nDay, nHour, nMin, nSec ) Constructs a COleDateTime object from the specified numerical values.

  • COleDateTime( wDosDate, wDosTime ) Constructs a COleDateTime object from the specified MS-DOS date and time values.

For more information, see the VARIANT entry in the Win32 SDK OLE Programmer's Reference.

For more information on the time_t data type, see the time function in the Run-Time Library Reference.

For more information, see the SYSTEMTIME and FILETIME structures in the Win32 SDK documentation.

For more information on MS-DOS date and time values, see DosDateTimeToVariantTime in the Win32 SDK documentation.

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::SetDate, COleDateTime::SetDateTime, COleDateTime::SetTime, COleDateTime::GetStatus, COleDateTime::operator =, COleDateTime::m_dt, COleDateTime::m_status


COleDateTime::Format

CString Format( DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT );

CString Format( LPCTSTR lpszFormat ) const;

CString Format( UINT nFormatID ) const;

Return Value

A CString that contains the formatted date/time value.

Parameters

dwFlags

Indicates flags for locale settings, possibly the following flag:

  • LOCALE_NOUSEROVERRIDE Use the system default locale settings, rather than custom user settings.

  • VAR_TIMEVALUEONLY Ignore the date portion during parsing.

  • VAR_DATEVALUEONLY Ignore the time portion during parsing.

lcid

Indicates locale ID to use for the conversion.

lpszFormat

A formatting string similar to the printf formatting string. Formatting codes, preceded by a percent (%) sign, are replaced by the corresponding COleDateTime component. Other characters in the formatting string are copied unchanged to the returned string. See the run-time function strftime for details. The value and meaning of the formatting codes for Format are listed below:

  • %H Hours in the current day

  • %M Minutes in the current hour

  • %S Seconds in the current minute

  • %% Percent sign

nFormatID

The resource ID for the format-control string.

Remarks

Call this member function to create a formatted representation of the date/time value. If the status of this COleDateTime object is null, the return value is an empty string. If the status is invalid, the return string is specified by the string resource IDS_INVALID_DATETIME.

A brief description of the three forms for this function follows:

Format( dwFlags, lcid )

This form formats the value using the national language specifications (locale IDs) for date/time. Using the default parameters, this form will print a time only if the date portion of the date/time value is date 0 (30 December 1899). Similarly, with the default parameters, this form will print a date only if the time portion of the date/time value is time 0 (midnight). If the date/time value is 0 (30 December 1899, midnight), this form with the default parameters will print midnight.

Format( lpszFormat )

This form formats the value using the format string which contains special formatting codes that are preceded by a percent sign (%), as in printf. The formatting string is passed as a parameter to the function. For more information about the formatting codes, see strftime, wcsftime in the Run-Time Library Reference.

Format( nFormatID )

This form formats the value using the format string which contains special formatting codes that are preceded by a percent sign (%), as in printf. The formatting string is a resource. The ID of this string resource is passed as the parameter. For more information about the formatting codes, see strftime, wcsftime in the Run-Time Library Reference.

For a listing of locale ID values, see the section Supporting Multiple National Languages in the Win32 SDK OLE Programmer’s Reference.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::ParseDateTime, COleDateTime::GetStatus


COleDateTime::GetAsSystemTime

BOOL GetAsSystemTime( SYSTEMTIME& sysTime ) const;

Return Value

TRUE if successful; FALSE if the conversion fails, or if the COleDateTime object is NULL or invalid.

Parameters

sysTime

A reference to a SYSTEMTIME structure to be converted to a date/time value and copied into the new COleDateTime object.

Remarks

Call this member function to convert the time in the COleDateTime object to be represented as a SYSTEMTIME data structure. GetAsSystemTime stores the resulting time in the referenced sysTime object. The SYSTEMTIME data structure initialized by this function will have its wMilliseconds member set to zero.

See GetStatus for more information on the status information held in a COleDateTime object.


COleDateTime::GetCurrentTime

static COleDateTime PASCAL GetCurrentTime( );

Remarks

Call this static member function to return the current date/time value.

Example

COleDateTime dateTest;
   // dateTest value = midnight 30 December 1899

dateTest = COleDateTime::GetCurrentTime();
   // dateTest value = current date and time


COleDateTime::GetDay

int GetDay( ) const;

Return Value

The day of the month represented by the value of this COleDateTime object.

Remarks

Call this member function to get the day of the month represented by this date/time value.

Valid return values range between 1 and 31. If the status of this COleDateTime object is not valid, the return value is AFX_OLE_DATETIME_ERROR.

For information on other member functions that query the value of this COleDateTime object, see the following member functions:

  • GetMonth

  • GetYear

  • GetHour

  • GetMinute

  • GetSecond

  • GetDayOfWeek

  • GetDayOfYear

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus


COleDateTime::GetDayOfWeek

int GetDayOfWeek( ) const;

Return Value

The day of the week represented by the value of this COleDateTime object.

Remarks

Call this member function to get the day of the month represented by this date/time value.

Valid return values range between 1 and 7, where 1=Sunday, 2=Monday, and so on. If the status of this COleDateTime object is not valid, the return value is AFX_OLE_DATETIME_ERROR.

For information on other member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetYear

  • GetHour

  • GetMinute

  • GetSecond

  • GetDayOfYear

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus


COleDateTime::GetDayOfYear

int GetDayOfYear( ) const;

Return Value

The day of the year represented by the value of this COleDateTime object.

Remarks

Call this member function to get the day of the year represented by this date/time value.

Valid return values range between 1 and 366, where January 1 = 1. If the status of this COleDateTime object is not valid, the return value is AFX_OLE_DATETIME_ERROR.

For information on other member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetYear

  • GetHour

  • GetMinute

  • GetSecond

  • GetDayOfWeek

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus


COleDateTime::GetHour

int GetHour( ) const;

Return Value

The hour represented by the value of this COleDateTime object.

Remarks

Call this member function to get the hour represented by this date/time value.

Valid return values range between 0 and 23. If the status of this COleDateTime object is not valid, the return value is AFX_OLE_DATETIME_ERROR.

For information on other member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetYear

  • GetMinute

  • GetSecond

  • GetDayOfWeek

  • GetDayOfYear

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus


COleDateTime::GetMinute

int GetMinute( ) const;

Return Value

The minute represented by the value of this COleDateTime object.

Remarks

Call this member function to get the minute represented by this date/time value.

Valid return values range between 0 and 59. If the status of this COleDateTime object is not valid, the return value is AFX_OLE_DATETIME_ERROR.

For information on other member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetYear

  • GetHour

  • GetSecond

  • GetDayOfWeek

  • GetDayOfYear

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus


COleDateTime::GetMonth

int GetMonth( ) const;

Return Value

The month represented by the value of this COleDateTime object.

Remarks

Call this member function to get the month represented by this date/time value.

Valid return values range between 1 and 12. If the status of this COleDateTime object is not valid, the return value is AFX_OLE_DATETIME_ERROR.

For information on other member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetYear

  • GetHour

  • GetMinute

  • GetSecond

  • GetDayOfWeek

  • GetDayOfYear

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus


COleDateTime::GetSecond

int GetSecond( ) const;

Return Value

The second represented by the value of this COleDateTime object.

Remarks

Call this member function to get the second represented by this date/time value.

Valid return values range between 0 and 59. If the status of this COleDateTime object is not valid, the return value is AFX_OLE_DATETIME_ERROR.

Note The COleDateTime class does not support leap seconds.

For more information about the implementation for COleDateTime, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

For information on other member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetYear

  • GetHour

  • GetMinute

  • GetDayOfWeek

  • GetDayOfYear

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus


COleDateTime::GetStatus

DateTimeStatus GetStatus( ) const;

Return Value

Returns the status of this COleDateTime value.

Remarks

Call this member function to get the status (validity) of a given COleDateTime object.

The return value is defined by the DateTimeStatus enumerated type, which is defined within the COleDateTime class.

enum DateTimeStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleDateTime::valid Indicates that this COleDateTime object is valid.

  • COleDateTime::invalid Indicates that this COleDateTime object is invalid; that is, its value may be incorrect.

  • COleDateTime::null Indicates that this COleDateTime object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

The status of a COleDateTime object is invalid in the following cases:

  • If its value is set from a VARIANT or COleVariant value that could not be converted to a date/time value.

  • If its value is set from a time_t, SYSTEMTIME, or FILETIME value that could not be converted to a valid date/time value.

  • If its value is set by SetDateTime with invalid parameter values.

  • If this object has experienced an overflow or underflow during an arithmetic assignment operation, namely, += or -=.

  • If an invalid value was assigned to this object.

  • If the status of this object was explicitly set to invalid using SetStatus.

For more information about the operations that may set the status to invalid, see the following member functions:

  • COleDateTime

  • SetDateTime

  • operator +, -

  • operator +=, -=

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::SetStatus, COleDateTime::m_status


COleDateTime::GetYear

int GetYear( ) const;

Return Value

The year represented by the value of this COleDateTime object.

Remarks

Call this member function to get the year represented by this date/time value.

Valid return values range between 100 and 9999, which includes the century. If the status of this COleDateTime object is not valid, the return value is AFX_OLE_DATETIME_ERROR.

For information on other member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetHour

  • GetMinute

  • GetSecond

  • GetDayOfWeek

  • GetDayOfYear

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus


COleDateTime::ParseDateTime

BOOL ParseDateTime( LPCTSTR lpszDate, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT );
throw( CMemoryException );
throw( COleException );

Return Value

Nonzero if the string was successfully converted to a date/time value, otherwise 0.

Parameters

lpszDate

A pointer to the null-terminated string which is to be parsed. For details, see Remarks.

dwFlags

Indicates flags for locale settings and parsing. One or more of the following flags:

  • LOCALE_NOUSEROVERRIDE Use the system default locale settings, rather than custom user settings.

  • VAR_TIMEVALUEONLY Ignore the date portion during parsing.

  • VAR_DATEVALUEONLY Ignore the time portion during parsing.

lcid

Indicates locale ID to use for the conversion.

Remarks

Call this member function to parse a string to read a date/time value. If the string was successfully converted to a date/time value, the value of this COleDateTime object is set to that value and its status to valid.

Note Year values must lie between 100 and 9999, inclusively.

The lpszDate parameter can take a variety of formats. For example, the following strings contain acceptable date/time formats:

"25 January 1996"
"8:30:00"
"20:30:00"
"January 25, 1996 8:30:00"
"8:30:00 Jan. 25, 1996"
"1/25/1996 8:30:00"  // always specify the full year,
                     // even in a 'short date' format

Note that the locale ID will also affect whether the string format is acceptable for conversion to a date/time value.

In the case of VAR_DATEVALUEONLY, the time value is set to time 0, or midnight. In the case of VAR_TIMEVALUEONLY, the date value is set to date 0, meaning 30 December 1899.

If the string could not be converted to a date/time value or if there was a numerical overflow, the status of this COleDateTime object is invalid.

If the string conversion failed due to memory allocation errors, this function throws a CMemoryException. In any other error state, this function throws a COleException.

For a listing of locale ID values, see the section Supporting Multiple National Languages in the Win32 SDK OLE Programmer’s Reference.

For more information about the bounds and implementation for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::Format, COleDateTime::GetStatus


COleDateTime::SetDate

int SetDate( int nYear, int nMonth, int nDay );

Return Value

Zero if the value of this COleDateTime object was set successfully; otherwise, 1. This return value is based on the DateTimeStatus enumerated type. For more information, see the SetStatus member function.

Parameters

nYear, nMonth, nDay

Indicate the date components to be copied into this COleDateTime object.

Remarks

Call this member function to set the date and time of this COleDateTime object. The date is set to the specified values. The time is set to time 0, midnight.

See the following table for bounds for the parameter values:

Parameter | Bounds
nYear | 100 – 9999
nMonth | 1 – 12
nDay | 1 – 31

The actual upper bound for nDay values varies based on the month and year. For months 1, 3, 5, 7, 8, 10, and 12, the upper bound is 31. For months 4, 6, 9, and 11, it is 30. For month 2, it is 28, or 29 in a leap year.

If the date value specified by the parameters is not valid, the status of this object is set to invalid and the value of this object is not changed.

Here are some examples of date values:

nYear | nMonth | nDay | Value
1995 | 4 | 15 | 15 April 1995
1789 | 7 | 14 | 17 July 1789
1925 | 2 | 30 | Invalid
10000 | 1 | 1 | Invalid

To set both date and time, see COleDateTime::SetDateTime.

For information on member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetYear

  • GetHour

  • GetMinute

  • GetSecond

  • GetDayOfWeek

  • GetDayOfYear

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus, COleDateTime::m_dt


COleDateTime::SetDateTime

int SetDateTime( int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec );

Return Value

Zero if the value of this COleDateTime object was set successfully; otherwise, 1. This return value is based on the DateTimeStatus enumerated type. For more information, see the SetStatus member function.

Parameters

nYear, nMonth, nDay, nHour, nMin, nSec

Indicate the date and time components to be copied into this COleDateTime object.

Remarks

Call this member function to set the date and time of this COleDateTime object.

See the following table for bounds for the parameter values:

Parameter | Bounds
nYear | 100 – 9999
nMonth | 1 – 12
nDay | 1 – 31
nHour | 0 – 23
nMin | 0 – 59
nSec | 0 – 59

The actual upper bound for nDay values varies based on the month and year. For months 1, 3, 5, 7, 8, 10, and 12, the upper bound is 31. For months 4, 6, 9, and 11, it is 30. For month 2, it is 28, or 29 in a leap year.

If the date or time value specified by the parameters is not valid, the status of this object is set to invalid and the value of this object is not changed.

Here are some examples of time values:

nHour | nMin | nSec | Value
1 | 3 | 3 | 01:03:03
23 | 45 | 0 | 23:45:00
25 | 30 | 0 | Invalid
9 | 60 | 0 | Invalid

Here are some examples of date values:

nYear | nMonth | nDay | Value
1995 | 4 | 15 | 15 April 1995
1789 | 7 | 14 | 17 July 1789
1925 | 2 | 30 | Invalid
10000 | 1 | 1 | Invalid

To set the date only, see COleDateTime::SetDate. To set the time only, see COleDateTime::SetTime.

For information on member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetYear

  • GetHour

  • GetMinute

  • GetSecond

  • GetDayOfWeek

  • GetDayOfYear

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDate, COleDateTime::SetTime, COleDateTime::operator =, COleDateTime::GetStatus, COleDateTime::m_dt


COleDateTime::SetStatus

void SetStatus( DateTimeStatus nStatus );

Parameters

nStatus

The new status value for this COleDateTime object.

Remarks

Call this member function to set the status of this COleDateTime object. The nStatus parameter value is defined by the DateTimeStatus enumerated type, which is defined within the COleDateTime class.

enum DateTimeStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleDateTime::valid Indicates that this COleDateTime object is valid.

  • COleDateTime::invalid Indicates that this COleDateTime object is invalid; that is, its value may be incorrect.

  • COleDateTime::null Indicates that this COleDateTime object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

Caution This function is for advanced programming situations. This function does not alter the data in this object. It will most often be used to set the status to null or invalid. Note that the assignment operator (operator =) and SetDateTime do set the status of the object based on the source value(s).

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::GetStatus, COleDateTime::operator =, COleDateTime::SetDateTime, COleDateTime::m_dt


COleDateTime::SetTime

int SetTime( int nHour, int nMin, int nSec );

Return Value

Zero if the value of this COleDateTime object was set successfully; otherwise, 1. This return value is based on the DateTimeStatus enumerated type. For more information, see the SetStatus member function.

Parameters

nHour, nMin, nSec

Indicate the time components to be copied into this COleDateTime object.

Remarks

Call this member function to set the date and time of this COleDateTime object. The time is set to the specified values. The date is set to date 0, meaning 30 December 1899.

See the following table for bounds for the parameter values:

Parameter | Bounds
nHour | 0 – 23
nMin | 0 – 59
nSec | 0 – 59

If the time value specified by the parameters is not valid, the status of this object is set to invalid and the value of this object is not changed.

Here are some examples of time values:

nHour | nMin | nSec | Value
1 | 3 | 3 | 01:03:03
23 | 45 | 0 | 23:45:00
25 | 30 | 0 | Invalid
9 | 60 | 0 | Invalid

To set both date and time, see COleDateTime::SetDateTime.

For information on member functions that query the value of this COleDateTime object, see the following member functions:

  • GetDay

  • GetMonth

  • GetYear

  • GetHour

  • GetMinute

  • GetSecond

  • GetDayOfWeek

  • GetDayOfYear

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::operator =, COleDateTime::GetStatus, COleDateTime::m_dt


COleDateTime::operator =

const COleDateTime& operator =( const COleDateTime& dateSrc );
const COleDateTime& operator =( const VARIANT& varSrc );
const COleDateTime& operator =( DATE dtSrc );
const COleDateTime& operator =( const time_t& timeSrc );
const COleDateTime& operator =( const SYSTEMTIME& systimeSrc );
const COleDateTime& operator =( const FILETIME& filetimeSrc );

Remarks

These overloaded assignment operators copy the source date/time value into this COleDateTime object. A brief description of each these overloaded assignment operators follows:

  • operator =( dateSrc ) The value and status of the operand are copied into this COleDateTime object.

  • operator =( varSrc ) If the conversion of the VARIANT value (or COleVariant object) to a date/time (VT_DATE) is successful, the converted value is copied into this COleDateTime object and its status is set to valid. If the conversion is not successful, the value of this object is set to zero (30 December 1899, midnight) and its status to invalid.

  • operator =( dtSrc ) The DATE value is copied into this COleDateTime object and its status is set to valid.

  • operator =( timeSrc ) The time_t value is converted and copied into this COleDateTime object. If the conversion is successful, the status of this object is set to valid; if unsuccessful, it is set to invalid.

  • operator =( systimeSrc ) The SYSTEMTIME value is converted and copied into this COleDateTime object. If the conversion is successful, the status of this object is set to valid; if unsuccessful, it is set to invalid.

  • operator =( filetimeSrc ) The FILETIME value is converted and copied into this COleDateTime object. If the conversion is successful, the status of this object is set to valid; if unsuccessful, it is set to invalid.

For more information, see the VARIANT entry in the Win32 SDK OLE Programmer's Reference.

For more information on the time_t data type, see the time function in the Run-Time Library Reference.

For more information, see the SYSTEMTIME and FILETIME structures in the Win32 SDK documentation.

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::GetStatus


COleDateTime::operator +, -

COleDateTime operator +( const COleDateTimeSpan& dateSpan ) const;

COleDateTime operator -( const COleDateTimeSpan& dateSpan ) const;

COleDateTimeSpan operator -( const COleDateTime& date ) const;

Remarks

COleDateTime objects represent absolute times. COleDateTimeSpan objects represent relative times. The first two operators allow you to add and subtract a COleDateTimeSpan value from a COleDateTime value. The third operator allows you to subtract one COleDateTime value from another to yield a COleDateTimeSpan value.

If either of the operands is null, the status of the resulting COleDateTime value is null.

If the resulting COleDateTime value falls outside the bounds of acceptable values, the status of that COleDateTime value is invalid.

If either of the operands is invalid and the other is not null, the status of the resulting COleDateTime value is invalid.

For more information on the valid, invalid, and null status values, see the m_status member variable.

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::operator +=, -=, COleDateTime::GetStatus, COleDateTimeSpan


COleDateTime::operator +=, -=

const COleDateTime& operator +=( const COleDateTimeSpan dateSpan );

const COleDateTime& operator -=( const COleDateTimeSpan dateSpan );

Remarks

These operators allow you to add and subtract a COleDateTimeSpan value to and from this COleDateTime.

If either of the operands is null, the status of the resulting COleDateTime value is null.

If the resulting COleDateTime value falls outside the bounds of acceptable values, the status of this COleDateTime value is set to invalid.

If either of the operands is invalid and other is not null, the status of the resulting COleDateTime value is invalid.

For more information on the valid, invalid, and null status values, see the m_status member variable.

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::operator +, -, COleDateTime::GetStatus


COleDateTime::operator DATE

operator DATE( ) const;

Remarks

This operator returns a DATE object whose value is copied from this COleDateTime object.

For more information about the implementation of the DATE object, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::m_dt


COleDateTime Relational Operators

BOOL operator ==( const COleDateTime& date ) const;
BOOL operator !=( const COleDateTime& date ) const;
BOOL operator <( const COleDateTime& date ) const;
BOOL operator >( const COleDateTime& date ) const;
BOOL operator <=( const COleDateTime& date ) const;
BOOL operator >=( const COleDateTime& date ) const;

Remarks

These operators compare two date/time values and return nonzero if the condition is true; otherwise 0.

Note The return value of the ordering operations (<, <=, >, >=) is undefined if the status of either operand is null or invalid. The equality operators (==, !=) consider the status of the operands.

Example

COleDateTime dateOne(95, 3, 15, 12, 0, 0); // 15 March 1995 12 noon
COleDateTime dateTwo(dateOne);             // 15 March 1995 12 noon
BOOL b;
b = dateOne == dateTwo;                    // TRUE

dateTwo.SetStatus(COleDateTime::invalid);
b = dateOne == dateTwo;                    // FALSE, different status
b = dateOne != dateTwo;                    // TRUE, different status
b = dateOne < dateTwo;                     // FALSE, same value
b = dateOne > dateTwo;                     // FALSE, same value
b = dateOne <= dateTwo;                    // TRUE, same value
b = dateOne >= dateTwo;                    // TRUE, same value

Note The last four lines of the preceding example will ASSERT in debug mode.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::GetStatus


COleDateTime::operator <<, >>

friend CDumpContext& AFXAPI operator <<( CDumpContext& dc, COleDateTime timeSrc );
friend CArchive& AFXAPI operator <<( CArchive& ar, COleDateTime dateSrc );
friend CArchive& AFXAPI operator >>( CArchive& ar, COleDateTime& dateSrc );

Remarks

The COleDateTime insertion (<<) operator supports diagnostic dumping and storing to an archive. The extraction (>>) operator supports loading from an archive.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also CDumpContext, CArchive


COleDateTime::m_dt

Remarks

The underlying DATE structure for this COleDateTime object.

Caution Changing the value in the DATE object accessed by the pointer returned by this function will change the value of this COleDateTime object. It does not change the status of this COleDateTime object.

For more information about the implementation of the DATE object, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::COleDateTime, COleDateTime::SetDateTime, COleDateTime::SetDate, COleDateTime::SetTime, COleDateTime::operator DATE


COleDateTime::m_status

Remarks

The type of this data member is the enumerated type DateTimeStatus, which is defined within the COleDateTime class.

enum DateTimeStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleDateTime::valid Indicates that this COleDateTime object is valid.

  • COleDateTime::invalid Indicates that this COleDateTime object is invalid; that is, its value may be incorrect.

  • COleDateTime::null Indicates that this COleDateTime object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

The status of a COleDateTime object is invalid in the following cases:

  • If its value is set from a VARIANT or COleVariant value that could not be converted to a date/time value.

  • If its value is set from a time_t, SYSTEMTIME, or FILETIME value that could not be converted to a valid date/time value.

  • If its value is set by SetDateTime with invalid parameter values.

  • If this object has experienced an overflow or underflow during an arithmetic assignment operation, namely, += or -=.

  • If an invalid value was assigned to this object.

  • If the status of this object was explicitly set to invalid using SetStatus.

For more information about the operations that may set the status to invalid, see the following member functions:

  • COleDateTime

  • SetDateTime

  • operator +, -

  • operator +=, -=

Caution This data member is for advanced programming situations. You should use the inline member functions GetStatus and SetStatus. See SetStatus for further cautions regarding explicitly setting this data member.

For more information about the bounds for COleDateTime values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTime Overview | Class Members | Hierarchy Chart

See Also COleDateTime::GetStatus, COleDateTime::SetStatus


COleDateTimeSpan

COleDateTimeSpan does not have a base class.

A COleDateTimeSpan object represents a relative time, a time span. A COleDateTimeSpan keeps time in days.

COleDateTimeSpan is used with its companion class COleDateTime. COleDateTime encapsulates the DATE data type of OLE automation. COleDateTime represents absolute time values. All COleDateTime calculations involve COleDateTimeSpan values. The relation between these classes is analogous to the one between CTime and CTimeSpan.

For more information on the COleDateTime and COleDateTimeSpan classes, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

#include <afxdisp.h>


COleDateTimeSpan Class Members

Constructor

COleDateTimeSpan Constructs a COleDateTimeSpan object.

Attributes

GetStatus | Gets the status (validity) of this COleDateTimeSpan object.
SetStatus | Sets the status (validity) of this COleDateTimeSpan object.
GetDays | Returns the day portion of the span this COleDateTimeSpan object represents.
GetHours | Returns the hour portion of the span this COleDateTimeSpan object represents.
GetMinutes | Returns the minute portion of the span this COleDateTimeSpan object represents.
GetSeconds | Returns the second portion of the span this COleDateTimeSpan object represents.
GetTotalDays | Returns the number of days this COleDateTimeSpan object represents.
GetTotalHours | Returns the number of hours this COleDateTimeSpan object represents.
GetTotalMinutes | Returns the number of minutes this COleDateTimeSpan object represents.
GetTotalSeconds | Returns the number of seconds this COleDateTimeSpan object represents.

Operations

SetDateTimeSpan | Sets the value of this COleDateTimeSpan object.
Format | Generates a formatted string representation of a COleDateTimeSpan object.

Operators

operator double | Converts this COleDateTimeSpan value to a double.
operator = | Copies a COleDateTimeSpan value.
operator +, - | Add, subtract, and change sign for COleDateTimeSpan values.
operator +=, -= | Add and subtract a COleDateTimeSpan value from this COleDateTimeSpan value.
operator ==, <, <= | Compare two COleDateTimeSpan values.

Data Members

m_span | Contains the underlying double for this COleDateTimeSpan object.
m_status | Contains the status of this COleDateTimeSpan object.

Dump/Archive

operator << | Outputs a COleDateTimeSpan value to CArchive or CDumpContext.
operator >> | Inputs a COleDateTimeSpan object from CArchive.


COleDateTimeSpan::COleDateTimeSpan

COleDateTimeSpan( );

COleDateTimeSpan( const COleDateTimeSpan& dateSpanSrc );

COleDateTimeSpan( double dblSpanSrc );

COleDateTimeSpan( long lDays, int nHours, int nMins, int nSecs );

Parameters

dateSpanSrc

An existing COleDateTimeSpan object to be copied into the new COleDateTimeSpan object.

dblSpanSrc

The number of days to be copied into the new COleDateTimeSpan object.

lDays, nHours, nMins, nSecs

Indicate the day and time values to be copied into the new COleDateTimeSpan object.

Remarks

All of these constructors create new COleDateTimeSpan objects initialized to the specified value. A brief description of each of these constructors follows:

  • COleDateTimeSpan( ) Constructs a COleDateTimeSpan object initialized to 0.

  • COleDateTimeSpan( dateSpanSrc ) Constructs a COleDateTimeSpan object from an existing COleDateTimeSpan object.

  • COleDateTimeSpan( dblSpanSrc ) Constructs a COleDateTimeSpan object from a floating-point value.

  • COleDateTimeSpan( lDays, nHours, nMins, nSecs ) Constructs a COleDateTimeSpan object initialized to the specified numerical values.

The status of the new COleDateTimeSpan object is set to valid.

For more information about the bounds for COleDateTimeSpan values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

Example

COleDateTimeSpan spanOne( 2.75 );          // 2 days and 18 hours
COleDateTimeSpan spanTwo( 2, 18, 0, 0 );   // 2 days and 18 hours
COleDateTimeSpan spanThree( 3, -6, 0, 0 ); // 2 days and 18 hours

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::operator =, COleDateTimeSpan::GetStatus, COleDateTimeSpan::m_span, COleDateTimeSpan::m_status


COleDateTimeSpan::Format

CString Format( LPCTSTR pFormat ) const;

CString Format( UINT nID ) const;

Return Value

A CString that contains the formatted date/time-span value.

Parameters

pFormat

A formatting string similar to the printf formatting string. Formatting codes, preceded by a percent (%) sign, are replaced by the corresponding COleDateTimeSpan component. Other characters in the formatting string are copied unchanged to the returned string. See the run-time function strftime for details. The value and meaning of the formatting codes for Format are listed below:

  • %H Hours in the current day

  • %M Minutes in the current hour

  • %S Seconds in the current minute

  • %% Percent sign

nID

The resource ID for the format-control string.

Remarks

Call these functions to create a formatted representation of the time-span value. If the status of this COleDateTimeSpan object is null, the return value is an empty string. If the status is invalid, the return string is specified by the string resource IDS_INVALID_DATETIMESPAN.

A brief description of the forms for this function follows:

Format( pFormat )

This form formats the value using the format string which contains special formatting codes that are preceded by a percent sign (%), as in printf. The formatting string is passed as a parameter to the function.

Format( nID )

This form formats the value using the format string which contains special formatting codes that are preceded by a percent sign (%), as in printf. The formatting string is a resource. The ID of this string resource is passed as the parameter.

For more information about the formatting codes used in this function, see strftime, wcsftime in the Run-Time Library Reference.

For a listing of locale ID values, see the section Supporting Multiple National Languages in the Win32 SDK OLE Programmer’s Reference.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::GetStatus


COleDateTimeSpan::GetDays

long GetDays( ) const;

Return Value

The day portion of this date/time-span value.

Remarks

Call this member function to retrieve the day portion of this date/time-span value.

The return values from this function range between approximately – 3,615,000 and 3,615,000.

For other functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetHours

  • GetMinutes

  • GetSeconds

  • GetTotalDays

  • GetTotalHours

  • GetTotalMinutes

  • GetTotalSeconds

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetDateTimeSpan


COleDateTimeSpan::GetHours

long GetHours( ) const;

Return Value

The hours portion of this date/time-span value.

Remarks

Call this member function to retrieve the hour portion of this date/time-span value.

The return values from this function range between – 23 and 23.

For other functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetDays

  • GetMinutes

  • GetSeconds

  • GetTotalDays

  • GetTotalHours

  • GetTotalMinutes

  • GetTotalSeconds

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetDateTimeSpan


COleDateTimeSpan::GetMinutes

long GetMinutes( ) const;

Return Value

The minutes portion of this date/time-span value.

Remarks

Call this member function to retrieve the minute portion of this date/time-span value.

The return values from this function range between – 59 and 59.

For other functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetDays

  • GetHours

  • GetSeconds

  • GetTotalDays

  • GetTotalHours

  • GetTotalMinutes

  • GetTotalSeconds

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetDateTimeSpan


COleDateTimeSpan::GetSeconds

long GetSeconds( ) const;

Return Value

The seconds portion of this date/time-span value.

Remarks

Call this member function to retrieve the second portion of this date/time-span value.

The return values from this function range between – 59 and 59.

For other functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetDays

  • GetHours

  • GetMinutes

  • GetTotalDays

  • GetTotalHours

  • GetTotalMinutes

  • GetTotalSeconds

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetDateTimeSpan


COleDateTimeSpan::GetStatus

DateTimeSpanStatus GetStatus( ) const;

Return Value

The status of this COleDateTimeSpan value.

Remarks

Call this member function to get the status (validity) of this COleDateTimeSpan object.

The return value is defined by the DateTimeSpanStatus enumerated type, which is defined within the COleDateTimeSpan class.

enum DateTimeSpanStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleDateTimeSpan::valid Indicates that this COleDateTimeSpan object is valid.

  • COleDateTimeSpan::invalid Indicates that this COleDateTimeSpan object is invalid; that is, its value may be incorrect.

  • COleDateTimeSpan::null Indicates that this COleDateTimeSpan object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

The status of a COleDateTimeSpan object is invalid in the following cases:

  • If this object has experienced an overflow or underflow during an arithmetic assignment operation, namely, += or -=.

  • If an invalid value was assigned to this object.

  • If the status of this object was explicitly set to invalid using SetStatus.

For more information about the operations that may set the status to invalid, see COleDateTimeSpan::operator +, - and COleDateTimeSpan::operator +=, -=.

For more information about the bounds for COleDateTimeSpan values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetStatus, COleDateTimeSpan::m_status


COleDateTimeSpan::GetTotalDays

double GetTotalDays( ) const;

Return Value

This date/time-span value expressed in days. Although this function is prototyped to return a double, it will always return an integer value.

Remarks

Call this member function to retrieve this date/time-span value expressed in days.

The return values from this function range between approximately – 3.65e6 and 3.65e6.

For other functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetDays

  • GetHours

  • GetMinutes

  • GetSeconds

  • GetTotalHours

  • GetTotalMinutes

  • GetTotalSeconds

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetDateTimeSpan, COleDateTimeSpan::operator double


COleDateTimeSpan::GetTotalHours

double GetTotalHours( ) const;

Return Value

This date/time-span value expressed in hours. Although this function is prototyped to return a double, it will always return an integer value.

Remarks

Call this member function to retrieve this date/time-span value expressed in hours.

The return values from this function range between approximately – 8.77e7 and 8.77e7.

For other functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetDays

  • GetHours

  • GetMinutes

  • GetSeconds

  • GetTotalDays

  • GetTotalMinutes

  • GetTotalSeconds

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetDateTimeSpan


COleDateTimeSpan::GetTotalMinutes

double GetTotalMinutes( ) const;

Return Value

This date/time-span value expressed in minutes. Although this function is prototyped to return a double, it will always return an integer value.

Remarks

Call this member function to retrieve this date/time-span value expressed in minutes.

The return values from this function range between approximately – 5.26e9 and 5.26e9.

For other functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetDays

  • GetHours

  • GetMinutes

  • GetSeconds

  • GetTotalDays

  • GetTotalHours

  • GetTotalSeconds

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetDateTimeSpan


COleDateTimeSpan::GetTotalSeconds

double GetTotalSeconds( ) const;

Return Value

This date/time-span value expressed in seconds. Although this function is prototyped to return a double, it will always return an integer value.

Remarks

Call this member function to retrieve this date/time-span value expressed in seconds.

The return values from this function range between approximately – 3.16e11 to 3.16e11.

For other functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetDays

  • GetHours

  • GetMinutes

  • GetSeconds

  • GetTotalDays

  • GetTotalHours

  • GetTotalMinutes

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::SetDateTimeSpan


COleDateTimeSpan::SetDateTimeSpan

void SetDateTimeSpan( long lDays, int nHours, int nMins, int nSecs );

Parameters

lDays, nHours, nMins, nSecs

Indicate the date-span and time-span values to be copied into this COleDateTimeSpan object.

Remarks

Call this member function to set the value of this date/time-span value.

For functions that query the value of a COleDateTimeSpan object, see the following member functions:

  • GetDays

  • GetHours

  • GetMinutes

  • GetSeconds

  • GetTotalDays

  • GetTotalHours

  • GetTotalMinutes

  • GetTotalSeconds

Example

COleDateTimeSpan spanOne;
COleDateTimeSpan spanTwo;
spanOne.SetDateTimeSpan(0, 2, 45, 0);  // 2 hours and 45 seconds
spanTwo.SetDateTimeSpan(0, 3, -15, 0); // 2 hours and 45 seconds

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::GetStatus, COleDateTimeSpan::m_span


COleDateTimeSpan::SetStatus

void SetStatus( DateTimeSpanStatus nStatus );

Parameters

nStatus

The new status value for this COleDateTimeSpan object.

Remarks

Call this member function to set the status (validity) of this COleDateTimeSpan object. The nStatus parameter value is defined by the DateTimeSpanStatus enumerated type, which is defined within the COleDateTimeSpan class.

enum DateTimeSpanStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleDateTimeSpan::valid Indicates that this COleDateTimeSpan object is valid.

  • COleDateTimeSpan::invalid Indicates that this COleDateTimeSpan object is invalid; that is, its value may be incorrect.

  • COleDateTimeSpan::null Indicates that this COleDateTimeSpan object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

Caution This function is for advanced programming situations. This function does not alter the data in this object. It will most often be used to set the status to null or invalid. Note that the assignment operator (operator =) and SetDateTimeSpan do set the status of the object based on the source value(s).

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::GetStatus, COleDateTimeSpan::m_status


COleDateTimeSpan::operator =

const COleDateTimeSpan& operator=( double dblSpanSrc );

const COleDateTimeSpan& operator=( const COleDateTimeSpan& dateSpanSrc );

Remarks

These overloaded assignment operators copy the source date/time-span value into this COleDateTimeSpan object.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::COleDateTimeSpan


COleDateTimeSpan::operator +, -

COleDateTimeSpan operator+( const COleDateTimeSpan& dateSpan ) const;

COleDateTimeSpan operator-( const COleDateTimeSpan& dateSpan ) const;

COleDateTimeSpan operator-( ) const;

Remarks

The first two operators let you add and subtract date/time-span values. The third lets you change the sign of a date/time-span value.

If either of the operands is null, the status of the resulting COleDateTimeSpan value is null.

If either of the operands is invalid and the other is not null, the status of the resulting COleDateTimeSpan value is invalid.

For more information on the valid, invalid, and null status values, see the m_status member variable.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::operator +=, -=


COleDateTimeSpan::operator +=, -=

const COleDateTimeSpan& operator+=( const COleDateTimeSpan dateSpan );

const COleDateTimeSpan& operator-=( const COleDateTimeSpan dateSpan );

Remarks

These operators let you add and subtract date/time-span values from this COleDateTimeSpan object.

If either of the operands is null, the status of the resulting COleDateTimeSpan value is null.

If either of the operands is invalid and the other is not null, the status of the resulting COleDateTimeSpan value is invalid.

For more information on the valid, invalid, and null status values, see the m_status member variable.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::operator +, -


COleDateTimeSpan::operator double

operator double( ) const;

Remarks

This operator returns the value of this COleDateTimeSpan value as a floating-point number of days.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::GetTotalDays, COleDateTimeSpan::SetDateTimeSpan, COleDateTimeSpan::m_span


COleDateTimeSpan Relational Operators

BOOL operator==( const COleDateTimeSpan& dateSpan ) const;

BOOL operator!=( const COleDateTimeSpan& dateSpan ) const;

BOOL operator<( const COleDateTimeSpan& dateSpan ) const;

BOOL operator>( const COleDateTimeSpan& dateSpan ) const;

BOOL operator<=( const COleDateTimeSpan& dateSpan ) const;

BOOL operator>=( const COleDateTimeSpan& dateSpan ) const;

Remarks

These operators compare two date/time-span values and return nonzero if the condition is true; otherwise 0.

Note The return value of the ordering operations (<, <=, >, >=) is undefined if the status of either operand is null or invalid. The equality operators (==, !=) consider the status of the operands.

Example

COleDateTimeSpan spanOne(3, 12, 0, 0); // 3 days and 12 hours
COleDateTimeSpan spanTwo(spanOne);     // 3 days and 12 hours
BOOL b;
b = spanOne == spanTwo;                // TRUE

spanTwo.SetStatus(COleDateTimeSpan::invalid);
b = spanOne == spanTwo;                // FALSE, different status
b = spanOne != spanTwo;                // TRUE, different status
b = spanOne < spanTwo;                 // FALSE, same value
b = spanOne > spanTwo;                 // FALSE, same value
b = spanOne <= spanTwo;                // TRUE, same value
b = spanOne >= spanTwo;                // TRUE, same value

Note The last four lines of the preceding example will ASSERT in debug mode.


COleDateTimeSpan::operator <<, >>

friend CDumpContext& AFXAPI operator<<( CDumpContext& dc, COleDateTimeSpan dateSpan );

friend CArchive& AFXAPI operator<<( CArchive& ar, COleDateTimeSpan dateSpan );

friend CArchive& AFXAPI operator>>( CArchive& ar, COleDateTimeSpan& dateSpan );

Remarks

The COleDateTimeSpan insertion (<<) operator supports diagnostic dumping and storing to an archive. The extraction (>>) operator supports loading from an archive.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also CDumpContext, CArchive


COleDateTimeSpan::m_span

Remarks

The underlying double value for this COleDateTime object. This value expresses the date/time-span in days.

Caution Changing the value in the double data member will change the value of this COleDateTimeSpan object. It does not change the status of this COleDateTimeSpan object.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::COleDateTimeSpan, COleDateTimeSpan::SetDateTimeSpan, COleDateTimeSpan::operator double


COleDateTimeSpan::m_status

Remarks

The type for this data member is the enumerated type DateTimeSpanStatus, which is defined within the COleDateTimeSpan class.

enum DateTimeSpanStatus{
   valid = 0,
   invalid = 1,
   null = 2,
};

For a brief description of these status values, see the following list:

  • COleDateTimeSpan::valid Indicates that this COleDateTimeSpan object is valid.

  • COleDateTimeSpan::invalid Indicates that this COleDateTimeSpan object is invalid; that is, its value may be incorrect.

  • COleDateTimeSpan::null Indicates that this COleDateTimeSpan object is null, that is, that no value has been supplied for this object. (This is “null” in the database sense of “having no value,” as opposed to the C++ NULL.)

The status of a COleDateTimeSpan object is invalid in the following cases:

  • If this object has experienced an overflow or underflow during an arithmetic assignment operation, namely, += or -=.

  • If an invalid value was assigned to this object.

  • If the status of this object was explicitly set to invalid using SetStatus.

For more information about the operations that may set the status to invalid, see COleDateTimeSpan::operator +, - and COleDateTimeSpan::operator +=, -=.

Caution This data member is for advanced programming situations. You should use the inline member functions GetStatus and SetStatus. See SetStatus for further cautions regarding explicitly setting this data member.

For more information about the bounds for COleDateTimeSpan values, see the article Date and Time: Automation Support in Visual C++ Programmer’s Guide.

COleDateTimeSpan Overview | Class Members | Hierarchy Chart

See Also COleDateTimeSpan::GetStatus, COleDateTimeSpan::SetStatus


COleDBRecordView

A COleDBRecordView object is a view that displays database records in controls. The view is a form view directly connected to a CRowset object. The view is created from a dialog template resource and displays the fields of the CRowset object in the dialog template's controls. The COleDBRecordView object uses dialog data exchange (DDX), and the navigational functionality built into CRowSet, to automate the movement of data between the controls on the form and the fields of the rowset. COleDBRecordView also supplies a default implementation for moving to the first, next, previous, or last record and an interface for updating the record currently on view.

Note If you are working with the Data Access Objects (DAO) classes rather than the OLE DB Consumer Template classes, use class CDaoRecordView instead. For more information, see the articles Database Topics (General) and DAO and MFC in Visual C++ Programmer's Guide.

COleDBRecordView keeps track of the user's position in the rowset so that the record view can update the user interface. When the user moves to either end of the rowset, the record view disables user interface objects — such as menu items or toolbar buttons — for moving further in the same direction.

For more information about rowset classes, see the Using OLE DB Consumer Templates article.

Class Members | Base Class | Hierarchy Chart

#include <afxoledb.h>


COleDBRecordView Class Members

Construction

COleDBRecordView Constructs a COleDBRecordView object.

Attributes

OnGetRowset Returns a pointer to an object of class CRowset.

Operations

OnMove Updates the current record (if dirty) on the data source and then moves to the specified record (next, previous, first, or last).


COleDBRecordView::COleDBRecordView

COleDBRecordView( LPCTSTR lpszTemplateName );

COleDBRecordView( UINT nIDTemplate );

Parameters

lpszTemplateName

Contains a null-terminated string that is the name of a dialog-template resource.

nIDTemplate

Contains the ID number of a dialog-template resource.

Remarks

When you create an object of a type derived from COleDBRecordView, invoke one of the constructors to create the view object and identify the dialog resource on which the view is based. You can identify the resource either by name (pass a string as the argument to the constructor) or by its ID (pass an unsigned integer as the argument).

Note Your derived class must supply its own constructor. In the constructor, invoke the constructor, COleDBRecordView::COleDBRecordView, with the resource name or ID as an argument.


COleDBRecordView::OnGetRowset

virtual CRowset* OnGetRowset( ) = 0;

Return Value

A pointer to a CRowset object if the object was successfully created; otherwise a NULL pointer.

Remarks

Returns a pointer to the CRowset object associated with the record view. You must override this member function to construct or obtain a rowset object and return a pointer to it. If you declare your record view class with ClassWizard, the wizard writes a default override for you. ClassWizard's default implementation returns the rowset pointer stored in the record view if one exists. If not, it constructs a rowset object of the type you specified with ClassWizard and calls its Open member function to open the table or run the query, and then returns a pointer to the object.

For more information and examples, see the article Record Views: Using a Record View in Visual C++ Programmer's Guide.


COleDBRecordView::OnMove

virtual BOOL OnMove( UINT nIDMoveCommand );

Return Value

Nonzero if the move was successful; otherwise 0 if the move request was denied.

Parameters

nIDMoveCommand

One of the following standard command ID values:

  • ID_RECORD_FIRST Move to the first record in the recordset.

  • ID_RECORD_LAST Move to the last record in the recordset.

  • ID_RECORD_NEXT Move to the next record in the recordset.

  • ID_RECORD_PREV Move to the previous record in the recordset.

Remarks

Call this member function to move to a different record in the rowset and display its fields in the controls of the record view. The default implementation calls the appropriate Move member function of the CRowset object associated with the record view.

By default, OnMove updates the current record on the data source if the user has changed it in the record view.

AppWizard creates a menu resource with First Record, Last Record, Next Record, and Previous Record menu items. If you select the Dockable Toolbar option, AppWizard also creates a toolbar with buttons corresponding to these commands.

If you move past the last record in the recordset, the record view continues to display the last record. If you move backward past the first record, the record view continues to display the first record.


COleDialog

The COleDialog class provides functionality common to dialog boxes for OLE. The Microsoft Foundation Class Library provides several classes derived from COleDialog.

These are:

  • COleInsertDialog

  • COleConvertDialog

  • COleChangeIconDialog

  • COleLinksDialog

  • COleBusyDialog

  • COleUpdateDialog

  • COlePasteSpecialDialog

  • COlePropertiesDialog

  • COleChangeSourceDialog

For more information about OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>


COleDialog Class Members

Operations

GetLastError Gets the error code returned by the dialog box.


COleDialog::GetLastError

UINT GetLastError( ) const;

Return Value

The error codes returned by GetLastError depend on the specific dialog box displayed.

Remarks

Call the GetLastError member function to get additional error information when DoModal returns IDABORT. See the DoModal member function in the derived classes for information about specific error messages.

COleDialog Overview | Class Members | Hierarchy Chart

See Also COleBusyDialog::DoModal, COleChangeIconDialog::DoModal, COleChangeSourceDialog::DoModal, COleConvertDialog::DoModal, COleInsertDialog::DoModal, COleLinksDialog::DoModal, COlePasteSpecialDialog::DoModal, COlePropertiesDialog::DoModal, COleUpdateDialog::DoModal


COleDispatchDriver

COleDispatchDriver does not have a base class.

The COleDispatchDriver class implements the client side of OLE automation. OLE dispatch interfaces provide access to an object’s methods and properties. Member functions of COleDispatchDriver attach, detach, create, and release a dispatch connection of type IDispatch. Other member functions use variable argument lists to simplify calling IDispatch::Invoke.

For more information, see IDispatch and IDispatch::Invoke in the Win32 SDK OLE Programmer’s Reference.

This class can be used directly, but it is generally used only by classes created by ClassWizard. When you create new C++ classes by importing a type library, ClassWizard derives the new classes from COleDispatchDriver.

For more information on using COleDispatchDriver, see the following articles in Visual C++ Programmer’s Guide:

  • Automation Clients

  • Automation Servers

  • ClassWizard: Automation Support

#include <afxdisp.h>

Class Members | Hierarchy Chart

Samples MFC Sample CALCDRIV | MFC Sample ACDUAL

See Also CCmdTarget


COleDispatchDriver Class Members

Data Members

m_bAutoRelease | Specifies whether to release the IDispatch during ReleaseDispatch or object destruction.
m_lpDispatch | Indicates the pointer to the IDispatch interface attached to this COleDispatchDriver.

Construction

COleDispatchDriver Constructs a COleDispatchDriver object.

Operations

CreateDispatch | Creates an IDispatch connection and attaches it to the COleDispatchDriver object.
AttachDispatch | Attaches an IDispatch connection to the COleDispatchDriver object.
DetachDispatch | Detaches an IDispatch connection, without releasing it.
ReleaseDispatch | Releases an IDispatch connection.
InvokeHelper | Helper for calling automation methods.
SetProperty | Sets an automation property.
GetProperty | Gets an automation property.


COleDispatchDriver::AttachDispatch

void AttachDispatch( LPDISPATCH lpDispatch, BOOL bAutoRelease = TRUE );

Parameters

lpDispatch

Pointer to an OLE IDispatch object to be attached to the COleDispatchDriver object.

bAutoRelease

Specifies whether the dispatch is to be released when this object goes out of scope.

Remarks

Call the AttachDispatch member function to attach an IDispatch pointer to the COleDispatchDriver object. This function releases any IDispatch pointer that is already attached to the COleDispatchDriver object.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::DetachDispatch, COleDispatchDriver::ReleaseDispatch, COleDispatchDriver::CreateDispatch, COleDispatchDriver::m_lpDispatch, COleDispatchDriver::m_bAutoRelease


COleDispatchDriver::COleDispatchDriver

COleDispatchDriver( );

COleDispatchDriver( LPDISPATCH lpDispatch, BOOL bAutoRelease = TRUE );

COleDispatchDriver( const COleDispatchDriver& dispatchSrc );

Parameters

lpDispatch

Pointer to an OLE IDispatch object to be attached to the COleDispatchDriver object.

bAutoRelease

Specifies whether the dispatch is to be released when this object goes out of scope.

dispatchSrc

Reference to an existing COleDispatchDriver object.

Remarks

Constructs a COleDispatchDriver object. The form COleDispatchDriver(LPDISPATCH lpDispatch, BOOL bAutoRelease = TRUE) connects the IDispatch interface.

The form COleDispatchDriver(const COleDispatchDriver& dispatchSrc) copies an existing COleDispatchDriver object and increments the reference count.

The form COleDispatchDriver( ) creates a COleDispatchDriver object but does not connect the IDispatch interface. Before using COleDispatchDriver( ) without arguments, you should connect an IDispatch to it using either COleDispatchDriver::CreateDispatch or COleDispatchDriver::AttachDispatch.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::AttachDispatch, COleDispatchDriver::CreateDispatch


COleDispatchDriver::CreateDispatch

BOOL CreateDispatch( REFCLSID clsid, COleException* pError = NULL );

BOOL CreateDispatch( LPCTSTR lpszProgID, COleException* pError = NULL );

Return Value

Nonzero on success; otherwise 0.

Parameters

clsid

Class ID of the IDispatch connection object to be created.

pError

Pointer to an OLE exception object, which will hold the status code resulting from the creation.

lpszProgID

Pointer to the programmatic identifier, such as “Excel.Document.5”, of the automation object for which the dispatch object is to be created.

Remarks

Creates an IDispatch object and attaches it to the COleDispatchDriver object.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::DetachDispatch, COleDispatchDriver::ReleaseDispatch, COleDispatchDriver::AttachDispatch, COleException, COleDispatchDriver::m_lpDispatch


COleDispatchDriver::DetachDispatch

LPDISPATCH DetachDispatch( );

Return Value

A pointer to the previously attached OLE IDispatch object.

Remarks

Detaches the current IDispatch connection from this object. The IDispatch is not released.

For more information about the LPDISPATCH type, see IDispatch in the OLE Programmer’s Reference.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::ReleaseDispatch, COleDispatchDriver::CreateDispatch, COleDispatchDriver::AttachDispatch, COleDispatchDriver::m_lpDispatch


COleDispatchDriver::GetProperty

void GetProperty( DISPID dwDispID, VARTYPE vtProp, void* pvProp ) const;

Parameters

dwDispID

Identifies the property to be retrieved. This value is usually supplied by ClassWizard.

vtProp

Specifies the property to be retrieved. For possible values, see the Remarks section for COleDispatchDriver::InvokeHelper.

pvProp

Address of the variable that will receive the property value. It must match the type specified by vtProp.

Remarks

Gets the object property specified by dwDispID.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::InvokeHelper, COleDispatchDriver::SetProperty


COleDispatchDriver::InvokeHelper

void InvokeHelper( DISPID dwDispID, WORD wFlags, VARTYPE vtRet, void* pvRet, const BYTE FAR* pbParamInfo, ... );
throw( COleException );
throw( COleDispatchException );

Parameters

dwDispID

Identifies the method or property to be invoked. This value is usually supplied by ClassWizard.

wFlags

Flags describing the context of the call to IDispatch::Invoke. For possible values, see the Platform SDK.

vtRet

Specifies the type of the return value. For possible values, see the Remarks section.

pvRet

Address of the variable that will receive the property value or return value. It must match the type specified by vtRet.

pbParamInfo

Pointer to a null-terminated string of bytes specifying the types of the parameters following pbParamInfo.

...

Variable list of parameters, of types specified in pbParamInfo.

Remarks

Calls the object method or property specified by dwDispID, in the context specified by wFlags. The pbParamInfo parameter specifies the types of the parameters passed to the method or property. The variable list of arguments is represented by ... in the syntax declaration.

Possible values for the vtRet argument are taken from the VARENUM enumeration. Possible values are as follows:

Symbol | Return Type
VT_EMPTY | void
VT_I2 | short
VT_I4 | long
VT_R4 | float
VT_R8 | double
VT_CY | CY
VT_DATE | DATE
VT_BSTR | BSTR
VT_DISPATCH | LPDISPATCH
VT_ERROR | SCODE
VT_BOOL | BOOL
VT_VARIANT | VARIANT
VT_UNKNOWN | LPUNKNOWN

The pbParamInfo argument is a space-separated list of VTS_ constants. One or more of these values, separated by spaces (not commas), specifies the function’s parameter list. Possible values are listed with the EVENT_CUSTOM macro.

This function converts the parameters to VARIANTARG values, then invokes the IDispatch::Invoke method. If the call to Invoke fails, this function will throw an exception. If the SCODE (status code) returned by IDispatch::Invoke is DISP_E_EXCEPTION, this function throws a COleException object; otherwise it throws a COleDispatchException.

For more information, see VARIANTARG, IDispatch, IDispatch::Invoke, and Structure of COM Error Codes in the Platform SDK.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleException, COleDispatchException


COleDispatchDriver::ReleaseDispatch

void ReleaseDispatch( );

Remarks

Releases the IDispatch connection. If auto release has been set for this connection, this function calls IDispatch::Release before releasing the interface.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::DetachDispatch, COleDispatchDriver::CreateDispatch, COleDispatchDriver::AttachDispatch, COleDispatchDriver::m_lpDispatch, COleDispatchDriver::m_bAutoRelease


COleDispatchDriver::SetProperty

void SetProperty(DISPID dwDispID, VARTYPE vtProp, ... );

Parameters

dwDispID

Identifies the property to be set. This value is usually supplied by ClassWizard.

vtProp

Specifies the type of the property to be set. For possible values, see the Remarks section for COleDispatchDriver::InvokeHelper.

...

A single parameter of the type specified by vtProp.

Remarks

Sets the OLE object property specified by dwDispID.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::InvokeHelper, COleDispatchDriver::GetProperty


COleDispatchDriver::m_bAutoRelease

Remarks

If TRUE, the COM object accessed by m_lpDispatch will be automatically released when ReleaseDispatch is called or when this COleDispatchDriver object is destroyed.

By default, m_bAutoRelease is set to TRUE in the constructor.

For more information on releasing COM objects, see Implementing Reference Counting and IUnknown::Release in the OLE 2 Programmer’s Reference, Volume 1.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::AttachDispatch, COleDispatchDriver::ReleaseDispatch, COleDispatchDriver::m_lpDispatch


COleDispatchDriver::m_lpDispatch

Remarks

The pointer to the IDispatch interface attached to this COleDispatchDriver. The m_lpDispatch data member is a public variable of type LPDISPATCH.

For more information, see IDispatch in the OLE Programmer’s Reference.

COleDispatchDriver Overview | Class Members | Hierarchy Chart

See Also COleDispatchDriver::AttachDispatch, COleDispatchDriver::ReleaseDispatch, COleDispatchDriver::CreateDispatch, COleDispatchDriver::DetachDispatch


COleDispatchException

The COleDispatchException class handles exceptions specific to the OLE IDispatch interface, which is a key part of OLE automation.

Like the other exception classes derived from the CException base class, COleDispatchException can be used with the THROW, THROW_LAST, TRY, CATCH, AND_CATCH, and END_CATCH macros.

In general, you should call AfxThrowOleDispatchException to create and throw a COleDispatchException object.

For more information on exceptions, see the articles Exceptions and Exceptions: OLE Exceptions in Visual C++ Programmer’s Guide.

#include <afxdisp.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CALCDRIV

See Also COleDispatchDriver, COleException


COleDispatchException Class Members

Data Members

m_wCode | IDispatch-specific error code.
m_strDescription | Verbal error description.
m_dwHelpContext | Help context for error.
m_strHelpFile | Help file to use with m_dwHelpContext.
m_strSource | Application that generated the exception.


COleDispatchException::m_dwHelpContext

DWORD m_dwHelpContext;

Remarks

Identifies a help context in your application’s help (.HLP) file. This member is set by the function AfxThrowOleDispatchException when an exception is thrown.

COleDispatchException Overview | Class Members | Hierarchy Chart

See Also COleDispatchException::m_strDescription, COleDispatchException::m_wCode, AfxThrowOleDispatchException


COleDispatchException::m_strDescription

CString m_strDescription;

Remarks

Contains a verbal error description, such as “Disk full.” This member is set by the function AfxThrowOleDispatchException when an exception is thrown.

COleDispatchException Overview | Class Members | Hierarchy Chart

See Also COleDispatchException::m_dwHelpContext, COleDispatchException::m_wCode, AfxThrowOleDispatchException


COleDispatchException::m_strHelpFile

CString m_strHelpFile;

Remarks

The framework fills in this string with the name of the application’s help file.

COleDispatchException Overview | Class Members | Hierarchy Chart

See Also AfxThrowOleDispatchException


COleDispatchException::m_strSource

CString m_strSource;

Remarks

The framework fills in this string with the name of the application that generated the exception.

COleDispatchException Overview | Class Members | Hierarchy Chart

See Also AfxThrowOleDispatchException


COleDispatchException::m_wCode

WORD m_wCode;

Remarks

Contains an error code specific to your application. This member is set by the function AfxThrowOleDispatchException when an exception is thrown.

COleDispatchException Overview | Class Members | Hierarchy Chart

See Also COleDispatchException::m_strDescription, COleDispatchException::m_dwHelpContext, AfxThrowOleDispatchException


COleDocObjectItem

The COleDocObjectItem class implements Active document containment. In MFC, an Active document is handled similarly to a regular, in-place editable embedding, with the following differences:

  • The COleDocument-derived class still maintains a list of the currently embedded items; however, these items may be COleDocObjectItem-derived items.

  • When an active document is active, it occupies the entire client area of the view when it is in-place active.

  • An Active document container has full control of the Help menu.

  • The Help menu contains menu items for both the Active document container and server.

Because the Active document container owns the Help menu, the container is responsible for forwarding server Help menu messages to the server. This integration is handled by COleDocObjectItem.

For more information on menu merging and Active document activation, see Overview of Active Document Containment in the Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample MFCBIND

See Also COleClientItem, CDocObjectServerItem


COleDocObjectItem Class Members

Constructors

COleDocObjectItem Constructs a COleDocObject item.

Operations

GetActiveView | Retrieves the document's active view.
OnPreparePrinting | Prepares the container application's document for printing.
OnPrint | Prints the container application's document.
GetPageCount | Retrieves the number of pages in the container application's document.
ExecCommand | Executes the command specified by the user.


COleDocObjectItem::COleDocObjectItem

COleDocObjectItem( COleDocument* pContainerDoc = NULL );

Parameters

pContainerDoc

A pointer to the COleDocument object acting as the active document container. This parameter must be NULL to enable IMPLEMENT_SERIALIZE. Normally OLE items are constructed with a non-NULL document pointer.

Remarks

Call this member function to initialize the COleDocObjectItem object.


COleDocObjectItem::ExecCommand

HRESULT ExecCommand( DWORD nCmdID, DWORD nCmdExecOpt = OLECMDEXECOPT_DONTPROMPTUSER, const GUID* pguidCmdGroup = NULL );

Return Value

Returns S_OK if successful; otherwise,returns one of the following error codes.

Value | Description
E_UNEXPECTED | Unexpected error occurred.
E_FAIL | Error occurred.
E_NOTIMPL | Indicates MFC itself should attempt to translate and dispatch the command.
OLECMDERR_E_UNKNOWNGROUP | pguidCmdGroup is non-NULL but does not specify a recognized command group.
OLECMDERR_E_NOTSUPPORTED | nCmdID is not recognized as a valid command in the group pGroup.
OLECMDERR_DISABLED | The command identified by nCmdID is disabled and cannot be executed.
OLECMDERR_NOHELP | Caller asked for help on the command identified by nCmdID but no help is available.
OLECMDERR_CANCELLED | User canceled the execution.

Parameters

nCmdID

The identifier of the command to execute. Must be in the group identified by pguidCmdGroup.

nCmdExecOpt

Specifies command-execution options. By default, set to execute the command without prompting the user. See OLECMDEXECOPT for a list of values.

pguidCmdGroup

Unique identifier of the command group. By default, NULL, which specifies the standard group. The command passed in nCmdID must belong to the group.

Remarks

Call this member function to execute the command specified by the user.

The pguidCmdGroup and the nCmdID parameters together uniquely identify the command to invoke. The nCmdExecOpt parameter specifies the exact action to take.

COleDocObjectItem Overview | Class Members | Hierarchy Chart

See Also IOleCommandTarget::Exec


COleDocObjectItem::GetActiveView

LPOLEDOCUMENTVIEW GetActiveView( ) const;

Return Value

A pointer to the IOleDocumentView interface of the currently active view. If there is no current view, it returns NULL.

Remarks

Call this member function to get a pointer to the IOleDocumentView interface of the currently active view. The reference count on the returned IOleDocumentView pointer is not incremented before it is returned by this function.


COleDocObjectItem::GetPageCount

BOOL GetPageCount( LPLONG pnFirstPage, LPLONG pcPages );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pnFirstPage

A pointer to the number of the document’s first page. Can be NULL, which indicates the caller doesn’t need this number.

pcPages

A pointer to the total number of pages in the document. Can be NULL, which indicates the caller doesn’t need this number.

Remarks

Call this member function to retrieve the number of pages in the document.

COleDocObjectItem Overview | Class Members | Hierarchy Chart

See Also IPrint::GetPageInfo


COleDocObjectItem::OnPreparePrinting

static BOOL OnPreparePrinting( CView* pCaller, CPrintInfo* pInfo, BOOL bPrintAll = TRUE );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pCaller

A pointer to a CView object that is sending the print command.

pInfo

A pointer to a CPrintInfo object that describes the job to be printed.

bPrintAll

Specifies whether the entire document is to be printed.

Remarks

This member function is called by the framework to prepare a document for printing.

COleDocObjectItem Overview | Class Members | Hierarchy Chart

See Also COleDocObjectItem::OnPrint


COleDocObjectItem::OnPrint

static void OnPrint( CView* pCaller, CPrintInfo* pInfo, BOOL bPrintAll = TRUE );

Parameters

pCaller

A pointer to a CView object that is sending the print command.

pInfo

A pointer to a CPrintInfo object that describes the job to be printed.

bPrintAll

Specifies whether the entire document is to be printed.

Remarks

This member function is called by the framework to print a document.

COleDocObjectItem Overview | Class Members | Hierarchy Chart

See Also COleDocObjectItem::OnPreparePrinting


COleDocument

COleDocument is the base class for OLE documents that support visual editing. COleDocument is derived from CDocument, which allows your OLE applications to use the document/view architecture provided by the Microsoft Foundation Class Library.

COleDocument treats a document as a collection of CDocItem objects to handle OLE items. Both container and server applications require such an architecture because their documents must be able to contain OLE items. The COleServerItem and COleClientItem classes, both derived from CDocItem, manage the interactions between applications and OLE items.

If you are writing a simple container application, derive your document class from COleDocument. If you are writing a container application that supports linking to the embedded items contained by its documents, derive your document class from COleLinkingDoc. If you are writing a server application or combination container/server, derive your document class from COleServerDoc. COleLinkingDoc and COleServerDoc are derived from COleDocument, so these classes inherit all the services available in COleDocument and CDocument.

To use COleDocument, derive a class from it and add functionality to manage the application’s non-OLE data as well as embedded or linked items. If you define CDocItem-derived classes to store the application’s native data, you can use the default implementation defined by COleDocument to store both your OLE and non-OLE data. You can also design your own data structures for storing your non-OLE data separately from the OLE items. For more information, see the article Containers: Compound Files in Visual C++ Programmer’s Guide.

CDocument supports sending your document via mail if mail support (MAPI) is present. COleDocument has updated OnFileSendMail to handle compound documents correctly. For more information, see the articles MAPI Topics and MAPI Support in MFC in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CONTAINER | MFC Sample MFCBIND


COleDocument Class Members

Construction

COleDocument Constructs a COleDocument object.

Operations

HasBlankItems | Checks for blank items in the document.
EnableCompoundFile | Causes documents to be stored using the OLE Structured Storage file format.
GetInPlaceActiveItem | Returns the OLE item that is currently in-place active.
GetStartPosition | Gets the initial position to begin iteration.
GetNextItem | Gets the next document item for iterating.
GetNextClientItem | Gets the next client item for iterating.
GetNextServerItem | Gets the next server item for iterating.
UpdateModifiedFlag | Marks the document as modified if any of the contained OLE items have been modified.
ApplyPrintDevice | Sets the print-target device for all client items in the document.
AddItem | Adds an item to the list of items maintained by the document.
RemoveItem | Removes an item from the list of items maintained by the document.

Overridables

GetPrimarySelectedItem | Returns the primary selected OLE item in the document.
OnShowViews | Called when the document becomes visible or invisible.

Mail Functions

OnFileSendMail Sends a mail message with the document attached.

Message Handlers

OnEditChangeIcon | Handles events in the Change Icon menu command.
OnEditConvert | Handles the conversion of an embedded or linked object from one type to another.
OnEditLinks | Handles events in the Links command on the Edit menu.
OnUpdateEditChangeIcon | Called by the framework to update the command UI for the Edit/Change Icon menu option.
OnUpdateEditLinksMenu | Called by the framework to update the command UI for the Edit/Links menu option.
OnUpdateObjectVerbMenu | Called by the framework to update the command UI for the Edit/ObjectName menu option and the Verb submenu accessed from Edit/ObjectName.
OnUpdatePasteLinkMenu | Called by the framework to update the command UI for the Paste Special menu option.
OnUpdatePasteMenu | Called by the framework to update the command UI for the Paste menu option.


COleDocument::AddItem

virtual void AddItem( CDocItem* pItem );

Parameters

pItem

Pointer to the document item being added.

Remarks

Call this function to add an item to the document. You do not need to call this function explicitly when it is called by the COleClientItem or COleServerItem constructor that accepts a pointer to a document.

COleDocument Overview | Class Members | Hierarchy Chart

See Also CDocItem, COleDocument::RemoveItem, COleServerItem::COleServerItem, COleClientItem::COleClientItem


COleDocument::ApplyPrintDevice

BOOL ApplyPrintDevice( const DVTARGETDEVICE FAR* ptd );

BOOL ApplyPrintDevice( const PRINTDLG* ppd );

Return Value

Nonzero if the function was successful; otherwise 0.

Parameters

ptd

Pointer to a DVTARGETDEVICE data structure, which contains information about the new print-target device. Can be NULL.

ppd

Pointer to a PRINTDLG data structure, which contains information about the new print-target device. Can be NULL.

Remarks

Call this function to change the print-target device for all embedded COleClientItem items in your application’s container document. This function updates the print-target device for all items but does not refresh the presentation cache for those items. To update the presentation cache for an item, call COleClientItem::UpdateLink.

The arguments to this function contain information that OLE uses to identify the target device. The PRINTDLG structure contains information that Windows uses to initialize the common Print dialog box. After the user closes the dialog box, Windows returns information about the user’s selections in this structure. The m_pd member of a CPrintDialog object is a PRINTDLG structure.

For more information, see the PRINTDLG structure in the Win32 SDK documentation.

For more information, see the DVTARGETDEVICE structure in the OLE 2 Programmer’s Reference, Volume 1.

COleDocument Overview | Class Members | Hierarchy Chart

See Also CPrintDialog


COleDocument::COleDocument

COleDocument( );

Remarks

Constructs a COleDocument object.


COleDocument::EnableCompoundFile

void EnableCompoundFile( BOOL bEnable = TRUE );

Parameters

bEnable

Specifies whether compound file support is enabled or disabled.

Remarks

Call this function if you want to store the document using the compound-file format. This is also called structured storage. You typically call this function from the constructor of your COleDocument-derived class. For more information about compound documents, see the article Containers: Compound Files in Visual C++ Programmer’s Guide.

If you do not call this member function, documents will be stored in a nonstructured (“flat”) file format.

After compound file support is enabled or disabled for a document, the setting should not be changed during the document’s lifetime.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleClientItem


COleDocument::GetInPlaceActiveItem

COleClientItem* GetInPlaceActiveItem( CWnd* pWnd );

Return Value

A pointer to the single, in-place active OLE item; NULL if there is no OLE item currently in the “in-place active” state.

Parameters

pWnd

Pointer to the window that displays the container document.

Remarks

Call this function to get the OLE item that is currently activated in place in the frame window containing the view identified by pWnd.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleClientItem


COleDocument::GetNextClientItem

COleClientItem* GetNextClientItem( POSITION& pos ) const;

Return Value

A pointer to the next client item in the document, or NULL if there are no more client items.

Parameters

pos

A reference to a POSITION value set by a previous call to GetNextClientItem; the initial value is returned by the GetStartPosition member function.

Remarks

Call this function repeatedly to access each of the client items in your document. After each call, the value of pos is set for the next item in the document, which might or might not be a client item.

Example

// Example for COleDocument::GetNextClientItem
// pDoc points to a COleDocument object
POSITION pos = pDoc->GetStartPosition();
COleClientItem *pItem;
while ( ( pItem = pDoc->GetNextClientItem( pos ) ) != NULL )
{
   // Use pItem
}

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleClientItem, COleDocument::GetStartPosition, COleDocument::GetNextServerItem, COleDocument::GetNextItem


COleDocument::GetNextItem

virtual CDocItem* GetNextItem( POSITION& pos ) const;

Return Value

A pointer to the document item at the specified position.

Parameters

pos

A reference to a POSITION value set by a previous call to GetNextItem; the initial value is returned by the GetStartPosition member function.

Remarks

Call this function repeatedly to access each of the items in your document. After each call, the value of pos is set to the POSITION value of the next item in the document. If the retrieved element is the last element in the document, the new value of pos is NULL.

Example

// Example for COleDocument::GetNextItem
// pDoc points to a COleDocument object
POSITION pos = pDoc->GetStartPosition();
CDocItem *pItem;
while( pos != NULL )
{
   pItem = pDoc->GetNextItem( pos );
   // Use pItem
}

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::GetStartPosition, COleDocument::GetNextClientItem, COleDocument::GetNextServerItem


COleDocument::GetNextServerItem

COleServerItem* GetNextServerItem( POSITION& pos ) const;

Return Value

A pointer to the next server item in the document, or NULL if there are no more server items.

Parameters

pos

A reference to a POSITION value set by a previous call to GetNextServerItem; the initial value is returned by the GetStartPosition member function.

Remarks

Call this function repeatedly to access each of the server items in your document. After each call, the value of pos is set for the next item in the document, which might or might not be a server item.

Example

// Example for COleDocument::GetNextServerItem
// pDoc points to a COleDocument object
POSITION pos = pDoc->GetStartPosition();
COleServerItem *pItem;
while ( ( pItem = pDoc->GetNextServerItem( pos ) ) != NULL )
{
   // Use pItem
}

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleServerItem, COleDocument::GetStartPosition, COleDocument::GetNextClientItem, COleDocument::GetNextItem


COleDocument::GetPrimarySelectedItem

virtual COleClientItem* GetPrimarySelectedItem( CView* pView );

Return Value

A pointer to the single, selected OLE item; NULL if no OLE items are selected or if more than one is selected.

Parameters

pView

Pointer to the active view object displaying the document.

Remarks

Called by the framework to retrieve the currently selected OLE item in the specified view. The default implementation searches the list of contained OLE items for a single selected item and returns a pointer to it. If there is no item selected, or if there is more than one item selected, the function returns NULL. You must override the CView::IsSelected member function in your view class for this function to work. Override this function if you have your own method of storing contained OLE items.

COleDocument Overview | Class Members | Hierarchy Chart

See Also CView::IsSelected


COleDocument::GetStartPosition

virtual POSITION GetStartPosition( ) const;

Return Value

A POSITION value that can be used to begin iterating through the document’s items; NULL if the document has no items.

Remarks

Call this function to get the position of the first item in the document. Pass the value returned to GetNextItem, GetNextClientItem, or GetNextServerItem.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::GetNextItem, COleDocument::GetNextClientItem, COleDocument::GetNextServerItem


COleDocument::HasBlankItems

BOOL HasBlankItems( ) const;

Return Value

Nonzero if the document contains any blank items; otherwise 0.

Remarks

Call this function to determine whether the document contains any blank items. A blank item is one whose rectangle is empty.

COleDocument Overview | Class Members | Hierarchy Chart

See Also CDocItem::IsBlank


COleDocument::OnEditChangeIcon

afx_msg void OnEditChangeIcon( );

Remarks

Displays the OLE Change Icon dialog box and changes the icon representing the currently selected OLE item to the icon the user selects in the dialog box. OnEditChangeIcon creates and launches a COleChangeIconDialog Change Icon dialog box.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::OnUpdateEditChangeIcon, COleChangeIconDialog


COleDocument::OnEditConvert

afx_msg void OnEditConvert( );

Remarks

Displays the OLE Convert dialog box and converts or activates the currently selected OLE item according to user selections in the dialog box. OnEditConvert creates and launches a COleConvertDialog Convert dialog box.

An example of conversion is converting a Microsoft Word document into a WordPad document.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::OnUpdateObjectVerbMenu, COleConvertDialog


COleDocument::OnEditLinks

afx_msg void OnEditLinks( );

Remarks

Displays the OLE Edit/Links dialog box. OnEditLinks creates and launches a COleLinksDialog Links dialog box that allows the user to change the linked objects.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::OnUpdateEditLinksMenu, COleLinksDialog


COleDocument::OnFileSendMail

afx_msg void OnFileSendMail( );

Remarks

Sends a message via the resident mail host (if any) with the document as an attachment. OnFileSendMail calls OnSaveDocument to serialize (save) untitled and modified documents to a temporary file, which is then sent via electronic mail. If the document has not been modified, a temporary file is not needed; the original is sent. OnFileSendMail loads MAPI32.DLL if it has not already been loaded.

Unlike the implementation of OnFileSendMail for CDocument, this function handles compound files correctly.

For more information, see the MAPI Topics and MAPI Support in MFC articles in Visual C++ Programmer’s Guide.

COleDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::OnFileSendMail, CDocument::OnUpdateFileSendMail, CDocument::OnSaveDocument


COleDocument::OnShowViews

virtual void OnShowViews( BOOL bVisible );

Parameters

bVisible

Indicates whether the document has become visible or invisible.

Remarks

The framework calls this function after the document’s visibility state changes.

The default version of this function does nothing. Override it if your application must perform any special processing when the document’s visibility changes.


COleDocument::OnUpdateEditChangeIcon

afx_msg void OnUpdateEditChangeIcon( CCmdUI* pCmdUI );

Parameters

pCmdUI

A pointer to a CCmdUI structure that represents the menu that generated the update command. The update handler calls the Enable member function of the CCmdUI structure through pCmdUI to update the user interface.

Remarks

Called by the framework to update the Change Icon command on the Edit menu. OnUpdateEditChangeIcon updates the command's user interface depending on whether or not a valid icon exists in the document. Override this function to change the behavior.

COleDocument Overview Class Members Hierarchy Chart

See Also COleDocument::OnEditChangeIcon, CCmdUI


COleDocument::OnUpdateEditLinksMenu

afx_msg void OnUpdateEditLinksMenu( CCmdUI* pCmdUI );

Parameters

pCmdUI

A pointer to a CCmdUI structure that represents the menu that generated the update command. The update handler calls the Enable member function of the CCmdUI structure through pCmdUI to update the user interface.

Remarks

Called by the framework to update the Links command on the Edit menu. Starting with the first OLE item in the document, OnUpdateEditLinksMenu accesses each item, tests whether the item is a link, and, if it is a link, enables the Links command. Override this function to change the behavior.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::OnEditLinks, COleDocument::GetStartPosition, COleDocument::GetNextClientItem, CCmdUI


COleDocument::OnUpdateObjectVerbMenu

afx_msg void OnUpdateObjectVerbMenu( CCmdUI* pCmdUI );

Parameters

pCmdUI

A pointer to a CCmdUI structure that represents the menu that generated the update command. The update handler calls the Enable member function of the CCmdUI structure through pCmdUI to update the user interface.

Remarks

Called by the framework to update the ObjectName command on the Edit menu and the Verb submenu accessed from the ObjectName command, where ObjectName is the name of the OLE object embedded in the document. OnUpdateObjectVerbMenu updates the ObjectName command's user interface depending on whether or not a valid object exists in the document. If an object exists, the ObjectName command on the Edit menu is enabled. When this menu command is selected, the Verb submenu is displayed. The Verb submenu contains all the verb commands available for the object, such as Edit, Properties, and so on. Override this function to change the behavior.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::OnEditConvert, CCmdUI


COleDocument::OnUpdatePasteLinkMenu

afx_msg void OnUpdatePasteLinkMenu( CCmdUI* pCmdUI );

Parameters

pCmdUI

A pointer to a CCmdUI structure that represents the menu that generated the update command. The update handler calls the Enable member function of the CCmdUI structure through pCmdUI to update the user interface.

Remarks

Called by the framework to determine whether a linked OLE item can be pasted from the Clipboard. The Paste Special menu command is enabled or disabled depending on whether the item can be pasted into the document or not.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::OnUpdatePasteMenu, CCmdUI


COleDocument::OnUpdatePasteMenu

afx_msg void OnUpdatePasteMenu( CCmdUI* pCmdUI );

Parameters

pCmdUI

A pointer to a CCmdUI structure that represents the menu that generated the update command. The update handler calls the Enable member function of the CCmdUI structure through pCmdUI to update the user interface.

Remarks

Called by the framework to determine whether an embedded OLE item can be pasted from the Clipboard. The Paste menu command and button are enabled or disabled depending on whether the item can be pasted into the document or not.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleDocument::OnUpdatePasteLinkMenu, CCmdUI


COleDocument::RemoveItem

virtual void RemoveItem( CDocItem* pItem );

Parameters

pItem

Pointer to the document item to be removed.

Remarks

Call this function to remove an item from the document. You typically do not need to call this function explicitly; it is called by the destructors for COleClientItem and COleServerItem.

COleDocument Overview | Class Members | Hierarchy Chart

See Also COleServerItem, COleClientItem, COleDocument::AddItem, CDocItem


COleDocument::UpdateModifiedFlag

void UpdateModifiedFlag( );

Remarks

Call this function to mark the document as modified if any of the contained OLE items have been modified. This allows the framework to prompt the user to save the document before closing, even if the native data in the document has not been modified.

COleDocument Overview | Class Members | Hierarchy Chart

See Also CDocument::SetModifiedFlag, COleClientItem::IsModified


COleDropSource

A COleDropSource object allows data to be dragged to a drop target. The COleDropTarget class handles the receiving portion of the drag-and-drop operation. The COleDropSource object is responsible for determining when a drag operation begins, providing feedback during the drag operation, and determining when the drag operation ends.

To use a COleDropSource object, just call the constructor. This simplifies the process of determining what events, such as a mouse click, begin a drag operation using COleDataSource::DoDragDrop, COleClientItem::DoDragDrop, or COleServerItem::DoDragDrop function. These functions will create a COleDropSource object for you. You might want to modify the default behavior of the COleDropSource overridable functions. These member functions will be called at the appropriate times by the framework.

For more information on drag-and-drop operations using OLE, see the article Drag and Drop (OLE) in Visual C++ Programmer’s Guide.

For more information, see IDropSource in the OLE 2 Programmer's Reference, Volume 1.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HIERSVR | MFC Sample OCLIENT


COleDropSource Class Members

Construction

COleDropSource Constructs a COleDropSource object.

Overridables

GiveFeedback | Changes the cursor during a drag-and-drop operation.
OnBeginDrag | Handles mouse capture during a drag-and-drop operation.
QueryContinueDrag | Checks to see whether dragging should continue.


COleDropSource::COleDropSource

COleDropSource( );

Remarks

Constructs a COleDropSource object.

COleDropSource Overview | Class Members | Hierarchy Chart

See Also COleDropTarget


COleDropSource::GiveFeedback

virtual SCODE GiveFeedback( DROPEFFECT dropEffect );

Return Value

Returns DRAGDROP_S_USEDEFAULTCURSORS if dragging is in progress, NOERROR if it is not.

Parameters

dropEffect

The effect you would like to display to the user, usually indicating what would happen if a drop occurred at this point with the selected data. Typically, this is the value returned by the most recent call to CView::OnDragEnter or CView::OnDragOver. It can be one or more of the following:

  • DROPEFFECT_NONE A drop would not be allowed.

  • DROPEFFECT_COPY A copy operation would be performed.

  • DROPEFFECT_MOVE A move operation would be performed.

  • DROPEFFECT_LINK A link from the dropped data to the original data would be established.

  • DROPEFFECT_SCROLL A drag scroll operation is about to occur or is occurring in the target.

Remarks

Called by the framework after calling COleDropTarget::OnDragOver or COleDropTarget::DragEnter. Override this function to provide feedback to the user about what would happen if a drop occurred at this point. The default implementation uses the OLE default cursors. For more information on drag-and-drop operations using OLE, see the article Drag and Drop (OLE) in Visual C++ Programmer’s Guide.

For more information, see IDropSource::GiveFeedback, IDropTarget::DragOver, and IDropTarget::DragEnter in the OLE 2 Programmer's Reference, Volume 1.

COleDropSource Overview | Class Members | Hierarchy Chart

See Also CView::OnDragEnter, CView::OnDragOver


COleDropSource::OnBeginDrag

virtual BOOL OnBeginDrag( CWnd* pWnd );

Return Value

Nonzero if dragging is allowed, otherwise 0.

Parameters

pWnd

Points to the window that contains the selected data.

Remarks

Called by the framework when an event occurs that could begin a drag operation, such as pressing the left mouse button. Override this function if you want to modify the way the dragging process is started. The default implementation captures the mouse and stays in drag mode until the user clicks the left or right mouse button or hits ESC, at which time it releases the mouse.

COleDropSource Overview | Class Members | Hierarchy Chart

See Also COleDropSource::GiveFeedback


COleDropSource::QueryContinueDrag

virtual SCODE QueryContinueDrag( BOOL bEscapePressed, DWORD dwKeyState );

Return Value

DRAGDROP_S_CANCEL if the ESC key or right button is pressed, or left button is raised before dragging starts. DRAGDROP_S_DROP if a drop operation should occur. Otherwise S_OK.

Parameters

bEscapePressed

States whether the ESC key has been pressed since the last call to COleDropSource::QueryContinueDrag.

dwKeyState

Contains the state of the modifier keys on the keyboard. This is a combination of any number of the following: MK_CONTROL, MK_SHIFT, MK_ALT, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.

Remarks

After dragging has begun, this function is called repeatedly by the framework until the drag operation is either canceled or completed. Override this function if you want to change the point at which dragging is canceled or a drop occurs.

The default implementation initiates the drop or cancels the drag as follows. It cancels a drag operation when the ESC key or the right mouse button is pressed. It initiates a drop operation when the left mouse button is raised after dragging has started. Otherwise, it returns S_OK and performs no further operations.

Because this function is called frequently, it should be optimized as much as possible.

COleDropSource Overview | Class Members | Hierarchy Chart

See Also COleDropSource::OnBeginDrag, COleDropTarget::OnDrop


COleDropTarget

A COleDropTarget object provides the communication mechanism between a window and the OLE libraries. Creating an object of this class allows a window to accept data through the OLE drag-and-drop mechanism.

To get a window to accept drop commands, you should first create an object of the COleDropTarget class, and then call the Register function with a pointer to the desired CWnd object as the only parameter.

For more information on drag-and-drop operations using OLE, see the article Drag and Drop (OLE) in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HIERSVR | MFC Sample OCLIENT

See Also COleDropSource


COleDropTarget Class Members

Construction

COleDropTarget Constructs a COleDropTarget object.

Operations

Register | Registers the window as a valid drop target.
Revoke | Causes the window to cease being a valid drop target.

Overridables

OnDragEnter | Called when the cursor first enters the window.
OnDragLeave | Called when the cursor is dragged out of the window.
OnDragOver | Called repeatedly when the cursor is dragged over the window.
OnDragScroll | Called to determine whether the cursor is dragged into the scroll region of the window.
OnDrop | Called when data is dropped into the window, default handler.
OnDropEx | Called when data is dropped into the window, initial handler.


COleDropTarget::COleDropTarget

COleDropTarget( );

Remarks

Constructs an object of class COleDropTarget. Call Register to associate this object with a window.

COleDropTarget Overview | Class Members | Hierarchy Chart

See Also COleDropSource, COleDropTarget::Register, COleDropTarget::Revoke


COleDropTarget::OnDragEnter

virtual DROPEFFECT OnDragEnter( CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point );

Return Value

The effect that would result if a drop were attempted at the location specified by point. It can be one or more of the following:

  • DROPEFFECT_NONE A drop would not be allowed.

  • DROPEFFECT_COPY A copy operation would be performed.

  • DROPEFFECT_MOVE A move operation would be performed.

  • DROPEFFECT_LINK A link from the dropped data to the original data would be established.

  • DROPEFFECT_SCROLL A drag scroll operation is about to occur or is occurring in the target.

Parameters

pWnd

Points to the window the cursor is entering.

pDataObject

Points to the data object containing the data that can be dropped.

dwKeyState

Contains the state of the modifier keys. This is a combination of any number of the following: MK_CONTROL, MK_SHIFT, MK_ALT, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.

point

Contains the current location of the cursor in client coordinates.

Remarks

Called by the framework when the cursor is first dragged into the window. Override this function to allow drop operations to occur in the window. The default implementation calls CView::OnDragEnter, which simply returns DROPEFFECT_NONE by default.

For more information, see IDropTarget::DragEnter in the OLE 2 Programmer’s Reference, Volume 1.

COleDropTarget Overview | Class Members | Hierarchy Chart

See Also COleDropTarget::OnDragOver, COleDropTarget::OnDragLeave, COleDropTarget::OnDrop, COleDropTarget::OnDropEx, CView::OnDragEnter


COleDropTarget::OnDragLeave

virtual void OnDragLeave( CWnd* pWnd );

Parameters

pWnd

Points to the window the cursor is leaving.

Remarks

Called by the framework when the cursor leaves the window while a dragging operation is in effect. Override this function if you want special behavior when the drag operation leaves the specified window. The default implementation of this function calls CView::OnDragLeave.

For more information, see IDropTarget::DragLeave in the OLE 2 Programmer’s Reference, Volume 1.

COleDropTarget Overview | Class Members | Hierarchy Chart

See Also COleDropTarget::OnDragEnter, COleDropTarget::OnDragOver, COleDropTarget::OnDrop, COleDropTarget::OnDropEx


COleDropTarget::OnDragOver

virtual DROPEFFECT OnDragOver( CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point );

Return Value

The effect that would result if a drop were attempted at the location specified by point. It can be one or more of the following:

  • DROPEFFECT_NONE A drop would not be allowed.

  • DROPEFFECT_COPY A copy operation would be performed.

  • DROPEFFECT_MOVE A move operation would be performed.

  • DROPEFFECT_LINK A link from the dropped data to the original data would be established.

  • DROPEFFECT_SCROLL Indicates that a drag scroll operation is about to occur or is occurring in the target.

Parameters

pWnd

Points to the window that the cursor is over.

pDataObject

Points to the data object that contains the data to be dropped.

dwKeyState

Contains the state of the modifier keys. This is a combination of any number of the following: MK_CONTROL, MK_SHIFT, MK_ALT, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.

point

Contains the current location of the cursor in client coordinates.

Remarks

Called by the framework when the cursor is dragged over the window. This function should be overridden to allow drop operations to occur in the window. The default implementation of this function calls CView::OnDragOver, which returns DROPEFFECT_NONE by default. Because this function is called frequently during a drag-and-drop operation, it should be optimized as much as possible.

For more information, see IDropTarget::DragOver in the OLE 2 Programmer’s Reference, Volume 1.

COleDropTarget Overview | Class Members | Hierarchy Chart

See Also COleDropTarget::OnDragEnter, COleDropTarget::OnDragLeave, COleDropTarget::OnDrop, COleDropTarget::OnDropEx


COleDropTarget::OnDragScroll

virtual DROPEFFECT OnDragScroll( CWnd* pWnd, DWORD dwKeyState, CPoint point );

Return Value

The effect that would result if a drop were attempted at the location specified by point. It can be one or more of the following:

  • DROPEFFECT_NONE A drop would not be allowed.

  • DROPEFFECT_COPY A copy operation would be performed.

  • DROPEFFECT_MOVE A move operation would be performed.

  • DROPEFFECT_LINK A link from the dropped data to the original data would be established.

  • DROPEFFECT_SCROLL Indicates that a drag scroll operation is about to occur or is occurring in the target.

Parameters

pWnd

Points to the window the cursor is currently over.

dwKeyState

Contains the state of the modifier keys. This is a combination of any number of the following: MK_CONTROL, MK_SHIFT, MK_ALT, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.

point

Contains the location of the cursor, in pixels, relative to the screen.

Remarks

Called by the framework before calling OnDragEnter or OnDragOver to determine whether point is in the scrolling region. Override this function when you want to provide special behavior for this event. The default implementation of this function calls CView::OnDragScroll, which returns DROPEFFECT_NONE and scrolls the window when the cursor is dragged into the default scroll region inside the border of the window.


COleDropTarget::OnDrop

virtual BOOL OnDrop( CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point );

Return Value

Nonzero if the drop is successful; otherwise 0.

Parameters

pWnd

Points to the window the cursor is currently over.

pDataObject

Points to the data object that contains the data to be dropped.

dropEffect

The effect that the user chose for the drop operation. It can be one or more of the following:

  • DROPEFFECT_COPY A copy operation would be performed.

  • DROPEFFECT_MOVE A move operation would be performed.

  • DROPEFFECT_LINK A link from the dropped data to the original data would be established.

point

Contains the location of the cursor, in pixels, relative to the screen.

Remarks

Called by the framework when a drop operation is to occur. The framework first calls OnDropEx. If the OnDropEx function does not handle the drop, the framework then calls this member function, OnDrop. Typically, the application overrides OnDropEx in the view class to handle right mouse-button drag and drop. Typically, the view class OnDrop is used to handle simple drag and drop.

The default implementation of COleDropTarget::OnDrop calls CView::OnDrop, which simply returns FALSE by default.

For more information, see IDropTarget::Drop in the OLE 2 Programmer’s Reference, Volume 1.

COleDropTarget Overview | Class Members | Hierarchy Chart

See Also COleDropTarget::OnDragOver, COleDropTarget::OnDragEnter, COleDropTarget::OnDropEx


COleDropTarget::OnDropEx

virtual DROPEFFECT OnDropEx( CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropDefault, DROPEFFECT dropList, CPoint point );

Return Value

The drop effect that resulted from the drop attempt at the location specified by point. Drop effects are discussed in the Remarks section.

Parameters

pWnd

Points to the window the cursor is currently over.

pDataObject

Points to the data object that contains the data to be dropped.

dropDefault

The effect that the user chose for the default drop operation based on the current key state. It can be DROPEFFECT_NONE. Drop effects are discussed in the Remarks section.

dropList

A list of the drop effects that the drop source supports. Drop effect values can be combined using the bitwise OR (|) operation. Drop effects are discussed in the Remarks section.

point

Contains the location of the cursor, in pixels, relative to the screen.

Remarks

Called by the framework when a drop operation is to occur. The framework first calls this function. If it does not handle the drop, the framework then calls OnDrop. Typically, you will override OnDropEx in the view class to support right mouse-button drag and drop. Typically, the view class OnDrop is used to handle the case of support for simple drag and drop.

The default implementation of COleDropTarget::OnDropEx calls CView::OnDropEx. By default, CView::OnDropEx simply returns a dummy value to indicate the OnDrop member function should be called.

Drop effects describe the action associated with a drop operation. See the following list of drop effects:

  • DROPEFFECT_NONE A drop would not be allowed.

  • DROPEFFECT_COPY A copy operation would be performed.

  • DROPEFFECT_MOVE A move operation would be performed.

  • DROPEFFECT_LINK A link from the dropped data to the original data would be established.

  • DROPEFFECT_SCROLL Indicates that a drag scroll operation is about to occur or is occurring in the target.

For more information, see IDropTarget::Drop in the OLE 2 Programmer’s Reference, Volume 1.

COleDropTarget Overview | Class Members | Hierarchy Chart

See Also COleDropTarget::OnDragOver, COleDropTarget::OnDragEnter


COleDropTarget::Register

BOOL Register( CWnd* pWnd );

Return Value

Nonzero if registration is successful; otherwise 0.

Parameters

pWnd

Points to the window that is to be registered as a drop target.

Remarks

Call this function to register your window with the OLE DLLs as a valid drop target. This function must be called for drop operations to be accepted.

For more information, see RegisterDragDrop in the OLE 2 Programmer’s Reference, Volume 1.

COleDropTarget Overview | Class Members | Hierarchy Chart

See Also COleDropTarget::Revoke, COleDropTarget::COleDropTarget


COleDropTarget::Revoke

virtual void Revoke( );

Remarks

Call this function before destroying any window that has been registered as a drop target through a call to Register to remove it from the list of drop targets. This function is called automatically from the OnDestroy handler for the window that was registered, so it is usually not necessary to call this function explicitly.

For more information, see RevokeDragDrop in the OLE 2 Programmer’s Reference, Volume 1.


COleException

A COleException object represents an exception condition related to an OLE operation. The COleException class includes a public data member that holds the status code indicating the reason for the exception.

In general, you should not create a COleException object directly; instead, you should call AfxThrowOleException.

For more information on exceptions, see the articles Exceptions and Exceptions: OLE Exceptions in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CALCDRIV


COleException Class Members

Data Members

m_sc Contains the status code that indicates the reason for the exception.

Operations

Process Translates a caught exception into an OLE return code.


COleException::Process

static SCODE PASCAL Process( const CException* pAnyException );

Return Value

An OLE status code.

Parameters

pAnyException

Pointer to a caught exception.

Remarks

Call the Process member function to translate a caught exception into an OLE status code.

Note This function is static.

For more information on SCODE, see Structure of COM Error Codes in the Platform SDK.

COleException Overview | Class Members | Hierarchy Chart

See Also CException


COleException::m_sc

SCODE m_sc;

Remarks

This data member holds the OLE status code that indicates the reason for the exception. This variable’s value is set by AfxThrowOleException.

For more information on SCODE, see Structure of COM Error Codes in the Platform SDK.

COleException Overview | Class Members | Hierarchy Chart

See Also AfxThrowOleException


COleInsertDialog

The COleInsertDialog class is used for the OLE Insert Object dialog box. Create an object of class COleInsertDialog when you want to call this dialog box. After a COleInsertDialog object has been constructed, you can use the m_io structure to initialize the values or states of controls in the dialog box. The m_io structure is of type OLEUIINSERTOBJECT. For more information about using this dialog class, see the DoModal member function.

Note AppWizard-generated container code uses this class.

For more information, see the OLEUIINSERTOBJECT structure in the OLE 2.01 User Interface Library.

For more information regarding OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample OCLIENT

See Also COleDialog


COleInsertDialog Class Members

Data Members

m_io A structure of type OLEUIINSERTOBJECT that controls the behavior of the dialog box.

Construction

COleInsertDialog Constructs a COleInsertDialog object.

Operations and Attributes

DoModal | Displays the OLE Insert Object dialog box.
CreateItem | Creates the item selected in the dialog box.
GetSelectionType | Gets the type of object selected.
GetClassID | Gets the CLSID associated with the chosen item.
GetDrawAspect | Tells whether to draw the item as an icon.
GetIconicMetafile | Gets a handle to the metafile associated with the iconic form of this item.
GetPathName | Gets the full path to the file chosen in the dialog box.


COleInsertDialog::COleInsertDialog

COleInsertDialog ( DWORD dwFlags = IOF_SELECTCREATENEW, CWnd* pParentWnd = NULL );

Parameters

dwFlags

Creation flag that contains any number of the following values to be combined using the bitwise-OR operator:

  • IOF_SHOWHELP Specifies that the Help button will be displayed when the dialog box is called.

  • IOF_SELECTCREATENEW Specifies that the Create New radio button will be selected initially when the dialog box is called. This is the default and cannot be used with IOF_SELECTCREATEFROMFILE.

  • IOF_SELECTCREATEFROMFILE Specifies that the Create From File radio button will be selected initially when the dialog box is called. Cannot be used with IOF_SELECTCREATENEW.

  • IOF_CHECKLINK Specifies that the Link check box will be checked initially when the dialog box is called.

  • IOF_DISABLELINK Specifies that the Link check box will be disabled when the dialog box is called.

  • IOF_CHECKDISPLAYASICON Specifies that the Display As Icon check box will be checked initially, the current icon will be displayed, and the Change Icon button will be enabled when the dialog box is called.

  • IOF_VERIFYSERVERSEXIST Specifies that the dialog box should validate the classes it adds to the list box by ensuring that the servers specified in the registration database exist before the dialog box is displayed. Setting this flag can significantly impair performance.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the parent window of the dialog object is set to the main application window.

Remarks

This function constructs only a COleInsertDialog object. To display the dialog box, call the DoModal function.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::DoModal


COleInsertDialog::CreateItem

BOOL CreateItem( COleClientItem* pItem );

Return Value

Nonzero if item was created; otherwise 0.

Parameters

pItem

Points to the item to be created.

Remarks

Call this function to create an object of type COleClientItem only if DoModal returns IDOK. You must allocate the COleClientItem object before you can call this function.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleClientItem::CreateLinkFromFile, COleClientItem::CreateFromFile, COleClientItem::CreateNewItem, COleClientItem::SetDrawAspect, COleInsertDialog::GetSelectionType, COleInsertDialog::DoModal


COleInsertDialog::DoModal

virtual int DoModal( );

int DoModal( DWORD dwFlags );

Return Value

Completion status for the dialog box. One of the following values:

  • IDOK if the dialog box was successfully displayed.

  • IDCANCEL if the user canceled the dialog box.

  • IDABORT if an error occurred. If IDABORT is returned, call the COleDialog::GetLastError member function to get more information about the type of error that occurred. For a listing of possible errors, see the OleUIInsertObject function in the OLE 2.01 User Interface Library.

Parameters

dwFlags

One of the following values:

COleInsertDialog::DocObjectOnly will insert only DocObjects.

COleInsertDialog::ControlsOnly will insert only ActiveX controls.

If zero, DoModal will insert neither a DocObject or an ActiveX control; it results in the same implementation as the first prototype listed above.

Remarks

Call this function to display the OLE Insert Object dialog box.

If you want to initialize the various dialog box controls by setting members of the m_io structure, you should do this before calling DoModal, but after the dialog object is constructed.

If DoModal returns IDOK, you can call other member functions to retrieve the settings or information input into the dialog box by the user.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleDialog::GetLastError, CDialog::DoModal, COleInsertDialog::GetSelectionType, COleInsertDialog::GetClassID, COleInsertDialog::GetDrawAspect, COleInsertDialog::GetIconicMetafile, COleInsertDialog::GetPathName, COleInsertDialog::m_io


COleInsertDialog::GetClassID

const CLSID& GetClassID( ) const;

Return Value

Returns the CLSID associated with the selected item.

Remarks

Call this function to get the CLSID associated with the selected item only if DoModal returns IDOK and the selection type is COleInsertDialog::createNewItem.

For more information, see CLSID Key in the OLE 2 Programmer’s Reference, Volume 1.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::DoModal, COleInsertDialog::GetSelectionType


COleInsertDialog::GetDrawAspect

DVASPECT GetDrawAspect( ) const;

Return Value

The method needed to render the object.

  • DVASPECT_CONTENT Returned if the Display As Icon check box was not checked.

  • DVASPECT_ICON Returned if the Display As Icon check box was checked.

Remarks

Call this function to determine if the user chose to display the selected item as an icon. Call this function only if DoModal returns IDOK.

For more information on drawing aspect, see FORMATETC data structure in the OLE 2 Programmer’s Reference, Volume 1.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::DoModal, COleInsertDialog::COleInsertDialog


COleInsertDialog::GetIconicMetafile

HGLOBAL GetIconicMetafile( ) const;

Return Value

The handle to the metafile containing the iconic aspect of the selected item, if the Display As Icon check box was checked when the dialog was dismissed by choosing OK; otherwise NULL.

Remarks

Call this function to get a handle to the metafile that contains the iconic aspect of the selected item.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::DoModal, COleInsertDialog::GetDrawAspect


COleInsertDialog::GetPathName

CString GetPathName( ) const;

Return Value

The full path to the file selected in the dialog box. If the selection type is createNewItem, this function returns a meaningless CString in release mode or causes an assertion in debug mode.

Remarks

Call this function to get the full path of the selected file only if DoModal returns IDOK and the selection type is not COleInsertDialog::createNewItem.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::GetSelectionType, COleInsertDialog::DoModal


COleInsertDialog::GetSelectionType

UINT GetSelectionType( ) const;

Return Value

Type of selection made.

Remarks

Call this function to get the selection type chosen when the Insert Object dialog box was dismissed by choosing OK.

The return type values are specified by the Selection enumeration type declared in the COleInsertDialog class.

enum Selection
{
   createNewItem,
   insertFromFile,
   linkToFile
};

Brief descriptions of these values follow:

  • COleInsertDialog::createNewItem The Create New radio button was selected.

  • COleInsertDialog::insertFromFile The Create From File radio button was selected and the Link check box was not checked.

  • COleInsertDialog::linkToFile The Create From File radio button was selected and the Link check box was checked.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::DoModal, COleInsertDialog::COleInsertDialog


COleInsertDialog::m_io

Remarks

Structure of type OLEUIINSERTOBJECT used to control the behavior of the Insert Object dialog box. Members of this structure can be modified either directly or through member functions.

For more information, see the OLEUIINSERTOBJECT structure in the OLE 2.01 User Interface Library.

COleInsertDialog Overview | Class Members | Hierarchy Chart

See Also COleInsertDialog::COleInsertDialog, COleInsertDialog::DoModal


COleIPFrameWnd

Use the COleIPFrameWnd class as the base for your application’s in-place editing window. This class creates and positions control bars within the container application’s document window. It also handles notifications generated by an embedded COleResizeBar object when the user resizes the in-place editing window.

For more information on using COleIPFrameWnd, see the article Activation in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HIERSVR | MFC Sample BINDSCRB

See Also CFrameWnd


COleIPFrameWnd Class Members

Construction

COleIPFrameWnd Constructs a COleIPFrameWnd object.

Overridables

OnCreateControlBars | Called by the framework when an item is activated for in-place editing.
RepositionFrame | Called by the framework to reposition the in-place editing window.


COleIPFrameWnd::COleIPFrameWnd

COleIPFrameWnd( );

Remarks

Constructs a COleIPFrameWnd object and initializes its in-place state information, which is stored in a structure of type OLEINPLACEFRAMEINFO.

For more information, see OLEINPLACEFRAMEINFO in the OLE 2 Programmer’s Reference, Volume 1.

COleIPFrameWnd Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::ActivateInPlace


COleIPFrameWnd::OnCreateControlBars

virtual BOOL OnCreateControlBars(CWnd* pWndFrame, CWnd* pWndDoc );

Return Value

Nonzero on success; otherwise, 0.

Parameters

pWndFrame

Pointer to the container application’s frame window.

pWndDoc

Pointer to the container’s document-level window. Can be NULL if the container is an SDI application.

Remarks

The framework calls the OnCreateControlBars function when an item is activated for in-place editing.

The default implementation does nothing. Override this function to perform any special processing required when control bars are created.

COleIPFrameWnd Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::ActivateInPlace


COleIPFrameWnd::RepositionFrame

virtual void RepositionFrame( LPCRECT lpPosRect, LPCRECT lpClipRect );

Parameters

lpPosRect

Pointer to a RECT structure or a CRect object containing the in-place frame window’s current position coordinates, in pixels, relative to the client area.

lpClipRect

Pointer to a RECT structure or a CRect object containing the in-place frame window’s current clipping-rectangle coordinates, in pixels, relative to the client area.

Remarks

The framework calls the RepositionFrame member function to lay out control bars and reposition the in-place editing window so all of it is visible.

Layout of control bars in the container window differs from that performed by a non-OLE frame window. The non-OLE frame window calculates the positions of control bars and other objects from a given frame-window size, as in a call to CFrameWnd::RecalcLayout. The client area is what remains after space for control bars and other objects is subtracted. A COleIPFrameWnd window, on the other hand, positions toolbars in accordance with a given client area. In other words, CFrameWnd::RecalcLayout works “from the outside in,” whereas COleIPFrameWnd::RepositionFrame works “from the inside out.”

COleIPFrameWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::RecalcLayout


COleLinkingDoc

The COleLinkingDoc class is the base class for OLE container documents that support linking to the embedded items they contain. A container application that supports linking to embedded items is called a “link container.” The OCLIENT sample application is an example of a link container.

When a linked item’s source is an embedded item in another document, that containing document must be loaded in order for the embedded item to be edited. For this reason, a link container must be able to be launched by another container application when the user wants to edit the source of a linked item. Your application must also use the COleTemplateServer class so that it can create documents when launched programmatically.

To make your container a link container, derive your document class from COleLinkingDoc instead of COleDocument. As with any other OLE container, you must design your class for storing the application’s native data as well as embedded or linked items. Also, you must design data structures for storing your native data. If you define a CDocItem-derived class for your application’s native data, you can use the interface defined by COleDocument to store your native data as well as your OLE data.

To allow your application to be launched programmatically by another container, declare a COleTemplateServer object as a member of your application’s CWinApp-derived class:

class COleClientApp : public CWinApp
{
// ...
protected:
   COleTemplateServer m_server;
// ...
};

In the InitInstance member function of your CWinApp-derived class, create a document template and specify your COleLinkingDoc-derived class as the document class:

// CMainDoc is derived from COleLinkingDoc
CMultiDocTemplate* pDocTemplate = new CMultiDocTemplate(IDR_OCLIENTTYPE,
   RUNTIME_CLASS(CMainDoc),
   RUNTIME_CLASS(CSplitFrame),
   RUNTIME_CLASS(CMainView));
pDocTemplate->SetContainerInfo(
   IDR_OCLIENTTYPE_CNTR_IP);
AddDocTemplate(pDocTemplate);

Connect your COleTemplateServer object to your document templates by calling the object’s ConnectTemplate member function, and register all class objects with the OLE system by calling COleTemplateServer::RegisterAll:

m_server.ConnectTemplate(clsid, pDocTemplate, FALSE);
COleTemplateServer::RegisterAll();

For a sample CWinApp-derived class definition and InitInstance function, see OCLIENT.H and OCLIENT.CPP in the MFC sample OCLIENT.

For more information on using COleLinkingDoc, see the articles Containers: Implementing a Container and Containers: Advanced Features in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample OCLIENT

See Also CDocTemplate


COleLinkingDoc Class Members

Construction

COleLinkingDoc Constructs a COleLinkingDoc object.

Operations

Register | Registers the document with the OLE system DLLs.
Revoke | Revokes the document’s registration.

Overridables

OnFindEmbeddedItem | Finds the specified embedded item.
OnGetLinkedItem | Finds the specified linked item.


COleLinkingDoc::COleLinkingDoc

COleLinkingDoc( );

Remarks

Constructs a COleLinkingDoc object without beginning communications with the OLE system DLLs. You must call the Register member function to inform OLE that the document is open.

COleLinkingDoc Overview | Class Members | Hierarchy Chart

See Also COleLinkingDoc::Register


COleLinkingDoc::OnFindEmbeddedItem

virtual COleClientItem* OnFindEmbeddedItem( LPCTSTR lpszItemName );

Return Value

A pointer to the specified item; NULL if the item is not found.

Parameters

lpszItemName

Pointer to the name of the embedded OLE item requested.

Remarks

Called by the framework to determine whether the document contains an embedded OLE item with the specified name. The default implementation searches the list of embedded items for an item with the specified name (the name comparison is case sensitive). Override this function if you have your own method of storing or naming embedded OLE items.

COleLinkingDoc Overview | Class Members | Hierarchy Chart

See Also COleClientItem, COleLinkingDoc::OnGetLinkedItem


COleLinkingDoc::OnGetLinkedItem

virtual COleServerItem* OnGetLinkedItem( LPCTSTR lpszItemName );

Return Value

A pointer to the specified item; NULL if the item is not found.

Parameters

lpszItemName

Pointer to the name of the linked OLE item requested.

Remarks

Called by the framework to check whether the document contains a linked server item with the specified name. The default COleLinkingDoc implementation always returns NULL. This function is overriden in the derived class COleServerDoc to search the list of OLE server items for a linked item with the specified name (the name comparison is case sensitive). Override this function if you have implemented your own method of storing or retrieving linked server items.

COleLinkingDoc Overview | Class Members | Hierarchy Chart

See Also COleServerItem::GetItemName, COleServerItem::SetItemName, COleLinkingDoc::OnFindEmbeddedItem


COleLinkingDoc::Register

BOOL Register( COleObjectFactory* pFactory, LPCTSTR lpszPathName );

Return Value

Nonzero if the document is successfully registered; otherwise 0.

Parameters

pFactory

Pointer to an OLE factory object (can be NULL).

lpszPathName

Pointer to the fully qualified path of the container document.

Remarks

Informs the OLE system DLLs that the document is open. Call this function when creating or opening a named file to register the document with the OLE system DLLs. There is no need to call this function if the document represents an embedded item.

If you are using COleTemplateServer in your application, Register is called for you by COleLinkingDoc’s implementation of OnNewDocument, OnOpenDocument, and OnSaveDocument.

COleLinkingDoc Overview | Class Members | Hierarchy Chart

See Also COleTemplateServer, COleObjectFactory, CDocument::OnNewDocument, CDocument::OnOpenDocument


COleLinkingDoc::Revoke

void Revoke( );

Remarks

Informs the OLE system DLLs that the document is no longer open. Call this function to revoke the document’s registration with the OLE system DLLs.

You should call this function when closing a named file, but you usually do not need to call it directly. Revoke is called for you by COleLinkingDoc’s implementation of OnCloseDocument, OnNewDocument, OnOpenDocument, and OnSaveDocument.

COleLinkingDoc Overview | Class Members | Hierarchy Chart

See Also COleTemplateServer, CDocument::OnCloseDocument, CDocument::OnNewDocument, CDocument::OnOpenDocument, CDocument::OnSaveDocument


COleLinksDialog

The COleLinksDialog object is used for the OLE Edit Links dialog box. Create an object of class COleLinksDialog when you want to call this dialog box. After a COleLinksDialog object has been constructed, you can use the m_el structure to initialize the values or states of controls in the dialog box. The m_el structure is of type OLEUIEDITLINKS. For more information about using this dialog class, see the DoModal member function.

Note AppWizard-generated container code uses this class.

For more information, see the OLEUIEDITLINKS structure in the OLE 2.01 User Interface Library.

For more information regarding OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

See Also COleDialog


COleLinksDialog Class Members

Data Members

m_el A structure of type OLEUIEDITLINKS that controls the behavior of the dialog box.

Construction

COleLinksDialog Constructs a COleLinksDialog object.

Operations

DoModal Displays the OLE Edit Links dialog box.


COleLinksDialog::COleLinksDialog

COleLinksDialog ( COleDocument* pDoc, CView* pView, DWORD dwFlags = 0, CWnd* pParentWnd = NULL );

Parameters

pDoc

Points to the OLE document that contains the links to be edited.

pView

Points to the current view on pDoc.

dwFlags

Creation flag, which contains either 0 or ELF_SHOWHELP to specify whether the Help button will be displayed when the dialog box is displayed.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the parent window of the dialog box is set to the main application window.

Remarks

This function constructs only a COleLinksDialog object. To display the dialog box, call the DoModal function.

COleLinksDialog Overview | Class Members | Hierarchy Chart

See Also COleDocument, COleLinksDialog::DoModal, CView, CWnd


COleLinksDialog::DoModal

virtual int DoModal( );

Return Value

Completion status for the dialog box. One of the following values:

  • IDOK if the dialog box was successfully displayed.

  • IDCANCEL if the user canceled the dialog box.

  • IDABORT if an error occurred. If IDABORT is returned, call the COleDialog::GetLastError member function to get more information about the type of error that occurred. For a listing of possible errors, see the OleUIEditLinks function in the OLE 2.01 User Interface Library.

Remarks

Call this function to display the OLE Edit Links dialog box.

If you want to initialize the various dialog box controls by setting members of the m_el structure, you should do it before calling DoModal, but after the dialog object is constructed.

COleLinksDialog Overview | Class Members | Hierarchy Chart

See Also COleDialog::GetLastError, CDialog::DoModal, COleLinksDialog::m_el


COleLinksDialog::m_el

Remarks

Structure of type OLEUIEDITLINKS used to control the behavior of the Edit Links dialog box. Members of this structure can be modified either directly or through member functions.

For more information, see the OLEUIEDITLINKS structure in the OLE 2.01 User Interface Library.

COleLinksDialog Overview | Class Members | Hierarchy Chart

See Also COleLinksDialog::COleLinksDialog, COleLinksDialog::DoModal


COleMessageFilter

The COleMessageFilter class manages the concurrency required by the interaction of OLE applications.

The COleMessageFilter class is useful in visual editing server and container applications, as well as OLE automation applications. For server applications that are being called, this class can be used to make the application “busy” so that incoming calls from other container applications are either canceled or retried later. This class can also be used to determine the action to be taken by a calling application when the called application is busy.

Common usage is for a server application to call BeginBusyState and EndBusyState when it would be dangerous for a document or other OLE accessible object to be destroyed. These calls are made in CWinApp::OnIdle during user-interface updates.

By default, a COleMessageFilter object is allocated when the application is initialized. It can be retrieved with AfxOleGetMessageFilter.

This is an advanced class; you seldom need to work with it directly.

For more information, see the article Servers: Implementing a Server in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

See Also CCmdTarget


COleMessageFilter Class Members

Construction

COleMessageFilter Constructs a COleMessageFilter object.

Operations

Register | Registers the message filter with the OLE system DLLs.
Revoke | Revokes the message filter’s registration with the OLE system DLLs.
BeginBusyState | Puts the application in the busy state.
EndBusyState | Terminates the application’s busy state.
SetBusyReply | Determines the busy application’s reply to an OLE call.
SetRetryReply | Determines the calling application’s reply to a busy application.
SetMessagePendingDelay | Determines how long the application waits for a response to an OLE call.
EnableBusyDialog | Enables and disables the dialog box that appears when a called application is busy.
EnableNotRespondingDialog | Enables and disables the dialog box that appears when a called application is not responding.

Overridables

OnMessagePending Called by the framework to process messages while an OLE call is in progress.


COleMessageFilter::BeginBusyState

virtual void BeginBusyState( );

Remarks

Call this function to begin a busy state. It works in conjunction with EndBusyState to control the application’s busy state. The function SetBusyReply determines the application’s reply to calling applications when it is busy.

The BeginBusyState and EndBusyState calls increment and decrement, respectively, a counter that determines whether the application is busy. For example, two calls to BeginBusyState and one call to EndBusyState still result in a busy state. To cancel a busy state it is necessary to call EndBusyState the same number of times BeginBusyState has been called.

By default, the framework enters the busy state during idle processing, which is performed by CWinApp::OnIdle. While the application is handling ON_COMMANDUPDATEUI notifications, incoming calls are handled later, after idle processing is complete.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::EndBusyState, COleMessageFilter::SetBusyReply, CWinApp::OnIdle


COleMessageFilter::COleMessageFilter

COleMessageFilter( );

Remarks

Creates a COleMessageFilter object.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::Register, COleMessageFilter::Revoke


COleMessageFilter::EnableBusyDialog

void EnableBusyDialog( BOOL bEnableBusy = TRUE );

Parameters

bEnableBusy

Specifies whether the “busy” dialog box is enabled or disabled.

Remarks

Enables and disables the busy dialog box, which is displayed when the message-pending delay expires (see SetRetryReply) during an OLE call.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::EnableNotRespondingDialog, COleMessageFilter::BeginBusyState, COleMessageFilter::SetBusyReply, COleMessageFilter::SetRetryReply, COleBusyDialog


COleMessageFilter::EnableNotRespondingDialog

void EnableNotRespondingDialog( BOOL bEnableNotResponding = TRUE );

Parameters

bEnableNotResponding

Specifies whether the “not responding” dialog box is enabled or disabled.

Remarks

Enables and disables the “not responding” dialog box, which is displayed if a keyboard or mouse message is pending during an OLE call and the call has timed out.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::EnableBusyDialog, COleMessageFilter::BeginBusyState, COleMessageFilter::SetBusyReply, COleBusyDialog


COleMessageFilter::EndBusyState

virtual void EndBusyState( );

Remarks

Call this function to end a busy state. It works in conjunction with BeginBusyState to control the application’s busy state. The function SetBusyReply determines the application’s reply to calling applications when it is busy.

The BeginBusyState and EndBusyState calls increment and decrement, respectively, a counter that determines whether the application is busy. For example, two calls to BeginBusyState and one call to EndBusyState still result in a busy state. To cancel a busy state it is necessary to call EndBusyState the same number of times BeginBusyState has been called.

By default, the framework enters the busy state during idle processing, which is performed by CWinApp::OnIdle. While the application is handling ON_UPDATE_COMMAND_UI notifications, incoming calls are handled after idle processing is complete.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::BeginBusyState, COleMessageFilter::SetBusyReply, CWinApp::OnIdle


COleMessageFilter::OnMessagePending

virtual BOOL OnMessagePending( const MSG* pMsg );

Return Value

Nonzero on success; otherwise 0.

Parameters

pMsg

Pointer to the pending message.

Remarks

Called by the framework to process messages while an OLE call is in progress.

When a calling application is waiting for a call to be completed, the framework calls OnMessagePending with a pointer to the pending message. By default, the framework dispatches WM_PAINT messages, so that window updates can occur during a call that is taking a long time.

You must register your message filter by means of a call to Register before it can become active.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::Register, AfxOleInit, CWinApp::InitInstance


COleMessageFilter::Register

BOOL Register( );

Return Value

Nonzero on success; otherwise 0.

Remarks

Registers the message filter with the OLE system DLLs. A message filter has no effect unless it is registered with the system DLLs. Usually your application's initialization code registers the application’s message filter. Any other message filter registered by your application should be revoked before the program terminates by a call to Revoke.

The framework’s default message filter is automatically registered during initialization and revoked at termination.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::Revoke


COleMessageFilter::Revoke

void Revoke( );

Remarks

Revokes a previous registration performed by a call to Register. A message filter should be revoked before the program terminates.

The default message filter, which is created and registered automatically by the framework, is also automatically revoked.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::Register


COleMessageFilter::SetBusyReply

void SetBusyReply( SERVERCALL nBusyReply );

Parameters

nBusyReply

A value from the SERVERCALL enumeration, which is defined in COMPOBJ.H. It can have any one of the following values:

  • SERVERCALL_ISHANDLED The application can accept calls but may fail in processing a particular call.

  • SERVERCALL_REJECTED The application probably will never be able to process a call.

  • SERVERCALL_RETRYLATER The application is temporarily in a state in which it cannot process a call.

Remarks

This function sets the application’s “busy reply.” The BeginBusyState and EndBusyState functions control the application’s busy state.

When an application has been made busy with a call to BeginBusyState, it responds to calls from the OLE system DLLs with a value determined by the last setting of SetBusyReply. The calling application uses this busy reply to determine what action to take.

By default, the busy reply is SERVERCALL_RETRYLATER. This reply causes the calling application to retry the call as soon as possible.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::BeginBusyState, COleMessageFilter::EndBusyState


COleMessageFilter::SetMessagePendingDelay

void SetMessagePendingDelay( DWORD nTimeout = 5000 );

Parameters

nTimeout

Number of milliseconds for the message-pending delay.

Remarks

Determines how long the calling application waits for a response from the called application before taking further action.

This function works in concert with SetRetryReply.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleMessageFilter::SetRetryReply


COleMessageFilter::SetRetryReply

void SetRetryReply( DWORD nRetryReply = 0 );

Parameters

nRetryReply

Number of milliseconds between retries.

Remarks

Determines the calling application’s action when it receives a busy response from a called application.

When a called application indicates that it is busy, the calling application may decide to wait until the server is no longer busy, to retry right away, or to retry after a specified interval. It may also decide to cancel the call altogether.

The caller’s response is controlled by the functions SetRetryReply and SetMessagePendingDelay. SetRetryReply determines how long the calling application should wait between retries for a given call. SetMessagePendingDelay determines how long the calling application waits for a response from the server before taking further action.

Usually the defaults are acceptable and do not need to be changed. The framework retries the call every nRetryReply milliseconds until the call goes through or the message-pending delay has expired. A value of 0 for nRetryReply specifies an immediate retry, and – 1 specifies cancellation of the call.

When the message-pending delay has expired, the OLE “busy dialog box” (see COleBusyDialog) is displayed so that the user can choose to cancel or retry the call. Call EnableBusyDialog to enable or disable this dialog box.

When a keyboard or mouse message is pending during a call and the call has timed out (exceeded the message-pending delay), the “not responding” dialog box is displayed. Call EnableNotRespondingDialog to enable or disable this dialog box. Usually this state of affairs indicates that something has gone wrong and the user is getting impatient.

When the dialogs are disabled, the current “retry reply” is always used for calls to busy applications.

COleMessageFilter Overview | Class Members | Hierarchy Chart

See Also COleBusyDialog, COleMessageFilter::EnableNotRespondingDialog, COleMessageFilter::EnableBusyDialog, COleMessageFilter::SetMessagePendingDelay


COleObjectFactory

The COleObjectFactory class implements the OLE class factory, which creates OLE objects such as servers, automation objects, and documents.

The COleObjectFactory class has member functions for performing the following functions:

  • Managing the registration of objects.

  • Updating the OLE system register, as well as the run-time registration that informs OLE that objects are running and ready to receive messages.

  • Enforcing licensing by limiting use of the control to licensed developers at design time and to licensed applications at run time.

  • Registering control object factories with the OLE system registry.

For more information about object creation, see the articles Data Objects and Data Sources (OLE) and Data Objects and Data Sources: Creation and Destruction. For more about registration, see the article Registration. These articles are in Visual C++ Programmer’s Guide.

#include <afxdisp.h>

Class Members | Base Class | Hierarchy Chart

See Also COleTemplateServer


COleObjectFactory Class Members

Construction

COleObjectFactory Constructs a COleObjectFactory object.

Operations

Register | Registers this object factory with the OLE system DLLs.
RegisterAll | Registers all of the application’s object factories with OLE system DLLs.
Revoke | Revokes this object factory’s registration with the OLE system DLLs.
RevokeAll | Revokes an application’s object factories’ registrations with the OLE system DLLs.
UpdateRegistryAll | Registers all of the application’s object factories with the OLE system registry.

Attributes

IsRegistered | Indicates whether the object factory is registered with the OLE system DLLs.
GetClassID | Returns the OLE class ID of the objects this factory creates.

Overridables

OnCreateObject | Called by the framework to create a new object of this factory’s type.
UpdateRegistry | Registers this object factory with the OLE system registry.
VerifyUserLicense | Verifies that the control is licensed for design-time use.
GetLicenseKey | Requests a unique key from the control’s DLL.
VerifyLicenseKey | Verifies that the key embedded in the control matches the key embedded in the container.


COleObjectFactory::COleObjectFactory

COleObjectFactory( REFCLSID clsid, CRuntimeClass* pRuntimeClass, BOOL bMultiInstance, LPCTSTR lpszProgID );

Parameters

clsid

Reference to the OLE class ID this object factory represents.

pRuntimeClass

Pointer to the run-time class of the C++ objects this factory can create.

bMultiInstance

Indicates whether a single instance of the application can support multiple instantiations. If TRUE, multiple instances of the application are launched for each request to create an object.

lpszProgID

Pointer to a string containing a verbal program identifier, such as “Microsoft Excel.”

Remarks

Constructs a COleObjectFactory object, initializes it as an unregistered object factory, and adds it to the list of factories. To use the object, however, you must register it.

For more information, see CLSID Key in the OLE 2 Programmer’s Reference, Volume 1.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also CRuntimeClass


COleObjectFactory::GetClassID

REFCLSID GetClassID( ) const;

Return Value

Reference to the OLE class ID this factory represents.

Remarks

Returns a reference to the OLE class ID this factory represents.

For more information, see CLSID Key in the OLE 2 Programmer’s Reference, Volume 1.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::COleObjectFactory


COleObjectFactory::GetLicenseKey

virtual BOOL GetLicenseKey( DWORD dwReserved, BSTR *pbstrKey );

Return Value

Nonzero if the license-key string is not NULL; otherwise 0.

Parameters

dwReserved

Reserved for future use.

pbstrKey

Pointer to a BSTR that will store the license key.

Remarks

Requests a unique license key from the control’s DLL and stores it in the BSTR pointed to by pbstrKey.

The default implementation of this function returns 0 and stores nothing in the BSTR. If you use MFC ActiveX ControlWizard to create your project, ControlWizard supplies an override that retrieves the control’s license key.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::VerifyUserLicense, COleObjectFactory::VerifyLicenseKey


COleObjectFactory::IsRegistered

BOOL IsRegistered( ) const;

Return Value

Nonzero if the factory is registered; otherwise 0.

Remarks

Returns a nonzero value if the factory is registered with the OLE system DLLs.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::Register, COleObjectFactory::Revoke


COleObjectFactory::OnCreateObject

virtual CCmdTarget* OnCreateObject( );

Return Value

A pointer to the created object. It can throw a memory exception if it fails.

Remarks

Called by the framework to create a new object. Override this function to create the object from something other than the CRuntimeClass passed to the constructor.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::COleObjectFactory, CRuntimeClass


COleObjectFactory::Register

BOOL Register( );

Return Value

Nonzero if the factory is successfully registered; otherwise 0.

Remarks

Registers this object factory with the OLE system DLLs. This function is usually called by CWinApp::InitInstance when the application is launched.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::Revoke, COleObjectFactory::RegisterAll, CWinApp::InitInstance


COleObjectFactory::RegisterAll

static BOOL PASCAL RegisterAll( );

Return Value

Nonzero if the factories are successfully registered; otherwise 0.

Remarks

Registers all of the application’s object factories with the OLE system DLLs. This function is usually called by CWinApp::InitInstance when the application is launched.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::Revoke, COleObjectFactory::Register, CWinApp::InitInstance


COleObjectFactory::Revoke

void Revoke( );

Remarks

Revokes this object factory’s registration with the OLE system DLLs. The framework calls this function automatically before the application terminates. If necessary, call it from an override of CWinApp::ExitInstance.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::RevokeAll, COleObjectFactory::Register, CWinApp::ExitInstance


COleObjectFactory::RevokeAll

static void PASCAL RevokeAll( );

Remarks

Revokes all of the application’s object factories’ registrations with the OLE system DLLs. The framework calls this function automatically before the application terminates. If necessary, call it from an override of CWinApp::ExitInstance.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::Revoke, COleObjectFactory::RegisterAll, CWinApp::ExitInstance


COleObjectFactory::UpdateRegistry

void UpdateRegistry( LPCTSTR lpszProgID = NULL );

virtual void UpdateRegistry( BOOL bRegister ) = 0;

Parameters

lpszProgID

Pointer to a string containing the human-readable program identifier, such as “Excel.Document.5.”

bRegister

Determines whether the control class’s object factory is to be registered.

Remarks

Brief discussions of the two forms for this function follow:

  • UpdateRegistry( lpszProgID ) Registers this object factory with the OLE system registry. This function is usually called by CWinApp::InitInstance when the application is launched.

  • UpdateRegistry( bRegister ) This form of the function is overridable. If bRegister is TRUE, this function registers the control class with the system registry. Otherwise, it unregisters the class.

    If you use MFC ActiveX ControlWizard to create your project, ControlWizard supplies an override to this pure virtual function.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::Revoke, COleObjectFactory::Register, COleObjectFactory::UpdateRegistryAll, CWinApp::InitInstance


COleObjectFactory::UpdateRegistryAll

static void PASCAL UpdateRegistryAll( );

Remarks

Registers all of the application’s object factories with the OLE system registry. This function is usually called by CWinApp::InitInstance when the application is launched.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::Revoke, COleObjectFactory::Register, COleObjectFactory::UpdateRegistry, CWinApp::InitInstance


COleObjectFactory::VerifyLicenseKey

virtual BOOL VerifyLicenseKey( BSTR bstrKey );

Return Value

Nonzero if the run-time license is valid; otherwise 0.

Parameters

bstrKey

A BSTR storing the container’s version of the license string.

Remarks

This function verifies that the container is licensed to use the OLE control. The default version calls GetLicenseKey to get a copy of the control’s license string and compares it with the string in bstrKey. If the two strings match, the function returns a nonzero value; otherwise it returns 0.

You can override this function to provide customized verification of the license.

The function VerifyUserLicense verifies the design-time license.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::VerifyUserLicense, COleObjectFactory::GetLicenseKey


COleObjectFactory::VerifyUserLicense

virtual BOOL VerifyUserLicense( );

Return Value

Nonzero if the design-time license is valid; otherwise 0.

Remarks

Verifies the design-time license for the OLE control.

COleObjectFactory Overview | Class Members | Hierarchy Chart

See Also COleObjectFactory::VerifyLicenseKey, COleObjectFactory::GetLicenseKey


COlePasteSpecialDialog

The COlePasteSpecialDialog class is used for the OLE Paste Special dialog box. Create an object of class COlePasteSpecialDialog when you want to call this dialog box. After a COlePasteSpecialDialog object has been constructed, you can use the AddFormat and AddStandardFormats member functions to add Clipboard formats to the dialog box. You can also use the m_ps structure to initialize the values or states of controls in the dialog box. The m_ps structure is of type OLEUIPASTESPECIAL.

For more information, see the OLEUIPASTESPECIAL structure in the OLE 2.01 User Interface Library.

For more information regarding OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample OCLIENT

See Also COleDialog


COlePasteSpecialDialog Class Members

Data Members

m_ps A structure of type OLEUIPASTESPECIAL that controls the function of the dialog box.

Construction

COlePasteSpecialDialog Constructs a COlePasteSpecialDialog object.

Operations and Attributes

DoModal | Displays the OLE Paste Special dialog box.
AddFormat | Adds custom formats to the list of formats your application can paste.
AddStandardFormats | Adds CF_BITMAP, CF_DIB, CF_METAFILEPICT, and optionally CF_LINKSOURCE to the list of formats your application can paste.
CreateItem | Creates the item in the container document using the specified format.
GetSelectionType | Gets the type of selection chosen.
GetDrawAspect | Tells whether to draw item as an icon or not.
GetIconicMetafile | Gets a handle to the metafile associated with the iconic form of this item.
GetPasteIndex | Gets the index of available paste options that was chosen by the user.


COlePasteSpecialDialog::AddFormat

void AddFormat( const FORMATETC& fmt, LPTSTR lpstrFormat, LPTSTR lpstrResult, DWORD flags );

void AddFormat( UINT cf, DWORD tymed, UINT nFormatID, BOOL bEnableIcon, BOOL bLink );

Parameters

fmt

Reference to the data type to add.

lpstrFormat

String that describes the format to the user.

lpstrResult

String that describes the result if this format is chosen in the dialog box.

flags

The different linking and embedding options available for this format. This flag is a bitwise combination of one or more of the different values in the OLEUIPASTEFLAG enumerated type.

cf

The clipboard format to add.

tymed

The types of media available in this format. This is a bitwise combination of one or more of the values in the TYMED enumerated type.

nFormatID

The ID of the string that identifies this format. The format of this string is two separate strings separated by a ‘\n’ character. The first string is the same that would be passed in the lpstrFormat parameter, and the second is the same as the lpstrResult parameter.

bEnableIcon

Flag that determines whether the Display As Icon check box is enabled when this format is chosen in the list box.

bLink

Flag that determines whether the Paste Link radio button is enabled when this format is chosen in the list box.

Remarks

Call this function to add new formats to the list of formats your application can support in a Paste Special operation. This function can be called to add either standard formats such as CF_TEXT or CF_TIFF or custom formats that your application has registered with the system. For more information about pasting data objects into your application, see the article Data Objects and Data Sources: Manipulation in Visual C++ Programmer’s Guide.

For more information, see the TYMED enumeration type and the FORMATETC structure in the OLE 2 Programmer’s Reference, Volume 1.

For more information, see the OLEUIPASTEFLAG enumerated type in the OLE 2.01 User Interface Library.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COlePasteSpecialDialog::AddStandardFormats


COlePasteSpecialDialog::AddStandardFormats

void AddStandardFormats( BOOL bEnableLink = TRUE );

Parameters

bEnableLink

Flag that determines whether to add CF_LINKSOURCE to the list of formats your application can paste.

Remarks

Call this function to add the following Clipboard formats to the list of formats your application can support in a Paste Special operation:

  • CF_BITMAP

  • CF_DIB

  • CF_METAFILEPICT

  • “Embedded Object”

  • (optionally) “Link Source”

These formats are used to support embedding and linking.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COlePasteSpecialDialog::AddFormat


COlePasteSpecialDialog::COlePasteSpecialDialog

COlePasteSpecialDialog( DWORD dwFlags = PSF_SELECTPASTE, COleDataObject* pDataObject = NULL, CWnd* pParentWnd = NULL );

Parameters

dwFlags

Creation flag, contains any number of the following flags combined using the bitwise-OR operator:

  • PSF_SELECTPASTE Specifies that the Paste radio button will be checked initially when the dialog box is called. Cannot be used in combination with PSF_SELECTPASTELINK. This is the default.

  • PSF_SELECTPASTELINK Specifies that the Paste Link radio button will be checked initially when the dialog box is called. Cannot be used in combination with PSF_SELECTPASTE.

  • PSF_CHECKDISPLAYASICON Specifies that the Display As Icon check box will be checked initially when the dialog box is called.

  • PSF_SHOWHELP Specifies that the Help button will be displayed when the dialog box is called.

pDataObject

Points to the COleDataObject for pasting. If this value is NULL, it gets the COleDataObject from the Clipboard.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the parent window of the dialog box is set to the main application window.

Remarks

This function only constructs a COlePasteSpecialDialog object. To display the dialog box, call the DoModal function.

For more information, see the OLEUIPASTEFLAG enumerated type in the OLE 2.01 User Interface Library.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COleDataObject, COlePasteSpecialDialog::DoModal


COlePasteSpecialDialog::CreateItem

BOOL CreateItem( COleClientItem* pNewItem );

Return Value

Nonzero if the item was created successfully; otherwise 0.

Parameters

pNewItem

Points to a COleClientItem instance. Cannot be NULL.

Remarks

Call this function to create the new item that was chosen in the Paste Special dialog box. This function should only be called after DoModal returns IDOK.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COleClientItem, COlePasteSpecialDialog::DoModal, COlePasteSpecialDialog::GetSelectionType, COlePasteSpecialDialog::COlePasteSpecialDialog


COlePasteSpecialDialog::DoModal

virtual int DoModal( );

Return Value

Completion status for the dialog box. One of the following values:

  • IDOK if the dialog box was successfully displayed.

  • IDCANCEL if the user canceled the dialog box.

  • IDABORT if an error occurred. If IDABORT is returned, call the COleDialog::GetLastError member function to get more information about the type of error that occurred. For a listing of possible errors, see the OleUIPasteSpecial function in the OLE 2.01 User Interface Library.

Remarks

Call this function to display the OLE Paste Special dialog box.

If you want to initialize the various dialog box controls by setting members of the m_ps structure, you should do this before calling DoModal, but after the dialog object is constructed.

If DoModal returns IDOK, you can call other member functions to retrieve the settings or information input by the user into the dialog box.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COleDataObject, COleDialog::GetLastError, CDialog::DoModal, COlePasteSpecialDialog::COlePasteSpecialDialog, COlePasteSpecialDialog::GetDrawAspect, COlePasteSpecialDialog::GetIconicMetafile, COlePasteSpecialDialog::GetPasteIndex, COlePasteSpecialDialog::GetSelectionType


COlePasteSpecialDialog::GetDrawAspect

DVASPECT GetDrawAspect( ) const;

Return Value

The method needed to render the object.

  • DVASPECT_CONTENT Returned if the Display As Icon check box was not checked when the dialog box was dismissed.

  • DVASPECT_ICON Returned if the Display As Icon check box was checked when the dialog box was dismissed.

Remarks

Call this function to determine if the user chose to display the selected item as an icon. Only call this function after DoModal returns IDOK.

For more information on drawing aspect, see the FORMATETC structure in the OLE 2 Programmer’s Reference, Volume 1.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COlePasteSpecialDialog::DoModal


COlePasteSpecialDialog::GetIconicMetafile

HGLOBAL GetIconicMetafile( ) const;

Return Value

The handle to the metafile containing the iconic aspect of the selected item, if the Display As Icon check box was selected when the dialog box was dismissed by choosing OK; otherwise NULL.

Remarks

Gets the metafile associated with the item selected by the user.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COlePasteSpecialDialog::GetDrawAspect, COlePasteSpecialDialog::DoModal


COlePasteSpecialDialog::GetPasteIndex

int GetPasteIndex( ) const;

Return Value

The index into the array of OLEUIPASTEENTRY structures that was selected by the user. The format that corresponds to the selected index should be used when performing the paste operation.

Remarks

Gets the index value associated with the entry the user selected.

For more information, see the OLEUIPASTEENTRY structure in the OLE 2.01 User Interface Library.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COlePasteSpecialDialog::DoModal


COlePasteSpecialDialog::GetSelectionType

UINT GetSelectionType( ) const;

Return Value

Returns type of selection made.

Remarks

Call this function to determine the type of selection the user made.

The return type values are specified by the Selection enumeration type declared in the COlePasteSpecialDialog class.

enum Selection
{
   pasteLink,
   pasteNormal,
   pasteOther,
   pasteStatic
};

Brief desccriptions of these values follow:

  • COlePasteSpecialDialog::pasteLink The Paste Link radio button was checked and the chosen format was a standard OLE format.

  • COlePasteSpecialDialog::pasteNormal The Paste radio button was checked and the chosen format was a standard OLE format.

  • COlePasteSpecialDialog::pasteOther The selected format is not a standard OLE format.

  • COlePasteSpecialDialog::pasteStatic The chosen format was a metafile.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COlePasteSpecialDialog::DoModal


COlePasteSpecialDialog::m_ps

Remarks

Structure of type OLEUIPASTESPECIAL used to control the behavior of the Paste Special dialog box. Members of this structure can be modified directly or through member functions.

For more information, see the OLEUIPASTESPECIAL structure in the OLE 2.01 User Interface Library.

COlePasteSpecialDialog Overview | Class Members | Hierarchy Chart

See Also COlePasteSpecialDialog::COlePasteSpecialDialog, COlePasteSpecialDialog::DoModal


COlePropertiesDialog

The COlePropertiesDialog class encapsulates the Windows common OLE Object Properties dialog box. Common OLE Object Properties dialog boxes provide an easy way to display and modify the properties of an OLE document item in a manner consistent with Windows standards. These properties include, among others, information on the file represented by the document item, options for displaying the icon and image scaling, and information on the item’s link (if the item is linked).

To use a COlePropertiesDialog object, first create the object using the COlePropertiesDialog constructor. After the dialog box has been constructed, call the DoModal member function to display the dialog box and allow the user to modify any properties of the item. DoModal returns whether the user selected the OK (IDOK) or the Cancel (IDCANCEL) button. In addition to the OK and Cancel buttons, there is an Apply button. When the user selects Apply, any changes made to the properties of the document item are applied to the item and its image is automatically updated, but remains active.

The m_psh data member is a pointer to a PROPSHEETHEADER structure, and in most cases you will not need to access it explicitly. One exception is when you need additional property pages beyond the default General, View, and Link pages. In this case, you can modify the m_psh data member to include your custom pages before calling the DoModal member function.

For more information on OLE dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CIRC3

See Also COleDialog, CPropertyPage


COlePropertiesDialog Class Members

Construction

COlePropertiesDialog Constructs a COlePropertiesDialog object.

Data Members

m_gp | A structure used to initialize the “General” page of a COlePropertiesDialog object.
m_lp | A structure used to initialize the “Link” page of a COlePropertiesDialog object.
m_op | A structure used to initialize the COlePropertiesDialog object.
m_psh | A structure used to add additional custom property pages.
m_vp | A structure used to customize the “View” page of a COlePropertiesDialog object.

Operations

DoModal Displays the dialog box and allows the user to make a selection.

Overridables

OnApplyScale Called by the framework when the scaling of the document item has changed.


COlePropertiesDialog::COlePropertiesDialog

COlePropertiesDialog( COleClientItem* pItem, UINT nScaleMin = 10, UINT nScaleMax = 500, CWnd* pParentWnd = NULL );

Parameters

pItem

Pointer to the document item whose properties are being accessed.

nScaleMin

Minimum scaling percentage for the document item image.

nScaleMax

Maximum scaling percentage for the document item image.

pParentWnd

Pointer to the dialog box’s parent or owner.

Remarks

Creates a COlePropertiesDialog object. Derive your common OLE Object Properties dialog class from COlePropertiesDialog in order to implement scaling for your document items. Any dialog boxes implemented by an instance of this class will not support scaling of the document item.

By default, the common OLE Object Properties dialog box has three default pages:

  • General

    This page contains system information for the file represented by the selected document item. From this page, the user can convert the selected item to another type.

  • View

    This page contains options for displaying the item, changing the icon, and changing the scaling of the image.

  • Link

    This page contains options for changing the location of the linked item and updating the linked item. From this page, the user can break the link of the selected item.

To add pages beyond those provided by default, modify the m_psh member variable before exiting the constructor of your COlePropertiesDialog-derived class. This is an advanced implementation of the COlePropertiesDialog constructor.

COlePropertiesDialog Overview | Class Members | Hierarchy Chart

See Also COlePropertiesDialog::OnApplyScale


COlePropertiesDialog::DoModal

virtual int DoModal( );

Return Value

IDOK or IDCANCEL if successful; otherwise 0. IDOK and IDCANCEL are constants that indicate whether the user selected the OK or Cancel button.

If IDCANCEL is returned, you can call the Windows CommDlgExtendedError function to determine whether an error occurred.

Remarks

Call this member function to display the Windows common OLE Object Properties dialog box and allow the user to view and/or change the various properties of the document item.

COlePropertiesDialog Overview | Class Members | Hierarchy Chart

See Also COlePropertiesDialog::OnApplyScale, COlePropertiesDialog::m_psh


COlePropertiesDialog::OnApplyScale

virtual BOOL OnApplyScale( COleClientItem* pItem, int nCurrentScale, BOOL bRelativeToOrig );

Return Value

Nonzero if handled; otherwise 0.

Parameters

pItem

Pointer to the document item whose properties are being accessed.

nCurrentScale

Numerical value of the dialog scale.

bRelativeToOrig

Indicates whether scaling applies to the original size of the document item.

Remarks

Called by the framework when the scaling value has changed and either OK or Apply was selected. The default implementation does nothing. You must override this function to enable the scaling controls.

Note Before the common OLE Object Properties dialog box is displayed, the framework calls this function with a NULL for pItem and a – 1 for nCurrentScale. This is done to determine if the scaling controls should be enabled.

COlePropertiesDialog Overview | Class Members | Hierarchy Chart

See Also COlePropertiesDialog::DoModal


COlePropertiesDialog::m_gp

Remarks

A structure of type OLEUIGNRLPROPS, used to initialize the General page of the OLE Object Properties dialog box. This page shows the type and size of an embedding and allows the user access to the Convert dialog box. This page also shows the link destination if the object is a link.

For more information on the OLEUIGNRLPROPS structure, see the OLE documentation.


COlePropertiesDialog::m_lp

Remarks

A structure of type OLEUILINKPROPS, used to initialize the Link page of the OLE Object Properties dialog box. This page shows the location of the linked item and allows the user to update, or break, the link to the item.

For more information on the OLEUILINKPROPS structure, see the OLE documentation.


COlePropertiesDialog::m_op

Remarks

A structure of type OLEUIOBJECTPROPS, used to initialize the common OLE Object Properties dialog box. This structure contains members used to initialize the General, Link, and View pages.

For more information, see the OLEUIOBJECTPROPS and OLEUILINKPROPS structures in the OLE documentation.


COlePropertiesDialog::m_psh

Remarks

A structure of type PROPSHEETHEADER, whose members store the characteristics of the dialog object. After constructing a COlePropertiesDialog object, you can use m_psh to set various aspects of the dialog box before calling the DoModal member function.

If you modify the m_psh data member directly, you will override any default behavior.

For more information on the PROPSHEETHEADER structure, see the Win32 SDK documentation.

COlePropertiesDialog Overview | Class Members | Hierarchy Chart

See Also COlePropertiesDialog::DoModal


COlePropertiesDialog::m_vp

Remarks

A structure of type OLEUIVIEWPROPS, used to initialize the View page of the OLE Object Properties dialog box. This page allows the user to toggle between “content” and “iconic” views of the object, and change its scaling within the container. It also allows the user access to the Change Icon dialog box when the object is being displayed as an icon.

For more information on the OLEUIVIEWPROPS structure, see the OLE documentation.


COlePropertyPage

The COlePropertyPage class is used to display the properties of a custom control in a graphical interface, similar to a dialog box. For instance, a property page may include an edit control that allows the user to view and modify the control’s caption property.

Each custom or stock control property can have a dialog control that allows the control’s user to view the current property value and modify that value if needed.

For more information on using COlePropertyPage, see the article ActiveX Controls: Property Pages in Visual C++ Programmer’s Guide and Modifying the Default Property Page in Visual C++ Tutorials.

#include <afxctl.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CIRC3 | MFC Sample DRAWPIC | MFC Sample TESTHELP

See Also CDialog


COlePropertyPage Class Members

Construction

COlePropertyPage Constructs a COlePropertyPage object.

Operations

GetObjectArray | Returns the array of objects being edited by the property page.
SetModifiedFlag | Sets a flag indicating whether the user has modified the property page.
IsModified | Indicates whether the user has modified the property page.
GetPageSite | Returns a pointer to the property page’s IPropertyPageSite interface.
SetDialogResource | Sets the property page’s dialog resource.
SetPageName | Sets the property page’s name (caption).
SetHelpInfo | Sets the property page’s brief help text, the name of its help file, and its help context.
GetControlStatus | Indicates whether the user has modified the value in the control.
SetControlStatus | Sets a flag indicating whether the user has modified the value in the control.
IgnoreApply | Determines which controls do not enable the Apply button.

Overridables

OnEditProperty | Called by the framework when the user edits a property.
OnHelp | Called by the framework when the user invokes help.
OnInitDialog | Called by the framework when the property page is initialized.
OnObjectsChanged | Called by the framework when another OLE control, with new properties, is chosen.
OnSetPageSite | Called by the framework when the property frame provides the page’s site.


COlePropertyPage::COlePropertyPage

COlePropertyPage( UINT idDlg, UINT idCaption );

Parameters

idDlg

Resource ID of the dialog template.

idCaption

Resource ID of the property page’s caption.

Remarks

When you implement a subclass of COlePropertyPage, your subclass’s constructor should use the COlePropertyPage constructor to identify the dialog-template resource on which the property page is based and the string resource containing its caption.


COlePropertyPage::GetControlStatus

BOOL GetControlStatus( UINT nID );

Return Value

TRUE if the control value has been modified; otherwise FALSE.

Parameters

nID

Resource ID of a property page control.

Remarks

Call this function to determine whether the user has modified the value of the property page control with the specified resource ID.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also COlePropertyPage::SetControlStatus


COlePropertyPage::GetObjectArray

LPDISPATCH FAR* GetObjectArray( ULONG FAR* pnObjects );

Return Value

Pointer to an array of IDispatch pointers, which are used to access the properties of each control on the property page. The caller must not release these interface pointers.

Parameters

pnObjects

Pointer to an unsigned long integer that will receive the number of objects being edited by the page.

Remarks

Each property page object maintains an array of pointers to the IDispatch interfaces of the objects being edited by the page. This function sets its pnObjects argument to the number of elements in that array and returns a pointer to the first element of the array.


COlePropertyPage::GetPageSite

LPPROPERTYPAGESITE GetPageSite( );

Return Value

A pointer to the property page’s IPropertyPageSite interface.

Remarks

Call this function to get a pointer to the property page’s IPropertyPageSite interface.

Controls and containers cooperate so that users can browse and edit control properties. The control provides property pages, each of which is an OLE object that allows the user to edit a related set of properties. The container provides a property frame that displays the property pages. For each page, the property frame provides a page site, which supports the IPropertyPageSite interface.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also COlePropertyPage::OnSetPageSite


COlePropertyPage::IgnoreApply

void IgnoreApply( UINT nID );

Parameters

nID

ID of the control to be ignored.

Remarks

The property page’s Apply button is enabled only when values of property page controls have been changed. Use this function to specify controls that do not cause the Apply button to be enabled when their values change.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also COlePropertyPage::GetControlStatus


COlePropertyPage::IsModified

BOOL IsModified( );

Return Value

TRUE if the property page has been modified.

Remarks

Call this function to determine whether the user has changed any values on the property page.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also COlePropertyPage::SetModifiedFlag


COlePropertyPage::OnEditProperty

virtual BOOL OnEditProperty( DISPID dispid );

Return Value

The default implementation returns FALSE. Overrides of this function should return TRUE.

Parameters

dispid

Dispatch ID of the property being edited.

Remarks

The framework calls this function when a specific property is to be edited. You can override it to set the focus to the appropriate control on the page. The default implementation does nothing and returns FALSE.


COlePropertyPage::OnHelp

virtual BOOL OnHelp( LPCTSTR lpszHelpDir );

Return Value

The default implementation returns FALSE.

Parameters

lpszHelpDir

Directory containing the property page’s help file.

Remarks

The framework calls this function when the user requests online help. Override it if your property page must perform any special action when the user accesses help. The default implementation does nothing and returns FALSE, which instructs the framework to call WinHelp.


COlePropertyPage::OnInitDialog

virtual BOOL OnInitDialog( );

Return Value

The default implementation returns FALSE.

Remarks

The framework calls this function when the property page’s dialog is initialized. Override it if any special action is required when the dialog is initialized. The default implementation calls CDialog::OnInitDialog and returns FALSE.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also CDialog::OnInitDialog


COlePropertyPage::OnObjectsChanged

virtual void OnObjectsChanged( );

Remarks

When viewing the properties of an OLE control in the developer environment, a modeless dialog box is used to display its property pages. If another control is selected, a different set of property pages must be displayed for the new set of properties. The framework calls this function to notify the property page of the change.

Override this function to receive notification of this action and perform any special actions.


COlePropertyPage::OnSetPageSite

virtual void OnSetPageSite( );

Remarks

The framework calls this function when the property frame provides the property page’s page site. The default implementation loads the page’s caption and attempts to determine the page’s size from the dialog resource. Override this function if your property page requires any further action; your override should call the base-class implementation.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also COlePropertyPage::GetPageSite


COlePropertyPage::SetControlStatus

BOOL SetControlStatus( UINT nID, BOOL IsDirty );

Return Value

TRUE, if the specified control was set; otherwise FALSE.

Parameters

nID

Contains the ID of a property page control.

IsDirty

Specifies if a field of the property page has been modified. Set to TRUE if the field has been modified, FALSE if it has not been modified.

Remarks

Call this function to change the status of a property page control.

If the status of a property page control is dirty when the property page is closed or the Apply button is chosen, the control’s property will be updated with the appropriate value.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also COlePropertyPage::GetControlStatus


COlePropertyPage::SetDialogResource

void SetDialogResource( HGLOBAL hDialog );

Parameters

hDialog

Handle to the property page’s dialog resource.

Remarks

Call this function to set the property page’s dialog resource.


COlePropertyPage::SetHelpInfo

void SetHelpInfo( LPCTSTR lpszDocString, LPCTSTR lpszHelpFile = NULL, DWORD dwHelpContext = 0 );

Parameters

lpszDocString

A string containing brief help information for display in a status bar or other location.

lpszHelpFile

Name of the property page’s help file.

dwHelpContext

Help context for the property page.

Remarks

Use this function to specify “tool tip” information, the help filename, and the help context for your property page.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also COlePropertyPage::OnHelp


COlePropertyPage::SetModifiedFlag

void SetModifiedFlag( BOOL bModified = TRUE );

Parameters

bModified

Specifies the new value for the property page’s modified flag.

Remarks

Use this function to indicate whether the user has modified the property page.

COlePropertyPage Overview | Class Members | Hierarchy Chart

See Also COlePropertyPage::IsModified


COlePropertyPage::SetPageName

void SetPageName( LPCTSTR lpszPageName );

Parameters

lpszPageName

Pointer to a string containing the property page’s name.

Remarks

Use this function to set the property page’s name, which the property frame will typically display on the page’s tab.


COleResizeBar

An object of the class COleResizeBar is a type of control bar that supports resizing of in-place OLE items. COleResizeBar objects appear as a CRectTracker with a hatched border and outer resize handles.

COleResizeBar objects are usually embedded members of frame-window objects derived from the COleIPFrameWnd class.

For more information, see the article Activation in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample SUPERPAD

See Also COleServerDoc


COleResizeBar Class Members

Construction

COleResizeBar | Constructs a COleResizeBar object.
Create | Creates and initializes a Windows child window and associates it to the COleResizeBar object.


COleResizeBar::Create

BOOL Create( CWnd* pParentWnd, DWORD dwStyle = WS_CHILD | WS_VISIBLE, UINT nID = AFX_IDW_RESIZE_BAR );

Return Value

Nonzero if the resize bar was created; otherwise 0.

Parameters

pParentWnd

Pointer to the parent window of the resize bar.

dwStyle

Specifies the window style attributes.

nID

The resize bar’s child window ID.

Remarks

Creates a child window and associates it with the COleResizeBar object.

COleResizeBar Overview | Class Members | Hierarchy Chart

See Also CWnd::Create, CControlBar


COleResizeBar::COleResizeBar

COleResizeBar( );

Remarks

Constructs a COleResizeBar object. Call Create to create the resize bar object.

COleResizeBar Overview | Class Members | Hierarchy Chart

See Also COleResizeBar::Create


COleSafeArray

Class COleSafeArray is a class for working with arrays of arbitrary type and dimension. COleSafeArray derives from the OLE VARIANT structure. The OLE SAFEARRAY member functions are available through COleSafeArray, as well as a set of member functions specifically designed for one-dimensional arrays of bytes.

#include <afxdisp.h>

Class Members | Hierarchy Chart

See Also COleVariant, CRecordSet, CDatabase


COleSafeArray Class Members

Construction

COleSafeArray Constructs a COleSafeArray object.

Operations

Attach | Gives control of the existing VARIANT array to the COleSafeArray object.
Clear | Frees all data in the underlying VARIANT.
Detach | Detaches the VARIANT array from the COleSafeArray object (so that the data will not be freed).

Win32 API Wrappers

AccessData | Retrieves a pointer to the array data.
AllocData | Allocates memory for the array.
AllocDescriptor | Allocates memory for the safe array descriptor.
Copy | Creates a copy of an existing array.
Create | Creates a safe array.
Destroy | Destroys an existing array.
DestroyData | Destroys data in a safe array.
DestroyDescriptor | Destroys a descriptor of a safe array.
GetDim | Returns the number of dimensions in the array.
GetElement | Retrieves a single element of the safe array.
GetElemSize | Returns the size, in bytes, of one element in a safe array.
GetLBound | Returns the lower bound for any dimension of a safe array.
GetUBound | Returns the upper bound for any dimension of a safe array.
Lock | Increments the lock count of an array and places a pointer to the array data in the array descriptor.
PtrOfIndex | Returns a pointer to the indexed element.
PutElement | Assigns a single element into the array.
Redim | Changes the least significant (rightmost) bound of a safe array.
UnaccessData | Decrements the lock count of an array and invalidates the pointer retrieved by AccessData.
Unlock | Decrements the lock count of an array so it can be freed or resized.

One-Dimensional Array Operations

CreateOneDim | Creates a one-dimensional COleSafeArray object.
GetOneDimSize | Returns the number of elements in the one-dimensional COleSafeArray object.
ResizeOneDim | Changes the number of elements in a one-dimensional COleSafeArray object.

Operators

operator = | Copies values into a COleSafeArray object (SAFEARRAY, VARIANT, COleVariant, or COleSafeArray array).
operator == | Compares two variant arrays (SAFEARRAY, VARIANT, COleVariant, or COleSafeArray arrays).
operator << | Outputs the contents of a COleSafeArray object to the dump context.
operator LPVARIANT | Accesses the underlying VARIANT structure of the COleSafeArray object.
operator LPCVARIANT | Accesses the underlying VARIANT structure of the COleSafeArray object.


COleSafeArray::AccessData

void AccessData( void** ppvData );

Parameters

ppvData

A pointer to a pointer to the array data.

Remarks

Retrieves a pointer to the array data. On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::UnaccessData, SafeArrayAccessData


COleSafeArray::AllocData

void AllocData( );

Remarks

Call this function to allocate memory for a safe array. On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::AllocDescriptor, SafeArrayAllocData


COleSafeArray::AllocDescriptor

void AllocDescriptor( DWORD dwDims );

Parameters

dwDims

Number of dimensions in the safe array.

Remarks

Call this function to allocate memory for the descriptor of a safe array. On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::AllocData, SafeArrayAllocDescriptor


COleSafeArray::Attach

void Attach( VARIANT& varSrc );

Parameters

varSrc

A VARIANT object. The varSrc parameter must have the VARTYPE VT_ARRAY.

Remarks

Call this function to give control of the data in an existing VARIANT array to the COleSafeArray object. The source VARIANT's type is set to VT_EMPTY. This function clears the current array data, if any.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Detach


COleSafeArray::Clear

void Clear( );

Remarks

Call this function to clear the safe array. The function clears a safe array by setting the VARTYPE of the object to VT_EMPTY. The current contents are released and the array is freed.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also VariantClear


COleSafeArray::COleSafeArray

COleSafeArray( );

COleSafeArray( const SAFEARRAY& saSrc, VARTYPE vtSrc );

COleSafeArray( LPCSAFEARRAY psaSrc, VARTYPE vtSrc );

COleSafeArray( const COleSafeArray& saSrc );

COleSafeArray( const VARIANT& varSrc );

COleSafeArray( LPCVARIANT pSrc );

COleSafeArray( const COleVariant& varSrc );

Parameters

saSrc

An existing COleSafeArray object or SAFEARRAY to be copied into the new COleSafeArray object.

vtSrc

The VARTYPE of the new COleSafeArray object.

psaSrc

A pointer to a SAFEARRAY to be copied into the new COleSafeArray object.

varSrc

An existing VARIANT or COleVariant object to be copied into the new COleSafeArray object.

pSrc

A pointer to a VARIANT object to be copied into the new COleSafeArray object.

Remarks

All of these constructors create new COleSafeArray objects. If there is no parameter, an empty COleSafeArray object is created (VT_EMPTY). If the COleSafeArray is copied from another array whose VARTYPE is known implicitly (a COleSafeArray, COleVariant, or VARIANT), the VARTYPE of the source array is retained and need not be specified. If the COleSafeArray is copied from another array whose VARTYPE is not known (SAFEARRAY), the VARTYPE must be specified in the vtSrc parameter.

On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also VariantCopy


COleSafeArray::Copy

void Copy( LPSAFEARRAY* ppsa );

Parameters

ppsa

Pointer to a location in which to return the new array descriptor.

Remarks

Creates a copy of an existing safe array. On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also SafeArrayCopy


COleSafeArray::Create

void Create( VARTYPE vtSrc, DWORD dwDims, DWORD* rgElements );

void Create( VARTYPE vtSrc, DWORD dwDims, SAFEARRAYBOUND* rgsabounds );

Parameters

vtSrc

The base type of the array (that is, the VARTYPE of each element of the array). The VARTYPE is restricted to a subset of the variant types. Neither the VT_ARRAY nor the VT_BYREF flag can be set. VT_EMPTY and VT_NULL are not valid base types for the array. All other types are legal.

dwDims

Number of dimensions in the array. This can be changed after the array is created with Redim.

rgElements

Pointer to an array of the number of elements for each dimension in the array.

rgsabounds

Pointer to a vector of bounds (one for each dimension) to allocate for the array.

Remarks

Call this function to allocate and initialize the data for the array. This function will clear the current array data if necessary. On error, the function throws a CMemoryException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also SafeArrayCreate


COleSafeArray::CreateOneDim

void CreateOneDim( VARTYPE vtSrc, DWORD dwElements, const void* pvSrcData = NULL, long nLBound = 0 );

Parameters

vtSrc

The base type of the array (that is, the VARTYPE of each element of the array).

dwElements

Number of elements in the array. This can be changed after the array is created with ResizeOneDim.

pvSrcData

Pointer to the data to copy into the array.

nLBound

The lower bound of the array.

Remarks

Call this function to create a new one-dimensional COleSafeArray object. The function allocates and initializes the data for the array, copying the specified data if the pointer pvSrcData is not NULL.

On error, the function throws a CMemoryException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::GetOneDimSize, COleSafeArray::ResizeOneDim, COleSafeArray::Create


COleSafeArray::Destroy

void Destroy( );

Remarks

Call this function to destroy an existing array descriptor and all the data in the array. If objects are stored in the array, each object is released. On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::DestroyData, COleSafeArray::DestroyDescriptor, SafeArrayDestroy


COleSafeArray::DestroyData

void DestroyData( );

Remarks

Call this function to destroy all the data in a safe array. If objects are stored in the array, each object is released. On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Destroy, COleSafeArray::DestroyDescriptor, SafeArrayDestroyData


COleSafeArray::DestroyDescriptor

void DestroyDescriptor( );

Remarks

Call this function to destroy a descriptor of a safe array. On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Destroy, COleSafeArray::DestroyData, SafeArrayDestroyDescriptor


COleSafeArray::Detach

VARIANT Detach( );

Return Value

The underlying VARIANT value in the COleSafeArray object.

Remarks

Call this function to detach the VARIANT data from the COleSafeArray object. The function detaches the data in a safe array by setting the VARTYPE of the object to VT_EMPTY. It is the caller's responsibility to free the array by calling the Windows function VariantClear.

On error, the function throws a COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Attach, VariantClear


COleSafeArray::GetDim

DWORD GetDim( );

Return Value

The number of dimensions in the safe array.

Remarks

Call this function to return the number of dimensions in the COleSafeArray object.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Create, COleSafeArray::Redim, SafeArrayGetDim


COleSafeArray::GetElement

void GetElement( long* rgIndices, void* pvData );

Parameters

rgIndices

Pointer to an array of indexes for each dimension of the array.

pvData

Pointer to the location to place the element of the array.

Remarks

Call this function to retrieve a single element of the safe array. This function automatically calls the windows functions SafeArrayLock and SafeArrayUnlock before and after retrieving the element. If the data element is a string, object, or variant, the function copies the element in the correct way. The parameter pvData should point to a large enough buffer to contain the element.

On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::PutElement, SafeArrayGetElement


COleSafeArray::GetElemSize

DWORD GetElemSize( );

Return Value

The size, in bytes, of the elements of a safe array.

Remarks

Call this function to retrieve the size of an element in a COleSafeArray object.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::GetDim, SafeArrayGetElemSize


COleSafeArray::GetLBound

void GetLBound( DWORD dwDim, long* pLBound );

Parameters

dwDim

The array dimension for which to get the lower bound.

pLBound

Pointer to the location to return the lower bound.

Remarks

Call this function to return the lower bound for any dimension of a COleSafeArray object. On error, the function throws a COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::GetUBound, SafeArrayGetLBound


COleSafeArray::GetOneDimSize

DWORD GetOneDimSize( );

Return Value

The number of elements in the one-dimensional safe array.

Remarks

Call this function to return the number of elements in the one-dimensional COleSafeArray object.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::CreateOneDimSize, COleSafeArray::ResizeOneDim, SafeArrayRedim


COleSafeArray::GetUBound

void GetUBound( DWORD dwDim, long* pUBound );

Parameters

dwDim

The array dimension for which to get the upper bound.

pUBound

Pointer to the location to return the upper bound.

Remarks

Call this function to return the upper bound for any dimension of a safe array. On error, the function throws a COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::GetLBound, SafeArrayGetUBound


COleSafeArray::Lock

void Lock( );

Remarks

Call this function to increment the lock count of an array and place a pointer to the array data in the array descriptor. On error, it throws a COleException.

The pointer in the array descriptor is valid until Unlock is called. Calls to Lock can be nested; an equal number of calls to Unlock are required.

An array cannot be deleted while it is locked.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Unlock, SafeArrayLock


COleSafeArray::PtrOfIndex

void PtrOfIndex( long* rgIndices, void** ppvData );

Parameters

rgIndices

An array of index values that identify an element of the array. All indexes for the element must be specified.

ppvData

On return, pointer to the element identified by the values in rgIndices.

Remarks

Call this function to return a pointer to the element specified by the index values.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also SafeArrayPtrOfIndex


COleSafeArray::PutElement

void PutElement( long* rgIndices, LPVOID pvData );

Parameters

rgIndices

Pointer to an array of indexes for each dimension of the array.

pvData

Pointer to the data to assign to the array. VT_DISPATCH, VT_UNKNOWN, and VT_BSTR variant types are pointers and do not require another level of indirection.

Remarks

Call this function to assign a single element into the array. This function automatically calls the Windows functions SafeArrayLock and SafeArrayUnlock before and after assigning the element. If the data element is a string, object, or variant, the function copies it correctly, and if the existing element is a string, object, or variant, it is cleared correctly.

Note that you can have multiple locks on an array, so you can put elements into an array while the array is locked by other operations.

On error, the function throws a CMemoryException or COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::GetElement, SafeArrayPutElement


COleSafeArray::Redim

void Redim( SAFEARRAYBOUND* psaboundNew );

Parameters

psaboundNew

Pointer to a new safe array bound structure containing the new array bound. Only the least significant dimension of an array may be changed.

Remarks

Call this function to change the least significant (rightmost) bound of a safe array. On error, the function throws a COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Create, COleSafeArray::GetDim, COleSafeArray::ResizeOneDim, SafeArrayRedim


COleSafeArray::ResizeOneDim

void ResizeOneDim( DWORD dwElements );

Parameters

dwElements

Number of elements in the one-dimensional safe array.

Remarks

Call this function to change the number of elements in a one-dimensional COleSafeArray object. On error, the function throws a COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Redim, COleSafeArray::GetOneDimSize, COleSafeArray::CreateOneDim, SafeArrayRedim


COleSafeArray::UnaccessData

void UnaccessData( );

Remarks

Call this function to decrement the lock count of an array and invalidate the pointer retrieved by AccessData. On error, the function throws a COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::AccessData, SafeArrayUnaccessData


COleSafeArray::Unlock

void Unlock( );

Remarks

Call this function to decrement the lock count of an array so it can be freed or resized. This function is called after access to the data in an array is finished. On error, it throws a COleException.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also COleSafeArray::Lock, SafeArrayUnlock


COleSafeArray::operator =

COleSafeArray& operator =( const COleSafeArray& saSrc );

COleSafeArray& operator =( const VARIANT& varSrc );

COleSafeArray& operator =( LPCVARIANT pSrc );

COleSafeArray& operator =( const COleVariant& varSrc );

Remarks

These overloaded assignment operators copy the source value into this COleSafeArray object. A brief description of each operator follows:

  • operator =( saSrc ) Copies an existing COleSafeArray object into this object.

  • operator =( varSrc ) Copies an existing VARIANT or COleVariant array into this object.

  • operator =( pSrc ) Copies the VARIANT array object accessed by pSrc into this object.

COleSafeArray Overview | Class Members | Hierarchy Chart

See Also VariantCopy


COleSafeArray::operator ==

BOOL operator ==( const SAFEARRAY& saSrc ) const;

BOOL operator ==( LPCSAFEARRAY pSrc ) const;

BOOL operator ==( const COleSafeArray& saSrc ) const;

BOOL operator ==( const VARIANT& varSrc ) const;

BOOL operator ==( LPCVARIANT pSrc ) const;

BOOL operator ==( const COleVariant& varSrc ) const;

Remarks

This operator compares two arrays (SAFEARRAY, VARIANT, COleVariant, or COleSafeArray arrays) and returns nonzero if they are equal; otherwise 0. Two arrays are equal if they have an equal number of dimensions, equal size in each dimension, and equal element values.


COleSafeArray::operator <<

CDumpContext& AFXAPI operator<<( CDumpContext& dc, COleSafeArray& saSrc );

Remarks

The COleSafeArray insertion (<<) operator supports diagnostic dumping and storing of a COleSafeArray object to an archive.


COleSafeArray::operator LPCVARIANT

operator LPCVARIANT( ) const;

Remarks

Call this casting operator to access the underlying VARIANT structure for this COleSafeArray object.


COleSafeArray::operator LPVARIANT

operator LPVARIANT( );

Remarks

Call this casting operator to access the underlying VARIANT structure for this COleSafeArray object.

Note that changing the value in the VARIANT structure accessed by the pointer returned by this function will change the value of this COleSafeArray object.


COleServerDoc

COleServerDoc is the base class for OLE server documents. A server document can contain COleServerItem objects, which represent the server interface to embedded or linked items. When a server application is launched by a container to edit an embedded item, the item is loaded as its own server document; the COleServerDoc object contains just one COleServerItem object, consisting of the entire document. When a server application is launched by a container to edit a linked item, an existing document is loaded from disk; a portion of the document’s contents is highlighted to indicate the linked item.

COleServerDoc objects can also contain items of the COleClientItem class. This allows you to create container-server applications. The framework provides functions to properly store the COleClientItem items while servicing the COleServerItem objects.

If your server application does not support links, a server document will always contain only one server item, which represents the entire embedded object as a document. If your server application does support links, it must create a server item each time a selection is copied to the Clipboard.

To use COleServerDoc, derive a class from it and implement the OnGetEmbeddedItem member function, which allows your server to support embedded items. Derive a class from COleServerItem to implement the items in your documents, and return objects of that class from OnGetEmbeddedItem.

To support linked items, COleServerDoc provides the OnGetLinkedItem member function. You can use the default implementation or override it if you have your own way of managing document items.

You need one COleServerDoc-derived class for each type of server document your application supports. For example, if your server application supports worksheets and charts, you need two COleServerDoc-derived classes.

For more information on servers, see the article Servers: Implementing a Server in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HIERSVR | MFC Sample BINDSCRB

See Also COleDocument, COleLinkingDoc, COleTemplateServer


COleServerDoc Class Members

Construction
Attributes
Operations
Overridables

Construction |
COleServerDoc | Constructs a COleServerDoc object.

Attributes |
IsEmbedded | Indicates whether the document is embedded in a container document or running stand-alone.
IsInPlaceActive | Returns TRUE if the item is currently activated in place.
GetEmbeddedItem | Returns a pointer to an item representing the entire document.
GetItemPosition | Returns the current position rectangle, relative to the container application’s client area, for in-place editing.
GetItemClipRect | Returns the current clipping rectangle for in-place editing.
GetZoomFactor | Returns the zoom factor in pixels.

Operations

OnExecOleCmd | Executes a specified command or displays help for the command.
NotifyChanged | Notifies containers that the user has changed the document.
NotifyRename | Notifies containers that the user has renamed the document.
NotifySaved | Notifies containers that the user has saved the document.
NotifyClosed | Notifies containers that the user has closed the document.
SaveEmbedding | Tells the container application to save the document.
ActivateInPlace | Activates the document for in-place editing.
DeactivateAndUndo | Deactivates the server’s user interface.
DiscardUndoState | Discards undo-state information.
RequestPositionChange | Changes the position of the in-place editing frame.
ScrollContainerBy | Scrolls the container document.
UpdateAllItems | Notifies containers that the user has changed the document.

Overridables

GetDocObjectServer | Override this function to create a new CDocObjectServer object and indicate that this document is a DocObject container.
OnUpdateDocument | Called by the framework when a server document that is an embedded item is saved, updating the container’s copy of the item.
OnGetEmbeddedItem | Called to get a COleServerItem that represents the entire document; used to get an embedded item. Implementation required.
OnClose | Called by the framework when a container requests to close the document.
OnSetHostNames | Called by the framework when a container sets the window title for an embedded object.
OnShowDocument | Called by the framework to show or hide the document.
OnDeactivate | Called by the framework when the user deactivates an item that was activated in place.
OnDeactivateUI | Called by the framework to destroy controls and other user-interface elements created for in-place activation.
OnSetItemRects | Called by the framework to position the in-place editing frame window within the container application’s window.
OnReactivateAndUndo | Called by the framework to undo changes made during in-place editing.
OnFrameWindowActivate | Called by the framework when the container’s frame window is activated or deactivated.
OnDocWindowActivate | Called by the framework when the container’s document frame window is activated or deactivated.
OnShowControlBars | Called by the framework to show or hide control bars for in-place editing.
OnResizeBorder | Called by the framework when the container application’s frame window or document window is resized.
CreateInPlaceFrame | Called by the framework to create a frame window for in-place editing.
DestroyInPlaceFrame | Called by the framework to destroy a frame window for in-place editing.


COleServerDoc::ActivateInPlace

BOOL ActivateInPlace( );

Return Value

Nonzero if successful; otherwise 0, which indicates that the item is fully open.

Remarks

Activates the item for in-place editing.

This function performs all operations necessary for in-place activation. It creates an in-place frame window, activates it and sizes it to the item, sets up shared menus and other controls, scrolls the item into view, and sets the focus to the in-place frame window.

This function is called by the default implementation of COleServerItem::OnShow. Call this function if your application supports another verb for in-place activation (such as Play).

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnShow


COleServerDoc::COleServerDoc

COleServerDoc( );

Remarks

Constructs a COleServerDoc object without connecting with the OLE system DLLs. You must call COleLinkingDoc::Register to open communications with OLE. If you are using COleTemplateServer in your application, COleLinkingDoc::Register is called for you by COleLinkingDoc’s implementation of OnNewDocument, OnOpenDocument, and OnSaveDocument.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleLinkingDoc::Register


COleServerDoc::DeactivateAndUndo

BOOL DeactivateAndUndo( );

Return Value

Nonzero on success; otherwise 0.

Remarks

Call this function if your application supports Undo and the user chooses Undo after activating an item but before editing it. If the container application is written using the Microsoft Foundation Class Library, calling this function causes COleClientItem::OnDeactivateAndUndo to be called, which deactivates the server’s user interface.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnDeactivateAndUndo


COleServerDoc::CreateInPlaceFrame

virtual COleIPFrameWnd* CreateInPlaceFrame( CWnd* pParentWnd );

Return Value

A pointer to the in-place frame window, or NULL if unsuccessful.

Parameters

pParentWnd

Pointer to the container application’s parent window.

Remarks

The framework calls this function to create a frame window for in-place editing. The default implementation uses information specified in the document template to create the frame. The view used is the first view created for the document. This view is temporarily detached from the original frame and attached to the newly created frame.

This is an advanced overridable.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::DestroyInPlaceFrame


COleServerDoc::DestroyInPlaceFrame

virtual void DestroyInPlaceFrame( COleIPFrameWnd* pFrame );

Parameters

pFrame

Pointer to the in-place frame window to be destroyed.

Remarks

The framework calls this function to destroy an in-place frame window and return the server application’s document window to its state before in-place activation.

This is an advanced overridable.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::CreateInPlaceFrame


COleServerDoc::DiscardUndoState

BOOL DiscardUndoState( );

Return Value

Nonzero on success; otherwise 0.

Remarks

If the user performs an editing operation that cannot be undone, call this function to force the container application to discard its undo-state information.

This function is provided so that servers that support Undo can free resources that would otherwise be consumed by undo-state information that cannot be used.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::OnReactivateAndUndo


COleServerDoc::GetDocObjectServer

virtual CDocObjectServer* GetDocObjectServer( LPOLEDOCUMENTSITE pSite );

Return Value

A pointer to a CDocObjectServer; NULL if the operation failed.

Parameters

pSite

Pointer to the IOleDocumentSite interface that will connect this document to the server.

Remarks

Override this function to create a new CDocObjectServer item and return a pointer to it. When a DocObject server is activated, the return of a non-NULL pointer shows that the client can support DocObjects. The default implementation returns NULL.

A typical implementation for a document that supports DocObjects will simply allocate a new CDocObjectServer object and return it to the caller. For example:

CDocObjectServer* COleServerDoc::GetDocObjectServer(LPOLEDOCUMENTSITE pSite)
{
   return new CDocObjectServer(this, pSite);
}

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also CDocObjectServer::CDocObjectServer


COleServerDoc::GetEmbeddedItem

COleServerItem* GetEmbeddedItem( );

Return Value

A pointer to an item representing the entire document; NULL if the operation failed.

Remarks

Call this function to get a pointer to an item representing the entire document. It calls COleServerDoc::OnGetEmbeddedItem, a virtual function with no default implementation.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::OnGetEmbeddedItem


COleServerDoc::GetItemClipRect

void GetItemClipRect( LPRECT lpClipRect ) const;

Parameters

lpClipRect

Pointer to a RECT structure or a CRect object to receive the clipping-rectangle coordinates of the item.

Remarks

Call the GetItemClipRect member function to get the clipping-rectangle coordinates of the item that is being edited in place. Coordinates are in pixels relative to the container application window’s client area.

Drawing should not occur outside the clipping rectangle. Usually, drawing is automatically restricted. Use this function to determine whether the user has scrolled outside the visible portion of the document; if so, scroll the container document as needed by means of a call to ScrollContainerBy.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::GetItemPosition, COleServerDoc::ScrollContainerBy


COleServerDoc::GetItemPosition

void GetItemPosition( LPRECT lpPosRect ) const;

Parameters

lpPosRect

Pointer to a RECT structure or a CRect object to receive the coordinates of the item.

Remarks

Call the GetItemPosition member function to get the coordinates of the item being edited in place. Coordinates are in pixels relative to the container application window’s client area.

The item’s position can be compared with the current clipping rectangle to determine the extent to which the item is visible (or not visible) on the screen.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::GetItemClipRect


COleServerDoc::GetZoomFactor

BOOL GetZoomFactor( LPSIZE lpSizeNum = NULL, LPSIZE lpSizeDenom = NULL, LPCRECT lpPosRect = NULL ) const;

Return Value

Nonzero if the item is activated for in-place editing and its zoom factor is other than 100% (1:1); otherwise 0.

Parameters

lpSizeNum

Pointer to an object of class CSize that will hold the zoom factor’s numerator. Can be NULL.

lpSizeDenom

Pointer to an object of class CSize that will hold the zoom factor’s denominator. Can be NULL.

lpPosRect

Pointer to an object of class CRect that describes the item’s new position. If this argument is NULL, the function uses the item’s current position.

Remarks

The GetZoomFactor member function determines the “zoom factor” of an item that has been activated for in-place editing. The zoom factor, in pixels, is the proportion of the item’s size to its current extent. If the container application has not set the item’s extent, its natural extent (as determined by COleServerItem::OnGetExtent) is used.

The function sets its first two arguments to the numerator and denominator of the item’s “zoom factor.” If the item is not being edited in place, the function sets these arguments to a default value of 100% (or 1:1) and returns zero. For further information, see Technical Note 40, MFC/OLE In-Place Resizing and Zooming.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::GetItemPosition, COleServerDoc::GetItemClipRect, COleServerDoc::OnSetItemRects


COleServerDoc::IsEmbedded

BOOL IsEmbedded( ) const;

Return Value

Nonzero if the COleServerDoc object is a document that represents an object embedded in a container; otherwise 0.

Remarks

Call the IsEmbedded member function to determine whether the document represents an object embedded in a container. A document loaded from a file is not embedded although it may be manipulated by a container application as a link. A document which is an embedding in a container document is considered to be embedded.


COleServerDoc::IsInPlaceActive

BOOL IsInPlaceActive( ) const;

Return Value

Nonzero if the COleServerDoc object is active in place; otherwise 0.

Remarks

Call the IsInPlaceActive member function to determine whether the item is currently in the in-place active state.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnActivate, COleServerDoc::OnReactivateAndUndo, COleServerDoc::ActivateInPlace


COleServerDoc::NotifyChanged

void NotifyChanged( );

Remarks

Call this function to notify all linked items connected to the document that the document has changed. Typically, you call this function after the user changes some global attribute such as the dimensions of the server document. If an OLE item is linked to the document with an automatic link, the item is updated to reflect the changes. In container applications written with the Microsoft Foundation Class Library, the OnChange member function of COleClientItem is called.

Note This function is included for compatibility with OLE 1. New applications should use UpdateAllItems.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also OleServerDoc::NotifyClosed, COleServerDoc::NotifySaved, COleClientItem::OnChange


COleServerDoc::NotifyClosed

void NotifyClosed( );

Remarks

Call this function to notify the container(s) that the document has been closed. When the user chooses the Close command from the File menu, NotifyClosed is called by COleServerDoc’s implementation of the OnCloseDocument member function. In container applications written with the Microsoft Foundation Class Library, the OnChange member function of COleClientItem is called.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::NotifyChanged, COleServerDoc::NotifySaved, COleClientItem::OnChange, CDocument::OnCloseDocument


COleServerDoc::NotifyRename

void NotifyRename( LPCTSTR lpszNewName );

Parameters

lpszNewName

Pointer to a string specifying the new name of the server document; this is typically a fully qualified path.

Remarks

Call this function after the user renames the server document. When the user chooses the Save As command from the File menu, NotifyRename is called by COleServerDoc’s implementation of the OnSaveDocument member function. This function notifies the OLE system DLLs, which in turn notify the containers. In container applications written with the Microsoft Foundation Class Library, the OnChange member function of COleClientItem is called.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::NotifySaved, CDocument::OnSaveDocument


COleServerDoc::NotifySaved

void NotifySaved( );

Remarks

Call this function after the user saves the server document. When the user chooses the Save command from the File menu, NotifySaved is called for you by COleServerDoc’s implementation of OnSaveDocument. This function notifies the OLE system DLLs, which in turn notify the containers. In container applications written with the Microsoft Foundation Class Library, the OnChange member function of COleClientItem is called.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::NotifyChanged, COleServerDoc::NotifyClosed, COleClientItem::OnChange, CDocument::OnSaveDocument


COleServerDoc::OnClose

virtual void OnClose( OLECLOSE dwCloseOption );

Parameters

dwCloseOption

A value from the enumeration OLECLOSE. This parameter can have one of the following values:

  • OLECLOSE_SAVEIFDIRTY The file is saved if it has been modified.

  • OLECLOSE_NOSAVE The file is closed without being saved.

  • OLECLOSE_PROMPTSAVE If the file has been modified, the user is prompted about saving it.

Remarks

Called by the framework when a container requests that the server document be closed. The default implementation calls CDocument::OnCloseDocument.

For more information and additional values, see OLECLOSE in the OLE documentation.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleException, CDocument::OnCloseDocument


COleServerDoc::OnDeactivate

virtual void OnDeactivate( );

Remarks

Called by the framework when the user deactivates an embedded or linked item that is currently in-place active. This function restores the container application’s user interface to its original state and destroys any menus and other controls that were created for in-place activation.

The undo state information should be unconditionally released at this point.

For more information, see the article Activation in Visual C++ Programmer’s Guide.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::ActivateInPlace, COleServerDoc::OnDeactivateUI, COleServerDoc::DestroyInPlaceFrame


COleServerDoc::OnDeactivateUI

virtual void OnDeactivateUI( BOOL bUndoable );

Parameters

bUndoable

Specifies whether the editing changes can be undone.

Remarks

Called when the user deactivates an item that was activated in place. This function restores the container application’s user interface to its original state, hiding any menus and other controls that were created for in-place activation.

The framework always sets bUndoable to FALSE. If the server supports undo and there is an operation that can be undone, call the base-class implementation with bUndoable set to TRUE.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::OnDeactivate


COleServerDoc::OnDocWindowActivate

virtual void OnDocWindowActivate( BOOL bActivate );

Parameters

bActivate

Specifies whether the document window is to be activated or deactivated.

Remarks

The framework calls this function to activate or deactivate a document window for in-place editing. The default implementation removes or adds the frame-level user interface elements as appropriate. Override this function if you want to perform additional actions when the document containing your item is activated or deactivated.

For more information, see the article Activation in Visual C++ Programmer’s Guide.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::ActivateInPlace, COleServerDoc::OnReactivateAndUndo, COleServerDoc::OnShowControlBars, COleServerDoc::OnDeactivateUI, COleServerDoc::OnFrameWindowActivate, COleIPFrameWnd


COleServerDoc::OnExecOleCmd

HRESULT OnExecOleCmd( const GUID* pGroup, DWORD nCmdID, DWORD nCmdExecOut, VARIANTARG* pvaIn, VARIANTARG* pvaOut );

Return Value

Returns S_OK if successful; otherwise, one of the following error codes:

Value | Description
E_UNEXPECTED | Unexpected error occurred
E_FAIL | Error occurred
E_NOTIMPL | Indicates MFC itself should attempt to translate and dispatch the command
OLECMDERR_E_UNKNOWNGROUP | pGroup is non-NULL but does not specify a recognized command group
OLECMDERR_E_NOTSUPPORTED | nCmdID is not recognized as a valid command in the group pGroup
OLECMDERR_DISABLED | The command identified by nCmdID is disabled and cannot be executed
OLECMDERR_NOHELP | Caller asked for help on the command identified by nCmdID but no help is available
OLECMDERR_CANCELED | User canceled the execution

Parameters

pGroup

A pointer to a GUID that identifies a set of commands. Can be NULL to indicate the default command group.

nCmdID

The command to execute. Must be in the group identified by pGroup.

nCmdExecOut

The way the object should execute the command, one or more of the following values from the OLECMDEXECOPT enumeration:

OLECMDEXECOPT_DODEFAULT

OLECMDEXECOPT_PROMPTUSER

OLECMDEXECOPT_DONTPROMPTUSER

OLECMDEXECOPT_SHOWHELP

pvaIn

Pointer to a VARIANTARG containing input arguments for the command. Can be NULL.

pvaOut

Pointer to a VARIANTARG to receive the output return values from the command. Can be NULL.

Remarks

The framework calls this function to execute a specified command or display help for the command.

COleCmdUI can be used to enable, update, and set other properties of DocObject user interface commands. After the commands are initialized, you can execute them with OnExecOleCmd.

The framework calls the function before attempting to translate and dispatch an OLE document command. You don't need to override this function to handle standard OLE document commands, but you must supply an override to this function if you want to handle your own custom commands or handle commands that accept parameters or return results.

Most of the commands do not take arguments or return values. For a majority of commands the caller can pass NULLs for pvaIn and pvaOut. For commands that expect input values, the caller can declare and initialize a VARIANTARG variable and pass a pointer to the variable in pvaIn. For commands that require a single value, the argument can be stored directly in the VARIANTARG and passed to the function. Multiple arguments must be packaged within the VARIANTARG using one of the supported types (such as IDispatch and SAFEARRAY ).

Similarly, if a command returns arguments the caller is expected to declare a VARIANTARG, initialize it to VT_EMPTY, and pass its address in pvaOut. If a command returns a single value, the object can store that value directly in pvaOut. Multiple output values must be packaged in some way appropriate for the VARIANTARG.

The base-class implementation of this function will walk the OLE_COMMAND_MAP structures associated with the command target and try to dispatch the command to an appropriate handler. The base-class implementation works only with commands that do not accept arguments or return values. If you need to handle commands that do accept arguments or return values, you must override this function and work with the pvaIn and pvaOut parameters yourself.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleCmdUI


COleServerDoc::OnFrameWindowActivate

virtual void OnFrameWindowActivate( BOOL bActivate );

Parameters

bActivate

Specifies whether the frame window is to be activated or deactivated.

Remarks

The framework calls this function when the container application’s frame window is activated or deactivated.

The default implementation cancels any help modes the frame window might be in. Override this function if you want to perform special processing when the frame window is activated or deactivated.

For more information, see the article Activation in Visual C++ Programmer’s Guide.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::OnDocWindowActivate


COleServerDoc::OnGetEmbeddedItem

virtual COleServerItem* OnGetEmbeddedItem( ) = 0;

Return Value

A pointer to an item representing the entire document; NULL if the operation failed.

Remarks

Called by the framework when a container application calls the server application to create or edit an embedded item. There is no default implementation. You must override this function to return an item that represents the entire document. This return value should be an object of a COleServerItem-derived class.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleLinkingDoc::OnGetLinkedItem, COleServerItem


COleServerDoc::OnReactivateAndUndo

virtual BOOL OnReactivateAndUndo( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

The framework calls this function when the user chooses to undo changes made to an item that has been activated in place, changed, and subsequently deactivated. The default implementation does nothing except return FALSE to indicate failure.

Override this function if your application supports undo. Usually you would perform the undo operation, then activate the item by calling ActivateInPlace. If the container application is written with the Microsoft Foundation Class Library, calling COleClientItem::ReactivateAndUndo causes this function to be called.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::ActivateInPlace, COleServerDoc::IsInPlaceActive, COleClientItem::ReactivateAndUndo


COleServerDoc::OnResizeBorder

virtual void OnResizeBorder( LPCRECT lpRectBorder, LPOLEINPLACEUIWINDOW lpUIWindow, BOOL bFrame );

Parameters

lpRectBorder

Pointer to a RECT structure or a CRect object that specifies the coordinates of the border.

lpUIWindow

Pointer to an object of class IOleInPlaceUIWindow that owns the current in-place editing session.

bFrame

TRUE if lpUIWindow points to the container application’s top-level frame window, or FALSE if lpUIWindow points to the container application’s document-level frame window.

Remarks

The framework calls this function when the container application’s frame windows change size. This function resizes and adjusts toolbars and other user-interface elements in accordance with the new window size.

For more information, see IOleInPlaceUIWindow in the OLE documentation.

This is an advanced overridable.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::OnShowControlBars


COleServerDoc::OnSetHostNames

virtual void OnSetHostNames( LPCTSTR lpszHost, LPCTSTR lpszHostObj );

Parameters

lpszHost

Pointer to a string that specifies the name of the container application.

lpszHostObj

Pointer to a string that specifies the container’s name for the document.

Remarks

Called by the framework when the container sets or changes the host names for this document. The default implementation changes the document title for all views referring to this document.

Override this function if your application sets the titles through a different mechanism.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleClientItem::SetHostNames


COleServerDoc::OnSetItemRects

virtual void OnSetItemRects( LPCRECT lpPosRect, LPCRECT lpClipRect );

Parameters

lpPosRect

Pointer to a RECT structure or a CRect object that specifies the in-place frame window’s position relative to the container application’s client area.

lpClipRect

Pointer to a RECT structure or a CRect object that specifies the in-place frame window’s clipping rectangle relative to the container application’s client area.

Remarks

The framework calls this function to position the in-place editing frame window within the container application’s frame window. Override this function to update the view’s zoom factor, if necessary.

This function is usually called in response to a RequestPositionChange call, although it can be called at any time by the container to request a position change for the in-place item.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::RequestPositionChange, COleIPFrameWnd::RepositionFrame, COleClientItem::SetItemRects, COleServerDoc::GetZoomFactor


COleServerDoc::OnShowControlBars

virtual void OnShowControlBars( CFrameWnd *pFrameWnd, BOOL bShow );

Parameters

pFrameWnd

Pointer to the frame window whose control bars should be hidden or shown.

bShow

Determines whether control bars are shown or hidden.

Remarks

The framework calls this function to show or hide the server application’s control bars associated with the frame window identified by pFrameWnd. The default implementation enumerates all control bars owned by that frame window and hides or shows them.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::ActivateInPlace, COleServerDoc::OnReactivateAndUndo, COleServerDoc::OnFrameWindowActivate, COleServerDoc::IsInPlaceActive


COleServerDoc::OnShowDocument

virtual void OnShowDocument( BOOL bShow );

Parameters

bShow

Specifies whether the user interface to the document is to be shown or hidden.

Remarks

The framework calls the OnShowDocument function when the server document must be hidden or shown. If bShow is TRUE, the default implementation activates the server application, if necessary, and causes the container application to scroll its window so that the item is visible. If bShow is FALSE, the default implementation deactivates the item through a call to OnDeactivate, then destroys or hides all frame windows that have been created for the document, except the first one. If no visible documents remain, the default implementation hides the server application.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::ActivateInPlace, COleServerItem::OnDoVerb, COleServerDoc::IsInPlaceActive, COleServerDoc::OnDeactivateUI


COleServerDoc::OnUpdateDocument

virtual BOOL OnUpdateDocument( );

Return Value

Nonzero if the document was successfully updated; otherwise 0.

Remarks

Called by the framework when saving a document that is an embedded item in a compound document. The default implementation calls the COleServerDoc::NotifySaved and COleServerDoc::SaveEmbedding member functions and then marks the document as clean. Override this function if you want to perform special processing when updating an embedded item.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::NotifySaved, COleServerDoc::SaveEmbedding, CDocument::OnSaveDocument


COleServerDoc::RequestPositionChange

void RequestPositionChange( LPCRECT lpPosRect );

Parameters

lpPosRect

Pointer to a RECT structure or a CRect object containing the item’s new position.

Remarks

Call this member function to have the container application change the item’s position. This function is usually called (in conjunction with UpdateAllItems) when the data in an in-place active item has changed. Following this call, the container might or might not perform the change by calling OnSetItemRects. The resulting position might be different from the one requested.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::ScrollContainerBy


COleServerDoc::SaveEmbedding

void SaveEmbedding( );

Remarks

Call this function to tell the container application to save the embedded object. This function is called automatically from OnUpdateDocument. Note that this function causes the item to be updated on disk, so it is usually called only as a result of a specific user action.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::NotifyClosed


COleServerDoc::ScrollContainerBy

BOOL ScrollContainerBy( CSize sizeScroll );

Return Value

Nonzero if successful; otherwise 0.

Parameters

sizeScroll

Indicates how far the container document is to scroll.

Remarks

Call the ScrollContainerBy member function to scroll the container document by the amount, in pixels, indicated by sizeScroll. Positive values indicate scrolling down and to the right; negative values indicate scrolling up and to the left.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnScrollBy


COleServerDoc::UpdateAllItems

void UpdateAllItems( COleServerItem* pSender, LPARAM lHint = 0L, CObject* pHint = NULL, DVASPECT nDrawAspect = DVASPECT_CONTENT );

Parameters

pSender

Pointer to the item that modified the document, or NULL if all items are to be updated.

lHint

Contains information about the modification.

pHint

Pointer to an object storing information about the modification.

nDrawAspect

Determines how the item is to be drawn. This is a value from the DVASPECT enumeration. This parameter can have one of the following values:

  • DVASPECT_CONTENT Item is represented in such a way that it can be displayed as an embedded object inside its container.

  • DVASPECT_THUMBNAIL Item is rendered in a “thumbnail” representation so that it can be displayed in a browsing tool.

  • DVASPECT_ICON Item is represented by an icon.

  • DVASPECT_DOCPRINT Item is represented as if it were printed using the Print command from the File menu.

Remarks

Call this function to notify all linked items connected to the document that the document has changed. You typically call this function after the user changes the server document. If an OLE item is linked to the document with an automatic link, the item is updated to reflect the changes. In container applications written with the Microsoft Foundation Class Library, the OnChange member function of COleClientItem is called.

This function calls the OnUpdate member function for each of the document’s items except the sending item, passing pHint, lHint, and nDrawAspect. Use these parameters to pass information to the items about the modifications made to the document. You can encode information using lHint or you can define a CObject-derived class to store information about the modifications and pass an object of that class using pHint. Override the OnUpdate member function in your COleServerItem-derived class to optimize the updating of each item depending on whether its presentation has changed.

COleServerDoc Overview | Class Members | Hierarchy Chart

See Also COleServerDoc::NotifyChanged, COleServerItem::OnUpdate, COleServerDoc::NotifySaved, COleClientItem::OnChange


COleServerItem

The COleServerItem class provides the server interface to OLE items. A linked item can represent some or all of a server document. An embedded item always represents an entire server document.

The COleServerItem class defines several overridable member functions that are called by the OLE system dynamic-link libraries (DLLs), usually in response to requests from the container application. These member functions allow the container application to manipulate the item indirectly in various ways, such as by displaying it, executing its verbs, or retrieving its data in various formats.

To use COleServerItem, derive a class from it and implement the OnDraw and Serialize member functions. The OnDraw function provides the metafile representation of an item, allowing it to be displayed when a container application opens a compound document. The Serialize function of CObject provides the native representation of an item, allowing an embedded item to be transferred between the server and container applications. OnGetExtent provides the natural size of the item to the container, enabling the container to size the item.

For more information about servers and related topics, see the article Servers: Implementing a Server and "Creating a Container/Server Application" in the article Containers: Advanced Features. Both articles are in Visual C++ Programmer’s Guide.

#include <afxole.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HIERSVR | MFC Sample BINDSCRB

See Also COleClientItem, COleServerDoc, COleTemplateServer


COleServerItem Class Members

Status
Operations
Construction
Overridables
Data Members

Status

GetDocument | Returns the server document that contains the item.
GetItemName | Returns the name of the item. Used for linked items only.
SetItemName | Sets the name of the item. Used for linked items only.
IsConnected | Indicates whether the item is currently attached to an active container.
IsLinkedItem | Indicates whether the item represents a linked OLE item.

Operations

CopyToClipboard | Copies the item to the Clipboard.
NotifyChanged | Updates all containers with automatic link update.
DoDragDrop | Performs a drag-and-drop operation.
GetClipboardData | Gets the data source for use in data transfer (drag and drop or Clipboard).
GetEmbedSourceData | Gets the CF_EMBEDSOURCE data for an OLE item.
AddOtherClipboardData | Places presentation and conversion formats in a COleDataSource object.
GetLinkSourceData | Gets the CF_LINKSOURCE data for an OLE item.
GetObjectDescriptorData | Gets the CF_OBJECTDESCRIPTOR data for an OLE item.

Construction

COleServerItem | Constructs a COleServerItem object.
GetDataSource | Gets the object used to store conversion formats.

Overridables

OnDraw | Called when the container requests to draw the item; implementation required.
OnDrawEx | Called for specialized item drawing.
OnUpdate | Called when some portion of the document the item belongs in is changed.
OnInitFromData | Called by the framework to initialize an OLE item using the contents of the data transfer object specified.
OnGetExtent | Called by the framework to retrieve the size of the OLE item.
OnSetExtent | Called by the framework to set the size of the OLE item.
OnGetClipboardData | Called by the framework to get the data that would be copied to the Clipboard.
OnSetColorScheme | Called to set the item’s color scheme.
OnSetData | Called to set the item’s data.
OnDoVerb | Called to execute a verb.
OnQueryUpdateItems | Called to determine whether any linked items require updating.
OnRenderData | Retrieves data as part of delayed rendering.
OnRenderFileData | Retrieves data into a CFile object as part of delayed rendering.
OnRenderGlobalData | Retrieves data into an HGLOBAL as part of delayed rendering.
OnUpdateItems | Called to update the presentation cache of all items in the server document.
OnOpen | Called by the framework to display the OLE item in its own top-level window.
OnShow | Called when the container requests to show the item.
OnHide | Called by the framework to hide the OLE item.

Data Members

m_sizeExtent Informs the server about how much of the OLE item is visible.


COleServerItem::AddOtherClipboardData

void AddOtherClipboardData( COleDataSource* pDataSource );

Parameters

pDataSource

Pointer to the COleDataSource object in which the data should be placed.

Remarks

Call this function to place the presentation and conversion formats for the OLE item in the specified COleDataSource object. You must have implemented the OnDraw member function to provide the presentation format (a metafile picture) for the item. To support other conversion formats, register them using the COleDataSource object returned by GetDataSource and override the OnRenderData member function to provide data in the formats you want to support.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource, COleServerItem::GetDataSource, COleServerItem::GetEmbedSourceData, COleServerItem::OnDraw


COleServerItem::COleServerItem

COleServerItem( COleServerDoc* pServerDoc, BOOL bAutoDelete );

Parameters

pServerDoc

Pointer to the document that will contain the new item.

bAutoDelete

Flag indicating whether the object can be deleted when a link to it is released. Set this to FALSE if the COleServerItem object is an integral part of your document’s data which you must delete. Set this to TRUE if the object is a secondary structure used to identify a range in your document’s data that can be deleted by the framework.

Remarks

Constructs a COleServerItem object and adds it to the server document’s collection of document items.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleDocument::AddItem


COleServerItem::CopyToClipboard

void CopyToClipboard( BOOL bIncludeLink = FALSE );

Parameters

bIncludeLink

Set this to TRUE if link data should be copied to the Clipboard. Set this to FALSE if your server application does not support links.

Remarks

Call this function to copy the OLE item to the Clipboard. The function uses the OnGetClipboardData member function to create a COleDataSource object containing the OLE item’s data in the formats supported. The function then places the COleDataSource object on the Clipboard by using the COleDataSource::SetClipboard function. The COleDataSource object includes the item’s native data and its representation in CF_METAFILEPICT format, as well as data in any conversion formats you choose to support. You must have implemented Serialize and OnDraw for this member function to work.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource::SetClipboard, COleDataSource, COleServerItem::AddOtherClipboardData, COleServerItem::GetClipboardData, COleServerItem::OnDraw, CObject::Serialize


COleServerItem::DoDragDrop

DROPEFFECT DoDragDrop( LPCRECT lpItemRect, CPoint ptOffset, BOOL bIncludeLink = FALSE, DWORD dwEffects = DROPEFFECT_COPY | DROPEFFECT_MOVE, LPCRECT lpRectStartDrag = NULL );

Return Value

A value from the DROPEFFECT enumeration. If it is DROPEFFECT_MOVE, the original data should be removed.

Parameters

lpItemRect

The item’s rectangle on screen, in pixels, relative to the client area.

ptOffset

The offset from lpItemRect where the mouse position was at the time of the drag.

bIncludeLink

Set this to TRUE if link data should be copied to the Clipboard. Set it to FALSE if your application does not support links.

dwEffects

Determines the effects that the drag source will allow in the drag operation (a combination of Copy, Move, and Link).

lpRectStartDrag

Pointer to the rectangle that defines where the drag actually starts. For more information, see the following Remarks section.

Remarks

Call the DoDragDrop member function to perform a drag-and-drop operation. The drag-and-drop operation does not start immediately. It waits until the mouse cursor leaves the rectangle specified by lpRectStartDrag or until a specified number of milliseconds have passed. If lpRectStartDrag is NULL, a default rectangle is used so that the drag starts when the mouse cursor moves one pixel.

The delay time is specified by a registry key setting. You can change the delay time by calling CWinApp::WriteProfileString or CWinApp::WriteProfileInt. If you do not specify the delay time, a default value of 200 milliseconds is used. Drag delay time is stored as follows:

  • Windows NT Drag delay time is stored in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\NT\CurrentVersion\IniFileMapping\win.ini\Windows\DragDelay.

  • Windows 3.x Drag delay time is stored in the WIN.INI file, under the [Windows} section.

  • Windows 95 Drag delay time is stored in a cached version of WIN.INI.

For more information about how drag delay information is stored in either the registry or the .INI file, see ::WriteProfileString in the Platform SDK.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource::DoDragDrop, COleServerItem::CopyToClipboard


COleServerItem::GetClipboardData

void GetClipboardData( COleDataSource* pDataSource, BOOL bIncludeLink = FALSE, LPPOINT lpOffset = NULL, LPSIZE lpSize = NULL );

Parameters

pDataSource

Pointer to the COleDataSource object that will receive the OLE item’s data in all supported formats.

bIncludeLink

TRUE if link data should be copied to the Clipboard. FALSE if your server application does not support links.

lpOffset

The offset, in pixels, of the mouse cursor from the origin of the object.

lpSize

The size of the object in pixels.

Remarks

Call this function to fill the specified COleDataSource object with all the data that would be copied to the Clipboard if you called CopyToClipboard (the same data would also be transferred if you called DoDragDrop). This function calls the GetEmbedSourceData member function to get the native data for the OLE item and calls the AddOtherClipboardData member function to get the presentation format and any supported conversion formats. If bIncludeLink is TRUE, the function also calls GetLinkSourceData to get the link data for the item.

Override this function if you want to put formats in a COleDataSource object before or after those formats supplied by CopyToClipboard.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource, COleServerItem::AddOtherClipboardData, COleServerItem::CopyToClipboard, COleServerItem::DoDragDrop, COleServerItem::GetEmbedSourceData, COleServerItem::GetLinkSourceData


COleServerItem::GetDataSource

COleDataSource* GetDataSource( );

Return Value

A pointer to the COleDataSource object used to store the conversion formats.

Remarks

Call this function to get the COleDataSource object used to store the conversion formats that the server application supports. If you want your server application to offer data in a variety of formats during data transfer operations, register those formats with the COleDataSource object returned by this function. For example, if you want to supply a CF_TEXT representation of the OLE item for Clipboard or drag-and-drop operations, you would register the format with the COleDataSource object this function returns, and then override the OnRenderXxxData member function to provide the data.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource, COleDataSource::DelayRenderData, COleServerItem::CopyToClipboard, COleServerItem::DoDragDrop, COleServerItem::OnRenderData, COleServerItem::OnRenderFileData, COleServerItem::OnRenderGlobalData


COleServerItem::GetDocument

COleServerDoc* GetDocument( ) const;

Return Value

A pointer to the document that contains the item; NULL if the item is not part of a document.

Remarks

Call this function to get a pointer to the document that contains the item. This allows access to the server document that you passed as an argument to the COleServerItem constructor.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::COleServerItem, COleServerDoc


COleServerItem::GetEmbedSourceData

void GetEmbedSourceData( LPSTGMEDIUM lpStgMedium );

Parameters

lpStgMedium

Pointer to the STGMEDIUM structure that will receive the CF_EMBEDSOURCE data for the OLE item.

Remarks

Call this function to get the CF_EMBEDSOURCE data for an OLE item. This format includes the item’s native data. You must have implemented the Serialize member function for this function to work properly.

The result can then be added to a data source by using COleDataSource::CacheData. This function is called automatically by COleServerItem::OnGetClipboardData.

For more information, see STGMEDIUM in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::GetLinkSourceData, COleServerItem::GetObjectDescriptorData, COleDataSource::CacheData, CObject::Serialize


COleServerItem::GetItemName

const CString& GetItemName( ) const;

Return Value

The name of the item.

Remarks

Call this function to get the name of the item. You typically call this function only for linked items.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::SetItemName, COleLinkingDoc::OnGetLinkedItem


COleServerItem::GetLinkSourceData

BOOL GetLinkSourceData( LPSTGMEDIUM lpStgMedium );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpStgMedium

Pointer to the STGMEDIUM structure that will receive the CF_LINKSOURCE data for the OLE item.

Remarks

Call this function to get the CF_LINKSOURCE data for an OLE item. This format includes the CLSID describing the type of the OLE item and the information needed to locate the document containing the OLE item.

The result can then be added to a data source with COleDataSource::CacheData. This function is called automatically by OnGetClipboardData.

For more information, see STGMEDIUM in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::GetEmbedSourceData, COleServerItem::GetObjectDescriptorData


COleServerItem::GetObjectDescriptorData

void GetObjectDescriptorData( LPPOINT* lpOffset, LPSIZE* lpSize, LPSTGMEDIUM lpStgMedium );

Parameters

lpOffset

Offset of the mouse click from the upper-left corner of the OLE item. Can be NULL.

lpSize

Size of the OLE item. Can be NULL.

lpStgMedium

Pointer to the STGMEDIUM structure that will receive the CF_OBJECTDESCRIPTOR data for the OLE item.

Remarks

Call this function to get the CF_OBJECTDESCRIPTOR data for an OLE item. The information is copied into the STGMEDIUM structure pointed to by lpStgMedium. This format includes the information needed for the Paste Special dialog.

For more information, see STGMEDIUM in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::AddOtherClipboardData, COleServerItem::GetEmbedSourceData, COleServerItem::GetLinkSourceData, COlePasteSpecialDialog


COleServerItem::IsConnected

BOOL IsConnected( ) const;

Return Value

Nonzero if the item is connected; otherwise 0.

Remarks

Call this function to see if the OLE item is connected. An OLE item is considered connected if one or more containers have references to the item. An item is connected if its reference count is greater than 0 or if it is an embedded item.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::IsLinkedItem, COleLinkingDoc::OnGetLinkedItem


COleServerItem::IsLinkedItem

BOOL IsLinkedItem( ) const;

Return Value

Nonzero if the item is a linked item; otherwise 0.

Remarks

Call this function to see if the OLE item is a linked item. An item is linked if the item is valid and is not returned in the document’s list of embedded items. A linked item might or might not be connected to a container.

It is common to use the same class for both linked and embedded items. IsLinkedItem allows you to make linked items behave differently than embedded items, although many times the code is common.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::IsConnected, COleLinkingDoc::OnGetLinkedItem


COleServerItem::NotifyChanged

void NotifyChanged( DVASPECT nDrawAspect = DVASPECT_CONTENT );

Parameters

nDrawAspect

A value from the DVASPECT enumeration that indicates which aspect of the OLE item has changed. This parameter can have any of the following values:

  • DVASPECT_CONTENT Item is represented in such a way that it can be displayed as an embedded object inside its container.

  • DVASPECT_THUMBNAIL Item is rendered in a “thumbnail” representation so that it can be displayed in a browsing tool.

  • DVASPECT_ICON Item is represented by an icon.

  • DVASPECT_DOCPRINT Item is represented as if it were printed using the Print command from the File menu.

Remarks

Call this function after the linked item has been changed. If a container item is linked to the document with an automatic link, the item is updated to reflect the changes. In container applications written using the Microsoft Foundation Class Library, COleClientItem::OnChange is called in response.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::OnChange, COleServerItem::OnUpdate, COleServerDoc::NotifyChanged


COleServerItem::OnDoVerb

virtual void OnDoVerb( LONG iVerb );

Parameters

iVerb

Specifies the verb to execute. It can be any one of the following:

Value | Meaning | Symbol
0 | Primary verb | OLEIVERB_PRIMARY
1 | Secondary verb | (None)
– 1 | Display item for editing | OLEIVERB_SHOW
– 2 | Edit item in separate window | OLEIVERB_OPEN
– 3 | Hide item | OLEIVERB_HIDE

The –1 value is typically an alias for another verb. If open editing is not supported, –2 has the same effect as –1. For additional values, see IOleObject::DoVerb in the OLE 2 Programmer’s Reference, Volume 1.

Remarks

Called by the framework to execute the specified verb. If the container application was written with the Microsoft Foundation Class Library, this function is called when the COleClientItem::Activate member function of the corresponding COleClientItem object is called. The default implementation calls the OnShow member function if the primary verb or OLEIVERB_SHOW is specified, OnOpen if the secondary verb or OLEIVERB_OPEN is specified, and OnHide if OLEIVERB_HIDE is specified. The default implementation calls OnShow if iVerb is not one of the verbs listed above.

Override this function if your primary verb does not show the item. For example, if the item is a sound recording and its primary verb is Play, you would not have to display the server application to play the item.

For more information, see IOleObject::DoVerb in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::Activate, COleServerItem::OnShow, COleServerItem::OnOpen, COleServerItem::OnHide


COleServerItem::OnDraw

virtual BOOL OnDraw( CDC* pDC, CSize& rSize ) = 0;

Return Value

Nonzero if the item was successfully drawn; otherwise 0.

Parameters

pDC

A pointer to the CDC object on which to draw the item. The display context is automatically connected to the attribute display context so you can call attribute functions, although doing so would make the metafile device-specific.

rSize

Size, in HIMETRIC units, in which to draw the metafile.

Remarks

Called by the framework to render the OLE item into a metafile. The metafile representation of the OLE item is used to display the item in the container application. If the container application was written with the Microsoft Foundation Class Library, the metafile is used by the Draw member function of the corresponding COleClientItem object. There is no default implementation. You must override this function to draw the item into the device context specified.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::Draw


COleServerItem::OnDrawEx

virtual BOOL OnDrawEx( CDC* pDC, DVASPECT nDrawAspect, CSize& rSize );

Return Value

Nonzero if the item was successfully drawn; otherwise 0.

Parameters

pDC

A pointer to the CDC object on which to draw the item. The DC is automatically connected to the attribute DC so you can call attribute functions, although doing so would make the metafile device-specific.

nDrawAspect

A value from the DVASPECT enumeration. This parameter can have any of the following values:

  • DVASPECT_CONTENT Item is represented in such a way that it can be displayed as an embedded object inside its container.

  • DVASPECT_THUMBNAIL Item is rendered in a “thumbnail” representation so that it can be displayed in a browsing tool.

  • DVASPECT_ICON Item is represented by an icon.

  • DVASPECT_DOCPRINT Item is represented as if it were printed using the Print command from the File menu.

rSize

Size of the item in HIMETRIC units.

Remarks

Called by the framework for all drawing. The default implementation calls OnDraw when DVASPECT is equal to DVASPECT_CONTENT; otherwise it fails.

Override this function to provide presentation data for aspects other than DVASPECT_CONTENT, such as DVASPECT_ICON or DVASPECT_THUMBNAIL.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnDraw


COleServerItem::OnGetClipboardData

virtual COleDataSource* OnGetClipboardData( BOOL bIncludeLink, LPPOINT lpOffset, LPSIZE lpSize );

Return Value

A pointer to a COleDataSource object containing the Clipboard data.

Parameters

bIncludeLink

Set this to TRUE if link data should be copied to the Clipboard. Set this to FALSE if your server application does not support links.

lpOffset

The offset of the mouse cursor from the origin of the object in pixels.

lpSize

The size of the object in pixels.

Remarks

Called by the framework to get a COleDataSource object containing all the data that would be placed on the Clipboard by a call to the CopyToClipboard member function. The default implementation of this function calls GetClipboardData.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource, COleDataSource::SetClipboard, COleServerItem::CopyToClipboard, COleServerItem::GetClipboardData


COleServerItem::OnGetExtent

virtual BOOL OnGetExtent( DVASPECT nDrawAspect, CSize& rSize );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nDrawAspect

Specifies the aspect of the OLE item whose bounds are to be retrieved. This parameter can have any of the following values:

  • DVASPECT_CONTENT Item is represented in such a way that it can be displayed as an embedded object inside its container.

  • DVASPECT_THUMBNAIL Item is rendered in a “thumbnail” representation so that it can be displayed in a browsing tool.

  • DVASPECT_ICON Item is represented by an icon.

  • DVASPECT_DOCPRINT Item is represented as if it were printed using the Print command from the File menu.

rSize

Reference to a CSize object that will receive the size of the OLE item.

Remarks

Called by the framework to retrieve the size, in HIMETRIC units, of the OLE item.

If the container application was written with the Microsoft Foundation Class Library, this function is called when the GetExtent member function of the corresponding COleClientItem object is called. The default implementation does nothing. You must implement it yourself. Override this function if you want to perform special processing when handling a request for the size of the OLE item.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::Draw, COleClientItem::GetExtent


COleServerItem::OnHide

virtual void OnHide( );

Remarks

Called by the framework to hide the OLE item. The default calls COleServerDoc::OnShowDocument( FALSE ). The function also notifies the container that the OLE item has been hidden. Override this function if you want to perform special processing when hiding an OLE item.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnOpen, COleServerItem::OnShow, COleServerDoc::OnShowDocument


COleServerItem::OnInitFromData

virtual BOOL OnInitFromData( COleDataObject* pDataObject, BOOL bCreation );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDataObject

Pointer to an OLE data object containing data in various formats for initializing the OLE item.

bCreation

TRUE if the function is called to initialize an OLE item being newly created by a container application. FALSE if the function is called to replace the contents of an already existing OLE item.

Remarks

Called by the framework to initialize an OLE item using the contents of pDataObject. If bCreation is TRUE, this function is called if a container implements Insert New Object based on the current selection. The data selected is used when creating the new OLE item. For example, when selecting a range of cells in a spreadsheet program and then using the Insert New Object to create a chart based on the values in the selected range. The default implementation does nothing. Override this function to choose an acceptable format from those offered by pDataObject and initialize the OLE item based on the data provided. This is an advanced overridable.

For more information, see IOleObject::InitFromData in the OLE 2 Programmer’s Reference, Volume 1.


COleServerItem::OnOpen

virtual void OnOpen( );

Remarks

Called by the framework to display the OLE item in a separate instance of the server application, rather than in place.

The default implementation activates the first frame window displaying the document that contains the OLE item; if the application is a mini-server, the default implementation shows the main window. The function also notifies the container that the OLE item has been opened.

Override this function if you want to perform special processing when opening an OLE item. This is especially common with linked items where you want to set the selection to the link when it is opened.

For more information, see IOleClientSite::OnShowWindow in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnShow


COleServerItem::OnQueryUpdateItems

virtual BOOL OnQueryUpdateItems( );

Return Value

Nonzero if the document has items needing updates; 0 if all items are up to date.

Remarks

Called by the framework to determine whether any linked items in the current server document are out of date. An item is out of date if its source document has been changed but the linked item has not been updated to reflect the changes in the document.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnUpdate, COleServerItem::OnUpdateItems


COleServerItem::OnRenderData

virtual BOOL OnRenderData( LPFORMATETC lpFormatEtc, LPSTGMEDIUM lpStgMedium );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

lpStgMedium

Points to a STGMEDIUM structure in which the data is to be returned.

Remarks

Called by the framework to retrieve data in the specified format. The specified format is one previously placed in the COleDataSource object using the DelayRenderData or DelayRenderFileData member function for delayed rendering. The default implementation of this function calls OnRenderFileData or OnRenderGlobalData, respectively, if the supplied storage medium is either a file or memory. If neither of these formats is supplied, the default implementation returns 0 and does nothing.

If lpStgMedium->tymed is TYMED_NULL, the STGMEDIUM should allocated and filled as specified by lpFormatEtc->tymed. If not TYMED_NULL, the STGMEDIUM should be filled in place with the data.

This is an advanced overridable. Override this function to provide your data in the requested format and medium. Depending on your data, you may want to override one of the other versions of this function instead. If your data is small and fixed in size, override OnRenderGlobalData. If your data is in a file, or is of variable size, override OnRenderFileData.

For more information, see IDataObject::GetData, STGMEDIUM, FORMATETC, and TYMED in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnRenderFileData


COleServerItem::OnRenderFileData

virtual BOOL OnRenderFileData( LPFORMATETC lpFormatEtc, CFile* pFile );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

pFile

Points to a CFile object in which the data is to be rendered.

Remarks

Called by the framework to retrieve data in the specified format when the storage medium is a file. The specified format is one previously placed in the COleDataSource object using the DelayRenderData member function for delayed rendering. The default implementation of this function simply returns FALSE.

This is an advanced overridable. Override this function to provide your data in the requested format and medium. Depending on your data, you might want to override one of the other versions of this function instead. If you want to handle multiple storage mediums, override OnRenderData. If your data is in a file, or is of variable size, override OnRenderFileData.

For more information, see IDataObject::GetData and FORMATETC in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnRenderData


COleServerItem::OnRenderGlobalData

virtual BOOL OnRenderGlobalData( LPFORMATETC lpFormatEtc, HGLOBAL* phGlobal );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpFormatEtc

Points to the FORMATETC structure specifying the format in which information is requested.

phGlobal

Points to a handle to global memory in which the data is to be returned. If no memory has been allocated, this parameter can be NULL.

Remarks

Called by the framework to retrieve data in the specified format when the specified storage medium is global memory. The specified format is one previously placed in the COleDataSource object using the DelayRenderData member function for delayed rendering. The default implementation of this function simply returns FALSE.

If phGlobal is NULL, then a new HGLOBAL should be allocated and returned in phGlobal. Otherwise, the HGLOBAL specified by phGlobal should be filled with the data. The amount of data placed in the HGLOBAL must not exceed the current size of the memory block. Also, the block cannot be reallocated to a larger size.

This is an advanced overridable. Override this function to provide your data in the requested format and medium. Depending on your data, you may want to override one of the other versions of this function instead. If you want to handle multiple storage mediums, override OnRenderData. If your data is in a file, or is of variable size, override OnRenderFileData.

For more information, see IDataObject::GetData and FORMATETC in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnRenderData


COleServerItem::OnSetColorScheme

virtual BOOL OnSetColorScheme( const LOGPALETTE FAR* lpLogPalette );

Return Value

Nonzero if the color palette is used; otherwise 0.

Parameters

lpLogPalette

Pointer to a Windows LOGPALETTE structure.

Remarks

Called by the framework to specify a color palette to be used when editing the OLE item. If the container application was written using the Microsoft Foundation Class Library, this function is called when the IOleObject::SetColorScheme function of the corresponding COleClientItem object is called. The default implementation returns FALSE. Override this function if you want to use the recommended palette. The server application is not required to use the suggested palette.

For more information, see IOleObject::SetColorScheme in the OLE 2 Programmer’s Reference, Volume 1.


COleServerItem::OnSetData

virtual BOOL OnSetData( LPFORMATETC pFormatEtc, LPSTGMEDIUM pStgMedium, BOOL bRelease );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pFormatEtc

Pointer to a FORMATETC structure specifying the format of the data.

pStgMedium

Pointer to a STGMEDIUM structure in which the data resides.

bRelease

Indicates who has ownership of the storage medium after completing the function call. The caller decides who is responsible for releasing the resources allocated on behalf of the storage medium. The caller does this by setting bRelease. If bRelease is nonzero, the server item takes ownership, freeing the medium when it has finished using it. When bRelease is 0, the caller retains ownership and the server item can use the storage medium only for the duration of the call.

Remarks

Called by the framework to replace the OLE item’s data with the specified data. The server item does not take ownership of the data until it has successfully obtained it. That is, it does not take ownership if it returns 0. If the data source takes ownership, it frees the storage medium by calling the ReleaseStgMedium function.

The default implementation does nothing. Override this function to replace the OLE item’s data with the specified data. This is an advanced overridable.

For more information, see STGMEDIUM, FORMATETC, and ReleaseStgMedium in the OLE 2 Programmer’s Reference, Volume 1.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleDataSource::OnSetData


COleServerItem::OnSetExtent

virtual BOOL OnSetExtent( DVASPECT nDrawAspect, const CSize& size );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nDrawAspect

Specifies the aspect of the OLE item whose bounds are being specified. This parameter can have any of the following values:

  • DVASPECT_CONTENT Item is represented in such a way that it can be displayed as an embedded object inside its container.

  • DVASPECT_THUMBNAIL Item is rendered in a “thumbnail” representation so that it can be displayed in a browsing tool.

  • DVASPECT_ICON Item is represented by an icon.

  • DVASPECT_DOCPRINT Item is represented as if it were printed using the Print command from the File menu.

size

A CSize structure specifying the new size of the OLE item.

Remarks

Called by the framework to tell the OLE item how much space is available to it in the container document. If the container application was written with the Microsoft Foundation Class Library, this function is called when the SetExtent member function of the corresponding COleClientItem object is called. The default implementation sets the m_sizeExtent member to the specified size if nDrawAspect is DVASPECT_CONTENT; otherwise it returns 0. Override this function to perform special processing when you change the size of the item.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleClientItem::SetExtent, COleServerItem::OnGetExtent, COleServerItem::m_sizeExtent


COleServerItem::OnShow

virtual void OnShow( );

Remarks

Called by the framework to instruct the server application to display the OLE item in place. This function is typically called when the user of the container application creates an item or executes a verb, such as Edit, that requires the item to be shown. The default implementation attempts in-place activation. If this fails, the function calls the OnOpen member function to display the OLE item in a separate window.

Override this function if you want to perform special processing when an OLE item is shown.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnOpen, COleClientItem::Activate


COleServerItem::OnUpdate

virtual void OnUpdate( COleServerItem* pSender, LPARAM lHint, CObject* pHint, DVASPECT nDrawAspect );

Parameters

pSender

Pointer to the item that modified the document. Can be NULL.

lHint

Contains information about the modification.

pHint

Pointer to an object storing information about the modification.

nDrawAspect

A value from the DVASPECT enumeration. This parameter can have any one of the following values:

  • DVASPECT_CONTENT Item is represented in such a way that it can be displayed as an embedded object inside its container.

  • DVASPECT_THUMBNAIL Item is rendered in a “thumbnail” representation so that it can be displayed in a browsing tool.

  • DVASPECT_ICON Item is represented by an icon.

  • DVASPECT_DOCPRINT Item is represented as if it were printed using the Print command from the File menu.

Remarks

Called by the framework when an item has been modified. The default implementation calls NotifyChanged, regardless of the hint or sender.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::NotifyChanged


COleServerItem::OnUpdateItems

virtual void OnUpdateItems( );

Remarks

Called by the framework to update all items in the server document. The default implementation calls UpdateLink for all COleClientItem objects in the document.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnUpdate, COleServerItem::OnQueryUpdateItems


COleServerItem::SetItemName

void SetItemName( LPCTSTR lpszItemName );

Parameters

lpszItemName

Pointer to the new name of the item.

Remarks

Call this function when you create a linked item to set its name. The name must be unique within the document. When a server application is called to edit a linked item, the application uses this name to find the item. You do not need to call this function for embedded items.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::GetItemName, COleLinkingDoc::OnGetLinkedItem


COleServerItem::m_sizeExtent

CSize m_sizeExtent;

Remarks

This member tells the server how much of the object is visible in the container document. The default implementation of OnSetExtent sets this member.

COleServerItem Overview | Class Members | Hierarchy Chart

See Also COleServerItem::OnSetExtent


COleStreamFile

A COleStreamFile object represents a stream of data (IStream) in a compound file as part of OLE Structured Storage. An IStorage object must exist before the stream can be opened or created unless it is a memory stream.

COleStreamFile objects are manipulated exactly like CFile objects.

For more information about manipulating streams and storages, see the article Containers: Compound Files in Visual C++ Programmer’s Guide.

For more information, see IStream and IStorage in the OLE 2 Programmer’s Reference, Volume 1.

#include <afxole.h>


COleStreamFile Class Members

Construction

COleStreamFile Constructs a COleStreamFile object.

Attributes and Operations

Attach | Associates a stream with the object.
CreateMemoryStream | Creates a stream from global memory and associates it with the object.
CreateStream | Creates a stream and associates it with the object.
Detach | Disassociates the stream from the object.
GetStream | Returns the current stream.
OpenStream | Safely opens a stream and associates it with the object.


COleStreamFile::Attach

void Attach( LPSTREAM lpStream );

Parameters

lpStream

Points to the OLE stream (IStream) to be associated with the object. Cannot be NULL.

Remarks

Associates the supplied OLE stream with the COleStreamFile object. The object must not already be associated with an OLE stream.

For more information, see IStream in the OLE 2 Programmer’s Reference, Volume 1.

COleStreamFile Overview | Class Members | Hierarchy Chart

See Also COleStreamFile::Detach


COleStreamFile::COleStreamFile

COleStreamFile( LPSTREAM lpStream = NULL );

Parameters

lpStream

Pointer to the OLE stream to be associated with the object.

Remarks

Creates a COleStreamFile object. If lpStream is NULL, the object is not associated with an OLE stream, otherwise, the object is associated with the supplied OLE stream.

For more information, see IStream in the OLE 2 Programmer’s Reference, Volume 1.

COleStreamFile Overview | Class Members | Hierarchy Chart

See Also COleStreamFile::Attach, CFile


COleStreamFile::CreateMemoryStream

BOOL CreateMemoryStream( CFileException* pError = NULL );

Return Value

Nonzero if the stream is created successfully; otherwise 0.

Parameters

pError

Points to a CFileException object or NULL that indicates the completion status of the create operation. Supply this parameter if you want to monitor possible exceptions generated by attempting to create the stream.

Remarks

Safely creates a new stream out of global, shared memory where a failure is a normal, expected condition. The memory is allocated by the OLE subsystem.

For more information, see CreateStreamOnHGlobal in the OLE 2 Programmer’s Reference, Volume 1.

COleStreamFile Overview | Class Members | Hierarchy Chart

See Also COleStreamFile::OpenStream, COleStreamFile::CreateStream, CFileException


COleStreamFile::CreateStream

BOOL CreateStream( LPSTORAGE lpStorage, LPCTSTR lpszName, DWORD nOpenFlags = modeReadWrite|shareExclusive|modeCreate, CFileException* pError = NULL );

Return Value

Nonzero if the stream is created successfully; otherwise 0.

Parameters

lpStorage

Points to the OLE storage object that contains the stream to be created. Cannot be NULL.

lpszStreamName

Name of the stream to be created. Cannot be NULL.

nOpenFlags

Access mode to use when opening the stream. Exclusive, read/write, and create modes are used by default. For a complete list of the available modes, see CFile::CFile.

pError

Points to a CFileException object or NULL. Supply this parameter if you want to monitor possible exceptions generated by attempting to create the stream.

Remarks

Safely creates a new stream in the supplied storage object where a failure is a normal, expected condition. A file exception will be thrown if the open fails and pError is not NULL.

For more information, see IStorage::CreateStream in the OLE 2 Programmer’s Reference, Volume 1.

COleStreamFile Overview | Class Members | Hierarchy Chart

See Also COleStreamFile::OpenStream, COleStreamFile::CreateMemoryStream, CFileException


COleStreamFile::Detach

LPSTREAM Detach( );

Return Value

A pointer to the stream (IStream) that was associated with the object.

Remarks

Disassociates the stream from the object without closing the stream. The stream must be closed in some other fashion before the program terminates.

For more information, see IStream in the OLE 2 Programmer’s Reference, Volume 1.

COleStreamFile Overview | Class Members | Hierarchy Chart

See Also COleStreamFile::Attach


COleStreamFile::GetStream

IStream* GetStream( ) const;

Return Value

A pointer to the current stream interface ( IStream).

Remarks

Call this function to return a pointer to current stream.


COleStreamFile::OpenStream

BOOL OpenStream( LPSTORAGE lpStorage, LPCTSTR lpszName, DWORD nOpenFlags = modeReadWrite|shareExclusive, CFileException* pError = NULL );

Return Value

Nonzero if the stream is opened successfully; otherwise 0.

Parameters

lpStorage

Points to the OLE storage object that contains the stream to be opened. Cannot be NULL.

lpszName

Name of the stream to be opened. Cannot be NULL.

nOpenFlags

Access mode to use when opening the stream. Exclusive and read/write modes are used by default. For the complete list of the available modes, see CFile::CFile.

pError

Points to a CFileException object or NULL. Supply this parameter if you want to monitor possible exceptions generated by attempting to open the stream.

Remarks

Opens an existing stream. A file exception will be thrown if the open fails and pError is not NULL.

For more information, see IStorage::OpenStream in the OLE 2 Programmer’s Reference, Volume 1.

COleStreamFile Overview | Class Members | Hierarchy Chart

See Also COleStreamFile::CreateStream, COleStreamFile::CreateMemoryStream, CFileException


COleTemplateServer

The COleTemplateServer class is used for OLE visual editing servers, automation servers, and link containers (applications that support links to embeddings). This class is derived from the class COleObjectFactory; usually, you can use COleTemplateServer directly rather than deriving your own class. COleTemplateServer uses a CDocTemplate object to manage the server documents. Use COleTemplateServer when implementing a full server, that is, a server that can be run as a standalone application. Full servers are typically multiple document interface (MDI) applications, although single document interface (SDI) applications are supported. One COleTemplateServer object is needed for each type of server document an application supports; that is, if your server application supports both worksheets and charts, you must have two COleTemplateServer objects.

COleTemplateServer overrides the OnCreateInstance member function defined by COleObjectFactory. This member function is called by the framework to create a C++ object of the proper type.

For more information about servers, see the article Servers: Implementing a Server in Visual C++ Programmer’s Guide.

#include <afxdisp.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample HIERSVR

See Also COleServerDoc, COleServerItem


COleTemplateServer Class Members

Construction

COleTemplateServer Constructs a COleTemplateServer object.

Operations

ConnectTemplate | Connects a document template to the underlying COleObjectFactory object.
UpdateRegistry | Registers the document type with the OLE system registry.


COleTemplateServer::COleTemplateServer

COleTemplateServer( );

Remarks

Constructs a COleTemplateServer object.

For a brief description of the use of the COleTemplateServer class, see the COleLinkingDoc class overview.


COleTemplateServer::ConnectTemplate

void ConnectTemplate( REFCLSID clsid, CDocTemplate* pDocTemplate, BOOL bMultiInstance );

Parameters

clsid

Reference to the OLE class ID that the template requests.

pDocTemplate

Pointer to the document template.

bMultiInstance

Indicates whether a single instance of the application can support multiple instantiations. If TRUE, multiple instances of the application are launched for each request to create an object.

Remarks

Connects the document template pointed to by pDocTemplate to the underlying COleObjectFactory object.

For more information, see CLSID Key in the OLE 2 Programmer’s Reference, Volume 1.

COleTemplateServer Overview | Class Members | Hierarchy Chart

See Also CDocTemplate


COleTemplateServer::UpdateRegistry

void UpdateRegistry( OLE_APPTYPE nAppType = OAT_INPLACE_SERVER, LPCSTR* rglpszRegister = NULL, LPCSTR FAR* rglpszOverwrite = NULL );

Parameters

nAppType

A value from the OLE_APPTYPE enumeration, which is defined in AFXDISP.H. It can have any one of the following values:

  • OAT_INPLACE_SERVER Server has full server user-interface.

  • OAT_SERVER Server supports only embedding.

  • OAT_CONTAINER Container supports links to embedded objects.

  • OAT_DISPATCH_OBJECT Object is IDispatch-capable.

  • OAT_DOCOBJECT_SERVER Server supports both embedding and the Document Object component model.

rglpszRegister

A list of entries that is written into the registry only if no entries exist.

rglpszOverwrite

A list of entries that is written into the registry regardless of whether any preceding entries exist.

Remarks

Loads file-type information from the document-template string and places that information in the OLE system registry.

The registration information is loaded by means of a call to CDocTemplate::GetDocString. The substrings retrieved are those identified by the indexes regFileTypeId, regFileTypeName, and fileNewName, as described in the GetDocString reference pages.

If the regFileTypeId substring is empty or if the call to GetDocString fails for any other reason, this function fails and the file information is not entered in the registry.

The information in the arguments rglpszRegister and rglpszOverwrite is written to the registry through a call to AfxOleRegisterServerClass. The default information, which is registered when the two arguments are NULL, is suitable for most applications. For information on the structure of the information in these arguments, see AfxOleRegisterServerClass.

For more information, see IDispatch in the Win32 SDK OLE Programmer's Reference.

COleTemplateServer Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::GetDocString, AfxOleRegisterServerClass


COleUpdateDialog

The COleUpdateDialog class is used for a special case of the OLE Edit Links dialog box, which should be used when you need to update only existing linked or embedded objects in a document.

For more information regarding OLE-specific dialog boxes, see the article Dialog Boxes in OLE in Visual C++ Programmer’s Guide.

#include <afxodlgs.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample OCLIENT

See Also COleLinksDialog


COleUpdateDialog Class Members

Construction

COleUpdateDialog Constructs a COleUpdateDialog object.

Operations

DoModal Displays the Edit Links dialog box in an update mode.


COleUpdateDialog::COleUpdateDialog

COleUpdateDialog( COleDocument* pDoc, BOOL bUpdateLinks = TRUE, BOOL bUpdateEmbeddings = FALSE, CWnd* pParentWnd = NULL );

Parameters

pDoc

Points to the document containing the links that may need updating.

bUpdateLinks

Flag that determines whether linked objects are to be updated.

bUpdateEmbeddings

Flag that determines whether embedded objects are to be updated.

pParentWnd

Points to the parent or owner window object (of type CWnd) to which the dialog object belongs. If it is NULL, the parent window of the dialog box will be set to the main application window.

Remarks

This function constructs only a COleUpdateDialog object. To display the dialog box, call DoModal. This class should be used instead of COleLinksDialog when you want to update only existing linked or embedded items.

COleUpdateDialog Overview | Class Members | Hierarchy Chart

See Also COleDialog, COleLinksDialog, COleDocument, CWnd, CDialog, COleUpdateDialog::DoModal


COleUpdateDialog::DoModal

virtual int DoModal( );

Return Value

Completion status for the dialog box. One of the following values:

  • IDOK if the dialog box returned successfully.

  • IDCANCEL if none of the linked or embedded items in the current document need updating.

  • IDABORT if an error occurred. If IDABORT is returned, call the COleDialog::GetLastError member function to get more information about the type of error that occurred. For a listing of possible errors, see the OleUIEditLinks function in the OLE 2.01 User Interface Library.

Remarks

Call this function to display the Edit Links dialog box in update mode. All links and/or embeddings are updated unless the user selects the Cancel button.

COleUpdateDialog Overview | Class Members | Hierarchy Chart

See Also COleDialog::GetLastError, COleLinksDialog::DoModal


COleVariant

COleVariant does not have a base class.

A COleVariant object encapsulates the VARIANT data type. This data type is used in OLE automation. Specifically, the DISPPARAMS structure contains a pointer to an array of VARIANT structures. A DISPPARAMS structure is used to pass parameters to IDispatch::Invoke.

Note This class is derived from the VARIANT structure. This means you can pass a COleVariant in a parameter that calls for a VARIANT and that the data members of the VARIANT structure are accessible data members of COleVariant.

The two related MFC classes COleCurrency and COleDateTime encapsulate the variant data types CURRENCY (VT_CY) and DATE (VT_DATE). The COleVariant class is used extensively in the DAO classes; see these classes for typical usage of this class, for example CDaoQueryDef and CDaoRecordset.

For more information, see the VARIANT, CURRENCY, DISPPARAMS, and IDispatch::Invoke entries in the Win32 SDK OLE Programmer’s Reference.

For more information on the COleVariant class and its use in OLE automation, see "Passing Parameters in OLE Automation" in the article Automation in Visual C++ Programmer’s Guide.

#include <afxdisp.h>


COleVariant Class Members

Construction

COleVariant Constructs a COleVariant object.

Operations

Attach | Attaches a VARIANT to a COleVariant.
ChangeType | Changes the variant type of this COleVariant object.
Clear | Clears this COleVariant object.
Detach | Detaches a VARIANT from a COleVariant and returns the VARIANT.
SetString | Sets the string to a particular type, typically ANSI.

Operators

operator LPCVARIANT | Converts a COleVariant value into an LPCVARIANT.
operator LPVARIANT | Converts a COleVariant object into an LPVARIANT.
operator = | Copies a COleVariant value.
operator == | Compares two COleVariant values.

Archive/Dump

operator << | Outputs a COleVariant value to CArchive or CDumpContext.
operator >> | Inputs a COleVariant object from CArchive.


COleVariant::Attach

void Attach( VARIANT& varSrc );

Parameters

varSrc

An existing VARIANT object to be attached to the current COleVariant object.

Remarks

Call this function to attach the given VARIANT object to the current COleVariant object. This function sets the VARTYPE of varSrc to VT_EMPTY.

For more information, see the VARIANT and VARTYPE entries in the Win32 SDK OLE Programmer’s Reference.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::operator LPCVARIANT, COleVariant::operator LPVARIANT


COleVariant::COleVariant

COleVariant( );

COleVariant( const VARIANT& varSrc );

COleVariant( const COleVariant& varSrc );

COleVariant( LPCVARIANT pSrc );

COleVariant( LPCTSTR lpszSrc );

COleVariant( LPCTSTR lpszSrc, VARTYPE vtSrc );

COleVariant( CString& strSrc );

COleVariant( BYTE nSrc );

COleVariant( short nSrc, VARTYPE vtSrc = VT_I2 );

COleVariant( long lSrc, VARTYPE vtSrc = VT_I4 );

COleVariant( const COleCurrency& curSrc );

COleVariant( float fltSrc );

COleVariant( double dblSrc );

COleVariant( const COleDateTime& dateSrc );

COleVariant( const CByteArray& arrSrc );

COleVariant( const CLongBinary& lbSrc );

Parameters

varSrc

An existing COleVariant or VARIANT object to be copied into the new COleVariant object.

pSrc

A pointer to a VARIANT object that will be copied into the new COleVariant object.

lpszSrc

A null-terminated string to be copied into the new COleVariant object.

vtSrc

The VARTYPE for the new COleVariant object.

strSrc

A CString object to be copied into the new COleVariant object.

nSrc, lSrc

A numerical value to be copied into the new COleVariant object.

vtSrc

The VARTYPE for the new COleVariant object.

curSrc

A COleCurrency object to be copied into the new COleVariant object.

fltSrc, dblSrc

A numerical value to be copied into the new COleVariant object.

dateSrc

A COleDateTime object to be copied into the new COleVariant object.

arrSrc

A CByteArray object to be copied into the new COleVariant object.

lbSrc

A CLongBinary object to be copied into the new COleVariant object.

Remarks

All of these constructors create new COleVariant objects initialized to the specified value. A brief description of each of these constructors follows.

  • COleVariant( ) Creates an empty COleVariant object, VT_EMPTY.

  • COleVariant( varSrc ) Copies an existing VARIANT or COleVariant object. The variant type is retained.

  • COleVariant( pSrc ) Copies an existing VARIANT or COleVariant object. The variant type is retained.

  • COleVariant( lpszSrc ) Copies a string into the new object, VT_BSTR (UNICODE).

  • COleVariant( lpszSrc, vtSrc ) Copies a string into the new object. The parameter vtSrc must be VT_BSTR (UNICODE) or VT_BSTRT (ANSI).

  • COleVariant( strSrc ) Copies a string into the new object, VT_BSTR (UNICODE).

  • COleVariant( nSrc ) Copies an 8-bit integer into the new object, VT_UI1.

  • COleVariant( nSrc, vtSrc ) Copies a 16-bit integer (or Boolean value) into the new object. The parameter vtSrc must be VT_I2 or VT_BOOL.

  • COleVariant( lSrc, vtSrc ) Copies a 32-bit integer (or SCODE value) into the new object. The parameter vtSrc must be VT_I4, VT_ERROR, or VT_BOOL.

  • COleVariant( curSrc ) Copies a COleCurrency value into the new object, VT_CY.

  • COleVariant( fltSrc ) Copies a 32-bit floating-point value into the new object, VT_R4.

  • COleVariant( dblSrc ) Copies a 64-bit floating-point value into the new object, VT_R8.

  • COleVariant( dateSrc ) Copies a COleDateTime value into the new object, VT_DATE.

  • COleVariant( arrSrc ) Copies a CByteArray object into the new object, VT_EMPTY.

  • COleVariant( lbSrc ) Copies a CLongBinary object into the new object, VT_EMPTY.

For more information, see the VARIANT and VARTYPE entries in the Platform SDK.

For more information on SCODE, see Structure of COM Error Codes in the Platform SDK.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::operator =, CString, COleCurrency, COleDateTime


COleVariant::ChangeType

void ChangeType( VARTYPE vartype, LPVARIANT pSrc = NULL );

Parameters

vartype

The VARTYPE for this COleVariant object.

pSrc

A pointer to the VARIANT object to be converted. If this value is NULL, this COleVariant object is used as the source for the conversion.

Remarks

Call this function to convert the type of variant value in this COleVariant object.

For more information, see the VARIANT, VARTYPE, and VariantChangeType entries in the Win32 SDK OLE Programmer’s Reference.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::operator =


COleVariant::Clear

void Clear( );

Remarks

Call this function to clear the VARIANT. This sets the VARTYPE for this object to VT_EMPTY. The COleVariant destructor calls this function.

For more information, see the VARIANT, VARTYPE, and VariantClear entries in the Win32 SDK OLE Programmer’s Reference.


COleVariant::Detach

VARIANT Detach( );

Return Type

The underlying VARIANT value of this COleVariant object.

Remarks

Call this function to detach the underlying VARIANT object from this COleVariant object. This function sets the VARTYPE for this COleVariant object to VT_EMPTY.

Note After calling Detach, it is the caller’s responsibility to call VariantClear on the resulting VARIANT structure.

For more information, see the VARIANT, VARTYPE, and VariantClear entries in the Win32 SDK OLE Programmer’s Reference.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::operator LPCVARIANT, COleVariant::operator LPVARIANT


COleVariant::SetString

void SetString( LPCTSTR lpszSrc, VARTYPE vtSrc );

Parameters

lpszSrc

A null-terminated string to be copied into the new COleVariant object.

vtSrc The VARTYPE for the new COleVariant object.

Remarks

Call this function to set the string to a particular type. The parameter vtSrc must be VT_BSTR (UNICODE) or VT_BSTRT (ANSI). SetString is typically used to set strings to ANSI, since the default for the COleVariant::COleVariant constructor with a string or string pointer parameter and no VARTYPE is UNICODE.

A DAO recordset in a non-UNICODE build expects strings to be ANSI. Thus, for DAO functions that use COleVariant objects, if you are not creating a UNICODE recordset, you must use the COleVariant::COleVariant( lpszSrc, vtSrc ) form of constructor with vtSrc set to VT_BSTRT (ANSI) or use SetString with vtSrc set to VT_BSTRT to make ANSI strings. For example, the CDAORecordset functions CDAORecordset::Seek and CDAORecordset::SetFieldValue use COleVariant objects as parameters. These objects must be ANSI if the DAO recordset is not UNICODE.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::COleVariant, CDAORecordset::Seek, CDAORecordset::SetFieldValue


COleVariant::operator =

const COleVariant& operator =( const VARIANT& varSrc );

const COleVariant& operator =( LPCVARIANT pSrc );

const COleVariant& operator =( const COleVariant& varSrc );

const COleVariant& operator =( const LPCTSTR lpszSrc );

const COleVariant& operator =( const CString& strSrc );

const COleVariant& operator =( const BYTE nSrc );

const COleVariant& operator =( const short nSrc );

const COleVariant& operator =( const long lSrc );

const COleVariant& operator =( const COleCurrency& curSrc );

const COleVariant& operator =( const float fltSrc );

const COleVariant& operator =( const double dblSrc );

const COleVariant& operator =( const COleDateTime& dateSrc );

const COleVariant& operator =( const CByteArray& arrSrc );

const COleVariant& operator =( const CLongBinary& lbSrc );

Remarks

These overloaded assignment operators copy the source value into this COleVariant object. A brief description of each operator follows:

  • operator =( varSrc ) Copies an existing VARIANT or COleVariant object into this object.

  • operator =( pSrc ) Copies the VARIANT object accessed by pSrc into this object.

  • operator =( lpszSrc ) Copies a null-terminated string into this object and sets the VARTYPE to VT_BSTR.

  • operator =( strSrc ) Copies a CString object into this object and sets the VARTYPE to VT_BSTR.

  • operator =( nSrc ) Copies an 8- or 16-bit integer value into this object. If nSrc is an 8-bit value, the VARTYPE of this is set to VT_UI1. If nSrc is a 16-bit value and the VARTYPE of this is VT_BOOL, it is kept; otherwise, it is set to VT_I2.

  • operator =( lSrc ) Copies a 32-bit integer value into this object. If the VARTYPE of this is VT_ERROR, it is kept; otherwise, it is set to VT_I4.

  • operator =( curSrc ) Copies a COleCurrency object into this object and sets the VARTYPE to VT_CY.

  • operator =( fltSrc ) Copies a 32-bit floating-point value into this object and sets the VARTYPE to VT_R4.

  • operator =( dblSrc ) Copies a 64-bit floating-point value into this object and sets the VARTYPE to VT_R8.

  • operator =( dateSrc ) Copies a COleDateTime object into this object and sets the VARTYPE to VT_DATE.

  • operator =( arrSrc ) Copies a CByteArray object into this COleVariant object.

  • operator =( lbSrc ) Copies a CLongBinary object into this COleVariant object.

For more information, see the VARIANT and VARTYPE entries in the Win32 SDK OLE Programmer’s Reference.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::COleVariant, COleCurrency, COleDateTime


COleVariant::operator ==

BOOL operator ==( const VARIANT& varSrc ) const;

BOOL operator ==( LPCVARIANT pSrc ) const;

Remarks

This operator compares two variant values and returns nonzero if they are equal; otherwise 0.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::operator =


COleVariant::operator LPCVARIANT

operator LPCVARIANT( ) const;

Remarks

This casting operator returns a VARIANT structure whose value is copied from this COleVariant object.

For more information, see the VARIANT entry in the Win32 SDK OLE Programmer’s Reference.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::operator LPVARIANT


COleVariant::operator LPVARIANT

operator LPVARIANT( );

Remarks

Call this casting operator to access the underlying VARIANT structure for this COleVariant object.

Caution Changing the value in the VARIANT structure accessed by the pointer returned by this function will change the value of this COleVariant object.

For more information, see the VARIANT entry in the Win32 SDK OLE Programmer’s Reference.

COleVariant Overview | Class Members | Hierarchy Chart

See Also COleVariant::operator LPCVARIANT


COleVariant::operator <<, >>

friend CDumpContext& AFXAPI operator <<( CDumpContext& dc, OleVariant varSrc );

friend CArchive& AFXAPI operator <<( CArchive& ar, COleVariant varSrc );

friend CArchive& AFXAPI operator >>( CArchive& ar, COleVariant& varSrc );

Remarks

The COleVariant insertion (<<) operator supports diagnostic dumping and storing to an archive. The extraction (>>) operator supports loading from an archive.

COleVariant Overview | Class Members | Hierarchy Chart

See Also CDumpContext, CArchive


CPageSetupDialog

The CPageSetupDialog class encapsulates the services provided by the Windows common OLE Page Setup dialog box with additional support for setting and modifying print margins. This class is designed to take the place of the Print Setup dialog box.

To use a CPageSetupDialog object, first create the object using the CPageSetupDialog constructor. Once the dialog box has been constructed, you can set or modify any values in the m_psd data member to initialize the values of the dialog box's controls. The m_psd structure is of type PAGESETUPDLG. The topic Setting Up the Printed Page in the Win32 SDK documentation show an example of the initialization of this structure.

After initializing the dialog box controls, call the DoModal member function to display the dialog box and allow the user to select print options. DoModal returns whether the user selected the OK (IDOK) or Cancel (IDCANCEL) button.

If DoModal returns IDOK, you can use several of CPageSetupDialog's member functions, or access the m_psd data member, to retrieve information input by the user.

Note After the common OLE Page Setup dialog box is dismissed, any changes made by the user will not be saved by the framework. It is up to the application itself to save any values from this dialog box to a permanent location, such as member of the application’s document or application class.

#include <afxdlgs.h>


CPageSetupDialog Class Members

Attributes

CreatePrinterDC | Creates a device context for printing.
GetDeviceName | Returns the device name of the printer.
GetDevMode | Returns the current DEVMODE of the printer.
GetDriverName | Returns the driver used by the printer.
GetMargins | Returns the current margin settings of the printer.
GetPortName | Returns the output port name.
GetPaperSize | Returns the paper size of the printer.

Construction

CPageSetupDialog Constructs a CPageSetupDialog object.

Data Members

m_psd A structure used to customize a CPageSetupDialog object.

Operations

DoModal Displays the dialog box and allows the user make a selection.

Overridables

OnDrawPage | Called by the framework to render a screen image of a printed page.
PreDrawPage | Called by the framework before rendering a screen image of a printed page.


CPageSetupDialog::CPageSetupDialog

CPageSetupDialog( DWORD dwFlags = PSD_MARGINS | PSD_INWININIINTLMEASURE, CWnd* pParentWnd = NULL );

Parameters

dwFlags

One or more flags you can use to customize the settings of the dialog box. The values can be combined using the bitwise-OR operator. These values have the following meanings:

  • PSD_DEFAULTMINMARGINS Sets the minimum allowable widths for the page margins to be the same as the printer’s minimums. This flag is ignored if the PSD_MARGINS and PSD_MINMARGINS flags are also specified.

  • PSD_INWININIINTLMEASURE Not implemented.

  • PSD_MINMARGINS Causes the system to use the values specified in the rtMinMargin member as the minimum allowable widths for the left, top, right, and bottom margins. The system prevents the user from entering a width that is less than the specified minimum. If PSD_MINMARGINS is not specified, the system sets the minimum allowable widths to those allowed by the printer.

  • PSD_MARGINS Activates the margin control area.

  • PSD_INTHOUSANDTHSOFINCHES Causes the units of the dialog box to be measured in 1/1000 of an inch.

  • PSD_INHUNDREDTHSOFMILLIMETERS Causes the units of the dialog box to be measured in 1/100 of a millimeter.

  • PSD_DISABLEMARGINS Disables the margin dialog box controls.

  • PSD_DISABLEPRINTER Disables the Printer button.

  • PSD_NOWARNING Prevents the warning message from being displayed when there is no default printer.

  • PSD_DISABLEORIENTATION Disables the page orientation dialog control.

  • PSD_RETURNDEFAULT Causes CPageSetupDialog to return DEVMODE and DEVNAMES structures that are initialized for the system default printer without displaying a dialog box. It is assumed that both hDevNames and hDevMode are NULL; otherwise, the function returns an error. If the system default printer is supported by an old printer driver (earlier than Windows version 3.0), only hDevNames is returned; hDevMode is NULL.

  • PSD_DISABLEPAPER Disables the paper selection control.

  • PSD_SHOWHELP Causes the dialog box to show the Help button. The hwndOwner member must not be NULL if this flag is specified.

  • PSD_ENABLEPAGESETUPHOOK Enables the hook function specified in lpfnSetupHook.

  • PSD_ENABLEPAGESETUPTEMPLATE Causes the operating system to create the dialog box by using the dialog template box identified by hInstance and lpSetupTemplateName.

  • PSD_ENABLEPAGESETUPTEMPLATEHANDLE Indicates that hInstance identifies a data block that contains a preloaded dialog box template. The system ignores lpSetupTemplateName if this flag is specified.

  • PSD_ENABLEPAGEPAINTHOOK Enables the hook function specified in lpfnPagePaintHook.

  • PSD_DISABLEPAGEPAINTING Disables the draw area of the dialog box.

pParentWnd

Pointer to the dialog box’s parent or owner.

Remarks

Call this function to construct a CPageSetupDialog object. Use the DoModal function to display the dialog box.

CPageSetupDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog, CPageSetupDialog


CPageSetupDialog::CreatePrinterDC

HDC CreatePrinterDC( );

Return Value

Handle to the newly created printer device context (DC).

Remarks

Creates a printer device context from the DEVMODE and DEVNAMES structures.

CPageSetupDialog Overview | Class Members | Hierarchy Chart

See Also CPageSetupDialog::GetDevMode, CPageSetupDialog::GetDeviceName, CPageSetupDialog::GetDriverName


CPageSetupDialog::DoModal

virtual int DoModal( );

Return Value

IDOK or IDCANCEL. If IDCANCEL is returned, call the Windows CommDlgExtendedError function to determine whether an error occurred.

IDOK and IDCANCEL are constants that indicate whether the user selected the OK or Cancel button.

Remarks

Call this function to display the Windows common OLE Page Setup dialog box and allow the user to select various print setup options such as the printing margins, size and orientation of the paper, and destination printer. In addition, the user can access the printer setup options such as network location and properties specific to the selected printer.

If you want to initialize the various Page Setup dialog options by setting members of the m_psd structure, you should do so before calling DoModal, and after the dialog object is constructed. After calling DoModal, call other member functions to retrieve the settings or information input by the user into the dialog box.

If you want to propagate the current settings entered by the user, make a call to CWinApp::SelectPrinter. This function takes the information from the CPageSetupDialog object and initializes and selects a new printer DC with the proper attributes.

AfxGetApp()->SelectPrinter(dlg.m_psd.hDevNames, dlg.m_psd.hDevMode);

CPageSetupDialog Overview | Class Members | Hierarchy Chart

See Also CPageSetupDialog::m_psd


CPageSetupDialog::GetDeviceName

CString GetDeviceName( ) const;

Return Value

The device name used by the CPageSetupDialog object.

Remarks

Call this function after DoModal to retrieve the name of the currently selected printer.


CPageSetupDialog::GetDevMode

LPDEVMODE GetDevMode( ) const;

Return Value

The DEVMODE data structure, which contains information about the device initialization and environment of a print driver. You must unlock the memory taken by this structure with the Windows GlobalUnlock function, which is described in the Platform SDK.

Remarks

Call this function after calling DoModal to retrieve information about the printer device context of the CPageSetupDialog object.


CPageSetupDialog::GetDriverName

CString GetDriverName( ) const;

Return Value

The name of the currently selected printer device driver.

Remarks

Call this function after calling DoModal to retrieve the name of the currently selected printer device driver.

CPageSetupDialog Overview | Class Members | Hierarchy Chart

See Also CPageSetupDialog::GetDeviceName, CPageSetupDialog::GetDevMode, CPageSetupDialog::GetPortName


CPageSetupDialog::GetMargins

void GetMargins( LPRECT lpRectMargins, LPRECT lpRectMinMargins ) const;

Parameters

lpRectMargins

Pointer to a RECT structure or CRect object that describes (in 1/1000 inches or 1/100 mm) the print margins for the currently selected printer. Pass NULL for this parameter, if you are not interested in this rectangle.

lpRectMinMargins

Pointer to a RECT structure or CRect object that describes (in 1/1000 inches or 1/100 mm) the minimum print margins for the currently selected printer. Pass NULL for this parameter, if you are not interested in this rectangle.

Remarks

Call this function after a call to DoModal to retrieve the margins of the printer device driver.


CPageSetupDialog::GetPaperSize

CSize GetPaperSize( ) const;

Return Value

A CSize object containing the size of the paper (in 1/1000 inches or 1/100 mm) selected for printing.

Remarks

Call this function to retrieve the size of the paper selected for printing.


CPageSetupDialog::GetPortName

CString GetPortName( ) const;

Return Value

The name of the currently selected printer port.

Remarks

Call this function after calling DoModal to retrieve the name of the currently selected printer port.

CPageSetupDialog Overview | Class Members | Hierarchy Chart

See Also CPageSetupDialog::GetDeviceName, CPageSetupDialog::GetDriverName


CPageSetupDialog::OnDrawPage

virtual UINT OnDrawPage( CDC* pDC, UINT nMessage, LPRECT lpRect );

Return Value

Nonzero value if handled; otherwise 0.

Parameters

pDC

Pointer to the printer device context.

nMessage

Specifies a message, indicating the area of the page currently being drawn. Can be one of the following:

  • WM_PSD_FULLPAGERECT The entire page area.

  • WM_PSD_MINMARGINRECT Current minimum margins.

  • WM_PSD_MARGINRECT Current margins.

  • WM_PSD_GREEKTEXTRECT Contents of the page.

  • WM_PSD_ENVSTAMPRECT Area reserved for a postage stamp representation.

  • WM_PSD_YAFULLPAGERECT Area for a return address representation. This area extends to the edges of the sample page area.

lpRect

Pointer to a CRect or RECT object containing the coordinates of the drawing area.

Remarks

Called by the framework to draw a screen image of a printed page. This image is then displayed as part of the common OLE Page Setup dialog box. The default implementation draws an image of a page of text.

Override this function to customize the drawing of a specific area of the image, or the entire image. You can do this by using a switch statement with case statements checking the value of nMessage. For example, to customize the rendering of the contents of the page image, you could use the following example code:

switch( nType )
{
    case WM_PSD_GREEKTEXTRECT:
      DrawMyImage(pDC, lpRect);    //draws my special graphic
      return 1;
    default:
      return ::Draw(CDC* pDC, UINT nDrawType, LPRECT lpRect);
};

Note that you do not need to handle every case of nMessage. You can choose to handle one component of the image, several components of the image, or the whole area.

CPageSetupDialog Overview | Class Members | Hierarchy Chart

See Also CPageSetupDialog::PreDrawPage


CPageSetupDialog::PreDrawPage

virtual UINT PreDrawPage( WORD wPaper, WORD wFlags, LPPAGESETUPDLG pPSD );

Return Value

Nonzero value if handled; otherwise 0.

Parameters

wPaper

Specifies a value that indicates the paper size. This value can be one of the DMPAPER_ values listed in the description of the DEVMODE structure.

wFlags

Indicates the orientation of the paper or envelope, and whether the printer is a dot-matrix or HPPCL (Hewlett Packard Printer Control Language) device. This parameter can have one of the following values:

  • 0x001 Paper in landscape mode (dot matrix)

  • 0x003 Paper in landscape mode (HPPCL)

  • 0x005 Paper in portrait mode (dot matrix)

  • 0x007 Paper in portrait mode (HPPCL)

  • 0x00b Envelope in landscape mode (HPPCL)

  • 0x00d Envelope in portrait mode (dot matrix)

  • 0x019 Envelope in landscape mode (dot matrix)

  • 0x01f Envelope in portrait mode (dot matrix)

pPSD

Pointer to a PAGESETUPDLG structure. For more information on this structure, see the Win32 documentation.

Remarks

Called by the framework before drawing the screen image of a printed page. Override this function to customize the drawing of the image. If you override this function and return TRUE, you must draw the entire image. If you override this function and return FALSE, the entire default image is drawn by the framework.

CPageSetupDialog Overview | Class Members | Hierarchy Chart

See Also CPageSetupDialog::OnDrawPage


CPageSetupDialog::m_psd

Remarks

A structure of type PAGESETUPDLG, whose members store the characteristics of the dialog object. After constructing a CPageSetupDialog object, you can use m_psd to set various aspects of the dialog box before calling the DoModal member function.

If you modify the m_psd data member directly, you will override any default behavior.

For more information on the PAGESETUPDLG structure, see the Win32 documentation.


CPaintDC

The CPaintDC class is a device-context class derived from CDC. It performs a CWnd::BeginPaint at construction time and CWnd::EndPaint at destruction time.

A CPaintDC object can only be used when responding to a WM_PAINT message, usually in your OnPaint message-handler member function.

For more information on using CPaintDC, see Device Contexts in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HELLO | MFC Sample MDI


CPaintDC Class Members

Data Members

m_ps | Contains the PAINTSTRUCT used to paint the client area.
m_hWnd | The HWND to which this CPaintDC object is attached.

Construction

CPaintDC Constructs a CPaintDC connected to the specified CWnd.


CPaintDC::CPaintDC

CPaintDC( CWnd* pWnd );
throw( CResourceException );

Parameters

pWnd

Points to the CWnd object to which the CPaintDC object belongs.

Remarks

Constructs a CPaintDC object, prepares the application window for painting, and stores the PAINTSTRUCT structure in the m_ps member variable.

An exception (of type CResourceException) is thrown if the Windows GetDC call fails. A device context may not be available if Windows has already allocated all of its available device contexts. Your application competes for the five common display contexts available at any given time under Windows.


CPaintDC::m_hWnd

Remarks

The HWND to which this CPaintDC object is attached. m_hWnd is a protected variable of type HWND.


CPaintDC::m_ps

Remarks

m_ps is a public member variable of type PAINTSTRUCT. It is the PAINTSTRUCT that is passed to and filled out by CWnd::BeginPaint.

The PAINTSTRUCT contains information that the application uses to paint the client area of the window associated with a CPaintDC object.

Note that you can access the device-context handle through the PAINTSTRUCT. However, you can access the handle more directly through the m_hDC member variable that CPaintDC inherits from CDC.


CPalette

The CPalette class encapsulates a Windows color palette. A palette provides an interface between an application and a color output device (such as a display device). The interface allows the application to take full advantage of the color capabilities of the output device without severely interfering with the colors displayed by other applications. Windows uses the application’s logical palette (a list of needed colors) and the system palette (which defines available colors) to determine the colors used.

A CPalette object provides member functions for manipulating the palette referred to by the object. Construct a CPalette object and use its member functions to create the actual palette, a graphics device interface (GDI) object, and to manipulate its entries and other properties.

For more information on using CPalette, see Graphic Objects in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample DIBLOOK

See Also CPalette::GetPaletteEntries, CPalette::SetPaletteEntries


CPalette Class Members

Construction

CPalette Constructs a CPalette object with no attached Windows palette. You must initialize the CPalette object with one of the initialization member functions before it can be used.

Initialization

CreatePalette | Creates a Windows color palette and attaches it to the CPalette object.
CreateHalftonePalette | Creates a halftone palette for the device context and attaches it to the CPalette object.

Operations

FromHandle | Returns a pointer to a CPalette object when given a handle to a Windows palette object.
AnimatePalette | Replaces entries in the logical palette identified by the CPalette object. The application does not have to update its client area, because Windows maps the new entries into the system palette immediately.
GetNearestPaletteIndex | Returns the index of the entry in the logical palette that most closely matches a color value.
ResizePalette | Changes the size of the logical palette specified by the CPalette object to the specified number of entries.

Attributes

GetEntryCount | Retrieves the number of palette entries in a logical palette.
GetPaletteEntries | Retrieves a range of palette entries in a logical palette.
SetPaletteEntries | Sets RGB color values and flags in a range of entries in a logical palette.
operator HPALETTE | Returns the HPALETTE attached to the CPalette.


CPalette::AnimatePalette

void AnimatePalette( UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors );

Parameters

nStartIndex

Specifies the first entry in the palette to be animated.

nNumEntries

Specifies the number of entries in the palette to be animated.

lpPaletteColors

Points to the first member of an array of PALETTEENTRY structures to replace the palette entries identified by nStartIndex and nNumEntries.

Remarks

Replaces entries in the logical palette attached to the CPalette object. When an application calls AnimatePalette, it does not have to update its client area, because Windows maps the new entries into the system palette immediately.

The AnimatePalette function will only change entries with the PC_RESERVED flag set in the corresponding palPaletteEntry member of the LOGPALETTE structure that is attached to the CPalette object. See LOGPALETTE in the Win32 SDK Programmer’s Reference for more information about this structure.

CPalette Overview | Class Members | Hierarchy Chart

See Also CPalette::CreatePalette, ::AnimatePalette


CPalette::CPalette

CPalette( );

Remarks

Constructs a CPalette object. The object has no attached palette until you call CreatePalette to attach one.

CPalette Overview | Class Members | Hierarchy Chart

See Also CPalette::CreatePalette


CPalette::CreateHalftonePalette

BOOL CreateHalftonePalette( CDC* pDC );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

pDC

Identifies the device context.

Remarks

Creates a halftone palette for the device context. An application should create a halftone palette when the stretching mode of a device context is set to HALFTONE. The logical halftone palette returned by the CreateHalftonePalette member function should then be selected and realized into the device context before the CDC::StretchBlt or ::StretchDIBits function is called.

See the Win32 SDK Programmer’s Reference for more information about CreateHalftonePalette and StretchDIBits.

CPalette Overview | Class Members | Hierarchy Chart

See Also CDC::RealizePalette, CDC::SelectPalette, CDC::SetStretchBltMode, ::CreateHalftonePalette, ::StretchDIBits


CPalette::CreatePalette

BOOL CreatePalette( LPLOGPALETTE lpLogPalette );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpLogPalette

Points to a LOGPALETTE structure that contains information about the colors in the logical palette.

Remarks

Initializes a CPalette object by creating a Windows logical color palette and attaching it to the CPalette object.

See the Win32 SDK Programmer’s Reference for more information about the LOGPALETTE structure.

CPalette Overview | Class Members | Hierarchy Chart

See Also ::CreatePalette, LOGPALETTE


CPalette::FromHandle

static CPalette* PASCAL FromHandle( HPALETTE hPalette );

Return Value

A pointer to a CPalette object if successful; otherwise NULL.

Parameters

hPalette

A handle to a Windows GDI color palette.

Remarks

Returns a pointer to a CPalette object when given a handle to a Windows palette object. If a CPalette object is not already attached to the Windows palette, a temporary CPalette object is created and attached. This temporary CPalette object is valid only until the next time the application has idle time in its event loop, at which time all temporary graphic objects are deleted. In other words, the temporary object is valid only during the processing of one window message.


CPalette::GetEntryCount

int GetEntryCount( );

Return Value

Number of entries in a logical palette.

Remarks

Call this member function to retrieve the number of entries in a given logical palette.

CPalette Overview | Class Members | Hierarchy Chart

See Also CPalette::GetPaletteEntries, CPalette::SetPaletteEntries


CPalette::GetNearestPaletteIndex

UINT GetNearestPaletteIndex( COLORREF crColor ) const;

Return Value

The index of an entry in a logical palette. The entry contains the color that most nearly matches the specified color.

Parameters

crColor

Specifies the color to be matched.

Remarks

Returns the index of the entry in the logical palette that most closely matches the specified color value.

CPalette Overview | Class Members | Hierarchy Chart

See Also ::GetNearestPaletteIndex


CPalette::GetPaletteEntries

UINT GetPaletteEntries( UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors ) const;

Return Value

The number of entries retrieved from the logical palette; 0 if the function failed.

Parameters

nStartIndex

Specifies the first entry in the logical palette to be retrieved.

nNumEntries

Specifies the number of entries in the logical palette to be retrieved.

lpPaletteColors

Points to an array of PALETTEENTRY data structures to receive the palette entries. The array must contain at least as many data structures as specified by nNumEntries.

Remarks

Retrieves a range of palette entries in a logical palette.

CPalette Overview | Class Members | Hierarchy Chart

See Also ::GetPaletteEntries, CPalette::SetPaletteEntries


CPalette::operator HPALETTE

operator HPALETTE( ) const;

Return Value

If successful, a handle to the Windows GDI object represented by the CPalette object; otherwise NULL.

Remarks

Use this operator to get the attached Windows GDI handle of the CPalette object. This operator is a casting operator, which supports direct use of an HPALETTE object.

For more information about using graphic objects, see the article Graphic Objects in the Win32 SDK Programmer’s Reference.


CPalette::ResizePalette

BOOL ResizePalette( UINT nNumEntries );

Return Value

Nonzero if the palette was successfully resized; otherwise 0.

Parameters

nNumEntries

Specifies the number of entries in the palette after it has been resized.

Remarks

Changes the size of the logical palette attached to the CPalette object to the number of entries specified by nNumEntries. If an application calls ResizePalette to reduce the size of the palette, the entries remaining in the resized palette are unchanged. If the application calls ResizePalette to enlarge the palette, the additional palette entries are set to black (the red, green, and blue values are all 0), and the flags for all additional entries are set to 0.

For more information on the Windows API ResizePalette, see ::ResizePalette in the Win32 SDK Programmer’s Reference.

CPalette Overview | Class Members | Hierarchy Chart

See Also ::ResizePalette


CPalette::SetPaletteEntries

UINT SetPaletteEntries( UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors );

Return Value

The number of entries set in the logical palette; 0 if the function failed.

Parameters

nStartIndex

Specifies the first entry in the logical palette to be set.

nNumEntries

Specifies the number of entries in the logical palette to be set.

lpPaletteColors

Points to an array of PALETTEENTRY data structures to receive the palette entries. The array must contain at least as many data structures as specified by nNumEntries.

Remarks

Sets RGB color values and flags in a range of entries in a logical palette.

If the logical palette is selected into a device context when the application calls SetPaletteEntries, the changes will not take effect until the application calls CDC::RealizePalette.

For more information on the Windows structure PALETTEENTRY, see PALETTEENTRY in the Win32 SDK Programmer’s Reference.

CPalette Overview | Class Members | Hierarchy Chart

See Also CDC::RealizePalette, CPalette::GetPaletteEntries, ::SetPaletteEntries


CPen

The CPen class encapsulates a Windows graphics device interface (GDI) pen.

For more information on using CPen, see Graphic Objects in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CBrush


CPen Class Members

Construction

CPen Constructs a CPen object.

Initialization

CreatePen | Creates a logical cosmetic or geometric pen with the specified style, width, and brush attributes, and attaches it to the CPen object.
CreatePenIndirect | Creates a pen with the style, width, and color given in a LOGPEN structure, and attaches it to the CPen object.

Operations

FromHandle Returns a pointer to a CPen object when given a Windows HPEN.

Attributes

operator HPEN | Returns the Windows handle attached to the CPen object.
GetLogPen | Gets a LOGPEN underlying structure.
GetExtLogPen | Gets an EXTLOGPEN underlying structure.


CPen::CPen

CPen( );

CPen( int nPenStyle, int nWidth, COLORREF crColor );
throw( CResourceException );

CPen( int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL );
throw( CResourceException );

Parameters

nPenStyle

Specifies the pen style. This parameter in the first version of the constructor can be one of the following values:

  • PS_SOLID Creates a solid pen.

  • PS_DASH Creates a dashed pen. Valid only when the pen width is 1 or less, in device units.

  • PS_DOT Creates a dotted pen. Valid only when the pen width is 1 or less, in device units.

  • PS_DASHDOT Creates a pen with alternating dashes and dots. Valid only when the pen width is 1 or less, in device units.

  • PS_DASHDOTDOT Creates a pen with alternating dashes and double dots. Valid only when the pen width is 1 or less, in device units.

  • PS_NULL Creates a null pen.

  • PS_INSIDEFRAME Creates a pen that draws a line inside the frame of closed shapes produced by the Windows GDI output functions that specify a bounding rectangle (for example, the Ellipse, Rectangle, RoundRect, Pie, and Chord member functions). When this style is used with Windows GDI output functions that do not specify a bounding rectangle (for example, the LineTo member function), the drawing area of the pen is not limited by a frame.

    The second version of the CPen constructor specifies a combination of type, style, end cap, and join attributes. The values from each category should be combined by using the bitwise OR operator (|). The pen type can be one of the following values:

  • PS_GEOMETRIC Creates a geometric pen.

  • PS_COSMETIC Creates a cosmetic pen.

    The second version of the CPen constructor adds the following pen styles for nPenStyle:

  • PS_ALTERNATE Creates a pen that sets every other pixel. (This style is applicable only for cosmetic pens.)

  • PS_USERSTYLE Creates a pen that uses a styling array supplied by the user.

    The end cap can be one of the following values:

  • PS_ENDCAP_ROUND End caps are round.

  • PS_ENDCAP_SQUARE End caps are square.

  • PS_ENDCAP_FLAT End caps are flat.

    The join can be one of the following values:

  • PS_JOIN_BEVEL Joins are beveled.

  • PS_JOIN_MITER Joins are mitered when they are within the current limit set by the ::SetMiterLimit function. If the join exceeds this limit, it is beveled.

  • PS_JOIN_ROUND Joins are round.

nWidth

Specifies the width of the pen.

  • For the first version of the constructor, if this value is 0, the width in device units is always 1 pixel, regardless of the mapping mode.

  • For the second version of the constructor, if nPenStyle is PS_GEOMETRIC, the width is given in logical units. If nPenStyle is PS_COSMETIC, the width must be set to 1.

crColor

Contains an RGB color for the pen.

pLogBrush

Points to a LOGBRUSH structure. If nPenStyle is PS_COSMETIC, the lbColor member of the LOGBRUSH structure specifies the color of the pen and the lbStyle member of the LOGBRUSH structure must be set to BS_SOLID. If nPenStyle is PS_GEOMETRIC, all members must be used to specify the brush attributes of the pen.

nStyleCount

Specifies the length, in doubleword units, of the lpStyle array. This value must be zero if nPenStyle is not PS_USERSTYLE.

lpStyle

Points to an array of doubleword values. The first value specifies the length of the first dash in a user-defined style, the second value specifies the length of the first space, and so on. This pointer must be NULL if nPenStyle is not PS_USERSTYLE.

Remarks

If you use the constructor with no arguments, you must initialize the resulting CPen object with the CreatePen, CreatePenIndirect, or CreateStockObject member functions. If you use the constructor that takes arguments, then no further initialization is necessary. The constructor with arguments can throw an exception if errors are encountered, while the constructor with no arguments will always succeed.

CPen Overview | Class Members | Hierarchy Chart

See Also CPen::CreatePen, CPen::CreatePenIndirect, CGdiObject::CreateStockObject


CPen::CreatePen

BOOL CreatePen( int nPenStyle, int nWidth, COLORREF crColor );

BOOL CreatePen( int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL );

Return Value

Nonzero, or the handle of a logical pen, if successful; otherwise 0.

Parameters

nPenStyle

Specifies the style for the pen. For a list of possible values, see the nPenStyle parameter in the CPen constructor.

nWidth

Specifies the width of the pen.

  • For the first version of CreatePen, if this value is 0, the width in device units is always 1 pixel, regardless of the mapping mode.

  • For the second version of CreatePen, if nPenStyle is PS_GEOMETRIC, the width is given in logical units. If nPenStyle is PS_COSMETIC, the width must be set to 1.

crColor

Contains an RGB color for the pen.

pLogBrush

Points to a LOGBRUSH structure. If nPenStyle is PS_COSMETIC, the lbColor member of the LOGBRUSH structure specifies the color of the pen and the lbStyle member of the LOGBRUSH structure must be set to BS_SOLID. If nPenStyle is PS_GEOMETRIC, all members must be used to specify the brush attributes of the pen.

nStyleCount

Specifies the length, in doubleword units, of the lpStyle array. This value must be zero if nPenStyle is not PS_USERSTYLE.

lpStyle

Points to an array of doubleword values. The first value specifies the length of the first dash in a user-defined style, the second value specifies the length of the first space, and so on. This pointer must be NULL if nPenStyle is not PS_USERSTYLE.

Remarks

The first version of CreatePen initializes a pen with the specified style, width, and color. The pen can be subsequently selected as the current pen for any device context.

Pens that have a width greater than 1 pixel should always have either the PS_NULL, PS_SOLID, or PS_INSIDEFRAME style.

If a pen has the PS_INSIDEFRAME style and a color that does not match a color in the logical color table, the pen is drawn with a dithered color. The PS_SOLID pen style cannot be used to create a pen with a dithered color. The style PS_INSIDEFRAME is identical to PS_SOLID if the pen width is less than or equal to 1.

The second version of CreatePen initializes a logical cosmetic or geometric pen that has the specified style, width, and brush attributes. The width of a cosmetic pen is always 1; the width of a geometric pen is always specified in world units. After an application creates a logical pen, it can select that pen into a device context by calling the CDC::SelectObject function. After a pen is selected into a device context, it can be used to draw lines and curves.

  • If nPenStyle is PS_COSMETIC and PS_USERSTYLE, the entries in the lpStyle array specify lengths of dashes and spaces in style units. A style unit is defined by the device in which the pen is used to draw a line.

  • If nPenStyle is PS_GEOMETRIC and PS_USERSTYLE, the entries in the lpStyle array specify lengths of dashes and spaces in logical units.

  • If nPenStyle is PS_ALTERNATE, the style unit is ignored and every other pixel is set.

When an application no longer requires a given pen, it should call the CGdiObject::DeleteObject member function or destroy the CPen object so the resource is no longer in use. An application should not delete a pen when the pen is selected in a device context.

CPen Overview | Class Members | Hierarchy Chart

See Also CPen::CreatePenIndirect, CPen::CPen, CGdiObject::DeleteObject, LOGBRUSH


CPen::CreatePenIndirect

BOOL CreatePenIndirect( LPLOGPEN lpLogPen );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpLogPen

Points to the Windows LOGPEN structure that contains information about the pen.

Remarks

Initializes a pen that has the style, width, and color given in the structure pointed to by lpLogPen.

Pens that have a width greater than 1 pixel should always have either the PS_NULL, PS_SOLID, or PS_INSIDEFRAME style.

If a pen has the PS_INSIDEFRAME style and a color that does not match a color in the logical color table, the pen is drawn with a dithered color. The PS_INSIDEFRAME style is identical to PS_SOLID if the pen width is less than or equal to 1.

CPen Overview | Class Members | Hierarchy Chart

See Also CPen::CreatePen, CPen::CPen


CPen::FromHandle

static CPen* PASCAL FromHandle( HPEN hPen );

Return Value

A pointer to a CPen object if successful; otherwise NULL.

Parameters

hPen

HPEN handle to Windows GDI pen.

Remarks

Returns a pointer to a CPen object given a handle to a Windows GDI pen object. If a CPen object is not attached to the handle, a temporary CPen object is created and attached. This temporary CPen object is valid only until the next time the application has idle time in its event loop, at which time all temporary graphic objects are deleted. In other words, the temporary object is only valid during the processing of one window message.


CPen::GetExtLogPen

int GetExtLogPen( EXTLOGPEN* pLogPen );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pLogPen

Points to an EXTLOGPEN structure that contains information about the pen.

Remarks

Call this member function to get an EXTLOGPEN underlying structure. The EXTLOGPEN structure defines the style, width, and brush attributes of a pen. For example, call GetExtLogPen to match the particular style of a pen.

See the following topics in the Win 32 SDK Programmer’s Reference for information about pen attributes:

  • GetObject

  • EXTLOGPEN

  • LOGPEN

  • ExtCreatePen

Example

The following code example demonstrates calling GetExtLogPen to retrieve a pen’s attributes, and then create a new, cosmetic pen with the same color.

EXTLOGPEN extlogpen;
penExisting.GetExtLogPen( &extlogpen );
CPen penOther;
LOGBRUSH LogBrush={ extlogpen.elpBrushStyle, extlogpen.elpColor, extlogpen.elpHatch };
penOther.CreatePen( PS_COSMETIC, 1, &LogBrush );

CPen Overview | Class Members | Hierarchy Chart

See Also CPen::GetLogPen, CPen::CreatePen


CPen::GetLogPen

int GetLogPen( LOGPEN* pLogPen );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pLogPen

Points to a LOGPEN structure to contain information about the pen.

Remarks

Call this member function to get a LOGPEN underlying structure. The LOGPEN structure defines the style, color, and pattern of a pen.

For example, call GetLogPen to match the particular style of pen.

See the following topics in the Win 32 SDK Programmer’s Reference for information about pen attributes:

  • GetObject

  • LOGPEN

Example

The following code example demonstrates calling GetLogPen to retrieve a pen character, and then create a new, solid pen with the same color.

LOGPEN logpen;
penExisting.GetLogPen( &logpen );
CPen penOther( PS_SOLID, 0, logpen.lopnColor);

CPen Overview | Class Members | Hierarchy Chart

See Also CPen::GetExtLogPen


CPen::operator HPEN

operator HPEN( ) const;

Return Value

If successful, a handle to the Windows GDI object represented by the CPen object; otherwise NULL.

Remarks

Use this operator to get the attached Windows GDI handle of the CPen object. This operator is a casting operator, which supports direct use of an HPEN object.

For more information about using graphic objects, see the article Graphic Objects in Win 32 SDK Programmer’s Reference.


CPictureHolder

CPictureHolder does not have a base class.

The purpose of the CPictureHolder class is implementation of a Picture property, which allows the user to display a picture in your control. With the stock Picture property, the developer can specify a bitmap, icon, or metafile for display.

For information on creating custom picture properties, see the article ActiveX Controls: Using Pictures in an ActiveX Control in Visual C++ Programmer’s Guide.

#include <afxctl.h>

Class Members | Hierarchy Chart

See Also CFontHolder


CPictureHolder Class Members

Data Members

m_pPict A pointer to a picture object.

Construction

CPictureHolder Constructs a CPictureHolder object.

Operations

GetDisplayString | Retrieves the string displayed in a control container’s property browser.
CreateEmpty | Creates an empty CPictureHolder object.
CreateFromBitmap | Creates a CPictureHolder object from a bitmap.
CreateFromMetafile | Creates a CPictureHolder object from a metafile.
CreateFromIcon | Creates a CPictureHolder object from an icon.
GetPictureDispatch | Returns the CPictureHolder object’s IDispatch interface.
SetPictureDispatch | Sets the CPictureHolder object’s IDispatch interface.
GetType | Tells whether the CPictureHolder object is a bitmap, a metafile, or an icon.
Render | Renders the picture.


CPictureHolder::CPictureHolder

CPictureHolder( );

Remarks

Constructs a CPictureHolder object.

CPictureHolder Overview | Class Members | Hierarchy Chart

See Also CPictureHolder::CreateEmpty


CPictureHolder::CreateEmpty

BOOL CreateEmpty( );

Return Value

Nonzero if the object is successfully created; otherwise 0.

Remarks

Creates an empty CPictureHolder object and connects it to an IPicture interface.

CPictureHolder Overview | Class Members | Hierarchy Chart

See Also CPictureHolder::CreateFromBitmap, CPictureHolder::CreateFromIcon, CPictureHolder::CreateFromMetafile


CPictureHolder::CreateFromBitmap

BOOL CreateFromBitmap( UINT idResource );

BOOL CreateFromBitmap( CBitmap* pBitmap, CPalette* pPal = NULL, BOOL bTransferOwnership = TRUE );

BOOL CreateFromBitmap( HBITMAP hbm, HPALETTE hpal = NULL );

Return Value

Nonzero if the object is successfully created; otherwise 0.

Parameters

idResource

Resource ID of a bitmap resource.

pBitmap

Pointer to a CBitmap object.

pPal

Pointer to a CPalette object.

bTransferOwnership

Indicates whether the picture object will take ownership of the bitmap and palette objects.

hbm

Handle to the bitmap from which the CPictureHolder object is created.

hpal

Handle to the palette used for rendering the bitmap.

Remarks

Uses a bitmap to initialize the picture object in a CPictureHolder. If bTransferOwnership is TRUE, the caller should not use the bitmap or palette object in any way after this call returns. If bTransferOwnership is FALSE, the caller is responsible for ensuring that the bitmap and palette objects remain valid for the lifetime of the picture object.

CPictureHolder Overview | Class Members | Hierarchy Chart

See Also CPictureHolder::CreateEmpty, CPictureHolder::CreateFromIcon, CPictureHolder::CreateFromMetafile


CPictureHolder::CreateFromIcon

BOOL CreateFromIcon( UINT idResource );

BOOL CreateFromIcon( HICON hIcon, BOOL bTransferOwnership = FALSE );

Return Value

Nonzero if the object is successfully created; otherwise 0.

Parameters

idResource

Resource ID of a bitmap resource.

hIcon

Handle to the icon from which the CPictureHolder object is created.

bTransferOwnership

Indicates whether the picture object will take ownership of the icon object.

Remarks

Uses an icon to initialize the picture object in a CPictureHolder. If bTransferOwnership is TRUE, the caller should not use the icon object in any way after this call returns. If bTransferOwnership is FALSE, the caller is responsible for ensuring that the icon object remains valid for the lifetime of the picture object.

CPictureHolder Overview | Class Members | Hierarchy Chart

See Also CPictureHolder::CreateEmpty, CPictureHolder::CreateFromBitmap, CPictureHolder::CreateFromMetafile


CPictureHolder::CreateFromMetafile

BOOL CreateFromMetafile( HMETAFILE hmf, int xExt, int yExt, BOOL bTransferOwnership = FALSE );

Return Value

Nonzero if the object is successfully created; otherwise 0.

Parameters

hmf

Handle to the metafile used to create the CPictureHolder object.

xExt

X extent of the picture.

yExt

Y extent of the picture.

bTransferOwnership

Indicates whether the picture object will take ownership of the metafile object.

Remarks

Uses a metafile to initialize the picture object in a CPictureHolder. If bTransferOwnership is TRUE, the caller should not use the metafile object in any way after this call returns. If bTransferOwnership is FALSE, the caller is responsible for ensuring that the metafile object remains valid for the lifetime of the picture object.

CPictureHolder Overview | Class Members | Hierarchy Chart

See Also CPictureHolder::CreateEmpty, CPictureHolder::CreateFromBitmap, CPictureHolder::CreateFromIcon


CPictureHolder::GetDisplayString

BOOL GetDisplayString( CString& strValue );

Return Value

Nonzero if the string is successfully retrieved; otherwise 0.

Parameters

strValue

Reference to the CString that is to hold the display string.

Remarks

Retrieves the string that is displayed in a container’s property browser.


CPictureHolder::GetPictureDispatch

LPPICTUREDISP GetPictureDispatch( );

Return Value

A pointer to the CPictureHolder object’s IPictureDisp interface.

Remarks

This function returns a pointer to the CPictureHolder object’s IPictureDisp interface. The caller must call Release on this pointer when finished with it.

CPictureHolder Overview | Class Members | Hierarchy Chart

See Also CPictureHolder::SetPictureDispatch


CPictureHolder::GetType

short GetType( );

Return Value

A value indicating the type of the picture. Possible values and their meanings are as follows:

Value | Meaning
PICTYPE_UNINITIALIZED | CPictureHolder object is unititialized.
PICTYPE_NONE | CPictureHolder object is empty.
PICTYPE_BITMAP | Picture is a bitmap.
PICTYPE_METAFILE | Picture is a metafile.
PICTYPE_ICON | Picture is an icon.

Remarks

Indicates whether the picture is a bitmap, metafile, or icon.


CPictureHolder::Render

void Render( CDC* pDC, const CRect& rcRender, const CRect& rcWBounds );

Parameters

pDC

Pointer to the display context in which the picture is to be rendered.

rcRender

Rectangle in which the picture is to be rendered.

rcWBounds

A rectangle representing the bounding rectangle of the object rendering the picture. For a control, this rectangle is the rcBounds parameter passed to an override of COleControl::OnDraw.

Remarks

Renders the picture in the rectangle referenced by rcRender.


CPictureHolder::SetPictureDispatch

void SetPictureDispatch( LPPICTUREDISP pDisp );

Parameters

pDisp

Pointer to the new IPictureDisp interface.

Remarks

Connects the CPictureHolder object to a IPictureDisp interface.

CPictureHolder Overview | Class Members | Hierarchy Chart

See Also CPictureHolder::GetPictureDispatch


CPictureHolder::m_pPict

Remarks

A pointer to the CPictureHolder object’s IPicture interface.


CPoint

The CPoint class is similar to the Windows POINT structure. It also includes member functions to manipulate CPoint and POINT structures.

A CPoint object can be used wherever a POINT structure is used. The operators of this class that interact with a “size” accept either CSize objects or SIZE structures, since the two are interchangeable.

Note This class is derived from the tagPOINT structure. (The name tagPOINT is a less-commonly-used name for the POINT structure.) This means that the data members of the POINT structure, x and y, are accessible data members of CPoint.

#include <afxwin.h>

Class Members | Hierarchy Chart

Sample MFC Sample MDI

See Also CRect, CSize


CPoint Class Members

Construction

CPoint Constructs a CPoint.

Operations

Offset | Adds values to the x and y members of the CPoint.
operator == | Checks for equality between two points.
operator != | Checks for inequality between two points.

Operators Returning CPoint Values

operator += | Offsets CPoint by adding a size or point.
operator –= | Offsets CPoint by subtracting a size or point.
operator + | Returns the sum of a CPoint and a size or point.
operator – | Returns the difference of a CPoint and a size, or the negation of a point.

Operators Returning CSize Values

operator – Returns the size difference between two points.

Operators Returning CRect Values

operator + | Returns a CRect offset by a size.
operator – | Returns a CRect offset by a negative size.


CPoint::CPoint

CPoint( );

CPoint( int initX, int initY );

CPoint( POINT initPt );

CPoint( SIZE initSize );

CPoint( DWORD dwPoint );

Parameters

initX

Specifies the value of the x member of CPoint.

initY

Specifies the value of the y member of CPoint.

initPt

POINT structure or CPoint that specifies the values used to initialize CPoint.

initSize

SIZE structure or CSize that specifies the values used to initialize CPoint.

dwPoint

Sets the x member to the low-order word of dwPoint and the y member to the high-order word of dwPoint.

Remarks

Constructs a CPoint object. If no arguments are given, x and y members are not initialized.


CPoint::Offset

void Offset( int xOffset, int yOffset );

void Offset( POINT point );

void Offset( SIZE size );

Parameters

xOffset

Specifies the amount to offset the x member of the CPoint.

yOffset

Specifies the amount to offset the y member of the CPoint.

point

Specifies the amount (POINT or CPoint) to offset the CPoint.

size

Specifies the amount (SIZE or CSize) to offset the CPoint.

Remarks

Adds values to the x and y members of the CPoint.

CPoint Overview | Class Members | Hierarchy Chart

See Also CPoint::operator +=, CPoint::operator –=


CPoint::operator ==

BOOL operator ==( POINT point ) const;

Return Value

Nonzero if the points are equal; otherwise 0.

Parameters

point

Contains a POINT structure or CPoint object.

Remarks

Checks for equality between two points.

CPoint Overview | Class Members | Hierarchy Chart

See Also CPoint::Operator !=


CPoint::operator !=

BOOL operator !=( POINT point ) const;

Return Value

Nonzero if the points are not equal; otherwise 0.

Parameters

point

Contains a POINT structure or CPoint object.

Remarks

Checks for inequality between two points.

CPoint Overview | Class Members | Hierarchy Chart

See Also CPoint::Operator ==


CPoint::operator +=

void operator +=( SIZE size );

void operator +=( POINT point );

Parameters

size

Contains a SIZE structure or CSize object.

point

Contains a POINT structure or CPoint object.

Remarks

The first overload adds a size to the CPoint.

The second overload adds a point to the CPoint.

In both cases, addition is done by adding the x (or cx) member of the right-hand operand to the x member of the CPoint and adding the y (or cy) member of the right-hand operand to the y member of the CPoint.

For example, adding CPoint(5, -7) to a variable which contains CPoint(30, 40) changes the variable to CPoint(35, 33).

CPoint Overview | Class Members | Hierarchy Chart

See Also CPoint::operator –=, CPoint::operator +, CPoint::Offset


CPoint::operator -=

void operator -=( SIZE size );

void operator -=( POINT point );

Parameters

size

Contains a SIZE structure or CSize object.

point

Contains a POINT structure or CPoint object.

Remarks

The first overload subtracts a size from the CPoint.

The second overload subtracts a point from the CPoint.

In both cases, subtraction is done by subtracting the x (or cx) member of the right-hand operand from the x member of the CPoint and subtracting the y (or cy) member of the right-hand operand from the y member of the CPoint.

For example, subtracting CPoint(5, -7) from a variable which contains CPoint(30, 40) changes the variable to CPoint(25, 47).

CPoint Overview | Class Members | Hierarchy Chart

See Also CPoint::operator –, CPoint::operator +=, CPoint::Offset


CPoint::operator +

CPoint operator +( SIZE size ) const;

CPoint operator +( POINT point ) const;

CRect operator +( const RECT* lpRect ) const;

Return Value

A CPoint that is offset by a size, a CPoint that is offset by a point, or a CRect offset by a point.

Parameters

size

Contains a SIZE structure or CSize object.

point

Contains a POINT structure or CPoint object.

lpRect

Contains a pointer to a RECT structure or CRect object.

Remarks

Use this operator to offset CPoint by a CPoint or CSize object, or to offset a CRect by a CPoint.

For example, using one of the first two overloads to offset the point
CPoint(25, -19) by a point CPoint(15, 5) or size CSize(15, 5) returns the value CPoint(40, -14).

Adding a rectangle to a point returns the rectangle after being offset by the the x and y values specified in the point. For example, using the last overload to offset a rectangle CRect(125, 219, 325, 419) by a point CPoint(25, -19) returns CRect(150, 200, 350, 400).

CPoint Overview | Class Members | Hierarchy Chart

See Also CPoint::operator –=, CPoint::operator –, CPoint::operator +=, CSize::operator +, CRect::operator +, CPoint::Offset, CRect::OffsetRect


CPoint::operator -

CSize operator -( POINT point ) const;

CPoint operator -( SIZE size ) const;

CRect operator -( const RECT* lpRect ) const;

CPoint operator -( ) const;

Return Value

A CSize that is the difference between two points, a CPoint that is offset by the negation of a size, a CRect that is offset by the negation of a point, or a CPoint that is the negation of a point.

Parameters

point

A POINT structure or CPoint object.

size

A SIZE structure or CSize object.

lpRect

A pointer to a RECT structure or a CRect object.

Remarks

Use one of the first two overloads to subtract a CPoint or CSize object from CPoint. The third overload offsets a CRect by the negation of CPoint. Finally, use the unary operator to negate CPoint.

For example, using the first overload to find the difference between two points CPoint(25, -19) and CPoint(15, 5) returns CSize(10, -24).

Subtracting a CSize from CPoint does the same calculation as above but returns a CPoint object, not a CSize object. For example, using the second overload to find the difference between the point
CPoint(25, -19) and the size CSize(15, 5) returns
CPoint(10, -24).

Subtracting a rectangle from a point returns the rectangle offset by the negatives of the x and y values specified in the point. For example, using the last overload to offset the rectangle CRect(125, 200, 325, 400) by the point CPoint(25, -19) returns
CRect(100, 219, 300, 419).

Use the unary operator to negate a point. For example, using the unary operator with the point CPoint(25, -19) returns CPoint(-25, 19).

CPoint Overview | Class Members | Hierarchy Chart

See Also CPoint::operator –=, CPoint::operator +=, CPoint::operator +, CSize::operator -, CRect::operator -, CPoint::Offset, CRect::OffsetRect


CPrintDialog

The CPrintDialog class encapsulates the services provided by the Windows common dialog box for printing. Common print dialog boxes provide an easy way to implement Print and Print Setup dialog boxes in a manner consistent with Windows standards.

If you wish, you can rely on the framework to handle many aspects of the printing process for your application. In this case, the framework automatically displays the Windows common dialog box for printing. You can also have the framework handle printing for your application but override the common Print dialog box with your own print dialog box. For more information on using the framework to handle printing tasks, see the article Printing in Visual C++ Programmer’s Guide.

If you want your application to handle printing without the framework’s involvement, you can use the CPrintDialog class “as is” with the constructor provided, or you can derive your own dialog class from CPrintDialog and write a constructor to suit your needs. In either case, these dialog boxes will behave like standard MFC dialog boxes because they are derived from class CCommonDialog.

To use a CPrintDialog object, first create the object using the CPrintDialog constructor. Once the dialog box has been constructed, you can set or modify any values in the m_pd structure to initialize the values of the dialog box’s controls. The m_pd structure is of type PRINTDLG. For more information on this structure, see the Win32 SDK documentation.

If you do not supply your own handles in m_pd for the hDevMode and hDevNames members, be sure to call the Windows function GlobalFree for these handles when you are done with the dialog box. When using the framework’s Print Setup implementation provided by CWinApp::OnFilePrintSetup, you do not have to free these handles. The handles are maintained by CWinApp and are freed in CWinApp’s destructor. It is only necessary to free these handles when using CPrintDialog stand-alone.

After initializing the dialog box controls, call the DoModal member function to display the dialog box and allow the user to select print options. DoModal returns whether the user selected the OK (IDOK) or Cancel (IDCANCEL) button.

If DoModal returns IDOK, you can use one of CPrintDialog’s member functions to retrieve the information input by the user.

The CPrintDialog::GetDefaults member function is useful for retrieving the current printer defaults without displaying a dialog box. This member function requires no user interaction.

You can use the Windows CommDlgExtendedError function to determine whether an error occurred during initialization of the dialog box and to learn more about the error. For more information on this function, see the Win32 SDK documentation.

CPrintDialog relies on the COMMDLG.DLL file that ships with Windows versions 3.1 and later.

To customize the dialog box, derive a class from CPrintDialog, provide a custom dialog template, and add a message map to process the notification messages from the extended controls. Any unprocessed messages should be passed on to the base class. Customizing the hook function is not required.

To process the same message differently depending on whether the dialog box is Print or Print Setup, you must derive a class for each dialog box. You must also override the Windows AttachOnSetup function, which handles the creation of a new dialog box when the Print Setup button is selected within a Print dialog box.

For more information on using CPrintDialog, see Common Dialog Classes in Visual C++ Programmer’s Guide.

#include <afxdlgs.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample DIBLOOK

See Also CPrintInfo


CPrintDialog Class Members

Data Members

m_pd A structure used to customize a CPrintDialog object.

Construction

CPrintDialog Constructs a CPrintDialog object.

Operations

CreatePrinterDC | Creates a printer device context without displaying the Print dialog box.
DoModal | Displays the dialog box and allows the user to make a selection.
GetCopies | Retrieves the number of copies requested.
GetDefaults | Retrieves device defaults without displaying a dialog box.
GetDeviceName | Retrieves the name of the currently selected printer device.
GetDevMode | Retrieves the DEVMODE structure.
GetDriverName | Retrieves the name of the currently selected printer driver.
GetFromPage | Retrieves the starting page of the print range.
GetToPage | Retrieves the ending page of the print range.
GetPortName | Retrieves the name of the currently selected printer port.
GetPrinterDC | Retrieves a handle to the printer device context.
PrintAll | Determines whether to print all pages of the document.
PrintCollate | Determines whether collated copies are requested.
PrintRange | Determines whether to print only a specified range of pages.
PrintSelection | Determines whether to print only the currently selected items.


CPrintDialog::CPrintDialog

CPrintDialog( BOOL bPrintSetupOnly, DWORD dwFlags = PD_ALLPAGES | PD_USEDEVMODECOPIES | PD_NOPAGENUMS | PD_HIDEPRINTTOFILE | PD_NOSELECTION, CWnd* pParentWnd = NULL );

Parameters

bPrintSetupOnly

Specifies whether the standard Windows Print dialog box or Print Setup dialog box is displayed. Set this parameter to TRUE to display the standard Windows Print Setup dialog box. Set it to FALSE to display the Windows Print dialog box. If bPrintSetupOnly is FALSE, a Print Setup option button is still displayed in the Print dialog box.

dwFlags

One or more flags you can use to customize the settings of the dialog box, combined using the bitwise OR operator. For example, the PD_ALLPAGES flag sets the default print range to all pages of the document. See the PRINTDLG structure in the Win32 SDK documentation for more information on these flags.

pParentWnd

A pointer to the dialog box’s parent or owner window.

Remarks

Constructs either a Windows Print or Print Setup dialog object. This member function only constructs the object. Use the DoModal member function to display the dialog box.

Note that when you call the constructor with bPrintSetupOnly set to FALSE, the PD_RETURNDC flag is automatically used. After calling DoModal, GetDefaults, or GetPrinterDC, a printer DC will be returned in m_pd.hDC. This DC must be freed by the caller of CPrintDialog.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::DoModal, ::PrintDlg


CPrintDialog::CreatePrinterDC

HDC CreatePrinterDC( );

Return Value

Handle to the newly created printer device context.

Remarks

Creates a printer device context (DC) from the DEVMODE and DEVNAMES structures. This DC is assumed to be the current printer DC, and any other previously obtained printer DCs must be deleted by the user. This function can be called, and the resulting DC used, without ever displaying the Print dialog box.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::GetDevMode


CPrintDialog::DoModal

virtual int DoModal( );

Return Value

IDOK or IDCANCEL. If IDCANCEL is returned, call the Windows CommDlgExtendedError function to determine whether an error occurred.

IDOK and IDCANCEL are constants that indicate whether the user selected the OK or Cancel button.

Remarks

Call this function to display the Windows common print dialog box and allow the user to select various printing options such as the number of copies, page range, and whether copies should be collated.

If you want to initialize the various print dialog options by setting members of the m_pd structure, you should do this before calling DoModal, but after the dialog object is constructed.

After calling DoModal, you can call other member functions to retrieve the settings or information input by the user into the dialog box.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::CPrintDialog, CDialog::DoModal


CPrintDialog::GetCopies

int GetCopies( ) const;

Return Value

The number of copies requested.

Remarks

Call this function after calling DoModal to retrieve the number of copies requested.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::PrintCollate


CPrintDialog::GetDefaults

BOOL GetDefaults( );

Return Value

Nonzero if the function was successful; otherwise 0.

Remarks

Call this function to retrieve the device defaults of the default printer without displaying a dialog box. The retrieved values are placed in the m_pd structure.

In some cases, a call to this function will call the constructor for CPrintDialog with bPrintSetupOnly set to FALSE. In these cases, a printer DC and hDevNames and hDevMode (two handles located in the m_pd data member) are automatically allocated.

If the constructor for CPrintDialog was called with bPrintSetupOnly set to FALSE, this function will not only return hDevNames and hDevMode (located in m_pd.hDevNames and m_pd.hDevMode) to the caller, but will also return a printer DC in m_pd.hDC. It is the responsibility of the caller to delete the printer DC and call the Windows GlobalFree function on the handles when you are finished with the CPrintDialog object.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::m_pd


CPrintDialog::GetDeviceName

CString GetDeviceName( ) const;

Return Value

The name of the currently selected printer.

Remarks

Call this function after calling DoModal to retrieve the name of the currently selected printer.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::GetDriverName, CPrintDialog::GetDevMode, CPrintDialog::GetPortName


CPrintDialog::GetDevMode

LPDEVMODE GetDevMode( ) const;

Return Value

The DEVMODE data structure, which contains information about the device initialization and environment of a print driver. You must unlock the memory taken by this structure with the Windows GlobalUnlock function, which is described in the Platform SDK.

Remarks

Call this function after calling DoModal to retrieve information about the printing device.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CDC::GetDeviceCaps


CPrintDialog::GetDriverName

CString GetDriverName( ) const;

Return Value

The name of the currently selected printer device driver.

Remarks

Call this function after calling DoModal to retrieve the name of the currently selected printer device driver.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::GetDeviceName, CPrintDialog::GetDevMode, CPrintDialog::GetPortName


CPrintDialog::GetFromPage

int GetFromPage( ) const;

Return Value

The starting page number in the range of pages to be printed.

Remarks

Call this function after calling DoModal to retrieve the starting page number in the range of pages to be printed.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::GetToPage, CPrintDialog::PrintRange


CPrintDialog::GetPortName

CString GetPortName( ) const;

Return Value

The name of the currently selected printer port.

Remarks

Call this function after calling DoModal to retrieve the name of the currently selected printer port.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::GetDriverName, CPrintDialog::GetDeviceName


CPrintDialog::GetPrinterDC

HDC GetPrinterDC( ) const;

Return Value

A handle to the printer device context if successful; otherwise NULL.

Remarks

If the bPrintSetupOnly parameter of the CPrintDialog constructor was FALSE (indicating that the Print dialog box is displayed), then GetPrinterDC returns a handle to the printer device context. You must call the Windows DeleteDC function to delete the device context when you are done using it.


CPrintDialog::GetToPage

int GetToPage( ) const;

Return Value

The ending page number in the range of pages to be printed.

Remarks

Call this function after calling DoModal to retrieve the ending page number in the range of pages to be printed.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::GetFromPage, CPrintDialog::PrintRange


CPrintDialog::PrintAll

BOOL PrintAll( ) const;

Return Value

Nonzero if all pages in the document are to be printed; otherwise 0.

Remarks

Call this function after calling DoModal to determine whether to print all pages in the document.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::PrintRange, CPrintDialog::PrintSelection


CPrintDialog::PrintCollate

BOOL PrintCollate( ) const;

Return Value

Nonzero if the user selects the collate check box in the dialog box; otherwise 0.

Remarks

Call this function after calling DoModal to determine whether the printer should collate all printed copies of the document.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::GetCopies


CPrintDialog::PrintRange

BOOL PrintRange( ) const;

Return Value

Nonzero if only a range of pages in the document are to be printed; otherwise 0.

Remarks

Call this function after calling DoModal to determine whether to print only a range of pages in the document.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::PrintAll, CPrintDialog::PrintSelection, CPrintDialog::GetFromPage, CPrintDialog::GetToPage


CPrintDialog::PrintSelection

BOOL PrintSelection( ) const;

Return Value

Nonzero if only the selected items are to be printed; otherwise 0.

Remarks

Call this function after calling DoModal to determine whether to print only the currently selected items.

CPrintDialog Overview | Class Members | Hierarchy Chart

See Also CPrintDialog::PrintRange, CPrintDialog::PrintAll


CPrintDialog::m_pd

PRINTDLG& m_pd;

Remarks

A structure whose members store the characteristics of the dialog object. After constructing a CPrintDialog object, you can use m_pd to set various aspects of the dialog box before calling the DoModal member function. For more information on the m_pd structure, see PRINTDLG in the Win32 SDK documentation.

If you modify the m_pd data member directly, you will override any default behavior.


CPrintInfo

CPrintInfo does not have a base class.

CPrintInfo stores information about a print or print-preview job. The framework creates an object of CPrintInfo each time the Print or Print Preview command is chosen and destroys it when the command is completed.

CPrintInfo contains information about both the print job as a whole, such as the range of pages to be printed, and the current status of the print job, such as the page currently being printed. Some information is stored in an associated CPrintDialog object; this object contains the values entered by the user in the Print dialog box.

A CPrintInfo object is passed between the framework and your view class during the printing process and is used to exchange information between the two. For example, the framework informs the view class which page of the document to print by assigning a value to the m_nCurPage member of CPrintInfo; the view class retrieves the value and performs the actual printing of the specified page.

Another example is the case in which the length of the document is not known until it is printed. In this situation, the view class tests for the end of the document each time a page is printed. When the end is reached, the view class sets the m_bContinuePrinting member of CPrintInfo to FALSE; this informs the framework to stop the print loop.

CPrintInfo is used by the member functions of CView listed under “See Also.” For more information about the printing architecture provided by the Microsoft Foundation Class Library, see Frame Window Topics and Document/View Architecture Topics and the articles Printing and Printing: Multipage Documents in Visual C++ Programmer’s Guide.

#include <afxext.h>

Class Members | Hierarchy Chart

Sample MFC Sample DIBLOOK

See Also CView::OnBeginPrinting, CView::OnEndPrinting, CView::OnEndPrintPreview, CView::OnPrepareDC, CView::OnPreparePrinting, CView::OnPrint


CPrintInfo Class Members

Data Members

m_bDocObject | Contains a flag indicating whether the document being printed is a DocObject.
m_dwFlags | Specifies DocObject printing operations.
m_nOffsetPage | Specifies offset of a particular DocObject's first page in a combined DocObject print job.
m_pPD | Contains a pointer to the CPrintDialog object used for the Print dialog box.
m_bDirect | Contains a flag indicating whether the document is being printed directly (without displaying the Print dialog box).
m_bPreview | Contains a flag indicating whether the document is being previewed.
m_bContinuePrinting | Contains a flag indicating whether the framework should continue the print loop.
m_nCurPage | Identifies the number of the page currently being printed.
m_nNumPreviewPages | Identifies the number of pages displayed in the preview window; either 1 or 2.
m_lpUserData | Contains a pointer to a user-created structure.
m_rectDraw | Specifies a rectangle defining the current usable page area.
m_strPageDesc | Contains a format string for page-number display.

Attributes

SetMinPage | Sets the number of the first page of the document.
SetMaxPage | Sets the number of the last page of the document.
GetMinPage | Returns the number of the first page of the document.
GetMaxPage | Returns the number of the last page of the document.
GetOffsetPage | Returns the number of the pages preceding the first page of a DocObject item being printed in a combined DocObject print job.
GetFromPage | Returns the number of the first page being printed.
GetToPage | Returns the number of the last page being printed.


CPrintInfo::GetFromPage

UINT GetFromPage( ) const;

Return Value

The number of the first page to be printed.

Remarks

Call this function to retrieve the number of the first page to be printed. This is the value specified by the user in the Print dialog box, and it is stored in the CPrintDialog object referenced by the m_pPD member. If the user has not specified a value, the default is the first page of the document.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_nCurPage, CPrintInfo::m_pPD, CPrintInfo::GetToPage


CPrintInfo::GetMaxPage

UINT GetMaxPage( ) const;

Return Value

The number of the last page of the document.

Remarks

Call this function to retrieve the number of the last page of the document. This value is stored in the CPrintDialog object referenced by the m_pPD member.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_nCurPage, CPrintInfo::m_pPD, CPrintInfo::GetMinPage, CPrintInfo::SetMaxPage, CPrintInfo::SetMinPage


CPrintInfo::GetMinPage

UINT GetMinPage( ) const;

Return Value

The number of the first page of the document.

Remarks

Call this function to retrieve the number of the first page of the document. This value is stored in the CPrintDialog object referenced by the m_pPD member.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_nCurPage, CPrintInfo::m_pPD, CPrintInfo::GetMaxPage, CPrintInfo::SetMaxPage, CPrintInfo::SetMinPage


CPrintInfo::GetOffsetPage

UINT GetOffsetPage( ) const;

Return Value

The number of pages preceding the first page of a DocObject item being printed in a combined DocObject print job.

Remarks

Call this function to retrieve the offset when printing multiple DocObject items from a DocObject client. This value is referenced by the m_nOffsetPage member. The first page of your document will be numbered the m_nOffsetPage value + 1 when printed as a DocObject with other active documents. The m_nOffsetPage member is valid only if the m_bDocObject value is TRUE.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_nOffsetPage, CPrintInfo::m_bDocObject


CPrintInfo::GetToPage

UINT GetToPage( ) const;

Return Value

The number of the last page to be printed.

Remarks

Call this function to retrieve the number of the last page to be printed. This is the value specified by the user in the Print dialog box, and it is stored in the CPrintDialog object referenced by the m_pPD member. If the user has not specified a value, the default is the last page of the document.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_nCurPage, CPrintInfo::m_pPD, CPrintInfo::GetFromPage


CPrintInfo::SetMaxPage

void SetMaxPage( UINT nMaxPage );

Parameters

nMaxPage

Number of the last page of the document.

Remarks

Call this function to specify the number of the last page of the document. This value is stored in the CPrintDialog object referenced by the m_pPD member. If the length of the document is known before it is printed, call this function from your override of CView::OnPreparePrinting. If the length of the document depends on a setting specified by the user in the Print dialog box, call this function from your override of CView::OnBeginPrinting. If the length of the document is not known until it is printed, use the m_bContinuePrinting member to control the print loop.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_bContinuePrinting, CPrintInfo::m_nCurPage, CPrintInfo::m_pPD, CPrintInfo::GetMinPage, CPrintInfo::GetToPage, CPrintInfo::SetMinPage, CView::OnBeginPrinting, CView::OnPreparePrinting


CPrintInfo::SetMinPage

void SetMinPage( UINT nMinPage );

Parameters

nMinPage

Number of the first page of the document.

Remarks

Call this function to specify the number of the first page of the document. Page numbers normally start at 1. This value is stored in the CPrintDialog object referenced by the m_pPD member.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_nCurPage, CPrintInfo::m_pPD, CPrintInfo::GetMaxPage, CPrintInfo::GetMinPage, CPrintInfo::SetMaxPage


CPrintInfo::m_bContinuePrinting

Remarks

Contains a flag indicating whether the framework should continue the print loop. If you are doing print-time pagination, you can set this member to FALSE in your override of CView::OnPrepareDC once the end of the document has been reached. You do not have to modify this variable if you have specified the length of the document at the beginning of the print job using the SetMaxPage member function. The m_bContinuePrinting member is a public variable of type BOOL.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::SetMaxPage, CView::OnPrepareDC


CPrintInfo::m_bDirect

Remarks

The framework sets this member to TRUE if the Print dialog box will be bypassed for direct printing; FALSE otherwise. The Print dialog is normally bypassed when you print from the shell or when printing is done using the command ID ID_FILE_PRINT_DIRECT.

You normally don’t change this member, but if you do change it, change it before you call CView::DoPreparePrinting in your override of CView::OnPreparePrinting.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CView::DoPreparePrinting, CView::OnPreparePrinting


CPrintInfo::m_bDocObject

Remarks

Contains a flag indicating whether the document being printed is a DocObject. Data members m_dwFlags and m_nOffsetPage are invalid unless this flag is TRUE.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_dwFlags, CPrintInfo::m_nOffsetPage


CPrintInfo::m_bPreview

Remarks

Contains a flag indicating whether the document is being previewed. This is set by the framework depending on which command the user executed. The Print dialog box is not displayed for a print-preview job. The m_bPreview member is a public variable of type BOOL.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CView::DoPreparePrinting, CView::OnPreparePrinting


CPrintInfo::m_dwFlags

Remarks

Contains a combination of flags specifying DocObject printing operations. Valid only if data member m_bDocObject is TRUE.

The flags can be one or more of the following values:

PRINTFLAG_MAYBOTHERUSER
PRINTFLAG_PROMPTUSER
PRINTFLAG_USERMAYCHANGEPRINTER
PRINTFLAG_RECOMPOSETODEVICE
PRINTFLAG_DONTACTUALLYPRINT
PRINTFLAG_FORCEPROPERTIES
PRINTFLAG_PRINTTOFILE

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_bDocObject, CPrintInfo::m_nOffsetPage


CPrintInfo::m_lpUserData

Remarks

Contains a pointer to a user-created structure. You can use this to store printing-specific data that you do not want to store in your view class. The m_lpUserData member is a public variable of type LPVOID.


CPrintInfo::m_nCurPage

Remarks

Contains the number of the current page. The framework calls CView::OnPrepareDC and CView::OnPrint once for each page of the document, specifying a different value for this member each time; its values range from the value returned by GetFromPage to that returned by GetToPage. Use this member in your overrides of CView::OnPrepareDC and CView::OnPrint to print the specified page of the document.

When preview mode is first invoked, the framework reads the value of this member to determine which page of the document should be previewed initially. You can set the value of this member in your override of CView::OnPreparePrinting to maintain the user’s current position in the document when entering preview mode. The m_nCurPage member is a public variable of type UINT.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::GetFromPage, CPrintInfo::GetToPage, CView::OnPrepareDC, CView::OnPreparePrinting, CView::OnPrint


CPrintInfo::m_nNumPreviewPages

Remarks

Contains the number of pages displayed in preview mode; it can be either 1 or 2. The m_nNumPreviewPages member is a public variable of type UINT.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_strPageDesc


CPrintInfo::m_nOffsetPage

Remarks

Contains the number of pages preceding the first page of a particular DocObject in a combined DocObject print job.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintInfo::m_bDocObject, CPrintInfo::m_dwFlags


CPrintInfo::m_pPD

Remarks

Contains a pointer to the CPrintDialog object used to display the Print dialog box for the print job. The m_pPD member is a public variable declared as a pointer to CPrintDialog.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CPrintDialog


CPrintInfo::m_rectDraw

Remarks

Specifies the usable drawing area of the page in logical coordinates. You may want to refer to this in your override of CView::OnPrint. You can use this member to keep track of what area remains usable after you print headers, footers, and so on. The m_rectDraw member is a public variable of type CRect.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CView::OnPrint


CPrintInfo::m_strPageDesc

Remarks

Contains a format string used to display the page numbers during print preview; this string consists of two substrings, one for single-page display and one for double-page display, each terminated by a ‘\n’ character. The framework uses “Page %u\nPages %u-%u\n” as the default value. If you want a different format for the page numbers, specify a format string in your override of CView::OnPreparePrinting. The m_strPageDesc member is a public variable of type CString.

CPrintInfo Overview | Class Members | Hierarchy Chart

See Also CView::OnPreparePrinting


CProgressCtrl

A “progress bar control” is a window that an application can use to indicate the progress of a lengthy operation. It consists of a rectangle that is gradually filled, from left to right, with the system highlight color as an operation progresses.

The CProgressCtrl class provides the functionality of the Windows common progress bar control. This control (and therefore the CProgressCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

A progress bar control has a range and a current position. The range represents the entire duration of the operation, and the current position represents the progress the application has made toward completing the operation. The window procedure uses the range and the current position to determine the percentage of the progress bar to fill with the highlight color and to determine the text, if any, to display within the progress bar. Because the range and current position values are expressed as signed integers, the possible range of current position values is from -217483648 to 217483647 inclusive.

For more information on using CProgressCtrl, see Control Topics and Using CProgressCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CMNCTRL2 | MFC Sample FIRE


CProgressCtrl Class Members

Construction

CProgressCtrl | Constructs a CProgressCtrl object.
Create | Creates a progress bar control and attaches it to a CProgressCtrl object.

Attributes

SetRange | Sets the minimum and maximum ranges for a progress bar control and redraws the bar to reflect the new ranges.
SetRange32 | Sets the minimum and maximum ranges for a progress bar control and redraws the bar to reflect the new ranges.
GetRange | Gets the lower and upper limits of the range of the progress bar control.
GetPos | Gets the current position of the progress bar.
SetPos | Sets the current position for a progress bar control and redraws the bar to reflect the new position.
OffsetPos | Advances the current position of a progress bar control by a specified increment and redraws the bar to reflect the new position.
SetStep | Specifies the step increment for a progress bar control.

Operations

StepIt Advances the current position for a progress bar control by the step increment (see SetStep) and redraws the bar to reflect the new position.


CProgressCtrl::CProgressCtrl

CProgressCtrl( );

Remarks

Constructs a CProgressCtrl object.

After constructing the CProgressCtrl object, call CProgressCtrl::Create to create the progress bar control.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also CProgressCtrl::Create


CProgressCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

TRUE if the CProgressCtrl object is successfully created; otherwise FALSE.

Parameters

dwStyle

Specifies the progress bar control’s style. Apply any combination of window styles, in addition to the following progress bar control styles, to the control:

  • PBS_VERTICAL Displays progress information vertically, top to bottom. Without this flag, the progress bar control displays horizontally, left to right.

  • PBS_SMOOTH Displays gradual, smooth filling in the progress bar control. Without this flag, the control will fill with blocks.

rect

Specifies the progress bar control’s size and position. It can be either a CRect object or a RECT structure. Because the control must be a child window, the specified coordinates are relative to the client area of the pParentWnd.

pParentWnd

Specifies the progress bar control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the progress bar control’s ID.

Remarks

You construct a CProgressCtrl object in two steps. First call the constructor, which creates the CProgressCtrl object; then call Create, which creates the progress bar control.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also CProgressCtrl::CProgressCtrl


CProgressCtrl::GetPos

int GetPos( );

Return Value

The position of the progress bar control.

Remarks

Call this member function to retrieve the current position of the progress bar. The position of the progress bar control is not the physical location on the screen, but rather is between the upper and lower range indicated in SetRange.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also CProgressCtrl::SetPos


CProgressCtrl::GetRange

void GetRange( int& nLower, int& nUpper );

Parameters

nLower

A reference to an integer receiving the lower limit of the progress bar control.

nUpper

A reference to an integer receiving the upper limit of the progress bar control.

Remarks

Call this member function to get the current lower and upper limits, or range, of the progress bar control. This function copies the values of the lower and upper limits to the integers referenced by nLower and nUpper, respectively.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also PBRANGE, PBM_GETRANGE


CProgressCtrl::OffsetPos

int OffsetPos( int nPos );

Return Value

The previous position of the progress bar control.

Parameters

nPos

Amount to advance the position.

Remarks

Advances the progress bar control’s current position by the increment specified by nPos and redraws the bar to reflect the new position.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also CProgressCtrl::SetPos, CProgressCtrl::SetRange, CProgressCtrl::StepIt


CProgressCtrl::SetPos

int SetPos( int nPos );

Return Value

The previous position of the progress bar control.

Parameters

nPos

New position of the progress bar control.

Remarks

Sets the progress bar control’s current position as specified by nPos and redraws the bar to reflect the new position.

The position of the progress bar control is not the physical location on the screen, but rather is between the upper and lower range indicated in SetRange.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also CProgressCtrl::OffsetPos, CProgressCtrl::SetRange, CProgressCtrl::StepIt


CProgressCtrl::SetRange

void SetRange( short nLower, short nUpper );

void SetRange32( int nLower, int nUpper );

Parameters

nLower

Specifies the lower limit of the range (default is zero).

nUpper

Specifies the upper limit of the range (default is 100).

Remarks

Sets the upper and lower limits of the progress bar control’s range and redraws the bar to reflect the new ranges.

The member function SetRange32 sets the 32-bit range for the progress control.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also CProgressCtrl::OffsetPos, CProgressCtrl::SetPos, CProgressCtrl::StepIt


CProgressCtrl::SetStep

int SetStep( int nStep );

Return Value

The previous step increment.

Parameters

nStep

New step increment.

Remarks

Specifies the step increment for a progress bar control. The step increment is the amount by which a call to CProgressCtrl::StepIt increases the progress bar’s current position.

The default step increment is 10.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also CProgressCtrl::OffsetPos, CProgressCtrl::SetPos, CProgressCtrl::StepIt


CProgressCtrl::StepIt

int StepIt( );

Return Value

The previous position of the progress bar control.

Remarks

Advances the current position for a progress bar control by the step increment and redraws the bar to reflect the new position. The step increment is set by the CProgressCtrl::SetStep member function.

CProgressCtrl Overview | Class Members | Hierarchy Chart

See Also CProgressCtrl::SetPos, CProgressCtrl::SetRange, CProgressCtrl::SetStep


CPropertyPage

Objects of class CPropertyPage represent individual pages of a property sheet, otherwise known as a tab dialog box. As with standard dialog boxes, you derive a class from CPropertyPage for each page in your property sheet. To use CPropertyPage-derived objects, first create a CPropertySheet object, and then create an object for each page that goes in the property sheet. Call CPropertySheet::AddPage for each page in the sheet, and then display the property sheet by calling CPropertySheet::DoModal for a modal property sheet, or CPropertySheet::Create for a modeless property sheet.

You can create a type of tab dialog box called a wizard, which consists of a property sheet with a sequence of property pages that guide the user through the steps of an operation, such as setting up a device or creating a newsletter. In a wizard-type tab dialog box, the property pages do not have tabs, and only one property page is visible at a time. Also, instead of having OK and Apply Now buttons, a wizard-type tab dialog box has a Back button, a Next or Finish button, and a Cancel button.

For more information on establishing a property sheet as a wizard, see CPropertySheet::SetWizardMode. For more information on using CPropertyPage objects, see the article Property Sheets in Visual C++ Programmer’s Guide.

#include <afxdlgs.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample BINDENRL | MFC Sample CMNCTRL1 | MFC Sample CMNCTRL2 | MFC Sample HTTPSVR | MFC Sample LISTHDR | MFC Sample ODBCINFO | MFC Sample PROPDLG | MFC Sample SNAPVW

See Also CPropertySheet, CDialog, CPropertySheet::SetWizardMode


CPropertyPage Class Members

Data Members

m_psp The Windows PROPSHEETPAGE structure. Provides access to basic property page parameters.

Construction

CPropertyPage | Constructs a CPropertyPage object.
Construct | Constructs a CPropertyPage object. Use Construct if you want to specify your parameters at run time, or if you are using arrays.

Operations

CancelToClose | Changes the OK button to read Close, and disables the Cancel button, after an unrecoverable change in the page of a modal property sheet.
SetModified | Call to activate or deactivate the Apply Now button.
QuerySiblings | Forwards the message to each page of the property sheet.

Overridables

OnCancel | Called by the framework when the Cancel button is clicked.
OnKillActive | Called by the framework when the current page is no longer the active page. Perform data validation here.
OnOK | Called by the framework when the OK, Apply Now, or Close button is clicked.
OnSetActive | Called by the framework when the page is made the active page.
OnApply | Called by the framework when the Apply Now button is clicked.
OnReset | Called by the framework when the Cancel button is clicked.
OnQueryCancel | Called by the framework when the Cancel button is clicked, and before the cancel has taken place.
OnWizardBack | Called by the framework when the Back button is clicked while using a wizard-type property sheet.
OnWizardNext | Called by the framework when the Next button is clicked while using a wizard-type property sheet.
OnWizardFinish | Called by the framework when the Finish button is clicked while using a wizard-type property sheet.


CPropertyPage::CancelToClose

void CancelToClose( );

Remarks

Call this function after an unrecoverable change has been made to the data in a page of a modal property sheet. This function will change the OK button to Close and disable the Cancel button. This change alerts the user that a change is permanent and the modifications cannot be cancelled.

The CancelToClose member function does nothing in a modeless property sheet, because a modeless property sheet does not have a Cancel button by default.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::OnKillActive, CPropertyPage::SetModified


CPropertyPage::Construct

void Construct( UINT nIDTemplate, UINT nIDCaption = 0 );

void Construct( LPCTSTR lpszTemplateName, UINT nIDCaption = 0 );

Parameters

nIDTemplate

ID of the template used for this page.

nIDCaption

ID of the name to be placed in the tab for this page. If 0, the name will be taken from the dialog template for this page.

lpszTemplateName

Contains a null-terminated string that is the name of a template resource.

Remarks

Call this member function to construct a CPropertyPage object. The object is displayed after all of the following conditions are met:

  • The page has been added to a property sheet using CPropertySheet::AddPage.

  • The property sheet’s DoModal or Create function has been called.

  • The user has selected (tabbed to) this page.

Call Construct if one of the other class constructors has not been called. The Construct member function is flexible because you can leave the parameter statement blank and then specify multiple parameters and construction at any point in your code.

You must use Construct when you work with arrays, and you must call Construct for each member of the array so that the data members are assigned proper values.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::CPropertyPage, CPropertySheet::DoModal, CPropertySheet::AddPage


CPropertyPage::CPropertyPage

CPropertyPage( );

CPropertyPage( UINT nIDTemplate, UINT nIDCaption = 0 );

CPropertyPage( LPCTSTR lpszTemplateName, UINT nIDCaption = 0 );

Parameters

nIDTemplate

ID of the template used for this page.

nIDCaption

ID of the name to be placed in the tab for this page. If 0, the name will be taken from the dialog template for this page.

lpszTemplateName

Points to a string containing the name of the template for this page. Cannot be NULL.

Remarks

Constructs a CPropertyPage object. The object is displayed after all of the following conditions are met:

  • The page has been added to a property sheet using CPropertySheet::AddPage.

  • The property sheet’s DoModal or Create function has been called.

  • The user has selected (tabbed to) this page.

If you have multiple parameters (for example, if you are using an array), use CPropertySheet::Construct instead of CPropertyPage.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::Create, CPropertySheet::DoModal, CPropertySheet::AddPage, CPropertyPage::Construct


CPropertyPage::OnApply

virtual BOOL OnApply( );

Return Value

Nonzero if the changes are accepted; otherwise 0.

Remarks

This member function is called by the framework when the user chooses the OK or the Apply Now button. When the framework calls this function, changes made on all property pages in the property sheet are accepted, the property sheet retains focus, and OnApply returns TRUE (the value 1). Before OnApply can be called by the framework, you must have called SetModified and set its parameter to TRUE. This will activate the Apply Now button as soon as the user makes a change on the property page.

Override this member function to specify what action your program takes when the user clicks the Apply Now button. When overriding, the function should return TRUE to accept changes and FALSE to prevent changes from taking effect.

The default implementation of OnApply calls OnOK.

For more information about notification messages sent when the user presses the Apply Now or OK button in a property sheet, see PSN_APPLY in the Win32 documentation.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::SetModified, CPropertyPage::OnOK


CPropertyPage::OnCancel

virtual void OnCancel( );

Remarks

This member function is called by the framework when the Cancel button is selected. Override this member function to perform Cancel button actions. The default negates any changes that have been made.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::OnApply, CDialog::OnCancel, CPropertyPage::OnOK


CPropertyPage::OnKillActive

virtual BOOL OnKillActive( );

Return Value

Nonzero if data was updated successfully, otherwise 0.

Remarks

This member function is called by the framework when the page is no longer the active page. Override this member function to perform special data validation tasks.

The default implementation of this member function copies settings from the controls in the property page to the member variables of the property page. If the data was not updated successfully due to a dialog data validation (DDV) error, the page retains focus.

After this member function returns successfully, the framework will call the page’s OnOK function.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CWnd::UpdateData, CPropertyPage::OnOK, CPropertyPage::OnSetActive


CPropertyPage::OnOK

virtual void OnOK( );

Remarks

This member function is called by the framework when the user chooses either the OK or Apply Now button, immediately after the framework calls OnKillActive. Override this member function to implement additional behavior specific to the currently active page when user dismisses the entire property sheet.

The default implementation of this member function marks the page as “clean” to reflect that the data was updated in the OnKillActive function.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CDialog::OnOK, CPropertyPage::OnKillActive


CPropertyPage::OnQueryCancel

virtual BOOL OnQueryCancel( );

Return Value

Returns FALSE to prevent the cancel operation or TRUE to allow it.

Remarks

This member function is called by the framework when the user clicks the Cancel button and before the cancel action has taken place.

Override this member function to specify an action the program takes when the user clicks the Cancel button.

The default implementation of OnQueryCancel returns TRUE.


CPropertyPage::OnReset

virtual void OnReset( );

Remarks

This member function is called by the framework when the user chooses the Cancel button. When the framework calls this function, changes to all property pages that were made by the user previously choosing the Apply Now button are discarded, and the property sheet retains focus.

Override this member function to specify what action the program takes when the user clicks the Cancel button.

The default implementation of OnReset does nothing.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::OnCancel, CPropertyPage::OnApply


CPropertyPage::OnSetActive

virtual BOOL OnSetActive( );

Return Value

Nonzero if the page was successfully set active; otherwise 0.

Remarks

This member function is called by the framework when the page is chosen by the user and becomes the active page. Override this member function to perform tasks when a page is activated. Your override of this member function should call the default version before any other processing is done.

The default implementation creates the window for the page, if not previously created, and makes it the active page.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::OnKillActive


CPropertyPage::OnWizardBack

virtual LRESULT OnWizardBack();

Return Value

0 to automatically advance to the next page; –1 to prevent the page from changing. To jump to a page other than the next one, return the identifier of the dialog to be displayed.

Remarks

This member function is called by the framework when the user clicks on the Back button in a wizard.

Override this member function to specify some action the user must take when the Back button is pressed.

For more information on how to make a wizard-type property sheet, see CPropertySheet::SetWizardMode.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::SetWizardMode


CPropertyPage::OnWizardFinish

virtual BOOL OnWizardFinish( );

Return Value

Nonzero if the property sheet is destroyed when the wizard finishes; otherwise zero.

Remarks

This member function is called by the framework when the user clicks on the Finish button in a wizard. When the framework calls this function, the property sheet is destroyed when the Finish button is pressed and OnWizardFinish returns TRUE ( a nonzero value).

Override this member function to specify some action the user must take when the Finish button is pressed. When overriding this function, return FALSE to prevent the property sheet from being destroyed.

For more information about notification messages sent when the user presses the Finish button in a wizard property sheet, see PSN_WIZFINISH in the Win32 documentation.

For more information on how to make a wizard-type property sheet, see CPropertySheet::SetWizardMode.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::SetWizardMode


CPropertyPage::OnWizardNext

virtual LRESULT OnWizardNext();

Return Value

0 to automatically advance to the next page; –1 to prevent the page from changing. To jump to a page other than the next one, return the identifier of the dialog to be displayed.

Remarks

This member function is called by the framework when the user clicks on the Next button in a wizard.

Override this member function to specify some action the user must take when the Next button is pressed.

For more information on how to make a wizard-type property sheet, see CPropertySheet::SetWizardMode.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::SetWizardMode


CPropertyPage::QuerySiblings

LRESULT QuerySiblings( WPARAM wParam, LPARAM lParam );

Return Value

The nonzero value from a page in the property sheet, or 0 if all pages return a value of 0.

Parameters

wParam

Specifies additional message-dependent information.

lParam

Specifies additional message-dependent information

Remarks

Call this member function to forward a message to each page in the property sheet. If a page returns a nonzero value, the property sheet does not send the message to subsequent pages.


CPropertyPage::SetModified

void SetModified( BOOL bChanged = TRUE );

Parameters

bChanged

TRUE to indicate that the property page settings have been modified since the last time they were applied; FALSE to indicate that the property page settings have been applied, or should be ignored.

Remarks

Call this member function to enable or disable the Apply Now button, based on whether the settings in the property page should be applied to the appropriate external object.

The framework keeps track of which pages are “dirty,” that is, property pages for which you have called SetModified( TRUE ). The Apply Now button will always be enabled if you call SetModified( TRUE ) for one of the pages. The Apply Now button will be disabled when you call SetModified( FALSE ) for one of the pages, but only if none of the other pages is “dirty.”

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::CancelToClose


CPropertyPage::m_psp

Remarks

m_psp is a structure whose members store the characteristics of PROPSHEETPAGE. Use this structure to initialize the appearance of a property page after it is constructed.

For more information on this structure, including a listing of its members, see PROPSHEETPAGE in the Windows SDK Programmer’s Reference.

CPropertyPage Overview | Class Members | Hierarchy Chart

See Also CPropertySheet, PROPSHEETPAGE


CPropertyPageEx

CPropertyPageEx provides support for the expanded PROPSHEETPAGE structure introduced in Windows 98 and Windows NT 5. The structure contains additional flags and members that support the following feature:

  • A wide header area to accommodate both a title and a subtitle.

To automatically display the new headers in your property page object, pass valid values for the title and subtitle in the call to CPropertyPageEx::Construct or CPropertyPageEx::CPropertySheetEx.

In all other respects, CPropertyPageEx behaves the same as its base class, CPropertyPage.

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample Wizard97

See Also CPropertySheet, CPropertySheetEx


CPropertyPageEx Class Members

Construction

CPropertyPageEx | Constructs a CPropertyPageEx object.
Construct | Constructs a CPropertyPageEx object.

CPropertyPageEx Overview | Base Class Members | Hierarchy Chart

See Also CPropertyPage, CPropertySheetEx


CPropertyPageEx::Construct

void Construct( UINT nIDTemplate, UINT nIDCaption = 0, UINT nIDHeaderTitle = 0, UINT nIDHeaderSubTitle = 0 );

void Construct( LPCTSTR lpszTemplateName, UINT nIDCaption = 0, UINT nIDHeaderTitle = 0, UINT nIDHeaderSubTitle = 0 );

Parameters

nIDTemplate

ID of the template used for this page.

lpszTemplateName

A pointer to a string containing the name of the template used for this page.

nIDCaption

ID of the name to be placed in the tab for this page. If 0, the name will be taken from the dialog template for this page. By default, 0.

nIDHeaderTitle

ID of the name to be placed in the title location of the property page header. By default, 0.

nIDHeaderSubTitle

ID of the name to be placed in the subtitle location of the property page header. By default, 0.

Remarks

Call this member function to construct a CPropertyPageEx object.

Use Construct if you want to specify your parameters at run time, or if you are using arrays.

CPropertyPageEx Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::Construct, CPropertyPageEx::CPropertyPageEx


CPropertyPageEx::CPropertyPageEx

CPropertyPageEx( );

CPropertyPageEx( UINT nIDTemplate, UINT nIDCaption = 0, UINT nIDHeaderTitle = 0, UINT nIDHeaderSubTitle = 0 );

CPropertyPageEx( LPCTSTR lpszTemplateName, UINT nIDCaption = 0, UINT nIDHeaderTitle = 0, UINT nIDHeaderSubTitle = 0 );

Parameters

nIDTemplate

ID of the template used for this page.

nIDCaption

ID of the name to be placed in the tab for this page. If 0, the name will be taken from the dialog template for this page.

nIDHeaderTitle

ID of the name to be placed in the title location of the property page header.

nIDHeaderSubTitle

ID of the name to be placed in the subtitle location of the property page header.

lpszTemplateName

A pointer to a string containing the name of the template used for this page.

Remarks

Call this member function to construct a CPropertyPageEx object. The object is displayed after all of the following conditions are met:

  • The page has been added to a property sheet using CPropertySheetEx::AddPage.

  • The property sheet’s DoModal or Create function has been called.

  • The user has selected (tabbed to) this page.

If you have multiple parameters (for example, if you are using an array), use Construct instead of CPropertyPageEx.

CPropertyPageEx Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::CPropertyPage


CPropertySheet

Objects of class CPropertySheet represent property sheets, otherwise known as tab dialog boxes. A property sheet consists of a CPropertySheet object and one or more CPropertyPage objects. A property sheet is displayed by the framework as a window with a set of tab indices, with which the user selects the current page, and an area for the currently selected page.

Even though CPropertySheet is not derived from CDialog, managing a CPropertySheet object is similar to managing a CDialog object. For example, creation of a property sheet requires two-part construction: call the constructor, and then call DoModal for a modal property sheet or Create for a modeless property sheet. CPropertySheet has two types of constructors: CPropertySheet::Construct and CPropertySheet::CPropertySheet.

Exchanging data between a CPropertySheet object and some external object is similar to exchanging data with a CDialog object. The important difference is that the settings of a property sheet are normally member variables of the CPropertyPage objects rather than of the CPropertySheet object itself.

You can create a type of tab dialog box called a wizard, which consists of a property sheet with a sequence of property pages that guide the user through the steps of an operation, such as setting up a device or creating a newsletter. In a wizard-type tab dialog box, the property pages do not have tabs, and only one property page is visible at a time. Also, instead of having OK and Apply Now buttons, a wizard-type tab dialog box has a Back button, a Next or Finish button, a Cancel button, and a Help button.

To create a wizard-type dialog box, follow the same steps you would follow to create a standard property sheet, but call SetWizardMode before you call DoModal. To enable the wizard buttons, call SetWizardButtons, using flags to customize their function and appearance. To enable the Finish button, call SetFinishText after the user has taken action on the last page of the wizard.

For more information on how to use CPropertySheet objects, see the article Property Sheets in Visual C++ Programmer’s Guide.

#include <afxdlgs.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample BINDENRL | MFC Sample CMNCTRL1 | MFC Sample CMNCTRL2 | MFC Sample LISTHDR | MFC Sample PROPDLG | MFC Sample SNAPVW


CPropertySheet Class Members

Data Members

m_psh The Windows PROPSHEETHEADER structure. Provides access to basic property sheet parameters.

Construction

CPropertySheet | Constructs a CPropertySheet object.
Construct | Constructs a CPropertySheet object.

Attributes

GetActiveIndex | Retrieves the index of the active page of the property sheet.
GetPageIndex | Retrieves the index of the specified page of the property sheet.
GetPageCount | Retrieves the number of pages in the property sheet.
GetPage | Retrieves a pointer to the specified page.
GetActivePage | Returns the active page object.
SetActivePage | Programmatically sets the active page object.
SetTitle | Sets the caption of the property sheet.
GetTabControl | Retrieves a pointer to a tab control.
SetFinishText | Sets the text for the Finish button.
SetWizardButtons | Enables the wizard buttons.
SetWizardMode | Enables the wizard mode.
EnableStackedTabs | Indicates whether the property sheet uses stacked or scrolling tabs.

Operations

DoModal | Displays a modal property sheet.
Create | Displays a modeless property sheet.
AddPage | Adds a page to the property sheet.
RemovePage | Removes a page from the property sheet.
PressButton | Simulates the choice of the specified button in a property sheet.
EndDialog | Terminates the property sheet.


CPropertySheet::AddPage

void AddPage( CPropertyPage *pPage );

Parameters

pPage

Points to the page to be added to the property sheet. Cannot be NULL.

Remarks

This member function adds the supplied page with the rightmost tab in the property sheet. Add pages to the property sheet in the left-to-right order you want them to appear.

AddPage adds the CPropertyPage object to the CPropertySheet object’s list of pages but does not actually create the window for the page. The framework postpones creation of the window for the page until the user selects that page.

When you add a property page using AddPage, the CPropertySheet is the parent of the CPropertyPage. To gain access to the property sheet from the property page, call CWnd::GetParent.

It is not necessary to wait until creation of the property sheet window to call AddPage. Typically, you will call AddPage before calling DoModal or Create.

If you call AddPage after displaying the property page, the tab row will reflect the newly added page.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::RemovePage


CPropertySheet::Construct

void Construct( UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0 );

void Construct( LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0 );

Parameters

nIDCaption

ID of the caption to be used for the property sheet.

pParentWnd

Pointer to the parent window of the property sheet. If NULL, the parent window will be the main window of the application.

iSelectPage

The index of the page that will initially be on top. Default is the first page added to the sheet.

pszCaption

Pointer to a string containing the caption to be used for the property sheet. Cannot be NULL.

Remarks

Call this member function to construct a CPropertySheet object. Call this member function if one of the class constructors has not already been called. For example, call Construct when you declare or allocate arrays of CPropertySheet objects. In the case of arrays, you must call Construct for each member in the array.

To display the property sheet, call DoModal or Create. The string contained in the first parameter will be placed in the caption bar for the property sheet.

Example

The following example demonstrates under what circumstances you would call Construct.

int i;
CPropertySheet   grpropsheet[4];
CPropertySheet   someSheet;   // no need to call Construct for this one

UINT rgID[4] = {IDD_SHEET1, IDD_SHEET2, IDD_SHEET3, IDD_SHEET4};

for (i = 0; i < 4; i++)
    grpropsheet[i].Construct(rgID[i]);

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::CPropertySheet, CPropertySheet::DoModal, CPropertySheet::Create


CPropertySheet::CPropertySheet

CPropertySheet( );

CPropertySheet( UINT nIDCaption, CWnd *pParentWnd = NULL, UINT iSelectPage = 0 );

CPropertySheet( LPCTSTR pszCaption, CWnd *pParentWnd = NULL, UINT iSelectPage = 0 );

Parameters

nIDCaption

ID of the caption to be used for the property sheet.

pParentWnd

Points to the parent window of the property sheet. If NULL, the parent window will be the main window of the application.

iSelectPage

The index of the page that will initially be on top. Default is the first page added to the sheet.

pszCaption

Points to a string containing the caption to be used for the property sheet. Cannot be NULL.

Remarks

Use this member function to construct a CPropertySheet object. To display the property sheet, call DoModal or Create. The string contained in the first parameter will be placed in the caption bar for the property sheet.

If you have multiple parameters (for example, if you are using an array), use Construct instead of CPropertySheet.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::Construct, CPropertySheet::DoModal, CPropertySheet::Create, CPropertyPage


CPropertySheet::Create

BOOL Create( CWnd* pParentWnd = NULL, DWORD dwStyle = (DWORD)–1, DWORD dwExStyle = 0 );

Return Value

Nonzero if the property sheet is created successfully; otherwise 0.

Parameters

pParentWnd

Points to parent window. If NULL, parent is the desktop.

dwStyle

Window styles for property sheet. For a complete list of available styles, see Window Styles.

dwExStyle

Extended window styles for property sheet. For a complete list of available styles, see Extended Window Styles

Remarks

Call this member function to display a modeless property sheet. The call to Create can be inside the constructor, or you can call it after the constructor is invoked.

The default style, expressed by passing –1 as dwStyle, is actually WS_SYSMENU | WS_POPUP | WS_CAPTION | DS_MODALFRAME | DS_CONTEXT_HELP | WS_VISIBLE. The default extended window style, expressed by passing 0 as dwExStyle, is actually WS_EX_DLGMODALFRAME.

The Create member function returns immediately after creating the property sheet. To destroy the property sheet, call CWnd::DestroyWindow.

Modeless property sheets displayed with a call to Create do not have OK, Cancel, Apply Now, and Help buttons as modal property sheets do. Desired buttons must be created by the user.

To display a modal property sheet, call DoModal instead.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CDialog::Create, CPropertySheet::DoModal


CPropertySheet::DoModal

virtual int DoModal( );

Return Value

IDOK or IDCANCEL if the function was successful; otherwise 0 or -1. If the property sheet has been established as a wizard (see SetWizardMode), DoModal returns either ID_WIZFINISH or IDCANCEL.

Remarks

Call this member function to display a modal property sheet. The return value corresponds to the ID of the control that closed the property sheet. After this function returns, the windows corresponding to the property sheet and all the pages will have been destroyed. The objects themselves will still exist. Typically, you will retrieve data from the CPropertyPage objects after DoModal returns IDOK.

To display a modeless property sheet, call Create instead.

Note The first time a property page is created from its corresponding dialog resource, it may cause a first-chance exception. This is a result of the property page changing the style of the dialog resource to the required style prior to creating the page. Because resources are generally read-only, this causes an exception. The exception is handled by the system, and a copy of the modified resource is made automatically by the system. The first-chance exception can thus be ignored.

Since this exception must be handled by the operating system, do not wrap calls to CPropertySheet::DoModal with a C++ try/catch block in which the catch handles all exceptions, for example, catch (...). This will handle the exception intended for the operating system, causing unpredictable behavior. Using C++ exception handling with specific exception types or using structured exception handling where the Access Violation exception is passed through to the operating system is safe, however.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CDialog::DoModal, CPropertySheet::Create


CPropertySheet::EnableStackedTabs

void EnableStackedTabs( BOOL bStacked );

Parameters

bStacked

Indicates whether stacked tabs are enabled in the property sheet. Disable stacked rows of tags by setting bStacked to FALSE.

Remarks

Call this member function to indicate whether to stack rows of tabs in a property sheet. By default, if a property sheet has more tabs than will fit in a single row in the width of the property sheet, the tabs will stack in multiple rows. To use scrolling tabs instead of stacking tabs, call EnableStackedTabs with bStacked set to FALSE before calling DoModal or Create.

You must call EnableStackedTabs when you create a modal or a modeless property sheet. To incorporate this style in a CPropertySheet-derived class, write a message handler for WM_CREATE. In the overridden version of CWnd::OnCreate, call EnableStackedTabs( FALSE ) before calling the base class implementation.

Example

int CMyPropertySheet::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
      // Set for Scrolling Tabs style
      EnableStackedTabs(FALSE);
      // Call the base class
      if (CPropertySheet::OnCreate(lpCreateStruct) == -1)
            return -1;
      // TODO: Add your specialized creation code here
      return 0;
}


CPropertySheet::EndDialog

void EndDialog( int nEndID );

Parameters

nEndID

Identifier to be used as return value of the property sheet.

Remarks

Use this member function to terminate the property sheet. This member function is called by the framework when the OK, Cancel, or Close button is pressed. Call this member function if an event occurs that should close the property sheet.

This member function is only used with a modal dialog box.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertyPage::OnOK, CPropertyPage::OnCancel, CWnd::DestroyWindow


CPropertySheet::GetActiveIndex

int GetActiveIndex( ) const;

Return Value

The index number of the active page.

Remarks

Call this member function to get the index number of the property sheet window’s active page, then use the returned index number as the parameter for GetPage.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::GetPage, CPropertySheet::GetActivePage


CPropertySheet::GetActivePage

CPropertyPage* GetActivePage( ) const;

Return Value

The pointer to the active page.

Remarks

Call this member function to retrieve the property sheet window’s active page. Use this member function to perform some action on the active page.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::GetPage


CPropertySheet::GetPage

CPropertyPage* GetPage( int nPage ) const;

Return Value

The pointer to the page corresponding to the nPage parameter.

Parameters

nPage

Index of the desired page, starting at 0. Must be between 0 and one less than the number of pages in the property sheet, inclusive.

Remarks

This member function returns a pointer to the specified page in this property sheet.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::AddPage, CPropertySheet::GetActivePage, CPropertySheet::GetPageCount, CPropertySheet::RemovePage, CPropertySheet::SetTitle


CPropertySheet::GetPageIndex

int GetPageIndex( CPropertyPage* pPage ) const;

Return Value

The index number of a page.

Parameters

pPage

Points to the page with the index to be found. Cannot be NULL.

Remarks

Use this member function to retrieve the index number of the specified page in the property sheet. For example, you would use GetPageIndex to get the page index in order to use SetActivePage or GetPage.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::SetActivePage, CPropertySheet::GetPage


CPropertySheet::GetPageCount

int GetPageCount( );

Return Value

The number of pages in the property sheet.

Remarks

Call this member function to determine the number of pages currently in the property sheet.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::GetPage, CPropertySheet::AddPage, CPropertySheet::RemovePage


CPropertySheet::GetTabControl

CTabCtrl* GetTabControl( );

Return Value

A pointer to a tab control.

Remarks

Use this member function to retrieve a pointer to a tab control to do something specific to the tab control (that is, to use any of the APIs in CTabCtrl). For example, call this member function if you want to add bitmaps to each of the tabs during initialization.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::CTabCtrl


CPropertySheet::PressButton

BOOL PressButton( int nButton );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nButton

nButton : Identifies the button to be pressed. This parameter can be one of the following values:

  • PSBTN_BACK Chooses the Back button.

  • PSBTN_NEXT Chooses the Next button.

  • PSBTN_FINISH Chooses the Finish button.

  • PSBTN_OK Chooses the OK button.

  • PSBTN_APPLYNOW Chooses the Apply Now button.

  • PSBTN_CANCEL Chooses the Cancel button.

  • PSBTN_HELP Chooses the Help button.

Remarks

Call this member function to simulate the choice of the specified button in a property sheet. See PSM_PRESSBUTTON for more information about the Windows SDK Pressbutton message.


CPropertySheet::RemovePage

void RemovePage( CPropertyPage *pPage );

void RemovePage( int nPage );

Parameters

pPage

Points to the page to be removed from the property sheet. Cannot be NULL.

nPage

Index of the page to be removed. Must be between 0 and one less than the number of pages in the property sheet, inclusive.

Remarks

This member function removes a page from the property sheet and destroys the associated window. The CPropertyPage object itself is not destroyed until the owner of the CPropertySheet window is closed.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::AddPage


CPropertySheet::SetActivePage

BOOL SetActivePage( int nPage );

BOOL SetActivePage( CPropertyPage* pPage );

Return Value

Nonzero if the property sheet is activated successfully; otherwise 0.

Parameters

nPage

Index of the page to set. It must be between 0 and one less than the number of pages in the property sheet, inclusive.

pPage

Points to the page to set in the property sheet. It cannot be NULL.

Remarks

Use this member function to change the active page. For example, use SetActivePage if a user’s action on one page should cause another page to become the active page.


CPropertySheet::SetFinishText

void SetFinishText( LPCTSTR lpszText );

Parameters

lpszText

Points to the text to be displayed on the Finish command button.

Remarks

Call this member function to set the text in the Finish command button. Call SetFinishText to display the text on the Finish command button and hide the Next and Back buttons after the user completes action on the last page of the wizard.


CPropertySheet::SetTitle

void SetTitle( LPCTSTR lpszText, UINT nStyle = 0 );

Parameters

nStyle

Specifies the style of the property sheet title. The style must be specified at 0 or as PSH_PROPTITLE. If the style is set as PSH_PROPTITLE, the words "Properties for" appear before the text specified as the caption.

lpszText

Points to the text to be used as the caption in the title bar of the property sheet.

Remarks

Call this member function to specify the property sheet's caption (the text displayed in the title bar of a frame window).

By default, a property sheet uses the caption parameter in the property sheet constructor.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::GetPage, CPropertySheet::GetActivePage


CPropertySheet::SetWizardButtons

void SetWizardButtons( DWORD dwFlags );

Parameters

dwFlags

A set of flags that customize the function and appearance of the wizard buttons. This parameter can be a combination of the following values:

  • PSWIZB_BACK Back button

  • PSWIZB_NEXT Next button

  • PSWIZB_FINISH Finish button

  • PSWIZB_DISABLEDFINISH Disabled Finish button

Remarks

Call this member function to enable or disable the Back, Next, or Finish button in a wizard property sheet. Call SetWizardButtons only after the dialog is open; you can’t call SetWizardButtons before you call DoModal. Typically, you should call SetWizardButtons from CPropertyPage::OnSetActive.

If you want to change the text on the Finish button or hide the Next and Back buttons once the user has completed the wizard, call SetFinishText. Note that the same button is shared for Finish and Next. You can display a Finish or a Next button at one time, but not both.


CPropertySheet::SetWizardMode

void SetWizardMode( );

Remarks

Call this member function to establish a property page as a wizard. A key characteristic of a wizard property page is that the user navigates using Next or Finish, Back, and Cancel buttons instead of tabs.

Call SetWizardMode before calling DoModal. After you call SetWizardMode, DoModal will return either ID_WIZFINISH (if the user closes with the Finish button) or IDCANCEL.

SetWizardMode sets the PSF_WIZARD flag.

Example

CPropertySheet dlg;
CPropertyPage page1, page2;

dlg.AddPage(&page1);
dlg.AddPage(&page2);
dlg.SetWizardMode();
dlg.DoModal();

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::DoModal


CPropertySheet::m_psh

Remarks

m_psh is a structure whose members store the characteristics of PROPSHEETHEADER. Use this structure to initialize the appearance of the property sheet after it is constructed but before it is displayed with the DoModal member function. For example, set the dwSize member of m_psh to the size you want the property sheet to have.

For more information on this structure, including a listing of its members, see PROPSHEETHEADER in the Windows SDK Programmer’s Reference.

CPropertySheet Overview | Class Members | Hierarchy Chart

See Also CPropertySheet::DoModal


CPropertySheetEx

CPropertySheetEx provides support for the expanded PROPSHEETHEADER structure introduced in Windows 98 and Windows NT 5. The structure contains additional flags and members that support the following feature:

  • A "watermark" background bitmap.

To automatically display these new images in your property sheet object, pass valid values for the bitmap and palette images in the call to CPropertySheetEx::Construct or CPropertySheetEx::CPropertySheetEx.

In all other respects, CPropertySheetEx behaves the same as its base class, CPropertySheet.

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample Wizard97

See Also CPropertyPage, CPropertyPageEx


CPropertySheetEx Class Members

Construction

CPropertySheetEx | Constructs a CPropertySheetEx object.
Construct | Constructs a CPropertySheetEx object. Use with a property page that has multiple parameters.

Data Members

m_psh The PROPSHEETHEADER structure whose members contain the characteristics of the property sheet to be created.

Operations

AddPage Adds a page to the property sheet.

CPropertySheetEx Overview | Base Class Members | Hierarchy Chart

See Also CPropertyPage, CPropertyPageEx


CPropertySheetEx::AddPage

void AddPage( CPropertyPageEx* pPage );

Parameters

pPage

Points to the page to be added to the property sheet. Cannot be NULL.

Remarks

Call this member function to add a property page to the property sheet. Add pages to the property sheet in the left-to-right order you want them to appear.

See CPropertySheet::AddPage for more information about adding a page to a property sheet.


CPropertySheetEx::Construct

void Construct( UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0, HBITMAP hbmWatermark = NULL, HPALETTE hpalWatermark = NULL, HBITMAP hbmHeader = NULL );

void Construct( LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0, HBITMAP hbmWatermark = NULL, HPALETTE hpalWatermark = NULL, HBITMAP hbmHeader = NULL );

Parameters

nIDCaption

ID of the caption to be used for the property sheet.

pParentWnd

Pointer to the parent window of the property sheet. If NULL, the parent window will be the main window of the application.

iSelectPage

The index of the page that will initially be on top. Default is the first page added to the sheet.

hbmWatermark

Handle to the watermark bitmap of the property page.

hpalWatermark

Handle to the palette of the watermark bitmap and/or header bitmap.

hbmHeader

Handle to the header bitmap of the property page.

pszCaption

Pointer to a string containing the caption to be used for the property sheet. Cannot be NULL.

Remarks

Call this member function to construct a CPropertySheetEx object. For more information, see CPropertySheet::Construct.

To display the property sheet, call DoModal or Create. The string contained in the first parameter will be placed in the caption bar for the property sheet.

The watermark and/or header images are automatically displayed if valid values are passed in the call to Construct.

CPropertySheetEx Overview | Class Members | Hierarchy Chart

See Also CPropertySheetEx::CPropertySheetEx, Graphic Objects in Visual C++ Programmer’s Guide


CPropertySheetEx::CPropertySheetEx

CPropertySheetEx( );

CPropertySheetEx( UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0, HBITMAP hbmWatermark = NULL, HPALETTE hpalWatermark = NULL, HBITMAP hbmHeader = NULL );

CPropertySheetEx( LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0, HBITMAP hbmWatermark = NULL, HPALETTE hpalWatermark = NULL, HBITMAP hbmHeader = NULL );

Parameters

nIDCaption

ID of the caption to be used for the property sheet.

pParentWnd

Points to the parent window of the property sheet. If NULL, the parent window will be the main window of the application.

iSelectPage

The index of the page that will initially be on top. Default is the first page added to the sheet.

hbmWatermark

A handle to the background bitmap of the property sheet.

hpalWatermark

Handle to the palette of the watermark bitmap and/or header bitmap.

hbmHeader

Handle to the header bitmap of the property page.

pszCaption

Pointer to a string containing the caption to be used for the property sheet. Cannot be NULL.

Remarks

Call this member function to construct a CPropertySheetEx object. To display the property sheet, call DoModal or Create. The string contained in the first parameter will be placed in the caption bar for the property sheet.

If you have multiple parameters (for example, if you are using an array), use CPropertySheetEx::Construct instead of CPropertySheetEx.

The watermark and/or header images are automatically displayed if valid values are passed in the call to CPropertySheetEx.

CPropertySheetEx Overview | Class Members | Hierarchy Chart

See Also CPropertySheetEx::Construct, Graphic Objects in Visual C++ Programmer’s Guide


CPropertySheetEx::m_psh

Remarks

A structure whose members store the characteristics of PROPSHEETHEADER. Use this structure to initialize the appearance of the property sheet after it is constructed but before it is displayed with CPropertySheet::DoModal. For example, set the dwSize member of m_psh to the size you want the property sheet to have.

For more information on this structure, including a listing of its members, see PROPSHEETHEADER in the Platform SDK.

CPropertySheetEx Overview | Class Members | Hierarchy Chart

See Also CPropertySheetEx::Construct


CPropExchange

CPropExchange does not have a base class.

Establishes the context and direction of a property exchange.

The CPropExchange class supports the implementation of persistence for your OLE controls. Persistence is the exchange of the control’s state information, usually represented by its properties, between the control itself and a medium.

The framework constructs an object derived from CPropExchange when it is notified that an OLE control’s properties are to be loaded from or stored to persistent storage.

The framework passes a pointer to this CPropExchange object to your control’s DoPropExchange function. If you used ClassWizard to create the starter files for your control, your control’s DoPropExchange function calls COleControl::DoPropExchange. The base-class version exchanges the control’s stock properties; you modify your derived class’s version to exchange properties you have added to your control.

CPropExchange can be used to serialize a control’s properties or initialize a control’s properties upon the load or creation of a control. The ExchangeProp and ExchangeFontProp member functions of CPropExchange are able to store properties to and load them from different media.

For more information on using CPropExchange, see the article ActiveX Controls: Property Pages in Visual C++ Programmer’s Guide.

#include <afxctl.h>

Class Members | Hierarchy Chart

Sample MFC Sample FIRE

See Also COleControl::DoPropExchange


CPropExchange Class Members

Operations

ExchangeFontProp | Exchanges a font property.
ExchangeProp | Exchanges properties of any built-in type.
ExchangeBlobProp | Exchanges a binary large object (BLOB) property.
ExchangePersistentProp | Exchanges a property between a control and a file.
ExchangeVersion | Exchanges the version number of an OLE control.
IsLoading | Indicates whether properties are being loaded into the control or saved from it.
GetVersion | Retrieves the version number of an OLE control.


CPropExchange::ExchangeBlobProp

virtual BOOL ExchangeBlobProp( LPCTSTR pszPropName, void** ppvBlob, const void* pvBlobDefault = NULL ) = 0;

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pszPropName

The name of the property being exchanged.

ppvBlob

Pointer to a variable pointing to where the property is stored (variable is typically a member of your class).

pvBlobDefault

Default value for the property.

Remarks

Serializes a property that stores binary large object (BLOB) data.

The property’s value is read from or written to, as appropriate, the variable referenced by ppvBlob. If pvBlobDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization fails.

The functions CArchivePropExchange::ExchangeBlobProp, CResetPropExchange::ExchangeBlobProp, and CPropsetPropExchange::ExchangeBlobProp override this pure virtual function.

CPropExchange Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange, CPropExchange::ExchangeFontProp, CPropExchange::ExchangePersistentProp, CPropExchange::ExchangeProp


CPropExchange::ExchangeFontProp

virtual BOOL ExchangeFontProp( LPCTSTR pszPropName, CFontHolder& font, const FONTDESC FAR* pFontDesc, LPFONTDISP pFontDispAmbient ) = 0;

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pszPropName

The name of the property being exchanged.

font

A reference to a CFontHolder object that contains the font property.

pFontDesc

A pointer to a FONTDESC structure containing values for initializing the default state of the font property when pFontDispAmbient is NULL.

pFontDispAmbient

A pointer to the IFontDisp interface of a font to be used for initializing the default state of the font property.

Remarks

Exchanges a font property between a storage medium and the control.

If the font property is being loaded from the medium to the control, the font’s characteristics are retrieved from the medium and the CFontHolder object referenced by font is initialized with them. If the font property is being stored, the characteristics in the font object are written to the medium.

The functions CArchivePropExchange::ExchangeFontProp, CResetPropExchange::ExchangeFontProp, and CPropsetPropExchange::ExchangeFontProp override this pure virtual function.

CPropExchange Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange, CPropExchange::ExchangeBlobProp, CPropExchange::ExchangePersistentProp, CPropExchange::ExchangeProp


CPropExchange::ExchangePersistentProp

virtual BOOL ExchangePersistentProp( LPCTSTR pszPropName, LPUNKNOWN FAR* ppUnk, REFIID iid, LPUNKNOWN pUnkDefault ) = 0;

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pszPropName

The name of the property being exchanged.

ppUnk

A pointer to a variable containing a pointer to the property’s IUnknown interface (this variable is typically a member of your class).

iid

Interface ID of the interface on the property that the control will use.

pUnkDefault

Default value for the property.

Remarks

Exchanges a property between the control and a file.

If the property is being loaded from the file to the control, the property is created and initialized from the file. If the property is being stored, its value is written to the file.

The functions CArchivePropExchange::ExchangePersistentProp, CResetPropExchange::ExchangePersistentProp, and CPropsetPropExchange::ExchangePersistentProp override this pure virtual function.

CPropExchange Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange, CPropExchange::ExchangeBlobProp, CPropExchange::ExchangeFontProp, CPropExchange::ExchangeProp


CPropExchange::ExchangeProp

virtual BOOL ExchangeProp( LPCTSTR pszPropName, VARTYPE vtProp, void* pvProp, const void* pvDefault = NULL ) = 0;

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pszPropName

The name of the property being exchanged.

vtProp

A symbol specifying the type of the property being exchanged. Possible values are:

Symbol | Property Type
VT_I2 | short
VT_I4 | long
VT_BOOL | BOOL
VT_BSTR | CString
VT_CY | CY
VT_R4 | float
VT_R8 | double

pvProp

A pointer to the property’s value.

pvDefault

Pointer to a default value for the property.

Remarks

Exchanges a property between a storage medium and the control.

If the property is being loaded from the medium to the control, the property’s value is retrieved from the medium and stored in the object pointed to by pvProp. If the property is being stored to the medium, the value of the object pointed to by pvProp is written to the medium.

The functions CArchivePropExchange::ExchangeProp, CResetPropExchange::ExchangeProp, and CPropsetPropExchange::ExchangeProp override this pure virtual function.

CPropExchange Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange, CPropExchange::ExchangeBlobProp, CPropExchange::ExchangeFontProp, CPropExchange::ExchangePersistentProp


CPropExchange::ExchangeVersion

BOOL ExchangeVersion( DWORD& dwVersionLoaded, DWORD dwVersionDefault, BOOL bConvert );

Return Value

Nonzero if the function succeeded; 0 otherwise.

Parameters

dwVersionLoaded

Reference to a variable where the version number of the persistent data being loaded will be stored.

dwVersionDefault

The current version number of the control.

bConvert

Indicates whether to convert persistent data to the current version or keep it at the same version that was loaded.

Remarks

Called by the framework to handle persistence of a version number.

CPropExchange Overview | Class Members | Hierarchy Chart

See Also COleControl::ExchangeVersion


CPropExchange::GetVersion

DWORD GetVersion( );

Return Value

The version number of the control.

Remarks

Call this function to retrieve the version number of the control.


CPropExchange::IsLoading

BOOL IsLoading( );

Return Value

Nonzero if properties are being loaded; otherwise 0.

Remarks

Call this function to determine whether properties are being loaded to the control or saved from it.

CPropExchange Overview | Class Members | Hierarchy Chart

See Also COleControl::DoPropExchange


CPtrArray

The CPtrArray class supports arrays of void pointers.

The member functions of CPtrArray are similar to the member functions of class CObArray. Because of this similarity, you can use the CObArray reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a pointer to void.

CObject* CObArray::GetAt( int <nIndex> ) const;

for example, translates to

void* CPtrArray::GetAt( int <nIndex> ) const;

CPtrArray incorporates the IMPLEMENT_DYNAMIC macro to support run-time type access and dumping to a CDumpContext object. If you need a dump of individual pointer array elements, you must set the depth of the dump context to 1 or greater.

Note Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

Pointer arrays cannot be serialized.

When a pointer array is deleted, or when its elements are removed, only the pointers are removed, not the entities they reference.

For more information on using CPtrArray, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

See Also CObArray


CPtrArray Class Members

Construction

CPtrArray Constructs an empty array for void pointers.

Bounds

GetSize | Gets number of elements in this array.
GetUpperBound | Returns the largest valid index.
SetSize | Sets the number of elements to be contained in this array.

Operations

FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.

Element Access

GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; array is not allowed to grow.
ElementAt | Returns a temporary reference to the element pointer within the array.
GetData | Allows access to elements in the array. Can be NULL.

Growing the Array

SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds an element to the end of the array; grows the array if necessary.
Append | Appends another array to the array; grows the array if necessary.
Copy | Copies another array to the array; grows the array if necessary.

Insertion/Removal

InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.

Operators

operator [] Sets or gets the element at the specified index.


CPtrList

The CPtrList class supports lists of void pointers.

The member functions of CPtrList are similar to the member functions of class CObList. Because of this similarity, you can use the CObList reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a pointer to void.

CObject*& CObList::GetHead() const;

for example, translates to

void*& CPtrList::GetHead() const;

CPtrList incorporates the IMPLEMENT_DYNAMIC macro to support run-time type access and dumping to a CDumpContext object. If you need a dump of individual pointer list elements, you must set the depth of the dump context to 1 or greater.

Pointer lists cannot be serialized.

When a CPtrList object is deleted, or when its elements are removed, only the pointers are removed, not the entities they reference.

For more information on using CPtrList, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

See Also CObList


CPtrList Class Members

Construction

CPtrList Constructs an empty list for void pointers.

Head/Tail Access

GetHead | Returns the head element of the list (cannot be empty).
GetTail | Returns the tail element of the list (cannot be empty).

Operations

RemoveHead | Removes the element from the head of the list.
RemoveTail | Removes the element from the tail of the list.
AddHead | Adds an element (or all the elements in another list) to the head of the list (makes a new head).
AddTail | Adds an element (or all the elements in another list) to the tail of the list (makes a new tail).
RemoveAll | Removes all the elements from this list.

Iteration

GetHeadPosition | Returns the position of the head element of the list.
GetTailPosition | Returns the position of the tail element of the list.
GetNext | Gets the next element for iterating.
GetPrev | Gets the previous element for iterating.

Retrieval/Modification

GetAt | Gets the element at a given position.
SetAt | Sets the element at a given position.
RemoveAt | Removes an element from this list, specified by position.

Insertion

InsertBefore | Inserts a new element before a given position.
InsertAfter | Inserts a new element after a given position.

Searching

Find | Gets the position of an element specified by pointer value.
FindIndex | Gets the position of an element specified by a zero-based index.

Status

GetCount | Returns the number of elements in this list.
IsEmpty | Tests for the empty list condition (no elements).


CReBar

A CReBar object is a control bar that provides layout, persistence, and state information for rebar controls.

A rebar object can contain a variety of child windows, usually other controls, including edit boxes, toolbars, and list boxes. A rebar object can display its child windows over a specified bitmap. Your application can automatically resize the rebar, or the user can manually resize the rebar by clicking or dragging its gripper bar.

Rebar Control

A rebar object behaves similarly to a toolbar object. A rebar uses the click-and-drag mechanism to resize its bands. A rebar control can contain one or more bands, with each band having any combination of a gripper bar, a bitmap, a text label, and a child window. However, bands cannot contain more than one child window.

CReBar uses the CReBarCtrl class to provide its implementation. You can access the rebar control through GetReBarCtrl to take advantage of the control's customization options. For more information about rebar controls, see CReBarCtrl. For more information about using rebar controls, see Using CReBarCtrl in the Visual C++ Programmer's Guide.

Warning Rebar and rebar control objects do not support MFC control bar docking. If CRebar::EnableDocking is called, your application will assert.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MFCIE


CReBar Class Members

Construction

Create Creates the rebar control and attaches it to the CReBar object.

Attributes

GetReBarCtrl | Allows direct access to the underlying common control.
AddBar | Adds a band to a rebar.


CReBar::AddBar

BOOL AddBar( CWnd* pBar, LPCTSTR lpszText = NULL, CBitmap* pbmp = NULL, DWORD dwStyle = RBBS_GRIPPERALWAYS | RBBS_FIXEDBMP );

BOOL AddBar( CWnd* pBar, COLORREF clrFore, COLORREF clrBack, LPCTSTR pszText = NULL, DWORD dwStyle = RBBS_GRIPPERALWAYS );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pBar

A pointer to a CWnd object that is the child window to be inserted into the rebar. The referenced object must have a WS_CHILD.

lpszText

A pointer to a string containing the text to appear on the rebar. NULL by default. The text contained in pszText is not part of the child window; it is on the rebar itself.

pbmp

A pointer to a CBitmap object to be displayed on the rebar background. NULL by default.

dwStyle

A DWORD containing the style to apply to the rebar. See the fStyle function description in the Win32 structure REBARBANDINFO for a complete list of band styles.

clrFore

A COLORREF value that represents the foreground color of the rebar.

clrBack

A COLORREF value that represents the background color of the rebar.

Remarks

Call this member function to add a band to the rebar.

CReBar Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl


CReBar::Create

BOOL Create( CWnd* pParentWnd, DWORD dwCtrlStyle = RBS_BANDBORDERS, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_TOP, UINT nID = AFX_IDW_REBAR );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pParentWnd

Pointer to the CWnd object whose Windows window is the parent of the status bar. Normally your frame window.

dwCtrlStyle

The rebar control style. By default, RBS_BANDBORDERS, which displays narrow lines to separate adjacent bands within the rebar control. See Rebar Control Styles in the Platform SDK for a list of styles.

dwStyle

The rebar window styles.

nID

The rebar's child-window ID.

Remarks

Call this member function to create a rebar.

CReBar Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl


CReBar::GetReBarCtrl

CReBarCtrl& GetReBarCtrl( ) const;

Return Value

A reference to a CReBarCtrl object.

Remarks

This member function allows direct access to the underlying common control.

Call this member function to take advantage of the functionality of the Windows rebar common control in customizing your rebar. When you call GetReBarCtrl, it returns a reference object to the CReBarCtrl object so you can use either set of member functions.

For more information about using CReBarCtrl to customize your rebar, see Using CReBarCtrl in the Visual C++ Programmer’s Guide.


CReBarCtrl

The CReBarCtrl class encapsulates the functionality of a rebar control, which is a container for a child window. The application in which the rebar control resides assigns the child window contained by the rebar control to the rebar band. The child window is usually another common control.

Rebar controls contain one or more bands. Each band can contain a combination of a gripper bar, a bitmap, a text label, and a child window. The band can contain only one of each of these items.

The rebar control can display the child window over a specified background bitmap. All rebar control bands can be resized, except those that use the RBBS_FIXEDSIZE style. As you reposition or resize a rebar control band, the rebar control manages the size and position of the child window assigned to that band. To resize or change the order of bands within the control, click and drag a band's gripper bar.

The following illustration shows a rebar control that has three bands:

  • Band 0 contains a flat, transparent toolbar control.

  • Band 1 contains both transparent standard and transparent dropdown buttons.

  • Band 2 contains a combo box and four standard buttons.

Rebar control

Rebar controls support:

  • Image lists.

  • Message-handling.

  • Custom draw functionality.

  • A variety of control styles in addition to standard window styles. For a list of these styles, see Rebar Control Styles in the Platform SDK.

For more information, see Using CReBarCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>


CReBarCtrl Class Members

Constructors

CReBarCtrl Constructs a CReBarCtrl object.

Initialization

Create Creates the rebar control and attaches it to the CReBarCtrl object.

Attributes

GetBandCount | Retrieves the count of bands currently in the rebar control.
GetBandInfo | Retrieves information about a specified band in a rebar control.
GetBarHeight | Retrieves the height of the rebar control.
GetBarInfo | Retrieves information about the rebar control and the image list it uses.
GetBkColor | Retrieves a rebar control's default background color.
GetDropTarget | Retrieves a rebar control's IDropTarget interface pointer.
GetRect | Retrieves the bounding rectangle for a given band in a rebar control.
GetRowCount | Retrieves the number of band rows in a rebar control.
GetRowHeight | Retrieves the height of a specified row in a rebar control.
GetTextColor | Retrieves a rebar control's default text color.
GetToolTips | Retrieves the handle to any tool tip control associated with the rebar control.
IDToIndex | Converts a band identifier (ID) to a band index in a rebar control.
SetBandInfo | Sets characteristics of an existing band in a rebar control.
SetBarInfo | Sets the characteristics of a rebar control.
SetBkColor | Sets a rebar control's default background color.
SetOwner | Sets a rebar control's owner window.
SetTextColor | Sets a rebar control's default text color.
SetToolTips | Associates a tool tip control with the rebar control.
GetImageList | Retrieves the image list associated with a rebar control.
SetImageList | Sets a rebar control's image list.
GetBandBorders | Retrieves the borders of a band.
GetPalette | Retrieves the rebar control's current palette.
SetPalette | Sets the rebar control's current palette.

Operations

BeginDrag | Places the rebar control into drag-and-drop mode.
DeleteBand | Deletes a band from a rebar control.
DragMove | Updates the drag position in the rebar control after a call to BeginDrag.
EndDrag | Terminates the rebar control's drag-and-drop operation.
HitTest | Determines which portion of a rebar band is at a given point on the screen, if a rebar band exists at that point.
InsertBand | Inserts a new band in a rebar control.
MaximizeBand | Resizes a band in a rebar control to its ideal or largest size.
MinimizeBand | Resizes a band in a rebar control to its smallest size.
ShowBand | Shows or hides a given band in a rebar control.
SizeToRect | Fits a rebar control to a specified rectangle.
MoveBand | Moves a band from one index to another.


CReBarCtrl::BeginDrag

void BeginDrag( UINT uBand, DWORD dwPos = (DWORD)-1 );

Parameters

uBand

Zero-based index of the band which the drag-and-drop operation will affect.

dwPos

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

Remarks

This member function implements the behavior of the Win32 message RB_BEGINDRAG, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also ::GetMessage, ::PeekMessage


CReBarCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if the object was created successfully; otherwise 0.

Parameters

dwStyle

Specifies the combination of rebar control styles applied to the control. See Rebar Control Styles in the Platform SDK for a list of supported styles.

rect

A reference to a CRect object or RECT structure, which is the position and size of the rebar control.

pParentWnd

A pointer to a CWnd object that is the parent window of the rebar control. It must not be NULL.

nID

Specifies the rebar control's control ID.

Remarks

Create a rebar control in two steps:

  1. Call CReBarCtrl to construct a CReBarCtrl object.

  2. Call this member function, which creates the Windows rebar control and attaches it to the CReBarCtrl object.

When you call Create, the common controls are initialized.


CReBarCtrl::CReBarCtrl

CReBarCtrl( );

Remarks

Call this member function to create a CReBarCtrl object.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::Create


CReBarCtrl::DeleteBand

BOOL DeleteBand( UINT uBand );

Return Value

Nonzero if the band deleted successfully; otherwise zero.

Parameters

uBand

Zero-based index of the band to be deleted.

Remarks

This member function implements the behavior of the Win32 message RB_DELETEBAND, as described in the Platform SDK.


CReBarCtrl::DragMove

void DragMove( DWORD dwPos = (DWORD)-1 );

Parameters

dwPos

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

Remarks

This member function implements the behavior of the Win32 message RB_DRAGMOVE, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::BeginDrag, CReBarCtrl::EndDrag, :: GetMessage, :: PeekMessage


CReBarCtrl::EndDrag

void EndDrag( );

Remarks

This member function implements the behavior of the Win32 message RB_ENDDRAG, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::BeginDrag, CReBarCtrl::DragMove


CReBarCtrl::GetBandBorders

void GetBandBorders( UINT uBand, LPRECT prc ) const;

Parameters

uBand

Zero-based index of the band for which the borders will be retrieved.

prc

A pointer to 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. For a description of rebar control styles, see Rebar Control Styles in the Platform SDK.

Remarks

This member function implements the behavior of the Win32 message RB_GETBANDBORDERS, as described in the Platform SDK.


CReBarCtrl::GetBandCount

UINT GetBandCount( ) const;

Return Value

The number of bands assigned to the control.

Remarks

This member function implements the behavior of the Win32 message RB_GETBANDCOUNT, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetBandInfo, CReBarCtrl::SetBandInfo, CReBarCtrl::DeleteBand, CReBarCtrl::InsertBand, CReBarCtrl::ShowBand


CReBarCtrl::GetBandInfo

BOOL GetBandInfo( UINT uBand, REBARBANDINFO* prbbi ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

uBand

Zero-based index of the band for which the information will be retrieved.

prbbi

A pointer to a REBARBANDINFO structure to receive the band information. You must set the cbSize member of this structure to sizeof(REBARBANDINFO) and set the fMask member to the items you want to retrieve before sending this message.

Remarks

This member function implements the behavior of the Win32 message RB_GETBANDINFO as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::SetBandInfo, CReBarCtrl::GetBandCount, CReBarCtrl::DeleteBand, CReBarCtrl::InsertBand, CReBarCtrl::ShowBand


CReBarCtrl::GetBarHeight

UINT GetBarHeight( ) const;

Return Value

Value that represents the height, in pixels, of the control.

Remarks

Call this member function to retrieve the height of the rebar bar.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetBarInfo, CReBarCtrl::SetBarInfo


CReBarCtrl::GetBarInfo

BOOL GetBarInfo( REBARINFO* prbi ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

prbi

A pointer to 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.

Remarks

This member function implements the behavior of the Win32 message RB_GETBARINFO, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CRebarCtrl::SetBarInfo


CReBarCtrl::GetBkColor

COLORREF GetBkColor( ) const;

Return Value

A COLORREF value that represent the current default background color.

Remarks

This member function implements the behavior of the Win32 message RB_GETBKCOLOR, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::SetBkColor


CReBarCtrl::GetDropTarget

IDropTarget* GetDropTarget( ) const;

Return Value

A pointer to an IDropTarget interface.

Remarks

This member function implements the behavior of the Win32 message RB_GETDROPTARGET, as described in the Platform SDK.


CReBarCtrl::GetImageList

CImageList* GetImageList( );

Return Value

A pointer to a CImageList object. Returns NULL if no image list is set for the control.

Remarks

Call this member function to get the CImageList object associated with a rebar control. This member function uses size and mask information stored in the REBARINFO structure, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::SetImageList


CReBarCtrl::GetPalette

CPalette* GetPalette( ) const;

Return Value

A pointer to a CPalette object specifying the rebar control's current palette.

Remarks

Call this member function to retrieve the rebar control's current palette.

Note that this member function uses a CPalette object as its return value, rather than an HPALETTE.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::SetPalette


CReBarCtrl::GetRect

BOOL GetRect(UINT uBand, LPRECT prc) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

uBand

Zero-based index of a band in the rebar control.

prc

A pointer to a RECT structure that will receive the bounds of the rebar band.

Remarks

This member function implements the behavior of the Win32 message RB_GETRECT, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::SizeToRect


CReBarCtrl::GetRowCount

UINT GetRowCount( ) const;

Return Value

A UINT value that represents the number of band rows in the control.

Remarks

This member function implements the behavior of the Win32 message RB_GETROWCOUNT, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetRowHeight


CReBarCtrl::GetRowHeight

UINT GetRowHeight( UINT uRow ) const;

Return Value

A UINT value that represents the row height, in pixels.

Parameters

uRow

Zero-based index of the band that will have its height retrieved.

Remarks

This member function implements the behavior of the Win32 message RB_GETROWHEIGHT, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetRowCount


CReBarCtrl::GetTextColor

COLORREF GetTextColor( ) const;

Return Value

A COLORREF value that represent the current default text color.

Remarks

This member function implements the behavior of the Win32 message RB_GETTEXTCOLOR, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::SetTextColor, CReBarCtrl::GetBkColor, CReBarCtrl::SetBkColor


CReBarCtrl::GetToolTips

CToolTipCtrl* GetToolTips( ) const;

Return Value

A pointer to a CToolTipCtrl object.

Remarks

This member function implements the behavior of the Win32 message RB_GETTOOLTIPS, as described in the Platform SDK.

Note that the MFC implementation of GetToolTips returns a pointer to a CToolTipCtrl, rather than an HWND.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::SetToolTips


CReBarCtrl::HitTest

int HitTest( RBHITTESTINFO* prbht );

Return Value

The zero-based index of the band at the given point, or -1 if no rebar band was at the point.

Parameters

prbht

A pointer to a RBHITTESTINFO structure. Before sending the message, the pt member of this structure must be initialized to the point that will be tested, in client coordinates.

Remarks

This member function implements the behavior of the Win32 message RB_HITTEST, as described in the Platform SDK.


CReBarCtrl::IDToIndex

int IDToIndex( UINT uBandID ) const;

Return Value

The zero-based band index if successful, or -1 otherwise. If duplicate band indices exist, the first one is returned.

Parameters

uBandID

The application-defined identifier of the specified band, passed in the wID member of the REBARBANDINFO structure when the band is inserted.

Remarks

This member function implements the behavior of the Win32 message RB_IDTOINDEX, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::InsertBand


CReBarCtrl::InsertBand

BOOL InsertBand( UINT uIndex, REBARBANDINFO* prbbi );

Return Value

Nonzero if successful; otherwise zero.

Parameters

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.

prbbi

A pointer to a REBARBANDINFO structure that defines the band to be inserted. You must set the cbSize member of this structure to sizeof(REBARBANDINFO) before calling this function.

Remarks

This member function implements the behavior of the Win32 message RB_INSERTBAND, as described in the Platform SDK.


CReBarCtrl::MaximizeBand

void MaximizeBand( UINT uBand );

Parameters

uBand

Zero-based index of the band to be maximized.

Remarks

This member function implements the behavior of the Win32 message RB_MAXIMIZEBAND, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::MinimizeBand


CReBarCtrl::MinimizeBand

void MinimizeBand( UINT uBand );

Parameters

uBand

Zero-based index of the band to be minimized.

Remarks

This member function implements the behavior of the Win32 message RB_MINIMIZEBAND, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::MaximizeBand


CReBarCtrl::MoveBand

BOOL MoveBand( UINT uFrom, UINT uTo );

Return Value

Nonzero if successful; otherwise zero.

Parameters

uFrom

Zero-based index of the band to be moved.

uTo

Zero-based index of the new band position. This parameter value must never be greater than the number of bands minus one. To obtain the number of bands, call GetBandCount.

Remarks

This member function implements the behavior of the Win32 message RB_MOVEBAND, as described in the Platform SDK.


CReBarCtrl::SetBandInfo

BOOL SetBandInfo( UINT uBand, REBARBANDINFO* prbbi );

Return Value

Nonzero if successful; otherwise zero.

Parameters

uBand

Zero-based index of the band to receive the new settings.

prbbi

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

Remarks

This member function implements the behavior of the Win32 message RB_SETBANDINFO, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetBandInfo


CReBarCtrl::SetBarInfo

BOOL SetBarInfo( REBARINFO* prbi );

Return Value

Nonzero if successful; otherwise zero.

Parameters

prbi

A pointer to 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

Remarks

This member function implements the behavior of the Win32 message RB_SETBARINFO, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetBarInfo


CReBarCtrl::SetBkColor

COLORREF SetBkColor( COLORREF clr );

Return Value

A COLORREF value that represents the previous default background color.

Parameters

clr

The COLORREF value that represents the new default background color.

Remarks

This member function implements the behavior of the Win32 message RB_SETBKCOLOR, as described in the Platform SDK. See this topic for more information about when to set the background color, and how to set the default.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetBkColor


CReBarCtrl::SetImageList

BOOL SetImageList( CImageList* pImageList );

Return Value

Nonzero if successful; otherwise zero.

Parameters

pImageList

A pointer to a CImageList object containing the image list to be assigned to the rebar control.

Remarks

Call this member function to assign an image list to a rebar control.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetImageList


CReBarCtrl::SetOwner

CWnd* SetOwner( CWnd* pWnd );

Return Value

A pointer to a CWnd object that is the current owner of the rebar control.

Parameters

pWnd

A pointer to a CWnd object to set as the owner of the rebar control.

Remarks

This member function implements the behavior of the Win32 message RB_SETPARENT, as described in the Platform SDK.

Note that this member function uses pointers to CWnd objects for both the current and selected owner of the rebar control, rather than handles to windows.

Note This member function does not change the actual parent that was set when the control was created; rather it sends notification messages to the window you specify.


CReBarCtrl::SetPalette

CPalette* SetPalette( HPALETTE hPal );

Return Value

A pointer to a CPalette object specifying the rebar control's previous palette.

Parameters

hPal

An HPALETTE that specifies the new palette that the rebar control will use.

Remarks

This member function implements the behavior of the Win32 message RB_SETPALETTE, as described in the Platform SDK.

Note that this member function uses a CPalette object as its return value, rather than an HPALETTE.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetPalette


CReBarCtrl::SetTextColor

COLORREF SetTextColor( COLORREF clr );

Return Value

The COLORREF value representing the previous text color associated with the CReBarCtrl object.

Parameters

clr

A COLORREF value that represents the new text color in the CReBarCtrl object.

Remarks

This member function implements the behavior of the Win32 message RB_SETTEXTCOLOR, as described in the Platform SDK. It is provided to support text color flexibility in a rebar control.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetTextColor


CReBarCtrl::SetToolTips

void SetToolTips( CToolTipCtrl* pToolTip );

Parameters

pToolTip

A pointer to a CToolTipCtrl object

Remarks

Call this member function to associate a tool tip control with a rebar control.

You must destroy the CToolTipCtrl object when you are done with it.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetToolTips


CReBarCtrl::ShowBand

BOOL ShowBand( UINT uBand, BOOL fShow = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

uBand

Zero-based index of a band in the rebar control.

fShow

Indicates if the band should be shown or hidden. If this value is TRUE, the band will be shown. Otherwise, the band will be hidden.

Remarks

This member function implements the behavior of the Win32 message RB_SHOWBAND, as described in the Platform SDK.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::SetBandInfo, CReBarCtrl::GetBandCount, CReBarCtrl::DeleteBand, CReBarCtrl::InsertBand, CReBarCtrl::GetBandInfo


CReBarCtrl::SizeToRect

BOOL SizeToRect( CRect& rect );

Return Value

Nonzero if successful; otherwise zero.

Parameters

rect

A reference to a CRect object that specifies the rectangle that the rebar control should be sized to.

Remarks

This member function implements the behavior of the Win32 message RB_SIZETORECT, as described in the Platform SDK.

Note that this member function uses a CRect object as a parameter, rather than a RECT structure.

CReBarCtrl Overview | Class Members | Hierarchy Chart

See Also CReBarCtrl::GetRect


CRecentFileList

CRecentFileList is a CObject class that supports control of the most recently used (MRU) file list. Files can be added to or deleted from the MRU file list, the file list can be read from or written to the registry or an .INI file, and the menu displaying the MRU file list can be updated.

#include <afxadv.h>


CRecentFileList Class Members

Construction

CRecentFileList Constructs a CRecentFileList object.

Attributes

GetSize Retrieves the number of files in the MRU file list.

Operations

Remove | Removes a file from the MRU file list.
Add | Adds a file to the MRU file list.
GetDisplayName | Provides a display name for menu display of an MRU filename.
UpdateMenu | Updates the menu display of the MRU file list.
ReadList | Reads the MRU file list from the registry or .INI file.
WriteList | Writes the MRU file list from the registry or .INI file.

Operators

operator[] Returns a CString object at a given position.


CRecentFileList::Add

virtual void Add( LPCTSTR lpszPathName );

Parameters

lpszPathName

Pathname to be added to the list.

Remarks

Call this function to add the file whose path is given in lpszPathName to the most recently used (MRU) file list. The file name will be added to the top of the MRU list. If the file name already exists in the MRU list, it will be moved to the top.

CRecentFileList Overview | Class Members | Hierarchy Chart

See Also CRecentFileList::Remove CRecentFileList::UpdateMenu


CRecentFileList::CRecentFileList

CRecentFileList( UINT nStart, LPCTSTR lpszSection, LPCTSTR lpszEntryFormat, int nSize, int nMaxDispLen = AFX_ABBREV_FILENAME_LEN );

Parameters

nStart

Offset for the numbering in the menu display of the MRU (most recently used) file list.

lpszSection

Points to the name of the section of the registry or the application's .INI file where the MRU file list is read and/or written.

lpszEntryFormat

Points to a format string to be used for the names of the entries stored in the registry or the application's .INI file.

nSize

Maximum number of files in the MRU file list.

nMaxDispLen

Maximum length, in characters, available for the menu display of a filename in the MRU file list.

Remarks

Constructs a CRecentFileList object.

The format string pointed to by lpszEntryFormat should contain "%d", which will be used for substituting the index of each MRU item. For example, if the format string is "file%d" then the entries will be named file0, file1, and so on.


CRecentFileList::GetDisplayName

BOOL GetDisplayName( CString& strName, int nIndex, LPCTSTR lpszCurDir, int nCurDir, BOOL bAtLeastName = TRUE) const;

Return Value

FALSE if there is no filename at the specified index in the MRU (most recently used) file list.

Parameters

strName

Full path of the file whose name is to be displayed in the menu list of MRU files.

nIndex

Zero-based index of the file in the MRU file list.

lpszCurDir

String holding the current directory.

nCurDir

Length of the current directory string.

bAtLeastName

If nonzero, indicates that the base name of the file should be returned, even if it exceeds the maximum display length (passed as the nMaxDispLen parameter to the CRecentFileList constructor).

Remarks

Call this function to obtain a display name for a file in the MRU file list, for use in the menu display of the MRU list. If the file is in the current directory, the function leaves the directory off the display. If the filename is too long, the directory and extension are stripped. If the filename is still too long, the display name is set to an empty string unless bAtLeastName is nonzero.

CRecentFileList Overview | Class Members | Hierarchy Chart

See Also CRecentFileList::ReadList CRecentFileList::WriteList


CRecentFileList::GetSize

int GetSize( ) const;

Return Value

The number of files in the current MRU (most recently used) file list.

CRecentFileList Overview | Class Members | Hierarchy Chart

See Also CRecentFileList::Add, CRecentFileList::Remove


CRecentFileList::ReadList

virtual void ReadList( );

Remarks

Call this function to read the most recently used (MRU) file list from the registry or the application's .INI file.

CRecentFileList Overview | Class Members | Hierarchy Chart

See Also CRecentFileList::WriteList


CRecentFileList::Remove

virtual void Remove( int nIndex );

Parameters

nIndex

Zero-based index of the file to be removed from the MRU (most recently used) file list.

Remarks

Call this function to remove a file from the MRU file list.

CRecentFileList Overview | Class Members | Hierarchy Chart

See Also CRecentFileList::Add, CRecentFileList::UpdateMenu


CRecentFileList::UpdateMenu

virtual void UpdateMenu( CCmdUI* pCmdUI );

Parameters

pCmdUI

A pointer to the MRU (most recently used) file list menu, which is a CCmdUI object.

Remarks

Updates the menu display of the MRU file list.

CRecentFileList Overview | Class Members | Hierarchy Chart

See Also CRecentFileList::Add, CRecentFileList::Remove


CRecentFileList::WriteList

virtual void WriteList( );

Remarks

Call this function to write the most recently used (MRU) file list into the registry or the application's .INI file.

CRecentFileList Overview | Class Members | Hierarchy Chart

See Also CRecentFileList::ReadList


CRecentFileList::operator [ ]

CString& operator[ ]( int nIndex );

Parameters

nIndex

Zero-based index of a CString in a set of CStrings.

Remarks

The overloaded subscript ([]) operator returns a single CString specified by the zero-based index in nIndex.


CRecordset

A CRecordset object represents a set of records selected from a data source. Known as “recordsets,” CRecordset objects are typically used in two forms: dynasets and snapshots. A dynaset stays synchronized with data updates made by other users. A snapshot is a static view of the data. Each form represents a set of records fixed at the time the recordset is opened, but when you scroll to a record in a dynaset, it reflects changes subsequently made to the record, either by other users or by other recordsets in your application.

Note If you are working with the Data Access Objects (DAO) classes rather than the Open Database Connectivity (ODBC) classes, use class CDaoRecordset instead. For more information, see the article Database Topics (General) and the article DAO and MFC. Both articles are in Visual C++ Programmer’s Guide.

To work with either kind of recordset, you typically derive an application-specific recordset class from CRecordset. Recordsets select records from a data source, and you can then:

  • Scroll through the records.

  • Update the records and specify a locking mode.

  • Filter the recordset to constrain which records it selects from those available on the data source.

  • Sort the recordset.

  • Parameterize the recordset to customize its selection with information not known until run time.

To use your class, open a database and construct a recordset object, passing the constructor a pointer to your CDatabase object. Then call the recordset’s Open member function, where you can specify whether the object is a dynaset or a snapshot. Calling Open selects data from the data source. After the recordset object is opened, use its member functions and data members to scroll through the records and operate on them. The operations available depend on whether the object is a dynaset or a snapshot, whether it is updatable or read-only (this depends on the capability of the Open Database Connectivity (ODBC) data source), and whether you have implemented bulk row fetching. To refresh records that may have been changed or added since the Open call, call the object’s Requery member function. Call the object’s Close member function and destroy the object when you finish with it.

In a derived CRecordset class, record field exchange (RFX) or bulk record field exchange (Bulk RFX) is used to support reading and updating of record fields.

For more information about recordsets and record field exchange, see the articles Database Topics (General), Recordset (ODBC), Recordset: Fetching Records in Bulk (ODBC), and Record Field Exchange. For a focus on dynasets and snapshots, see the articles Dynaset and Snapshot. All articles are in Visual C++ Programmer’s Guide.

#include <afxdb.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CATALOG | MFC Sample DBFETCH | MFC Sample ODBCINFO | MFC Sample WWWQUOTE

See Also CDatabase, CRecordView


CRecordset Class Members

Data Members
Construction
Recordset Attributes
Recordset Update Operations
Recordset Navigation Operations
Other Recordset Operations
Recordset Overridables

Data Members

m_hstmt | Contains the ODBC statement handle for the recordset. Type HSTMT.
m_nFields | Contains the number of field data members in the recordset. Type UINT.
m_nParams | Contains the number of parameter data members in the recordset. Type UINT.
m_pDatabase | Contains a pointer to the CDatabase object through which the recordset is connected to a data source.
m_strFilter | Contains a CString that specifies a Structured Query Language (SQL) WHERE clause. Used as a filter to select only those records that meet certain criteria.
m_strSort | Contains a CString that specifies an SQL ORDER BY clause. Used to control how the records are sorted.

Construction

CRecordset | Constructs a CRecordset object. Your derived class must provide a constructor that calls this one.
Open | Opens the recordset by retrieving the table or performing the query that the recordset represents.
Close | Closes the recordset and the ODBC HSTMT associated with it.

Recordset Attributes

CanAppend | Returns nonzero if new records can be added to the recordset via the AddNew member function.
CanBookmark | Returns nonzero if the recordset supports bookmarks.
CanRestart | Returns nonzero if Requery can be called to run the recordset’s query again.
CanScroll | Returns nonzero if you can scroll through the records.
CanTransact | Returns nonzero if the data source supports transactions.
CanUpdate | Returns nonzero if the recordset can be updated (you can add, update, or delete records).
GetODBCFieldCount | Returns the number of fields in the recordset.
GetRecordCount | Returns the number of records in the recordset.
GetStatus | Gets the status of the recordset: the index of the current record and whether a final count of the records has been obtained.
GetTableName | Gets the name of the table on which the recordset is based.
GetSQL | Gets the SQL string used to select records for the recordset.
IsOpen | Returns nonzero if Open has been called previously.
IsBOF | Returns nonzero if the recordset has been positioned before the first record. There is no current record.
IsEOF | Returns nonzero if the recordset has been positioned after the last record. There is no current record.
IsDeleted | Returns nonzero if the recordset is positioned on a deleted record.

Recordset Update Operations

AddNew | Prepares for adding a new record. Call Update to complete the addition.
CancelUpdate | Cancels any pending updates due to an AddNew or Edit operation.
Delete | Deletes the current record from the recordset. You must explicitly scroll to another record after the deletion.
Edit | Prepares for changes to the current record. Call Update to complete the edit.
Update | Completes an AddNew or Edit operation by saving the new or edited data on the data source.

Recordset Navigation Operations

GetBookmark | Assigns the bookmark value of a record to the parameter object.
Move | Positions the recordset to a specified number of records from the current record in either direction.
MoveFirst | Positions the current record on the first record in the recordset. Test for IsBOF first.
MoveLast | Positions the current record on the last record or on the last rowset. Test for IsEOF first.
MoveNext | Positions the current record on the next record or on the next rowset. Test for IsEOF first.
MovePrev | Positions the current record on the previous record or on the previous rowset. Test for IsBOF first.
SetAbsolutePosition | Positions the recordset on the record corresponding to the specified record number.
SetBookmark | Positions the recordset on the record specified by the bookmark.

Other Recordset Operations

Cancel | Cancels an asynchronous operation or a process from a second thread.
FlushResultSet | Returns nonzero if there is another result set to be retrieved, when using a predefined query.
GetFieldValue | Returns the value of a field in a recordset.
GetODBCFieldInfo | Returns specific kinds of information about the fields in a recordset.
GetRowsetSize | Returns the number of records you wish to retrieve during a single fetch.
GetRowsFetched | Returns the actual number of rows retrieved during a fetch.
GetRowStatus | Returns the status of the row after a fetch.
IsFieldDirty | Returns nonzero if the specified field in the current record has been changed.
IsFieldNull | Returns nonzero if the specified field in the current record is Null (has no value).
IsFieldNullable | Returns nonzero if the specified field in the current record can be set to Null (having no value).
RefreshRowset | Refreshes the data and status of the specified row(s).
Requery | Runs the recordset’s query again to refresh the selected records.
SetFieldDirty | Marks the specified field in the current record as changed.
SetFieldNull | Sets the value of the specified field in the current record to Null (having no value).
SetLockingMode | Sets the locking mode to “optimistic” locking (the default) or “pessimistic” locking. Determines how records are locked for updates.
SetParamNull | Sets the specified parameter to Null (having no value).
SetRowsetCursorPosition | Positions the cursor on the specified row within the rowset.

Recordset Overridables

Check | Called to examine the return code from an ODBC API function.
CheckRowsetError | Called to handle errors generated during record fetching.
DoBulkFieldExchange | Called to exchange bulk rows of data from the data source to the recordset. Implements bulk record field exchange (Bulk RFX).
DoFieldExchange | Called to exchange data (in both directions) between the field data members of the recordset and the corresponding record on the data source. Implements record field exchange (RFX).
GetDefaultConnect | Called to get the default connect string.
GetDefaultSQL | Called to get the default SQL string to execute.
OnSetOptions | Called to set options for the specified ODBC statement.
SetRowsetSize | Specifies the number of records you wish to retrieve during a fetch.


CRecordset::AddNew

virtual void AddNew( );
throw( CDBException );

Remarks

Call this member function to prepare for adding a new record to the table. You must call the Requery member function to see the newly added record. The record’s fields are initially Null. (In database terminology, Null means “having no value” and is not the same as NULL in C++.) To complete the operation, you must call the Update member function. Update saves your changes to the data source.

Note If you have implemented bulk row fetching, you cannot call AddNew. This will result in a failed assertion. Although class CRecordset does not provide a mechanism for updating bulk rows of data, you can write your own functions by using the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

AddNew prepares a new, empty record using the recordset’s field data members. After you call AddNew, set the values you want in the recordset’s field data members. (You do not have to call the Edit member function for this purpose; use Edit only for existing records.) When you subsequently call Update, changed values in the field data members are saved on the data source.

Caution If you scroll to a new record before you call Update, the new record is lost, and no warning is given.

If the data source supports transactions, you can make your AddNew call part of a transaction. For more information about transactions, see class CDatabase. Note that you should call CDatabase::BeginTrans before calling AddNew.

Important For dynasets, new records are added to the recordset as the last record. Added records are not added to snapshots — you must call Requery to refresh the recordset.

It is illegal to call AddNew for a recordset whose Open member function has not been called. A CDBException is thrown if you call AddNew for a recordset that cannot be appended to. You can determine whether the recordset is updatable by calling CanAppend.

For more information, see the following articles in Visual C++ Programmer’s Guide: Recordset: How Recordsets Update Records (ODBC), Recordset: Adding, Updating, and Deleting Records (ODBC), and Transaction (ODBC).

Example

See the article Transaction: Performing a Transaction in a Recordset (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Edit, CRecordset::Delete, CRecordset::Update, CRecordset::Requery, CDatabase::BeginTrans, CDBException


CRecordset::CanAppend

BOOL CanAppend( ) const;

Return Value

Nonzero if the recordset allows adding new records; otherwise 0. CanAppend will return 0 if you opened the recordset as read-only.

Remarks

Call this member function to determine whether the previously opened recordset allows you to add new records.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::AddNew, CRecordset::Requery


CRecordset::CanBookmark

BOOL CanBookmark( ) const;

Return Value

Nonzero if the recordset supports bookmarks; otherwise 0.

Remarks

Call this member function to determine whether the recordset allows you to mark records using bookmarks. This function is independent of the CRecordset::useBookmarks option in the dwOptions parameter of the Open member function. CanBookmark indicates whether the given ODBC driver and cursor type support bookmarks. CRecordset::useBookmarks indicates whether bookmarks will be available, provided they are supported.

Note Bookmarks are not supported on forward-only recordsets.

For more information about bookmarks and recordset navigation, see the articles Recordset: Bookmarks and Absolute Positions (ODBC) and Recordset: Scrolling (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::GetBookmark, CRecordset::SetBookmark


CRecordset::Cancel

void Cancel( );

Remarks

Call this member function to request that the data source cancel either an asynchronous operation in progress or a process from a second thread. Note that the MFC ODBC classes no longer use asynchronous processing; to perform an asychronous operation, you must directly call the ODBC API function SQLSetConnectOption. For more information, see the topic "Executing Functions Asynchronously" in the ODBC SDK Programmer's Guide.


CRecordset::CancelUpdate

void CancelUpdate( );

Remarks

Call this member function to cancel any pending updates, due to an Edit or AddNew operation, before Update is called.

Note This member function is not applicable on recordsets that are using bulk row fetching, since such recordsets cannot call Edit, AddNew, or Update. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

If automatic dirty field checking is enabled, CancelUpdate will restore the member variables to the values they had before Edit or AddNew was called; otherwise, any value changes will remain. By default, automatic field checking is enabled when the recordset is opened. To disable it, you must specify the CRecordset::noDirtyFieldCheck in the dwOptions parameter of the Open member function.

For more information about updating data, see the article Recordset: Adding, Updating, and Deleting Records (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::AddNew, CRecordset::Edit, CRecordset::Update


CRecordset::CanRestart

BOOL CanRestart( ) const;

Return Value

Nonzero if requery is allowed; otherwise 0.

Remarks

Call this member function to determine whether the recordset allows restarting its query (to refresh its records) by calling the Requery member function.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Requery


CRecordset::CanScroll

BOOL CanScroll( ) const;

Return Value

Nonzero if the recordset allows scrolling; otherwise 0.

Remarks

Call this member function to determine whether the recordset allows scrolling.

For more information about scrolling, see the article Recordset: Scrolling (ODBC) in Visual C++ Programmer’s Guide.


CRecordset::CanTransact

BOOL CanTransact( ) const;

Return Value

Nonzero if the recordset allows transactions; otherwise 0.

Remarks

Call this member function to determine whether the recordset allows transactions. For more information, see the article Transaction (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CDatabase::BeginTrans, CDatabase::CommitTrans, CDatabase::Rollback


CRecordset::CanUpdate

BOOL CanUpdate( ) const;

Return Value

Nonzero if the recordset can be updated; otherwise 0.

Remarks

Call this member function to determine whether the recordset can be updated. A recordset might be read-only if the underlying data source is read-only or if you specified CRecordset::readOnly in the dwOptions parameter when you opened the recordset.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Open, CRecordset::AddNew, CRecordset::Edit, CRecordset::Delete, CRecordset::Update


CRecordset::Check

virtual BOOL Check( RETCODE nRetCode ) const;

Return Value

Nonzero if the value of nRetCode is SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_NO_DATA_FOUND or SQL_NEED_DATA; otherwise 0.

Parameters

nRetCode

An ODBC API function return code. For details, see Remarks.

Remarks

Call this member function to examine the return code from an ODBC API function. The following table lists the possible values for nRetCode.

nRetCode | Description
SQL_SUCCESS | Function completed successfully; no additional information is available.
SQL_SUCCESS_WITH_INFO | Function completed successfully, possibly with a nonfatal error. Additional information can be obtained by calling SQLError.
SQL_NO_DATA_FOUND | All rows from the result set have been fetched.
SQL_ERROR | Function failed. Additional information can be obtained by calling SQLError.
SQL_INVALID_HANDLE | Function failed due to an invalid environment handle, connection handle, or statement handle. This indicates a programming error. No additional information is available from SQLError.
SQL_STILL_EXECUTING | A function that was started asynchronously is still executing. Note that by default, MFC will never pass this value to Check because MFC uses only synchronous processing.
SQL_NEED_DATA | While processing a statement, the driver determined that the application needs to send parameter data values.

For more information about SQLError, see the ODBC SDK Programmer's Reference.

Example

See the macro AFX_ODBC_CALL.

CRecordset Overview | Class Members | Hierarchy Chart

See Also AFX_ODBC_CALL


CRecordset::CheckRowsetError

virtual void CheckRowsetError( RETCODE nRetCode );
throw( CDBException );

Parameters

nRetCode

An ODBC API function return code. For details, see Remarks.

Remarks

This virtual member function handles errors that occur when records are fetched, and is useful during bulk row fetching. You may want to consider overriding CheckRowsetError in order to implement your own error handling.

CheckRowsetError is called automatically in a cursor navigation operation, such as Open, Requery, or any Move operation. It is passed the return value of the ODBC API function SQLExtendedFetch. The following table lists the possible values for the nRetCode parameter.

nRetCode | Description
SQL_SUCCESS | Function completed successfully; no additional information is available.
SQL_SUCCESS_WITH_INFO | Function completed successfully, possibly with a nonfatal error. Additional information can be obtained by calling SQLError.
SQL_NO_DATA_FOUND | All rows from the result set have been fetched.
SQL_ERROR | Function failed. Additional information can be obtained by calling SQLError.
SQL_INVALID_HANDLE | Function failed due to an invalid environment handle, connection handle, or statement handle. This indicates a programming error. No additional information is available from SQLError.
SQL_STILL_EXECUTING | A function that was started asynchronously is still executing. Note that by default, MFC will never pass this value to CheckRowsetError; MFC will continue calling SQLExtendedFetch until it no longer returns SQL_STILL_EXECUTING.

For more information about SQLError, see the ODBC SDK Programmer's Reference. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::DoBulkFieldExchange, CRecordset::GetRowsetSize, CRecordset::SetRowsetSize, CRecordset::Move


CRecordset::Close

virtual void Close( );

Remarks

Call this member function to close the recordset. The ODBC HSTMT and all memory the framework allocated for the recordset are deallocated. Usually after calling Close, you delete the C++ recordset object if it was allocated with new.

You can call Open again after calling Close. This lets you reuse the recordset object. The alternative is to call Requery.

Example

// Example for CRecordset::Close

// Construct a snapshot object
CCustSet rsCustSet( NULL );

if( !rsCustSet.Open( ) )
   return FALSE;

// Use the snapshot ...

// Close the snapshot
rsCustSet.Close( );

// Destructor is called when the function exits

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::CRecordset, CRecordset::Open, CRecordset::Requery


CRecordset::CRecordset

CRecordset( CDatabase* pDatabase = NULL);

Parameters

pDatabase

Contains a pointer to a CDatabase object or the value NULL. If not NULL and the CDatabase object’s Open member function has not been called to connect it to the data source, the recordset attempts to open it for you during its own Open call. If you pass NULL, a CDatabase object is constructed and connected for you using the data source information you specified when you derived your recordset class with ClassWizard.

Remarks

Constructs a CRecordset object. You can either use CRecordset directly or derive an application-specific class from CRecordset. You can use ClassWizard to derive your recordset classes.

Note A derived class must supply its own constructor. In the constructor of your derived class, call the constructor CRecordset::CRecordset, passing the appropriate parameters along to it.

Pass NULL to your recordset constructor to have a CDatabase object constructed and connected for you automatically. This is a useful shorthand that does not require you to construct and connect a CDatabase object prior to constructing your recordset.

Example

For more information, see the article Recordset: Declaring a Class for a Table (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Open, CRecordset::Close


CRecordset::Delete

virtual void Delete( );
throw( CDBException );

Remarks

Call this member function to delete the current record. After a successful deletion, the recordset’s field data members are set to a Null value, and you must explicitly call one of the Move functions in order to move off the deleted record. Once you move off the deleted record, it is not possible to return to it. If the data source supports transactions, you can make the Delete call part of a transaction. For more information, see the article Transaction (ODBC) in Visual C++ Programmer’s Guide.

Note If you have implemented bulk row fetching, you cannot call Delete. This will result in a failed assertion. Although class CRecordset does not provide a mechanism for updating bulk rows of data, you can write your own functions by using the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Caution The recordset must be updatable and there must be a valid record current in the recordset when you call Delete; otherwise, an error occurs. For example, if you delete a record but do not scroll to a new record before you call Delete again, Delete throws a CDBException.

Unlike AddNew and Edit, a call to Delete is not followed by a call to Update. If a Delete call fails, the field data members are left unchanged.

Example

This example shows a recordset created on the frame of a function. The example assumes the existence of m_dbCust, a member variable of type CDatabase already connected to the data source.

// Create a derived CRecordset object
CCustSet rsCustSet( &m_dbCust );
rsCustSet.Open( );

if( rsCustSet.IsEOF( ) || !rsCustSet.CanUpdate( ) ||
    !rsCustSet.CanTransact( ) )
   return;

if( !m_dbCust.BeginTrans( ) )
{
   // Do something to handle a failure
}
else
{
   // Perhaps scroll to a new record...
   // Delete the current record
   rsCustSet.Delete( );
   // ...

   // Finished commands for this transaction
   if( <the user confirms the transaction> )
      m_dbCust.CommitTrans( );
   else // User changed mind
      m_dbCust.Rollback( );
}
// ...

CRecordset Overview | Class Members | Hierarchy Chart

See Also Database::BeginTrans, CDatabase::CommitTrans, CDatabase::Rollback, CDBException


CRecordset::DoBulkFieldExchange

virtual void DoBulkFieldExchange( CFieldExchange* pFX );
throw( CDBException );

Parameters

pFX

A pointer to a CFieldExchange object. The framework will already have set up this object to specify a context for the field exchange operation.

Remarks

When bulk row fetching is implemented, the framework calls this member function to automatically transfer data from the data source to your recordset object. DoBulkFieldExchange also binds your parameter data members, if any, to parameter placeholders in the SQL statement string for the recordset's selection.

If bulk row fetching is not implemented, the framework calls DoFieldExchange. To implement bulk row fetching, you must specify the CRecordset::useMultiRowFetch option of the dwOptions parameter in the Open member function.

Note DoBulkFieldExchange is available only if you are using a class derived from CRecordset. If you have created a recordset object directly from CRecordset, you must call the GetFieldValue member function to retrieve data.

Bulk record field exchange (Bulk RFX) is similar to record field exchange (RFX). Data is automatically transferred from the data source to the recordset object. However, you cannot call AddNew, Edit, Delete, or Update to transfer changes back to the data source. Class CRecordset currently does not provide a mechanism for updating bulk rows of data; however, you can write your own functions by using the ODBC API function SQLSetPos.

Note that ClassWizard does not support bulk record field exchange; therefore, you must override DoBulkFieldExchange manually by writing calls to the Bulk RFX functions. For more information about these functions, see the topic Record Field Exchange Functions.

For an example of how to implement bulk record field exchange, see the sample DBFETCH. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC). For related information, see the article Record Field Exchange (RFX). Both articles are in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::m_nFields, CRecordset::m_nParams, CRecordset::DoFieldExchange, CRecordset::GetFieldValue, CFieldExchange, Record Field Exchange Functions


CRecordset::DoFieldExchange

virtual void DoFieldExchange( CFieldExchange* pFX );
throw( CDBException );

Parameters

pFX

A pointer to a CFieldExchange object. The framework will already have set up this object to specify a context for the field exchange operation.

Remarks

When bulk row fetching is not implemented, the framework calls this member function to automatically exchange data between the field data members of your recordset object and the corresponding columns of the current record on the data source. DoFieldExchange also binds your parameter data members, if any, to parameter placeholders in the SQL statement string for the recordset’s selection.

If bulk row fetching is implemented, the framework calls DoBulkFieldExchange. To implement bulk row fetching, you must specify the CRecordset::useMultiRowFetch option of the dwOptions parameter in the Open member function.

Note DoFieldExchange is available only if you are using a class derived from CRecordset. If you have created a recordset object directly from CRecordset, you must call the GetFieldValue member function to retrieve data.

The exchange of field data, called record field exchange (RFX), works in both directions: from the recordset object’s field data members to the fields of the record on the data source, and from the record on the data source to the recordset object.

The only action you must normally take to implement DoFieldExchange for your derived recordset class is to create the class with ClassWizard and specify the names and data types of the field data members. You might also add code to what ClassWizard writes to specify parameter data members or to deal with any columns you bind dynamically. For more information, see the article Recordset: Dynamically Binding Data Columns (ODBC) in Visual C++ Programmer’s Guide.

When you declare your derived recordset class with ClassWizard, the wizard writes an override of DoFieldExchange for you, which resembles the following example:

void CCustSet::DoFieldExchange(CFieldExchange* pFX)
{
   //{{AFX_FIELD_MAP(CCustSet)
   pFX->SetFieldType(CFieldExchange::outputColumn);
   RFX_Text(pFX, "Name", m_strName);
   RFX_Int(pFX, "Age", m_wAge);
   //}}AFX_FIELD_MAP
}

For more information about the RFX functions, see the topic Record Field Exchange Functions.

For further examples and details about DoFieldExchange, see the article Record Field Exchange: How RFX Works. For general information about RFX, see the article Record Field Exchange. Both articles are in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::m_nFields, CRecordset::m_nParams, CRecordset::DoBulkFieldExchange, CRecordset::GetFieldValue, CFieldExchange, Record Field Exchange Functions


CRecordset::Edit

virtual void Edit( );
throw( CDBException, CMemoryException );

Remarks

Call this member function to allow changes to the current record. After you call Edit, you can change the field data members by directly resetting their values. The operation is completed when you subsequently call the Update member function to save your changes on the data source.

Note If you have implemented bulk row fetching, you cannot call Edit. This will result in a failed assertion. Although class CRecordset does not provide a mechanism for updating bulk rows of data, you can write your own functions by using the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Edit saves the values of the recordset’s data members. If you call Edit, make changes, then call Edit again, the record’s values are restored to what they were before the first Edit call.

In some cases, you may want to update a column by making it Null (containing no data). To do so, call SetFieldNull with a parameter of TRUE to mark the field Null; this also causes the column to be updated. If you want a field to be written to the data source even though its value has not changed, call SetFieldDirty with a parameter of TRUE. This works even if the field had the value Null.

If the data source supports transactions, you can make the Edit call part of a transaction. Note that you should call CDatabase::BeginTrans before calling Edit and after the recordset has been opened. Also note that calling CDatabase::CommitTrans is not a substitute for calling Update to complete the Edit operation. For more information about transactions, see class CDatabase.

Depending on the current locking mode, the record being updated may be locked by Edit until you call Update or scroll to another record, or it may be locked only during the Edit call. You can change the locking mode with SetLockingMode.

The previous value of the current record is restored if you scroll to a new record before calling Update. A CDBException is thrown if you call Edit for a recordset that cannot be updated or if there is no current record.

For more information, see the articles Transaction (ODBC) and Recordset: Locking Records (ODBC) in Visual C++ Programmer’s Guide.

Example

// Example for CRecordset::Edit
// To edit a record,
// First set up the edit buffer
rsCustSet.Edit( );

// Then edit field data members for the record
rsCustSet.m_dwCustID = 2795;
rsCustSet.m_strCustomer = "Jones Mfg";

// Finally, complete the operation
if( !rsCustSet.Update( ) )
    // Handle the failure to update

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Update, CRecordset::AddNew, CRecordset::Delete, CRecordset::SetFieldDirty, CRecordset::SetFieldNull, CRecordset::CanUpdate, CRecordset::CanTransact, CRecordset::SetLockingMode


CRecordset::FlushResultSet

BOOL FlushResultSet( ) const;
throw( CDBException );

Return Value

Nonzero if there are more result sets to be retrieved; otherwise 0.

Remarks

Call this member function to retrieve the next result set of a predefined query (stored procedure), if there are multiple result sets. You should call FlushResultSet only when you are completely finished with the cursor on the current result set. Note that when you retrieve the next result set by calling FlushResultSet, your cursor is not valid on that result set; you should call the MoveNext member function after calling FlushResultSet.

If a predefined query uses an output parameter or input/output parameters, you must call FlushResultSet until it returns FALSE (the value 0), in order to obtain these parameter values.

FlushResultSet calls the ODBC API function SQLMoreResults. If SQLMoreResults returns SQL_ERROR or SQL_INVALID_HANDLE, then FlushResultSet will throw an exception. For more information about SQLMoreResults, see the ODBC SDK Programmer's Reference.

Example

The following code assumes that COutParamRecordset is a CRecordset-derived object based on a predefined query with an input parameter and an output parameter, and having multiple result sets. Note the structure of the DoFieldExchange override.

// DoFieldExchange override
//
// Only necessary to handle parameter bindings.
// Don't use CRecordset-derived class with bound
// fields unless all result sets have same schema
// OR there is conditional binding code.

void COutParamRecordset::DoFieldExchange( CFieldExchange* pFX )
{
   pFX->SetFieldType( CFieldExchange::outputParam );
   RFX_Long( pFX, "Param1", m_nOutParamInstructorCount );
         // The "Param1" name here is a dummy name
         // that is never used

   pFX->SetFieldType( CFieldExchange::inputParam );
   RFX_Text( pFX, "Param2", m_strInParamName );
         // The "Param2" name here is a dummy name
         // that is never used

}

// Now implement COurParamRecordset.

// Assume db is an already open CDatabase object
COutParamRecordset rs( &db );
rs.m_strInParamName = _T("Some_Input_Param_Value");

// Get the first result set
// NOTE: SQL Server requires forwardOnly cursor
//       type for multiple rowset returning stored
//       procedures
rs.Open( CRecordset::forwardOnly,
         "{? = CALL GetCourses( ? )}",
         CRecordset::readOnly);

// Loop through all the data in the first result set
while ( !rs.IsEOF( ) )
{
   CString strFieldValue;
   for( int nIndex = 0;
        nIndex < rs.GetODBCFieldCount( );
        nIndex++ )
   {
      rs.GetFieldValue( nIndex, strFieldValue );

      // TO DO: Use field value string.
   }
   rs.MoveNext( );
}

// Retrieve other result sets...
while( rs.FlushResultSet( ) )
{
   // must call MoveNext because cursor is invalid
   rs.MoveNext( );

   while ( !rs.IsEOF( ) )
   {
      CString strFieldValue;
      for( int nIndex = 0;
           nIndex < rs.GetODBCFieldCount( );
           nIndex++ )
      {
         rs.GetFieldValue( nIndex, strFieldValue );

         // TO DO: Use field value string.
      }
      rs.MoveNext( );
   }
}

// All result sets have been flushed. Cannot
// use the cursor, but the output parameter,
// m_nOutParamInstructorCount, has now been written.
// Note that m_nOutParamInstructorCount not valid until
// CRecordset::FlushResultSet has returned FALSE,
// indicating no more result sets will be returned.

// TO DO: Use m_nOutParamInstructorCount

// Cleanup
rs.Close( );
db.Close( );

CRecordset Overview | Class Members | Hierarchy Chart

See Also CFieldExchange::SetFieldType


CRecordset::GetBookmark

void GetBookmark( CDBVariant& varBookmark );
throw( CDBException, CMemoryException );

Parameters

varBookmark

A reference to a CDBVariant object representing the bookmark on the current record.

Remarks

Call this member function to obtain the bookmark value for the current record. To determine if bookmarks are supported on the recordset, call CanBookmark. To make bookmarks available if they are supported, you must set the CRecordset::useBookmarks option in the dwOptions parameter of the Open member function.

Note If bookmarks are unsupported or unavailable, calling GetBookmark will result in an exception being thrown. Bookmarks are not supported on forward-only recordsets.

GetBookmark assigns the value of the bookmark for the current record to a CDBVariant object. To return to that record at any time after moving to a different record, call SetBookmark with the corresponding CDBVariant object.

Note After certain recordset operations, bookmarks may no longer be valid. For example, if you call GetBookmark followed by Requery, you may not be able to return to the record with SetBookmark. Call CDatabase::GetBookmarkPersistence to check whether you can safely call SetBookmark.

For more information about bookmarks and recordset navigation, see the articles Recordset: Bookmarks and Absolute Positions (ODBC) and Recordset: Scrolling (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::CanBookmark, CRecordset::SetBookmark, CDatabase::GetBookmarkPersistence


CRecordset::GetDefaultConnect

virtual CString GetDefaultConnect( );

Return Value

A CString that contains the default connect string.

Remarks

The framework calls this member function to get the default connect string for the data source on which the recordset is based. ClassWizard implements this function for you by identifying the same data source you use in ClassWizard to get information about tables and columns. You will probably find it convenient to rely on this default connection while developing your application. But the default connection may not be appropriate for users of your application. If that is the case, you should reimplement this function, discarding ClassWizard’s version. For more information about connect strings, see the article Data Source (ODBC) in Visual C++ Programmer’s Guide.


CRecordset::GetDefaultSQL

virtual CString GetDefaultSQL( );

Return Value

A CString that contains the default SQL statement.

Remarks

The framework calls this member function to get the default SQL statement on which the recordset is based. This might be a table name or an SQL SELECT statement.

You indirectly define the default SQL statement by declaring your recordset class with ClassWizard, and ClassWizard performs this task for you.

If you need the SQL statement string for your own use, call GetSQL, which returns the SQL statement used to select the recordset’s records when it was opened. You can edit the default SQL string in your class’s override of GetDefaultSQL. For example, you could specify a call to a predefined query using a CALL statement. For more information, see the article Recordset: Declaring a Class for a Table (ODBC) in Visual C++ Programmer’s Guide.

Caution The table name will be empty if the framework could not identify a table name, if multiple table names were supplied, or if a CALL statement could not be interpreted. Note that when using a CALL statement, you must not insert whitespace between the curly brace and the CALL keyword, nor should you insert whitespace before the curly brace or before the SELECT keyword in a SELECT statement.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::GetSQL


CRecordset::GetFieldValue

void GetFieldValue( LPCTSTR lpszName, CDBVariant& varValue, short nFieldType = DEFAULT_FIELD_TYPE );
throw( CDBException, CMemoryException );

void GetFieldValue( short nIndex, CDBVariant& varValue, short nFieldType = DEFAULT_FIELD_TYPE );
throw( CDBException, CMemoryException );

void GetFieldValue( LPCTSTR lpszName, CString& strValue );
throw( CDBException, CMemoryException );

void GetFieldValue( short nIndex, CString& strValue );
throw( CDBException, CMemoryException );

Parameters

lpszName

The name of a field.

varValue

A reference to a CDBVariant object that will store the field's value.

nFieldType

The ODBC C data type of the field. Using the default value, DEFAULT_FIELD_TYPE, forces GetFieldValue to determine the C data type from the SQL data type, based on the following table. Otherwise, you can specify the data type directly or choose a compatible data type; for example, you can store any data type into SQL_C_CHAR.

C data type | SQL data type
SQL_C_BIT | SQL_BIT
SQL_C_UTINYINT | SQL_TINYINT
SQL_C_SSHORT | SQL_SMALLINT
SQL_C_SLONG | SQL_INTEGER
SQL_C_FLOAT | SQL_REAL
SQL_C_DOUBLE | SQL_FLOAT SQL_DOUBLE
SQL_C_TIMESTAMP | SQL_DATE SQL_TIME SQL_TIMESTAMP
SQL_C_CHAR | SQL_NUMERIC SQL_DECIMAL SQL_BIGINT SQL_CHAR SQL_VARCHAR SQL_LONGVARCHAR
SQL_C_BINARY | SQL_BINARY SQL_VARBINARY SQL_LONGVARBINARY

For more information about ODBC data types, see the topics "SQL Data Types" and "C Data Types" in Appendix D of the ODBC SDK Programmer's Reference.

nIndex

The zero-based index of the field.

strValue

A reference to a CString object that will store the field's value converted to text, regardless of the field's data type.

Remarks

Call this member function to retrieve field data in the current record. You can look up a field either by name or by index. You can store the field value in either a CDBVariant object or a CString object.

If you have implemented bulk row fetching, the current record is always positioned on the first record in a rowset. To use GetFieldValue on a record within a given rowset, you must first call the SetRowsetCursorPosition member function to move the cursor to the desired row within that rowset. Then call GetFieldValue for that row. To implement bulk row fetching, you must specify the CRecordset::useMultiRowFetch option of the dwOptions parameter in the Open member function.

You can use GetFieldValue to dynamically fetch fields at run time rather than statically binding them at design time. For example, if you have declared a recordset object directly from CRecordset, you must use GetFieldValue to retrieve the field data; record field exchange (RFX), or bulk record field exchange (Bulk RFX), is not implemented.

Note If you declare a recordset object without deriving from CRecordset, do not have the ODBC Cursor Library loaded. The cursor library requires that the recordset have at least one bound column; however, when you use CRecordset directly, none of the columns are bound. The member functions CDatabase::OpenEx and CDatabase::Open control whether the cursor library will be loaded.

GetFieldValue calls the ODBC API function SQLGetData. If your driver outputs the value SQL_NO_TOTAL for the actual length of the field value, GetFieldValue throws an exception. For more information about SQLGetData, see the ODBC SDK Programmer's Reference.

Example

The following sample code illustrates calls to GetFieldValue for a recordset object declared directly from CRecordset.

// Create and open a database object;
// do not load the cursor library
CDatabase db;
db.OpenEx( NULL, CDatabase::forceOdbcDialog );

// Create and open a recordset object
// directly from CRecordset. Note that a
// table must exist in a connected database.
// Use forwardOnly type recordset for best
// performance, since only MoveNext is required
CRecordset rs( &db );
rs.Open( CRecordset::forwardOnly,
         _T( "SELECT * FROM SomeTable" ) );

// Create a CDBVariant object to
// store field data
CDBVariant varValue;

// Loop through the recordset,
// using GetFieldValue and
// GetODBCFieldCount to retrieve
// data in all columns
short nFields = rs.GetODBCFieldCount( );
while( !rs.IsEOF( ) )
{
   for( short index = 0; index < nFields; index++ )
   {
      rs.GetFieldValue( index, varValue );
      // do something with varValue
   }
   rs.MoveNext( );
}

rs.Close( );
db.Close( );

Note Unlike the DAO class CDaoRecordset, CRecordset does not have a SetFieldValue member function. If you create an object directly from CRecordset, it is effectively read-only.

For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::DoFieldExchange, CRecordset::DoBulkFieldExchange, CRecordset::GetODBCFieldCount, CRecordset::GetODBCFieldInfo, CRecordset::SetRowsetCursorPosition


CRecordset::GetODBCFieldCount

short GetODBCFieldCount( ) const;

Return Value

The number of fields in the recordset.

Remarks

Call this member function to retrieve the total number of fields in your recordset object.

For more information about creating recordsets, see the article Recordset: Creating and Closing Recordsets (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::GetFieldValue


CRecordset::GetODBCFieldInfo

void GetODBCFieldInfo( LPCTSTR lpszName, CODBCFieldInfo& fieldinfo );
throw( CDBException );

void GetODBCFieldInfo( short nIndex, CODBCFieldInfo& fieldinfo );
throw( CDBException );

Parameters

lpszName

The name of a field.

fieldinfo

A reference to a CODBCFieldInfo structure.

nIndex

The zero-based index of the field.

Remarks

Call this member function to obtain information about the fields in the recordset. One version of the function lets you look up a field by name. The other version lets you look up a field by index.

For a description about the information returned, see the CODBCFieldInfo structure.

For more information about creating recordsets, see the article Recordset: Creating and Closing Recordsets (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::GetFieldValue, CODBCFieldInfo


CRecordset::GetRecordCount

long GetRecordCount( ) const;

Return Value

The number of records in the recordset; 0 if the recordset contains no records; or –1 if the record count cannot be determined.

Remarks

Call this member function to determine the size of the recordset.

Caution The record count is maintained as a “high water mark” — the highest-numbered record yet seen as the user moves through the records. The total number of records is only known after the user has moved beyond the last record. For performance reasons, the count is not updated when you call MoveLast. To count the records yourself, call MoveNext repeatedly until IsEOF returns nonzero. Adding a record via CRecordset:AddNew and Update increases the count; deleting a record via CRecordset::Delete decreases the count.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::MoveLast, CRecordset::MoveNext, CRecordset::IsEOF, CRecordset::GetStatus


CRecordset::GetRowsetSize

DWORD GetRowsetSize( ) const;

Return Value

The number of rows to retrieve during a given fetch.

Remarks

Call this member function to obtain the current setting for the number of rows you wish to retrieve during a given fetch. If you are using bulk row fetching, the default rowset size when the recordset is opened is 25; otherwise, it is 1.

To implement bulk row fetching, you must specify the CRecordset::useMultiRowFetch option in the dwOptions parameter of the Open member function. To change the setting for the rowset size, call SetRowsetSize.

For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Open, CRecordset::SetRowsetSize, CRecordset::CheckRowsetError, CRecordset::DoBulkFieldExchange


CRecordset::GetRowsFetched

DWORD GetRowsFetched( ) const;

Return Value

The number of rows retrieved from the data source after a given fetch.

Remarks

Call this member function to determine how many records were actually retrieved after a fetch. This is useful when you have implemented bulk row fetching. The rowset size normally indicates how many rows will be retrieved from a fetch; however, the total number of rows in the recordset also affects how many rows will be retrieved in a rowset. For example, if your recordset has 10 records with a rowset size setting of 4, then looping through the recordset by calling MoveNext will result in the final rowset having only 2 records.

To implement bulk row fetching, you must specify the CRecordset::useMultiRowFetch option in the dwOptions parameter of the Open member function. To specify the rowset size, call SetRowsetSize.

For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Example

MultiRowSet rs;

// Set the rowset size
rs.SetRowsetSize( 5 );

// Open the recordset
rs.Open( CRecordset::dynaset, NULL,
         CRecordset::useMultiRowFetch );

// loop through the recordset by rowsets
while( !rs.IsEOF( ) )
{
    for( int rowCount = 0;
         rowCount < (int)rs.GetRowsFetched( );
         rowCount++ )
    {
       // do something
    }

   rs.MoveNext( );
}

rs.Close( );

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::SetRowsetSize, CRecordset::CheckRowsetError


CRecordset::GetRowStatus

WORD GetRowStatus( WORD wRow ) const;

Return Value

A status value for the row. For details, see Remarks.

Parameters

wRow

The one-based position of a row in the current rowset. This value can range from 1 to the size of the rowset.

Remarks

Call this member function to obtain the status for a row in the current rowset. GetRowStatus returns a value that indicates either any change in status to the row since it was last retrieved from the data source, or that no row corresponding to wRow was fetched. The following table lists the possible return values.

Status value | Description
SQL_ROW_SUCCESS | The row is unchanged.
SQL_ROW_UPDATED | The row has been updated.
SQL_ROW_DELETED | The row has been deleted.
SQL_ROW_ADDED | The row has been added.
SQL_ROW_ERROR | The row is unretrievable due to an error.
SQL_ROW_NOROW | There is no row that corresponds to wRow.

For more information, see the ODBC API function SQLExtendedFetch in the ODBC SDK Programmer's Reference.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::CheckRowsetError, CRecordset::GetRowsFetched, CRecordset::RefreshRowset


CRecordset::GetStatus

void GetStatus( CRecordsetStatus& rStatus ) const;

Parameters

rStatus

A reference to a CRecordsetStatus object. See the Remarks section for more information.

Remarks

Call this member function to determine the index of the current record in the recordset and/or whether the last record has been seen. CRecordset attempts to track the index, but under some circumstances this may not be possible. See GetRecordCount for an explanation.

The CRecordsetStatus structure has the following form:

struct CRecordsetStatus
{
    long m_lCurrentRecord;
    BOOL m_bRecordCountFinal;
};

The two members of CRecordsetStatus have the following meanings:

  • m_lCurrentRecord Contains the zero-based index of the current record in the recordset, if known. If the index cannot be determined, this member contains AFX_CURRENT_RECORD_UNDEFINED (–2). If IsBOF is TRUE (empty recordset or attempt to scroll before first record), then m_lCurrentRecord is set to AFX_CURRENT_RECORD_BOF (–1). If on the first record, then it is set to 0, second record 1, and so on.

  • m_bRecordCountFinal Nonzero if the total number of records in the recordset has been determined. Generally this must be accomplished by starting at the beginning of the recordset and calling MoveNext until IsEOF returns nonzero. If this member is zero, the record count as returned by GetRecordCount, if not –1, is only a “high water mark” count of the records.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::GetRecordCount


CRecordset::GetSQL

const CString& GetSQL( ) const;

Return Value

A const reference to a CString that contains the SQL statement.

Remarks

Call this member function to get the SQL statement that was used to select the recordset’s records when it was opened. This will generally be an SQL SELECT statement. The string returned by GetSQL is read-only.

The string returned by GetSQL is typically different from any string you may have passed to the recordset in the lpszSQL parameter to the Open member function. This is because the recordset constructs a full SQL statement based on what you passed to Open, what you specified with ClassWizard, what you may have specified in the m_strFilter and m_strSort data members, and any parameters you may have specified. For details about how the recordset constructs this SQL statement, see the article Recordset: How Recordsets Select Records (ODBC) in Visual C++ Programmer’s Guide.

Important Call this member function only after calling Open.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::GetDefaultSQL, CRecordset::Open, CRecordset::m_strFilter, CRecordset::m_strSort


CRecordset::GetTableName

const CString& GetTableName( ) const;

Return Value

A const reference to a CString that contains the table name, if the recordset is based on a table; otherwise, an empty string.

Remarks

Call this member function to get the name of the SQL table on which the recordset’s query is based. GetTableName is only valid if the recordset is based on a table, not a join of multiple tables or a predefined query (stored procedure). The name is read-only.

Important Call this member function only after calling Open.


CRecordset::IsBOF

BOOL IsBOF( ) const;

Return Value

Nonzero if the recordset contains no records or if you have scrolled backward before the first record; otherwise 0.

Remarks

Call this member function before you scroll from record to record to learn whether you have gone before the first record of the recordset. You can also use IsBOF along with IsEOF to determine whether the recordset contains any records or is empty. Immediately after you call Open, if the recordset contains no records, IsBOF returns nonzero.When you open a recordset that has at least one record, the first record is the current record and IsBOF returns 0.

If the first record is the current record and you call MovePrev, IsBOF will subsequently return nonzero. If IsBOF returns nonzero and you call MovePrev, an error occurs. If IsBOF returns nonzero, the current record is undefined, and any action that requires a current record will result in an error.

Example

This example uses IsBOF and IsEOF to detect the limits of a recordset as the code scrolls through the recordset in both directions.

// Open a recordset; first record is current
CCustSet rsCustSet( NULL );
rsCustSet.Open( );

if( rsCustSet.IsBOF( ) )
    return;
    // The recordset is empty

// Scroll to the end of the recordset, past
// the last record, so no record is current
while ( !rsCustSet.IsEOF( ) )
    rsCustSet.MoveNext( );

// Move to the last record
rsCustSet.MoveLast( );

// Scroll to beginning of the recordset, before
// the first record, so no record is current
while( !rsCustSet.IsBOF( ) )
    rsCustSet.MovePrev( );

// First record is current again
rsCustSet.MoveFirst( );

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::IsEOF, CRecordset::MoveFirst, CRecordset::MovePrev


CRecordset::IsDeleted

BOOL IsDeleted( ) const;

Return Value

Nonzero if the recordset is positioned on a deleted record; otherwise 0.

Remarks

Call this member function to determine whether the current record has been deleted. If you scroll to a record and IsDeleted returns TRUE (nonzero), then you must scroll to another record before you can perform any other recordset operations.

Be aware that the result of IsDeleted depends on many factors, such as your recordset type, whether your recordset is updatable, whether you specified the CRecordset::skipDeletedRecords option when you opened the recordset, whether your driver packs deleted records, and whether there are multiple users.

For more information about CRecordset::skipDeletedRecords and driver packing, see the Open member function.

Note If you have implemented bulk row fetching, you should not call IsDeleted. Instead, call the GetRowStatus member function. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Delete, CRecordset::IsBOF, CRecordset::IsEOF


CRecordset::IsEOF

BOOL IsEOF( ) const;

Return Value

Nonzero if the recordset contains no records or if you have scrolled beyond the last record; otherwise 0.

Remarks

Call this member function as you scroll from record to record to learn whether you have gone beyond the last record of the recordset. You can also use IsEOF to determine whether the recordset contains any records or is empty. Immediately after you call Open, if the recordset contains no records, IsEOF returns nonzero. When you open a recordset that has at least one record, the first record is the current record and IsEOF returns 0.

If the last record is the current record when you call MoveNext, IsEOF will subsequently return nonzero. If IsEOF returns nonzero and you call MoveNext, an error occurs. If IsEOF returns nonzero, the current record is undefined, and any action that requires a current record will result in an error.

Example

See the example for IsBOF.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::IsBOF, CRecordset::MoveLast, CRecordset::MoveNext


CRecordset::IsFieldDirty

BOOL IsFieldDirty( void* pv );
throw( CMemoryException );

Return Value

Nonzero if the specified field data member has changed since calling AddNew or Edit; otherwise 0.

Parameters

pv

A pointer to the field data member whose status you want to check, or NULL to determine if any of the fields are dirty.

Remarks

Call this member function to determine whether the specified field data member has been changed since Edit or AddNew was called. The data in all dirty field data members will be transferred to the record on the data source when the current record is updated by a call to the Update member function of CRecordset (following a call to Edit or AddNew).

Note This member function is not applicable on recordsets that are using bulk row fetching. If you have implemented bulk row fetching, then IsFieldDirty will always return FALSE and will result in a failed assertion. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Calling IsFieldDirty will reset the effects of preceding calls to SetFieldDirty since the dirty status of the field is re-evaluated. In the AddNew case, if the current field value differs from the pseudo null value, the field status is set dirty. In the Edit case, if the field value differs from the cached value, then the field status is set dirty.

IsFieldDirty is implemented through DoFieldExchange.

For more information on the dirty flag, see the article Recordset: How Recordsets Select Records (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::SetFieldDirty, CRecordset::IsFieldNull


CRecordset::IsFieldNull

BOOL IsFieldNull( void* pv );
throw( CMemoryException );

Return Value

Nonzero if the specified field data member is flagged as Null; otherwise 0.

Parameters

pv

A pointer to the field data member whose status you want to check, or NULL to determine if any of the fields are Null.

Remarks

Call this member function to determine whether the specified field data member of a recordset has been flagged as Null. (In database terminology, Null means “having no value” and is not the same as NULL in C++.) If a field data member is flagged as Null, it is interpreted as a column of the current record for which there is no value.

Note This member function is not applicable on recordsets that are using bulk row fetching. If you have implemented bulk row fetching, then IsFieldNull will always return FALSE and will result in a failed assertion. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

IsFieldNull is implemented through DoFieldExchange.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::SetFieldNull, CRecordset::IsFieldDirty


CRecordset::IsFieldNullable

BOOL IsFieldNullable( void* pv );
throw( CDBException );

Parameters

pv

A pointer to the field data member whose status you want to check, or NULL to determine if any of the fields can be set to a Null value.

Remarks

Call this member function to to determine whether the specified field data member is “nullable” (can be set to a Null value; C++ NULL is not the same as Null, which, in database terminology, means “having no value”).

Note If you have implemented bulk row fetching, you cannot call IsFieldNullable. Instead, call the GetODBCFieldInfo member function to determine whether a field can be set to a Null value. Note that you can always call GetODBCFieldInfo, regardless of whether you have implemented bulk row fetching. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

A field that cannot be Null must have a value. If you attempt to set a such a field to Null when adding or updating a record, the data source rejects the addition or update, and Update will throw an exception. The exception occurs when you call Update, not when you call SetFieldNull.

Using NULL for the first argument of the function will apply the function only to outputColumns, not params. For instance, the call

SetFieldNull( NULL );

will set only outputColumns to NULL. Params will be unaffected.

To work on params, you must supply the actual address of the individual param you want to work on, such as:

SetFieldNull( &m_strParam );

This means you cannot set all params NULL, as you can with outputColumns.

IsFieldNullable is implemented through DoFieldExchange.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::IsFieldNull, CRecordset::SetFieldNull


CRecordset::IsOpen

BOOL IsOpen( ) const;

Return Value

Nonzero if the recordset object’s Open or Requery member function has previously been called and the recordset has not been closed; otherwise 0.

Remarks

Call this member function to determine if the recordset is already open.


CRecordset::Move

virtual void Move( long nRows, WORD wFetchType = SQL_FETCH_RELATIVE );
throw( CDBException, CMemoryException );

Parameters

nRows

The number of rows to move forward or backward. Positive values move forward, toward the end of the recordset. Negative values move backward, toward the beginning.

wFetchType

Determines the rowset that Move will fetch. For details, see Remarks.

Remarks

Call this member function to move the current record pointer within the recordset, either forward or backward. If you pass a value of 0 for nRows, Move refreshes the current record; Move will end any current AddNew or Edit mode, and will restore the current record's value before AddNew or Edit was called.

Note When moving through a recordset, deleted records may not be skipped. See the IsDeleted member function for details.

Move repositions the recordset by rowsets. Based on the values for nRows and wFetchType, Move fetches the appropriate rowset and then makes the first record in that rowset the current record. If you have not implemented bulk row fetching, then the rowset size is always 1. When fetching a rowset, Move directly calls the CheckRowsetError member function to handle any errors resulting from the fetch.

Depending on the values you pass, Move is equivalent to other CRecordset member functions. In particular, the value of wFetchType may indicate a member function that is more intuitive and often the preferred method for moving the current record.

The following table lists the possible values for wFetchType, the rowset that Move will fetch based on wFetchType and nRows, and any equivalent member function corresponding to wFetchType.

wFetchType | Fetched rowset | Equivalent member function
SQL_FETCH_RELATIVE (the default value) | The rowset starting nRows row(s) from the first row in the current rowset. |
SQL_FETCH_NEXT | The next rowset; nRows is ignored. | MoveNext
SQL_FETCH_PRIOR | The previous rowset; nRows is ignored. | MovePrev
SQL_FETCH_FIRST | The first rowset in the recordset; nRows is ignored. | MoveFirst
SQL_FETCH_LAST | The last complete rowset in the recordset; nRows is ignored. | MoveLast
SQL_FETCH_ABSOLUTE | If nRows > 0, the rowset starting nRows row(s) from the beginning of the recordset. If nRows < 0, the rowset starting nRows row(s) from the end of the recordset. If nRows = 0, then a beginning-of-file (BOF) condition is returned. | SetAbsolutePosition
SQL_FETCH_BOOKMARK | The rowset starting at the row whose bookmark value corresponds to nRows. | SetBookmark

Note For foward-only recordsets, Move is only valid with a value of SQL_FETCH_NEXT for wFetchType.

Caution Calling Move throws an exception if the recordset has no records. To determine whether the recordset has any records, call IsBOF and IsEOF.

If you have scrolled past the beginning or end of the recordset (IsBOF or IsEOF returns nonzero), calling a Move function will possibly throw a CDBException. For example, if IsEOF returns nonzero and IsBOF does not, then MoveNext will throw an exception, but MovePrev will not.

If you call Move while the current record is being updated or added, the updates are lost without warning.

For more information about recordset navigation, see the articles Recordset: Scrolling (ODBC) and Recordset: Bookmarks and Absolute Positions (ODBC) in Visual C++ Programmer’s Guide. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide. For related information, see the ODBC API function SQLExtendedFetch in the ODBC SDK Programmer's Reference.

Example

// rs is a CRecordset or a
// CRecordset-derived object

// Change the rowset size to 5
rs.SetRowsetSize( 5 );

// Move to the first record
// in the recordset
rs.MoveFirst( );

// Move to the sixth record
rs.Move( 5 );
// Other equivalent ways to
// move to the sixth record:
// rs.Move( 6, SQL_FETCH_ABSOLUTE );
// rs.SetAbsolutePosition( 6 );
// In this case, the sixth record is
// the first record in the next rowset,
// so the following are also equivalent:
// rs.Move( 1, SQL_FETCH_NEXT );
// rs.MoveNext( );

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::MoveNext, CRecordset::MovePrev, CRecordset::MoveFirst, CRecordset::MoveLast, CRecordset::SetAbsolutePosition, CRecordset::SetBookmark, CRecordset::IsBOF, CRecordset::IsEOF, CRecordset::CheckRowsetError


CRecordset::MoveFirst

void MoveFirst( );
throw( CDBException, CMemoryException );

Remarks

Call this member function to make the first record in the first rowset the current record. Regardless of whether bulk row fetching has been implemented, this will always be the first record in the recordset.

You do not have to call MoveFirst immediately after you open the recordset. At that time, the first record (if any) is automatically the current record.

Note This member function is not valid for forward-only recordsets.

Note When moving through a recordset, deleted records may not be skipped. See the IsDeleted member function for details.

Caution Calling any of the Move functions throws an exception if the recordset has no records. To determine whether the recordset has any records, call IsBOF and IsEOF.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

For more information about recordset navigation, see the articles Recordset: Scrolling (ODBC) and Recordset: Bookmarks and Absolute Positions (ODBC) in Visual C++ Programmer’s Guide. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Example

See the example for IsBOF.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Move, CRecordset::MoveLast, CRecordset::MoveNext, CRecordset::MovePrev, CRecordset::IsBOF, CRecordset::IsEOF


CRecordset::MoveLast

void MoveLast( );
throw( CDBException, CMemoryException );

Remarks

Call this member function to make the first record in the last complete rowset the current record. If you have not implemented bulk row fetching, your recordset has a rowset size of 1, so MoveLast simply moves to the last record in the recordset.

Note This member function is not valid for forward-only recordsets.

Note When moving through a recordset, deleted records may not be skipped. See the IsDeleted member function for details.

Caution Calling any of the Move functions throws an exception if the recordset has no records. To determine whether the recordset has any records, call IsBOF and IsEOF.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

For more information about recordset navigation, see the articles Recordset: Scrolling (ODBC) and Recordset: Bookmarks and Absolute Positions (ODBC) in Visual C++ Programmer’s Guide. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Example

See the example for IsBOF.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Move, CRecordset::MoveFirst, CRecordset::MoveNext, CRecordset::MovePrev, CRecordset::IsBOF, CRecordset::IsEOF


CRecordset::MoveNext

void MoveNext( );
throw( CDBException, CMemoryException );

Remarks

Call this member function to make the first record in the next rowset the current record. If you have not implemented bulk row fetching, your recordset has a rowset size of 1, so MoveNext simply moves to the next record.

Note When moving through a recordset, deleted records may not be skipped. See the IsDeleted member function for details.

Caution Calling any of the Move functions throws an exception if the recordset has no records. To determine whether the recordset has any records, call IsBOF and IsEOF.

It is also recommended that you call IsEOF before calling MoveNext. For example, if you have scrolled past the end of the recordset, IsEOF will return nonzero; a subsequent call to MoveNext would throw an exception.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

For more information about recordset navigation, see the articles Recordset: Scrolling (ODBC) and Recordset: Bookmarks and Absolute Positions (ODBC) in Visual C++ Programmer’s Guide. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Example

See the example for IsBOF.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Move, CRecordset::MovePrev, CRecordset::MoveFirst, CRecordset::MoveLast, CRecordset::IsBOF, CRecordset::IsEOF


CRecordset::MovePrev

void MovePrev( );
throw( CDBException, CMemoryException );

Remarks

Call this member function to make the first record in the previous rowset the current record. If you have not implemented bulk row fetching, your recordset has a rowset size of 1, so MovePrev simply moves to the previous record.

Note This member function is not valid for forward-only recordsets.

Note When moving through a recordset, deleted records may not be skipped. See the IsDeleted member function for details.

Caution Calling any of the Move functions throws an exception if the recordset has no records. To determine whether the recordset has any records, call IsBOF and IsEOF.

It is also recommended that you call IsBOF before calling MovePrev. For example, if you have scrolled ahead of the beginning of the recordset, IsBOF will return nonzero; a subsequent call to MovePrev would throw an exception.

If you call any of the Move functions while the current record is being updated or added, the updates are lost without warning.

For more information about recordset navigation, see the articles Recordset: Scrolling (ODBC) and Recordset: Bookmarks and Absolute Positions (ODBC) in Visual C++ Programmer’s Guide. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Example

See the example for IsBOF.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Move, CRecordset::MoveNext, CRecordset::MoveFirst, CRecordset::MoveLast, CRecordset::IsBOF, CRecordset::IsEOF


CRecordset::OnSetOptions

virtual void OnSetOptions( HSTMT hstmt );

Parameters

hstmt

The HSTMT of the ODBC statement whose options are to be set.

Remarks

The framework calls this member function to set initial options for the recordset. OnSetOptions determines the data source’s support for scrollable cursors and for cursor concurrency and sets the recordset’s options accordingly.

Override OnSetOptions to set additional options specific to the driver or the data source. For example, if your data source supports opening for exclusive access, you might override OnSetOptions to take advantage of that ability.

For more information about cursors, see the article ODBC in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CDatabase::OnSetOptions


CRecordset::Open

virtual BOOL Open( UINT nOpenType = AFX_DB_USE_DEFAULT_TYPE, LPCTSTR lpszSQL = NULL, DWORD dwOptions = none );
throw( CDBException, CMemoryException );

Return Value

Nonzero if the CRecordset object was successfully opened; otherwise 0 if CDatabase::Open (if called) returns 0.

Parameters

nOpenType

Accept the default value, AFX_DB_USE_DEFAULT_TYPE, or use one of the following values from the enum OpenType:

  • CRecordset::dynaset A recordset with bi-directional scrolling. The membership and ordering of the records are determined when the recordset is opened, but changes made by other users to the data values are visible following a fetch operation. Dynasets are also known as keyset-driven recordsets.

  • CRecordset::snapshot A static recordset with bi-directional scrolling. The membership and ordering of the records are determined when the recordset is opened; the data values are determined when the records are fetched. Changes made by other users are not visible until the recordset is closed and then reopened.

  • CRecordset::dynamic A recordset with bi-directional scrolling. Changes made by other users to the membership, ordering, and data values are visible following a fetch operation. Note that many ODBC drivers do not support this type of recordset.

  • CRecordset::forwardOnly A read-only recordset with only forward scrolling.

    For CRecordset, the default value is CRecordset::snapshot. The default-value mechanism allows the Visual C++ wizards to interact with both ODBC CRecordset and DAO CDaoRecordset, which have different defaults.

    For more information about these recordset types, see the article Recordset (ODBC) in Visual C++ Programmer’s Guide. For related information, see the article ”Using Block and Scrollable Cursors" in the ODBC SDK Programmer's Reference.

    Caution If the requested type is not supported, the framework throws an exception.

lpszSQL

A string pointer containing one of the following:

  • A NULL pointer.

  • The name of a table.

  • An SQL SELECT statement (optionally with an SQL WHERE or ORDER BY clause).

  • A CALL statement specifying the name of a predefined query (stored procedure). Be careful that you do not insert whitespace between the curly brace and the CALL keyword.

    For more information about this string, see the table and the discussion of ClassWizard’s role under Remarks.

    Note The order of the columns in your result set must match the order of the RFX or Bulk RFX function calls in your DoFieldExchange or DoBulkFieldExchange function override.

dwOptions

A bitmask which can specify a combination of the values listed below. Some of these are mutually exclusive. The default value is none.

  • CRecordset::none No options set. This parameter value is mutually exclusive with all other values. By default, the recordset can be updated with Edit or Delete and allows appending new records with AddNew. Updatability depends on the data source as well as on the nOpenType option you specify. Optimization for bulk additions is not available. Bulk row fetching will not be implemented. Deleted records will not be skipped during recordset navigation. Bookmarks are not available. Automatic dirty field checking is implemented.

  • CRecordset::appendOnly Do not allow Edit or Delete on the recordset. Allow AddNew only. This option is mutually exclusive with CRecordset::readOnly.

  • CRecordset::readOnly Open the recordset as read-only. This option is mutually exclusive with CRecordset::appendOnly.

  • CRecordset::optimizeBulkAdd Use a prepared SQL statement to optimize adding many records at one time. Applies only if you are not using the ODBC API function SQLSetPos to update the recordset. The first update determines which fields are marked dirty. This option is mutually exclusive with CRecordset::useMultiRowFetch.

  • CRecordset::useMultiRowFetch Implement bulk row fetching to allow multiple rows to be retrieved in a single fetch operation. This is an advanced feature designed to improve performance; however, bulk record field exchange is not supported by ClassWizard. This option is mutually exclusive with CRecordset::optimizeBulkAdd. Note that if you specify CRecordset::useMultiRowFetch, then the option CRecordset::noDirtyFieldCheck will be turned on automatically (double buffering will not be available); on forward-only recordsets, the option CRecordset::useExtendedFetch will be turned on automatically. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

  • CRecordset::skipDeletedRecords Skip all deleted records when navigating through the recordset. This will slow performance in certain relative fetches. This option is not valid on forward-only recordsets. Note that CRecordset::skipDeletedRecords is similar to driver packing, which means that deleted rows are removed from the recordset. However, if your driver packs records, then it will skip only those records that you delete; it will not skip records deleted by other users while the recordset is open. CRecordset::skipDeletedRecords will skip rows deleted by other users.

  • CRecordset::useBookmarks May use bookmarks on the recordset, if supported. Bookmarks slow data retrieval but improve performance for data navigation. Not valid on forward-only recordsets. For more information, see the article Recordset: Bookmarks and Absolute Positions (ODBC) in Visual C++ Programmer’s Guide.

  • CRecordset::noDirtyFieldCheck Turn off automatic dirty field checking (double buffering). This will improve performance; however, you must manually mark fields as dirty by calling the SetFieldDirty and SetFieldNull member functions.Note that double buffering in class CRecordset is similar to double buffering in class CDaoRecordset. However, in CRecordset, you cannot enable double buffering on individual fields; you either enable it for all fields or disable it for all fields. For more information about double buffering, see the DAO article DAO Record Field Exchange: Double Buffering Records in Visual C++ Programmer’s Guide. Note that if you specify the option CRecordset::useMultiRowFetch, then CRecordset::noDirtyFieldCheck will be turned on automatically; however, SetFieldDirty and SetFieldNull cannot be used on recordsets that implement bulk row fetching.

  • CRecordset::executeDirect Do not use a prepared SQL statement. For improved performance, specify this option if the Requery member function will never be called.

  • CRecordset::useExtendedFetch Implement SQLExtendedFetch instead of SQLFetch. This is designed for implementing bulk row fetching on forward-only recordsets. If you specify the option CRecordset::useMultiRowFetch on a forward-only recordset, then CRecordset::useExtendedFetch will be turned on automatically.

  • CRecordset::userAllocMultiRowBuffers The user will allocate storage buffers for the data. Use this option in conjunction with CRecordset::useMultiRowFetch if you want to allocate your own storage; otherwise, the framework will automatically allocate the necessary storage. For more information, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide. Note that specifying CRecordset::userAllocMultiRowBuffers without specifying CRecordset::useMultiRowFetch will result in a failed assertion.

Remarks

You must call this member function to run the query defined by the recordset. Before calling Open, you must construct the recordset object.

This recordset’s connection to the data source depends on how you construct the recordset before calling Open. If you pass a CDatabase object to the recordset constructor that has not been connected to the data source, this member function uses GetDefaultConnect to attempt to open the database object. If you pass NULL to the recordset constructor, the constructor constructs a CDatabase object for you, and Open attempts to connect the database object. For details on closing the recordset and the connection under these varying circumstances, see Close.

Note Access to a data source through a CRecordset object is always shared. Unlike the CDaoRecordset class, you cannot use a CRecordset object to open a data source with exclusive access.

When you call Open, a query, usually an SQL SELECT statement, selects records based on criteria shown in the following table.

Value of the lpszSQL parameter | Records selected are determined by | Example
NULL | The string returned by GetDefaultSQL.
SQL table name All columns of the table-list in DoFieldExchange or DoBulkFieldExchange.
"Customer"
Predefined query (stored procedure) name The columns the query is defined to return.
"{call OverDueAccts}"
SELECT column-list FROM table-list The specified columns from the specified table(s).
"SELECT CustId, CustName FROM
Customer"

! Warning Be careful that you do not insert extra whitespace in your SQL string. For example, if you insert whitespace between the curly brace and the CALL keyword, MFC will misinterpret the SQL string as a table name and incorporate it into a SELECT statement, which will result in an exception being thrown. Similarly, if your predefined query uses an output parameter, do not insert whitespace between the curly brace and the '?' symbol. Finally, you must not insert whitespace before the curly brace in a CALL statement or before the SELECT keyword in a SELECT statment.

The usual procedure is to pass NULL to Open; in this case, Open calls GetDefaultSQL. If you are using a derived CRecordset class, GetDefualtSQL gives the table name(s) you specified in ClassWizard. You can instead specify other information in the lpszSQL parameter.

Whatever you pass, Open constructs a final SQL string for the query (the string may have SQL WHERE and ORDER BY clauses appended to the lpszSQL string you passed) and then executes the query. You can examine the constructed string by calling GetSQL after calling Open. For additional details about how the recordset constructs an SQL statement and selects records, see the article Recordset: How Recordsets Select Records (ODBC) in Visual C++ Programmer’s Guide.

The field data members of your recordset class are bound to the columns of the data selected. If any records are returned, the first record becomes the current record.

If you want to set options for the recordset, such as a filter or sort, specify these after you construct the recordset object but before you call Open. If you want to refresh the records in the recordset after the recordset is already open, call Requery.

For more information, including additional examples, see the articles Recordset (ODBC), Recordset: How Recordsets Select Records (ODBC), and Recordset: Creating and Closing Recordsets (ODBC) in Visual C++ Programmer’s Guide.

Example

The following code examples show different forms of the Open call.

// rs is a CRecordset or
// CRecordset-derived object

// Open rs using the default SQL statement,
// implement bookmarks, and turn off
// automatic dirty field checking
rs.Open( CRecordset::snapshot, NULL,
         CRecordset::useBookmarks |
         CRecordset::noDirtyFieldCheck );

// Pass a complete SELECT statement
// and open as a dynaset
rs.Open( CRecordset::dynaset,
         _T( "Select L_Name from Customer" ) );

// Accept all defaults
rs.Open( );

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::CRecordset, CRecordset::Close, CRecordset::GetDefaultSQL, CRecordset::GetSQL, CRecordset::m_strFilter, CRecordset::m_strSort, CRecordset::Requery


CRecordset::RefreshRowset

void RefreshRowset( WORD wRow, WORD wLockType = SQL_LOCK_NO_CHANGE );

Parameters

wRow

The one-based position of a row in the current rowset. This value can range from zero to the size of the rowset.

wLockType

A value indicating how to lock the row after it has been refreshed. For details, see Remarks.

Remarks

Call this member function to update the data and the status for a row in the current rowset. If you pass a value of zero for wRow, then every row in the rowset will be refreshed.

To use RefreshRowset, you must have implemented bulk row fetching by specifying the CRecordset::useMulitRowFetch option in the Open member function.

RefreshRowset calls the ODBC API function SQLSetPos. The wLockType parameter specifies the lock state of the row after SQLSetPos has executed. The following table describes the possible values for wLockType.

wLockType | Description
SQL_LOCK_NO_CHANGE (the default value) | The driver or data source ensures that the row is in the same locked or unlocked state as it was before RefreshRowset was called.
SQL_LOCK_EXCLUSIVE | The driver or data source locks the row exclusively. Not all data sources support this type of lock.
SQL_LOCK_UNLOCK | The driver or data source unlocks the row. Not all data sources support this type of lock.

For more information about SQLSetPos, see the ODBC SDK Programmer's Reference. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::SetRowsetCursorPosition, CRecordset::SetRowsetSize


CRecordset::Requery

virtual BOOL Requery( );
throw( CDBException, CMemoryException );

Return Value

Nonzero if the recordset was successfully rebuilt; otherwise 0.

Remarks

Call this member function to rebuild (refresh) a recordset. If any records are returned, the first record becomes the current record.

In order for the recordset to reflect the additions and deletions that you or other users are making to the data source, you must rebuild the recordset by calling Requery. If the recordset is a dynaset, it automatically reflects updates that you or other users make to its existing records (but not additions). If the recordset is a snapshot, you must call Requery to reflect edits by other users as well as additions and deletions.

For either a dynaset or a snapshot, call Requery any time you want to rebuild the recordset using a new filter or sort, or new parameter values. Set the new filter or sort property by assigning new values to m_strFilter and m_strSort before calling Requery. Set new parameters by assigning new values to parameter data members before calling Requery. If the filter and sort strings are unchanged, you can reuse the query, which improves performance.

If the attempt to rebuild the recordset fails, the recordset is closed. Before you call Requery, you can determine whether the recordset can be requeried by calling the CanRestart member function. CanRestart does not guarantee that Requery will succeed.

Caution Call Requery only after you have called Open.

Example

This example rebuilds a recordset to apply a different sort order.

// Example for CRecordset::Requery

CCustSet rsCustSet( NULL );

// Open the recordset
rsCustSet.Open( );

// Use the recordset ...

// Set the sort order and Requery the recordset
rsCustSet.m_strSort = "District, Last_Name";
if( !rsCustSet.CanRestart( ) )
   return;    // Unable to requery

if( !rsCustSet.Requery( ) )
   // Requery failed, so take action

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::CanRestart, CRecordset::m_strFilter, CRecordset::m_strSort


CRecordset::SetAbsolutePosition

void SetAbsolutePosition( long nRows );
throw( CDBException, CMemoryException );

Parameters

nRows

The one-based ordinal position for the current record in the recordset.

Remarks

Call this member function to position the recordset on the record corresponding to the specified record number. SetAbsolutePosition moves the current record pointer based on this ordinal position.

Note This member function is not valid on forward-only recordsets.

For ODBC recordsets, an absolute position setting of 1 refers to the first record in the recordset; a setting of 0 refers to the beginning-of-file (BOF) position.

You can also pass negative values to SetAbsolutePosition. In this case the recordset's position is evaluated from the end of the recordset. For example, SetAbsolutePosition( -1 ) moves the current record pointer to the last record in the recordset.

Note Absolute position is not intended to be used as a surrogate record number. Bookmarks are still the recommended way of retaining and returning to a given position, since a record's position changes when preceding records are deleted. In addition, you cannot be assured that a given record will have the same absolute position if the recordset is re-created again because the order of individual records within a recordset is not guaranteed unless it is created with an SQL statement using an ORDER BY clause.

For more information about recordset navigation and bookmarks, see the articles Recordset: Scrolling (ODBC) and Recordset: Bookmarks and Absolute Positions (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::SetBookmark


CRecordset::SetBookmark

void SetBookmark( const CDBVariant& varBookmark );
throw( CDBException, CMemoryException );

Parameters

varBookmark

A reference to a CDBVariant object containing the bookmark value for a specific record.

Remarks

Call this member function to position the recordset on the record containing the specified bookmark. To determine if bookmarks are supported on the recordset, call CanBookmark. To make bookmarks available if they are supported, you must set the CRecordset::useBookmarks option in the dwOptions parameter of the Open member function.

Note If bookmarks are unsupported or unavailable, calling SetBookmark will result in an exception being thrown. Bookmarks are not supported on forward-only recordsets.

To first retrieve the bookmark for the current record, call GetBookmark, which saves the bookmark value to a CDBVariant object. Later, you can return to that record by calling SetBookmark using the saved bookmark value.

Note After certain recordset operations, you should check the bookmark persistence before calling SetBookmark. For example, if you retrieve a bookmark with GetBookmark and then call Requery, the bookmark may no longer be valid. Call CDatabase::GetBookmarkPersistence to check whether you can safely call SetBookmark.

For more information about bookmarks and recordset navigation, see the articles Recordset: Bookmarks and Absolute Positions (ODBC) and Recordset: Scrolling (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::CanBookmark, CRecordset::GetBookmark, CRecordset::SetAbsolutePosition, CDatabase::GetBookmarkPersistence


CRecordset::SetFieldDirty

void SetFieldDirty( void* pv, BOOL bDirty = TRUE );

Parameters

pv

Contains the address of a field data member in the recordset or NULL. If NULL, all field data members in the recordset are flagged. (C++ NULL is not the same as Null in database terminology, which means “having no value.”)

bDirty

TRUE if the field data member is to be flagged as “dirty” (changed). Otherwise FALSE if the field data member is to be flagged as “clean” (unchanged).

Remarks

Call this member function to flag a field data member of the recordset as changed or as unchanged. Marking fields as unchanged ensures the field is not updated and results in less SQL traffic.

Note This member function is not applicable on recordsets that are using bulk row fetching. If you have implemented bulk row fetching, then SetFieldDirty will result in a failed assertion. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

The framework marks changed field data members to ensure they will be written to the record on the data source by the record field exchange (RFX) mechanism. Changing the value of a field generally sets the field dirty automatically, so you will seldom need to call SetFieldDirty yourself, but you might sometimes want to ensure that columns will be explicitly updated or inserted regardless of what value is in the field data member.

Important Call this member function only after you have called Edit or AddNew.

Using NULL for the first argument of the function will apply the function only to outputColumns, not params. For instance, the call

SetFieldNull( NULL );

will set only outputColumns to NULL. Params will be unaffected.

To work on params, you must supply the actual address of the individual param you want to work on, such as:

SetFieldNull( &m_strParam );

This means you cannot set all params NULL, as you can with outputColumns.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::IsFieldDirty, CRecordset::SetFieldNull, CRecordset::Edit, CRecordset::Update


CRecordset::SetFieldNull

void SetFieldNull( void* pv, BOOL bNull = TRUE );

Parameters

pv

Contains the address of a field data member in the recordset or NULL. If NULL, all field data members in the recordset are flagged. (C++ NULL is not the same as Null in database terminology, which means “having no value.”)

bNull

Nonzero if the field data member is to be flagged as having no value (Null). Otherwise 0 if the field data member is to be flagged as non-Null.

Remarks

Call this member function to flag a field data member of the recordset as Null (specifically having no value) or as non-Null. When you add a new record to a recordset, all field data members are initially set to a Null value and flagged as “dirty” (changed). When you retrieve a record from a data source, its columns either already have values or are Null.

Note Do not call this member function on recordsets that are using bulk row fetching. If you have implemented bulk row fetching, calling SetFieldNull results in a failed assertion. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

If you specifically wish to designate a field of the current record as not having a value, call SetFieldNull with bNull set to TRUE to flag it as Null. If a field was previously marked Null and you now want to give it a value, simply set its new value. You do not have to remove the Null flag with SetFieldNull. To determine whether the field is allowed to be Null, call IsFieldNullable.

Important Call this member function only after you have called Edit or AddNew.

Using NULL for the first argument of the function will apply the function only to outputColumns, not params. For instance, the call

SetFieldNull( NULL );

will set only outputColumns to NULL. Params will be unaffected.

To work on params, you must supply the actual address of the individual param you want to work on, such as:

SetFieldNull( &m_strParam );

This means you cannot set all params NULL, as you can with outputColumns.

Note When setting parameters to Null, a call to SetFieldNull before the recordset is opened results in an assertion. In this case, call SetParamNull.

SetFieldNull is implemented through DoFieldExchange.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::IsFieldNull, CRecordset::SetFieldDirty, CRecordset::Edit, CRecordset::Update, CRecordset::IsFieldNullable


CRecordset::SetLockingMode

void SetLockingMode( UINT nMode );

Parameters

nMode

Contains one of the following values from the enum LockMode:

  • optimistic Optimistic locking locks the record being updated only during the call to Update.

  • pessimistic Pessimistic locking locks the record as soon as Edit is called and keeps it locked until the Update call completes or you move to a new record.

Remarks

Call this member function if you need to specify which of two record-locking strategies the recordset is using for updates. By default, the locking mode of a recordset is optimistic. You can change that to a more cautious pessimistic locking strategy. Call SetLockingMode after you construct and open the recordset object but before you call Edit.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Edit, CRecordset::Update


CRecordset::SetParamNull

void SetParamNull( int nIndex, BOOL bNull = TRUE );

Parameters

nIndex

The zero-based index of the parameter.

bNull

If TRUE (the default value), the parameter is flagged as Null. Otherwise, the parameter is flagged as non-Null.

Remarks

Call this member function to flag a parameter as Null (specifically having no value) or as non-Null. Unlike SetFieldNull, you can call SetParamNull before you have opened the recordset.

SetParamNull is typically used with predefined queries (stored procedures).

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::FlushResultSet


CRecordset::SetRowsetCursorPosition

void SetRowsetCursorPosition( WORD wRow, WORD wLockType = SQL_LOCK_NO_CHANGE );

Parameters

wRow

The one-based position of a row in the current rowset. This value can range from 1 to the size of the rowset.

wLockType

Value indicating how to lock the row after it has been refreshed. For details, see Remarks.

Remarks

Call this member function to move the cursor to a row within the current rowset. When implementing bulk row fetching, records are retrieved by rowsets, where the first record in the fetched rowset is the current record. In order to make another record within the rowset the current record, call SetRowsetCursorPosition. For example, you can combine SetRowsetCursorPosition with the GetFieldValue member function to dynamically retrieve the data from any record of your recordset.

To use SetRowsetCursorPosition, you must have implemented bulk row fetching by specifying the CRecordset::useMultiRowFetch option of the dwOptions parameter in the Open member function.

SetRowsetCursorPosition calls the ODBC API function SQLSetPos. The wLockType parameter specifies the lock state of the row after SQLSetPos has executed. The following table describes the possible values for wLockType.

wLockType | Description
SQL_LOCK_NO_CHANGE (the default value) | The driver or data source ensures that the row is in the same locked or unlocked state as it was before SetRowsetCursorPosition was called.
SQL_LOCK_EXCLUSIVE | The driver or data source locks the row exclusively. Not all data sources support this type of lock.
SQL_LOCK_UNLOCK | The driver or data source unlocks the row. Not all data sources support this type of lock.

For more information about SQLSetPos, see the ODBC SDK Programmer's Reference. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::RefreshRowset, CRecordset::SetRowsetSize


CRecordset::SetRowsetSize

virtual void SetRowsetSize( DWORD dwNewRowsetSize );

Parameters

dwNewRowsetSize

The number of rows to retrieve during a given fetch.

Remarks

This virtual member function specifies how many rows you wish to retrieve during a single fetch when using bulk row fetching. To implement bulk row fetching, you must set the CRecordset::useMultiRowFetch option in the dwOptions parameter of the Open member function.

Note Calling SetRowsetSize without implementing bulk row fetching will result in a failed assertion.

Call SetRowsetSize before calling Open to initially set the rowset size for the recordset. The default rowset size when implementing bulk row fetching is 25.

Note Use caution when calling SetRowsetSize. If you are manually allocating storage for the data (as specified by the CRecordset::userAllocMultiRowBuffers option of the dwOptions parameter in Open), you should check whether you need to reallocate these storage buffers after you call SetRowsetSize, but before you perform any cursor navigation operation.

To obtain the current setting for the rowset size, call GetRowsetSize.

For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Open, CRecordset::GetRowsetSize, CRecordset::CheckRowsetError, CRecordset::DoBulkFieldExchange


CRecordset::Update

virtual BOOL Update( );
throw( CDBException );

Return Value

Nonzero if one record was successfully updated; otherwise 0 if no columns have changed. If no records were updated, or if more than one record was updated, an exception is thrown. An exception is also thrown for any other failure on the data source.

Remarks

Call this member function after a call to the AddNew or Edit member function. This call is required to complete the AddNew or Edit operation.

Note If you have implemented bulk row fetching, you cannot call Update. This will result in a failed assertion. Although class CRecordset does not provide a mechanism for updating bulk rows of data, you can write your own functions by using the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Both AddNew and Edit prepare an edit buffer in which the added or edited data is placed for saving to the data source. Update saves the data. Only those fields marked or detected as changed are updated.

If the data source supports transactions, you can make the Update call (and its corresponding AddNew or Edit call) part of a transaction. For more information about transactions, see the article Transaction (ODBC) in Visual C++ Programmer’s Guide.

Caution If you call Update without first calling either AddNew or Edit, Update throws a CDBException. If you call AddNew or Edit, you must call Update before you call a Move operation or before you close either the recordset or the data source connection. Otherwise, your changes are lost without notification.

For details on handling Update failures, see the article Recordset: How Recordsets Update Records (ODBC) in Visual C++ Programmer’s Guide.

Example

See the article Transaction: Performing a Transaction in a Recordset (ODBC) in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::Edit, CRecordset::AddNew, CRecordset::SetFieldDirty, CDBException


CRecordset::m_hstmt

Remarks

Contains a handle to the ODBC statement data structure, of type HSTMT, associated with the recordset. Each query to an ODBC data source is associated with an HSTMT.

Caution Do not use m_hstmt before Open has been called.

Normally you do not need to access the HSTMT directly, but you might need it for direct execution of SQL statements. The ExecuteSQL member function of class CDatabase provides an example of using m_hstmt.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CDatabase::ExecuteSQL


CRecordset::m_nFields

Remarks

Contains the number of field data members in the recordset class — the number of columns selected by the recordset from the data source. The constructor for the recordset class must initialize m_nFields with the correct number. If you have not implemented bulk row fetching, ClassWizard writes this initialization for you when you use it to declare your recordset class. You can also write it manually.

The framework uses this number to manage interaction between the field data members and the corresponding columns of the current record on the data source.

Important This number must correspond to the number of “output columns” registered in DoFieldExchange or DoBulkFieldExchange after a call to SetFieldType with the parameter CFieldExchange::outputColumn.

You can bind columns dynamically, as explained in the article “Recordset: Dynamically Binding Data Columns.” If you do so, you must increase the count in m_nFields to reflect the number of RFX or Bulk RFX function calls in your DoFieldExchange or DoBulkFieldExchange member function for the dynamically bound columns.

For more information, see the articles Recordset: Dynamically Binding Data Columns (ODBC) and Recordset: Fetching Records in Bulk (ODBC) in Visual C++ Programmer’s Guide.

Example

See the article Record Field Exchange: Using RFX in Visual C++ Programmer's Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::DoFieldExchange, CRecordset::DoBulkFieldExchange, CRecordset::m_nParams, CFieldExchange::SetFieldType


CRecordset::m_nParams

Remarks

Contains the number of parameter data members in the recordset class — the number of parameters passed with the recordset’s query. If your recordset class has any parameter data members, the constructor for the class must initialize m_nParams with the correct number. The value of m_nParams defaults to 0. If you add parameter data members — which you must do manually — you must also manually add an initialization in the class constructor to reflect the number of parameters (which must be at least as large as the number of ‘?’ placeholders in your m_strFilter or m_strSort string).

The framework uses this number when it parameterizes the recordset’s query.

Important This number must correspond to the number of “params” registered in DoFieldExchange or DoBulkFieldExchange after a call to SetFieldType with a parameter value of CFieldExchange::inputParam, CFieldExchange::param, CFieldExchange::outputParam, or CFieldExchange::inoutParam.

Example

See the articles Recordset: Parameterizing a Recordset (ODBC) and Record Field Exchange: Using RFX in Visual C++ Programmer’s Guide.

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::DoFieldExchange, CRecordset::DoBulkFieldExchange, CRecordset::m_nFields, CFieldExchange::SetFieldType


CRecordset::m_pDatabase

Remarks

Contains a pointer to the CDatabase object through which the recordset is connected to a data source. This variable is set in two ways. Typically, you pass a pointer to an already connected CDatabase object when you construct the recordset object. If you pass NULL instead, CRecordset creates a CDatabase object for you and connects it. In either case, CRecordset stores the pointer in this variable.

Normally you will not directly need to use the pointer stored in m_pDatabase. If you write your own extensions to CRecordset, however, you might need to use the pointer. For example, you might need the pointer if you throw your own CDBExceptions. Or you might need it if you need to do something using the same CDatabase object, such as running transactions, setting timeouts, or calling the ExecuteSQL member function of class CDatabase to execute SQL statements directly.


CRecordset::m_strFilter

Remarks

After you construct the recordset object, but before you call its Open member function, use this data member to store a CString containing an SQL WHERE clause. The recordset uses this string to constrain — or filter — the records it selects during the Open or Requery call. This is useful for selecting a subset of records, such as “all salespersons based in California” (“state = CA”). The ODBC SQL syntax for a WHERE clause is

WHERE search-condition

Note that you do not include the WHERE keyword in your string. The framework supplies it.

You can also parameterize your filter string by placing ‘?’ placeholders in it, declaring a parameter data member in your class for each placeholder, and passing parameters to the recordset at run time. This lets you construct the filter at run time. For more information, see the article Recordset: Parameterizing a Recordset (ODBC) in Visual C++ Programmer’s Guide.

For more information about SQL WHERE clauses, see the article SQL. For more information about selecting and filtering records, see the article Recordset: Filtering Records (ODBC). Both articles are in Visual C++ Programmer’s Guide.

Example

// Example for CRecordset::m_strFilter

CCustSet rsCustSet( NULL );

// Set the filter
rsCustSet.m_strFilter = “state = 'CA'”;

// Run the filtered query
rsCustSet.Open( CRecordset::snapshot, "Customers" );

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::m_strSort, CRecordset::Requery


CRecordset::m_strSort

Remarks

After you construct the recordset object, but before you call its Open member function, use this data member to store a CString containing an SQL ORDER BY clause. The recordset uses this string to sort the records it selects during the Open or Requery call. You can use this feature to sort a recordset on one or more columns. The ODBC SQL syntax for an ORDER BY clause is

ORDER BY sort-specification [, sort-specification]...

where a sort-specification is an integer or a column name. You can also specify ascending or descending order (the order is ascending by default) by appending “ASC” or “DESC” to the column list in the sort string. The selected records are sorted first by the first column listed, then by the second, and so on. For example, you might order a “Customers” recordset by last name, then first name. The number of columns you can list depends on the data source. For more information, see the ODBC SDK Programmer’s Reference.

Note that you do not include the ORDER BY keyword in your string. The framework supplies it.

For more information about SQL clauses, see the article SQL. For more information about sorting records, see the article Recordset: Sorting Records (ODBC). Both articles are in Visual C++ Programmer’s Guide.

Example

// Example for CRecordset::m_strSort

CCustSet rsCustSet( NULL );

// Set the sort string
rsCustSet.m_strSort = "District, Last_Name";

// Run the sorted query
rsCustSet.Open( CRecordset::snapshot, “Customers” );

CRecordset Overview | Class Members | Hierarchy Chart

See Also CRecordset::m_strFilter, CRecordset::Requery


CRecordView

A CRecordView object is a view that displays database records in controls. The view is a form view directly connected to a CRecordset object. The view is created from a dialog template resource and displays the fields of the CRecordset object in the dialog template’s controls. The CRecordView object uses dialog data exchange (DDX) and record field exchange (RFX) to automate the movement of data between the controls on the form and the fields of the recordset. CRecordView also supplies a default implementation for moving to the first, next, previous, or last record and an interface for updating the record currently on view.

Note If you are working with the Data Access Objects (DAO) classes rather than the Open Database Connectivity (ODBC) classes, use class CDaoRecordView instead. For more information, see the articles Database Topics (General) and DAO and MFC in Visual C++ Programmer’s Guide.

The most common way to create your record view is with AppWizard. AppWizard creates both the record view class and its associated recordset class as part of your skeleton starter application. If you don’t create the record view class with AppWizard, you can create it later with ClassWizard. If you simply need a single form, the AppWizard approach is easier. ClassWizard lets you decide to use a record view later in the development process. Using ClassWizard to create a record view and a recordset separately and then connect them is the most flexible approach because it gives you more control in naming the recordset class and its .H/.CPP files. This approach also lets you have multiple record views on the same recordset class.

To make it easy for end-users to move from record to record in the record view, AppWizard creates menu (and optionally toolbar) resources for moving to the first, next, previous, or last record. If you create a record view class with ClassWizard, you need to create these resources yourself with the menu and bitmap editors. For more information about these resources, see Overview: Creating a Program That Supports a Database and ClassWizard: Creating a Database Form.

For information about the default implementation for moving from record to record, see IsOnFirstRecord and IsOnLastRecord and the article Record Views: Using a Record View.

CRecordView keeps track of the user’s position in the recordset so that the record view can update the user interface. When the user moves to either end of the recordset, the record view disables user interface objects — such as menu items or toolbar buttons — for moving further in the same direction.

For more information about declaring and using your record view and recordset classes, see "Designing and Creating a Record View" in the article Record Views. For more information about how record views work and how to use them, see the article Record Views: Using a Record View. All the articles mentioned above are in Visual C++ Programmer’s Guide.

#include <afxdb.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CATALOG

See Also CRecordset, CFormView


CRecordView Class Members

Construction

CRecordView Constructs a CRecordView object.

Attributes

OnGetRecordset | Returns a pointer to an object of a class derived from CRecordset. ClassWizard overrides this function for you and creates the recordset if necessary.
IsOnFirstRecord | Returns nonzero if the current record is the first record in the associated recordset.
IsOnLastRecord | Returns nonzero if the current record is the last record in the associated recordset.

Operations

OnMove If the current record has changed, updates it on the data source, then moves to the specified record (next, previous, first, or last).


CRecordView::CRecordView

CRecordView( LPCSTR lpszTemplateName );

CRecordView( UINT nIDTemplate );

Parameters

lpszTemplateName

Contains a null-terminated string that is the name of a dialog template resource.

nIDTemplate

Contains the ID number of a dialog template resource.

Remarks

When you create an object of a type derived from CRecordView, call either form of the constructor to initialize the view object and identify the dialog resource on which the view is based. You can either identify the resource by name (pass a string as the argument to the constructor) or by its ID (pass an unsigned integer as the argument). Using a resource ID is recommended.

Note Your derived class must supply its own constructor. In the constructor of your derived class, call the constructor CRecordView::CRecordView with the resource name or ID as an argument, as shown in the example below.

CRecordView::OnInitialUpdate calls UpdateData, which calls DoDataExchange. This initial call to DoDataExchange connects CRecordView controls (indirectly) to CRecordset field data members created by ClassWizard. These data members cannot be used until after you call the base class CFormView::OnInitialUpdate member function.

Note If you use ClassWizard, the wizard defines an enum value CRecordView::IDD and specifies it in the member initialization list for the constructor where you see IDD_MYFORM in the example. The example shows how you can specify the dialog template resource ID if you write the code yourself without the wizard.

Example

CMyRecordView::CMyRecordView()
   : CRecordView( IDD_MYFORM )
{
   //{{AFX_DATA_INIT( CMyRecordView )
      // NOTE: the ClassWizard will add member initialization here
   //}}AFX_DATA_INIT
   // Other construction code, such as data initialization
}

CRecordView Overview | Class Members | Hierarchy Chart

See Also CRecordset::DoFieldExchange, CView::OnInitialUpdate, CWnd::UpdateData


CRecordView::IsOnFirstRecord

BOOL IsOnFirstRecord( );

Return Value

Nonzero if the current record is the first record in the recordset; otherwise 0.

Remarks

Call this member function to determine whether the current record is the first record in the recordset object associated with this record view. This function is useful for writing your own implementations of default command update handlers written by ClassWizard.

If the user moves to the first record, the framework disables any user interface objects you have for moving to the first or the previous record.

CRecordView Overview | Class Members | Hierarchy Chart

See Also CRecordView::OnMove, CRecordView::IsOnLastRecord, CRecordset::IsBOF, CRecordset::GetRecordCount


CRecordView::IsOnLastRecord

BOOL IsOnLastRecord( );

Return Value

Nonzero if the current record is the last record in the recordset; otherwise 0.

Remarks

Call this member function to determine whether the current record is the last record in the recordset object associated with this record view. This function is useful for writing your own implementations of the default command update handlers that ClassWizard writes to support a user interface for moving from record to record.

Caution The result of this function is reliable except that the view cannot detect the end of the recordset until the user has moved past it. The user must move beyond the last record before the record view can tell that it must disable any user interface objects for moving to the next or last record. If the user moves past the last record and then moves back to the last record (or before it), the record view can track the user’s position in the recordset and disable user interface objects correctly. IsOnLastRecord is also unreliable after a call to the implementation function OnRecordLast, which handles the ID_RECORD_LAST command, or CRecordset::MoveLast.

CRecordView Overview | Class Members | Hierarchy Chart

See Also CRecordView::OnMove, CRecordView::IsOnFirstRecord, CRecordset::IsEOF, CRecordset::GetRecordCount


CRecordView::OnGetRecordset

virtual CRecordset* OnGetRecordset( ) = 0;

Return Value

A pointer to a CRecordset-derived object if the object was successfully created; otherwise a NULL pointer.

Remarks

Returns a pointer to the CRecordset-derived object associated with the record view. You must override this member function to construct or obtain a recordset object and return a pointer to it. If you declare your record view class with ClassWizard, the wizard writes a default override for you. ClassWizard’s default implementation returns the recordset pointer stored in the record view if one exists. If not, it constructs a recordset object of the type you specified with ClassWizard and calls its Open member function to open the table or run the query, and then returns a pointer to the object.

For more information and examples, see the article Record Views: Using a Record View in Visual C++ Programmer’s Guide.

CRecordView Overview | Class Members | Hierarchy Chart

See Also CRecordset, CRecordset::Open


CRecordView::OnMove

virtual BOOL OnMove( UINT nIDMoveCommand );
throw( CDBException );

Return Value

Nonzero if the move was successful; otherwise 0 if the move request was denied.

Parameters

nIDMoveCommand

One of the following standard command ID values:

  • ID_RECORD_FIRST Move to the first record in the recordset.

  • ID_RECORD_LAST Move to the last record in the recordset.

  • ID_RECORD_NEXT Move to the next record in the recordset.

  • ID_RECORD_PREV Move to the previous record in the recordset.

Remarks

Call this member function to move to a different record in the recordset and display its fields in the controls of the record view. The default implementation calls the appropriate Move member function of the CRecordset object associated with the record view.

By default, OnMove updates the current record on the data source if the user has changed it in the record view.

AppWizard creates a menu resource with First Record, Last Record, Next Record, and Previous Record menu items. If you select the Dockable Toolbar option, AppWizard also creates a toolbar with buttons corresponding to these commands.

If you move past the last record in the recordset, the record view continues to display the last record. If you move backward past the first record, the record view continues to display the first record.

Caution Calling OnMove throws an exception if the recordset has no records. Call the appropriate user interface update handler function — OnUpdateRecordFirst, OnUpdateRecordLast, OnUpdateRecordNext, or OnUpdateRecordPrev — before the corresponding move operation to determine whether the recordset has any records. For information about the update handlers, see Overview: Creating a Program That Supports a Database in Visual C++ Programmer’s Guide.

CRecordView Overview | Class Members | Hierarchy Chart

See Also CRecordset::Move


CRect

The CRect class is similar to a Windows RECT structure. CRect also includes member functions to manipulate CRect objects and Windows RECT structures.

A CRect object can be passed as a function parameter wherever a RECT structure, LPCRECT, or LPRECT can be passed.

Note This class is derived from the tagRECT structure. (The name tagRECT is a less-commonly-used name for the RECT structure.) This means that the data members (left, top, right, and bottom) of the RECT structure are accessible data members of CRect.

A CRect contains member variables that define the top-left and bottom-right points of a rectangle.

When specifying a CRect, you must be careful to construct it so that it is normalized — in other words, such that the value of the left coordinate is less than the right and the top is less than the bottom. For example, a top left of (10,10) and bottom right of (20,20) defines a normalized rectangle but a top left of (20,20) and bottom right of (10,10) defines a non-normalized rectangle. If the rectangle is not normalized, many CRect member functions may return incorrect results. (See CRect::NormalizeRect for a list of these functions.) Before you call a function that requires normalized rectangles, you can normalize non-normalized rectangles by calling the NormalizeRect function.

Use caution when manipulating a CRect with the CDC::DPtoLP and CDC::LPtoDP member functions. If the mapping mode of a display context is such that the y-extent is negative, as in MM_LOENGLISH, then CDC::DPtoLP will transform the CRect so that its top is greater than the bottom. Functions such as Height and Size will then return negative values for the height of the transformed CRect, and the rectangle will be non-normalized.

When using overloaded CRect operators, the first operand must be a CRect; the second can be either a RECT structure or a CRect object.

#include <afxwin.h>

Class Members | Hierarchy Chart

Sample MFC Sample HELLO

See Also CPoint, CSize, RECT


CRect Class Members

Construction/Destruction
Operations
Operators

Construction

CRect Constructs a CRect object.

Operations

Width | Calculates the width of CRect.
Height | Calculates the height of CRect.
Size | Calculates the size of CRect.
TopLeft | Returns the top-left point of CRect.
BottomRight | Returns the bottom-right point of CRect.
CenterPoint | Returns the centerpoint of CRect.
IsRectEmpty | Determines whether CRect is empty. CRect is empty if the width and/or height are 0.
IsRectNull | Determines whether the top, bottom, left, and right member variables are all equal to 0.
PtInRect | Determines whether the specified point lies within CRect.
SetRect | Sets the dimensions of CRect.
SetRectEmpty | Sets CRect to an empty rectangle (all coordinates equal to 0).
CopyRect | Copies the dimensions of a source rectangle to CRect.
EqualRect | Determines whether CRect is equal to the given rectangle.
InflateRect | Increases the width and height of CRect.
DeflateRect | Decreases the width and height of CRect.
NormalizeRect | Standardizes the height and width of CRect.
OffsetRect | Moves CRect by the specified offsets.
SubtractRect | Subtracts one rectangle from another.
IntersectRect | Sets CRect equal to the intersection of two rectangles.
UnionRect | Sets CRect equal to the union of two rectangles.

Operators

operator LPCRECT | Converts a CRect to an LPCRECT.
operator LPRECT | Converts a CRect to an LPRECT.
operator = | Copies the dimensions of a rectangle to CRect.
operator == | Determines whether CRect is equal to a rectangle.
operator != | Determines whether CRect is not equal to a rectangle.
operator += | Adds the specified offsets to CRect or inflates CRect.
operator –= | Subtracts the specified offsets from CRect or deflates CRect.
operator &= | Sets CRect equal to the intersection of CRect and a rectangle.
operator |= | Sets CRect equal to the union of CRect and a rectangle.
operator + | Adds the given offsets to CRect or inflates CRect and returns the resulting CRect.
operator – | Subtracts the given offsets from CRect or deflates CRect and returns the resulting CRect.
operator & | Creates the intersection of CRect and a rectangle and returns the resulting CRect.
operator | | Creates the union of CRect and a rectangle and returns the resulting CRect.


CRect::BottomRight

CPoint& BottomRight( );

const CPoint& BottomRight( ) const;

Return Value

The coordinates of the bottom-right corner of the rectangle.

Remarks

The coordinates are returned as a reference to a CPoint object that is contained in CRect.

You can use this function to either get or set the bottom-right corner of the rectangle. Set the corner by using this function on the left side of the assignment operator.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::TopLeft, CPoint, CRect::CenterPoint


CRect::CenterPoint

CPoint CenterPoint( ) const;

Return Value

A CPoint object that is the centerpoint of CRect.

Remarks

Calculates the centerpoint of CRect by adding the left and right values and dividing by two, and adding the top and bottom values and dividing by two.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::Width, CRect::Height, CRect::Size, CRect::TopLeft, CRect::BottomRight, CRect::IsRectNull, CPoint


CRect::CopyRect

void CopyRect( LPCRECT lpSrcRect );

Parameters

lpSrcRect

Points to the RECT structure or CRect object that is to be copied.

Remarks

Copies the lpSrcRect rectangle into Crect.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::CRect, CRect::operator =, CRect::SetRect, CRect::SetRectEmpty


CRect::CRect

CRect( );

CRect( int l, int t, int r, int b );

CRect( const RECT& srcRect );

CRect( LPCRECT lpSrcRect );

CRect( POINT point, SIZE size );

CRect( POINT topLeft, POINT bottomRight );

Parameters

l

Specifies the left position of CRect.

t

Specifies the top of CRect.

r

Specifies the right position of CRect.

b

Specifies the bottom of CRect.

srcRect

Refers to the RECT structure with the coordinates for CRect.

lpSrcRect

Points to the RECT structure with the coordinates for CRect.

point

Specifies the origin point for the rectangle to be constructed. Corresponds to the top-left corner.

size

Specifies the displacement from the top-left corner to the bottom-right corner of the rectangle to be constructed.

topLeft

Specifies the top-left position of CRect.

bottomRight

Specifies the bottom-right position of CRect.

Remarks

Constructs a CRect object. If no arguments are given, left, top, right, and bottom members are not initialized.

The CRect( const RECT& ) and CRect( LPCRECT ) constructors perform a CopyRect. The other constructors initialize the member variables of the object directly.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::SetRect, CRect::CopyRect, CRect::operator =, CRect::SetRectEmpty


CRect::DeflateRect

void DeflateRect( int x, int y );

void DeflateRect( SIZE size );

void DeflateRect( LPCRECT lpRect );

void DeflateRect( int l, int t, int r, int b );

Parameters

x

Specifies the number of units to deflate the left and right sides of CRect.

y

Specifies the number of units to deflate the top and bottom of CRect.

size

A SIZE or CSize that specifies the number of units to deflate CRect. The cx value specifies the number of units to deflate the left and right sides and the cy value specifies the number of units to deflate the top and bottom.

lpRect

Points to a RECT structure or CRect that specifies the number of units to deflate each side.

l

Specifies the number of units to deflate the left side of CRect.

t

Specifies the number of units to deflate the top of CRect.

r

Specifies the number of units to deflate the right side of CRect.

b

Specifies the number of units to deflate the bottom of CRect.

Remarks

DeflateRect deflates CRect by moving its sides toward its center. To do this, DeflateRect adds units to the left and top and subtracts units from the right and bottom. The parameters of DeflateRect are signed values; positive values deflate CRect and negative values inflate it.

The first two overloads deflate both pairs of opposite sides of CRect so that its total width is decreased by two times x (or cx) and its total height is decreased by two times y (or cy). The other two overloads deflate each side of CRect independently of the others.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::InflateRect, CRect::operator -, CRect::operator -=, ::InflateRect


CRect::EqualRect

BOOL EqualRect( LPCRECT lpRect ) const;

Return Value

Nonzero if the two rectangles have the same top, left, bottom, and right values; otherwise 0.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

Parameters

lpRect

Points to a RECT structure or CRect object that contains the upper-left and lower-right corner coordinates of a rectangle.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator ==, CRect::operator !=, CRect::NormalizeRect, ::EqualRect


CRect::Height

int Height( ) const;

Return Value

The height of CRect.

Remarks

Calculates the height of CRect by subtracting the top value from the bottom value. The resulting value can be negative.

Note The rectangle must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangle before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::Width, CRect::Size, CRect::CenterPoint, CRect::IsRectEmpty, CRect::IsRectNull, CRect::NormalizeRect


CRect::InflateRect

void InflateRect( int x, int y );

void InflateRect( SIZE size );

void InflateRect( LPCRECT lpRect );

void InflateRect( int l, int t, int r, int b );

Parameters

x

Specifies the number of units to inflate the left and right sides of CRect.

y

Specifies the number of units to inflate the top and bottom of CRect.

size

A SIZE or CSize that specifies the number of units to inflate CRect. The cx value specifies the number of units to inflate the left and right sides and the cy value specifies the number of units to inflate the top and bottom.

lpRect

Points to a RECT structure or CRect that specifies the number of units to inflate each side.

l

Specifies the number of units to inflate the left side of CRect.

t

Specifies the number of units to inflate the top of CRect.

r

Specifies the number of units to inflate the right side of CRect.

b

Specifies the number of units to inflate the bottom of CRect.

Remarks

InflateRect inflates CRect by moving its sides away from its center. To do this, InflateRect subtracts units from the left and top and adds units to the right and bottom. The parameters of InflateRect are signed values; positive values inflate CRect and negative values deflate it.

The first two overloads inflate both pairs of opposite sides of CRect so that its total width is increased by two times x (or cx) and its total height is increased by two times y (or cy). The other two overloads inflate each side of CRect independently of the others.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::DeflateRect, CRect::operator +, CRect::operator +=, ::InflateRect


CRect::IntersectRect

BOOL IntersectRect( LPCRECT lpRect1, LPCRECT lpRect2 );

Return Value

Nonzero if the intersection is not empty; 0 if the intersection is empty.

Parameters

lpRect1

Points to a RECT structure or CRect object that contains a source rectangle.

lpRect2

Points to a RECT structure or CRect object that contains a source rectangle.

Remarks

Makes a CRect equal to the intersection of two existing rectangles. The intersection is the largest rectangle contained in both existing rectangles.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator &=, CRect::operator &, CRect::UnionRect, CRect::SubtractRect, CRect::NormalizeRect, ::IntersectRect


CRect::IsRectEmpty

BOOL IsRectEmpty( ) const;

Return Value

Nonzero if CRect is empty; 0 if CRect is not empty.

Remarks

Determines whether CRect is empty. A rectangle is empty if the width and/or height are 0 or negative. Differs from IsRectNull, which determines whether all coordinates of the rectangle are zero.

Note The rectangle must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangle before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::IsRectNull, CRect::SetRectEmpty, CRect::NormalizeRect, ::IsRectEmpty


CRect::IsRectNull

BOOL IsRectNull( ) const;

Return Value

Nonzero if CRect’s top, left, bottom, and right values are all equal to 0; otherwise 0.

Remarks

Determines whether the top, left, bottom, and right values of CRect are all equal to 0. Differs from IsRectEmpty, which determines whether the rectangle is empty.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::IsRectEmpty, CRect::SetRectEmpty


CRect::NormalizeRect

void NormalizeRect( );

Remarks

Normalizes CRect so that both the height and width are positive. The rectangle is normalized for fourth-quadrant positioning, which Windows typically uses for coordinates. NormalizeRect compares the top and bottom values, and swaps them if the top is greater than the bottom. Similarly, it swaps the left and right values if the left is greater than the right. This function is useful when dealing with different mapping modes and inverted rectangles.

Note The following CRect member functions require normalized rectangles in order to work properly: Height, Width, Size, IsRectEmpty, PtInRect, EqualRect, UnionRect, IntersectRect, SubtractRect, operator ==, operator !=, operator |, operator |=, operator &, and operator &=.


CRect::OffsetRect

void OffsetRect( int x, int y );

void OffsetRect( POINT point );

void OffsetRect( SIZE size );

Parameters

x

Specifies the amount to move left or right. It must be negative to move left.

y

Specifies the amount to move up or down. It must be negative to move up.

point

Contains a POINT structure or CPoint object specifying both dimensions by which to move.

size

Contains a SIZE structure or CSize object specifying both dimensions by which to move.

Remarks

Moves CRect by the specified offsets. Moves CRect x units along the x-axis and y units along the y-axis. The x and y parameters are signed values, so CRect can be moved left or right and up or down.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator +, CRect::operator +=, CRect::operator -, CRect::operator -=


CRect::PtInRect

BOOL PtInRect( POINT point ) const;

Return Value

Nonzero if the point lies within CRect; otherwise 0.

Parameters

point

Contains a POINT structure or CPoint object.

Remarks

Determines whether the specified point lies within CRect. A point is within CRect if it lies on the left or top side or is within all four sides. A point on the right or bottom side is outside CRect.

Note The rectangle must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangle before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::NormalizeRect, ::PtInRect


CRect::SetRect

void SetRect( int x1, int y1, int x2, int y2 );

Parameters

x1

Specifies the x-coordinate of the upper-left corner.

y1

Specifies the y-coordinate of the upper-left corner.

x2

Specifies the x-coordinate of the lower-right corner.

y2

Specifies the y-coordinate of the lower-right corner.

Remarks

Sets the dimensions of CRect to the specified coordinates.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::CRect, CRect::operator =, CRect::CopyRect, CRect::SetRectEmpty, ::SetRect


CRect::SetRectEmpty

void SetRectEmpty( );

Remarks

Makes CRect a null rectangle by setting all coordinates to zero.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::CRect, CRect::SetRect, CRect::CopyRect, CRect::operator =, CRect::IsRectEmpty, CRect::IsRectNull, ::SetRectEmpty


CRect::Size

CSize Size( ) const;

Return Value

A CSize object that contains the size of CRect.

Remarks

The cx and cy members of the return value contain the height and width of CRect. Either the height or width can be negative.

Note The rectangle must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangle before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::Height, CRect::Width, CRect::IsRectEmpty, CRect::IsRectNull, CRect::NormalizeRect


CRect::SubtractRect

BOOL SubtractRect( LPCRECT lpRectSrc1, LPCRECT lpRectSrc2 );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpRectSrc1

Points to the RECT structure or CRect object from which a rectangle is to be subtracted.

lpRectSrc2

Points to the RECT structure or CRect object that is to be subtracted from the rectangle pointed to by the lpRectSrc1 parameter.

Remarks

Makes the dimensions of the lpRectSrc1 rectangle equal to the subtraction of lpRectSrc2 from lpRectSrc1. The subtraction is the smallest rectangle that contains all of the points in lpRectScr1 that are not in the intersection of lpRectScr1 and lpRectScr2.

The rectangle specified by lpRectSrc1 will be unchanged if the rectangle specified by lpRectSrc2 doesn't completely overlap the rectangle specified by lpRectSrc1 in at least one of the x- or y-directions.

For example, if lpRectSrc1 were (10,10, 100,100) and lpRectSrc2 were (50,50, 150,150), the rectangle pointed to by lpRectSrc1 would be unchanged when the function returned. If lpRectSrc1 were (10,10, 100,100) and lpRectSrc2 were (50,10, 150,150), however, the rectangle pointed to by lpRectSrc1 would contain the coordinates (10,10, 50,100) when the function returned.

SubtractRect is not the same as operator - nor operator -=. Neither of these operators ever calls SubtractRect.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator -, CRect::operator -=, CRect::IntersectRect, CRect::UnionRect, CRect::NormalizeRect, ::SubtractRect


CRect::TopLeft

CPoint& TopLeft( );

const CPoint& TopLeft( ) const;

Return Value

The coordinates of the top-left corner of the rectangle.

Remarks

The coordinates are returned as a reference to a CPoint object that is contained in CRect.

You can use this function to either get or set the top-left corner of the rectangle. Set the corner by using this function on the left side of the assignment operator.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::BottomRight, CPoint, CRect::CenterPoint


CRect::UnionRect

BOOL UnionRect( LPCRECT lpRect1, LPCRECT lpRect2 );

Return Value

Nonzero if the union is not empty; 0 if the union is empty.

Parameters

lpRect1

Points to a RECT or CRect that contains a source rectangle.

lpRect2

Points to a RECT or CRect that contains a source rectangle.

Remarks

Makes the dimensions of CRect equal to the union of the two source rectangles. The union is the smallest rectangle that contains both source rectangles.

Windows ignores the dimensions of an empty rectangle; that is, a rectangle that has no height or has no width.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator |=, CRect::operator |, CRect::IntersectRect, CRect::SubtractRect, CRect::NormalizeRect, ::UnionRect


CRect::Width

int Width( ) const;

Return Value

The width of CRect.

Remarks

Calculates the width of CRect by subtracting the left value from the right value. The width can be negative.

Note The rectangle must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangle before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::Height, CRect::Size, CRect::CenterPoint, CRect::IsRectEmpty, CRect::IsRectNull, CRect::NormalizeRect


CRect::operator LPCRECT

operator LPCRECT( ) const;

Remarks

Converts a CRect to an LPCRECT. When you use this function, you don't need the address-of (&) operator. This operator will be automatically used when you pass a CRect object to a function that expects an LPCRECT.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator LPRECT


CRect::operator LPRECT

operator LPRECT( );

Remarks

Converts a CRect to an LPRECT. When you use this function, you don't need the address-of (&) operator. This operator will be automatically used when you pass a CRect object to a function that expects an LPRECT.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator LPCRECT


CRect::operator =

void operator =( const RECT& srcRect );

Parameters

srcRect

Refers to a source rectangle. Can be a RECT or CRect.

Remarks

Assigns srcRect to CRect.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::CRect, CRect::SetRect, CRect::CopyRect, CRect::SetRectEmpty, ::CopyRect


CRect::operator ==

BOOL operator ==( const RECT& rect ) const;

Return Value

Nonzero if equal; otherwise 0.

Parameters

rect

Refers to a source rectangle. Can be a RECT or CRect.

Remarks

Determines whether rect is equal to CRect by comparing the coordinates of their upper-left and lower-right corners.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator !=, CRect::NormalizeRect, ::EqualRect


CRect::operator !=

BOOL operator !=( const RECT& rect ) const;

Return Value

Nonzero if not equal; otherwise 0.

Parameters

rect

Refers to a source rectangle. Can be a RECT or CRect.

Remarks

Determines whether rect is not equal to CRect by comparing the coordinates of their upper-left and lower-right corners.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator ==, CRect::NormalizeRect, ::EqualRect


CRect::operator +=

void operator +=( POINT point );

void operator +=( SIZE size );

void operator +=( LPCRECT lpRect );

Parameters

point

A POINT structure or CPoint object that specifies the number of units to move the rectangle.

size

A SIZE structure or CSize object that specifies the number of units to move the rectangle.

lpRect

Points to a RECT structure or CRect object that contains the number of units to inflate each side of CRect.

Remarks

The first two overloads move CRect by the specified offsets. The parameter’s x and y (or cx and cy) values are added to CRect.

The third overload inflates CRect by the number of units specifed in each member of the parameter.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::OffsetRect, CRect::InflateRect, CRect::operator +, CRect::operator -=


CRect::operator -=

void operator -=( POINT point );

void operator -=( SIZE size );

void operator -=( LPCRECT lpRect );

Parameters

point

A POINT structure or CPoint object that specifies the number of units to move the rectangle.

size

A SIZE structure or CSize object that specifies the number of units to move the rectangle.

lpRect

Points to a RECT structure or CRect object that contains the number of units to deflate each side of CRect.

Remarks

The first two overloads move CRect by the specified offsets. The parameter’s x and y (or cx and cy) values are subtracted from CRect.

The third overload deflates CRect by the number of units specifed in each member of the parameter. Note that this overload functions like DeflateRect.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::OffsetRect, CRect::DeflateRect, CRect::SubtractRect, CRect::operator -, CRect::operator +=


CRect::operator &=

void operator &=( const RECT& rect );

Parameters

rect

Contains a RECT or CRect.

Remarks

Sets CRect equal to the intersection of CRect and rect. The intersection is the largest rectangle that is contained in both rectangles.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator &, CRect::operator |=, CRect::IntersectRect, CRect::NormalizeRect, ::IntersectRect


CRect::operator |=

void operator |=( const RECT& rect );

Parameters

rect

Contains a CRect or RECT.

Remarks

Sets CRect equal to the union of CRect and rect. The union is the smallest rectangle that contains both source rectangles.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator |, CRect::operator &=, CRect::UnionRect, CRect::NormalizeRect, ::UnionRect


CRect::operator +

CRect operator +( POINT point ) const;

CRect operator +( LPCRECT lpRect ) const;

CRect operator +( SIZE size ) const;

Return Value

The CRect resulting from moving or inflating CRect by the number of units specified in the parameter.

Parameters

point

A POINT structure or CPoint object that specifies the number of units to move the return value.

size

A SIZE structure or CSize object that specifies the number of units to move the return value.

lpRect

Points to a RECT structure or CRect object that contains the number of units to inflate each side of the return value.

Remarks

The first two overloads return a CRect object that is equal to CRect displaced by the specified offsets. The parameter’s x and y (or cx and cy) parameters are added to CRect’s position.

The third overload returns a new CRect that is equal to CRect inflated by the number of units specifed in each member of the parameter.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator +=, CRect::operator -, CRect::OffsetRect, CRect::InflateRect


CRect::operator -

CRect operator -( POINT point ) const;

CRect operator -( SIZE size ) const;

CRect operator -( LPCRECT lpRect ) const;

Return Value

The CRect resulting from moving or deflating CRect by the number of units specified in the parameter.

Parameters

point

A POINT structure or CPoint object that specifies the number of units to move the return value.

size

A SIZE structure or CSize object that specifies the number of units to move the return value.

lpRect

Points to a RECT structure or CRect object that contains the number of units to deflate each side of the return value.

Remarks

The first two overloads return a CRect object that is equal to CRect displaced by the specified offsets. The parameter’s x and y (or cx and cy) parameters are subtracted from CRect’s position.

The third overload returns a new CRect that is equal to CRect deflated by the number of units specifed in each member of the parameter. Note that this overload functions like DeflateRect, not SubtractRect.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::operator -=, CRect::operator +, CRect::OffsetRect, CRect::DeflateRect, CRect::SubtractRect


CRect::operator &

CRect operator &( const RECT& rect2 ) const;

Return Value

A CRect that is the intersection of CRect and rect2.

Parameters

rect2

Contains a RECT or CRect.

Remarks

Returns a CRect that is the intersection of CRect and rect2. The intersection is the largest rectangle that is contained in both rectangles.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::IntersectRect, CRect::operator &=, CRect::operator |, CRect::NormalizeRect


CRect::operator |

CRect operator |( const RECT& rect2 ) const;

Return Value

A CRect that is the union of CRect and rect2.

Parameters

rect2

Contains a RECT or CRect.

Remarks

Returns a CRect that is the union of CRect and rect2. The union is the smallest rectangle that contains both rectangles.

Note Both of the rectangles must be normalized or this function may fail. You can call NormalizeRect to normalize the rectangles before calling this function.

CRect Overview | Class Members | Hierarchy Chart

See Also CRect::UnionRect, CRect::operator |=, CRect::operator &, CRect::NormalizeRect


CRectTracker

CRectTracker does not have a base class.

The CRectTracker class allows an item to be displayed, moved, and resized in different fashions. Although the CRectTracker class is designed to allow the user to interact with OLE items by using a graphical interface, its use is not restricted to OLE-enabled applications. It can be used anywhere such a user interface is required.

CRectTracker borders can be solid or dotted lines. The item can be given a hatched border or overlaid with a hatched pattern to indicate different states of the item. You can place eight resize handles on either the outside or the inside border of the item. (For an explanation of the resize handles, see GetHandleMask.) Finally, a CRectTracker allows you to change the orientation of an item during resizing.

To use CRectTracker, construct a CRectTracker object and specify which display states are initialized. You can then use this interface to give the user visual feedback on the current status of the OLE item associated with the CRectTracker object.

For more information on using CRectTracker, see the article Trackers in Visual C++ Programmer’s Guide.

#include <afxext.h>

Class Members | Hierarchy Chart

Samples MFC Sample TRACKER | MFC Sample DRAWCLI

See Also COleResizeBar, CRect, CRectTracker::GetHandleMask


CRectTracker Class Members

Data Members

m_nHandleSize | Determines size of resize handles.
m_rect | Current position (in pixels) of the rectangle.
m_sizeMin | Determines minimum rectangle width and height.
m_nStyle | Current style(s) of the tracker.

Construction

CRectTracker Constructs a CRectTracker object.

Operations

Draw | Renders the rectangle.
GetTrueRect | Returns width and height of rectangle, including resize handles.
HitTest | Returns the current position of the cursor related to the CRectTracker object.
NormalizeHit | Normalizes a hit-test code.
SetCursor | Sets the cursor, depending on its position over the rectangle.
Track | Allows the user to manipulate the rectangle.
TrackRubberBand | Allows the user to “rubber-band” the selection.

Overridables

AdjustRect | Called when the rectangle is resized.
DrawTrackerRect | Called when drawing the border of a CRectTracker object.
OnChangedRect | Called when the rectangle has been resized or moved.
GetHandleMask | Called to get the mask of a CRectTracker item’s resize handles.


CRectTracker::AdjustRect

virtual void AdjustRect( int nHandle, LPRECT lpRect );

Parameters

nHandle

Index of handle used.

lpRect

Pointer to the current size of the rectangle. (The size of a rectangle is given by its height and width.)

Remarks

Called by the framework when the tracking rectangle is resized by using a resize handle. The default behavior of this function allows the rectangle’s orientation to change only when Track and TrackRubberBand are called with inverting allowed.

Override this function to control the adjustment of the tracking rectangle during a dragging operation. One method is to adjust the coordinates specified by lpRect before returning.

Special features that are not directly supported by CRectTracker, such as snap-to-grid or keep-aspect-ratio, can be implemented by overriding this function.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::Track, CRectTracker::TrackRubberBand, CRectTracker::OnChangedRect


CRectTracker::CRectTracker

CRectTracker( );

CRectTracker( LPCRECT lpSrcRect, UINT nStyle );

Parameters

lpSrcRect

The coordinates of the rectangle object.

nStyle

Specifies the style of the CRectTracker object. The following styles are supported:

  • CRectTracker::solidLine Use a solid line for the rectangle border.

  • CRectTracker::dottedLine Use a dotted line for the rectangle border.

  • CRectTracker::hatchedBorder Use a hatched pattern for the rectangle border.

  • CRectTracker::resizeInside Resize handles located inside the rectangle.

  • CRectTracker::resizeOutside Resize handles located outside the rectangle.

  • CRectTracker::hatchInside Hatched pattern covers the entire rectangle.

Remarks

Creates and initializes a CRectTracker object.

The default constructor initializes the CRectTracker object with the values from lpSrcRect and initializes other sizes to system defaults. If the object is created with no parameters, the m_rect and m_nStyle data members are uninitialized.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRect::CRect


CRectTracker::Draw

void Draw( CDC* pDC ) const;

Parameters

pDC

Pointer to the device context on which to draw.

Remarks

Call this function to draw the rectangle’s outer lines and inner region. The style of the tracker determines how the drawing is done. See the constructor for CRectTracker for more information on the styles available.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::DrawTrackerRect, CRectTracker::CRectTracker, CRect::NormalizeRect


CRectTracker::DrawTrackerRect

virtual void DrawTrackerRect( LPCRECT lpRect, CWnd* pWndClipTo, CDC* pDC, CWnd* pWnd );

Parameters

lpRect

Pointer to the RECT that contains the rectangle to draw.

pWndClipTo

Pointer to the window to use in clipping the rectangle.

pDC

Pointer to the device context on which to draw.

pWnd

Pointer to the window on which the drawing will occur.

Remarks

Called by the framework whenever the position of the tracker has changed while inside the Track or TrackRubberBand member function. The default implementation makes a call to CDC::DrawFocusRect, which draws a dotted rectangle.

Override this function to provide different feedback during the tracking operation.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::Track, CRectTracker::TrackRubberBand, CDC::DrawFocusRect


CRectTracker::GetHandleMask

virtual UINT GetHandleMask( ) const;

Return Value

The mask of a CRectTracker item’s resize handles.

Remarks

The framework calls this member function to retrieve the mask for a rectangle’s resize handles.

The resize handles appear on the sides and corners of the rectangle and allow the user to control the shape and size of the rectangle.

A rectangle has 8 resize handles numbered 0–7. Each resize handle is represented by a bit in the mask; the value of that bit is 2^n, where n is the resize handle number. Bits 0–3 correspond to the corner resize handles, starting at the top left moving clockwise. Bits 4–7 correspond to the side resize handles starting at the top moving clockwise. The following illustration shows a rectangle’s resize handles and their corresponding resize handle numbers and values:

The default implementation of GetHandleMask returns the mask of the bits so that the resize handles appear. If the single bit is on, the corresponding resize handle will be drawn.

Override this member function to hide or show the indicated resize handles.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::AdjustRect


CRectTracker::GetTrueRect

void GetTrueRect( LPRECT lpTrueRect ) const;

Parameters

lpTrueRect

Pointer to the RECT structure that will contain the device coordinates of the CRectTracker object.

Remarks

Call this function to retrieve the coordinates of the rectangle. The dimensions of the rectangle include the height and width of any resize handles located on the outer border. Upon returning, *lpTrueRect is always a normalized rectangle in device coordinates.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRect::NormalizeRect


CRectTracker::HitTest

int HitTest( CPoint point ) const;

Return Value

The value returned is based on the enumerated type CRectTracker::TrackerHit and can have one of the following values:

  • CRectTracker::hitNothing –1

  • CRectTracker::hitTopLeft 0

  • CRectTracker::hitTopRight 1

  • CRectTracker::hitBottomRight 2

  • CRectTracker:hitBottomLeft 3

  • CRectTracker:hitTop 4

  • CRectTracker:hitRight 5

  • CRectTracker:hitBottom 6

  • CRectTracker:hitLeft 7

  • CRectTracker:hitMiddle 8

Parameters

point

The point, in device coordinates, to test.

Remarks

Call this function to find out whether the user has grabbed a resize handle.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::NormalizeHit, CRectTracker::SetCursor


CRectTracker::NormalizeHit

int NormalizeHit( int nHandle ) const;

Return Value

The index of the normalized handle.

Parameters

nHandle

Handle selected by the user.

Remarks

Call this function to convert a potentially inverted handle.

When CRectTracker::Track or CRectTracker::TrackRubberBand is called with inverting allowed, it is possible for the rectangle to be inverted on the x-axis, the y-axis, or both. When this happens, HitTest will return handles that are also inverted with respect to the rectangle. This is inappropriate for drawing cursor feedback because the feedback depends on the screen position of the rectangle, not the portion of the rectangle data structure that will be modified.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::HitTest, CRectTracker::Track, CRectTracker::TrackRubberBand


CRectTracker::OnChangedRect

virtual void OnChangedRect( const CRect& rectOld );

Parameters

rectOld

Contains the old device coordinates of the CRectTracker object.

Remarks

Called by the framework whenever the tracker rectangle has changed during a call to Track. At the time this function is called, all feedback drawn with DrawTrackerRect has been removed. The default implementation of this function does nothing.

Override this function when you want to perform any actions after the rectangle has been resized.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::AdjustRect, CRectTracker::Track, CRectTracker::TrackRubberBand


CRectTracker::SetCursor

BOOL SetCursor( CWnd* pWnd, UINT nHitTest ) const;

Return Value

Nonzero if the previous hit was over the tracker rectangle; otherwise 0.

Parameters

pWnd

Points to the window that currently contains the cursor.

nHitTest

Results of the previous hit test, from the WM_SETCURSOR message.

Remarks

Call this function to change the cursor shape while it is over the CRectTracker object’s region.

Call this function from inside the function of your window that handles the WM_SETCURSOR message (typically OnSetCursor).

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::NormalizeHit, CRectTracker::HitTest, CWinApp::LoadCursor, CWnd::OnSetCursor


CRectTracker::Track

BOOL Track( CWnd* pWnd, CPoint point, BOOL bAllowInvert = FALSE, CWnd* pWndClipTo = NULL );

Return Value

If the ESC key is pressed, the tracking process is halted, the rectangle stored in the tracker is not altered, and 0 is returned. If the change is committed, by moving the mouse and releasing the left mouse button, the new position and/or size is recorded in the tracker’s rectangle and nonzero is returned.

Parameters

pWnd

The window object that contains the rectangle.

point

Device coordinates of the current mouse position relative to the client area.

bAllowInvert

If TRUE, the rectangle can be inverted along the x-axis or y-axis; otherwise FALSE.

pWndClipTo

The window that drawing operations will be clipped to. If NULL, pWnd is used as the clipping rectangle.

Remarks

Call this function to display the user interface for resizing the rectangle. This is usually called from inside the function of your application that handles the WM_LBUTTONDOWN message (typically OnLButtonDown).

This function will capture the mouse until the user releases the left mouse button, presses the ESC key, or presses the right mouse button. As the user moves the mouse cursor, the feedback is updated by calling DrawTrackerRect and OnChangedRect.

If bAllowInvert is TRUE, the tracking rectangle can be inverted on either the x-axis or y-axis.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::DrawTrackerRect, CRectTracker::OnChangedRect, CRectTracker::CRectTracker, CRectTracker::TrackRubberBand


CRectTracker::TrackRubberBand

BOOL TrackRubberBand( CWnd* pWnd, CPoint point, BOOL bAllowInvert = TRUE );

Return Value

Nonzero if the mouse has moved and the rectangle is not empty; otherwise 0.

Parameters

pWnd

The window object that contains the rectangle.

point

Device coordinates of the current mouse position relative to the client area.

bAllowInvert

If TRUE, the rectangle can be inverted along the x-axis or y-axis; otherwise FALSE.

Remarks

Call this function to do rubber-band selection. It is usually called from inside the function of your application that handles the WM_LBUTTONDOWN message (typically OnLButtonDown).

This function will capture the mouse until the user releases the left mouse button, presses the ESC key, or presses the right mouse button. As the user moves the mouse cursor, the feedback is updated by calling DrawTrackerRect and OnChangedRect.

Tracking is performed with a rubber-band-type selection from the lower-right handle. If inverting is allowed, the rectangle can be sized by dragging either up and to the left or down and to the right.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::DrawTrackerRect, CRectTracker::OnChangedRect, CRectTracker::CRectTracker


CRectTracker::m_nHandleSize

Remarks

The size, in pixels, of the CRectTracker resize handles. Initialized with the default system value.


CRectTracker::m_rect

Remarks

The current position of the rectangle in client coordinates (pixels).

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::CRectTracker, CRectTracker::Track, CRectTracker::TrackRubberBand


CRectTracker::m_sizeMin

Remarks

The minimum size of the rectangle. Both default values, cx and cy, are calculated from the default system value for the border width. This data member is used only by the AdjustRect member function.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::Track, CRectTracker::TrackRubberBand, CRectTracker::AdjustRect


CRectTracker::m_nStyle

Remarks

Current style of the rectangle. See CRectTracker::CRectTracker for a list of possible styles.

CRectTracker Overview | Class Members | Hierarchy Chart

See Also CRectTracker::CRectTracker, CRectTracker::Draw


CResourceException

A CResourceException object is generated when Windows cannot find or allocate a requested resource. No further qualification is necessary or possible.

For more information on using CResourceException, see the article Exceptions in Visual C++ Programmer’s Guide.

#include <afxwin.h>


CResourceException Class Members

Construction

CResourceException Constructs a CResourceException object.


CResourceException::CResourceException

CResourceException( );

Remarks

Constructs a CResourceException object.

Do not use this constructor directly, but rather call the global function AfxThrowResourceException. For more information about exceptions, see the article Exceptions in Visual C++ Programmer’s Guide.

CResourceException Overview | Class Members | Hierarchy Chart

See Also AfxThrowResourceException, Exception Processing


CRgn

The CRgn class encapsulates a Windows graphics device interface (GDI) region. A region is an elliptical or polygonal area within a window. To use regions, you use the member functions of class CRgn with the clipping functions defined as members of class CDC.

The member functions of CRgn create, alter, and retrieve information about the region object for which they are called.

For more information on using CRgn, see Graphic Objects in Visual C++ Programmer’s Guide.

#include <afxwin.h>


CRgn Class Members

Construction

CRgn Constructs a CRgn object.

Initialization

CreateRectRgn | Initializes a CRgn object with a rectangular region.
CreateRectRgnIndirect | Initializes a CRgn object with a rectangular region defined by a RECT structure.
CreateEllipticRgn | Initializes a CRgn object with an elliptical region.
CreateEllipticRgnIndirect | Initializes a CRgn object with an elliptical region defined by a RECT structure.
CreatePolygonRgn | Initializes a CRgn object with a polygonal region. The system closes the polygon automatically, if necessary, by drawing a line from the last vertex to the first.
CreatePolyPolygonRgn | Initializes a CRgn object with a region consisting of a series of closed polygons. The polygons may be disjoint, or they may overlap.
CreateRoundRectRgn | Initializes a CRgn object with a rectangular region with rounded corners.
CombineRgn | Sets a CRgn object so that it is equivalent to the union of two specified CRgn objects.
CopyRgn | Sets a CRgn object so that it is a copy of a specified CRgn object.
CreateFromPath | Creates a region from the path that is selected into the given device context.
CreateFromData | Creates a region from the given region and transformation data.

Operations

EqualRgn | Checks two CRgn objects to determine whether they are equivalent.
FromHandle | Returns a pointer to a CRgn object when given a handle to a Windows region.
GetRegionData | Fills the specified buffer with data describing the given region.
GetRgnBox | Retrieves the coordinates of the bounding rectangle of a CRgn object.
OffsetRgn | Moves a CRgn object by the specified offsets.
PtInRegion | Determines whether a specified point is in the region.
RectInRegion | Determines whether any part of a specified rectangle is within the boundaries of the region.
SetRectRgn | Sets the CRgn object to the specified rectangular region.

Operators

operator HRGN Returns the Windows handle contained in the CRgn object.


CRgn::CombineRgn

int CombineRgn( CRgn* pRgn1, CRgn* pRgn2, int nCombineMode );

Return Value

Specifies the type of the resulting region. It can be one of the following values:

  • COMPLEXREGION New region has overlapping borders.

  • ERROR No new region created.

  • NULLREGION New region is empty.

  • SIMPLEREGION New region has no overlapping borders.

Parameters

pRgn1

Identifies an existing region.

pRgn2

Identifies an existing region.

nCombineMode

Specifies the operation to be performed when combining the two source regions. It can be any one of the following values:

  • RGN_AND Uses overlapping areas of both regions (intersection).

  • RGN_COPY Creates a copy of region 1 (identified by pRgn1).

  • RGN_DIFF Creates a region consisting of the areas of region 1 (identified by pRgn1) that are not part of region 2 (identified by pRgn2).

  • RGN_OR Combines both regions in their entirety (union).

  • RGN_XOR Combines both regions but removes overlapping areas.

Remarks

Creates a new GDI region by combining two existing regions. The regions are combined as specified by nCombineMode.

The two specified regions are combined, and the resulting region handle is stored in the CRgn object. Thus, whatever region is stored in the CRgn object is replaced by the combined region.

The size of a region is limited to 32,767 by 32,767 logical units or 64K of memory, whichever is smaller.

Use CopyRgn to simply copy one region into another region.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CopyRgn, ::CombineRgn


CRgn::CopyRgn

int CopyRgn( CRgn* pRgnSrc );

Return Value

Specifies the type of the resulting region. It can be one of the following values:

  • COMPLEXREGION New region has overlapping borders.

  • ERROR No new region created.

  • NULLREGION New region is empty.

  • SIMPLEREGION New region has no overlapping borders.

Parameters

pRgnSrc

Identifies an existing region.

Remarks

Copies the region defined by pRgnSrc into the CRgn object. The new region replaces the region formerly stored in the CRgn object. This function is a special case of the CombineRgn member function.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CombineRgn, ::CombineRgn


CRgn::CreateEllipticRgn

BOOL CreateEllipticRgn( int x1, int y1, int x2, int y2 );

Return Value

Nonzero if the operation succeeded; otherwise 0.

Parameters

x1

Specifies the logical x-coordinate of the upper-left corner of the bounding rectangle of the ellipse.

y1

Specifies the logical y-coordinate of the upper-left corner of the bounding rectangle of the ellipse.

x2

Specifies the logical x-coordinate of the lower-right corner of the bounding rectangle of the ellipse.

y2

Specifies the logical y-coordinate of the lower-right corner of the bounding rectangle of the ellipse.

Remarks

Creates an elliptical region. The region is defined by the bounding rectangle specified by x1, y1, x2, and y2. The region is stored in the CRgn object.

The size of a region is limited to 32,767 by 32,767 logical units or 64K of memory, whichever is smaller.

When it has finished using a region created with the CreateEllipticRgn function, an application should select the region out of the device context and use the DeleteObject function to remove it.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreateEllipticRgnIndirect, ::CreateEllipticRgn


CRgn::CreateEllipticRgnIndirect

BOOL CreateEllipticRgnIndirect( LPCRECT lpRect );

Return Value

Nonzero if the operation succeeded; otherwise 0.

Parameters

lpRect

Points to a RECT structure or a CRect object that contains the logical coordinates of the upper-left and lower-right corners of the bounding rectangle of the ellipse.

Remarks

Creates an elliptical region. The region is defined by the structure or object pointed to by lpRect and is stored in the CRgn object.

The size of a region is limited to 32,767 by 32,767 logical units or 64K of memory, whichever is smaller.

When it has finished using a region created with the CreateEllipticRgnIndirect function, an application should select the region out of the device context and use the DeleteObject function to remove it.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreateEllipticRgn, ::CreateEllipticRgnIndirect


CRgn::CreateFromData

BOOL CreateFromData( const XFORM* lpXForm, int nCount, const RGNDATA* pRgnData );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpXForm

Points to an XFORM data structure that defines the transformation to be performed on the region. If this pointer is NULL, the identity transformation is used.

nCount

Specifies the number of bytes pointed to by pRgnData.

pRgnData

Points to a RGNDATA data structure that contains the region data.

Remarks

Creates a region from the given region and transformation data. An application can retrieve data for a region by calling the CRgn::GetRegionData function.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::GetRegionData, ::ExtCreateRegion


CRgn::CreateFromPath

BOOL CreateFromPath( CDC* pDC );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

pDC

Identifies a device context that contains a closed path.

Remarks

Creates a region from the path that is selected into the given device context. The device context identified by the pDC parameter must contain a closed path. After CreateFromPath converts a path into a region, Windows discards the closed path from the device context.

CRgn Overview | Class Members | Hierarchy Chart

See Also CDC::BeginPath, CDC::EndPath, CDC::SetPolyFillMode


CRgn::CreatePolygonRgn

BOOL CreatePolygonRgn( LPPOINT lpPoints, int nCount, int nMode );

Return Value

Nonzero if the operation succeeded; otherwise 0.

Parameters

lpPoints

Points to an array of POINT structures or an array of CPoint objects. Each structure specifies the x-coordinate and y-coordinate of one vertex of the polygon. The POINT structure has the following form:

typedef struct tagPOINT {
   int x;
   int y;
} POINT;

nCount

Specifies the number of POINT structures or CPoint objects in the array pointed to by lpPoints.

nMode

Specifies the filling mode for the region. This parameter may be either ALTERNATE or WINDING.

Remarks

Creates a polygonal region. The system closes the polygon automatically, if necessary, by drawing a line from the last vertex to the first. The resulting region is stored in the CRgn object.

The size of a region is limited to 32,767 by 32,767 logical units or 64K of memory, whichever is smaller.

When the polygon-filling mode is ALTERNATE, the system fills the area between odd-numbered and even-numbered polygon sides on each scan line. That is, the system fills the area between the first and second side, between the third and fourth side, and so on.

When the polygon-filling mode is WINDING, the system uses the direction in which a figure was drawn to determine whether to fill an area. Each line segment in a polygon is drawn in either a clockwise or a counterclockwise direction. Whenever an imaginary line drawn from an enclosed area to the outside of a figure passes through a clockwise line segment, a count is incremented. When the line passes through a counterclockwise line segment, the count is decremented. The area is filled if the count is nonzero when the line reaches the outside of the figure.

When an application has finished using a region created with the CreatePolygonRgn function, it should select the region out of the device context and use the DeleteObject function to remove it.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreatePolyPolygonRgn, ::CreatePolygonRgn


CRgn::CreatePolyPolygonRgn

BOOL CreatePolyPolygonRgn( LPPOINT lpPoints, LPINT lpPolyCounts, int nCount, int nPolyFillMode );

Return Value

Nonzero if the operation succeeded; otherwise 0.

Parameters

lpPoints

Points to an array of POINT structures or an array of CPoint objects that defines the vertices of the polygons. Each polygon must be explicitly closed because the system does not close them automatically. The polygons are specified consecutively. The POINT structure has the following form:

typedef struct tagPOINT {
   int x;
   int y;
} POINT;

lpPolyCounts

Points to an array of integers. The first integer specifies the number of vertices in the first polygon in the lpPoints array, the second integer specifies the number of vertices in the second polygon, and so on.

nCount

Specifies the total number of integers in the lpPolyCounts array.

nPolyFillMode

Specifies the polygon-filling mode. This value may be either ALTERNATE or WINDING.

Remarks

Creates a region consisting of a series of closed polygons. The resulting region is stored in the CRgn object.

The polygons may be disjoint, or they may overlap.

The size of a region is limited to 32,767 by 32,767 logical units or 64K of memory, whichever is smaller.

When the polygon-filling mode is ALTERNATE, the system fills the area between odd-numbered and even-numbered polygon sides on each scan line. That is, the system fills the area between the first and second side, between the third and fourth side, and so on.

When the polygon-filling mode is WINDING, the system uses the direction in which a figure was drawn to determine whether to fill an area. Each line segment in a polygon is drawn in either a clockwise or a counterclockwise direction. Whenever an imaginary line drawn from an enclosed area to the outside of a figure passes through a clockwise line segment, a count is incremented. When the line passes through a counterclockwise line segment, the count is decremented. The area is filled if the count is nonzero when the line reaches the outside of the figure.

When an application has finished using a region created with the CreatePolyPolygonRgn function, it should select the region out of the device context and use the CGDIObject::DeleteObject member function to remove it.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreatePolygonRgn, CDC::SetPolyFillMode, ::CreatePolyPolygonRgn


CRgn::CreateRectRgn

BOOL CreateRectRgn( int x1, int y1, int x2, int y2 );

Return Value

Nonzero if the operation succeeded; otherwise 0.

Parameters

x1

Specifies the logical x-coordinate of the upper-left corner of the region.

y1

Specifies the logical y-coordinate of the upper-left corner of the region.

x2

Specifies the logical x-coordinate of the lower-right corner of the region.

y2

Specifies the logical y-coordinate of the lower-right corner of the region.

Remarks

Creates a rectangular region that is stored in the CRgn object.

The size of a region is limited to 32,767 by 32,767 logical units or 64K of memory, whichever is smaller.

When it has finished using a region created by CreateRectRgn, an application should use the CGDIObject::DeleteObject member function to remove the region.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreateRectRgnIndirect, CRgn::CreateRoundRectRgn, ::CreateRectRgn


CRgn::CreateRectRgnIndirect

BOOL CreateRectRgnIndirect( LPCRECT lpRect );

Return Value

Nonzero if the operation succeeded; otherwise 0.

Parameters

lpRect

Points to a RECT structure or CRect object that contains the logical coordinates of the upper-left and lower-right corners of the region. The RECT structure has the following form:

typedef struct tagRECT {
   int left;
   int top;
   int right;
   int bottom;
} RECT;

Remarks

Creates a rectangular region that is stored in the CRgn object.

The size of a region is limited to 32,767 by 32,767 logical units or 64K of memory, whichever is smaller.

When it has finished using a region created by CreateRectRgnIndirect, an application should use the CGDIObject::DeleteObject member function to remove the region.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreateRectRgn, CRgn::CreateRoundRectRgn, ::CreateRectRgnIndirect


CRgn::CreateRoundRectRgn

BOOL CreateRoundRectRgn( int x1, int y1, int x2, int y2, int x3, int y3 );

Return Value

Nonzero if the operation succeeded; otherwise 0.

Parameters

x1

Specifies the logical x-coordinate of the upper-left corner of the region.

y1

Specifies the logical y-coordinate of the upper-left corner of the region.

x2

Specifies the logical x-coordinate of the lower-right corner of the region.

y2

Specifies the logical y-coordinate of the lower-right corner of the region.

x3

Specifies the width of the ellipse used to create the rounded corners.

y3

Specifies the height of the ellipse used to create the rounded corners.

Remarks

Creates a rectangular region with rounded corners that is stored in the CRgn object.

The size of a region is limited to 32,767 by 32,767 logical units or 64K of memory, whichever is smaller.

When an application has finished using a region created with the CreateRoundRectRgn function, it should select the region out of the device context and use the CGDIObject::DeleteObject member function to remove it.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreateRectRgn, CRgn::CreateRectRgnIndirect, ::CreateRoundRectRgn


CRgn::CRgn

CRgn( );

Remarks

Constructs a CRgn object. The m_hObject data member does not contain a valid Windows GDI region until the object is initialized with one or more of the other CRgn member functions.


CRgn::EqualRgn

BOOL EqualRgn( CRgn* pRgn ) const;

Return Value

Nonzero if the two regions are equivalent; otherwise 0.

Parameters

pRgn

Identifies a region.

Remarks

Determines whether the given region is equivalent to the region stored in the CRgn object.

CRgn Overview | Class Members | Hierarchy Chart

See Also ::EqualRgn


CRgn::FromHandle

static CRgn* PASCAL FromHandle( HRGN hRgn );

Return Value

A pointer to a CRgn object. If the function was not successful, the return value is NULL.

Parameters

hRgn

Specifies a handle to a Windows region.

Remarks

Returns a pointer to a CRgn object when given a handle to a Windows region. If a CRgn object is not already attached to the handle, a temporary CRgn object is created and attached. This temporary CRgn object is valid only until the next time the application has idle time in its event loop, at which time all temporary graphic objects are deleted. Another way of saying this is that the temporary object is only valid during the processing of one window message.


CRgn::GetRegionData

Int GetRegionData( LPRGNDATA lpRgnData, int nCount ) const;

Return Value

Specifies the type of the resulting region. It can be one of the following values:

  • COMPLEXREGION New region has overlapping borders.

  • ERROR No new region created.

  • NULLREGION New region is empty.

  • SIMPLEREGION New region has no overlapping borders.

Parameters

lpRgnData

Points to a RGNDATA data structure that receives the information. If this parameter is NULL, the return value contains the number of bytes needed for the region data.

nCount

Specifies the size, in bytes, of the lpRgnData buffer.

Remarks

Fills the specified buffer with data describing the region. This data includes the dimensions of the rectangles that make up the region. This function is used in conjunction with the CRgn::CreateFromData function.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreateFromData


CRgn::GetRgnBox

int GetRgnBox( LPRECT lpRect ) const;

Return Value

Specifies the region’s type. It can be any of the following values:

  • COMPLEXREGION Region has overlapping borders.

  • NULLREGION Region is empty.

  • ERROR CRgn object does not specify a valid region.

  • SIMPLEREGION Region has no overlapping borders.

Parameters

lpRect

Points to a RECT structure or CRect object to receive the coordinates of the bounding rectangle. The RECT structure has the following form:

typedef struct tagRECT {
   int left;
   int top;
   int right;
   int bottom;
} RECT;

Remarks

Retrieves the coordinates of the bounding rectangle of the CRgn object.

CRgn Overview | Class Members | Hierarchy Chart

See Also ::GetRgnBox


CRgn::OffsetRgn

int OffsetRgn( int x, int y );

int OffsetRgn( POINT point );

Return Value

The new region’s type. It can be any one of the following values:

  • COMPLEXREGION Region has overlapping borders.

  • ERROR Region handle is not valid.

  • NULLREGION Region is empty.

  • SIMPLEREGION Region has no overlapping borders.

Parameters

x

Specifies the number of units to move left or right.

y

Specifies the number of units to move up or down.

point

The x-coordinate of point specifies the number of units to move left or right. The y-coordinate of point specifies the number of units to move up or down. The point parameter may be either a POINT structure or a CPoint object.

Remarks

Moves the region stored in the CRgn object by the specified offsets. The function moves the region x units along the x-axis and y units along the y-axis.

The coordinate values of a region must be less than or equal to 32,767 and greater than or equal to –32,768. The x and y parameters must be carefully chosen to prevent invalid region coordinates.

CRgn Overview | Class Members | Hierarchy Chart

See Also ::OffsetRgn


CRgn::PtInRegion

BOOL PtInRegion( int x, int y ) const;

BOOL PtInRegion( POINT point ) const;

Return Value

Nonzero if the point is in the region; otherwise 0.

Parameters

x

Specifies the logical x-coordinate of the point to test.

y

Specifies the logical y-coordinate of the point to test.

point

The x- and y-coordinates of point specify the x- and y-coordinates of the point to test the value of. The point parameter can either be a POINT structure or a CPoint object.

Remarks

Checks whether the point given by x and y is in the region stored in the CRgn object.

CRgn Overview | Class Members | Hierarchy Chart

See Also ::PtInRegion


CRgn::RectInRegion

BOOL RectInRegion( LPCRECT lpRect ) const;

Return Value

Nonzero if any part of the specified rectangle lies within the boundaries of the region; otherwise 0.

Parameters

lpRect

Points to a RECT structure or CRect object. The RECT structure has the following form:

typedef struct tagRECT {
   int left;
   int top;
   int right;
   int bottom;
} RECT;

Remarks

Determines whether any part of the rectangle specified by lpRect is within the boundaries of the region stored in the CRgn object.

CRgn Overview | Class Members | Hierarchy Chart

See Also ::RectInRegion


CRgn::SetRectRgn

void SetRectRgn( int x1, int y1, int x2, int y2 );

void SetRectRgn( LPCRECT lpRect );

Parameters

x1

Specifies the x-coordinate of the upper-left corner of the rectangular region.

y1

Specifies the y-coordinate of the upper-left corner of the rectangular region.

x2

Specifies the x-coordinate of the lower-right corner of the rectangular region.

y2

Specifies the y-coordinate of the lower-right corner of the rectangular region.

lpRect

Specifies the rectangular region. Can be either a pointer to a RECT structure or a CRect object.

Remarks

Creates a rectangular region. Unlike CreateRectRgn, however, it does not allocate any additional memory from the local Windows application heap. Instead, it uses the space allocated for the region stored in the CRgn object. This means that the CRgn object must already have been initialized with a valid Windows region before calling SetRectRgn. The points given by x1, y1, x2, and y2 specify the minimum size of the allocated space.

Use this function instead of the CreateRectRgn member function to avoid calls to the local memory manager.

CRgn Overview | Class Members | Hierarchy Chart

See Also CRgn::CreateRectRgn, ::SetRectRgn


CRgn::operator HRGN

operator HRGN( ) const;

Return Value

If successful, a handle to the Windows GDI object represented by the CRgn object; otherwise NULL.

Remarks

Use this operator to get the attached Windows GDI handle of the CRgn object. This operator is a casting operator, which supports direct use of an HRGN object.

For more information about using graphic objects, see the article Graphic Objects in the Win 32 SDK Programmer’s Reference.


CRichEditCntrItem

A “rich edit control” is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. Rich edit controls provide a programming interface for formatting text. However, an application must implement any user interface components necessary to make formatting operations available to the user.

The CRichEditCntrItem class, with CRichEditView and CRichEditDoc, provides the functionality of the rich edit control within the context of MFC’s document view architecture. CRichEditView maintains the text and formatting characteristic of text. CRichEditDoc maintains the list of OLE client items which are in the view. CRichEditCntrItem provides container-side access to the OLE client item.

This Windows Common control (and therefore the CRichEditCtrl and related classes) is available only to programs running under Windows 95 and Windows NT versions 3.51 and later.

For an example of using rich edit container items in an MFC application, see the WORDPAD sample application.

#include <afxrich.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample WORDPAD

See Also CRichEditDoc, CRichEditView


CRichEditCntrItem Class Members

Constructor

CRichEditCntrItem Constructs a CRichEditCntrItem object.

Operations

SyncToRichEditObject Activates the item as another type.


CRichEditCntrItem::CRichEditCntrItem

CRichEditCntrItem( REOBJECT* preo = NULL, CRichEditDoc* pContainer = NULL );

Parameters

preo

Pointer to an REOBJECT structure which describes an OLE item. The new CRichEditCntrItem object is constructed around this OLE item. If preo is NULL, the client item is empty.

pContainer

Pointer to the container document that will contain this item. If pContainer is NULL, you must explicitly call COleDocument::AddItem to add this client item to a document.

Remarks

Call this function to create a CRichEditCntrItem object and add it to the container document. This function does not perform any OLE initialization.

For more information, see the REOBJECT structure in the Win32 documentation.

CRichEditCntrItem Overview | Class Members | Hierarchy Chart

See Also COleDocument::AddItem, CRichEditDoc


CRichEditCntrItem::SyncToRichEditObject

void SyncToRichEditObject( REOBJECT& reo );

Parameters

reo

Reference to an REOBJECT structure which describes an OLE item.

Remarks

Call this function to synchronize the device aspect, DVASPECT, of this CRichEditCntrltem to that specified by reo.

For more information, see DVASPECT in the OLE documentation.


CRichEditCtrl

A “rich edit control” is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. Rich edit controls provide a programming interface for formatting text. However, an application must implement any user interface components necessary to make formatting operations available to the user.

The CRichEditCtrl class provides the functionality of the rich edit control. This Windows Common control (and therefore the CRichEditCtrl class) is available only to programs running under Windows 95 and Windows NT versions 3.51 and later.

Important If you are using a rich edit control in a dialog box (regardless whether your application is SDI, MDI, or dialog-based), you must call AfxInitRichEdit once before the dialog box is displayed. A typical place to call this function is in your program’s InitInstance member function. You do not need to call it for each time you display the dialog box, only the first time. You do not have to call AfxInitRichEdit if you are working with CRichEditView.

For more information on using CRichEditCtrl, see Control Topics and Using CRichEditCtrl in the Visual C++ Programmer's Guide.

For an example of using a rich edit control in an MFC application, see the WORDPAD sample application.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample WORDPAD

See Also CEdit, CRichEditView


CRichEditCtrl Class Members

Construction
Line Operations
Selection Operations
Formatting Operations
Editing Operations
General Operations
Clipboard Operations
OLE Operations

Construction

CRichEditCtrl | Constructs a CRichEditCtrl object.
Create | Creates the Windows rich edit control and associates it with this CRichEditCtrl object.

Line Operations

GetLineCount | Retrieves the number of lines in this CRichEditCtrl object.
GetLine | Retrieves a line of text from this CRichEditCtrl object.
GetFirstVisibleLine | Determines the topmost visible line in this CRichEditCtrl object.
LineIndex | Retrieves the character index of a given line in this CRichEditCtrl object.
LineFromChar | Determines which line contains the given character.
LineLength | Retrieves the length of a given line in this CRichEditCtrl object.
LineScroll | Scrolls the text in this CRichEditCtrl object.

Selection Operations

GetSel | Gets the starting and ending positions of the current selection in this CRichEditCtrl object.
GetSelText | Gets the text of the current selection in this CRichEditCtrl object
GetSelectionType | Retrieves the type of contents in the current selection in this CRichEditCtrl object.
Clear | Clears the current selection.
SetSel | Sets the selection in this CRichEditCtrl object.
ReplaceSel | Replaces the current selection in this CRichEditCtrl object with specified text.
HideSelection | Shows or hides the the current selection.

Formatting Operations

GetDefaultCharFormat | Retrieves the current default character formatting attributes in this CRichEditCtrl object.
GetSelectionCharFormat | Retrieves the character formatting attributes in the current selection in this CRichEditCtrl object.
GetParaFormat | Retrieves the paragraph formatting attributes in the current selection in this CRichEditCtrl object.
SetDefaultCharFormat | Sets the current default character formatting attributes in this CRichEditCtrl object.
SetSelectionCharFormat | Sets the character formatting attributes in the current selection in this CRichEditCtrl object.
SetWordCharFormat | Sets the character formatting attributes in the current word in this CRichEditCtrl object.
SetParaFormat | Sets the paragraph formatting attributes in the current selection in this CRichEditCtrl object.

Editing Operations

Undo | Reverses the last editing operation.
CanUndo | Determines if an editing operation can be undone.
EmptyUndoBuffer | Resets (clears) the undo flag of this CRichEditCtrl object.
StreamIn | Inserts text from an input stream into this CRichEditCtrl object.
StreamOut | Stores text from this CRichEditCtrl object into an output stream.

General Operations

GetModify | Determines if the contents of this CRichEditCtrl object have changed since the last save.
SetModify | Sets or clears the modification flag for this CRichEditCtrl object.
FindText | Locates text within this CRichEditCtrl object.
GetRect | Retrieves the formatting rectangle for this CRichEditCtrl object.
SetRect | Sets the formatting rectangle for this CRichEditCtrl object.
GetCharPos | Determines the location of a given character within this CRichEditCtrl object.
SetOptions | Sets the options for this CRichEditCtrl object.
SetReadOnly | Sets the read-only option for this CRichEditCtrl object.
GetTextLength | Retrieves the length of the text in this CRichEditCtrl object.
GetLimitText | Gets the limit on the amount of text a user can enter into this CRichEditCtrl object.
LimitText | Limits the amount of text a user can enter into the CRichEditCtrl object.
GetEventMask | Retrieves the event mask for this CRichEditCtrl object.
SetEventMask | Sets the event mask for this CRichEditCtrl object.
RequestResize | Forces this CRichEditCtrl object to send request resize notifications.
SetBackgroundColor | Sets the background color in this CRichEditCtrl object.
SetTargetDevice | Sets the target output device for this CRichEditCtrl object.
FormatRange | Formats a range of text for the target output device.
DisplayBand | Displays a portion of the contents of this CRichEditCtrl object.

Clipboard Operations

Copy | Copies the current selection to the Clipboard.
Cut | Cuts the current selection to the Clipboard.
Paste | Inserts the contents of the Clipboard into this rich edit control.
PasteSpecial | Inserts the contents of the Clipboard into this rich edit control in the specified data format.
CanPaste | Determines if the contents of the Clipboard can be pasted into this rich edit control.

OLE Operations

GetIRichEditOle | Retrieves a pointer to the IRichEditOle interface for this rich edit control.
SetOLECallback | Sets the IRichEditOleCallback COM object for this rich edit control.


CRichEditCtrl::CanPaste

BOOL CanPaste( UINT nFormat = 0 ) const;

Return Value

Nonzero if the Clipboard format can be pasted; otherwise 0.

Parameters

nFormat

The Clipboard data format to query. This parameter can be one of the predefined Clipboard formats or the value returned by RegisterClipboardFormat.

Remarks

Call this function to determine if the rich edit control can paste the specified Clipboard format. If nFormat is 0, CanPaste will try any format currently on the Clipboard.

For more information, see EM_CANPASTE message and RegisterClipboardFormat function in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Paste, CRichEditCtrl::PasteSpecial


CRichEditCtrl::CanUndo

BOOL CanUndo( ) const;

Return Value

Nonzero if the last edit operation can be undone by a call to the Undo member function; 0 if it cannot be undone.

Remarks

Call this function to determine if the last editing operation can be undone.

For more information, see EM_CANUNDO in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Undo, CRichEditCtrl::EmptyUndoBuffer


CRichEditCtrl::Clear

void Clear( );

Remarks

Call this function to delete (clear) the current selection (if any) in the rich edit control.

The deletion performed by Clear can be undone by calling the Undo member function.

To delete the current selection and place the deleted contents onto the Clipboard, call the Cut member function.

For more information, see WM_CLEAR in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Undo, CRichEditCtrl::Cut, CRichEditCtrl::Copy, CRichEditCtrl::Paste


CRichEditCtrl::Copy

void Copy( );

Remarks

Call this function to copy the current selection (if any) in the rich edit control to the Clipboard.

For more information, see WM_COPY in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Paste, CRichEditCtrl::Cut


CRichEditCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if initialization is successful; otherwise, 0.

Parameters

dwStyle

Specifies the edit control’s style. Apply any combination of edit styles to the control.

rect

Specifies the edit control’s size and position. Can be a CRect object or RECT structure.

pParentWnd

Specifies the edit control’s parent window (often a CDialog). It must not be NULL.

nID

Specifies the edit control’s ID.

Remarks

You construct a CRichEditCtrl object in two steps. First, call the CRichEditCtrl constructor, then call Create, which creates the Windows edit control and attaches it to the CRichEditCtrl object.

When you create a rich edit control with this function, first you must load the necessary common controls library. To load the libary, call the global function AfxInitRichEdit, which in turn initializes the common controls library. You need to call AfxInitRichEdit only once in your process.

When Create executes, Windows sends the WM_NCCREATE, WM_NCCALCSIZE, WM_CREATE, and WM_GETMINMAXINFO messages to the edit control.

These messages are handled by default by the OnNcCreate, OnNcCalcSize, OnCreate, and OnGetMinMaxInfo member functions in the CWnd base class. To extend the default message handling, derive a class from CRichEditCtrl, add a message map to the new class, and override the above message-handler member functions. Override OnCreate, for example, to perform needed initialization for the new class.

Apply the following window styles to an edit control.

  • WS_CHILD Always.

  • WS_VISIBLE Usually.

  • WS_DISABLED Rarely.

  • WS_GROUP To group controls.

  • WS_TABSTOP To include edit control in the tabbing order.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::CRichEditCtrl


CRichEditCtrl::CRichEditCtrl

CRichEditCtrl( );

Remarks

Constructs a CRichEditCtrl object. Use Create to construct the Windows rich edit control.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Create


CRichEditCtrl::Cut

void Cut( );

Remarks

Call this function to delete (cut) the current selection (if any) in the rich edit control and copy the deleted text to the Clipboard.

The deletion performed by Cut can be undone by calling the Undo member function.

To delete the current selection without placing the deleted text into the Clipboard, call the Clear member function.

For more information, see WM_CUT in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Copy, CRichEditCtrl::Undo, CRichEditCtrl::Clear


CRichEditCtrl::DisplayBand

BOOL DisplayBand( LPRECT pDisplayRect );

Return Value

Nonzero if the display of the formatted text succeeds, otherwise, 0.

Parameters

pDisplayRect

Pointer to a RECT or CRect object specifying the area of the device to display the text.

Remarks

Call this function to display a portion of the contents of the rich edit control (text and OLE items), as previously formatted by FormatRange. The text and OLE items are clipped to the area specified by the pointer pDisplayRect.

For more information, see EM_DISPLAYBAND in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::FormatRange


CRichEditCtrl::EmptyUndoBuffer

void EmptyUndoBuffer( );

Remarks

Call this function to reset (clear) the undo flag of this rich edit control. The control will now be unable to undo the last editing operation. The undo flag is set whenever an operation within the rich edit control can be undone.

The undo flag is automatically cleared whenever you call the CWnd member function SetWindowText.

For more information, see EM_EMPTYUNDOBUFFER in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::CanUndo¸ CRichEditCtrl::Undo, CWnd::SetWindowText


CRichEditCtrl::FindText

long FindText( DWORD dwFlags, FINDTEXTEX* pFindText ) const;

Return Value

Zero-based character position of the next match; – 1 if there are no more matches.

Parameters

dwFlags

Flags for the match criteria. Can be zero or more of the following values:

  • FR_MATCHCASE Indicates that the search is case sensitive.

  • FR_WHOLEWORD Indicates that the word boundaries should be considered in the search.

pFindText

Pointer to the FINDTEXTEX structure giving the parameters for the search and returning the range where the match was found.

Remarks

Call this function to find text within the rich edit control. You can search either up or down by setting the proper range parameters in the CHARRANGE structure within the FINDTEXTEX structure.

For more information, see EM_FINDTEXTEX message and FINDTEXTEX structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetSel


CRichEditCtrl::FormatRange

long FormatRange( FORMATRANGE* pfr, BOOL bDisplay = TRUE );

Return Value

The index of the last character that fits in the region plus one.

Parameters

pfr

Pointer to the FORMATRANGE structure which contains information about the output device. NULL indicates that cached information within the rich edit control can be freed.

bDisplay

Indicates if the text should be rendered. If FALSE, the text is just measured.

Remarks

Call this function to format a range of text in a rich edit control for a specific device. Typically, this call is followed by a call to DisplayBand.

For more information, see EM_FORMATRANGE message and FORMATRANGE structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::DisplayBand


CRichEditCtrl::GetCharPos

CPoint GetCharPos( long lChar ) const;

Return Value

The location of the top-left corner of the character specified by lChar.

Parameters

lChar

Zero-based index of the character.

Remarks

Call this function to get the position (top-left corner) of a given character within this CRichEditCtrl object. The character is specified by giving its zero-based index value. If lChar is greater than the index of the last character in this CRichEditCtrl object, the return value specifies the coordinates of the character position just past the last character in this CRichEditCtrl object.

For more information, see EM_POSFROMCHAR in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::FindText


CRichEditCtrl::GetDefaultCharFormat

DWORD GetDefaultCharFormat( CHARFORMAT& cf ) const;

Return Value

The dwMask data member of cf. It specified the default character formatting attributes.

Parameters

cf

Pointer to a CHARFORMAT structure which will hold the default character formatting attributes.

Remarks

Call this function to get the default character formatting attributes of this CRichEditCtrl object.

For more information, see EM_GETCHARFORMAT message and CHARFORMAT structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetDefaultCharFormat, CRichEditCtrl::GetSelectionCharFormat, CRichEditCtrl::GetParaFormat


CRichEditCtrl::GetEventMask

long GetEventMask( ) const;

Return Value

The event mask for this CRichEditCtrl object.

Remarks

Call this function to get the event mask for this CRichEditCtrl object. The event mask specifies which notification messages the CRichEditCtrl object sends to its parent window.

For more information, see EM_GETEVENTMASK in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetEventMask, CRichEditCtrl::CRichEditCtrl


CRichEditCtrl::GetFirstVisibleLine

int GetFirstVisibleLine( ) const;

Return Value

Zero-based index of the uppermost visible line in this CRichEditCtrl object.

Remarks

Call this function to determine the topmost visible line in this CRichEditCtrl object.

For more information, see EM_GETFIRSTVISIBLELINE in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetLine, CRichEditCtrl::GetLineCount


CRichEditCtrl::GetIRichEditOle

IRichEditOle* GetIRichEditOle( ) const;

Return Value

Pointer to the IRichEditOle interface that can be used to access this CRichEditCtrl object’s OLE functionality; NULL if the interface is not accessible.

Remarks

Call this member function to access the IRichEditOle interface for this CRichEditCtrl object. Use this interface to access this CRichEditCtrl object’s OLE functionality.

For more information, see EM_GETOLEINTERFACE message and IRichEditOle interface in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetOLECallback


CRichEditCtrl::GetLimitText

long GetLimitText( ) const;

Return Value

The current text limit, in bytes, for this CRichEditCtrl object.

Remarks

Call this member function to get the text limit for this CRichEditCtrl object. The text limit is the maximum amount of text, in bytes, the rich edit control can accept.

For more information, see EM_GETLIMITTEXT in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::LimitText


CRichEditCtrl::GetLine

int GetLine( int nIndex, LPTSTR lpszBuffer ) const;

int GetLine( int nIndex, LPTSTR lpszBuffer, int nMaxLength ) const;

Return Value

The number of characters copied into lpszBuffer.

Parameters

nIndex

Zero-based index of the line to retrieve.

lpszBuffer

Points to the buffer to receive the text. The first word of the buffer must specify the maximum number of bytes that can be copied into the buffer.

nMaxLength

Maximum number of characters that can be copied into lpszBuffer. The second form of GetLine places this value into the first word of the buffer specified by lpszBuffer.

Remarks

Call this function to retrieve a line of text from this CRichEditCtrl object. The copied line does not contain a terminating null character.

Note Because the first word of the buffer stores the number of characters to be copied, make sure that your buffer is at least 4 bytes long.

For more information, see EM_GETLINE in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::LineLength


CRichEditCtrl::GetLineCount

int GetLineCount( ) const;

Return Value

The number of lines in this CRichEditCtrl object.

Remarks

Call this function to retrieve the number of lines in the CRichEditCtrl object.

For more information, see EM_GETLINECOUNT in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetLine


CRichEditCtrl::GetModify

BOOL GetModify( ) const;

Return Value

Nonzero if the text in this CRichEditCtrl object has been modified; otherwise 0.

Remarks

Call this function to determine if the contents of this CRichEditCtrl object have been modified.

Windows maintains an internal flag indicating whether the contents of the rich edit control have been changed. This flag is cleared when the edit control is first created and can also be cleared by calling the SetModify member function.

For more information, see EM_GETMODIFY in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetModify


CRichEditCtrl::GetParaFormat

DWORD GetParaFormat( PARAFORMAT& pf ) const;

Return Value

The dwMask data member of pf. It specifies the paragraph formatting attributes that are consistent throughout the current selection.

Parameters

pf

Pointer to a PARAFORMAT structure to hold the paragraph formatting attributes of the current selection.

Remarks

Call this function to get the paragraph formatting attributes of the current selection. If more than one paragraph is selected, pf receives the attributes of the first selected paragraph. The return value specifies which attributes are consistent throughout the selection.

For more information, see EM_GETPARAFORMAT message and PARAFORMAT structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetParaFormat, CRichEditCtrl::GetSelectionCharFormat


CRichEditCtrl::GetRect

void GetRect( LPRECT lpRect ) const;

Parameters

lpRect

CRect or pointer to a RECT to receive the formatting rectangle of this CRichEditCtrl object.

Remarks

Call this function to retrieve the formatting rectangle for this CRichEditCtrl object. The formatting rectangle is the bounding rectangle for the text. This value is independent of the size of the CRichEditCtrl object.

For more information, see EM_GETRECT in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetRect


CRichEditCtrl::GetSel

void GetSel( CHARRANGE& cr ) const;

void GetSel( long& nStartChar, long& nEndChar ) const;

Parameters

cr

Reference to a CHARRANGE structure to receive the bounds of the current selection.

nStartChar

Zero-based index of the first character in the current selection.

nEndChar

Zero-based index of the last character in the current selection.

Remarks

Call this function to retrieve the bounds of the current selection in this CRichEditCtrl object.

The two forms of this function provide alternate ways to get the bounds for the selection. Brief descriptions of these forms follow:

  • GetSel( cr ) This form uses the CHARRANGE structure with its cpMin and cpMax members to return the bounds.

  • GetSel( nStartChar, nEndChar ) This form returns the bounds in the parameters nStartChar and nEndChar.

The selection includes everything if the beginning (cpMin or nStartChar) is 0 and the end (cpMax or nEndChar) is – 1.

For more information, see EM_EXGETSEL message and CHARRANGE structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetSel, CRichEditCtrl::GetSelText, CRichEditCtrl::GetParaFormat, CRichEditCtrl::GetSelectionCharFormat


CRichEditCtrl::GetSelectionCharFormat

DWORD GetSelectionCharFormat( CHARFORMAT& cf ) const;

Return Value

The dwMask data member of cf. It specifies the character formatting attributes that are consistent throughout the current selection.

Parameters

cf

Pointer to a CHARFORMAT structure to receive the character formatting attributes of the current selection.

Remarks

Call this function to get the character formatting attributes of the current selection. The cf parameter receives the attributes of the first character in the current selection. The return value specifies which attributes are consistent throughout the selection.

For more information, see EM_GETCHARFORMAT message and CHARFORMAT structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetDefaultCharFormat, CRichEditCtrl::GetParaFormat, CRichEditCtrl::SetSelectionCharFormat, CRichEditCtrl::GetSelText


CRichEditCtrl::GetSelectionType

WORD GetSelectionType( ) const;

Return Value

Flags indicating the contents of the current selection. A combination of the following flags:

  • SEL_EMPTY Indicates that there is no current selection.

  • SEL_TEXT Indicates that the current selection contains text.

  • SEL_OBJECT Indicates that the current selection contains at least one OLE item.

  • SEL_MULTICHAR Indicates that the current selection contains more than one character of text.

  • SEL_MULTIOBJECT Indicates that the current selection contains more than one OLE object.

Remarks

Call this function to determine the selection type in this CRichEditCtrl object.

For more information, see EM_SELECTIONTYPE in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetSel, CRichEditCtrl::GetSelText


CRichEditCtrl::GetSelText

long GetSelText( LPTSTR lpBuf ) const;

CString GetSelText( ) const;

Return Value

Depends on the form:

  • GetSelText( lpBuf ) The number of characters copied into lpBuf, not including the null termination.

  • GetSelText( ) The string containing the current selection.

Parameters

lpBuf

Pointer to the buffer to receive the text in the current selection.

Remarks

Call this function to retrieve the text from the current selection in this CRichEditCtrl object.

If you use the first form, GetSelText( lpBuf ), you must ensure that the buffer is large enough for the text it will receive. Call GetSel to determine the number of characters in the current selection.

For more information, see EM_GETSELTEXT in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetSel, CRichEditCtrl::GetSelectionType


CRichEditCtrl::GetTextLength

long GetTextLength( );

Return Value

The length of the text in this CRichEditCtrl object.

Remarks

Call this function to retrieve the length of the text in this CRichEditCtrl object.

For more information, see WM_GETTEXTLENGTH in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::LimitText, CRichEditCtrl::GetLimitText


CRichEditCtrl::HideSelection

void HideSelection( BOOL bHide, BOOL bPerm );

Parameters

bHide

Indicates if the selection should be shown or hidden, TRUE to hide the selection.

pPerm

Indicates if this change in visibility for the selection should be permanent.

Remarks

Call the function to change the visibility of the selection.

When pPerm is TRUE, it changes the ECO_NOHIDESEL option for this CRichEditCtrl object. For a brief description of this option, see SetOptions. You can use this function to set all the options for this CRichEditCtrl object.

For more information, see EM_HIDESELECTION in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetSel, CRichEditCtrl::GetSelectionType


CRichEditCtrl::LimitText

void LimitText( long nChars = 0 );

Parameters

nChars

Specifies the length (in bytes) of the text that the user can enter. If this parameter is 0, the text length is set to UINT_MAX bytes. This is the default behavior.

Remarks

Call this function to limit the length of the text that the user can enter into an edit control.

Changing the text limit restricts only the text the user can enter. It has no effect on any text already in the edit control, nor does it affect the length of the text copied to the edit control by the SetWindowText member function in CWnd. If an application uses the SetWindowText function to place more text into an edit control than is specified in the call to LimitText, the user can delete any of the text within the edit control. However, the text limit will prevent the user from replacing the existing text with new text, unless deleting the current selection causes the text to fall below the text limit.

Note For the text limit, each OLE item counts as a single character.

For more information, see EM_EXLIMITTEXT in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetLimitText


CRichEditCtrl::LineFromChar

long LineFromChar( long nIndex ) const;

Return Value

The zero-based line number of the line containing the character index specified by nIndex. If nIndex is –1, the number of the line that contains the first character of the selection is returned. If there is no selection, the current line number is returned.

Parameters

nIndex

Contains the zero-based index value for the desired character in the text of the edit control, or contains –1. If nIndex is –1, it specifies the current line, that is, the line that contains the caret.

Remarks

Call this function to retrieve the line number of the line that contains the specified character index. A character index is the number of characters from the beginning of the rich edit control. For character counting, an OLE item is counted as a single character.

For more information, see EM_EXLINEFROMCHAR in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetLineCount, CRichEditCtrl::GetLine, CRichEditCtrl::LineIndex


CRichEditCtrl::LineIndex

int LineIndex( int nLine = -1 ) const;

Return Value

The character index of the line specified in nLine or –1 if the specified line number is greater then the number of lines in the edit control.

Parameters

nLine

Contains the index value for the desired line in the text of the edit control, or contains –1. If nLine is –1, it specifies the current line, that is, the line that contains the caret.

Remarks

Call this function to retrieve the character index of a line within this CRichEditCtrl object. The character index is the number of characters from the beginning of the rich edit control to the specified line.

For more information, see EM_LINEINDEX in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::LineFromChar, CRichEditCtrl::GetLineCount


CRichEditCtrl::LineLength

int LineLength( int nLine = -1 ) const;

Return Value

When LineLength is called for a multiple-line edit control, the return value is the length (in bytes) of the line specified by nLine. When LineLength is called for a single-line edit control, the return value is the length (in bytes) of the text in the edit control.

Parameters

nLine

Specifies the character index of a character in the line whose length is to be retrieved. If this parameter is –1, the length of the current line (the line that contains the caret) is returned, not including the length of any selected text within the line. When LineLength is called for a single-line edit control, this parameter is ignored.

Remarks

Call this function to retrieve the length of a line in a rich edit control.

Use the LineIndex member function to retrieve a character index for a given line number within this CRichEditCtrl object.

For more information, see EM_LINELENGTH in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::LineIndex


CRichEditCtrl::LineScroll

void LineScroll( int nLines, int nChars = 0 );

Parameters

nLines

Specifies the number of lines to scroll vertically.

nChars

Specifies the number of character positions to scroll horizontally. This value is ignored if the rich edit control has either the ES_RIGHT or ES_CENTER style. Edit styles are specified in Create.

Remarks

Call this function to scroll the text of a multiple-line edit control.

The edit control does not scroll vertically past the last line of text in the edit control. If the current line plus the number of lines specified by nLines exceeds the total number of lines in the edit control, the value is adjusted so that the last line of the edit control is scrolled to the top of the edit-control window.

LineScroll can be used to scroll horizontally past the last character of any line.

For more information, see EM_LINESCROLL in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::LineIndex


CRichEditCtrl::Paste

void Paste( );

Remarks

Call this function to insert the data from the Clipboard into the CRichEditCtrl at the insertion point, the location of the caret. Data is inserted only if the Clipboard contains data in a recognized format.

For more information, see WM_PASTE in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Copy, CRichEditCtrl::Cut, CRichEditCtrl::PasteSpecial


CRichEditCtrl::PasteSpecial

void PasteSpecial( UINT nClipFormat, DWORD dvAspect = 0, HMETAFILE hMF = 0 );

Parameters

nClipFormat

Clipboard format to paste into this CRichEditCtrl object.

dvAspect

Device aspect for the data to be retrieved from the Clipboard.

hMF

Handle to the metafile containing the iconic view of the object to be pasted.

Remarks

Call this function to paste data in a specific Clipboard format into this CRichEditCtrl object. The new material is inserted at the insertion point, the location of the caret.

For more information, see EM_PASTESPECIAL in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Paste, CRichEditCtrl::Copy, CRichEditCtrl::Cut


CRichEditCtrl::ReplaceSel

void ReplaceSel( LPCTSTR lpszNewText, BOOL bCanUndo = FALSE );

Parameters

lpszNewText

Pointer to a null-terminated string containing the replacement text.

bCanUndo

To specify that this function can be undone, set the value of this parameter to TRUE. The default value is FALSE.

Remarks

Call this function to replace the current selection in this CRichEditCtrl object with the specified text. To replace all the text in this CRichEditCtrl object, use CWnd::SetWindowText.

If there is no current selection, the replacement text is inserted at the insertion point, that is, the current caret location.

For more information, see EM_REPLACESEL in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::CanUndo, CRichEditCtrl::Undo, CWnd::SetWindowText


CRichEditCtrl::RequestResize

void RequestResize( );

Remarks

Call this function to force this CRichEditCtrl object to send EN_REQUESTRESIZE notification messages to its parent window. This function is useful during CWnd::OnSize processing for a bottomless CRichEditCtrl object.

For more information, see the EM_REQUESTRESIZE message and the Bottomless Rich Edit Controls article in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CWnd::OnSize, CRichEditCtrl::Create


CRichEditCtrl::SetBackgroundColor

COLORREF SetBackgroundColor( BOOL bSysColor, COLORREF cr );

Return Value

The previous background color for this CRichEditCtrl object.

Parameters

bSysColor

Indicates if the background color should be set to the system value. If this value is TRUE, cr is ignored.

cr

The requested background color. Used only if bSysColor is FALSE.

Remarks

Call this function to set the background color for this CRichEditCtrl object. The background color can be set to the system value or to a specified COLORREF value.

For more information, see EM_SETBKGNDCOLOR message and COLORREF structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CDC::SetBkColor


CRichEditCtrl::SetDefaultCharFormat

BOOL SetDefaultCharFormat( CHARFORMAT& cf );

Return Value

Nonzero if successful; otherwise, 0.

Parameters

cf

CHARFORMAT structure containing the new default character formatting attributes.

Remarks

Call this function to set the character formatting attributes for new text in this CRichEditCtrl object. Only the attributes specified by the dwMask member of cf are changed by this function.

For more information, see EM_SETCHARFORMAT message and CHARFORMAT structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetDefaultCharFormat, CRichEditCtrl::SetSelectionCharFormat


CRichEditCtrl::SetEventMask

DWORD SetEventMask( DWORD dwEventMask );

Return Value

The previous event mask.

Parameters

dwEventMask

The new event mask for this CRichEditCtrl object.

Remarks

Call this function to set the event mask for this CRichEditCtrl object. The event mask specifies which notification messages the CRichEditCtrl object sends to its parent window.

For more information, see EM_SETEVENTMASK in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetEventMask


CRichEditCtrl::SetModify

void SetModify( BOOL bModified = TRUE );

Parameters

bModified

A value of TRUE indicates that the text has been modified, and a value of FALSE indicates it is unmodified. By default, the modified flag is set.

Remarks

Call this function to set or clear the modified flag for an edit control. The modified flag indicates whether or not the text within the edit control has been modified. It is automatically set whenever the user changes the text. Its value can be retrieved with the GetModify member function.

For more information, see EM_SETMODIFY in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetModify


CRichEditCtrl::SetOLECallback

BOOL SetOLECallback( IRichEditOleCallback* pCallback );

Parameters

pCallback

Pointer to an IRichEditOleCallback object that this CRichEditCtrl object will use to get OLE-related resources and information.

Return Value

Nonzero if successful; otherwise, 0.

Remarks

Call this function to give this CRichEditCtrl object an IRichEditOleCallback object to use to access OLE-related resources and information. This CRichEditCtrl object will call IUnknown::AddRef to increment the usage count for the COM object specified by pCallback.

For more information, see EM_SETOLECALLBACK message and IRichEditOleCallback interface in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetIRichEditOle


CRichEditCtrl::SetOptions

void SetOptions( WORD wOp, DWORD dwFlags );

Parameters

wOp

Indicates the type of operation. One of the following values:

  • ECOOP_SET Set the options to those specified by dwFlags.

  • ECOOP_OR Combine the current options with those specified by dwFlags.

  • ECOOP_AND Retain only those current options that are also specified by dwFlags.

  • ECOOP_XOR Retain only those current options that are not specified by dwFlags.

dwFlags

Rich edit options. The flag values are listed in the Remarks section.

Remarks

Call this function to set the options for this CRichEditCtrl object.

The options can be a combination of the following values:

  • ECO_AUTOWORDSELECTION Automatic word selection on double-click.

  • ECO_AUTOVSCROLL Automatically scrolls text to the right by 10 characters when the user types a character at the end of the line. When the user presses the ENTER key, the control scrolls all text back to position zero.

  • ECO_AUTOHSCROLL Automatically scrolls text up one page when the user presses the ENTER key on the last line.

  • ECO_NOHIDESEL Negates the default behavior for an edit control. The default behavior hides the selection when the control loses the input focus and shows the selection when the control receives the input focus. If you specify ECO_NOHIDESEL, the selected text is inverted, even if the control does not have the focus.

  • ECO_READONLY Prevents the user from typing or editing text in the edit control.

  • ECO_WANTRETURN Specifies that a carriage return be inserted when the user presses the ENTER key while entering text into a multiple-line rich edit control in a dialog box. If you do not specify this style, pressing the ENTER key sends a command to the rich edit control’s parent window, which mimics clicking the parent window’s default button (for example, the OK button in a dialog box). This style has no effect on a single-line edit control.

  • ECO_SAVESEL Preserves the selection when the control loses the focus. By default, the entire contents of the control are selected when it regains the focus.

  • ECO_VERTICAL Draws text and objects in a vertical direction. Available for Asian languages only.

For more information, see EM_SETOPTIONS in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::HideSelection, CRichEditCtrl::SetReadOnly


CRichEditCtrl::SetParaFormat

BOOL SetParaFormat( PARAFORMAT& pf );

Return Value

Nonzero if successful; otherwise, 0.

Parameters

pf

PARAFORMAT structure containing the new default paragraph formatting attributes.

Remarks

Call this function to set the paragraph formatting attributes for the current selection in this CRichEditCtrl object. Only the attributes specified by the dwMask member of pf are changed by this function.

For more information, see EM_SETPARAFORMAT message and PARAFORMAT structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetParaFormat, CRichEditCtrl::SetSelectionCharFormat


CRichEditCtrl::SetReadOnly

BOOL SetReadOnly( BOOL bReadOnly = TRUE );

Return Value

Nonzero if successful; otherwise, 0.

Parameters

bReadOnly

Indicates if this CRichEditCtrl object should be read only.

Remarks

Call this member function to change the ECO_READONLY option for this CRichEditCtrl object. For a brief description of this option, see SetOptions. You can use this function to set all the options for this CRichEditCtrl object.

For more information, see EM_SETREADONLY in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Create, CRichEditCtrl::SetOptions


CRichEditCtrl::SetRect

void SetRect( LPCRECT lpRect );

Parameters

lpRect

CRect or pointer to a RECT that indicates the new bounds for the formatting rectangle.

Remarks

Call this function to set the formatting rectangle for this CRichEditCtrl object. The formatting rectangle is the limiting rectangle for the text. The limiting rectangle is independent of the size of the rich edit control window. When this CRichEditCtrl object is first created, the formatting rectangle is the same size as the client area of the window. Use SetRect to make the formatting rectangle larger or smaller than the rich edit window.

For more information, see EM_SETRECT in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetRect


CRichEditCtrl::SetSel

void SetSel( long nStartChar, long nEndChar );

void SetSel( CHARRANGE& cr );

Parameters

nStartChar

Zero-based index of the first character for the selection.

nEndChar

Zero-based index of the last character for the selection.

cr

CHARRANGE structure which holds the bounds of the current selection.

Remarks

Call this function to set the selection within this CRichEditCtrl object.

The two forms of this function provide alternate ways to set the bounds for the selection. Brief descriptions of these forms follow:

  • SetSel( cr ) This form uses the CHARRANGE structure with its cpMin and cpMax members to set the bounds.

  • SetSel( nStartChar, nEndChar ) This form use the parameters nStartChar and nEndChar to set the bounds.

The caret is placed at the end of the selection indicated by the greater of the start (cpMin or nStartChar) and end (cpMax or nEndChar) indices. This function does not scroll the contents of the CRichEditCtrl so that the caret is visible.

To select all the text in this CRichEditCtrl object, call SetSel with a start index of 0 and an end index of – 1.

For more information, see EM_EXSETSEL message and CHARRANGE structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetSel, CRichEditCtrl::GetSelectionType


CRichEditCtrl::SetSelectionCharFormat

BOOL SetSelectionCharFormat( CHARFORMAT& cf );

Return Value

Nonzero if successful; otherwise, 0.

Parameters

cf

CHARFORMAT structure containing the new character formatting attributes for the current selection.

Remarks

Call this function to set the character formatting attributes for the text in the current selection in this CRichEditCtrl object. Only the attributes specified by the dwMask member of cf are changed by this function.

For more information, see EM_SETCHARFORMAT message and CHARFORMAT structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetSelectionCharFormat, CRichEditCtrl::SetDefaultCharFormat


CRichEditCtrl::SetTargetDevice

BOOL SetTargetDevice( HDC hDC, long lLineWidth );

BOOL SetTargetDevice( CDC& dc, long lLineWidth );

Return Value

Nonzero if successful; otherwise, 0.

Parameters

hDC

Handle to the device context for the new target device.

lLineWidth

Line width to use for formatting.

dc

CDC for the new target device.

Remarks

Call this function to set the target device and line width used for WYSIWYG (what you see is what you get) formatting in this CRichEditCtrl object.

If this function is successful, the rich edit control owns the device context passed as a parameter. In that case, the calling function should not destroy the device context.

For more information, see EM_SETTARGETDEVICE in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::FormatRange, CRichEditCtrl::DisplayBand


CRichEditCtrl::SetWordCharFormat

BOOL SetWordCharFormat( CHARFORMAT& cf );

Return Value

Nonzero if successful; otherwise, 0.

Parameters

cf

CHARFORMAT structure containing the new character formatting attributes for the currently selected word.

Remarks

Call this function to set the character formatting attributes for the currently selected word in this CRichEditCtrl object. Only the attributes specified by the dwMask member of cf are changed by this function.

For more information, see EM_SETCHARFORMAT message and CHARFORMAT structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::SetSelectionCharFormat


CRichEditCtrl::StreamIn

long StreamIn( int nFormat, EDITSTREAM& es );

Return Value

Number of characters read from the input stream.

Parameters

nFormat

Flags specifying the input data formats. See the Remarks section for more information.

es

EDITSTREAM structure specifying the input stream. See the Remarks section for more information.

Remarks

Call this function to replace text in this CRichEditCtrl object with text from the specified input stream.

The value of nFormat must be one of the following:

  • SF_TEXT Indicates reading text only.

  • SF_RTF Indicates reading text and formatting.

Either of these values can be combined with SFF_SELECTION. If SFF_SELECTION is specified, StreamIn replaces the current selection with the contents of the input stream. If it is not specified, StreamIn replaces the entire contents of this CRichEditCtrl object.

In the EDITSTREAM parameter es, you specify a callback function which fills a buffer with text. This callback function is called repeatedly, until the input stream is exhausted.

For more information, see EM_STREAMIN message and EDITSTREAM structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::StreamOut


CRichEditCtrl::StreamOut

long StreamOut( int nFormat, EDITSTREAM& es );

Return Value

Number of characters written to the output stream.

Parameters

nFormat

Flags specifying the output data formats. See the Remarks section for more information.

es

EDITSTREAM structure specifying the output stream. See the Remarks section for more information.

Remarks

Call this function to write out the contents of this CRichEditCtrl object to the specified output stream.

The value of nFormat must be one of the following:

  • SF_TEXT Indicates writing text only.

  • SF_RTF Indicates writing text and formatting.

  • SF_RTFNOOBJS Indicates writing text and formatting, replacing OLE items with spaces.

  • SF_TEXTIZED Indicates writing text and formatting, with textual representations of OLE items.

Any of these values can be combined with SFF_SELECTION. If SFF_SELECTION is specified, StreamOut writes out the current selection into the output stream. If it is not specified, StreamOut writes out the the entire contents of this CRichEditCtrl object.

In the EDITSTREAM parameter es, you specify a callback function which fills a buffer with text. This callback function is called repeatedly, until the output stream is exhausted.

For more information, see EM_STREAMOUT message and EDITSTREAM structure in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::StreamIn


CRichEditCtrl::Undo

BOOL Undo( );

Return Value

Nonzero if the undo operation is successful; otherwise, 0.

Remarks

Call this function to undo the last operation in the rich edit control.

An undo operation can also be undone. For example, you can restore deleted text with the first call to Undo. As long as there is no intervening edit operation, you can remove the text again with a second call to Undo.

For more information, see EM_UNDO in the Win32 documentation.

CRichEditCtrl Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::CanUndo, CRichEditCtrl::EmptyUndoBuffer


CRichEditDoc

A “rich edit control” is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. Rich edit controls provide a programming interface for formatting text. However, an application must implement any user interface components necessary to make formatting operations available to the user.

The CRichEditDoc class, with CRichEditView and CRichEditCntrItem, provides the functionality of the rich edit control within the context of MFC’s document view architecture. CRichEditView maintains the text and formatting characteristic of text. CRichEditDoc maintains the list of client items which are in the view. CRichEditCntrItem provides container-side access to the OLE client items.

This Windows Common control (and therefore the CRichEditCtrl and related classes) is available only to programs running under Windows 95 and Windows NT versions 3.51 and later.

For an example of using a rich edit document in an MFC application, see the WORDPAD sample application.

#include <afxrich.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample WORDPAD

See Also CRichEditView, CRichEditCntrItem, COleDocument, CRichEditCtrl


CRichEditDoc Class Members

Attributes

GetStreamFormat | Indicates whether stream input and output should include formatting information.
GetView | Retrieves the asssociated CRichEditView object.

Data Members

m_bRTF Indicates whether stream I/O should include formatting.

Overridables

CreateClientItem Called to perform cleanup of the document.


CRichEditDoc::CreateClientItem

virtual CRichEditCntrItem* CreateClientItem( REOBJECT* preo = NULL ) const = 0;

Return Value

Pointer to a new CRichEditCntrItem object which has been added to this document.

Parameters

preo

Pointer to an REOBJECT structure which describes an OLE item. The new CRichEditCntrItem object is constructed around this OLE item. If preo is NULL, the new client item is empty.

Remarks

Call this function to create a CRichEditCntrItem object and add it to this document. This function does not perform any OLE initialization.

For more information, see the REOBJECT structure in the Win32 documentation.

CRichEditDoc Overview | Class Members | Hierarchy Chart

See Also CRichEditCntrItem::CRichEditCntrItem, COleDocument::AddItem


CRichEditDoc::GetStreamFormat

int GetStreamFormat( ) const;

Return Value

One of the following flags:

  • SF_TEXT Indicates that the rich edit control does not maintain formatting information.

  • SF_RTF Indicates that the rich edit control does maintain formatting information.

Remarks

Call this function to determine the text format for streaming the contents of the rich edit. The return value is based on the m_bRTF data member. This function returns SF_RTF if m_bRTF is TRUE; otherwise, SF_TEXT.

CRichEditDoc Overview | Class Members | Hierarchy Chart

See Also CRichEditDoc::m_bRTF, CRichEditCtrl::StreamIn, CRichEditCtrl::StreamOut


CRichEditDoc::GetView

CRichEditView* GetView( ) const;

Return Value

Pointer to the CRichEditView object associated with the document.

Remarks

Call this function to access the CRichEditView object associated with this CRichEditDoc object. The text and formatting information are contained within the CRichEditView object. The CRichEditDoc object maintains the OLE items for serialization. There should be only one CRichEditView for each CRichEditDoc.

CRichEditDoc Overview | Class Members | Hierarchy Chart

See Also CRichEditView, CDocument::GetNextView


CRichEditDoc::m_bRTF

Remarks

When TRUE, indicates that CRichEditCtrl::StreamIn and CRichEditCtrl::StreamOut should store paragraph and character-formatting characteristics.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditDoc::GetStreamFormat


CRichEditView

A “rich edit control” is a window in which the user can enter and edit text. The text can be assigned character and paragraph formatting, and can include embedded OLE objects. Rich edit controls provide a programming interface for formatting text. However, an application must implement any user interface components necessary to make formatting operations available to the user.

The CRichEditView class, with CRichEditDoc and CRichEditCntrItem, provides the functionality of the rich edit control within the context of MFC’s document view architecture. CRichEditView maintains the text and formatting characteristic of text. CRichEditDoc maintains the list of OLE client items which are in the view. CRichEditCntrItem provides container-side access to the OLE client item.

This Windows Common control (and therefore the CRichEditCtrl and related classes) is available only to programs running under Windows 95 and Windows NT versions 3.51 and later.

For an example of using a rich edit view in an MFC application, see the WORDPAD sample application.

#include <afxrich.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample WORDPAD

See Also CRichEditDoc, CRichEditCntrItem


CRichEditView Class Members

Constructor

CRichEditView Constructs a CRichEditView object.

Attributes

GetDocument | Retrieves a pointer to the related CRichEditDoc.
GetCharFormatSelection | Retrieves the character formatting attributes for the current selection.
SetCharFormat | Sets the character formatting attributes for the current selection.
GetParaFormatSelection | Retrieves the paragraph formatting attributes for the current selection.
SetParaFormat | Sets the paragraph formatting attributes for the current selection.
GetTextLength | Retrieves the length of the text in the rich edit view.
GetPaperSize | Retrieves the paper size for this rich edit view.
SetPaperSize | Sets the paper size for this rich edit view.
GetMargins | Retrieves the margins for this rich edit view.
SetMargins | Sets the margins for this rich edit view.
GetPrintWidth | Retrieves the print width for this rich edit view.
GetPrintRect | Retrieves the print rectangle for this rich edit view.
GetPageRect | Retrieves the page rectangle for this rich edit view.
GetSelectedItem | Retrieves the selected item from the rich edit view.
GetInPlaceActiveItem | Retrieves the OLE item that is currently in-place active in the rich edit view.
GetRichEditCtrl | Retrieves the rich edit control.

Data Members

m_nBulletIndent | Indicates the amount of indent for bullet lists.
m_nWordWrap | Indicates the word wrap constraints.

Operations

FindText | Finds the specified text, invoking the wait cursor.
FindTextSimple | Finds the specified text.
IsRichEditFormat | Tells whether the Clipboard contains data in a rich edit or text format.
CanPaste | Tells whether the Clipboard contains data that can be pasted into the rich edit view.
DoPaste | Pastes an OLE item into this rich edit view.
InsertItem | Inserts a new item as an OLE item.
InsertFileAsObject | Inserts a file as an OLE item.
AdjustDialogPosition | Moves a dialog box so that it doesn’t obscure the current selection.
OnCharEffect | Changes the character formatting for the current selection.
OnParaAlign | Changes the alignment of paragraphs.
OnUpdateCharEffect | Updates the Command UI for character public member functions.
OnUpdateParaAlign | Updates the Command UI for paragraph public member functions.
PrintInsideRect | Formats the specified text within the given rectangle.
PrintPage | Formats the specified text within the given page.

Overridables

OnInitialUpdate | Refreshes a view when it is first attached to a document.
IsSelected | Indicates if the given OLE item is selected or not.
OnFindNext | Finds the next occurrence of a substring.
OnTextNotFound | Handles user notification that the requested text was not found.
OnReplaceAll | Replaces all occurrences of a given string with a new string.
OnReplaceSel | Replaces the current selection.
QueryAcceptData | Queries to see about the data on the IDataObject.
OnPasteNativeObject | Retrieves native data from an OLE item.
OnPrinterChanged | Sets the print characteristics to the given device.
WrapChanged | Adjusts the target output device for this rich edit view, based on the value of m_nWordWrap.
GetClipboardData | Retrieves a Clipboard object for a range in this rich edit view.
GetContextMenu | Retrieves a context menu to use on a right mouse-button down.


CRichEditView::AdjustDialogPosition

void AdjustDialogPosition( CDialog* pDlg );

Parameters

pDlg

Pointer to a CDialog object.

Remarks

Call this function to move the given dialog box so that it does not obscure the current selection.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetSel


CRichEditView::CanPaste

BOOL CanPaste( ) const;

Return Value

Nonzero if the Clipboard contains data in a format which this rich edit view can accept; otherwise, 0.

Remarks

Call this function to determine if the Clipboard contains information that can be pasted into this rich edit view.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Paste, CRichEditView::DoPaste, CRichEditView::IsRichEditFormat


CRichEditView::CRichEditView

CRichEditView( );

Remarks

Call this function to create a CRichEditView object.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditDoc, CRichEditCtrl


CRichEditView::DoPaste

void DoPaste( COleDataObject& dataobj, CLIPFORMAT cf, HMETAFILEPICT hMetaPict );

Parameters

dataobj

The COleDataObject containing the data to paste.

cf

The desired Clipboard format.

hMetaPict

The metafile that represents the item to be pasted.

Remarks

Call this function to paste the OLE item in dataobj into this rich edit document/view. The framework calls this function as part of the default implementation of QueryAcceptData.

This function determines the type of paste based on the results of the handler for Paste Special. If cf is 0, the new item uses the current iconic representation. If cf is nonzero and hMetaPict is not NULL, the new item uses hMetaPict for its representation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::Paste, CRichEditView::IsRichEditFormat, CRichEditView::InsertItem


CRichEditView::FindText

BOOL FindText( LPCTSTR lpszFind, BOOL bCase = TRUE, BOOL bWord = TRUE );

Return Value

Nonzero if the lpszFind text is found; otherwise 0.

Parameters

lpszFind

Contains the string to search for.

bCase

Indicates if the search is case sensitive.

bWord

Indicates if the search should match whole words only, not parts of words.

Remarks

Call this function to find the specified text and set it to be the current selection. This function displays the wait cursor during the find operation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::FindText, CRichEditCtrl::SetSel, CRichEditView::FindTextSimple, CWaitCursor


CRichEditView::FindTextSimple

BOOL FindTextSimple( LPCTSTR lpszFind, BOOL bCase = TRUE, BOOL bWord = TRUE );

Return Value

Nonzero if the lpszFind text is found; otherwise 0.

Parameters

lpszFind

Contains the string to search for.

bCase

Indicates if the search is case sensitive.

bWord

Indicates if the search should match whole words only, not parts of words.

Remarks

Call this function to find the specified text and set it to be the current selection.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::FindText, CRichEditCtrl::SetSel, CRichEditView::FindText


CRichEditView::GetCharFormatSelection

CHARFORMAT& GetCharFormatSelection( );

Return Value

A CHARFORMAT structure which contains the character formatting attributes of the current selection.

Remarks

Call this function to get the character formatting attributes of the current selection.

For more information, see the EM_GETCHARFORMAT message and the CHARFORMAT structure in the Win32 documentation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::SetCharFormat, CRichEditView::GetParaFormatSelection, CRichEditCtrl::GetSelectionCharFormat


CRichEditView::GetClipboardData

virtual HRESULT GetClipboardData( CHARRANGE* lpchrg, DWORD dwReco, LPDATAOBJECT lpRichDataObj, LPDATAOBJECT* lplpdataobj );

Return Value

An HRESULT value reporting the success of the operation. For more information on HRESULT, see Structure of COM Error Codes in the Platform SDK.

Parameters

lpchrg

Pointer to the CHARRANGE structure specifying the range of characters (and OLE items) to copy to the data object specified by lplpdataobj.

dwReco

Clipboard operation flag. Can be one of these values.

  • RECO_COPY Copy to the Clipboard.

  • RECO_CUT Cut to the Clipboard.

  • RECO_DRAG Drag operation (drag and drop).

  • RECO_DROP Drop operation (drag and drop).

  • RECO_PASTE Paste from the Clipboard.

lpRichDataObj

Pointer to an IDataObject object containing the Clipboard data from the rich edit control ( IRichEditOle::GetClipboardData).

lplpdataobj

Pointer to the pointer variable that receives the address of the IDataObject object representing the range specified in the lpchrg parameter. The value of lplpdataobj is ignored if an error is returned.

Remarks

The framework calls this function as part of the processing of IRichEditOleCallback::GetClipboardData. If the return value indicates success, IRichEditOleCallback::GetClipboardData returns the IDataObject accessed by lplpdataobj; otherwise, it returns the one accessed by lpRichDataObj. Override this function to supply your own Clipboard data. The default implementation of this function returns E_NOTIMPL.

This is an advanced overridable.

For more information, see IRichEditOle::GetClipboardData, IRichEditOleCallback::GetClipboardData, and CHARRANGE in the Win32 documentation and see IDataObject in the OLE documentation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also COleServerItem::GetClipboardData


CRichEditView::GetContextMenu

virtual HMENU GetContextMenu( WORD seltyp, LPOLEOBJECT lpoleobj, CHARRANGE* lpchrg );

Return Value

Handle to the context menu.

Parameters

seltyp

The selection type. The selection type values are described in the Remarks section.

lpoleobj

Pointer to a OLEOBJECT structure specifying the first selected OLE object if the selection contains one or more OLE items. If the selection contains no items, lpoleobj is NULL. The OLEOBJECT structure holds a pointer to an OLE object v-table.

lpchrg

Pointer to a CHARRANGE structure containing the current selection.

Remarks

The framework calls this function as part of the processing of IRichEditOleCallback::GetContextMenu. This function is a typical part of right mouse-button down processing.

The selection type can be any combination of the following flags:

  • SEL_EMPTY Indicates that there is no current selection.

  • SEL_TEXT Indicates that the current selection contains text.

  • SEL_OBJECT Indicates that the current selection contains at least one OLE item.

  • SEL_MULTICHAR Indicates that the current selection contains more than one character of text.

  • SEL_MULTIOBJECT Indicates that the current selection contains more than one OLE object.

The default implementation returns NULL. This is an advanced overridable.

For more information, see IRichEditOleCallback::GetContextMenu and CHARRANGE in the Win32 documentation.

For more information on the OLEOBJECT type, see the OLE Data Structures and Structure Allocation article in the OLE Knowledge Base.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetSelectionType


CRichEditView::GetDocument

CRichEditDoc* GetDocument( ) const;

Return Value

Pointer to a CRichEditDoc object associated with your CRichEditView object.

Remarks

Call this function to get a pointer to the CRichEditDoc associated with this view.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditDoc, CView::GetDocument, COleClientItem::GetDocument


CRichEditView::GetInPlaceActiveItem

CRichEditCntrItem* GetInPlaceActiveItem( ) const;

Return Value

A pointer to the single, in-place active CRichEditCntrItem object in this rich edit view; NULL if there is no OLE item currently in the in-place active state.

Remarks

Call this function to get the OLE item that is currently activated in place in this CRichEditView object.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also COleDocument::GetInPlaceActiveItem, CRichEditCntrItem, CRichEditView::GetSelectedItem


CRichEditView::GetMargins

CRect GetMargins( ) const;

Return Value

The margins used in printing, measured in MM_TWIPS.

Remarks

Call this function to retrieve the current margins used in printing.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::SetMargins, CRichEditView::GetPrintWidth, CRichEditView::GetPrintRect, CRichEditView::GetPaperSize, CRichEditView::PrintPage, CRichEditView::WrapChanged


CRichEditView::GetPageRect

CRect GetPageRect( ) const;

Return Value

The bounds of the page used in printing, measured in MM_TWIPS.

Remarks

Call this function to get the dimensions of the page used in printing. This value is based on the paper size.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetMargins, CRichEditView::GetPrintWidth, CRichEditView::GetPrintRect, CRichEditView::GetPaperSize, CRichEditView::PrintPage


CRichEditView::GetPaperSize

CSize GetPaperSize( ) const;

Return Value

The size of the paper used in printing, measured in MM_TWIPS.

Remarks

Call this function to retrieve the current paper size.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::SetPaperSize, CRichEditView::GetMargins, CRichEditView::GetPrintWidth, CRichEditView::GetPrintRect, CRichEditView::GetPageRect, CRichEditView::PrintPage


CRichEditView::GetParaFormatSelection

PARAFORMAT& GetParaFormatSelection( );

Return Value

A PARAFORMAT structure which contains the paragraph formatting attributes of the current selection.

Remarks

Call this function to get the paragraph formatting attributes of the current selection.

For more information, see EM_GETPARAFORMAT message and PARAFORMAT structure in the Win32 documentation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetCharFormatSelection, CRichEditView::SetParaFormat, CRichEditCtrl::GetParaFormat


CRichEditView::GetPrintRect

CRect GetPrintRect( ) const;

Return Value

The bounds of the image area used in printing, measured in MM_TWIPS.

Remarks

Call this function to retrieve the bounds of the printing area within the page rectangle.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetMargins, CRichEditView::GetPrintWidth, CRichEditView::GetPaperSize, CRichEditView::GetPageRect, CRichEditView::PrintPage


CRichEditView::GetPrintWidth

int GetPrintWidth( ) const;

Return Value

The width of the printing area, measured in MM_TWIPS.

Remarks

Call this function to determine the width of the printing area.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetMargins, CRichEditView::GetPrintRect, CRichEditView::GetPaperSize, CRichEditView::GetPageRect, CRichEditView::PrintPage, CRichEditView::WrapChanged


CRichEditView::GetRichEditCtrl

CRichEditCtrl& GetRichEditCtrl( ) const;

Return Value

The CRichEditCtrl object for this view.

Remarks

Call this function to retrieve the CRichEditCtrl object associated with the CRichEditView object.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl, CEditView::GetEditCtrl, CTreeView::GetTreeCtrl, CListView::GetListCtrl


CRichEditView::GetSelectedItem

CRichEditCntrItem* GetSelectedItem( ) const;

Return Value

Pointer to a CRichEditCntrItem object selected in the CRichEditView object; NULL if no item is selected in this view.

Remarks

Call this function to retrieve the OLE item (a CRichEditCntrItem object) currently selected in this CRichEditView object.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCntrItem, CRichEditView::GetInPlaceActiveItem


CRichEditView::GetTextLength

long GetTextLength( ) const;

Return Value

The length of the text in this CRichEditView object.

Remarks

Call this function to retrieve the length of the text in this CRichEditView object.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::GetTextLength


CRichEditView::InsertFileAsObject

void InsertFileAsObject( LPCTSTR lpszFileName );

Parameters

lpszFileName

String containing the name of the file to be inserted.

Remarks

Call this function to insert the specified file (as a CRichEditCntrItem object) into a rich edit view.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::InsertItem, CRichEditCntrItem


CRichEditView::InsertItem

HRESULT InsertItem( CRichEditCntrItem* pItem );

Return Value

An HRESULT value indicating the success of the insertion.

Parameters

pItem

Pointer to the item to be inserted.

Remarks

Call this function to insert a CRichEditCntrItem object into a rich edit view.

For more information on HRESULT, see Structure of COM Error Codes in the Platform SDK.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::InsertFileAsObject, CRichEditCntrItem


CRichEditView::IsRichEditFormat

BOOL IsRichEditFormat( CLIPFORMAT cf );

Return Value

Nonzero if cf is a rich edit or text Clipboard format.

Parameters

cf

The Clipboard format of interest.

Remarks

Call this function to determine if cf is a Clipboard format which is text, rich text, or rich text with OLE items.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditCtrl::CanPaste, CRichEditCtrl::Paste, CRichEditView::DoPaste


CRichEditView::IsSelected

virtual BOOL IsSelected( const CObject* pDocItem ) const;

Return Value

Nonzero if the object is selected; otherwise 0.

Parameters

pDocItem

Pointer to an object in the view.

Remarks

Call this function to determine if the specified OLE item is currently selected in this view.

Override this function if your derived view class has a different method for handling selection of OLE items.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetSelectedItem, CRichEditView::GetInPlaceActiveItem


CRichEditView::OnCharEffect

void OnCharEffect( DWORD dwMask, DWORD dwEffect );

Parameters

dwMask

The character formatting effects to modify in the current selection.

dwEffect

The desired list of character formatting effects.

Remarks

Call this function to change the character formatting effects for the current selection.

For more information on the dwMask and dwEffect parameters and their potential values, see the corresponding data members of CHARFORMAT in the Win32 documentation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::SetCharFormat


CRichEditView::OnFindNext

virtual void OnFindNext( LPCTSTR lpszFind, BOOL bNext, BOOL bCase, BOOL bWord );

Parameters

lpszFind

The string to find.

bNext

The direction to search: TRUE indicates down; FALSE, up.

bCase

Indicates whether the search is to be case sensitive.

bWord

Indicates whether the search is to match whole words only or not.

Remarks

Called by the framework when processing commands from the Find/Replace dialog box. Call this function to find text within the CRichEditView. Override this function to alter search characterics for your derived view class.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::FindText, CRichEditView::FindTextSimple


CRichEditView::OnInitialUpdate

virtual void OnInitialUpdate( );

Remarks

Called by the framework after the view is first attached to the document, but before the view is initially displayed. The default implementation of this function calls the CView::OnUpdate member function with no hint information (that is, using the default values of 0 for the lHint parameter and NULL for the pHint parameter). Override this function to perform any one-time initialization that requires information about the document. For example, if your application has fixed-sized documents, you can use this function to initialize a view's scrolling limits based on the document size. If your application supports variable-sized documents, use OnUpdate to update the scrolling limits every time the document changes.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CView::OnUpdate


CRichEditView::OnPasteNativeObject

virtual BOOL OnPasteNativeObject( LPSTORAGE lpStg );

Return Value

Nonzero if successful; otherwise, 0;

Parameters

lpStg

Pointer to an IStorage object.

Remarks

Use this function to load native data from an embedded item. Typically, you would do this by creating a COleStreamFile around the IStorage. The COleStreamFile can be attached to an archive and CObject::Serialize called to load the data.

This is an advanced overridable.

For more information, see IStorage in the OLE documentation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also COleStreamFile¸ CObject::Serialize, CArchive


CRichEditView::OnParaAlign

void OnParaAlign( WORD wAlign );

Parameters

wAlign

Desired paragraph alignment. One of the following values:

  • PFA_LEFT Align the paragraphs with the left margin.

  • PFA_RIGHT Align the paragraphs with the right margin.

  • PFA_CENTER Center the paragraphs between the margins.

Remarks

Call this function to change the paragraph alignment for the selected paragraphs.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::OnUpdateParaAlign


CRichEditView::OnPrinterChanged

virtual void OnPrinterChanged( const CDC& dcPrinter );

Parameters

dcPrinter

A CDC object for the new printer.

Remarks

Override this function to change characteristics for this rich edit view when the printer changes. The default implementation sets the paper size to the physical height and width for the output device (printer). If there is no device context associated wtih dcPrinter, the default implementation sets the paper size to 8.5 by 11 inches.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::SetPaperSize, CRichEditView::WrapChanged


CRichEditView::OnReplaceAll

virtual void OnReplaceAll( LPCTSTR lpszFind, LPCTSTR lpszReplace, BOOL bCase, BOOL bWord );

Parameters

lpszFind

The text to be replaced.

lpszReplace

The replacement text.

bCase

Indicates if the search is case sensitive.

bWord

Indicates if the search must select whole words or not.

Remarks

Called by the framework when processing Replace All commands from the Replace dialog box. Call this function to replace all occurrences of some given text with another string. Override this function to alter search characterics for this view.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::OnReplaceSel, CRichEditView::OnFindNext


CRichEditView::OnReplaceSel

virtual void OnReplaceSel( LPCTSTR lpszFind, BOOL bNext, BOOL bCase, BOOL bWord, LPCTSTR lpszReplace );

Parameters

lpszFind

The text to be replaced.

bNext

Indicates the direction of the search: TRUE is down; FALSE, up.

bCase

Indicates if the search is case sensitive.

bWord

Indicates if the search must select whole words or not.

lpszReplace

The replacement text.

Remarks

Called by the framework when processing Replace commands from the Replace dialog box. Call this function to replace one occurrence of some given text with another string. Override this function to alter search characterics for this view.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::OnReplaceAll


CRichEditView::OnTextNotFound

virtual void OnTextNotFound( LPCTSTR lpszFind );

Parameters

pszFind

The text which was not found.

Remarks

Called by the framework whenever a search fails. Override this function to change the output notification from a MessageBeep.

For more information, see MessageBeep in the Win32 documentation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::FindText, CRichEditView::FindTextSimple, CRichEditView::OnFindNext


CRichEditView::OnUpdateCharEffect

void OnUpdateCharEffect( CCmdUI* pCmdUI, DWORD dwMask, DWORD dwEffect );

Parameters

pCmdUI

Pointer to a CCmdUI object.

dwMask

Indicates the character formatting mask.

dwEffect

Indicates the character formatting effect.

Remarks

The framework calls this function to update the command UI for character effect commands. The mask dwMask specifies which character formatting attributes to check. The flags dwEffect list the character formatting attributes to set/clear.

For more information on the dwMask and dwEffect parameters and their potential values, see the corresponding data members of CHARFORMAT in the Win32 documentation.


CRichEditView::OnUpdateParaAlign

void OnParaAlign( CCmdUI* pCmdUI, WORD wAlign );

Parameters

pCmdUI

Pointer to a CCmdUI object.

wAlign

The paragraph alignment to check. One of the following values:

  • PFA_LEFT Align the paragraphs with the left margin.

  • PFA_RIGHT Align the paragraphs with the right margin.

  • PFA_CENTER Center the paragraphs between the margins.

Remarks

The framework calls this function to update the command UI for paragraph effect commands.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetParaFormatSelection, CRichEditView::OnParaAlign, CRichEditView::SetParaFormat


CRichEditView::PrintInsideRect

long PrintInsideRect( CDC* pDC, RECT& rectLayout, long nIndexStart, long nIndexStop, BOOL bOutput );

Return Value

The index of the last character that fits in the output area plus one.

Parameters

pDC

Pointer to a device context for the output area.

rectLayout

RECT or CRect which defines the output area.

nIndexStart

Zero-based index of the first character to be formatted.

nIndexStop

Zero-based index of the last character to be formatted.

bOutput

Indicates if the text should be rendered. If FALSE, the text is just measured.

Remarks

Call this function to format a range of text in a rich edit control to fit within rectLayout for the device specified by pDC. Typically, this call is followed by a call to CRichEditCtrl::DisplayBand which generates the output.

CRichEditView Overview | Class Members | Hierarchy Chart

CRichEditCtrl::FormatRange, CRichEditView::PrintPage, CRichEditCtrl::DisplayBand


CRichEditView::PrintPage

long PrintPage( CDC* pDC, long nIndexStart, long nIndexStop );

Return Value

The index of the last character that fits on the page plus one.

Parameters

pDC

Pointer to a device context for page output.

nIndexStart

Zero-based index of the first character to be formatted.

nIndexStop

Zero-based index of the last character to be formatted.

Remarks

Call this function to format a range of text in a rich edit control for the output device specified by pDC. The layout of each page is controlled by GetPageRect and GetPrintRect. Typically, this call is followed by a call to CRichEditCtrl::DisplayBand which generates the output.

Note that margins are relative to the physical page, not the logical page. Thus, margins of zero will often clip the text since many printers have unprintable areas on the page. To avoid clipping your text, you should call SetMargins and set reasonable margins before printing.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::PrintInsideRect, CRichEditView::GetPageRect, CRichEditView::GetPrintRect, CRichEditView::SetMargins


CRichEditView::QueryAcceptData

virtual HRESULT QueryAcceptData( LPDATAOBJECT lpdataobj, CLIPFORMAT FAR * lpcfFormat, DWORD dwReco, BOOL bReally, HGLOBAL hMetaFile );

Return Value

An HRESULT value reporting the success of the operation.

Parameters

lpdataobj

Pointer to the IDataObject to query.

lpcfFormat

Pointer to the acceptable data format.

dwReco

Not used.

bReally

Indicates if the paste operation should continue or not.

hMetaFile

A handle to the metafile used for drawing the item’s icon.

Remarks

Called by the framework to paste an object into the rich edit. Override this function to handle different organization of COM items in your derived document class. This is an advanced overridable.

For more information on HRESULT and IDataObject, see Structure of COM Error Codes and IDataObject, respectively, in the Platform SDK.


CRichEditView::SetCharFormat

void SetCharFormat( CHARFORMAT cf );

Parameters

cf

CHARFORMAT structure containing the new default character formatting attributes.

Remarks

Call this function to set the character formatting attributes for new text in this CRichEditView object. Only the attributes specified by the dwMask member of cf are changed by this function.

For more information, see EM_SETCHARFORMAT message and CHARFORMAT structure in the Win32 documentation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetCharFormatSelection, CRichEditView::SetParaFormat


CRichEditView::SetMargins

void SetMargins( const CRect& rectMargin );

Parameters

rectMargin

The new margin values for printing, measured in MM_TWIPS.

Remarks

Call this function to set the printing margins for this rich edit view. If m_nWordWrap is WrapToTargetDevice, you should call WrapChanged after using this function to adjust printing characteristics.

Note that the margins used by PrintPage are relative to the physical page, not the logical page. Thus, margins of zero will often clip the text since many printers have unprintable areas on the page. To avoid clipping your text, you should call use SetMargins to set reasonable printer margins before printing.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetMargins, CRichEditView::GetPrintWidth, CRichEditView::GetPrintRect, CRichEditView::GetPaperSize, CRichEditView::GetPageRect, CRichEditView::PrintPage, CRichEditView::WrapChanged


CRichEditView::SetPaperSize

void SetPaperSize( CSize sizePaper );

Parameters

sizePaper

The new paper size values for printing, measured in MM_TWIPS.

Remarks

Call this function to set the paper size for printing this rich edit view. If m_nWordWrap is WrapToTargetDevice, you should call WrapChanged after using this function to adjust printing characteristics.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetPaperSize, CRichEditView::GetMargins, CRichEditView::GetPrintWidth, CRichEditView::GetPrintRect, CRichEditView::GetPageRect, CRichEditView::PrintPage, CRichEditView::WrapChanged


CRichEditView::SetParaFormat

BOOL SetParaFormat( PARAFORMAT& pf );

Return Value

Nonzero if successful; otherwise, 0.

Parameters

pf

PARAFORMAT structure containing the new default paragraph formatting attributes.

Remarks

Call this function to set the paragraph formatting attributes for the current selection in this CRichEditView object. Only the attributes specified by the dwMask member of pf are changed by this function.

For more information, see EM_SETPARAFORMAT message and PARAFORMAT structure in the Win32 documentation.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::GetParaFormatSelection, CRichEditView::SetCharFormat


CRichEditView::WrapChanged

virtual void WrapChanged( );

Remarks

Call this function when the printing characteristics have changed (SetMargins or SetPaperSize).

Override this function to modify the way the rich edit view responds to changes in m_nWordWrap or the printing characteristics (OnPrinterChanged).

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::m_nWordWrap, CRichEditView::OnPrinterChanged, CRichEditView::SetMargins, CRichEditView::SetPaperSize


CRichEditView::m_nBulletIndent

Remarks

The indentation for bullet items in a list; by default, 720 units, which is 1/2 inch.


CRichEditView::m_nWordWrap

Remarks

Indicates the type of word wrap for this rich edit view. One of the following values:

  • WrapNone Indicates no automatic word wrapping.

  • WrapToWindow Indicates word wrapping based on the width of the window.

  • WrapToTargetDevice Indicates word wrapping based on the characteristics of the target device.

CRichEditView Overview | Class Members | Hierarchy Chart

See Also CRichEditView::WrapChanged


CRuntimeClass

CRuntimeClass does not have a base class.

Each class derived from CObject is associated with a CRuntimeClass structure that you can use to obtain information about an object or its base class at run time. The ability to determine the class of an object at run time is useful when extra type checking of function arguments is needed, or when you must write special-purpose code based on the class of an object. Run-time class information is not supported directly by the C++ language.

The structure has the following members:

LPCSTR m_lpszClassName

A null-terminated string containing the ASCII class name.

int m_nObjectSize

The size of the object, in bytes. If the object has data members that point to allocated memory, the size of that memory is not included.

UINT m_wSchema

The schema number ( –1 for nonserializable classes). See the IMPLEMENT_SERIAL macro for a description of the schema number.

CObject* ( PASCAL* m_pfnCreateObject )( )

A function pointer to the default constructor that creates an object of your class (valid only if the class supports dynamic creation; otherwise, returns NULL).

CRuntimeClass* ( PASCAL* m_pfn_GetBaseClass )( )

If your application is dynamically linked to the AFXDLL version of MFC, a pointer to a function that returns the CRuntimeClass structure of the base class.

CRuntimeClass* m_pBaseClass

If your application is statically linked to MFC, a pointer to the CRuntimeClass structure of the base class.

Feature Only in Professional and Enterprise Editions Static linking to MFC is supported only in Visual C++ Professional and Enterprise Editions. For more information, see Visual C++ Editions.

CObject* CreateObject( );

Classes derived from CObject can support dynamic creation, which is the ability to create an object of a specified class at run time. Document, view, and frame classes, for example, should support dynamic creation. The CreateObject member function can be used to implement this function and create objects for these classes during run time. For more information on dynamic creation and the CreateObject member, see CObject Class Topics and CObject Class: Specifying Levels of Functionality in Visual C++ Programmer’s Guide.

BOOL IsDerivedFrom( const CRuntimeClass* pBaseClass) const;

Returns TRUE if the class of the class member calling IsDerivedFrom is derived from the base class whose CRuntimeClass structure is given as a parameter. IsDerivedFrom walks from the member's class up the chain of derived classes all the way to the top and returns FALSE only if no match is found for the base class.

Note To use the CRuntimeClass structure, you must include the IMPLEMENT_DYNAMIC, IMPLEMENT_DYNCREATE, or IMPLEMENT_SERIAL macro in the implementation of the class for which you want to retrieve run-time object information.

For more information on using CRuntimeClass, see the article CObject Class: Accessing Run-Time Class Information in Visual C++ Programmer’s Guide.

Hierarchy Chart

See Also CObject::GetRuntimeClass, CObject::IsKindOf, RUNTIME_CLASS, IMPLEMENT_DYNAMIC, IMPLEMENT_DYNCREATE, IMPLEMENT_SERIAL


CScrollBar

The CScrollBar class provides the functionality of a Windows scroll-bar control.

You create a scroll-bar control in two steps. First, call the constructor CScrollBar to construct the CScrollBar object, then call the Create member function to create the Windows scroll-bar control and attach it to the CScrollBar object.

If you create a CScrollBar object within a dialog box (through a dialog resource), the CScrollBar is automatically destroyed when the user closes the dialog box.

If you create a CScrollBar object within a window, you may also need to destroy it.

If you create the CScrollBar object on the stack, it is destroyed automatically. If you create the CScrollBar object on the heap by using the new function, you must call delete on the object to destroy it when the user terminates the Windows scroll bar.

If you allocate any memory in the CScrollBar object, override the CScrollBar destructor to dispose of the allocations.

For related information about using CScrollBar, see Control Topics in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CWnd, CButton, CComboBox, CEdit, CListBox, CStatic, CDialog


CScrollBar Class Members

Construction

CScrollBar Constructs a CScrollBar object.

Initialization

Create Creates the Windows scroll bar and attaches it to the CScrollBar object.

Operations

GetScrollPos | Retrieves the current position of a scroll box.
SetScrollPos | Sets the current position of a scroll box.
GetScrollRange | Retrieves the current minimum and maximum scroll-bar positions for the given scroll bar.
SetScrollRange | Sets minimum and maximum position values for the given scroll bar.
ShowScrollBar | Shows or hides a scroll bar.
EnableScrollBar | Enables or disables one or both arrows of a scroll bar.
SetScrollInfo | Sets information about the scroll bar.
GetScrollInfo | Retrieves information about the scroll bar.
GetScrollLimit | Retrieves the limit of the scroll bar


CScrollBar::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise 0.

Parameters

dwStyle

Specifies the scroll bar’s style. Apply any combination of scroll-bar styles to the scroll bar.

rect

Specifies the scroll bar’s size and position. Can be either a RECT structure or a CRect object.

pParentWnd

Specifies the scroll bar’s parent window, usually a CDialog object. It must not be NULL.

nID

The scroll bar’s control ID.

Remarks

You construct a CScrollBar object in two steps. First call the constructor, which constructs the CScrollBar object; then call Create, which creates and initializes the associated Windows scroll bar and attaches it to the CScrollBar object.

Apply the following window styles to a scroll bar:

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

  • WS_GROUP To group controls

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CScrollBar::CScrollBar


CScrollBar::CScrollBar

CScrollBar( );

Remarks

Constructs a CScrollBar object. After constructing the object, call the Create member function to create and initialize the Windows scroll bar.

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CScrollBar::Create


CScrollBar::EnableScrollBar

BOOL EnableScrollBar( UINT nArrowFlags = ESB_ENABLE_BOTH );

Return Value

Nonzero if the arrows are enabled or disabled as specified; otherwise 0, which indicates that the arrows are already in the requested state or that an error occurred.

Parameters

nArrowFlags

Specifies whether the scroll arrows are enabled or disabled and which arrows are enabled or disabled. This parameter can be one of the following values:

  • ESB_ENABLE_BOTH Enables both arrows of a scroll bar.

  • ESB_DISABLE_LTUP Disables the left arrow of a horizontal scroll bar or the up arrow of a vertical scroll bar.

  • ESB_DISABLE_RTDN Disables the right arrow of a horizontal scroll bar or the down arrow of a vertical scroll bar.

  • ESB_DISABLE_BOTH Disables both arrows of a scroll bar.

Remarks

Enables or disables one or both arrows of a scroll bar.

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CWnd::EnableScrollBar, ::EnableScrollBar


CScrollBar::GetScrollInfo

BOOL GetScrollInfo( LPSCROLLINFO lpScrollInfo, UINT nMask );

Return Value

If the message retrieved any values, the return is TRUE. Otherwise, it is FALSE.

Parameters

lpScrollInfo

A pointer to a SCROLLINFO structure. See the Win32 Programmer’s Reference for more information about this structure.

nMask

Specifies the scroll bar parameters to retrieve. Typical usage, SIF_ALL, specifies a combination of SIF_PAGE, SIF_POS, SIF_TRACKPOS, and SIF_RANGE. See SCROLLINFO for more information on the nMask values.

Remarks

Call this member function to retrieve the information that the SCROLLINFO structure maintains about a scroll bar. GetScrollInfo enables applications to use 32-bit scroll positions.

The SCROLLINFO structure contains information about a scroll bar, including the minimum and maximum scrolling positions, the page size, and the position of the scroll box (the thumb). See the SCROLLINFO structure topic in the Win32 SDK Programmer’s Reference for more information about changing the structure defaults.

The MFC Windows message handlers that indicate scroll bar position, CWnd::OnHScroll and CWnd::OnVScroll, provide only 16 bits of position data. GetScrollInfo and SetScrollInfo provide 32 bits of scroll bar position data. Thus, an application can call GetScrollInfo while processing either CWnd::OnHScroll or CWnd::OnVScroll to obtain 32-bit scroll bar position data.

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CScrollBar::SetScrollInfo, CWnd::SetScrollInfo, CWnd::SetScrollPos, CWnd::OnVScroll, CWnd::OnHScroll, SCROLLINFO


CScrollBar::GetScrollLimit

int GetScrollLimit( );

Return Value

Specifies the maximum position of a scroll bar if successful; otherwise 0.

Remarks

Call this member function to retrieve the maximum scrolling position of the scroll bar.

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CWnd::GetScrollLimit


CScrollBar::GetScrollPos

int GetScrollPos( ) const;

Return Value

Specifies the current position of the scroll box if successful; otherwise 0.

Remarks

Retrieves the current position of a scroll box. The current position is a relative value that depends on the current scrolling range. For example, if the scrolling range is 100 to 200 and the scroll box is in the middle of the bar, the current position is 150.

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CScrollBar::SetScrollPos, CScrollBar::GetScrollRange, CScrollBar::SetScrollRange, ::GetScrollPos


CScrollBar::GetScrollRange

void GetScrollRange( LPINT lpMinPos, LPINT lpMaxPos ) const;

Parameters

lpMinPos

Points to the integer variable that is to receive the minimum position.

lpMaxPos

Points to the integer variable that is to receive the maximum position.

Remarks

Copies the current minimum and maximum scroll-bar positions for the given scroll bar to the locations specified by lpMinPos and lpMaxPos.

The default range for a scroll-bar control is empty (both values are 0).

CScrollBar Overview | Class Members | Hierarchy Chart

See Also ::GetScrollRange, CScrollBar::SetScrollRange, CScrollBar::GetScrollPos, CScrollBar::SetScrollPos


CScrollBar::SetScrollInfo

BOOL SetScrollInfo( LPSCROLLINFO lpScrollInfo, BOOL bRedraw = TRUE );

Return Value

If successful, the return is TRUE. Otherwise, it is FALSE.

Parameters

lpScrollInfo

A pointer to a SCROLLINFO structure.

bRedraw

Specifies whether the scroll bar should be redrawn to reflect the new information. If bRedraw is TRUE, the scroll bar is redrawn. If it is FALSE, it is not redrawn. The scroll bar is redrawn by default.

Remarks

Call this member function to set the information that the SCROLLINFO structure maintains about a scroll bar. You must provide the values required by the SCROLLINFO structure parameters, including the flag values.

The SCROLLINFO structure contains information about a scroll bar, including the minimum and maximum scrolling positions, the page size, and the position of the scroll box (the thumb). See the SCROLLINFO structure topic in the Win32 SDK Programmer’s Reference for more information about changing the structure defaults.

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CScrollBar::GetScrollInfo, CWnd::SetScrollInfo, CWnd::SetScrollPos, CWnd::OnVScroll, CWnd::OnHScroll, CWnd::GetScrollInfo, SCROLLINFO


CScrollBar::SetScrollPos

int SetScrollPos( int nPos, BOOL bRedraw = TRUE );

Return Value

Specifies the previous position of the scroll box if successful; otherwise 0.

Parameters

nPos

Specifies the new position for the scroll box. It must be within the scrolling range.

bRedraw

Specifies whether the scroll bar should be redrawn to reflect the new position. If bRedraw is TRUE, the scroll bar is redrawn. If it is FALSE, it is not redrawn. The scroll bar is redrawn by default.

Remarks

Sets the current position of a scroll box to that specified by nPos and, if specified, redraws the scroll bar to reflect the new position.

Set bRedraw to FALSE whenever the scroll bar will be redrawn by a subsequent call to another function to avoid having the scroll bar redrawn twice within a short interval.

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CScrollBar::GetScrollPos, CScrollBar::GetScrollRange, CScrollBar::SetScrollRange, ::SetScrollPos


CScrollBar::SetScrollRange

void SetScrollRange( int nMinPos, int nMaxPos, BOOL bRedraw = TRUE );

Parameters

nMinPos

Specifies the minimum scrolling position.

nMaxPos

Specifies the maximum scrolling position.

bRedraw

Specifies whether the scroll bar should be redrawn to reflect the change. If bRedraw is TRUE, the scroll bar is redrawn; if FALSE, it is not redrawn. It is redrawn by default.

Remarks

Sets minimum and maximum position values for the given scroll bar. Set nMinPos and nMaxPos to 0 to hide standard scroll bars.

Do not call this function to hide a scroll bar while processing a scroll-bar notification message.

If a call to SetScrollRange immediately follows a call to the SetScrollPos member function, set bRedraw in SetScrollPos to 0 to prevent the scroll bar from being redrawn twice.

The difference between the values specified by nMinPos and nMaxPos must not be greater than 32,767. The default range for a scroll-bar control is empty (both nMinPos and nMaxPos are 0).

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CScrollBar::GetScrollPos, CScrollBar::SetScrollPos, CScrollBar::GetScrollRange, ::SetScrollRange


CScrollBar::ShowScrollBar

void ShowScrollBar( BOOL bShow = TRUE );

Parameters

bShow

Specifies whether the scroll bar is shown or hidden. If this parameter is TRUE, the scroll bar is shown; otherwise it is hidden.

Remarks

Shows or hides a scroll bar.

An application should not call this function to hide a scroll bar while processing a scroll-bar notification message.

CScrollBar Overview | Class Members | Hierarchy Chart

See Also CScrollBar::GetScrollPos, CScrollBar::GetScrollRange, CWnd::ScrollWindow, CScrollBar::SetScrollPos, CScrollBar::SetScrollRange


CScrollView

The CScrollView class is a CView with scrolling capabilities.

You can handle standard scrolling yourself in any class derived from CView by overriding the message-mapped OnHScroll and OnVScroll member functions. But CScrollView adds the following features to its CView capabilities:

  • It manages window and viewport sizes and mapping modes.

  • It scrolls automatically in response to scroll-bar messages.

  • It scrolls automatically in response to messages from the keyboard, a non-scrolling mouse, or the IntelliMouse wheel.

You can handle mouse wheel scrolling yourself by overriding the message-mapped OnMouseWheel and OnRegisteredMouseWheel member functions. As they are for CScrollView, these member functions support the recommended behaviour for WM_MOUSEWHEEL, the wheel rotation message.

To take advantage of automatic scrolling, derive your view class from CScrollView instead of from CView. When the view is first created, if you want to calculate the size of the scrollable view based on the size of the document, call the SetScrollSizes member function from your override of either CView::OnInitialUpdate or CView::OnUpdate. (You must write your own code to query the size of the document. For an example, see Enhancing Views in Visual C++ Tutorials.)

The call to the SetScrollSizes member function sets the view’s mapping mode, the total dimensions of the scroll view, and the amounts to scroll horizontally and vertically. All sizes are in logical units. The logical size of the view is usually calculated from data stored in the document, but in some cases you may want to specify a fixed size. For examples of both approaches, see CScrollView::SetScrollSizes.

You specify the amounts to scroll horizontally and vertically in logical units. By default, if the user clicks a scroll bar shaft outside of the scroll box, CScrollView scrolls a “page.” If the user clicks a scroll arrow at either end of a scroll bar, CScrollView scrolls a “line.” By default, a page is 1/10 of the total size of the view; a line is 1/10 of the page size. Override these default values by passing custom sizes in the SetScrollSizes member function. For example, you might set the horizontal size to some fraction of the width of the total size and the vertical size to the height of a line in the current font.

Instead of scrolling, CScrollView can automatically scale the view to the current window size. In this mode, the view has no scroll bars and the logical view is stretched or shrunk to exactly fit the window’s client area. To use this scale-to-fit capability, call CScrollView::SetScaleToFitSize. (Call either SetScaleToFitSize or SetScrollSizes, but not both.)

Before the OnDraw member function of your derived view class is called, CScrollView automatically adjusts the viewport origin for the CPaintDC device-context object that it passes to OnDraw.

To adjust the viewport origin for the scrolling window, CScrollView overrides CView::OnPrepareDC. This adjustment is automatic for the CPaintDC device context that CScrollView passes to OnDraw, but you must call CScrollView::OnPrepareDC yourself for any other device contexts you use, such as a CClientDC. You can override CScrollView::OnPrepareDC to set the pen, background color, and other drawing attributes, but call the base class to do scaling.

Scroll bars can appear in three places relative to a view, as shown in the following cases:

  • Standard window-style scroll bars can be set for the view using the WS_HSCROLL and WS_VSCROLL styles.

  • Scroll-bar controls can also be added to the frame containing the view, in which case the framework forwards WM_HSCROLL and WM_VSCROLL messages from the frame window to the currently active view.

  • The framework also forwards scroll messages from a CSplitterWnd splitter control to the currently active splitter pane (a view). When placed in a CSplitterWnd with shared scroll bars, a CScrollView object will use the shared ones rather than creating its own.

For more information on using CScrollView, see Document/View Architecture Topics and Derived View Classes in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample DIBLOOK

See Also CView, CSplitterWnd


CScrollView Class Members

Operations

FillOutsideRect | Fills the area of a view outside the scrolling area.
GetDeviceScrollPosition | Gets the current scroll position in device units.
GetDeviceScrollSizes | Gets the current mapping mode, the total size, and the line and page sizes of the scrollable view. Sizes are in device units.
GetScrollPosition | Gets the current scroll position in logical units.
GetTotalSize | Gets the total size of the scroll view in logical units.
ResizeParentToFit | Causes the size of the view to dictate the size of its frame.
ScrollToPosition | Scrolls the view to a given point, specified in logical units.
SetScaleToFitSize | Puts the scroll view into scale-to-fit mode.
SetScrollSizes | Sets the scroll view’s mapping mode, total size, and horizontal and vertical scroll amounts.

Construction

CScrollView Constructs a CScrollView object.


CScrollView::CScrollView

CScrollView( );

Remarks

Constructs a CScrollView object. You must call either SetScrollSizes or SetScaleToFitSize before the scroll view is usable.

CScrollView Overview | Class Members | Hierarchy Chart

See Also CScrollView::SetScrollSizes, CScrollView::SetScaleToFitSize


CScrollView::FillOutsideRect

void FillOutsideRect( CDC* pDC, CBrush* pBrush );

Parameters

pDC

Device context in which the filling is to be done.

pBrush

Brush with which the area is to be filled.

Remarks

Call FillOutsideRect to fill the area of the view that appears outside of the scrolling area. Use FillOutsideRect in your scroll view’s OnEraseBkgnd handler function to prevent excessive background repainting.

Example

BOOL CScaleView::OnEraseBkgnd( CDC* pDC )
{
    CBrush br( GetSysColor( COLOR_WINDOW ) );
    FillOutsideRect( pDC, &br );
    return TRUE;                   // Erased
}

CScrollView Overview | Class Members | Hierarchy Chart

See Also CWnd::OnEraseBkgnd


CScrollView::GetDeviceScrollPosition

CPoint GetDeviceScrollPosition( ) const;

Return Value

The horizontal and vertical positions (in device units) of the scroll boxes as a CPoint object.

Remarks

Call GetDeviceScrollPosition when you need the current horizontal and vertical positions of the scroll boxes in the scroll bars. This coordinate pair corresponds to the location in the document to which the upper-left corner of the view has been scrolled. This is useful for offsetting mouse-device positions to scroll-view device positions.

GetDeviceScrollPosition returns values in device units. If you want logical units, use GetScrollPosition instead.

CScrollView Overview | Class Members | Hierarchy Chart

See Also CScrollView::GetScrollPosition


CScrollView::GetDeviceScrollSizes

void GetDeviceScrollSizes( int& nMapMode, SIZE& sizeTotal, SIZE& sizePage, SIZE& sizeLine ) const;

Parameters

nMapMode

Returns the current mapping mode for this view. For a list of possible values, see SetScrollSizes.

sizeTotal

Returns the current total size of the scroll view in device units.

sizePage

Returns the current horizontal and vertical amounts to scroll in each direction in response to a mouse click in a scroll-bar shaft. The cx member contains the horizontal amount. The cy member contains the vertical amount.

sizeLine

Returns the current horizontal and vertical amounts to scroll in each direction in response to a mouse click in a scroll arrow. The cx member contains the horizontal amount. The cy member contains the vertical amount.

Remarks

GetDeviceScrollSizes gets the current mapping mode, the total size, and the line and page sizes of the scrollable view. Sizes are in device units. This member function is rarely called.

CScrollView Overview | Class Members | Hierarchy Chart

See Also CScrollView::SetScrollSizes, CScrollView::GetTotalSize


CScrollView::GetScrollPosition

CPoint GetScrollPosition( ) const;

Return Value

The horizontal and vertical positions (in logical units) of the scroll boxes as a CPoint object.

Remarks

Call GetScrollPosition when you need the current horizontal and vertical positions of the scroll boxes in the scroll bars. This coordinate pair corresponds to the location in the document to which the upper-left corner of the view has been scrolled.

GetScrollPosition returns values in logical units. If you want device units, use GetDeviceScrollPosition instead.

CScrollView Overview | Class Members | Hierarchy Chart

See Also CScrollView::GetDeviceScrollPosition


CScrollView::GetTotalSize

CSize GetTotalSize( ) const;

Return Value

The total size of the scroll view in logical units. The horizontal size is in the cx member of the CSize return value. The vertical size is in the cy member.

Remarks

Call GetTotalSize to retrieve the current horizontal and vertical sizes of the scroll view.

CScrollView Overview | Class Members | Hierarchy Chart

See Also CScrollView::GetDeviceScrollSizes, CScrollView::SetScrollSizes


CScrollView::ResizeParentToFit

void ResizeParentToFit( BOOL bShrinkOnly = TRUE );

Parameters

bShrinkOnly

The kind of resizing to perform. The default value, TRUE, shrinks the frame window if appropriate. Scroll bars will still appear for large views or small frame windows. A value of FALSE causes the view always to resize the frame window exactly. This can be somewhat dangerous since the frame window could get too big to fit inside the multiple document interface (MDI) frame window or the screen.

Remarks

Call ResizeParentToFit to let the size of your view dictate the size of its frame window. This is recommended only for views in MDI child frame windows. Use ResizeParentToFit in the OnInitialUpdate handler function of your derived CScrollView class. For an example of this member function, see CScrollView::SetScrollSizes.

ResizeParentToFit assumes that the size of the view window has been set. If the view window size has not been set when ResizeParentToFit is called, you will get an assertion. To ensure that this does not happen, make the following call before calling ResizeParentToFit:

GetParentFrame()->RecalcLayout();

CScrollView Overview | Class Members | Hierarchy Chart

See Also CView::OnInitialUpdate, CScrollView::SetScrollSizes


CScrollView::ScrollToPosition

void ScrollToPosition( POINT pt );

Parameters

pt

The point to scroll to, in logical units. The x member must be a positive value (greater than or equal to 0, up to the total size of the view). The same is true for the y member when the mapping mode is MM_TEXT. The y member is negative in mapping modes other than MM_TEXT.

Remarks

Call ScrollToPosition to scroll to a given point in the view. The view will be scrolled so that this point is at the upper-left corner of the window. This member function must not be called if the view is scaled to fit.

CScrollView Overview | Class Members | Hierarchy Chart

See Also CScrollView::GetDeviceScrollPosition, CScrollView::SetScaleToFitSize, CScrollView::SetScrollSizes


CScrollView::SetScaleToFitSize

void SetScaleToFitSize( SIZE sizeTotal );

Parameters

sizeTotal

The horizontal and vertical sizes to which the view is to be scaled. The scroll view’s size is measured in logical units. The horizontal size is contained in the cx member. The vertical size is contained in the cy member. Both cx and cy must be greater than or equal to 0.

Remarks

Call SetScaleToFitSize when you want to scale the viewport size to the current window size automatically. With scroll bars, only a portion of the logical view may be visible at any time. But with the scale-to-fit capability, the view has no scroll bars and the logical view is stretched or shrunk to exactly fit the window’s client area. When the window is resized, the view draws its data at a new scale based on the size of the window.

You’ll typically place the call to SetScaleToFitSize in your override of the view’s OnInitialUpdate member function. If you do not want automatic scaling, call the SetScrollSizes member function instead.

SetScaleToFitSize can be used to implement a “Zoom to Fit” operation. Use SetScrollSizes to reinitialize scrolling.

SetScaleToFitSize assumes that the size of the view window has been set. If the view window size has not been set when SetScaleToFitSize is called, you will get an assertion. To ensure that this does not happen, make the following call before calling SetScaleToFitSize:

GetParentFrame()->RecalcLayout();

CScrollView Overview | Class Members | Hierarchy Chart

See Also CScrollView::SetScrollSizes, CView::OnInitialUpdate


CScrollView::SetScrollSizes

void SetScrollSizes( int nMapMode, SIZE sizeTotal, const SIZE& sizePage = sizeDefault, const SIZE& sizeLine = sizeDefault );

Parameters

nMapMode

The mapping mode to set for this view. Possible values include:

Mapping Mode | Logical Unit | Positive y-axis Extends...
MM_TEXT | 1 pixel | Downward
MM_HIMETRIC | 0.01 mm | Upward
MM_TWIPS | 1/1440 in | Upward
MM_HIENGLISH | 0.001 in | Upward
MM_LOMETRIC | 0.1 mm | Upward
MM_LOENGLISH | 0.01 in | Upward

All of these modes are defined by Windows. Two standard mapping modes, MM_ISOTROPIC and MM_ANISOTROPIC, are not used for CScrollView. The class library provides the SetScaleToFitSize member function for scaling the view to window size. Column three in the table above describes the coordinate orientation.

sizeTotal

The total size of the scroll view. The cx member contains the horizontal extent. The cy member contains the vertical extent. Sizes are in logical units. Both cx and cy must be greater than or equal to 0.

sizePage

The horizontal and vertical amounts to scroll in each direction in response to a mouse click in a scroll-bar shaft. The cx member contains the horizontal amount. The cy member contains the vertical amount.

sizeLine

The horizontal and vertical amounts to scroll in each direction in response to a mouse click in a scroll arrow. The cx member contains the horizontal amount. The cy member contains the vertical amount.

Remarks

Call SetScrollSizes when the view is about to be updated. Call it in your override of the OnUpdate member function to adjust scrolling characteristics when, for example, the document is initially displayed or when it changes size.

You will typically obtain size information from the view’s associated document by calling a document member function, perhaps called GetMyDocSize, that you supply with your derived document class. The following code shows this approach:

SetScrollSizes( nMapMode, GetDocument( )->GetMyDocSize( ) );

Alternatively, you might sometimes need to set a fixed size, as in the following code:

SetScrollSizes( nMapMode, CSize(100, 100) );

You must set the mapping mode to any of the Windows mapping modes except MM_ISOTROPIC or MM_ANISOTROPIC. If you want to use an unconstrained mapping mode, call the SetScaleToFitSize member function instead of SetScrollSizes.

Example

void CScaleView::OnUpdate( )
{
   // ...
   // Implement a GetDocSize( ) member function in
   // your document class; it returns a CSize.
   SetScrollSizes( MM_LOENGLISH, GetDocument( )->GetDocSize( ) );
   ResizeParentToFit( );   // Default bShrinkOnly argument
   // ...
}

CScrollView Overview | Class Members | Hierarchy Chart

See Also CScrollView::SetScaleToFitSize, CScrollView::GetDeviceScrollSizes, CScrollView::GetTotalSize


CSemaphore

An object of class CSemaphore represents a “semaphore” — a synchronization object that allows a limited number of threads in one or more processes to access a resource. A CSemaphore object maintains a count of the number of threads currently accessing a specified resource.

Semaphores are useful in controlling access to a shared resource that can only support a limited number of users. The current count of the CSemaphore object is the number of additional users allowed. When the count reaches zero, all attempts to use the resource controlled by the CSemaphore object will be inserted into a system queue and wait until they either time out or the count rises above 0. The maximum number of users who can access the controlled resource at one time is specified during construction of the CSemaphore object.

To use a CSemaphore object, construct the CSemaphore object when it is needed. Specify the name of the semaphore you wish to wait on, and that your application should initially own it. You can then access the semaphore when the constructor returns. Call CSyncObject::Unlock when you are done accessing the controlled resource.

An alternative method for using CSemaphore objects is to add a variable of type CSemaphore as a data member to the class you wish to control. During construction of the controlled object, call the constructor of the CSemaphore data member specifying the initial access count, maximum access count, name of the semaphore (if it will be used across process boundaries), and desired security attributes.

To access resources contolled by CSemaphore objects in this manner, first create a variable of either type CSingleLock or type CMultiLock in your resource’s access member function. Then call the lock object’s Lock member function (for example, CSingleLock::Lock). At this point, your thread will either gain access to the resource, wait for the resource to be released and gain access, or wait for the resource to be released and time out, failing to gain access to the resource. In any case, your resource has been accessed in a thread-safe manner. To release the resource, use the lock object’s Unlock member function (for example, CSingleLock::Unlock), or allow the lock object to fall out of scope.

Alternatively, you can create a CSemaphore object stand-alone, and access it explicitly before attempting to access the controlled resource. This method, while clearer to someone reading your source code, is more prone to error.

For more information on how to use CSemaphore objects, see the article Multithreading: How to Use the Synchronization Classes in Visual C++ Programmer’s Guide.

#include <afxmt.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MUTEXES


CSemaphore Class Members

Construction

CSemaphore Constructs a CSemaphore object.


CSemaphore::CSemaphore

CSemaphore( LONG lInitialCount = 1, LONG lMaxCount = 1, LPCTSTR pstrName = NULL, LPSECURITY_ATTRIBUTES lpsaAttributes = NULL );

Parameters

lInitialCount

The initial usage count for the semaphore. Must be greater than or equal to 0, and less than or equal to lMaxCount.

lMaxCount

The maximum usage count for the semaphore. Must be greater than 0.

pstrName

The name of the semaphore. Must be supplied if the semaphore will be accessed across process boundaries. If NULL, the object will be unnamed. If the name matches an existing semaphore, the constructor builds a new CSemaphore object which references the semaphore of that name. If the name matches an existing synchronization object that is not a semaphore, the construction will fail.

lpsaAttributes

Security attributes for the semaphore object. For a full description of this structure, see SECURITY_ATTRIBUTES in the Win32 Programmer’s Reference.

Remarks

Constructs a named or unnamed CSemaphore object. To access or release a CSemaphore object, create a CMultiLock or CSingleLock object and call its Lock and Unlock member functions.

CSemaphore Overview | Class Members | Hierarchy Chart

See Also CMutex, CEvent, CMultiLock, CSingleLock


CSharedFile

CSharedFile is the CMemFile-derived class that supports shared memory files. Memory files behave like disk files except that the file is stored in RAM rather than on disk. A memory file is useful for fast temporary storage or for transferring raw bytes or serialized objects between independent processes.

Shared memory files differ from other memory files in that memory for them is allocated with the GlobalAlloc Windows function. The CSharedFile class stores data in a globally allocated memory block (created using GlobalAlloc), and this memory block can be shared using DDE, the Clipboard, or other OLE/COM uniform data transfer operations, for example, using IDataObject.

GlobalAlloc returns an HGLOBAL handle rather than a pointer to memory, such as the pointer returned by malloc. The HGLOBAL handle is needed in certain applications. For example, to put data on the Clipboard you need an HGLOBAL handle.

Please note that CSharedFile does not use memory-mapped files, and the data cannot be directly shared between processes.

CSharedFile objects can automatically allocate their own memory or you can attach your own memory block to the CSharedFile object by calling CSharedFile::SetHandle. In either case, memory for growing the memory file automatically is allocated in nGrowBytes-sized increments if nGrowBytes is not zero.

For more information, see the article Files in MFC in the Visual C++ Programmer's Guide and File Handling in the Run-Time Library Reference.

#include <afxadv.h>

Class Members | Base Class | Hierarchy Chart

See Also CMemFile, GlobalAlloc, GlobalFree, GlobalRealloc


CSharedFile Class Members

Construction

CSharedFile Constructs a CSharedFile object.

Operations

Detach | Closes the shared memory file and returns the handle of its memory block.
SetHandle | Attaches the shared memory file to a memory block.


CSharedFile::CSharedFile

CSharedFile( UINT nAllocFlags = GMEM_DDESHARE | GMEM_MOVEABLE, UINT nGrowBytes = 4096 );

Parameters

nAllocFlags

Flags indicating how memory is to be allocated. See GlobalAlloc for a list of valid flag values.

nGrowBytes

The memory allocation increment in bytes.

Remarks

Constructs a CSharedFile object and allocates memory for it.

CSharedFile Overview | Class Members | Hierarchy Chart

See Also CSharedFile::Detach, CSharedFile::SetHandle


CSharedFile::Detach

HGLOBAL Detach( );

Return Value

The handle of the memory block that contains the contents of the memory file.

Remarks

Call this function to close the memory file and detach it from the memory block. You can reopen it by calling SetHandle, using the handle returned by Detach.

CSharedFile Overview | Class Members | Hierarchy Chart

See Also CSharedFile::CSharedFile, CSharedFile::SetHandle


CSharedFile::SetHandle

void SetHandle( HGLOBAL hGlobalMemory, BOOL bAllowGrow = TRUE );

Parameters

hGlobalMemory

Handle to the global memory to be attached to the CSharedFile.

bAllowGrow

Specifies whether the memory block is allowed to grow.

Remarks

Call this function to attach a block of global memory to the CSharedFile object. If bAllowGrow is nonzero, the size of the memory block is increased as necessary, for example, if an attempt is made to write more bytes to the file than were allocated for the memory block.

CSharedFile Overview | Class Members | Hierarchy Chart

See Also CSharedFile::CSharedFile, CSharedFile::Detach


CSingleDocTemplate

The CSingleDocTemplate class defines a document template that implements the single document interface (SDI). An SDI application uses the main frame window to display a document; only one document can be open at a time.

A document template defines the relationship between three types of classes:

  • A document class, which you derive from CDocument.

  • A view class, which displays data from the document class listed above. You can derive this class from CView, CScrollView, CFormView, or CEditView. (You can also use CEditView directly.)

  • A frame window class, which contains the view. For an SDI document template, you can derive this class from CFrameWnd; if you do not need to customize the behavior of the main frame window, you can use CFrameWnd directly without deriving your own class.

An SDI application typically supports one type of document, so it has only one CSingleDocTemplate object. Only one document can be open at a time.

You don’t need to call any member functions of CSingleDocTemplate except the constructor. The framework handles CSingleDocTemplate objects internally.

For more information on using CSingleDocTemplate, see Document Templates and the Document/View Creation Process in Visual C++ Programmer’s Guide.

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample DOCKTOOL

See Also CDocTemplate, CDocument, CFrameWnd, CMultiDocTemplate, CView, CWinApp


CSingleDocTemplate Class Members

Construction

CSingleDocTemplate Constructs a CSingleDocTemplate object.


CSingleDocTemplate::CSingleDocTemplate

CSingleDocTemplate( UINT nIDResource, CRuntimeClass* pDocClass, CRuntimeClass* pFrameClass, CRuntimeClass* pViewClass );

Parameters

nIDResource

Specifies the ID of the resources used with the document type. This may include menu, icon, accelerator table, and string resources.

The string resource consists of up to seven substrings separated by the ‘\n’ character (the ‘\n’ character is needed as a placeholder if a substring is not included; however, trailing ‘\n’ characters are not necessary); these substrings describe the document type. For information about the substrings, see CDocTemplate::GetDocString. This string resource is found in the application’s resource file. For example:

// MYCALC.RC
STRINGTABLE PRELOAD DISCARDABLE
BEGIN
    IDR_MAINFRAME "MyCalc Windows Application\nSheet\nWorksheet\n Worksheets (*.myc)\n.myc\nMyCalcSheet\n MyCalc Worksheet"
END

You can edit this string using the string editor; the entire string appears as a single entry in the String Editor, not as seven separate entries.

For more information about these resource types, see the String Editor (described in the Visual C++ User's Guide).

pDocClass

Points to the CRuntimeClass object of the document class. This class is a CDocument-derived class you define to represent your documents.

pFrameClass

Points to the CRuntimeClass object of the frame window class. This class can be a CFrameWnd-derived class, or it can be CFrameWnd itself if you want default behavior for your main frame window.

pViewClass

Points to the CRuntimeClass object of the view class. This class is a CView-derived class you define to display your documents.

Remarks

Constructs a CSingleDocTemplate object. Dynamically allocate a CSingleDocTemplate object and pass it to CWinApp::AddDocTemplate from the InitInstance member function of your application class.

Example

// example for CSingleDocTemplate::CSingleDocTemplate
BOOL CMyApp::InitInstance()
{
        // ...
        // Establish the document type
        // supported by the application

        AddDocTemplate( new CSingleDocTemplate( IDR_MAINFRAME,
                            RUNTIME_CLASS( CSheetDoc ),
                            RUNTIME_CLASS( CFrameWnd ),
                            RUNTIME_CLASS( CSheetView ) ) );

        // ...
}

CSingleDocTemplate Overview | Class Members | Hierarchy Chart

See Also CDocTemplate::GetDocString, CWinApp::AddDocTemplate, CWinApp::InitInstance, CRuntimeClass, RUNTIME_CLASS


CSingleLock

CSingleLock does not have a base class.

An object of class CSingleLock represents the access-control mechanism used in controlling access to a resource in a multithreaded program. In order to use the synchronization classes CSemaphore, CMutex, CCriticalSection, and CEvent, you must create either a CSingleLock or CMultiLock object to wait on and release the synchronization object. Use CSingleLock when you only need to wait on one object at a time. Use CMultiLock when there are multiple objects that you could use at a particular time.

To use a CSingleLock object, call its constructor inside a member function in the controlled resource’s class. Then call the IsLocked member function to determine if the resource is available. If it is, continue with the remainder of the member function. If the resource is unavailable, either wait for a specified amount of time for the resource to be released, or return failure. After use of the resource is complete, either call the Unlock function if the CSingleLock object is to be used again, or allow the CSingleLock object to be destroyed.

CSingleLock objects require the presence of an object derived from CSyncObject. This is usually a data member of the controlled resource’s class. For more information on how to use CSingleLock objects, see the article Multithreading: How to Use the Synchronization Classes in Visual C++ Programmer’s Guide.

#include <afxmt.h>

Class Members | Hierarchy Chart

See Also CMultiLock


CSingleLock Class Members

Construction

CSingleLock Constructs a CSingleLock object.

Methods

IsLocked | Determines if the object is locked.
Lock | Waits on a synchronization object.
Unlock | Releases a synchronization object.


CSingleLock::CSingleLock

CSingleLock( CSyncObject* pObject, BOOL bInitialLock = FALSE );

Parameters

pObject

Points to the synchronization object to be accessed. Cannot be NULL.

bInitialLock

Specifies whether to initially attempt to access the supplied object.

Remarks

Constructs a CSingleLock object. This function is generally called from within an access member function of the controlled resource.


CSingleLock::IsLocked

BOOL IsLocked( );

Return Value

Nonzero if the object is locked; otherwise 0.

Remarks

Determines if the object associated with the CSingleLock object is nonsignaled (unavailable).


CSingleLock::Lock

BOOL Lock( DWORD dwTimeOut = INFINITE );

Return Value

Nonzero if the function was successful; otherwise 0.

Parameters

dwTimeOut

Specifies the amount of time to wait for the synchronization object to be available (signaled). If INFINITE, Lock will wait until the object is signaled before returning.

Remarks

Call this function to gain access to the resource controlled by the synchronization object supplied to the CSingleLock constructor. If the synchronization object is signaled, Lock will return successfully and the thread now owns the object. If the synchronization object is nonsignaled (unavailable), Lock will wait for the synchronization object to become signaled up to the number of milliseconds specified in the dwTimeOut parameter. If the synchronization object did not become signaled in the specified amount of time, Lock returns failure.


CSingleLock::Unlock

BOOL Unlock( );

BOOL Unlock( LONG lCount, LPLONG lPrevCount = NULL );

Return Value

Nonzero if the function was successful; otherwise 0.

Parameters

lCount

Number of accesses to release. Must be greater than 0. If the specified amount would cause the object’s count to exceed its maximum, the count is not changed and the function returns FALSE.

lPrevCount

Points to a variable to receive the previous count of the synchronization object. If NULL, the previous count is not returned.

Remarks

Releases the synchronization object owned by CSingleLock. This function is called by CSingleLock’s destructor.

If you need to release more than one access count of a semaphore, use the second form of Unlock and specify the number of accesses to release.


CSize

The CSize class is similar to the Windows SIZE structure, which implements a relative coordinate or position.

Note This class is derived from the SIZE structure. This means you can pass a CSize in a parameter that calls for a SIZE and that the data members of the SIZE structure are accessible data members of CSize.

The cx and cy members of SIZE (and CSize) are public. In addition, CSize implements member functions to manipulate the SIZE structure.

#include <afxwin.h>

Class Members | Hierarchy Chart

Sample MFC Sample MDI

See Also CRect, CPoint


CSize Class Members

Construction

CSize Constructs a CSize object.

Operators

operator == | Checks for equality between CSize and a size.
operator != | Checks for inequality between CSize and a size.
operator += | Adds a size to CSize.
operator –= | Subtracts a size from CSize.

Operators Returning CSize Values

operator + | Adds two sizes.
operator – | Subtracts two sizes.


CSize::CSize

CSize( );

CSize( int initCX, int initCY );

CSize( SIZE initSize );

CSize( POINT initPt );

CSize( DWORD dwSize );

Parameters

initCX

Sets the cx member for the CSize.

initCY

Sets the cy member for the CSize.

initSize

SIZE structure or CSize object used to initialize CSize.

initPt

POINT structure or CPoint object used to initialize CSize.

dwSize

DWORD used to initialize CSize. The low-order word is the cx member and the high-order word is the cy member.

Remarks

Constructs a CSize object. If no arguments are given, cx and cy members are not initialized.


CSize::operator ==

BOOL operator ==( SIZE size ) const;

Remarks

Checks for equality between two sizes. Returns nonzero if the sizes are equal, otherwize 0.

CSize Overview | Class Members | Hierarchy Chart

See Also CSize::operator !=


CSize::operator !=

BOOL operator !=( SIZE size ) const;

Remarks

Checks for inequality between two sizes. Returns nonzero if the sizes are not equal, otherwise 0.

CSize Overview | Class Members | Hierarchy Chart

See Also CSize::operator ==


CSize::operator +=

void operator +=( SIZE size );

Remarks

Adds a size to this Csize.

CSize Overview | Class Members | Hierarchy Chart

See Also CSize::operator +


CSize::operator -=

void operator -=( SIZE size );

Remarks

Subtracts a size from this CSize.

CSize Overview | Class Members | Hierarchy Chart

See Also CSize::operator -


CSize::operator +

CSize operator +( SIZE size ) const;

CPoint operator +( POINT point ) const;

CRect operator +( const RECT* lpRect ) const;

Remarks

These operators add this CSize value to the value of parameter. See the following descriptions of the individual operators:

  • operator +( size ) This operation adds two CSize values.

  • operator +( point ) This operation offsets (moves) a POINT (or CPoint) value by this CSize value. The cx and cy members of this CSize value are added to the x and y data members of the POINT value. It is analogous to the version of CPoint::operator + that takes a SIZE parameter.

  • operator +( lpRect ) This operation offsets (moves) a RECT (or CRect) value by this CSize value. The cx and cy members of this CSize value are added to the left, top, right, and bottom data members of the RECT value. It is analogous to the version of CRect::operator + that takes a SIZE parameter.

CSize Overview | Class Members | Hierarchy Chart

See Also CPoint::operator +, CRect::operator +


CSize::operator -

CSize operator -( SIZE size ) const;

CPoint operator -( POINT point ) const;

CRect operator -( const RECT* lpRect ) const;

CSize operator -( ) const;

Remarks

The first three of these operators subtract this CSize value to the value of parameter. The fourth operator, the unary minus, changes the sign of the CSize value. See the following descriptions of the individual operators:

  • operator -( size ) This operation subtracts two CSize values.

  • operator -( point ) This operation offsets (moves) a POINT or CPoint value by the additive inverse of this CSize value. The cx and cy of this CSize value are subtracted from the x and y data members of the POINT value. It is analogous to the version of CPoint::operator - that takes a SIZE parameter.

  • operator -( lpRect ) This operation offsets (moves) a RECT or CRect value by the additive inverse of this CSize value. The cx and cy members of this CSize value are subtracted from the left, top, right, and bottom data members of the RECT value. It is analogous to the version of CRect::operator - that takes a SIZE parameter.

  • operator -( ) This operation returns the additive inverse of this CSize value.

CSize Overview | Class Members | Hierarchy Chart

See Also CPoint::operator -, CRect::operator -


CSliderCtrl

A “slider control” (also known as a trackbar) is a window containing a slider and optional tick marks. When the user moves the slider, using either the mouse or the direction keys, the control sends notification messages to indicate the change.

Slider controls 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 slider control to allow the user to set the repeat rate of the keyboard by moving the slider to a given tick mark.

The CSliderCtrl class provides the functionality of the Windows common slider control. This control (and therefore the CSliderCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

The slider moves in increments that you specify when you create it. For example, if you specify that the slider should have a range of five, the slider can only occupy six positions: a position at the left side of the slider control and one position for each increment in the range. Typically, each of these positions is identified by a tick mark.

You create a slider by using the constructor and the Create member function of CSliderCtrl. Once you have created a slider control, you can use member functions in CSliderCtrl to change many of its properties. Changes that you can make include setting the minimum and maximum positions for the slider, drawing tick marks, setting a selection range, and repositioning the slider.

For more information on using CSliderCtrl, see Control Topics and Using CSliderCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CMNCTRL2 | MFC Sample FIRE

See Also CProgressCtrl


CSliderCtrl Class Members

Construction
Attributes
Operations

Construction

CSliderCtrl | Constructs a CSliderCtrl object.
Create | Creates a slider control and attaches it to a CSliderCtrl object.

Attributes

GetLineSize | Retrieves the line size of a slider control.
SetLineSize | Sets the line size of a slider control.
GetPageSize | Retrieves the page size of a slider control.
SetPageSize | Sets the page size of a slider control.
GetRangeMax | Retrieves the maximum position for a slider.
GetRangeMin | Retrieves the minimum position for a slider.
GetRange | Retrieves the minimum and maximum positions for a slider.
SetRangeMin | Sets the minimum position for a slider.
SetRangeMax | Sets the maximum position for a slider.
SetRange | Sets the minimum and maximum positions for a slider.
GetSelection | Retrieves the range of the current selection.
SetSelection | Sets the range of the current selection.
GetChannelRect | Retrieves the size of the slider control’s channel.
GetThumbRect | Retrieves the size of the slider control’s thumb.
GetPos | Retrieves the current position of the slider.
SetPos | Sets the current position of the slider.
GetNumTics | Retrieves the number of tick marks in a slider control.
GetTicArray | Retrieves the array of tick mark positions for a slider control.
GetTic | Retrieves the position of the specified tick mark.
GetTicPos | Retrieves the position of the specified tick mark, in client coordinates.
SetTic | Sets the position of the specified tick mark.
SetTicFreq | Sets the frequency of tick marks per slider control increment.
GetBuddy | Retrieves the handle to a slider control buddy window at a given location.
SetBuddy | Assigns a window as the buddy window for a slider control.
GetToolTips | Retrieves the handle to the tooltip control assigned to the slider control, if any.
SetToolTips | Assigns a tooltip control to a slider control.
SetTipSide | Positions a tooltip control used by a trackbar control.

Operations

ClearSel | Clears the current selection in a slider control.
VerifyPos | Verifies that the position of a slider control is between the minimum and maximum values.
ClearTics | Removes the current tick marks from a slider control.


CSliderCtrl::ClearSel

void ClearSel( BOOL bRedraw = FALSE );

Parameters

bRedraw

Redraw flag. If this parameter is TRUE, the slider is redrawn after the selection is cleared; otherwise the slider is not redrawn.

Remarks

Call this function to clear the current selection in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetSelection, CSliderCtrl::SetSelection


CSliderCtrl::ClearTics

void ClearTics( BOOL bRedraw = FALSE );

Parameters

bRedraw

Redraw flag. If this parameter is TRUE, the slider is redrawn after the tick marks are cleared; otherwise the slider is not redrawn.

Remarks

Call this function to remove the current tick marks from a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetTicArray, CSliderCtrl::GetTic, CSliderCtrl::GetNumTics


CSliderCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if initialization was successful; otherwise 0.

Parameters

dwStyle

Specifies the slider control’s style. Apply any combination of slider control styles to the control.

rect

Specifies the slider control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the slider control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the slider control’s ID.

Remarks

You construct a CSliderCtrl in two steps. First call the constructor, then call Create, which creates the slider control and attaches it to the CSliderCtrl object.

Slider controls can have either a vertical or horizontal orientation. They can have tick marks on either side, both sides, or neither. They can also be used to specify a range of consecutive values. These properties are controlled by using slider styles, which you specify when you create the slider control:

  • TBS_HORZ Orients the slider horizontally. This is the default orientation.

  • TBS_VERT Orients the slider vertically. If you do not specify an orientation, the slider is oriented horizontally.

  • TBS_AUTOTICKS Creates a slider that has a tick mark for each increment in its range of values. These tick marks are added automatically when an application calls the SetRange member function. You cannot use the SetTic and SetTicFreq member functions to specify the position of the tick marks if you use this style. Use the ClearTics member function instead.

  • TBS_NOTICKS Creates a slider that does not display tick marks.

  • TBS_BOTTOM Displays tick marks on the bottom of a horizontal slider. Can be used with the TBS_TOP style to display tick marks on both sides of the slider control.

  • TBS_TOP Displays tick marks on the top of a horizontal slider. Can be used with the TBS_BOTTOM style to display tick marks on both sides of the slider control.

  • TBS_RIGHT Displays tick marks on the right of a vertical slider. Can be used with the TBS_LEFT style to display tick marks on both sides of the slider control.

  • TBS_LEFT Displays tick marks on the left of a vertical slider. Can be used with the TBS_RIGHT style to display tick marks on both sides of the slider control.

  • TBS_BOTH Displays tick marks on both sides of the slider in any orientation.

  • TBS_ENABLESELRANGE Displays a selection range. When a slider control has this style, the tick marks at the starting and ending positions of a selection range are displayed as triangles (instead of vertical dashes) and the selection range is highlighted. For example, selection ranges might be useful in a simple scheduling application. The user could select a range of tick marks corresponding to hours in a day to identify a scheduled meeting time.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::CSliderCtrl


CSliderCtrl::CSliderCtrl

CSliderCtrl( );

Remarks

Constructs a CSliderCtrl object.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::Create


CSliderCtrl::GetBuddy

CWnd* GetBuddy( BOOL fLocation = TRUE ) const;

Return Value

A pointer to a CWnd object that is the buddy window at the location specified by fLocation, or NULL if no buddy window exists at that location.

Parameters

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 slider. If the slider control uses the TBS_VERT style, the message will retrieve the buddy above the slider.

  • FALSE Retrieves the handle to the buddy to the right of the slider. If the slider control uses the TBS_VERT style, the message will retrieve the buddy below the slider.

Remarks

This member function implements the behavior of the Win32 message TBM_GETBUDDY, as described in the Platform SDK.

For a description of the slider control styles, see Trackbar Control Styles in the Platform SDK.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetBuddy


CSliderCtrl::GetChannelRect

void GetChannelRect( LPRECT lprc ) const;

Parameters

lprc

A pointer to a CRect object that contains the size and position of the channel’s bounding rectangle when the function returns.

Remarks

Call this function to retrieve the size and position of the bounding rectangle for a slider control’s channel. The channel is the area over which the slider moves and which contains the highlight when a range is selected.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetThumbRect


CSliderCtrl::GetLineSize

int GetLineSize( ) const;

Return Value

The size of a line for the slider control.

Remarks

Call this function to retrieve the size of the line for a slider control. The line size affects how much the slider moves for the TB_LINEUP and TB_LINEDOWN notifications. The default setting for the line size is 1.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetLineSize, CSliderCtrl::GetPageSize


CSliderCtrl::GetNumTics

UINT GetNumTics( ) const;

Return Value

The number of tick marks in the slider control.

Remarks

Call this function to retrieve the number of tick marks in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetTicArray, CSliderCtrl::GetTic, CSliderCtrl::GetTicPos, CSliderCtrl::SetTicFreq, CSliderCtrl::ClearTics


CSliderCtrl::GetPageSize

int GetPageSize( ) const;

Return Value

The size of a page for the slider control.

Remarks

Call this function to retrieve the size of the page for a slider control. The page size affects how much the slider moves for the TB_PAGEUP and TB_PAGEDOWN notifications.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetLineSize, CSliderCtrl::SetPageSize


CSliderCtrl::GetPos

int GetPos( ) const;

Return Value

The current position.

Remarks

Call this function to retrieve the current position of the slider in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetPos, CSliderCtrl::GetTicPos


CSliderCtrl::GetRange

void GetRange( int& nMin, int& nMax ) const;

Parameters

nMin

Reference to an integer that receives the minimum position.

nMax

Reference to an integer that receives the maximum position.

Remarks

Call this function to retrieve the maximum and minimum positions for the slider in a slider control. This function copies the values into the integers referenced by nMin and nMax.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetRangeMin, CSliderCtrl::GetRangeMax, CSliderCtrl::SetRange


CSliderCtrl::GetRangeMax

int GetRangeMax( ) const;

Return Value

The control’s maximum position.

Remarks

Call this function to retrieve the maximum position for the slider in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetRangeMin, CSliderCtrl::GetRange, CSliderCtrl::SetRange


CSliderCtrl::GetRangeMin

int GetRangeMin( ) const;

Return Value

The control’s minimum position.

Remarks

Call this function to retrieve the minimum position for the slider in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetRange, CSliderCtrl::GetRangeMax, CSliderCtrl::SetRange


CSliderCtrl::GetSelection

void GetSelection( int& nMin, int& nMax ) const;

Parameters

nMin

Reference to an integer that receives the starting position of the current selection.

nMax

Reference to an integer that receives the ending position of the current selection.

Remarks

Call this function to retrieve the starting and ending positions of the current selection in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetSelection, CSliderCtrl::ClearSel


CSliderCtrl::GetThumbRect

void GetThumbRect( LPRECT lprc ) const;

Parameters

lprc

A pointer to a CRect object that contains the bounding rectangle for the slider when the function returns.

Remarks

Call this function to retrieve the size and position of the bounding rectangle for the slider (thumb) in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetChannelRect


CSliderCtrl::GetTic

int GetTic( int nTic ) const;

Return Value

The position of the specified tick mark or – 1 if nTic does not specify a valid index.

Parameters

nTic

Zero-based index identifying a tick mark.

Remarks

Call this function to retrieve the position of a tick mark in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetTic, CSliderCtrl::GetTicArray, CSliderCtrl::GetTicPos, CSliderCtrl::SetTicFreq, CSliderCtrl::ClearTics


CSliderCtrl::GetTicArray

DWORD* GetTicArray( ) const;

Return Value

The address of the array containing tick mark positions for the slider control.

Remarks

Call this function to retrieve the address of the array containing the positions of tick marks for a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetTic, CSliderCtrl::GetTic, CSliderCtrl::GetTicPos, CSliderCtrl::SetTicFreq, CSliderCtrl::ClearTics


CSliderCtrl::GetTicPos

int GetTicPos( int nTic ) const;

Return Value

The physical position, in client coordinates, of the specified tick mark or – 1 if nTic does not specify a valid index.

Parameters

nTic

Zero-based index identifying a tick mark.

Remarks

Call this function to retrieve the current physical position of a tick mark in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetTic, CSliderCtrl::GetTic, CSliderCtrl::SetTicFreq, CSliderCtrl::ClearTics


CSliderCtrl::GetToolTips

CToolTipCtrl* GetToolTips( ) const;

Return Value

A pointer to a CToolTipCtrl object, or NULL if tooltips are not in use. If the slider control does not use the TBS_TOOLTIPS style, the return value is NULL.

Remarks

This member function implements the behavior of the Win32 message TBM_GETTOOLTIPS, as described in the Platform SDK.

Note that this member function returns a CToolTipCtrl object instead of a handle to a control.

For a description of the slider control styles, see Trackbar Control Styles in the Platform SDK.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetToolTips


CSliderCtrl::SetBuddy

CWnd* SetBuddy( CWnd* pWndBuddy, BOOL fLocation = TRUE );

Return Value

A pointer to a CWnd object that was previously assigned to the slider control at that location.

Parameters

pWndBuddy

A pointer to a CWnd object that will be set as the slider control's buddy.

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.

Remarks

This member function implements the behavior of the Win32 message TBM_SETBUDDY, as described in the Platform SDK.

Note that this member function uses pointers to CWnd objects, rather than window handles for both its return value and parameter.

For a description of the slider control styles, see Trackbar Control Styles in the Platform SDK.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetBuddy


CSliderCtrl::SetLineSize

int SetLineSize( int nSize );

Return Value

The previous line size.

Parameters

nSize

The new line size of the slider control.

Remarks

Call this function to set the size of the line for a slider control. The line size affects how much the slider moves for the TB_LINEUP and TB_LINEDOWN notifications.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetLineSize, CSliderCtrl::SetPageSize


CSliderCtrl::SetPageSize

int SetPageSize( int nSize );

Return Value

The previous page size.

Parameters

nSize

The new page size of the slider control.

Remarks

Call this function to set the size of the page for a slider control. The page size affects how much the slider moves for the TB_PAGEUP and TB_PAGEDOWN notifications.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetPageSize, CSliderCtrl::GetLineSize


CSliderCtrl::SetPos

void SetPos( int nPos );

Parameters

nPos

Specifies the new slider position.

Remarks

Call this function to set the current position of the slider in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetPos, CSliderCtrl::SetTic, CSliderCtrl::VerifyPos


CSliderCtrl::SetRange

void SetRange( int nMin, int nMax, BOOL bRedraw = FALSE );

Parameters

nMin

Minimum position for the slider.

nMax

Maximum position for the slider.

bRedraw

The redraw flag. If this parameter is TRUE, the slider is redrawn after the range is set; otherwise the slider is not redrawn.

Remarks

Call this function to set the range (minimum and maximum positions) for the slider in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetRange, CSliderCtrl::SetRangeMax, CSliderCtrl::SetRangeMin


CSliderCtrl::SetRangeMax

void SetRangeMax( int nMax, BOOL bRedraw = FALSE );

Parameters

nMax

Maximum position for the slider.

bRedraw

The redraw flag. If this parameter is TRUE, the slider is redrawn after the range is set; otherwise the slider is not redrawn.

Remarks

Call this function to set the maximum range for the slider in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetRange, CSliderCtrl::GetRangeMax, CSliderCtrl::SetRangeMin


CSliderCtrl::SetRangeMin

void SetRangeMin( int nMin, BOOL bRedraw = FALSE );

Parameters

nMin

Minimum position for the slider.

bRedraw

The redraw flag. If this parameter is TRUE, the slider is redrawn after the range is set; otherwise the slider is not redrawn.

Remarks

Call this function to set the minimum range for the slider in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::SetRange, CSliderCtrl::GetRangeMin, CSliderCtrl::SetRangeMax


CSliderCtrl::SetSelection

void SetSelection( int nMin, int nMax );

Parameters

nMin

Starting position for the slider.

nMax

Ending position for the slider.

Remarks

Call this function to set the starting and ending positions for the current selection in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetSelection, CSliderCtrl::ClearSel


CSliderCtrl::SetTic

BOOL SetTic( int nTic );

Return Value

Nonzero if the tick mark is set; otherwise 0.

Parameters

nTic

Position of the tick mark. This parameter must specify a positive value.

Remarks

Call this function to set the position of a tick mark in a slider control.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetTic, CSliderCtrl::GetTicArray, CSliderCtrl::GetTicPos, CSliderCtrl::SetTicFreq, CSliderCtrl::ClearTics


CSliderCtrl::SetTicFreq

void SetTicFreq( int nFreq );

Parameters

nFreq

Frequency of the tick marks.

Remarks

Call this function to set the frequency with which tick marks are displayed in a slider. For example, if the frequency is set to 2, a tick mark is displayed for every other increment in the slider’s range. The default setting for the frequency is 1 (that is, every increment in the range is associated with a tick mark).

You must create the control with the TBS_AUTOTICKS style to use this function. For more information, see CSliderCtrl::Create.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::Create, CSliderCtrl::SetTic, CSliderCtrl::GetTicArray


CSliderCtrl::SetTipSide

int SetTipSide( int nLocation );

Return Value

A value that represents the tooltip control's previous location. The return value equals one of the possible values for nLocation.

Parameters

nLocation

Value representing the location at which to display the tooltip control. For a list of possible values, see the Win32 message TBM_SETTIPSIDE, as described in the Platform SDK.

Remarks

This member function implements the behavior of the Win32 message TBM_SETTIPSIDE, as described in the Platform SDK.

Slider controls that use the TBS_TOOLTIPS style display tooltips. For a description of the slider control styles, see Trackbar Control Styles in the Platform SDK.


CSliderCtrl::SetToolTips

void SetToolTips( CToolTipCtrl* pWndTip );

Parameters

pWndTip

A pointer to a CToolTipCtrl object containing the tooltips to use with the slider control.

Remarks

This member function implements the behavior of the Win32 message TBM_SETTOOLTIPS, as described in the Platform SDK.

When a slider 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. For a description of the slider control styles, see Trackbar Control Styles in the Platform SDK.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetToolTips


CSliderCtrl::VerifyPos

void VerifyPos( );

Remarks

Call this function to verify that the current position of the slider in a slider control is between the minimum and maximum values.

CSliderCtrl Overview | Class Members | Hierarchy Chart

See Also CSliderCtrl::GetRange, CSliderCtrl::SetPos, CSliderCtrl::GetTicPos


CSocket

Class CSocket derives from CAsyncSocket and inherits its encapsulation of the Windows Sockets API. A CSocket object represents a higher level of abstraction of the Windows Sockets API than that of a CAsyncSocket object. CSocket works with classes CSocketFile and CArchive to manage the sending and receiving of data.

A CSocket object also provides blocking, which is essential to the synchronous operation of CArchive. Blocking functions, such as Receive, Send, ReceiveFrom, SendTo, and Accept (all inherited from CAsyncSocket), do not return a WSAEWOULDBLOCK error in CSocket. Instead, these functions wait until the operation completes. Additionally, the original call will terminate with the error WSAEINTR if CancelBlockingCall is called while one of these functions is blocking.

To use a CSocket object, call the constructor, then call Create to create the underlying SOCKET handle (type SOCKET). The default parameters of Create create a stream socket, but if you are not using the socket with a CArchive object, you can specify a parameter to create a datagram socket instead, or bind to a specific port to create a server socket. Connect to a client socket using Connect on the client side and Accept on the server side. Then create a CSocketFile object and associate it to the CSocket object in the CSocketFile constructor. Next, create a CArchive object for sending and one for receiving data (as needed), then associate them with the CSocketFile object in the CArchive constructor. When communications are complete, destroy the CArchive, CSocketFile, and CSocket objects. The SOCKET data type is described in the article Windows Sockets: Background in Visual C++ Programmer’s Guide.

For more information, see Windows Sockets in MFC, Windows Sockets: Using Sockets with Archives, Windows Sockets: How Sockets with Archives Work, Windows Sockets: Sequence of Operations, Windows Sockets: Example of Sockets Using Archives, and related articles in Visual C++ Programmer’s Guide. Also see Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

#include <afxsock.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample CHATSRVR

See Also CAsyncSocket, CSocketFile


CSocket Class Members

Construction

CSocket | Constructs a CSocket object.
Create | Creates a socket.

Attributes

IsBlocking | Determines whether a blocking call is in progress.
FromHandle | Returns a pointer to a CSocket object, given a SOCKET handle.
Attach | Attaches a SOCKET handle to a CSocket object.

Operations

CancelBlockingCall Cancels a blocking call that is currently in progress.

Overridables

OnMessagePending Called to process pending messages while waiting for a blocking call to complete.


CSocket::Attach

BOOL Attach( SOCKET hSocket );

Return Value

Nonzero if the function is successful.

Parameters

hSocket

Contains a handle to a socket.

Remarks

Call this member function to attach the hSocket handle to a CSocket object. The SOCKET handle is stored in the object’s m_hSocket data member.

For more information, see Windows Sockets: Using Sockets with Archives and related articles in Visual C++ Programmer’s Guide. Also see Windows Sockets Programming Considerations in the Win32 SDK documentation.

CSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Attach


CSocket::CancelBlockingCall

void CancelBlockingCall( );

Remarks

Call this member function to cancel a blocking call currently in progress. This function cancels any outstanding blocking operation for this socket. The original blocking call will terminate as soon as possible with the error WSAEINTR.

In the case of a blocking Connect operation, the Windows Sockets implementation will terminate the blocking call as soon as possible, but it may not be possible for the socket resources to be released until the connection has completed (and then been reset) or timed out. This is likely to be noticeable only if the application immediately tries to open a new socket (if no sockets are available), or to connect to the same peer.

Canceling any operation other than Accept can leave the socket in an indeterminate state. If an application cancels a blocking operation on a socket, the only operation that the application can depend on being able to perform on the socket is a call to Close, although other operations may work on some Windows Sockets implementations. If you desire maximum portability for your application, you must be careful not to depend on performing operations after a cancel.

For more information, see Windows Sockets: Using Sockets with Archives and related articles in Visual C++ Programmer’s Guide. Also see Windows Sockets Programming Considerations in the Win32 SDK documentation.

CSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Accept, CAsyncSocket::Close, CAsyncSocket::Connect, CSocket::IsBlocking, ::WSASetBlockingHook


CSocket::Create

BOOL Create( UINT nSocketPort = 0, int nSocketType = SOCK_STREAM, LPCTSTR lpszSocketAddress = NULL );

Return Value

Nonzero if the function is successful; otherwise 0, and a specific error code can be retrieved by calling GetLastError.

Parameters

nSocketPort

A particular port to be used with the socket, or 0 if you want MFC to select a port.

nSocketType

SOCK_STREAM or SOCK_DGRAM.

lpszSockAddress

A pointer to a string containing the network address of the connected socket, a dotted number such as "128.56.22.8".

Remarks

Call the Create member function after constructing a socket object to create the Windows socket and attach it. Create then calls Bind to bind the socket to the specified address. The following socket types are supported:

  • SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams. Uses Transmission Control Protocol (TCP) for the Internet address family.

  • SOCK_DGRAM Supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. Uses User Datagram Protocol (UDP) for the Internet address family. To use this option, you must not use the socket with a CArchive object.

Note The Accept member function takes a reference to a new, empty CSocket object as its parameter. You must construct this object before you call Accept. Keep in mind that if this socket object goes out of scope, the connection closes. Do not call Create for this new socket object.

For more information about stream and datagram sockets, see the articles Windows Sockets: Background, Windows Sockets: Ports and Socket Addresses, and Windows Sockets: Using Sockets with Archives in Visual C++ Programmer’s Guide and Windows Sockets Programming Considerations in the Win32 SDK documentation.

CSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Create, CAsyncSocket::Bind


CSocket::CSocket

CSocket( );

Remarks

Constructs a CSocket object. After construction, you must call the Create member function.

For more information, see Windows Sockets: Using Sockets with Archives and related articles in Visual C++ Programmer’s Guide. Also see Windows Sockets Programming Considerations in the Win32 SDK documentation.

CSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::Create


CSocket::FromHandle

static CSocket* PASCAL FromHandle( SOCKET hSocket );

Return Value

A pointer to a CSocket object, or NULL if there is no CSocket object attached to hSocket.

Parameters

hSocket

Contains a handle to a socket.

Remarks

Returns a pointer to a CSocket object. When given a SOCKET handle, if a CSocket object is not attached to the handle, the member function returns NULL and does not create a temporary object.

For more information, see Windows Sockets: Using Sockets with Archives and related articles in Visual C++ Programmer’s Guide. Also see Windows Sockets Programming Considerations in the Win32 SDK documentation.

CSocket Overview | Class Members | Hierarchy Chart

See Also CAsyncSocket::FromHandle


CSocket::IsBlocking

BOOL IsBlocking( );

Return Value

Nonzero if the socket is blocking; otherwise 0.

Remarks

Call this member function to determine if a blocking call is in progress.

For more information, see Windows Sockets: Using Sockets with Archives and related articles in Visual C++ Programmer’s Guide. Also see Windows Sockets Programming Considerations in the Win32 SDK documentation.

CSocket Overview | Class Members | Hierarchy Chart

See Also CSocket::CancelBlockingCall


CSocket::OnMessagePending

virtual BOOL OnMessagePending( );

Return Value

Nonzero if the message was handled; otherwise 0.

Remarks

Override this member function to look for particular messages from Windows and respond to them in your socket. This is an advanced overridable.

The framework calls OnMessagePending while the socket is pumping Windows messages to give you an opportunity to deal with messages of interest to your application. For examples of how you might use OnMessagePending, see the article Windows Sockets: Deriving from Socket Classes in Visual C++ Programmer’s Guide.

For more information, see Windows Sockets: Using Sockets with Archives and related articles in Visual C++ Programmer’s Guide. Also see Windows Sockets Programming Considerations in the Win32 SDK documentation.

CSocket Overview | Class Members | Hierarchy Chart

See Also CSocket::CancelBlockingCall, CSocket::IsBlocking


CSocketFile

A CSocketFile object is a CFile object used for sending and receiving data across a network via Windows Sockets. You can attach the CSocketFile object to a CSocket object for this purpose. You also can — and usually do — attach the CSocketFile object to a CArchive object to simplify sending and receiving data using MFC serialization.

To serialize (send) data, you insert it into the archive, which calls CSocketFile member functions to write data to the CSocket object. To deserialize (receive) data, you extract from the archive. This causes the archive to call CSocketFile member functions to read data from the CSocket object.

Tip Besides using CSocketFile as described here, you can use it as a stand-alone file object, just as you can with CFile, its base class. You can also use CSocketFile with any archive-based MFC serialization functions. Because CSocketFile does not support all of CFile’s functionality, some default MFC serialize functions are not compatible with CSocketFile. This is particularly true of the CEditView class. You should not try to serialize CEditView data through a CArchive object attached to a CSocketFile object using CEditView::SerializeRaw; use CEditView::Serialize instead. The SerializeRaw function expects the file object to have functions, such as Seek, that CSocketFile does not have.

For more information, see Windows Sockets in MFC, Windows Sockets: Using Sockets with Archives, and related articles in Visual C++ Programmer’s Guide, as well as Overview of Windows Sockets 2 and Windows Sockets Programming Considerations in the Win32 SDK documentation.

#include <afxsock.h>

Class Members | Base Class | Hierarchy Chart

See Also CAsyncSocket, CSocket


CSocketFile Class Members

Construction

CSocketFile Constructs a CSocketFile object.


CSocketFile::CSocketFile

CSocketFile( CSocket* pSocket, BOOL bArchiveCompatible = TRUE );

Parameters

pSocket

The socket to attach to the CSocketFile object.

bArchiveCompatible

Specifies whether the file object is for use with a CArchive object. Pass FALSE only if you want to use the CSocketFile object in a stand-alone manner as you would a stand-alone CFile object, with certain limitations. This flag changes how the CArchive object attached to the CSocketFile object manages its buffer for reading.

Remarks

Constructs a CSocketFile object. The object’s destructor disassociates itself from the socket object when the object goes out of scope or is deleted.

Note A CSocketFile can also be used as a (limited) file without a CArchive object. By default, the CSocketFile constructor’s bArchiveCompatible parameter is TRUE. This specifies that the file object is for use with an archive. To use the file object without an archive, pass FALSE in the bArchiveCompatible parameter.

In its “archive compatible” mode, a CSocketFile object provides better performance and reduces the danger of a “deadlock.” A deadlock occurs when both the sending and receiving sockets are waiting on each other, or for a common resource. This situation might occur if the CArchive object worked with the CSocketFile the way it does with a CFile object. With CFile, the archive can assume that if it receives fewer bytes than it requested, the end of file has been reached.

With CSocketFile, however, data is message based; the buffer can contain multiple messages, so receiving fewer than the number of bytes requested does not imply end of file. The application does not block in this case as it might with CFile, and it can continue reading messages from the buffer until the buffer is empty. The CArchive::IsBufferEmpty function is useful for monitoring the state of the archive’s buffer in such a case.

For more information on the use of CSocketFile, see the articles Windows Sockets: Using Sockets with Archives and Windows Sockets: Example of Sockets Using Archives in Visual C++ Programmer’s Guide.

CSocketFile Overview | Class Members | Hierarchy Chart

See Also CFile::CFile, CFile::Read


CSpinButtonCtrl

A “spin button control” (also known as 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 a spin button control is called its current position. A spin button control is most often used with a companion control, called a “buddy window.”

The CSpinButtonCtrl class provides the functionality of the Windows common spin button control. This control (and therefore the CSpinButtonCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

To the user, a spin button control and its buddy window often look like a single control. You can specify that a spin button control automatically position itself next to its buddy window, and that it automatically set the caption of the buddy window to its current position. You can use a spin button control with an edit control to prompt the user for numeric input.

Clicking the up arrow moves the current position toward the maximum, and clicking the down arrow moves the current position toward the minimum. By default, the minimum is 100 and the maximum is 0. Any time the minimum setting is greater than the maximum setting (for example, when the default settings are used), clicking the up arrow decreases the position value and clicking the down arrow increases it.

A spin button control without a buddy window functions as a sort of simplified scroll bar. For example, a tab control sometimes displays a spin button control to enable the user to scroll additional tabs into view.

For more information on using CSpinButtonCtrl, see Control Topics and Using CSpinButtonCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CMNCTRL2 | MFC Sample FIRE

See Also CSliderCtrl


CSpinButtonCtrl Class Members

Construction

CSpinButtonCtrl | Constructs a CSpinButtonCtrl object.
Create | Creates a spin button control and attaches it to a CSpinButtonCtrl object.

Attributes

SetAccel | Sets the acceleration for a spin button control.
GetAccel | Retrieves acceleration information for a spin button control.
SetBase | Sets the base for a spin button control.
GetBase | Retrieves the current base for a spin button control.
SetBuddy | Sets the buddy window for a spin button control.
GetBuddy | Retrieves a pointer to the current buddy window.
SetPos | Sets the current position for the control.
GetPos | Retrieves the current position of a spin button control.
SetRange | Sets the upper and lower limits (range) for a spin button control.
GetRange | Retrieves the upper and lower limits (range) for a spin button control.
SetRange32 | Sets the 32-bit range for a spin button control.
GetRange32 | Retrieves the 32-bit range for a spin button control.


CSpinButtonCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if initialization was successful; otherwise 0.

Parameters

dwStyle

Specifies the spin button control’s style. Apply any combination of spin button control styles to the control.

rect

Specifies the spin button control’s size and position. It can be either a CRect object or a RECT structure

pParentWnd

A pointer to the spin button control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the spin button control’s ID.

Remarks

You construct a CSpinButtonCtrl object in two steps. First call the constructor, then call Create, which creates the spin button control and attaches it to the CSpinButtonCtrl object.

The following styles are specific to spin button controls:

  • UDS_HORZ Causes the control’s arrows to point left and right instead of up and down.

  • UDS_WRAP Causes the position to “wrap” if it is incremented or decremented beyond the ending or beginning of the range.

  • UDS_ARROWKEYS Causes the control to increment and decrement the position when the UP ARROW and DOWN ARROW keys are pressed.

  • UDS_SETBUDDYINT Causes the 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_NOTHOUSANDS Does not insert a thousands separator between every three decimal digits.

  • UDS_AUTOBUDDY Automatically selects the previous window in the Z-order as the control’s buddy window.

  • UDS_ALIGNRIGHT Positions the spin button control next to the right edge of the buddy window. The width of the buddy window is decreased to accommodate the width of the control.

  • UDS_ALIGNLEFT Positions the spin button control next to the left edge of the buddy window. The buddy window is moved to the right and its width decreased to accommodate the width of the control.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::CSpinButtonCtrl


CSpinButtonCtrl::CSpinButtonCtrl

CSpinButtonCtrl( );

Remarks

Constructs a CSpinButtonCtrl object.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::Create


CSpinButtonCtrl::GetAccel

UINT GetAccel( int nAccel, UDACCEL* pAccel ) const;

Return Value

Number of accelerator structures retrieved.

Parameters

nAccel

Number of elements in the array specified by pAccel.

pAccel

Pointer to an array of UDACCEL structures that receives acceleration information.

Remarks

Call this function to retrieve acceleration information for a spin button control.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::SetAccel


CSpinButtonCtrl::GetBase

UINT GetBase( ) const;

Return Value

The current base value.

Remarks

Call this function to retrieve the current base for a spin button control.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::SetBase


CSpinButtonCtrl::GetBuddy

CWnd* GetBuddy( ) const;

Return Value

A pointer to the current buddy window.

Remarks

Call this function to retrieve a pointer to the current buddy window.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::SetBuddy


CSpinButtonCtrl::GetPos

int GetPos( ) const;

Return Value

The current position in the low-order word. The high-order word is nonzero if an error occurred.

Remarks

Call this function to retrieve the current position of a spin button control. When it processes the value returned, the control updates its current position based on the caption of the buddy window. The control returns an error if there is no buddy window or if the caption specifies an invalid or out-of-range value.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::SetPos


CSpinButtonCtrl::GetRange

DWORD GetRange( ) const;

void GetRange( int &lower, int& upper ) const;

void GetRange32( int &lower, int &upper ) const;

Return Value

The first version returns a 32-bit value containing the upper and lower limits. The low-order word is the upper limit for the control, and the high-order word is the lower limit.

Parameters

lower

Reference to an integer that receives the lower limit for the control.

upper

Reference to an integer that receives the upper limit for the control.

Remarks

Call this function to retrieve the upper and lower limits (range) for a spin button control.

The member function GetRange32 retrieves the spin button control's range as a 32-bit integer.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::SetRange


CSpinButtonCtrl::SetAccel

BOOL SetAccel( int nAccel, UDACCEL* pAccel );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nAccel

Number of UDACCEL structures specified by pAccel.

pAccel

Pointer to an array of UDACCEL structures, which contain acceleration information. Elements should be sorted in ascending order based on the nSec member.

Remarks

Call this function to set the acceleration for a spin button control.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::GetAccel


CSpinButtonCtrl::SetBase

int SetBase( int nBase );

Return Value

The previous base value if successful, or zero if an invalid base is given.

Parameters

nBase

New base value for the control. It can be 10 for decimal or 16 for hexadecimal.

Remarks

Call this function to set the base for a spin button control. The base value determines whether the buddy window displays numbers in decimal or hexadecimal digits. Hexadecimal numbers are always unsigned; decimal numbers are signed.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::GetBase


CSpinButtonCtrl::SetBuddy

CWnd* SetBuddy( CWnd* pWndBuddy );

Return Value

A pointer to the previous buddy window.

Parameters

pWndBuddy

Pointer to the new buddy window.

Remarks

Call this function to set the buddy window for a spin button control.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::GetBuddy


CSpinButtonCtrl::SetPos

int SetPos( int nPos );

Return Value

The previous position.

Parameters

nPos

New position for the control. This value must be in the range specified by the upper and lower limits for the control.

Remarks

Call this function to set the current position for a spin button control.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::SetRange, CSpinButtonCtrl::GetPos


CSpinButtonCtrl::SetRange

void SetRange( int nLower, int nUpper );

void SetRange32( int nLower, int nUpper );

Parameters

nLower and nUpper

Upper and lower limits for the control. Neither limit can be greater than UD_MAXVAL or less than UD_MINVAL. In addition, the difference between the two limits cannot exceed UD_MAXVAL.

Remarks

Call this function to set the upper and lower limits (range) for a spin button control.

The member function SetRange32 sets the 32-bit range for the spin button control.

Note The default range for the spin button has the maximum set to zero (0) and the minimum set to 100. Since the maximum value is less than the minimum value, clicking the up arrow will decrease the position and clicking the down arrow will increase it. Use CSpinButtonCtrl::SetRange to adjust these values.

CSpinButtonCtrl Overview | Class Members | Hierarchy Chart

See Also CSpinButtonCtrl::GetRange, CSpinButtonCtrl::GetPos, Using CSpinButtonCtrl


CSplitterWnd

The CSplitterWnd class provides the functionality of a splitter window, which is a window that contains multiple panes. A pane is usually an application-specific object derived from CView, but it can be any CWnd object that has the appropriate child window ID.

A CSplitterWnd object is usually embedded in a parent CFrameWnd or CMDIChildWnd object. Create a CSplitterWnd object using the following steps:

  1. Embed a CSplitterWnd member variable in the parent frame.

  2. Override the parent frame’s CFrameWnd::OnCreateClient member function.

  3. From within the overridden OnCreateClient, call the Create or CreateStatic member function of CSplitterWnd.

Call the Create member function to create a dynamic splitter window. A dynamic splitter window typically is used to create and scroll a number of individual panes, or views, of the same document. The framework automatically creates an initial pane for the splitter; then the framework creates, resizes, and disposes of additional panes as the user operates the splitter window’s controls.

When you call Create, you specify a minimum row height and column width that determine when the panes are too small to be fully displayed. After you call Create, you can adjust these minimums by calling the SetColumnInfo and SetRowInfo member functions.

Also use the SetColumnInfo and SetRowInfo member functions to set an “ideal” width for a column and “ideal” height for a row. When the framework displays a splitter window, it first displays the parent frame, then the splitter window. The framework then lays out the panes in columns and rows according to their ideal dimensions, working from the upper-left to the lower-right corner of the splitter window’s client area.

All panes in a dynamic splitter window must be of the same class. Familiar applications that support dynamic splitter windows include Microsoft Word and Microsoft Excel.

Use the CreateStatic member function to create a static splitter window. The user can change only the size of the panes in a static splitter window, not their number or order.

You must specifically create all the static splitter’s panes when you create the static splitter. Make sure you create all the panes before the parent frame’s OnCreateClient member function returns, or the framework will not display the window correctly.

The CreateStatic member function automatically initializes a static splitter with a minimum row height and column width of 0. After you call Create, adjust these minimums by calling the SetColumnInfo and SetRowInfo member functions. Also use SetColumnInfo and SetRowInfo after you call CreateStatic to indicate desired ideal pane dimensions.

The individual panes of a static splitter often belong to different classes. For examples of static splitter windows, see the graphics editor and the Windows File Manager.

A splitter window supports special scroll bars (apart from the scroll bars that panes may have). These scroll bars are children of the CSplitterWnd object and are shared with the panes.

You create these special scroll bars when you create the splitter window. For example, a CSplitterWnd that has one row, two columns, and the WS_VSCROLL style will display a vertical scroll bar that is shared by the two panes. When the user moves the scroll bar, WM_VSCROLL messages are sent to both panes. When the panes set the scroll-bar position, the shared scroll bar is set.

For further information on splitter windows, see Technical Note 29. For more information on how to create dynamic splitter windows, see Adding Splitter Windows to Scribble in Enhancing Views in Visual C++ Tutorials, and the MFC General sample VIEWEX.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample VIEWEX

See Also CView, CWnd


CSplitterWnd Class Members

Construction

CSplitterWnd | Call to construct a CSplitterWnd object.
Create | Call to create a dynamic splitter window and attach it to the CSplitterWnd object.
CreateStatic | Call to create a static splitter window and attach it to the CSplitterWnd object.
CreateView | Call to create a pane in a splitter window.

Operations

GetRowCount | Returns the current pane row count.
GetColumnCount | Returns the current pane column count.
GetRowInfo | Returns information on the specified row.
SetRowInfo | Call to set the specified row information.
GetColumnInfo | Returns information on the specified column.
SetColumnInfo | Call to set the specified column information.
GetPane | Returns the pane at the specified row and column.
IsChildPane | Call to determine whether the window is currently a child pane of this splitter window.
IdFromRowCol | Returns the child window ID of the pane at the specified row and column.
RecalcLayout | Call to redisplay the splitter window after adjusting row or column size.
GetScrollStyle | Returns the shared scroll-bar style.
SetScrollStyle | Specifies the new scroll-bar style for the splitter window’s shared scroll-bar support.

Overridables

OnDrawSplitter | Renders an image of a split window.
OnInvertTracker | Renders the image of a split window to be the same size and shape as the frame window.
CreateScrollBarCtrl | Creates a shared scroll bar control.
DeleteView | Deletes a view from the splitter window.
SplitRow | Indicates where a frame window splits horizontally.
SplitColumn | Indicates where a frame window splits vertically.
DeleteRow | Deletes a row from the splitter window.
DeleteColumn | Deletes a column from the splitter window.
GetActivePane | Determines the active pane from the focus or active view in the frame.
SetActivePane | Sets a pane to be the active one in the frame.
CanActivateNext | Checks to see if the Next Pane or Previous Pane command is currently possible.
ActivateNext | Performs the Next Pane or Previous Pane command.
DoKeyboardSplit | Performs the keyboard split command, usually "Window Split."
DoScroll | Performs synchronized scrolling of split windows.
DoScrollBy | Scrolls split windows by a given number of pixels.


CSplitterWnd::ActivateNext

virtual void ActivateNext( BOOL bPrev = FALSE );

Parameters

bPrev

Indicates which window to activate. TRUE for previous; FALSE for next.

Remarks

This member function is called by the framework to perform the Next Pane or Previous Pane command.

This member function is a high level command that is used by the CView class to delegate to the CSplitterWnd implementation.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CView, CSplitterWnd::CanActivateNext, CSplitterWnd::SetActivePane


CSplitterWnd::CanActivateNext

virtual BOOL CanActivateNext( BOOL bPrev = FALSE );

Return Value

Nonzero if successful; otherwise 0.

Parameters

bPrev

Indicates which window to activate. TRUE for previous; FALSE for next.

Remarks

This member function is called by the framework to check to see if the Next Pane or Previous Pane command is currently possible.

This member function is a high level command that is used by the CView class to delegate to the CSplitterWnd implementation.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::ActivateNext, CSplitterWnd::SetActivePane


CSplitterWnd::Create

BOOL Create( CWnd* pParentWnd, int nMaxRows, int nMaxCols, SIZE sizeMin, CCreateContext* pContext, DWORD dwStyle = WS_CHILD | WS_VISIBLE |WS_HSCROLL | WS_VSCROLL | SPLS_DYNAMIC_SPLIT, UINT nID = AFX_IDW_PANE_FIRST );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pParentWnd

The parent frame window of the splitter window.

nMaxRows

The maximum number of rows in the splitter window. This value must not exceed 2.

nMaxCols

The maximum number of columns in the splitter window. This value must not exceed 2.

sizeMin

Specifies the minimum size at which a pane may be displayed.

pContext

A pointer to a CCreateContext structure. In most cases, this can be the pContext passed to the parent frame window.

dwStyle

Specifies the window style.

nID

The child window ID of the window. The ID can be AFX_IDW_PANE_FIRST unless the splitter window is nested inside another splitter window.

Remarks

To create a dynamic splitter window, call the Create member function.

You can embed a CSplitterWnd in a parent CFrameWnd or CMDIChildWnd object by taking the following steps:

  1. Embed a CSplitterWnd member variable in the parent frame.

  2. Override the parent frame’s CFrameWnd::OnCreateClient member function.

  3. Call the Create member function from within the overridden OnCreateClient.

When you create a splitter window from within a parent frame, pass the parent frame’s pContext parameter to the splitter window. Otherwise, this parameter can be NULL.

The initial minimum row height and column width of a dynamic splitter window are set by the sizeMin parameter. These minimums, which determine whether a pane is too small to be shown in its entirety, can be changed with the SetRowInfo and SetColumnInfo member functions.

For more on dynamic splitter windows, see "Splitter Windows" in the article Multiple Document Types, Views, and Frame Windows in Visual C++ Programmer’s Guide, Technical Note 29, and the CSplitterWnd class overview.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::CreateStatic, CFrameWnd::OnCreateClient, CSplitterWnd::SetRowInfo, CSplitterWnd::SetColumnInfo, CSplitterWnd::CreateView


CSplitterWnd::CreateScrollBarCtrl

virtual BOOL CreateScrollBarCtrl( DWORD dwStyle, UINT nID );

Return Value

Nonzero if successful; otherwise 0.

Parameters

dwStyle

Specifies the window style.

nID

The child window ID of the window. The ID can be AFX_IDW_PANE_FIRST unless the splitter window is nested inside another splitter window.

Remarks

This member function is called by the framework to create a shared scroll bar control. Override CreateScrollBarCtrl to include extra controls next to a scroll bar. The default behavior is to create normal Windows scroll bar controls.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also AfxGetInstanceHandle


CSplitterWnd::CreateStatic

BOOL CreateStatic( CWnd* pParentWnd, int nRows, int nCols, DWORD dwStyle = WS_CHILD | WS_VISIBLE, UINT nID = AFX_IDW_PANE_FIRST );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pParentWnd

The parent frame window of the splitter window.

nRows

The number of rows. This value must not exceed 16.

nCols

The number of columns. This value must not exceed 16.

dwStyle

Specifies the window style.

nID

The child window ID of the window. The ID can be AFX_IDW_PANE_FIRST unless the splitter window is nested inside another splitter window.

Remarks

To create a static splitter window, call the CreateStatic member function.

A CSplitterWnd is usually embedded in a parent CFrameWnd or CMDIChildWnd object by taking the following steps:

  1. Embed a CSplitterWnd member variable in the parent frame.

  2. Override the parent frame’s OnCreateClient member function.

  3. Call the CreateStatic member function from within the overridden CFrameWnd::OnCreateClient.

A static splitter window contains a fixed number of panes, often from different classes.

When you create a static splitter window, you must at the same time create all its panes. The CreateView member function is usually used for this purpose, but you can create other nonview classes as well.

The initial minimum row height and column width for a static splitter window is 0. These minimums, which determine when a pane is too small to be shown in its entirety, can be changed with the SetRowInfo and SetColumnInfo member functions.

To add scroll bars to a static splitter window, add the WS_HSCROLL and WS_VSCROLL styles to dwStyle.

See "Splitter Windows" in the article Multiple Document Types, Views, and Frame Windows in Visual C++ Programmer’s Guide, Technical Note 29, and the CSplitterWnd class overview for more on static splitter windows.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::Create, CFrameWnd::OnCreateClient, CSplitterWnd::SetRowInfo, CSplitterWnd::SetColumnInfo, CSplitterWnd::CreateView


CSplitterWnd::CreateView

virtual BOOL CreateView( int row, int col, CRuntimeClass* pViewClass, SIZE sizeInit, CCreateContext* pContext );

Return Value

Nonzero if successful; otherwise 0.

Parameters

row

Specifies the splitter window row in which to place the new view.

col

Specifies the splitter window column in which to place the new view.

pViewClass

Specifies the CRuntimeClass of the new view.

sizeInit

Specifies the initial size of the new view.

pContext

A pointer to a creation context used to create the view (usually the pContext passed into the parent frame’s overridden CFrameWnd::OnCreateClient member function in which the splitter window is being created).

Remarks

Call this member function to create the panes for a static splitter window. All panes of a static splitter window must be created before the framework displays the splitter.

The framework also calls this member function to create new panes when the user of a dynamic splitter window splits a pane, row, or column.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::Create


CSplitterWnd::CSplitterWnd

CSplitterWnd( );

Remarks

Construct a CSplitterWnd object in two steps. First call the constructor, which creates the CSplitterWnd object, then call the Create member function, which creates the splitter window and attaches it to the CSplitterWnd object.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::Create


CSplitterWnd::DeleteColumn

virtual void DeleteColumn( int colDelete );

Parameters

colDelete

Specifies the column to be deleted.

Remarks

This member function is called when a column is to be deleted.

This member function is called by the framework to implement the logic of the dynamic splitter window (that is, if the splitter window has the SPLS_DYNAMIC_SPLIT style). It can be customized, along with the virtual function CreateView, to implement more advanced dynamic splitters.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::DeleteRow, CSplitterWnd::CreateView, CSplitterWnd::DeleteView


CSplitterWnd::DeleteRow

virtual void DeleteRow( int rowDelete );

Parameters

rowDelete

Specifies the row to be deleted.

Remarks

DeleteRow is called when a row is to be deleted.

This member function is called by the framework to implement the logic of the dynamic splitter window (that is, if the splitter window has the SPLS_DYNAMIC_SPLIT style). It can be customized, along with the virtual function CreateView, to implement more advanced dynamic splitters.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::DeleteColumn, CSplitterWnd::CreateView, CSplitterWnd::DeleteView


CSplitterWnd::DeleteView

virtual void DeleteView( int row, int col );

Parameters

row

Specifies the splitter window row at which to delete the view.

col

Specifies the splitter window column at which to delete the view.

Remarks

DeleteView is called when a view is to be deleted. If the active view is being deleted, the next view will become active. The default implementation assumes the view will auto delete in PostNcDestroy.

This member function is called by the framework to implement the logic of the dynamic splitter window (that is, if the splitter window has the SPLS_DYNAMIC_SPLIT style). It can be customized, along with the virtual function CreateView, to implement more advanced dynamic splitters.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::PostNcDestroy, CSplitterWnd::CreateView, CSplitterWnd::DeleteColumn, CSplitterWnd::DeleteRow


CSplitterWnd::DoKeyboardSplit

virtual BOOL DoKeyboardSplit( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

This member function is called by the framework to perform a keyboard split command, usually Window Split.

This member function is a high level command that is used by the CView class to delegate to the CSplitterWnd implementation.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CView


CSplitterWnd::DoScroll

virtual BOOL DoScroll( CView* pViewFrom, UINT nScrollCode, BOOL bDoScroll = TRUE );

Return Value

Nonzero if synchronized scrolling occurs; otherwise 0.

Parameters

pViewFrom

A pointer to the view from which the scrolling message originates.

nScrollCode

A scroll-bar code that indicates the user's scrolling request. This parameter is composed of two parts: a low-order byte, which determines the type of scrolling occurring horizontally, and a high-order byte, which determines the type of scrolling occurring vertically:

  • SB_BOTTOM Scrolls to bottom.

  • SB_LINEDOWN Scrolls one line down.

  • SB_LINEUP Scrolls one line up.

  • SB_PAGEDOWN Scrolls one page down.

  • SB_PAGEUP Scrolls one page up.

  • SB_TOP Scrolls to top.

bDoScroll

Determines whether the specified scrolling action occurs. If bDoScroll is TRUE (that is, if a child window exists, and if the split windows have a scroll range), then the specified scrolling action can take place; if bDoScroll is FALSE (that is, if no child window exists, or the split views have no scroll range), then scrolling does not occur.

Remarks

This member function is called by the framework to perform synchronized scrolling of split windows when the view receives a scroll message.

Override to require an action by the user before synchronized scrolling is allowed.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::DoScrollBy, CView::OnScroll


CSplitterWnd::DoScrollBy

virtual BOOL DoScrollBy( CView* pViewFrom, CSize sizeScroll, BOOL bDoScroll = TRUE );

Return Value

Nonzero if synchronized scrolling occurs; otherwise 0.

Parameters

pViewFrom

A pointer to the view from which the scrolling message originates.

sizeScroll

Number of pixels to be scrolled horizontally and vertically.

bDoScroll

Determines whether the specified scrolling action occurs. If bDoScroll is TRUE (that is, if a child window exists, and if the split windows have a scroll range), then the specified scrolling action can take place; if bDoScroll is FALSE (that is, if no child window exists, or the split views have no scroll range), then scrolling does not occur.

Remarks

This member function is called by the framework in response to a scroll message, to perform synchronized scrolling of the split windows by the amount, in pixels, indicated by sizeScroll. Positive values indicate scrolling down and to the right; negative values indicate scrolling up and to the left.

Override to require an action by the user before allowing scroll.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::DoScroll, CView::OnScroll


CSplitterWnd::GetActivePane

virtual CWnd* GetActivePane(int* pRow = NULL, int* pCol = NULL);

Return Value

Pointer to the active pane. NULL if no active pane exists.

Parameters

pRow

A pointer to an int to retrieve the row number of the active pane.

pCol

A pointer to an int to retrieve the column number of the active pane.

Remarks

This member function is called by the framework to determine the active pane in a splitter window.

Override to require an action by the user before getting the active pane.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::SetActivePane, CFrameWnd::GetActiveView,CWnd::GetParentFrame, CWnd::GetFocus


CSplitterWnd::GetColumnCount

int GetColumnCount( );

Return Value

Returns the current number of columns in the splitter. For a static splitter, this will also be the maximum number of columns.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetRowCount


CSplitterWnd::GetColumnInfo

void GetColumnInfo( int col, int& cxCur, int& cxMin );

Parameters

col

Specifies a column.

cxCur

A reference to an int to be set to the current width of the column.

cxMin

A reference to an int to be set to the current minimum width of the column.

Remarks

Call this member function to obtain information about the specified column.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::SetColumnInfo, CSplitterWnd::GetRowInfo


CSplitterWnd::GetPane

CWnd* GetPane( int row, int col );

Return Value

Returns the pane at the specified row and column. The returned pane is usually a CView-derived class.

Parameters

row

Specifies a row.

col

Specifies a column.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetActivePane, CSplitterWnd::IdFromRowCol, CSplitterWnd::IsChildPane


CSplitterWnd::GetRowCount

int GetRowCount( );

Return Value

Returns the current number of rows in the splitter window. For a static splitter window, this will also be the maximum number of rows.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetColumnCount


CSplitterWnd::GetRowInfo

void GetRowInfo( int row, int& cyCur, int& cyMin );

Parameters

row

Specifies a row.

cyCur

Reference to int to be set to the current height of the row in pixels.

cyMin

Reference to int to be set to the current minimum height of the row in pixels.

Remarks

Call this member function to obtain information about the specified row. The cyCur parameter is filled with the current height of the specified row, and cyMin is filled with the minimum height of the row.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::SetRowInfo, CSplitterWnd::GetColumnInfo


CSplitterWnd::GetScrollStyle

DWORD GetScrollStyle( ) const;

Return Value

One or more of the following windows style flags, if successful:

  • WS_HSCROLL If the splitter currently manages shared horizontal scroll bars.

  • WS_VSCROLL If the splitter currently manages shared vertical scroll bars.

If zero, the splitter window does not currently manage any shared scroll bars.

Remarks

Returns the shared scroll-bar style for the splitter window.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::SetScrollStyle


CSplitterWnd::IdFromRowCol

int IdFromRowCol( int row, int col );

Return Value

The child window ID for the pane.

Parameters

row

Specifies the splitter window row.

col

Specifies the splitter window column.

Remarks

Call this member function to obtain the child window ID for the pane at the specified row and column. This member function is used for creating nonviews as panes and may be called before the pane exists.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetPane, CSplitterWnd::IsChildPane


CSplitterWnd::IsChildPane

BOOL IsChildPane( CWnd* pWnd, int& row, int& col );

Return Value

If nonzero, pWnd is currently a child pane of this splitter window, and row and col are filled in with the position of the pane in the splitter window. If pWnd is not a child pane of this splitter window, 0 is returned.

Parameters

pWnd

A pointer to a CWnd object to be tested.

row

Reference to an int in which to store row number.

col

Reference to an int in which to store a column number.

Remarks

Call this member function to determine whether pWnd is currently a child pane of this splitter window.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetPane


CSplitterWnd::OnDrawSplitter

virtual void OnDrawSplitter( CDC* pDC, ESplitType nType, const CRect& rect );

Parameters

pDC

A pointer to the device context in which to draw. If pDC is NULL, then CWnd::RedrawWindow is called by the framework and no split window is drawn.

nType

A value of the enum ESplitType, which can be one of the following:

  • splitBox The splitter drag box.

  • splitBar The bar that appears between the two split windows.

  • splitIntersection The intersection of the split windows. This element will not be called when running on Windows 95.

  • splitBorder The split window borders.

rect

A reference to a CRect object specifying the size and shape of the split windows.

Remarks

This member function is called by the framework to draw and specify the exact characteristics of a splitter window.

Override OnDrawSplitter for advanced customization of the imagery for the various graphical components of a splitter window. The default imagery is similar to the splitter in Microsoft Works for Windows or Microsoft Windows 95, in that the intersections of the splitter bars are blended together.

For more on dynamic splitter windows, see "Splitter Windows" in the article Multiple Document Types, Views, and Frame Windows in Visual C++ Programmer’s Guide, Technical Note 29, and the CSplitterWnd class overview.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::OnInvertTracker


CSplitterWnd::OnInvertTracker

virtual void OnInvertTracker( const CRect& rect );

Parameters

rect

Reference to a CRect object specifying the tracking rectangle.

Remarks

This member function is called by the framework during resizing of splitters.

Override OnInvertTracker for advanced customization of the imagery of the splitter window. The default imagery is similar to the splitter in Microsoft Works for Windows or Microsoft Windows 95, in that the intersections of the splitter bars are blended together.

For more on dynamic splitter windows, see "Splitter Windows" in the article Multiple Document Types, Views, and Frame Windows in Visual C++ Programmer’s Guide, Technical Note 29, and the CSplitterWnd class overview.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::OnDrawSplitter


CSplitterWnd::RecalcLayout

void RecalcLayout( );

Remarks

Call this member function to correctly redisplay the splitter window after you have adjusted row and column sizes with the SetRowInfo and SetColumnInfo member functions. If you change row and column sizes as part of the creation process before the splitter window is visible, it is not necessary to call this member function.

The framework calls this member function whenever the user resizes the splitter window or moves a split.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::SetRowInfo, CSplitterWnd::SetColumnInfo


CSplitterWnd::SetActivePane

virtual void SetActivePane( int row, int col, CWnd* pWnd = NULL );

Parameters

row

If pWnd is NULL, specifies the row in the pane that will be active.

col

If pWnd is NULL, specifies the column in the pane that will be active.

pWnd

A pointer to a CWnd object. If NULL, the pane specified by row and col is set active. If not NULL, specifies the pane that is set active.

Remarks

This member function is called by the framework to set a pane as active when the user changes the focus to a pane within the frame window. You may explicitly call SetActivePane to change the focus to the specified view.

Specify pane by providing either row and column, or by providing pWnd.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetActivePane, CSplitterWnd::GetPane, CFrameWnd::SetActiveView


CSplitterWnd::SetColumnInfo

void SetColumnInfo( int col, int cxIdeal, int cxMin );

Parameters

col

Specifies a splitter window column.

cxIdeal

Specifies an ideal width for the splitter window column in pixels.

cxMin

Specifies a minimum width for the splitter window column in pixels.

Remarks

Call this member function to set a new minimum width and ideal width for a column. The column minimum value determines when the column will be too small to be fully displayed.

When the framework displays the splitter window, it lays out the panes in columns and rows according to their ideal dimensions, working from the upper-left to the lower-right corner of the splitter window’s client area.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetRowInfo, CSplitterWnd::RecalcLayout


CSplitterWnd::SetRowInfo

void SetRowInfo( int row, int cyIdeal, int cyMin );

Parameters

row

Specifies a splitter window row.

cyIdeal

Specifies an ideal height for the splitter window row in pixels.

cyMin

Specifies a minimum height for the splitter window row in pixels.

Remarks

Call this member function to set a new minimum height and ideal height for a row. The row minimum value determines when the row will be too small to be fully displayed.

When the framework displays the splitter window, it lays out the panes in columns and rows according to their ideal dimensions, working from the upper-left to the lower-right corner of the splitter window’s client area.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetRowInfo, CSplitterWnd::SetColumnInfo, CSplitterWnd::RecalcLayout


CSplitterWnd::SetScrollStyle

void SetScrollStyle( DWORD dwStyle );

Parameters

dwStyle

The new scroll style for the splitter window’s shared scroll-bar support, which can be one of the following values:

  • WS_HSCROLL Create/show horizontal shared scroll bars.

  • WS_VSCROLL Create/show vertical shared scroll bars.

Remarks

Specifies the new scroll style for the splitter window’s shared scroll-bar support. Once a scroll bar is created it will not be destroyed even if SetScrollStyle is called without that style; instead those scroll bars are hidden. This allows the scroll bars to retain their state even though they are hidden. After calling SetScrollStyle it is necessary to call RecalcLayout for all the changes to take effect.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::GetScrollStyle


CSplitterWnd::SplitColumn

virtual BOOL SplitColumn( int cxBefore );

Return Value

Nonzero if successful; otherwise 0.

Parameters

cxBefore

The position, in pixels, before which the split occurs.

Remarks

This member function is called when a vertical splitter window is created. SplitColumn indicates the default location where the split occurs.

SplitColumn is called by the framework to implement the logic of the dynamic splitter window (that is, if the splitter window has the SPLS_DYNAMIC_SPLIT style). It can be customized, along with the virtual function CreateView, to implement more advanced dynamic splitters.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::CreateView, CSplitterWnd::SplitRow, CSplitterWnd::RecalcLayout


CSplitterWnd::SplitRow

virtual BOOL SplitRow( int cyBefore );

Return Value

Nonzero if successful; otherwise 0.

Parameters

cyBefore

The position, in pixels, before which the split occurs.

Remarks

This member function is called when a horizontal splitter window is created. SplitRow indicates the default location where the split occurs.

SplitRow is called by the framework to implement the logic of the dynamic splitter window (that is, if the splitter window has the SPLS_DYNAMIC_SPLIT style). It can be customized, along with the virtual function CreateView, to implement more advanced dynamic splitters.

CSplitterWnd Overview | Class Members | Hierarchy Chart

See Also CSplitterWnd::SplitColumn, CSplitterWnd::CreateView, CSplitterWnd::RecalcLayout


CStatic

The CStatic class provides the functionality of a Windows static control. A static control displays a text string, box, rectangle, icon, cursor, bitmap, or enhanced metafile. It can be used to label, box, or separate other controls. A static control normally takes no input and provides no output; however, it can notify its parent of mouse clicks if it's created with SS_NOTIFY style.

Create a static control in two steps. First, call the constructor to construct the CStatic object, then call the Create member function to create the static control and attach it to the CStatic object.

If you create a CStatic object within a dialog box (through a dialog resource), the CStatic object is automatically destroyed when the user closes the dialog box.

If you create a CStatic object within a window, you may also need to destroy it. A CStatic object created on the stack within a window is automatically destroyed. If you create the CStatic object on the heap by using the new function, you must call delete on the object to destroy it when the you are done with it.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CWnd, CButton, CComboBox, CEdit, CListBox, CScrollBar, CDialog


CStatic Class Members

Construction

CStatic Constructs a CStatic object.

Initialization

Create Creates the Windows static control and attaches it to the CStatic object.

Operations

SetBitmap | Specifies a bitmap to be displayed in the static control.
GetBitmap | Retrieves the handle of the bitmap previously set with SetBitmap.
SetIcon | Specifies an icon to be displayed in the static control.
GetIcon | Retrieves the handle of the icon previously set with SetIcon.
SetCursor | Specifies a cursor image to be displayed in the static control.
GetCursor | Retrieves the handle of the cursor image previously set with SetCursor.
SetEnhMetaFile | Specifies an enhanced metafile to be displayed in the static control.
GetEnhMetaFile | Retrieves the handle of the enhanced metafile previously set with SetEnhMetaFile.


CStatic::Create

BOOL Create( LPCTSTR lpszText, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID = 0xffff );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszText

Specifies the text to place in the control. If NULL, no text will be visible.

dwStyle

Specifies the static control’s window style. Apply any combination of static control styles to the control.

rect

Specifies the position and size of the static control. It can be either a RECT structure or a CRect object.

pParentWnd

Specifies the CStatic parent window, usually a CDialog object. It must not be NULL.

nID

Specifies the static control’s control ID.

Remarks

Construct a CStatic object in two steps. First call the constructor CStatic, then call Create, which creates the Windows static control and attaches it to the CStatic object.

Apply the following window styles to a static control:

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

If you're going to display a bitmap, cursor, icon, or metafile in the static control, you'll need to apply one of the following styles:

  • SS_BITMAP Use this style for bitmaps.

  • SS_ICON Use this style for cursors and icons.

  • SS_ENHMETAFILE Use this style for enhanced metafiles.

For cursors, bitmaps, or icons, you may also want to use the following style:

  • SS_CENTERIMAGE Use to center the image in the static control.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::CStatic


CStatic::CStatic

CStatic( );

Remarks

Constructs a CStatic object.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::Create


CStatic::GetBitmap

HBITMAP GetBitmap( ) const;

Return Value

A handle to the current bitmap, or NULL if no bitmap has been set.

Remarks

Call this member function to get the handle of the bitmap, previously set with SetBitmap, that is associated with CStatic.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::SetBitmap, STM_GETIMAGE, Bitmaps


CStatic::GetCursor

HCURSOR GetCursor( );

Return Value

A handle to the current cursor, or NULL if no cursor has been set.

Remarks

Call this member function to get the handle of the cursor, previously set with SetCursor, that is associated with CStatic.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::SetCursor, STM_GETIMAGE, Cursors


CStatic::GetEnhMetaFile

HENHMETAFILE GetEnhMetaFile( ) const;

Return Value

A handle to the current enhanced metafile, or NULL if no enhanced metafile has been set.

Remarks

Call this member function to get the handle of the enhanced metafile, previously set with SetEnhMetafile, that is associated with Cstatic.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::SetEnhMetafile, STM_GETIMAGE


CStatic::GetIcon

HICON GetIcon( ) const;

Return Value

A handle to the current icon, or NULL if no icon has been set.

Remarks

Call this member function to get the handle of the icon, previously set with SetIcon, that is associated with CStatic.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::SetIcon, STM_GETICON, Icons


CStatic::SetBitmap

HBITMAP SetBitmap( HBITMAP hBitmap );

Return Value

The handle of the bitmap previously associated with the static control, or NULL if no bitmap was associated with the static control.

Parameters

hBitmap

Handle of the bitmap to be drawn in the static control.

Remarks

Call this member function to associate a new bitmap with the static control.

The bitmap will be automatically drawn in the static control. By default, it will be drawn in the upper-left corner and the static control will be resized to the size of the bitmap.

You can use various window and static control styles, including the following:

  • SS_BITMAP Use this style always for bitmaps.

  • SS_CENTERIMAGE Use to center in the static control. If the image is larger than the static control, it will be clipped. If it is smaller than the static control, the empty space around the image will be filled by the color of the pixel in the upper left corner of the bitmap.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::GetBitmap, STM_SETIMAGE, Bitmaps


CStatic::SetCursor

HCURSOR SetCursor( HCURSOR hCursor );

Return Value

The handle of the cursor previously associated with the static control, or NULL if no cursor was associated with the static control.

Parameters

hCursor

Handle of the cursor to be drawn in the static control.

Remarks

Call this member function to associate a new cursor image with the static control.

The cursor will be automatically drawn in the static control. By default, it will be drawn in the upper-left corner and the static control will be resized to the size of the cursor.

You can use various window and static control styles, including the following:

  • SS_ICON Use this style always for cursors and icons.

  • SS_CENTERIMAGE Use to center in the static control. If the image is larger than the static control, it will be clipped. If it is smaller than the static control, the empty space around the image will be filled with the background color of the static control.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::GetCursor, STM_SETIMAGE, Cursors


CStatic::SetEnhMetaFile

HENHMETAFILE SetEnhMetaFile( HENHMETAFILE hMetaFile );

Return Value

The handle of the enhanced metafile previously associated with the static control, or NULL if no enhanced metafile was associated with the static control.

Parameters

hMetaFile

Handle of the enhanced metafile to be drawn in the static control.

Remarks

Call this member function to associate a new enhanced metafile image with the static control.

The enhanced metafile will be automatically drawn in the static control. The enhanced metafile is scaled to fit the size of the static control.

You can use various window and static control styles, including the following:

  • SS_ENHMETAFILE Use this style always for enhanced metafiles.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::GetEnhMetafile, STM_SETIMAGE


CStatic::SetIcon

HICON SetIcon( HICON hIcon );

Return Value

The handle of the icon previously associated with the static control, or NULL if no icon was associated with the static control.

Parameters

hIcon

Handle of the icon to be drawn in the static control.

Remarks

Call this member function to associate a new icon image with the static control.

The icon will be automatically drawn in the static control. By default, it will be drawn in the upper-left corner and the static control will be resized to the size of the icon.

You can use various window and static control styles, including the following:

  • SS_ICON Use this style always for cursors and icons.

  • SS_CENTERIMAGE Use to center in the static control. If the image is larger than the static control, it will be clipped. If it is smaller than the static control, the empty space around the image will be filled with the background color of the static control.

CStatic Overview | Class Members | Hierarchy Chart

See Also CStatic::GetIcon, STM_SETICON, Icons


CStatusBar

A CStatusBar object is a control bar with a row of text output panes, or “indicators.” The output panes commonly are used as message lines and as status indicators. Examples include the menu help-message lines that briefly explain the selected menu command and the indicators that show the status of the SCROLL LOCK, NUM LOCK, and other keys.

CStatusBar::GetStatusBarCtrl, a member function new to MFC 4.0, allows you to take advantage of the Windows common control’s support for status bar customization and additional functionality. CStatusBar member functions give you most of the functionality of the Windows common controls; however, when you call GetStatusBarCtrl, you can give your status bars even more of the characteristics of a Windows 95 status bar. When you call GetStatusBarCtrl, it will return a reference to a CStatusBarCtrl object. See CStatusBarCtrl for more information about designing toolbars using Windows common controls. For more general information about common controls, see Common Controls in the Windows 95 SDK Programmer’s Reference.

The framework stores indicator information in an array with the leftmost indicator at position 0. When you create a status bar, you use an array of string IDs that the framework associates with the corresponding indicators. You can then use either a string ID or an index to access an indicator.

By default, the first indicator is “elastic”: it takes up the status-bar length not used by the other indicator panes, so that the other panes are right-aligned.

To create a status bar, follow these steps:

  1. Construct the CStatusBar object.

  2. Call the Create (or CreateEx) function to create the status-bar window and attach it to the CStatusBar object.

  3. Call SetIndicators to associate a string ID with each indicator.

There are three ways to update the text in a status-bar pane:

  4. Call CWnd::SetWindowText to update the text in pane 0 only.

  5. Call CCmdUI::SetText in the status bar’s ON_UPDATE_COMMAND_UI handler.

  6. Call SetPaneText to update the text for any pane.

Call SetPaneStyle to update the style of a status-bar pane.

For more information on using CStatusBar, see the article Status Bars in Visual C++ Programmer’s Guide and Technical Note 31, Control Bars.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CTRLBARS | MFC Sample DLGCBR32

See Also CStatusBarCtrl, CControlBar, CWnd::SetWindowText, CStatusBar::SetIndicators


CStatusBar Class Members

Construction

CStatusBar | Constructs a CStatusBar object.
Create | Creates the status bar, attaches it to the CStatusBar object, and sets the initial font and bar height.
CreateEx | Creates a CStatusBar object with additional styles for the embedded CStatusBarCtrl object.
SetIndicators | Sets indicator IDs.

Attributes

CommandToIndex | Gets index for a given indicator ID.
GetItemID | Gets indicator ID for a given index.
GetItemRect | Gets display rectangle for a given index.
GetPaneInfo | Gets indicator ID, style, and width for a given index.
GetPaneStyle | Gets indicator style for a given index.
GetPaneText | Gets indicator text for a given index.
GetStatusBarCtrl | Allows direct access to the underlying common control.
SetPaneStyle | Sets indicator style for a given index.
SetPaneText | Sets indicator text for a given index.
SetPaneInfo | Sets indicator ID, style, and width for a given index.

Overridables

DrawItem Called when a visual aspect of an owner-draw status bar control changes.


CStatusBar::CommandToIndex

int CommandToIndex( UINT nIDFind ) const;

Return Value

The index of the indicator if successful; –1 if not successful.

Parameters

nIDFind

String ID of the indicator whose index is to be retrieved.

Remarks

Gets the indicator index for a given ID. The index of the first indicator is 0.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::GetItemID


CStatusBar::Create

BOOL Create( CWnd* pParentWnd, DWORD dwStyle = WS_CHILD | WS_VISIBLE | CBRS_BOTTOM, UINT nID = AFX_IDW_STATUS_BAR );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pParentWnd

Pointer to the CWnd object whose Windows window is the parent of the status bar.

dwStyle

The status-bar style. In addition to the standard Windows styles, these styles are supported.

  • CBRS_TOP Control bar is at top of frame window.

  • CBRS_BOTTOM Control bar is at bottom of frame window.

  • CBRS_NOALIGN Control bar is not repositioned when the parent is resized.

nID

The toolbar’s child-window ID.

Remarks

Creates a status bar (a child window) and associates it with the CStatusBar object. Also sets the initial font and sets the status bar’s height to a default value.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::SetIndicators


CStatusBar::CreateEx

BOOL CreateEx( CWnd* pParentWnd, DWORD dwCtrlStyle = 0 ,
DWORD dwStyle = WS_CHILD | WS_VISIBLE | CBRS_BOTTOM,
UINT nID = AFX_IDW_STATUS_BAR );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pParentWnd

Pointer to the CWnd object whose Windows window is the parent of the status bar.

dwCtrlStyle

Additional styles for the creation of the embedded CStatusBarCtrl object. For a complete list of supported styles, see dwStyle.

Status bar styles supported are:

  • SBARS_SIZEGRIP The status bar control includes 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.

  • SBT_TOOLTIPS The status bar supports tooltips.

dwStyle

The status-bar style. Supported styles include:

  • SBARS_SIZEGRIP The status bar control includes 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.

  • SBT_TOOLTIPS The status bar supports tooltips.

nID

The status bar’s child-window ID.

Remarks

Call this function to create a status bar (a child window) and associate it with the CStatusBar object. This function also sets the initial font and sets the status bar’s height to a default value.

Use CreateEx, instead of Create, when certain styles need to be present during the creation of the embedded status bar control. For example, set dwCtrlStyle to SBT_TOOLTIPS to display tooltips in a status bar object.


CStatusBar::CStatusBar

CStatusBar( );

Remarks

Constructs a CStatusBar object, creates a default status-bar font if necessary, and sets the font characteristics to default values.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::Create


CStatusBar::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A pointer to a DRAWITEMSTRUCT structure that contains information about the type of drawing required.

Remarks

This member function is called by the framework when a visual aspect of an owner-drawn status bar changes.

The itemAction member of the DRAWITEMSTRUCT structure defines the drawing action that is to be performed. Override this member function to implement drawing for an owner-draw CStatusBar object. The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before the termination of this member function.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CWnd::OnDrawItem


CStatusBar::GetItemID

UINT GetItemID( int nIndex ) const;

Return Value

The ID of the indicator specified by nIndex.

Parameters

nIndex

Index of the indicator whose ID is to be retrieved.

Remarks

Returns the ID of the indicator specified by nIndex.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::CommandToIndex


CStatusBar::GetItemRect

void GetItemRect( int nIndex, LPRECT lpRect ) const;

Parameters

nIndex

Index of the indicator whose rectangle coordinates are to be retrieved.

lpRect

Points to a RECT structure or a CRect object that will receive the coordinates of the indicator specified by nIndex.

Remarks

Copies the coordinates of the indicator specified by nIndex into the structure pointed to by lpRect. Coordinates are in pixels relative to the upper-left corner of the status bar.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::CommandToIndex, CStatusBar::GetPaneInfo


CStatusBar::GetPaneInfo

void GetPaneInfo( int nIndex, UINT& nID, UINT& nStyle, int& cxWidth ) const;

Parameters

nIndex

Index of the pane whose information is to be retrieved.

nID

Reference to a UINT that is set to the ID of the pane.

nStyle

Reference to a UINT that is set to the style of the pane.

cxWidth

Reference to an integer that is set to the width of the pane.

Remarks

Sets nID, nStyle, and cxWidth to the ID, style, and width of the indicator pane at the location specified by nIndex.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::SetPaneInfo, CStatusBar::GetItemID, CStatusBar::GetItemRect


CStatusBar::GetPaneStyle

UINT GetPaneStyle( int nIndex ) const;

Return Value

The style of the status-bar pane specified by nIndex.

Parameters

nIndex

Index of the pane whose style is to be retrieved.

Remarks

Call this member function to retrieve the style of a status bar’s pane. A pane’s style determines how the pane appears.

For a list of styles available for status bars, see Create.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::Create, CStatusBar::SetPaneStyle


CStatusBar::GetPaneText

CString GetPaneText( int nIndex ) const;

void GetPaneText( int nIndex, CString& rString ) const;

Return Value

A CString object containing the pane’s text.

Parameters

nIndex

Index of the pane whose text is to be retrieved.

rString

A reference to a CString object that contains the text to be retrieved.

Remarks

Call this member function to retrieve the text that appears in a status-bar pane. The second form of this member function fills a CString object with the string text.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::SetPaneText


CStatusBar::GetStatusBarCtrl

CStatusBarCtrl& GetStatusBarCtrl( ) const;

Return Value

Contains a reference to a CStatusBarCtrl object.

Remarks

This member function allows direct access to the underlying common control.

Use GetStatusBarCtrl to take advantage of the functionality of the Windows status-bar common control, and to take advantage of the support CStatusBarCtrl provides for status-bar customization. For example, by using the common control, you can specify a style that includes a sizing grip on the status bar, or you can specify a style to have the status bar appear at the top of the parent window’s client area.

For more general information about common controls, See Common Controls in the Windows 95 SDK Programmer’s Reference.


CStatusBar::SetIndicators

BOOL SetIndicators( const UINT* lpIDArray, int nIDCount );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpIDArray

Pointer to an array of IDs.

nIDCount

Number of elements in the array pointed to by lpIDArray.

Remarks

Sets each indicator’s ID to the value specified by the corresponding element of the array lpIDArray, loads the string resource specified by each ID, and sets the indicator’s text to the string.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::CStatusBar, CStatusBar::Create, CStatusBar::SetPaneInfo, CStatusBar::SetPaneText


CStatusBar::SetPaneInfo

void SetPaneInfo( int nIndex, UINT nID, UINT nStyle, int cxWidth );

Parameters

nIndex

Index of the indicator pane whose style is to be set.

nID

New ID for the indicator pane.

nStyle

New style for the indicator pane.

cxWidth

New width for the indicator pane.

Remarks

Sets the specified indicator pane to a new ID, style, and width.

The following indicator styles are supported:

  • SBPS_NOBORDERS No 3-D border around the pane.

  • SBPS_POPOUT Reverse border so that text “pops out.”

  • SBPS_DISABLED Do not draw text.

  • SBPS_STRETCH Stretch pane to fill unused space. Only one pane per status bar can have this style.

  • SBPS_NORMAL No stretch, borders, or pop-out.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::GetPaneInfo


CStatusBar::SetPaneStyle

void SetPaneStyle( int nIndex, UINT nStyle );

Parameters

nIndex

Index of the pane whose style is to be set.

nStyle

Style of the pane whose style is to be set.

Remarks

Call this member function to set the style of a status bar’s pane. A pane’s style determines how the pane appears.

For a list of styles available for status bars, see SetPaneInfo.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::Create, CStatusBar::GetPaneStyle


CStatusBar::SetPaneText

BOOL SetPaneText( int nIndex, LPCTSTR lpszNewText, BOOL bUpdate = TRUE );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nIndex

Index of the pane whose text is to be set.

lpszNewText

Pointer to the new pane text.

bUpdate

If TRUE, the pane is invalidated after the text is set.

Remarks

Sets the pane text to the string pointed to by lpszNewText.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBar::GetPaneText


CStatusBarCtrl

A “status bar control” is a horizontal window, usually displayed at the bottom of a parent window, in which an application can display various kinds of status information. The status bar control can be divided into parts to display more than one type of information.

The CStatusBarCtrl class provides the functionality of the Windows common status bar control. This control (and therefore the CStatusBarCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

For more information on using CStatusBarCtrl, see Control Topics and Using CStatusBarCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

See Also CToolBarCtrl


CStatusBarCtrl Class Members

Construction

CStatusBarCtrl | Constructs a CStatusBarCtrl object.
Create | Creates a status bar control and attaches it to a CStatusBarCtrl object.

Attributes

SetText | Sets the text in the given part of a status bar control.
GetText | Retrieves the text from the given part of a status bar control.
GetTextLength | Retrieve the length, in characters, of the text from the given part of a status bar control.
SetParts | Sets the number of parts in a status bar control and the coordinate of the right edge of each part.
GetParts | Retrieves a count of the parts in a status bar control.
GetBorders | Retrieves the current widths of the horizontal and vertical borders of a status bar control.
SetMinHeight | Sets the minimum height of a status bar control’s drawing area.
SetSimple | Specifies whether a status bar control displays simple text or displays all control parts set by a previous call to SetParts.
GetRect | Retrieves the bounding rectangle of a part in a status bar control.
IsSimple | Checks a status window control to determine if it is in simple mode.
GetTipText | Retrieves the tooltip text for a pane in a status bar.
SetTipText | Sets the tooltip text for a pane in a status bar.
SetBkColor | Sets the background color in a status bar.
SetIcon | Sets the icon for a pane in a status bar.

Overridables

DrawItem Called when a visual aspect of an owner-draw status bar control changes.


CStatusBarCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise zero.

Parameters

dwStyle Specifies the status bar control’s style. Apply any combination of status bar control styles to the control. This parameter must include the WS_CHILD style. It should also include the WS_VISIBLE style. See the Remarks section for more information.

rect

Specifies the status bar control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the status bar control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the status bar control’s ID.

Remarks

You construct a CStatusBarCtrl in two steps. First call the constructor, then call Create, which creates the status bar control and attaches it to the CStatusBarCtrl object.

The dwStyle parameter can have any combination of the following values:

  • 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 bar controls have this style by default.

  • CCS_NODIVIDER Prevents a two-pixel highlight from being drawn at the top of the control.

  • CCS_NOHILITE Prevents a one-pixel highlight from being drawn at the top of the control.

  • CCS_NOMOVEY Causes the control to resize and move itself horizontally, but not vertically, in response to a WM_SIZE message. If the CCS_NORESIZE style is used, this style does not apply.

  • 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 window. If the CCS_TOP or CCS_BOTTOM style is also used, the height is adjusted to the default, but the position and width remain unchanged.

  • CCS_NORESIZE Prevents the control from using the default width and height when setting its initial size or a new size. Instead, the control uses the width and height specified in the request for creation or sizing.

  • CCS_TOP Causes the control to position itself at the top of the parent window’s client area and sets the width to be the same as the parent window’s width.

The default position of a status window is along the bottom of the parent window, but you can specify the CCS_TOP style to have it appear at the top of the parent window’s client area. You can specify the SBARS_SIZEGRIP style to include a sizing grip at the right end of the status window. Combining the CCS_TOP and SBARS_SIZEGRIP styles is not recommended, because the resulting sizing grip is not functional even though the system draws it in the status window.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::CStatusBarCtrl


CStatusBarCtrl::CStatusBarCtrl

CStatusBarCtrl( );

Remarks

Constructs a CStatusBarCtrl object.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::Create


CStatusBarCtrl::DrawItem

virtual void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A long pointer to a DRAWITEMSTRUCT structure that contains information about the type of drawing required.

Remarks

Called by the framework when a visual aspect of an owner-draw status bar control changes. The itemAction member of the DRAWITEMSTRUCT structure defines the drawing action that is to be performed.

By default, this member function does nothing. Override this member function to implement drawing for an owner-draw CStatusBarCtrl object.

The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before this member function terminates.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CWnd::OnDrawItem


CStatusBarCtrl::GetBorders

BOOL GetBorders( int* pBorders ) const;

BOOL GetBorders( int& nHorz, int& nVert, int& nSpacing ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

pBorders

Address of an integer array having 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.

nHorz

Reference to an integer that receives the width of the horizontal border.

nVert

Reference to an integer that receives the width of the vertical border.

nSpacing

Reference to an integer that receives the width of the border between rectangles.

Remarks

Call this function to retrieve the status bar control’s current widths of the horizontal and vertical borders and of the space between rectangles. These borders determine the spacing between the outside edge of the control and the rectangles within the control that contain text.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::GetParts, CStatusBarCtrl::SetParts


CStatusBarCtrl::GetParts

int GetParts( int nParts, int* pParts ) const;

Return Value

The number of parts in the control if successful, or zero otherwise.

Parameters

nParts

Number of parts for which to retrieve coordinates. If this parameter is greater than the number of parts in the control, the message retrieves coordinates for existing parts only.

pParts

Address of an integer array having the same number of elements as the number of 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 status bar.

Remarks

Call this function to retrieve a count of the parts in a status bar control. This member function also retrieves the coordinate of the right edge of the given number of parts.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::GetBorders, CStatusBarCtrl::SetParts


CStatusBarCtrl::GetRect

BOOL GetRect( int nPane, LPRECT lpRect ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

nPane

Zero-based index of the part whose bounding rectangle is to be retrieved.

lpRect

Address of a RECT structure that receives the bounding rectangle.

Remarks

Retrieves the bounding rectangle of a part in a status bar control.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::GetParts


CStatusBarCtrl::GetText

int GetText( LPCTSTR lpszText, int nPane, int* pType ) const;

Return Value

The length, in characters, of the text.

Parameters

lpszText

Address of the buffer that receives the text. This parameter is a null-terminated string.

nPane

Zero-based index of the part from which to retrieve text.

pType

Pointer to an integer that receives the type information. The type can be one of these values:

  • 0 The text is drawn with a border to appear lower than the plane of the status bar.

  • 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 status bar.

  • SBT_OWNERDRAW If the text has the SBT_OWNERDRAW drawing type, pType receives this message and returns the 32-bit value associated with the text instead of the length and operation type.

Remarks

Call this function to retrieve the text from the given part of a status bar control.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::SetText, CStatusBarCtrl::GetTextLength


CStatusBarCtrl::GetTextLength

int GetTextLength( int nPane, int* pType ) const;

Return Value

The length, in characters, of the text.

Parameters

nPane

Zero-based index of the part from which to retrieve text.

pType

Pointer to an integer that receives the type information. The type can be one of these values:

  • 0 The text is drawn with a border to appear lower than the plane of the status bar.

  • 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 status bar.

Remarks

Call this function to retrieve the length, in characters, of the text from the given part of a status bar control.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::GetText, CStatusBarCtrl::SetText


CStatusBarCtrl::GetTipText

CString GetTipText( int nPane ) const;

Return Value

A CString object containing the text to be used in the tooltip.

Parameters

nPane

The zero-based index of status bar pane to receive the tooltip text.

Remarks

This member function implements the behavior of the Win32 message SB_GETTIPTEXT, as described in the Platform SDK.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::SetTipText


CStatusBarCtrl::IsSimple

BOOL IsSimple( ) const;

Return Value

Nonzero if the status window control is in simple mode; otherwise zero.

Remarks

This member function implements the behavior of the Win32 message SB_ISSIMPLE, as described in the Platform SDK.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::SetSimple


CStatusBarCtrl::SetBkColor

COLORREF SetBkColor( COLORREF cr );

Return Value

A COLORREF value that represents the previous default background color.

Parameters

cr

COLORREF value that specifies the new background color. Specify the CLR_DEFAULT value to cause the status bar to use its default background color.

Remarks

This member function implements the behavior of the Win32 message SB_SETBKCOLOR, as described in the Platform SDK.


CStatusBarCtrl::SetIcon

BOOL SetIcon( int nPane, HICON hIcon );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nPane

The zero-based index of the pane 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.

Remarks

This member function implements the behavior of the Win32 message SB_SETICON, as described in the Platform SDK.


CStatusBarCtrl::SetMinHeight

void SetMinHeight( int nMin );

Parameters

nMin

Minimum height, in pixels, of the control.

Remarks

Call this function to set the minimum height of a status bar control’s drawing area. The minimum height is the sum of nMin and twice the width, in pixels, of the vertical border of the status bar control.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::GetRect, CStatusBarCtrl::GetBorders


CStatusBarCtrl::SetParts

BOOL SetParts( int nParts, int* pWidths );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nParts

Number of parts to set. The number of parts cannot be greater than 255.

pWidths

Address of an integer array having 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 control.

Remarks

Call this function to set the number of parts in a status bar control and the coordinate of the right edge of each part.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::GetBorders, CStatusBarCtrl::GetParts


CStatusBarCtrl::SetSimple

BOOL SetSimple( BOOL bSimple = TRUE );

Return Value

Zero if an error occurs.

Parameters

bSimple

Display-type flag. If this parameter is TRUE, the control displays simple text; if it is FALSE, it displays multiple parts.

Remarks

Call this function to specify whether a status bar control displays simple text or displays all control parts set by a previous call to SetParts.

If the status bar control is being changed from nonsimple to simple, or vice versa, the control is immediately redrawn.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::SetParts


CStatusBarCtrl::SetText

BOOL SetText( LPCTSTR lpszText, int nPane, int nType );

Return Value

Nonzero if successful; otherwise zero.

Parameters

lpszText

Address of a null-terminated string specifying the text to set. If nType is SBT_OWNERDRAW, lpszText represents 32 bits of data.

nPane

Zero-based index of the part to set. If this value is 255, the status bar control is assumed to be a simple control having only one part.

nType

Type of drawing operation. It can be one of these values:

  • 0 The text is drawn with a border to appear lower than the plane of the status bar.

  • 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 status bar.

Remarks

Call this function to set the text in the given part of a status bar control. The message invalidates the portion of the control that has changed, causing it to display the new text when the control next receives the WM_PAINT message.

CStatusBarCtrl Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::GetText, CStatusBarCtrl::GetTextLength


CStatusBarCtrl::SetTipText

void SetTipText( int nPane, LPCTSTR pszTipText );

Parameters

nPane

The zero-based index of status bar pane to receive the tooltip text.

pszTipText

A pointer to a string containing the tooltip text.

Remarks

This member function implements the behavior of the Win32 message SB_SETTIPTEXT, as described in the Platform SDK.

CStatusBar Overview | Class Members | Hierarchy Chart

See Also CStatusBarCtrl::GetTipText


CStdioFile

A CStdioFile object represents a C run-time stream file as opened by the run-time function fopen. Stream files are buffered and can be opened in either text mode (the default) or binary mode.

Text mode provides special processing for carriage return–linefeed pairs. When you write a newline character (0x0A) to a text-mode CStdioFile object, the byte pair (0x0A, 0x0D) is sent to the file. When you read, the byte pair (0x0A, 0x0D) is translated to a single 0x0A byte.

The CFile functions Duplicate, LockRange, and UnlockRange are not supported for CStdioFile.

If you call these functions on a CStdioFile, you will get a CNotSupportedException.

For more information on using CStdioFile, see the article Files in MFC in Visual C++ Programmer’s Guide and File Handling in the Run-Time Library Reference.

#include <afx.h>

Class Members | Base Class | Hierarchy Chart

See Also CFile, CFile::Duplicate, CFile::LockRange, CFile::UnlockRange, CNotSupportedException


CStdioFile Class Members

Data Members

m_pStream Contains a pointer to an open file.

Construction

CStdioFile Constructs a CStdioFile object from a path or file pointer.

Text Read/Write

ReadString | Reads a single line of text.
WriteString | Writes a single line of text.


CStdioFile::CStdioFile

CStdioFile( );

CStdioFile( FILE* pOpenStream );

CStdioFile( LPCTSTR lpszFileName, UINT nOpenFlags );
throw( CFileException );

Parameters

pOpenStream

Specifies the file pointer returned by a call to the C run-time function fopen.

lpszFileName

Specifies a string that is the path to the desired file. The path can be relative or absolute.

nOpenFlags

Sharing and access mode. Specifies the action to take when the file is opened. You can combine options by using the bitwise OR (|) operator. One access permission and a text-binary specifier are required; the create and noInherit modes are optional. See CFile::CFile for a list of mode options and other flags. In MFC version 3.0 and later, share flags are allowed.

Remarks

The default version of the constructor works in conjunction with the CFile::Open member function to test errors.

The one-parameter version constructs a CStdioFile object from a pointer to a file that is already open. Allowed pointer values include the predefined input/output file pointers stdin, stdout, or stderr.

The two-parameter version constructs a CStdioFile object and opens the corresponding operating-system file with the given path.

CFileException is thrown if the file cannot be opened or created.

Example

// example for CStdioFile::CStdioFile
char* pFileName = "test.dat";
CStdioFile f1;
if( !f1.Open( pFileName, CFile::modeCreate
       | CFile::modeWrite | CFile::typeText ) ) {
   #ifdef _DEBUG
      afxDump << "Unable to open file" << "\n";
   #endif
   exit( 1 );
}
CStdioFile f2( stdout );
TRY
{
   CStdioFile f3( pFileName,
      CFile::modeCreate | CFile::modeWrite | CFile::typeText );
}
CATCH( CFileException, e )
{
   #ifdef _DEBUG
      afxDump << "File could not be opened "
              << e->m_cause << "\n";
   #endif
}
END_CATCH


CStdioFile::ReadString

virtual LPTSTR ReadString( LPTSTR lpsz, UINT nMax );
throw( CFileException );

BOOL ReadString(CString& rString);
throw( CFileException );

Return Value

A pointer to the buffer containing the text data. NULL if end-of-file was reached without reading any data; or if boolean, FALSE if end-of-file was reached without reading any data.

Parameters

lpsz

Specifies a pointer to a user-supplied buffer that will receive a null-terminated text string.

nMax

Specifies the maximum number of characters to read, not counting the terminating null character.

rString

A reference to a CString object that will contain the string when the function returns.

Remarks

Reads text data into a buffer, up to a limit of nMax–1 characters, from the file associated with the CStdioFile object. Reading is stopped by the first newline character. If, in that case, fewer than nMax–1 characters have been read, a newline character is stored in the buffer. A null character (‘\0’) is appended in either case.

CFile::Read is also available for text-mode input, but it does not terminate on a carriage return–linefeed pair.

Note The CString version of this function removes the '/n' if present; the LPTSTR version does not.

Example

// example for CStdioFile::ReadString
extern CStdioFile f;
char buf[100];

f.ReadString( buf, 99 );

CStdioFile Overview | Class Members | Hierarchy Chart

See Also CStdioFile::WriteString, CFile::Read


CStdioFile::WriteString

virtual void WriteString( LPCTSTR lpsz );
throw( CFileException );

Parameters

lpsz

Specifies a pointer to a buffer containing a null-terminated text string.

Remarks

Writes data from a buffer to the file associated with the CStdioFile object. The terminating null character (‘\0’) is not written to the file. Any newline character in lpsz is written to the file as a carriage return–linefeed pair.

WriteString throws an exception in response to several conditions, including the disk-full condition.

This is a text-oriented write function available to CStdioFile and its descendents, and to CArchive. CFile::Write is also available, but rather than terminating on a null character, it writes the requested number of bytes to the file.

Example

// example for CStdioFile::WriteString
extern CStdioFile f;
char buf[] = "test string";

f.WriteString( buf );

CStdioFile Overview | Class Members | Hierarchy Chart

See Also CArchive::ReadString, CFile::Write


CStdioFile::m_pStream

Remarks

The m_pStream data member is the pointer to an open file as returned by the C run-time function fopen. It is NULL if the file has never been opened or has been closed.


CString

CString does not have a base class.

A CString object consists of a variable-length sequence of characters. CString provides functions and operators using a syntax similar to that of Basic. Concatenation and comparison operators, together with simplified memory management, make CString objects easier to use than ordinary character arrays.

CString is based on the TCHAR data type. If the symbol _UNICODE is defined for your program, TCHAR is defined as type wchar_t, a 16-bit character type; otherwise, it is defined as char, the normal 8-bit character type. Under Unicode, then, CString objects are composed of 16-bit characters. Without Unicode, they are composed of 8-bit char type.

When not using _UNICODE, CString is enabled for multibyte character sets (MBCS, also known as double-byte character sets, DBCS). Note that for MBCS strings, CString still counts, returns, and manipulates strings based on 8-bit characters, and your application must interpret MBCS lead and trail bytes itself.

CString objects also have the following characteristics:

  • CString objects can grow as a result of concatenation operations.

  • CString objects follow “value semantics.” Think of a CString object as an actual string, not as a pointer to a string.

  • You can freely substitute CString objects for const char* and LPCTSTR function arguments.

  • A conversion operator gives direct access to the string’s characters as a read-only array of characters (a C-style string).

Tip Where possible, allocate CString objects on the frame rather than on the heap. This saves memory and simplifies parameter passing.

CString assists you in conserving memory space by allowing two strings sharing the same value also to share the same buffer space. However, if you attempt to change the contents of the buffer directly (not using MFC), you can alter both strings unintentionally. CString provides two member functions, CString::LockBuffer and CString::UnlockBuffer, to help you protect your data. When you call LockBuffer, you create a copy of a string, then set the reference count to -1, which "locks" the buffer. While the buffer is locked, no other string can reference the data in that string, and the locked string will not reference another string. By locking the string in the buffer, you ensure that the string’s exclusive hold on the data will remain intact. When you have finished with the data, call UnlockBuffer to reset the reference count to 1.

For more information, see the Strings in MFC and Strings: Unicode and Multibyte Character Set (MBCS) Support articles in Visual C++ Programmer’s Guide and String Manipulation Routines in the Run-Time Library Reference.

#include <afx.h>

Class Members | Hierarchy Chart

Sample MFC Sample HELLO

See Also In Visual C++ Programmer’s Guide: Strings: Basic CString Operations, Strings: CString Semantics, Strings: CString Operations Relating to C-Style Strings, Strings: CString Exception Cleanup, Strings: CString Argument Passing


CString Class Members

Construction
The String as an Array
Assignment/Concatenation
Comparison
Extraction
Other Conversions
Searching
Archive/Dump
Buffer Access
Windows-Specific

Construction

CString Constructs CString objects in various ways.

The String as an Array

GetLength | Returns the number of characters in a CString object. For multibyte characters, counts each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.
IsEmpty | Tests whether a CString object contains no characters.
Empty | Forces a string to have 0 length.
GetAt | Returns the character at a given position.
operator [] | Returns the character at a given position — operator substitution for GetAt.
SetAt | Sets a character at a given position.
operator LPCTSTR | Directly accesses characters stored in a CString object as a C-style string.

Assignment/Concatenation

operator = | Assigns a new value to a CString object.
operator + | Concatenates two strings and returns a new string.
operator += | Concatenates a new string to the end of an existing string.

Comparison

operator == <, etc. | Comparison operators (case sensitive).
Compare | Compares two strings (case sensitive).
CompareNoCase | Compares two strings (case insensitive).
Collate | Compares two strings (case sensitive, uses locale-specific information).
CollateNoCase | Compares two strings (case insensitive, uses locale-specific information).

Extraction

Mid | Extracts the middle part of a string (like the Basic MID$ function).
Left | Extracts the left part of a string (like the Basic LEFT$ function).
Right | Extracts the right part of a string (like the Basic RIGHT$ function).
SpanIncluding | Extracts a substring that contains only the characters in a set.
SpanExcluding | Extracts a substring that contains only the characters not in a set.

Other Conversions

MakeUpper | Converts all the characters in this string to uppercase characters.
MakeLower | Converts all the characters in this string to lowercase characters.
MakeReverse | Reverses the characters in this string.
Replace | Replaces indicated characters with other characters.
Remove | Removes indicated characters from a string.
Insert | Inserts a single character or a substring at the given index within the string.
Delete | Deletes a character or characters from a string.
Format | Format the string as sprintf does.
FormatV | Formats the string as vsprintf does.
TrimLeft | Trim leading whitespace characters from the string.
TrimRight | Trim trailing whitespace characters from the string.
FormatMessage | Formats a message string.

Searching

Find | Finds a character or substring inside a larger string.
ReverseFind | Finds a character inside a larger string; starts from the end.
FindOneOf | Finds the first matching character from a set.

Archive/Dump

operator << | Inserts a CString object to an archive or dump context.
operator >> | Extracts a CString object from an archive.

Buffer Access

GetBuffer | Returns a pointer to the characters in the CString.
GetBufferSetLength | Returns a pointer to the characters in the CString, truncating to the specified length.
ReleaseBuffer | Releases control of the buffer returned by GetBuffer.
FreeExtra | Removes any overhead of this string object by freeing any extra memory previously allocated to the string.
LockBuffer | Disables reference counting and protects the string in the buffer.
UnlockBuffer | Enables reference counting and releases the string in the buffer.

Windows-Specific

AllocSysString | Allocates a BSTR from CString data.
SetSysString | Sets an existing BSTR object with data from a CString object.
LoadString | Loads an existing CString object from a Windows resource.
AnsiToOem | Makes an in-place conversion from the ANSI character set to the OEM character set.
OemToAnsi | Makes an in-place conversion from the OEM character set to the ANSI character set.


CString::AllocSysString

BSTR AllocSysString ( ) const;
throw( CMemoryException );

Return Value

Points to the newly allocated string.

Remarks

Allocates a new OLE Automation–compatible string of the type BSTR and copies the contents of the CString object into it, including the terminating null character. A CMemoryException is thrown if insufficient memory exists. This function is normally used to return strings for OLE Automation.

Use ::SysFreeString in the rare case that you need to deallocate the returned string.

Note You must link with MFCO42D.DLL to obtain this function if you are using MFC in a shared library and building in debug mode. You can cause the linker to get MFCO42D.DLL automatically by including <afxdisp.h> in your STDAFX.H file.

For more information about OLE allocation functions in Windows, see ::SysAllocString and ::SysFreeString in the Win32 SDK OLE Programmer’s Reference.

CString Overview | Class Members | Hierarchy Chart

See Also ::SysAllocString, ::SysFreeString, CMemoryException


CString::AnsiToOem

void AnsiToOem( );

Remarks

Converts all the characters in this CString object from the ANSI character set to the OEM character set. See the ANSI Character Codes Chart in the C++ Language Reference.

The function is not available if _UNICODE is defined.

CString Overview | Class Members | Hierarchy Chart

See Also CString::OemToAnsi


CString::Collate

int Collate( LPCTSTR lpsz ) const;

Return Value

Zero if the strings are identical, <0 if this CString object is less than lpsz, or >0 if this CString object is greater than lpsz.

Parameters

lpsz

The other string used for comparison.

Remarks

Compares this CString object with another string using the generic-text function _tcscoll. The generic-text function _tcscoll, which is defined in TCHAR.H, maps to either strcoll, wcscoll, or _mbscoll depending on the character set that is defined at compile time. Each of these functions performs a case-sensitive comparison of the strings according to the code page currently in use. For more information, see strcat, wcscat, _mbscat in the Run-Time Library Reference.

CString Overview | Class Members | Hierarchy Chart

See Also CString::Compare, CString::CompareNoCase


CString::CollateNoCase

int CollateNoCase( LPCTSTR lpsz ) const;

Return Value

Zero if the strings are identical (ignoring case), <0 if this CString object is less than lpsz (ignoring case), or >0 if this CString object is greater than lpsz (ignoring case).

Parameters

lpsz

A pointer to the other string used for comparison.

Remarks

Compares this CString object with another string using the generic-text function _tcscoll. The generic-text function _tcscoll, which is defined in TCHAR.H, maps to either stricoll, wcsicoll, or _mbsicoll depending on the character set that is defined at compile time. Each of these functions performs a case-insensitive comparison of the strings, according to the code page currently in use.

CString Overview | Class Members | Hierarchy Chart

See Also CString::Collate, CString::CompareNoCase, CString::Compare


CString::Compare

int Compare( LPCTSTR lpsz ) const;

Return Value

Zero if the strings are identical, < 0 if this CString object is less than lpsz, or > 0 if this CString object is greater than lpsz.

Parameters

lpsz

The other string used for comparison.

Remarks

Compares this CString object with another string using the generic-text function _tcscmp. The generic-text function _tcscmp, which is defined in TCHAR.H, maps to either strcmp, wcscmp, or _mbscmp depending on the character set that is defined at compile time. Each of these functions performs a case-sensitive comparison of the strings, and is not affected by locale. For more information, see strcmp, wcscmp, _mbscmp in the Run-Time Library Reference.

Example

The following example demonstrates the use of CString::Compare.

// example for CString::Compare
CString s1( "abc" );
CString s2( "abd" );
ASSERT( s1.Compare( s2 ) == -1 ); // Compare with another CString.
ASSERT( s1.Compare( "abe" ) == -1 ); // Compare with LPTSTR string.

CString Overview | Class Members | Hierarchy Chart

See Also CString::CompareNoCase, CString::Collate, CString::CollateNoCase


CString::CompareNoCase

int CompareNoCase( LPCTSTR lpsz ) const;

Return Value

Zero if the strings are identical (ignoring case), <0 if this CString object is less than lpsz (ignoring case), or >0 if this CString object is greater than lpsz (ignoring case).

Remarks

Compares this CString object with another string using the generic-text function _tcsicmp. The generic-text function _tcsicmp, which is defined in TCHAR.H, maps to either _stricmp, _wcsicmp, _mbsicmp depending on the character set that is defined at compile time. Each of these functions performs a case-insensitive comparison of the strings, and is not affected by locale. For more information, see _stricmp, _wcsicmp, _mbsicmp in the Run-Time Library Reference.

Example

The following example demonstrates the use of CString::CompareNoCase.

// example for CString::CompareNoCase
CString s1( "abc" );
CString s2( "ABD" );
ASSERT( s1.CompareNoCase( s2 ) == -1 ); // Compare with a CString.
ASSERT( s1.Compare( "ABE" ) == -1 ); // Compare with LPTSTR string.

CString Overview | Class Members | Hierarchy Chart

See Also CString::Compare, CString::Collate, CString::CollateNoCase


CString::CString

CString( );

CString( const CString& stringSrc );
throw( CMemoryException );

CString( TCHAR ch, int nRepeat = 1 );
throw( CMemoryException );

CString( LPCTSTR lpch, int nLength );
throw( CMemoryException );

CString( const unsigned char* psz );
throw( CMemoryException );

CString( LPCWSTR lpsz );
throw( CMemoryException );

CString( LPCSTR lpsz );
throw( CMemoryException );

Parameters

stringSrc

An existing CString object to be copied into this CString object.

ch

A single character to be repeated nRepeat times.

nRepeat

The repeat count for ch.

lpch

A pointer to an array of characters of length nLength, not null-terminated.

nLength

A count of the number of characters in pch.

psz

A null-terminated string to be copied into this CString object.

lpsz

A null-terminated string to be copied into this CString object.

Remarks

Each of these constructors initializes a new CString object with the specified data.

Because the constructors copy the input data into new allocated storage, you should be aware that memory exceptions may result. Note that some of these constructors act as conversion functions. This allows you to substitute, for example, an LPTSTR where a CString object is expected.

Several forms of the constructor have special purposes:

  • CString( LPCSTR lpsz ) Constructs a Unicode CString from an ANSI string. You can also use this constructor to load a string resource as shown in the example below.

  • CString( LPCWSTR lpsz ) Constructs a CString from a Unicode string.

  • CString( const unsigned char* psz ) Allows you to construct a CString from a pointer to unsigned char.

For more information, see Strings: CString Exception Cleanup in Visual C++ Programmer’s Guide

Example

The following example demonstrates the use of CString::CString.

// example for CString::CString
CString s1;                    // Empty string
CString s2( "cat" );           // From a C string literal
CString s3 = s2;               // Copy constructor
CString s4( s2 + " " + s3 );   // From a string expression

CString s5( 'x' );             // s5 = "x"
CString s6( 'x', 6 );          // s6 = "xxxxxx"

CString s7((LPCSTR)ID_FILE_NEW); // s7 = "Create a new document"

CString city = "Philadelphia"; // NOT the assignment operator

CString Overview | Class Members | Hierarchy Chart

See Also CString::operator =


CString::Delete

int Delete( int nIndex, int nCount = 1 )
throw( CMemoryException );

Return Value

The length of the changed string.

Parameters

nIndex

The index of the first character to delete.

nCount

The number of characters to be removed.

Remarks

Call this member function to delete a character or characters from a string starting with the character at nIndex. If nCount is longer than the string, the remainder of the string will be removed.

Example

//The following example demonstrates the use of CString::Delete.
   str2 = "Hockey is best!";
   printf("Before: %s\n", (LPCTSTR) str2);
   int n = str2.Delete(6, 3);
   printf("After: %s\n", (LPCTSTR) str2);
   ASSERT(n == str2.GetLength());

//this code generates this line of output:

Before: Hockey is best!
After: Hockey best!

CString Overview | Class Members | Hierarchy Chart

See Also CString::Insert


CString::Empty

void Empty( );

Remarks

Makes this CString object an empty string and frees memory as appropriate.

For more information, see Strings: CString Exception Cleanup n Visual C++ Programmer’s Guide

Example

The following example demonstrates the use of CString::Empty.

// example for CString::Empty
CString s( "abc" );
s.Empty();
ASSERT( s.GetLength( ) == 0 );

CString Overview | Class Members | Hierarchy Chart

See Also CString::IsEmpty


CString::Find

int Find( TCHAR ch ) const;

int Find( LPCTSTR lpszSub ) const;

int Find( TCHAR ch, int nStart ) const;

int Find( LPCTSTR pstr, int nStart ) const;

Return Value

The zero-based index of the first character in this CString object that matches the requested substring or characters; -1 if the substring or character is not found.

Parameters

ch

A single character to search for.

lpszSub

A substring to search for.

nStart

The index of the character in the string to begin the search with, or 0 to start from the beginning. The character at nStart is excluded from the search if nStart is not equal to 0.

pstr

A pointer to a string to search for.

Remarks

Searches this string for the first match of a substring. The function is overloaded to accept both single characters (similar to the run-time function strchr) and strings (similar to strstr).

Example

// First example demonstrating
// CString::Find ( TCHAR ch )
CString s( "abcdef" );
ASSERT( s.Find( 'c' ) == 2 );
ASSERT( s.Find( "de" ) == 3 );

// Second example demonstrating
// CString::Find( TCHAR ch, int nStart )
CString str("The stars are aligned");
int n = str.Find('e', 5);
ASSERT(n == 12);

CString Overview | Class Members | Hierarchy Chart

See Also CString::ReverseFind, CString::FindOneOf


CString::FindOneOf

int FindOneOf( LPCTSTR lpszCharSet ) const;

Return Value

The zero-based index of the first character in this string that is also in lpszCharSet; –1 if there is no match.

Parameters

lpszCharSet

String containing characters for matching.

Remarks

Searches this string for the first character that matches any character contained in lpszCharSet.

Example

The following example demonstrates the use of CString::FindOneOf.

// example for CString::FindOneOf
CString s( "abcdef" );
ASSERT( s.FindOneOf( "xd" ) == 3 ); // 'd' is first match

CString Overview | Class Members | Hierarchy Chart

See Also CString::Find


CString::Format

void Format( LPCTSTR lpszFormat, ... );

void Format( UINT nFormatID, ... );

Parameters

lpszFormat

A format-control string.

nFormatID

The string resource identifier that contains the format-control string.

Remarks

Call this member function to write formatted data to a CString in the same way that sprintf formats data into a C-style character array. This function formats and stores a series of characters and values in the CString. Each optional argument (if any) is converted and output according to the corresponding format specification in lpszFormat or from the string resource identified by nFormatID.

The call will fail if the string object itself is offered as a parameter to Format. For example, the following code:

CString str = "Some Data";
str.Format("%s%d", str, 123);   // Attention: str is also used in the parameter list.

will cause unpredictable results.

When you pass a character string as an optional argument, you must cast it explicitly as LPCTSTR. The format has the same form and function as the format argument for the printf function. (For a description of the format and arguments, see printf in the Run-Time Library Reference.) A null character is appended to the end of the characters written.

For more information, see sprintf in the Run-Time Library Reference.

CString Overview | Class Members | Hierarchy Chart

See Also CString::GetBuffer, CString::FormatV


CString::FormatV

void FormatV( LPCTSTR lpszFormat, va_list argList );

Parameters

lpszFormat

A format-control string.

argList

A list of arguments to be passed.

Remarks

Call this member function to write a formatted string and a variable list of arguments to a CString object in the same way that vsprintf formats data into a C-style character array. This function formats and stores a series of characters and values in the CString. The string and arguments are converted and output according to the corresponding format specification in lpszFormat.

The call will fail if the string object itself is offered as a parameter to FormatV. For example, the following code:

CString str = "Some Data";
str.FormatV("%s%d", str, 123);   // Attention: str is also used in the parameter list.

will cause unpredictable results.

For more information, see vsprintf in the Run-Time Library Reference.

Example

//Using CString::FormatV(), you can write functions like the following:

void WriteLogEntry(CStdioFile& refFile, LPCTSTR pstrFormat, ...)
{
   CTime timeWrite;
   timeWrite = CTime::GetCurrentTime();

   // write the time out
   CString str = timeWrite.Format("%d %b %y %H:%M:%S - ");
   refFile.Write(str, str.GetLength());

   // format and write the data we were given
   va_list args;
   va_start(args, pstrFormat);
   str.FormatV(pstrFormat, args);
   refFile.Write(str, str.GetLength());

   // put a newline
   refFile.Write("\n", 1);
   return;
}

You can call the above function with any number of parameters, for example:

   WriteLogEntry(fileLog, "Program started");
   WriteLogEntry(fileLog, "Processed %d bytes", 91341);
   WriteLogEntry(fileLog, "%d error(s) found in %d line(s)", 10, 1351);
   WriteLogEntry(fileLog, "Program completed");

which would add output to your fileLog file similar to the following:

   17 Apr 97 12:34:53 - Program started
   17 Apr 97 12:34:59 - Processed 91341 bytes
   17 Apr 97 12:35:22 - 10 error(s) found in 1351 line(s)
   17 Apr 97 12:35:23 - Program completed

CString Overview | Class Members | Hierarchy Chart

See Also CString::Format, va_start


CString::FormatMessage

void FormatMessage( LPCTSTR lpszFormat, ... );

void FormatMessage( UINT nFormatID, ... );

Parameters

lpszFormat

Points to the format-control string. It will be scanned for inserts and formatted accordingly. The format string is similar to run-time function printf-style format strings, except it allows for the parameters to be inserted in an arbitrary order.

nFormatID

The string resource identifier that contains the unformatted message text.

Remarks

Call this member function to format a message string. The function requires a message definition as input. The message definition is determined by lpszFormat or from the string resource identified by nFormatID. The function copies the formatted message text to the CString, processing any embedded insert sequences if requested.

Each insert must have a corresponding parameter following the lpszFormat or nFormatID parameter. Within the message text, several escape sequences are supported for dynamically formatting the message. For a description of these escape sequences and their meanings, see the Windows ::FormatMessage function in the Win32 SDK Programmer’s Reference.

CString Overview | Class Members | Hierarchy Chart

See Also ::FormatMessage, CString::LoadString, CString::Format


CString::FreeExtra

void FreeExtra( );

Remarks

Call this member function to free any extra memory previously allocated by the string but no longer needed. This should reduce the memory overhead consumed by the string object. The function reallocates the buffer to the exact length returned by GetLength.


CString::GetAt

TCHAR GetAt( int nIndex ) const;

Return Value

A TCHAR containing the character at the specified position in the string.

Parameters

nIndex

Zero-based index of the character in the CString object. The nIndex parameter must be greater than or equal to 0 and less than the value returned by GetLength. The Debug version of the Microsoft Foundation Class Library validates the bounds of nIndex; the Release version does not.

Remarks

You can think of a CString object as an array of characters. The GetAt member function returns a single character specified by an index number. The overloaded subscript ([]) operator is a convenient alias for GetAt.

Example

The following example demonstrates the use of CString::GetAt.

// example for CString::GetAt
CString s( "abcdef" );
ASSERT( s.GetAt(2) == 'c' );

CString Overview | Class Members | Hierarchy Chart

See Also CString::GetAt, CString::GetLength, CString::operator []


CString::GetBuffer

LPTSTR GetBuffer( int nMinBufLength );
throw( CMemoryException );

Return Value

An LPTSTR pointer to the object’s (null-terminated) character buffer.

Parameters

nMinBufLength

The minimum size of the character buffer in characters. This value does not include space for a null terminator.

Remarks

Returns a pointer to the internal character buffer for the CString object. The returned LPTSTR is not const and thus allows direct modification of CString contents.

If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.

The address returned by GetBuffer may not be valid after the call to ReleaseBuffer since additional CString operations may cause the CString buffer to be reallocated. The buffer will not be reallocated if you do not change the length of the CString.

The buffer memory will be freed automatically when the CString object is destroyed.

Note that if you keep track of the string length yourself, you should not append the terminating null character. You must, however, specify the final string length when you release the buffer with ReleaseBuffer. If you do append a terminating null character, you should pass –1 for the length to ReleaseBuffer and ReleaseBuffer will perform a strlen on the buffer to determine its length.

Example

The following example demonstrates the use of CString::GetBuffer.

// example for CString::GetBuffer
CString s( "abcd" );
#ifdef _DEBUG
afxDump << "CString s " << s << "\n";
#endif
LPTSTR p = s.GetBuffer( 10 );
strcpy( p, "Hello" );   // directly access CString buffer
s.ReleaseBuffer( );
#ifdef _DEBUG
afxDump << "CString s " << s << "\n";
#endif

CString Overview | Class Members | Hierarchy Chart

See Also CString::GetBufferSetLength, CString::ReleaseBuffer


CString::GetBufferSetLength

LPTSTR GetBufferSetLength( int nNewLength );
throw( CMemoryException );

Return Value

An LPTSTR pointer to the object’s (null-terminated) character buffer.

Parameters

nNewLength

The exact size of the CString character buffer in characters.

Remarks

Returns a pointer to the internal character buffer for the CString object, truncating or growing its length if necessary to exactly match the length specified in nNewLength. The returned LPTSTR pointer is not const and thus allows direct modification of CString contents.

If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.

The address returned by GetBufferSetLength may not be valid after the call to ReleaseBuffer since additional CString operations may cause the CString buffer to be reallocated. The buffer will not be reassigned if you do not change the length of the CString.

The buffer memory will be freed automatically when the CString object is destroyed.

Note that if you keep track of the string length yourself, you should not append the terminating null character. You must, however, specify the final string length when you release the buffer with ReleaseBuffer. If you do append a terminating null character when you call ReleaseBuffer, you should pass –1 (the default) for the length. ReleaseBuffer will perform a strlen on the buffer to determine its length.

For more information about reference counting, see the following articles:

  • Managing Object Lifetimes through Reference Counting in the Win32 SDK Programmer’s Reference

  • Implementing Reference Counting in the Win32 SDK Programmer’s Reference

  • Rules for Managing Reference Counts in the Win32 SDK Programmer’s Reference

CString Overview | Class Members | Hierarchy Chart

See Also CString::GetBuffer, CString::ReleaseBuffer


CString::GetLength

int GetLength( ) const;

Return Value

A count of the bytes in the string.

Remarks

Call this member function to get a count of the bytes in this CString object. The count does not include a null terminator.

For multibyte character sets (MBCS), GetLength counts each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two bytes.

Example

The following example demonstrates the use of CString::GetLength.

// example for CString::GetLength
CString s( "abcdef" );
ASSERT( s.GetLength() == 6 );

CString Overview | Class Members | Hierarchy Chart

See Also CString::IsEmpty


CString::Insert

int Insert( int nIndex, TCHAR ch )
throw( CMemoryException );

int Insert( int nIndex, LPCTSTR pstr )
throw( CMemoryException );

Return Value

The length of the changed string.

Parameters

nIndex

The index of the character before which the insertion will take place.

ch

The character to be inserted.

pstr

A pointer to the substring to be inserted.

Remarks

Call this member function to insert a single character or a substring at the given index within the string. The nIndex parameter identifies the first character that will be moved to make room for the character or substring. If nIndex is zero, the insertion will occur before the entire string. If nIndex is higher than the length of the string, the function will concatenate the present string and the new material provided by either ch or pstr.

Example

//The following example demonstrates the use of CString::Insert.
   CString str("HockeyBest");
   int n = str.Insert(6, "is ");
   ASSERT(n == str.GetLength());
   printf("1: %s\n", (LPCTSTR) str);

   n = str.Insert(6, ' ');
   ASSERT(n == str.GetLength());
   printf("2: %s\n", (LPCTSTR) str);

   n = str.Insert(555, '!');
   ASSERT(n == str.GetLength());
   printf("3: %s\n", (LPCTSTR) str);

//this code generates these lines of output:

1: Hockeyis Best
2: Hockey is Best
3: Hockey is Best!

CString Overview | Class Members | Hierarchy Chart

See Also CString::Delete, CString::operator +


CString::IsEmpty

BOOL IsEmpty( ) const;

Return Value

Nonzero if the CString object has 0 length; otherwise 0.

Remarks

Tests a CString object for the empty condition.

Example

The following example demonstrates the use of CString::IsEmpty.

// example for CString::IsEmpty
CString s;
ASSERT( s.IsEmpty() );

CString Overview | Class Members | Hierarchy Chart

See Also CString::GetLength


CString::Left

CString Left( int nCount ) const;
throw( CMemoryException );

Return Value

A CString object containing a copy of the specified range of characters. Note that the returned CString object may be empty.

Parameters

nCount

The number of characters to extract from this CString object.

Remarks

Extracts the first (that is, leftmost) nCount characters from this CString object and returns a copy of the extracted substring. If nCount exceeds the string length, then the entire string is extracted. Left is similar to the Basic LEFT$ function (except that indexes are zero-based).

For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.

Example

The following example demonstrates the use of CString::Left.

// example for CString::Left
CString s( _T("abcdef") );
ASSERT( s.Left(2) == _T("ab") );

CString Overview | Class Members | Hierarchy Chart

See Also CString::Mid, CString::Right


CString::LoadString

BOOL LoadString( UINT nID );
throw( CMemoryException );

Return Value

Nonzero if resource load was successful; otherwise 0.

Parameters

nID

A Windows string resource ID.

Remarks

Reads a Windows string resource, identified by nID, into an existing CString object.

Example

The following example demonstrates the use of CString::LoadString.

// example for CString::LoadString
#define IDS_FILENOTFOUND 1
CString s;
if (! s.LoadString( IDS_FILENOTFOUND ))
{
    AfxMessageBox("Error Loading String: IDS_FILENOTFOUND");
    ...
}


CString::LockBuffer

LPTSTR LockBuffer( );

Return Value

A pointer to a CString object or a NULL-terminated string.

Remarks

Call this member function to lock a string in the buffer.

By calling LockBuffer, you create a copy of the string, and then set the reference count to -1. When the reference count is set to -1, the string in the buffer is considered to be in a "locked" state. While in a locked state, the string is protected in two ways:

  • No other string can get a reference to the data in the locked string, even if that string is assigned to the locked string.

  • The locked string will never reference another string, even if that other string is copied to the locked string.

By locking the string in the buffer, you ensure that the string’s exclusive hold on the buffer will remain intact.

After you have finished with LockBuffer, call UnlockBuffer to reset the reference count to 1.

For more information about reference counting, see the following articles:

  • Managing Object Lifetimes through Reference Counting in the Win32 SDK Programmer’s Reference

  • Implementing Reference Counting in the Win32 SDK Programmer’s Reference

  • Rules for Managing Reference Counts in the Win32 SDK Programmer’s Reference

CString Overview | Class Members | Hierarchy Chart

See Also CString::UnlockBuffer, CString::GetBuffer, CString::ReleaseBuffer


CString::MakeLower

void MakeLower( );

Remarks

Converts this CString object to a lowercase string.

Example

The following example demonstrates the use of CString::MakeLower.

// example for CString::MakeLower
CString s( "ABC" );
s.MakeLower();
ASSERT( s == "abc" );

CString Overview | Class Members | Hierarchy Chart

See Also CString::MakeUpper


CString::MakeReverse

void MakeReverse( );

Remarks

Reverses the order of the characters in this CString object.

Example

The following example demonstrates the use of CString::MakeReverse.

// example for CString::MakeReverse
CString s( "abc" );
s.MakeReverse();
ASSERT( s == "cba" );


CString::MakeUpper

void MakeUpper( );

Remarks

Converts this CString object to an uppercase string.

Example

The following example demonstrates the use of CString::MakeUpper.

// example for CString::MakeUpper
CString s( "abc" );
s.MakeUpper();
ASSERT( s == "ABC" );

CString Overview | Class Members | Hierarchy Chart

See Also CString::MakeLower


CString::Mid

CString Mid( int nFirst ) const;
throw( CMemoryException );

CString Mid( int nFirst, int nCount ) const;
throw( CMemoryException );

Return Value

A CString object that contains a copy of the specified range of characters. Note that the returned CString object may be empty.

Parameters

nFirst

The zero-based index of the first character in this CString object that is to be included in the extracted substring.

nCount

The number of characters to extract from this CString object. If this parameter is not supplied, then the remainder of the string is extracted.

Remarks

Extracts a substring of length nCount characters from this CString object, starting at position nFirst (zero-based). The function returns a copy of the extracted substring. Mid is similar to the Basic MID$ function (except that indexes are zero-based).

For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.

Example

The following example demonstrates the use of CString::Mid.

// example for CString::Mid
CString s( _T("abcdef") );
ASSERT( s.Mid( 2, 3 ) == _T("cde") );

CString Overview | Class Members | Hierarchy Chart

See Also CString::Left, CString::Right


CString::OemToAnsi

void OemToAnsi( );

Remarks

Converts all the characters in this CString object from the OEM character set to the ANSI character set. See the ANSI Character Codes Chart in the C++ Language Reference.

This function is not available if _UNICODE is defined.

CString Overview | Class Members | Hierarchy Chart

See Also CString::AnsiToOem


CString::ReleaseBuffer

void ReleaseBuffer( int nNewLength = -1 );

Parameters

nNewLength

The new length of the string in characters, not counting a null terminator. If the string is null-terminated, the -1 default value sets the CString size to the current length of the string.

Remarks

Use ReleaseBuffer to end use of a buffer allocated by GetBuffer. If you know that the string in the buffer is null-terminated, you can omit the nNewLength argument. If your string is not null-terminated, then use nNewLength to specify its length. The address returned by GetBuffer is invalid after the call to ReleaseBuffer or any other CString operation.

Example

The following example demonstrates the use of CString::ReleaseBuffer.

// example for CString::ReleaseBuffer
CString s;
s = "abc";
LPTSTR p = s.GetBuffer( 1024 );
strcpy(p, "abc");   // use the buffer directly
ASSERT( s.GetLength() == 3 ); // String length = 3
s.ReleaseBuffer();  // Surplus memory released, p is now invalid.
ASSERT( s.GetLength() == 3 ); // Length still 3

CString Overview | Class Members | Hierarchy Chart

See Also CString::GetBuffer


CString::Remove

int CString::Remove( TCHAR ch );

Return Value

The count of characters removed from the string. Zero if the string isn't changed.

Parameters

ch

The character to be removed from a string.

Remarks

Call this member function to remove instances of ch from the string. Comparisons for the character are case-sensitive.

Example

//remove the lower-case letter 't' from a sentence:

CString str("This is a test.");
int n = str.Remove('t');
ASSERT(n == 2);
ASSERT(str == "This is a es.");

CString Overview | Class Members | Hierarchy Chart

See Also CString::Replace


CString::Replace

int Replace( TCHAR chOld, TCHAR chNew );

int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew );

Return Value

The number of replaced instances of the character. Zero if the string isn't changed.

Parameters

chOld

The character to be replaced by chNew.

chNew

The character replacing chOld.

lpszOld

A pointer to a string containing the character to be replaced by lpszNew.

lpszNew

A pointer to a string containing the character replacing lpszOld.

Remarks

Call this member function to replace a character with another. The first prototype of the function replaces instances of chOld with chNew in-place in the string. The second prototype of the function replaces instances of the substring lpszOld with instances of the string lpszNew.

The string may grow or shrink as a result of the replacement; that is, lpszNew and lpszOld do not have to be equal in length. Both versions perform case-sensitive matches.

Example

//First example, with old and new equal in length.

CString strZap("C--");
int n = strZap.Replace('-', '+');
ASSERT(n == 2);
ASSERT(strZap == "C++");

//Second example, old and new are of different lengths.

CString strBang("Everybody likes ice hockey");
n = strBang.Replace("hockey", "golf");
ASSERT(n == 1);
n = strBang.Replace("likes", "plays");
ASSERT(n == 1);
n = strBang.Replace("ice", NULL);
ASSERT(n == 1);
ASSERT(strBang == "Everybody plays  golf");

// note that you now have an extra space in your
// sentence. To remove the extra space, include it
// in the string to be replaced, i.e.,"ice ".

CString Overview | Class Members | Hierarchy Chart

See Also CString::Remove


CString::ReverseFind

int ReverseFind( TCHAR ch ) const;

Return Value

The index of the last character in this CString object that matches the requested character; –1 if the character is not found.

Parameters

ch

The character to search for.

Remarks

Searches this CString object for the last match of a substring. The function is similar to the run-time function strrchr.

Example

// Example for CString::ReverseFind
CString s( "abcabc" );
ASSERT( s.ReverseFind( 'b' ) == 4 );

CString Overview | Class Members | Hierarchy Chart

See Also CString::Find, CString::FindOneOf


CString::Right

CString Right( int nCount ) const;
throw( CMemoryException );

Return Value

A CString object that contains a copy of the specified range of characters. Note that the returned CString object may be empty.

Parameters

nCount

The number of characters to extract from this CString object.

Remarks

Extracts the last (that is, rightmost) nCount characters from this CString object and returns a copy of the extracted substring. If nCount exceeds the string length, then the entire string is extracted. Right is similar to the Basic RIGHT$ function (except that indexes are zero-based).

For multibyte character sets (MBCS), nCount refers to each 8-bit character; that is, a lead and trail byte in one multibyte character are counted as two characters.

Example

The following example demonstrates the use of CString::Right.

// example for CString::Right
CString s( _T("abcdef") );
ASSERT( s.Right(2) == _T("ef") );

CString Overview | Class Members | Hierarchy Chart

See Also CString::Mid, CString::Left


CString::SetAt

void SetAt( int nIndex, TCHAR ch );

Parameters

nIndex

Zero-based index of the character in the CString object. The nIndex parameter must be greater than or equal to 0 and less than the value returned by GetLength. The Debug version of the Microsoft Foundation Class Library will validate the bounds of nIndex; the Release version will not.

ch

The character to insert.

Remarks

You can think of a CString object as an array of characters. The SetAt member function overwrites a single character specified by an index number. SetAt will not enlarge the string if the index exceeds the bounds of the existing string.

CString Overview | Class Members | Hierarchy Chart

See Also CString::GetAt, CString::operator [ ]


CString::SetSysString

BSTR SetSysString( BSTR* pbstr ) const;

Return Value

The new string.

Parameters

pbstr

A pointer to a character string.

Remarks

Reallocates the BSTR pointed to by pbstr and copies the contents of the CString object into it, including the NULL character. The value of the BSTR referenced by pbstr may change. The function throws a CMemoryException if insufficient memory exists.

This function is normally used to change the value of strings passed by reference for OLE Automation.

For more information about OLE reallocation functions in Windows, see ::SysReallocStringLen and ::SysFreeString in the Win32 SDK OLE Programmer’s Referenc.


CString::SpanExcluding

CString SpanExcluding( LPCTSTR lpszCharSet ) const;
throw( CMemoryException );

Return Value

A substring that contains characters in the string that are not in lpszCharSet, beginning with the first character in the string and ending with the first character found in the string that is also in lpszCharSet (that is, starting with the first character in the string and up to but excluding the first character in the string that is found lpszCharSet). It returns the entire string if no character in lpszCharSet is found in the string.

Parameters

lpszCharSet

A string interpreted as a set of characters.

Remarks

Use this function to search the string for the first occurrence of any character in the specified set lpszCharSet. SpanExcluding extracts and returns all characters preceding the first occurrence of a character from lpszCharSet (in other words, the character from lpszCharSet and all characters following it in the string, are not returned). If no character from lpszCharSet is found in the string, then SpanExcluding returns the entire string.

Example

The following function returns the first portion of the src param.

// Portions are delimited by a semi-colon( ; ),
//  a comma( , ), a period( . ), a dash( - ),
// or a colon( : ).

CString GetFirstPart( CString src)
{
    return src.SpanExcluding( ";,.- :");
}

CString Overview | Class Members | Hierarchy Chart

See Also CString::SpanIncluding


CString::SpanIncluding

CString SpanIncluding( LPCTSTR lpszCharSet ) const;
throw( CMemoryException );

Return Value

A substring that contains characters in the string that are in lpszCharSet, beginning with the first character in the string and ending when a character is found in the string that is not in lpszCharSet. SpanIncluding returns an empty substring if the first character in the string is not in the specified set.

Parameters

lpszCharSet

A string interpreted as a set of characters.

Remarks

Call this member function to extract characters from the string, starting with the first character, that are in the set of characters identified by lpszCharSet. If the first character of the string is not in the character set, then SpanIncluding returns an empty string. Otherwise, it returns a sequence of consecutive characters which are in the set.

Example

The following example demonstrates the use of CString::SpanIncluding.

// example for CString::SpanIncluding
CString str( "cabbage" );
CString res = str.SpanIncluding( "abc" );
ASSERT( res == "cabba" );
res = str.SpanIncluding( "xyz" );
ASSERT( res.IsEmpty( ) );

CString Overview | Class Members | Hierarchy Chart

See Also CString::SpanExcluding


CString::TrimLeft

void TrimLeft( );

void CString::TrimLeft( TCHAR chTarget );

void CString::TrimLeft( LPCTSTR lpszTargets );

Parameters

chTarget

The target characters to be trimmed.

lpszTargets

A pointer to a string containing the target characters to be trimmed.

Remarks

Call the version of this member function with no parameters to trim leading whitespace characters from the string. When used with no parameters, TrimLeft removes newline, space, and tab characters.

Use the versions of this function that accept parameters to remove a particular character or a particular group of characters from the beginning of a string.

For a code example, see TrimRight. For more information, see Strings Topics in Visual C++ Programmer’s Guide

CString Overview | Class Members | Hierarchy Chart

See Also CString::Mid, CString::Left, CString::Right, CString::MakeUpper, CString::MakeLower, CString::MakeReverse, CString::Format


CString::TrimRight

void TrimRight( );

void CString::TrimRight( TCHAR chTarget );

void CString::TrimRight( LPCTSTR lpszTargets );

Parameters

chTarget

The target characters to be trimmed.

lpszTargets

A pointer to a string containing the target characters to be trimmed.

Remarks

Call the version of this member function with no parameters to trim trailing whitespace characters from the string. When used with no parameters, TrimRight removes trailing newline, space, and tab characters from the string.

Use the versions of this function that accept parameters to remove a particular character or a particular group of characters from the end of a string.

Example

CString strBefore;
CString strAfter;

   strBefore = "Hockey is Best!!!!";
   strAfter = strBefore;
   str.TrimRight('!');
   printf("Before: \"%s\"\n", (LPCTSTR) strBefore);
   printf("After : \"%s\"\n\n", (LPCTSTR) strAfter);

   strBefore = "Hockey is Best?!?!?!?!";
   strAfter = strBefore;
   str.TrimRight("?!");
   printf("Before: \"%s\"\n", (LPCTSTR) strBefore);
   printf("After : \"%s\"\n\n", (LPCTSTR) strAfter);

In the first example above, the string reading, "Hockey is Best!!!!" becomes "Hockey is Best".

In the second example above, the string reading, , "Hockey is Best?!?!?!?!" becomes "Hockey is Best".

For more information, see Strings Topics in Visual C++ Programmer’s Guide

CString Overview | Class Members | Hierarchy Chart

See Also CString::TrimLeft, CString::Mid, CString::Left, CString::Right, CString::MakeUpper, CString::MakeLower, CString::MakeReverse, CString::Format


CString::UnlockBuffer

void UnlockBuffer( );

Remarks

Call this member function to unlock the buffer that was previously secured by calling LockBuffer. UnlockBuffer resets the reference count to 1.

The CString destructor implies UnlockBuffer to ensure that you do not leave the buffer locked when the destructor is called.

CString Overview | Class Members | Hierarchy Chart

See Also CString::LockBuffer, CString::GetBuffer, CString::ReleaseBuffer


CString::operator =

const CString& operator =( const CString& stringSrc );
throw( CMemoryException );

const CString& operator =( TCHAR ch );
throw( CMemoryException );

const CString& operator =( const unsigned char* psz );
throw( CMemoryException );

const CString& operator =( LPCWSTR lpsz );
throw( CMemoryException );

const CString& operator =( LPCSTR lpsz );
throw( CMemoryException );

Remarks

The CString assignment (=) operator reinitializes an existing CString object with new data. If the destination string (that is, the left side) is already large enough to store the new data, no new memory allocation is performed. You should be aware that memory exceptions may occur whenever you use the assignment operator because new storage is often allocated to hold the resulting CString object.

Example

The following example demonstrates the use of CString::operator =.

// example for CString::operator =
CString s1, s2;        // Empty CString objects

s1 = "cat";            // s1 = "cat"
s2 = s1;               // s1 and s2 each = "cat"
s1 = "the " + s1;      // Or expressions
s1 = 'x';              // Or just individual characters

CString Overview | Class Members | Hierarchy Chart

See Also CString::CString


CString::operator LPCTSTR

operator LPCTSTR ( ) const;

Return Value

A character pointer to the string’s data.

Remarks

This useful casting operator provides an efficient method to access the null-terminated C string contained in a CString object. No characters are copied; only a pointer is returned. Be careful with this operator. If you change a CString object after you have obtained the character pointer, you may cause a reallocation of memory that invalidates the pointer.


CString::operator <<, >>

friend CArchive& operator <<( CArchive& ar, const CString& string );
throw( CArchiveException );

friend CArchive& operator >>( CArchive& ar, CString& string );
throw( CArchiveException );

friend CDumpContext& operator <<( CDumpContext& dc, const CString& string );

Remarks

The CString insertion (<<) operator supports diagnostic dumping and storing to an archive. The extraction (>>) operator supports loading from an archive.

The CDumpContext operators are valid only in the Debug version of the Microsoft Foundation Class Library.

Example

The following example demonstrates the use of CString::operator <<, >>.

// example for CString::operator <<, >>
    extern CArchive ar;
    CString s( "abc" );
#ifdef _DEBUG
    afxDump << s;  // Prints the value (abc)
    afxDump << &s;  // Prints the address
#endif

    if( ar.IsLoading() )
        ar >> s;
    else
        ar << s;

CString Overview | Class Members | Hierarchy Chart

See Also CDumpContext


CString::operator +

friend CString operator +( const CString& string1, const CString& string2 );
throw( CMemoryException );

friend CString operator +( const CString& string, TCHAR ch );
throw( CMemoryException );

friend CString operator +( TCHAR ch, const CString& string );
throw( CMemoryException );

friend CString operator +( const CString& string, LPCTSTR lpsz );
throw( CMemoryException );

friend CString operator +( LPCTSTR lpsz, const CString& string );
throw( CMemoryException );

Return Value

A CString object that is the temporary result of the concatenation. This return value makes it possible to combine several concatenations in the same expression.

Parameters

string, string1, string2

CString objects to concatenate.

ch

A character to concatenate to a string or to concatenate a string to.

lpsz

A pointer to a null-terminated character string.

Remarks

The + concatenation operator joins two strings and returns a CString object. One of the two argument strings must be a CString object. The other can be a character pointer or a character. You should be aware that memory exceptions may occur whenever you use the concatenation operator since new storage may be allocated to hold temporary data.

Example

The following example demonstrates the use of CString::operator +.

// example for CString::operator +
CString s1( "abc" );
CString s2( "def" );
ASSERT( (s1 + s2 ) == "abcdef" );
CString s3;
s3 = CString( "abc" ) + "def" ; // Correct
s3 = "abc" + "def";
// Wrong! The first argument must be a CString.

CString Overview | Class Members | Hierarchy Chart

See Also CString::operator +=


CString::operator +=

const CString& operator +=( const CString& string );
throw( CMemoryException );

const CString& operator +=( TCHAR ch );
throw( CMemoryException );

const CString& operator +=( LPCTSTR lpsz );
throw( CMemoryException );

Parameters

string

A CString to concatenate to this string.

ch

A character to concatenate to this string.

lpsz

A pointer to a null-terminated string to concatenate to this string.

Remarks

The += concatenation operator joins characters to the end of this string. The operator accepts another CString object, a character pointer, or a single character. You should be aware that memory exceptions may occur whenever you use this concatenation operator because new storage may be allocated for characters added to this CString object.

Example

The following example demonstrates the use of CString::operator +=.

// example for CString::operator +=
CString s( "abc" );
ASSERT( ( s += "def" ) == "abcdef" );

CString Overview | Class Members | Hierarchy Chart

See Also CString::operator +


CString Comparison Operators

BOOL operator ==( const CString& s1, const CString& s2 );

BOOL operator ==( const CString& s1, LPCTSTR s2 );

BOOL operator ==( LPCTSTR s1, const CString& s2 );

BOOL operator !=( const CString& s1, const CString& s2 );

BOOL operator !=( const CString& s1, LPCTSTR s2 );

BOOL operator !=( LPCTSTR s1, const CString& s2 );

BOOL operator <( const CString& s1, const CString& s2 );

BOOL operator <( const CString& s1, LPCTSTR s2 );

BOOL operator <( LPCTSTR s1, const CString& s2 );

BOOL operator >( const CString& s1, const CString& s2 );

BOOL operator >( const CString& s1, LPCTSTR s2 );

BOOL operator >( LPCTSTR s1, const CString& s2 );

BOOL operator <=( const CString& s1, const CString& s2 );

BOOL operator <=( const CString& s1, LPCTSTR s2 );

BOOL operator <=( LPCTSTR s1, const CString& s2 );

BOOL operator >=( const CString& s1, const CString& s2 );

BOOL operator >=( const CString& s1, LPCTSTR s2 );

BOOL operator >=( LPCTSTR s1, const CString& s2 );

Return Value

Nonzero if the strings meet the comparison condition; otherwise 0.

Parameters

s1, s2

CString objects to compare.

Remarks

These comparison operators compare two strings. The operators are a convenient substitute for the case-sensitive Compare member function.

Example

The following example demonstrates the use of CString Comparison Operators.

// example for CString Comparison Operators
CString s1( "abc" );
CString s2( "abd" );
ASSERT( s1 < s2 ); // Operator is overloaded for both.
ASSERT( "ABC" < s1 ); // CString and char*
ASSERT( s2 > "abe" );


CString::operator [ ]

TCHAR operator []( int nIndex ) const;

Parameters

nIndex

Zero-based index of a character in the string.

Remarks

You can think of a CString object as an array of characters. The overloaded subscript ([]) operator returns a single character specified by the zero-based index in nIndex. This operator is a convenient substitute for the GetAt member function.

Important You can use the subscript ([]) operator to get the value of a character in a CString, but you cannot use it to change the value of a character in a CString.

Example

The following example demonstrates the use of CString::operator [ ].

// example for CString::operator [ ]
CString s( "abc" );
ASSERT( s[1] == 'b' );

CString Overview | Class Members | Hierarchy Chart

See Also CString::GetAt, CString::SetAt


CStringArray

The CStringArray class supports arrays of CString objects.

The member functions of CStringArray are similar to the member functions of class CObArray. Because of this similarity, you can use the CObArray reference documentation for member function specifics. Wherever you see a CObject pointer as a return value, substitute a CString (not a CString pointer). Wherever you see a CObject pointer as a function parameter, substitute a LPCTSTR.

CObject* CObArray::GetAt( int <nIndex> ) const;

for example, translates to

CString CStringArray::GetAt( int <nIndex> ) const;

and

void SetAt( int <nIndex>, CObject* <newElement> )

translates to

void SetAt( int <nIndex>, LPCTSTR <newElement> )

CStringArray incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. If an array of CString objects is stored to an archive, either with an overloaded insertion operator or with the Serialize member function, each element is serialized in turn.

Note Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

If you need a dump of individual string elements in the array, you must set the depth of the dump context to 1 or greater.

When a CString array is deleted, or when its elements are removed, string memory is freed as appropriate.

For more information on using CStringArray, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>


CStringArray Class Members

Construction

CStringArray Constructs an empty array for CString objects.

Bounds

GetSize | Gets number of elements in this array.
GetUpperBound | Returns the largest valid index.
SetSize | Sets the number of elements to be contained in this array.

Operations

FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.

Element Access

GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; array not allowed to grow.
ElementAt | Returns a temporary reference to the element pointer within the array.
GetData | Allows access to elements in the array. Can be NULL.

Growing the Array

SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds an element to the end of the array; grows the array if necessary.
Append | Appends another array to the array; grows the array if necessary.
Copy | Copies anolther array to the array; grows the array if necessary.

Insertion/Removal

InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.

Operators

operator [] Sets or gets the element at the specified index.


CStringList

The CStringList class supports lists of CString objects. All comparisons are done by value, meaning that the characters in the string are compared instead of the addresses of the strings.

The member functions of CStringList are similar to the member functions of class CObList. Because of this similarity, you can use the CObList reference documentation for member function specifics. Wherever you see a CObject pointer as a return value, substitute a CString (not a CString pointer). Wherever you see a CObject pointer as a function parameter, substitute an LPCTSTR.

CObject*& CObList::GetHead() const;

for example, translates to

CString& CStringList::GetHead() const;

and

POSITION AddHead( CObject* <newElement> );

translates to

POSITION AddHead( LPCTSTR <newElement> );

CStringList incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. If a list of CString objects is stored to an archive, either with an overloaded insertion operator or with the Serialize member function, each CString element is serialized in turn.

If you need a dump of individual CString elements, you must set the depth of the dump context to 1 or greater.

When a CStringList object is deleted, or when its elements are removed, the CString objects are deleted as appropriate.

For more information on using CStringList, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample COLLECT


CStringList Class Members

Construction

CStringList Constructs an empty list for CString objects.

Head/Tail Access

GetHead | Returns the head element of the list (cannot be empty).
GetTail | Returns the tail element of the list (cannot be empty).

Operations

RemoveHead | Removes the element from the head of the list.
RemoveTail | Removes the element from the tail of the list.
AddHead | Adds an element (or all the elements in another list) to the head of the list (makes a new head).
AddTail | Adds an element (or all the elements in another list) to the tail of the list (makes a new tail).
RemoveAll | Removes all the elements from this list.

Iteration

GetHeadPosition | Returns the position of the head element of the list.
GetTailPosition | Returns the position of the tail element of the list.
GetNext | Gets the next element for iterating.
GetPrev | Gets the previous element for iterating.

Retrieval/Modification

GetAt | Gets the element at a given position.
SetAt | Sets the element at a given position.
RemoveAt | Removes an element from this list as specified by position.

Insertion

InsertBefore | Inserts a new element before a given position.
InsertAfter | Inserts a new element after a given position.

Searching

Find | Gets the position of an element specified by string value.
FindIndex | Gets the position of an element specified by a zero-based index.

Status

GetCount | Returns the number of elements in this list.
IsEmpty | Tests for the empty list condition (no elements).


CSyncObject

The CSyncObject class is a pure virtual class that provides functionality common to the synchronization objects in Win32. The Microsoft Foundation Class Library provides several classes derived from CSyncObject. These are CEvent, CMutex, CCriticalSection, and CSemaphore.

For information on how to use the synchronization objects, see the article Multithreading: How to Use the Synchronization Classes in Visual C++ Programmer’s Guide.

#include <afxmt.h>


CSyncObject Class Members

Construction

CSyncObject Constructs a CSyncObject object.

Methods

Lock | Gains access to the synchronization object.
Unlock | Releases access to the synchronization object.

Attributes

operator HANDLE Gains access to the synchronization object.


CSyncObject::CSyncObject

CSyncObject( LPCTSTR pstrName );

virtual ~CSyncObject( );

Parameters

pstrName

The name of the object. If NULL, pstrName will be null.

Remarks

Constructs a synchronization object with the supplied name.


CSyncObject::Lock

virtual BOOL Lock( DWORD dwTimeout = INFINITE );

Return Value

Nonzero if the function was successful; otherwise 0.

Parameters

dwTimeout

Specifies the amount of time to wait for the synchronization object to be available (signaled). If INFINITE, Lock will wait until the object is signaled before returning.

Remarks

Call this function to gain access to the resource controlled by the synchronization object. If the synchronization object is signaled, Lock will return successfully and the thread now owns the object. If the synchronization object is nonsignaled (unavailable), Lock will wait for the synchronization object to become signaled up to the number of milliseconds specified in the dwTimeOut parameter. If the synchronization object did not become signaled in the specified amount of time, Lock returns failure.


CSyncObject::operator HANDLE

operator HANDLE( ) const;

Return Value

If successful, the handle of the synchronization object; otherwise, NULL.

Remarks

Use this operator to get the handle of the CSyncObject object. You can use the handle to call Windows APIs directly.


CSyncObject::Unlock

virtual BOOL Unlock( ) = 0;

virtual BOOL Unlock( LONG lCount, LPLONG lpPrevCount = NULL );

Return Value

Default implementation always returns TRUE.

Parameters

lCount

Not used by default implementation.

lpPrevCount

Not used by default implementation.

Remarks

The declaration of Unlock with no parameters is a pure virtual function, and must be overridden by all classes deriving from CSyncObject. The default implementation of the declaration with two parameters always returns TRUE. This function is called to release access to the synchronization object owned by the calling thread. The second declaration is provided for synchronization objects such as semaphores that allow more than one access of a controlled resource.


CTabCtrl

A “tab control” is analogous to the dividers in a notebook or the labels in a file cabinet. By using a tab control, an application can define multiple pages for the same area of a window or dialog box. Each page consists of a set of information or a group of controls that the application displays when the user selects the corresponding tab. A special type of tab control displays tabs that look like buttons. Clicking a button should immediately perform a command instead of displaying a page.

The CTabCtrl class provides the functionality of the Windows common tab control. This control (and therefore the CTabCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

For more information on using CTabCtrl, see Control Topics and Using CTabCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample FIRE

See Also CHeaderCtrl, CListCtrl


CTabCtrl Class Members

Construction
Attributes
Operations
Overridables

Construction

CTabCtrl | Constructs a CTabCtrl object.
Create | Creates a tab control and attaches it to an instance of a CTabCtrl object.

Attributes

GetImageList | Retrieves the image list associated with a tab control.
SetImageList | Assigns an image list to a tab control.
GetItemCount | Retrieves the number of tabs in the tab control.
GetItem | Retrieves information about a tab in a tab control.
SetItem | Sets some or all of a tab’s attributes.
SetItemExtra | Sets the number of bytes per tab reserved for application-defined data in a tab control.
GetItemRect | Retrieves the bounding rectangle for a tab in a tab control.
GetCurSel | Determines the currently selected tab in a tab control.
SetCurSel | Selects a tab in a tab control.
SetCurFocus | Sets the focus to a specified tab in a tab control.
SetItemSize | Sets the width and height of an item.
SetPadding | Sets the amount of space (padding) around each tab’s icon and label in a tab control.
GetRowCount | Retrieves the current number of rows of tabs in a tab control.
GetToolTips | Retrieves the handle of the tool tip control associated with a tab control.
SetToolTips | Assigns a tool tip control to a tab control.
GetCurFocus | Retrieves the tab with the current focus of a tab control.
SetMinTabWidth | Sets the minimum width of items in a tab control.
GetExtendedStyle | Retrieves the extended styles that are currently in use for the tab control.
SetExtendedStyle | Sets the extended styles for a tab control.
GetItemState | Retrieves the state of the indicated tab control item.
SetItemState | Sets the state of the indicated tab control item.

Operations

InsertItem | Inserts a new tab in a tab control.
DeleteItem | Removes an item from a tab control.
DeleteAllItems | Removes all items from a tab control.
AdjustRect | Calculates a tab control’s display area given a window rectangle, or calculates the window rectangle that would correspond to a given display area.
RemoveImage | Removes an image from a tab control’s image list.
HitTest | Determines which tab, if any, is at a specified screen position.
DeselectAll | Resets items in a tab control, clearing any that were pressed.
HighlightItem | Sets the highlight state of a tab item.

Overridables

DrawItem Draws a specified item of a tab control.


CTabCtrl::AdjustRect

void AdjustRect( BOOL bLarger, LPRECT lpRect );

Parameters

bLarger

Indicates which operation to perform. If this parameter is TRUE, lpRect specifies a display rectangle and receives the corresponding window rectangle. If this parameter is FALSE, lpRect specifies a window rectangle and receives the corresponding display rectangle.

lpRect

Pointer to a RECT structure that specifies the given rectangle and receives the calculated rectangle.

Remarks

Call this function to calculate a tab control’s display area given a window rectangle, or calculate the window rectangle that would correspond to a given display area.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetItemSize, CTabCtrl::GetItemRect, CTabCtrl::AdjustRect


CTabCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

TRUE if initialization of the object was successful; otherwise FALSE.

Parameters

dwStyle

Specifies the tab control’s style. Apply any combination of tab control styles to the control.

rect

Specifies the tab control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the tab control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the tab control’s ID.

Remarks

You construct a CTabCtrl object in two steps. First call the constructor, then call Create, which creates the tab control and attaches it to the CTabCtrl object.

The following styles can be applied to a tab control:

  • TCS_BUTTONS Modifies the appearance of the tabs to look like buttons.

  • TCS_FIXEDWIDTH Makes all tabs the same width. (By default, the tab control automatically sizes each tab to fit its icon.) You cannot use this style with the TCS_RIGHTJUSTIFY style.

  • TCS_FOCUSNEVER Specifies that a tab never receives the input focus.

  • TCS_FOCUSONBUTTONDOWN Specifies that a tab receives the input focus when clicked. This style is typically used only with the TCS_BUTTONS style.

  • TCS_FORCEICONLEFT Forces the icon to the left, but leaves the tab label centered. (By default, the control centers the icon and label with the icon to the left of the label.)

  • TCS_FORCELABELLEFT Left-aligns both the icon and label.

  • TCS_MULTILINE Causes a tab control to display multiple rows of tabs. Thus all tabs can be displayed at once. (By default, a tab control displays a single row of tabs.)

  • TCS_OWNERDRAWFIXED Specifies that the parent window draws the tabs in the control.

  • TCS_RIGHTJUSTIFY Right justifies tabs. (By default, tabs are left-justified within each row.)

  • TCS_SHAREIMAGELISTS Specifies that a tab control’s image lists are not destroyed when the control is destroyed.

  • TCS_TOOLTIPS Specifies that the tab control has a tool tip control associated with it.

  • TCS_TABS Tabs appear as tabs, and a border is drawn around the display area. This style is the default.

  • TCS_SINGLELINE Displays only one row of tabs. The user can scroll to see more tabs, if necessary. This style is the default.

  • TCS_RAGGEDRIGHT Does not stretch each row of tabs to fill the entire width of the control. This style is the default.

In addition, you can apply the following window styles to a tab control:

  • WS_CHILD Creates a child window that represents the tab control. Cannot be used with the WS_POPUP style.

  • WS_VISIBLE Creates a tab control that is initially visible.

  • WS_DISABLED Creates a window that is initially disabled.

  • WS_GROUP Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style after the first control belong to the same group. The next control with the WS_GROUP style ends the style group and starts the next group (that is, one group ends where the next begins).

  • WS_TABSTOP Specifies one of any number of controls through which the user can move by using the TAB key. The TAB key moves the user to the next control specified by the WS_TABSTOP style.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::CTabCtrl


CTabCtrl::CTabCtrl

CTabCtrl( );

Remarks

Call this function to construct a CTabCtrl object.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::Create


CTabCtrl::DeleteAllItems

BOOL DeleteAllItems( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this function to remove all items from a tab control.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::DeleteItem


CTabCtrl::DeleteItem

BOOL DeleteItem( int nItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nItem

Zero-based value of the item to delete.

Remarks

Call this function to remove the specified item from a tab control.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::DeleteAllItems


CTabCtrl::DeselectAll

void DeselectAll( BOOL fExcludeFocus );

Parameters

fExcludeFocus

Flag that specifies the scope of the item deselection. If this parameter is set to FALSE, all tab buttons will be reset. If it is set to TRUE, then all tab items except for the one currently selected will be reset.

Remarks

This member function implements the behavior of the Win32 message, TCM_DESELECTALL, as described in the Intenet Client SDK.


CTabCtrl::DrawItem

void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

lpDrawItemStruct

A pointer to a DRAWITEMSTRUCT structure describing the item to be painted.

Remarks

Called by the framework when a visual aspect of an owner-draw tab control changes. The itemAction member of the DRAWITEMSTRUCT structure defines the drawing action that is to be performed.

By default, this member function does nothing. Override this member function to implement drawing for an owner-draw CTabCtrl object.

The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before this member function terminates.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CWnd::OnDrawItem


CTabCtrl::GetCurFocus

int GetCurFocus( ) const;

Return Value

The zero-based index of the tab with the current focus.

Remarks

Call this function to retrieve the index of the tab with the current focus.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetCurSel


CTabCtrl::GetCurSel

int GetCurSel( ) const;

Return Value

Zero-based index of the selected tab if successful or – 1 if no tab is selected.

Remarks

Call this function to retrieve the currently selected tab in a tab control.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetCurSel, CTabCtrl::GetCurFocus


CTabCtrl::GetExtendedStyle

DWORD GetExtendedStyle( );

Return Value

Represents the extended styles currently in use for the tab control. This value is a combination of tab control extended styles, as described in the Intenet Client SDK.

Remarks

This member function implements the behavior of the Win32 message TCM_GETEXTENDEDSTYLE, as described in the Intenet Client SDK.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetExtendedStyle


CTabCtrl::GetImageList

HIMAGELIST GetImageList( ) const;

Return Value

The handle of the image list of the tab control if successful; otherwise NULL.

Remarks

Call this function to retrieve the image list associated with a tab control.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetImageList, CImageList


CTabCtrl::GetItem

BOOL GetItem( int nItem, TCITEM* pTabCtrlItem ) const;

Return Value

Returns TRUE if successful; FALSE otherwise.

Parameters

nItem

Zero-based index of the tab.

pTabCtrlItem

Pointer to a TCITEM structure, used to specify the information to retrieve. Also used to receive information about the tab. This structure is used with the InsertItem, GetItem, and SetItem member functions.

Remarks

Call this function to retrieve information about a tab in a tab control.

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.

mask

Value specifying which TCITEM structure members to retrieve or set. This member can be zero or a combination of the following values:

  • TCIF_TEXT The pszText member is valid.

  • 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 The dwState member is valid.

pszText

Pointer to a null-terminated string containing the tab text if the structure contains information about a tab. If the structure is receiving information, this member specifies the address of the buffer that receives the tab text.

cchTextMax

Size of the buffer pointed to by pszText. This member is ignored if the structure is not receiving information.

iImage

Index into the tab control’s image list, or – 1 if there is no image for the tab.

lParam

Application-defined data associated with the tab. If there are more than four bytes of application-defined data 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. The TCITEMHEADER structure is identical to the TCITEM structure, but without the lParam member. The difference between the size of your structure and the size of the TCITEMHEADER structure should equal the number of extra bytes per tab.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::InsertItem, CTabCtrl::SetItem


CTabCtrl::GetItemCount

int GetItemCount( ) const;

Return Value

Number of items in the tab control.

Remarks

Call this function to retrieve the number of tabs in the tab control.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetItem, CTabCtrl::SetItem


CTabCtrl::GetItemRect

BOOL GetItemRect( int nItem, LPRECT lpRect ) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

nItem

Zero-based index of the tab item.

lpRect

Pointer to a RECT structure that receives the bounding rectangle of the tab. These coordinates use the viewport’s current mapping mode.

Remarks

Retrieves the bounding rectangle for the specified tab in a tab control.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetItemSize, CTabCtrl::AdjustRect


CTabCtrl::GetItemState

BOOL GetItemState( int nItem, DWORD dwMask, DWORD& dwState ) const;

Return Value

Nonzero if successful; otherwise 0. If successful, dwState receives the state information.

Parameters

nItem

The zero-based index number of the item for which to retrieve state information.

dwMask

Mask specifying which of the item's state flags to return. For a list of values, see the mask member of the TCITEM structure, as described in the Platform SDK.

dwState

A reference to a DWORD value receiving the state information. Can be one of the following values:

Value | Description
TCIS_BUTTONPRESSED | The tab control item is selected.
TCIS_HIGHLIGHTED | The tab control item is highlighted, and the tab and text are drawn using the current highlight color. When using highlight color, this will be a true interpolation, not a dithered color.

Remarks

Call this member function to retrieve the state of the tab control item identified by nItem. An item's state is specified by the dwState member of the TCITEM structure.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetItemState


CTabCtrl::GetRowCount

int GetRowCount( ) const;

Return Value

The number of rows of tabs in the tab control.

Remarks

Retrieves the current number of rows in a tab control. Only tab controls that have the TCS_MULTILINE style can have multiple rows of tabs.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::Create


CTabCtrl::GetToolTips

CToolTipCtrl* GetToolTips( ) const;

Return Value

Handle of the tool tip control if successful; otherwise NULL.

Remarks

Retrieves the handle of the tool tip control associated with a tab control. A tab control creates a tool tip control if it has the TCS_TOOLTIPS style. You can also assign a tool tip control to a tab control by using the SetToolTips member function.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetToolTips, CTabCtrl::Create


CTabCtrl::HighlightItem

BOOL HighlightItem( int idItem, BOOL fHighlight = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

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.

Remarks

This member function implements the Win32 message TCM_HIGHLIGHTITEM, as described in the Intenet Client SDK.


CTabCtrl::HitTest

int HitTest( TCHITTESTINFO* pHitTestInfo ) const;

Return Value

Returns the zero-based index of the tab or – 1 if no tab is at the specified position.

Parameters

pHitTestInfo

Pointer to a TCHITTESTINFO structure, as described in the Platform SDK, which specifies the screen position to test.

Remarks

Call this function to determine which tab, if any, is at the specified screen position.


CTabCtrl::InsertItem

BOOL InsertItem( int nItem, TCITEM* pTabCtrlItem );

BOOL InsertItem( int nItem, LPCTSTR lpszItem );

BOOL InsertItem( int nItem, LPCTSTR lpszItem, int nImage );

BOOL InsertItem( UINT nMask, int nItem, LPCTSTR lpszItem, int nImage, LPARAM lParam );

Return Value

Zero-based index of the new tab if successful; otherwise – 1.

Parameters

nItem

Zero-based index of the new tab.

pTabCtrlItem

Pointer to a TCITEM structure that specifies the attributes of the tab.

lpszItem

Pointer to the item to insert.

nImage

The zero-based index of an image to insert from an image list.

nMask

Specifies which TCITEM structure attributes to set. Can be zero or a combination of the following values:

  • TCIF_TEXT The pszText member is valid.

  • 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 The dwState member is valid.

lParam

Application-defined data associated with the tab.

Remarks

Call this function to insert a new tab in an existing tab control.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetItem, CTabCtrl::SetItem


CTabCtrl::RemoveImage

void RemoveImage( int nImage );

Parameters

nImage

Zero-based index of the image to remove.

Remarks

Call this function to remove the specified image from a tab control’s image list. The tab control updates each tab’s image index so that each tab remains associated with the same image.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetImageList, CTabCtrl::SetImageList


CTabCtrl::SetCurFocus

void SetCurFocus( int nItem );

Parameters

nItem

Specifies the index of the tab that gets the focus.

Remarks

This member function implements the behavior of the Win32 message TCM_SETCURFOCUS, as described in the Intenet Client SDK.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetCurSel


CTabCtrl::SetCurSel

int SetCurSel( int nItem );

Return Value

Zero-based index of the previously selected tab if successful, otherwise – 1.

Parameters

nItem

The zero-based index of the item to be selected.

Remarks

Selects a tab in a tab control. A tab control does not send a TCN_SELCHANGING or TCN_SELCHANGE notification message when a tab is selected using this function. These notifications are sent, using WM_NOTIFY, when the user clicks or uses the keyboard to change tabs.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetCurSel, CTabCtrl::GetCurFocus


CTabCtrl::SetExtendedStyle

DWORD SetExtendedStyle( DWORD dwNewStyle, DWORD dwExMask = 0 );

Return Value

A DWORD value that contains the previous tab control extended styles, as described in the Intenet Client SDK.

Parameters

dwNewStyle

Value specifying a combination of tab control extended styles.

dwExMask

A DWORD value that indicates which styles in dwNewStyle are to be affected. Only the extended styles in dwExMask will be changed. All other styles will be maintained as is. If this parameter is zero, then all of the styles in dwNewStyle will be affected.

Return Value

This member function implements the behavior of the Win32 message TCM_SETEXTENDEDSTYLE, as described in the Intenet Client SDK.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetExtendedStyle


CTabCtrl::SetImageList

CImageList * SetImageList( CImageList * pImageList );

Return Value

Returns a pointer to the previous image list or NULL if there is no previous image list.

Parameters

pImageList

Pointer to the image list to be assigned to the tab control.

Remarks

Call this function to assign an image list to a tab control.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetImageList, CImageList


CTabCtrl::SetItem

BOOL SetItem( int nItem, TCITEM* pTabCtrlItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nItem

Zero-based index of the item.

pTabCtrlItem

Pointer to a TCITEM structure that contains the new item attributes. The mask member specifies which attributes to set. If the mask member specifies the TCIF_TEXT value, the pszText member is the address of a null-terminated string and the cchTextMax member is ignored.

Remarks

Call this function to set some or all of a tab’s attributes.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::InsertItem, CTabCtrl::GetItem


CTabCtrl::SetItemExtra

BOOL SetItemExtra( int nBytes );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nBytes

The number of extra bytes to set.

Remarks

This member function implements the behavior of the Win32 message TCM_SETITEMEXTRA, as described in the Intenet Client SDK.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::SetItem


CTabCtrl::SetItemSize

CSize SetItemSize( CSize size );

Return Value

Returns the old width and height of the tab control items.

Parameters

size

The new width and height, in pixels, of the tab control items.

Remarks

Call this function to set the width and height of the tab control items.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::AdjustRect, CTabCtrl::GetItemRect, CTabCtrl::SetItemSize


CTabCtrl::SetItemState

BOOL SetItemState( int nItem, DWORD dwMask, DWORD dwState );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nItem

The zero-based index number of the item for which to set state information.

dwMask

Mask specifying which of the item's state flags to set. For a list of values, see the mask member of the TCITEM structure, as described in the Platform SDK.

dwState

A reference to a DWORD value containing the state information. Can be one of the following values:

Value | Description
TCIS_BUTTONPRESSED | The tab control item is selected.
TCIS_HIGHLIGHTED | The tab control item is highlighted, and the tab and text are drawn using the current highlight color. When using highlight color, this will be a true interpolation, not a dithered color.

Remarks

Call this member function to set the state of the tab control item identified by nItem.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetItemState


CTabCtrl::SetMinTabWidth

int SetMinTabWidth( int cx );

Return Value

The previous minimum tab width.

Parameters

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.

Return Value

This member function implements the behavior of the Win32 message TCM_SETMINTABWIDTH, as described in the Intenet Client SDK.


CTabCtrl::SetPadding

void SetPadding( CSize size );

Parameters

size

Sets the amount of space (padding) around each tab’s icon and label in a tab control.

Remarks

Call this function to set the amount of space (padding) around each tab’s icon and label in a tab control.


CTabCtrl::SetToolTips

void SetToolTips( CToolTipCtrl* pWndTip );

Parameters

pWndTip

Handle of the tool tip control.

Remarks

Call this function to assign a tool tip control to a tab control. You can get the tool tip control associated with a tab control by making a call to GetToolTips.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also CTabCtrl::GetToolTips


CTime

CTime does not have a base class.

A CTime object represents an absolute time and date. The CTime class incorporates the ANSI time_t data type and its associated run-time functions, including the ability to convert to and from a Gregorian date and 24-hour time.

CTime values are based on coordinated universal time (UTC), which is equivalent to Greenwich mean time (GMT). The local time zone is controlled by the TZ environment variable.

When creating a CTime, set the nDST parameter to 0 to indicate that standard time is in effect, or to a value greater than 0 to indicate that daylight savings time is in effect, or to a value less than zero to have the C run-time library code compute whether standard time or daylight savings time is in effect. tm_isdst is a required field. If not set, its value is undefined and the return value from mktime is unpredictable. If timeptr points to a tm structure returned by a previous call to asctime, gmtime, or localtime, the tm_isdst field contains the correct value.

See the Run-Time Library Reference for more information on the time_t data type and the run-time functions that are used by CTime.

A companion class, CTimeSpan, represents a time interval — the difference between two CTime objects.

The CTime and CTimeSpan classes are not designed for derivation. Because there are no virtual functions, the size of CTime and CTimeSpan objects is exactly 4 bytes. Most member functions are inline.

For more information on using CTime, see the article Date and Time in Visual C++ Programmer’s Guide and Time Management in the Run-Time Library Reference.

#include <afx.h>

Class Members | Hierarchy Chart

See Also Run-time functions: asctime, _ftime, gmtime, localtime, strftime, time


CTime Class Members

Construction

CTime | Constructs CTime objects in various ways.
GetCurrentTime | Creates a CTime object that represents the current time (static member function).

Extraction

GetTime | Returns a time_t that corresponds to this CTime object.
GetYear | Returns the year that this CTime object represents.
GetMonth | Returns the month that this CTime object represents (1 through 12).
GetDay | Returns the day that this CTime object represents (1 through 31).
GetHour | Returns the hour that this CTime object represents (0 through 23).
GetMinute | Returns the minute that this CTime object represents (0 through 59).
GetSecond | Returns the second that this CTime object represents (0 through 61).
GetDayOfWeek | Returns the day of the week (1 for Sunday, 2 for Monday, and so forth).

Conversion

GetGmtTm | Breaks down a CTime object into components — based on UTC.
GetLocalTm | Breaks down a CTime object into components — based on the local time zone.
GetAsSystemTime | Converts the time information stored in the CTime object to a Win32-compatible SYSTEMTIME structure
Format | Converts a CTime object into a formatted string — based on the local time zone.
FormatGmt | Converts a CTime object into a formatted string — based on UTC.

Operators

operator = | Assigns new time values.
operator + – | Add and subtract CTimeSpan and CTime objects.
operator +=, –= | Add and subtract a CTimeSpan object to and from this CTime object.
operator ==, < , etc. | Compare two absolute times.

Archive/Dump

operator << | Outputs a CTime object to CArchive or CDumpContext.
operator >> | Inputs a CTime object from CArchive.


CTime::CTime

CTime( );

CTime( const CTime& timeSrc );

CTime( time_t time );

CTime( int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec, int nDST = -1 );

CTime( WORD wDosDate, WORD wDosTime, int nDST = -1 );

CTime( const SYSTEMTIME& sysTime, int nDST = -1 );

CTime( const FILETIME& fileTime, int nDST = -1 );

Parameters

timeSrc

Indicates a CTime object that already exists.

time

Indicates a time value.

nYear, nMonth, nDay, nHour, nMin, nSec

Indicates the date and time values to be copied into the new CTime object.

nDST

Indicates whether daylight savings time is in effect. Can have one of three values, as follows:

  • nDST set to 0 Standard time is in effect.

  • nDST set to a value greater than 0 Daylight savings time is in effect.

  • nDST set to a value less than 0 The default. Automatically computes whether standard time or daylight savings time is in effect.

wDosDate, wDosTime

MS-DOS date and time values to be converted to a date/time value and copied into the new CTime object.

sysTime

A SYSTEMTIME structure to be converted to a date/time value and copied into the new CTime object.

fileTime

A FILETIME structure to be converted to a date/time value and copied into the new CTime object.

Remarks

All these constructors create a new CTime object initialized with the specified absolute time, based on the current time zone.

Each constructor is described below:

  • CTime( ); Constructs an unitialized CTime object. This constructor allows you to define CTime object arrays. You should initialize such arrays with valid times prior to use.

  • CTime( const CTime& ); Constructs a CTime object from another CTime value.

  • CTime( time_t ); Constructs a CTime object from a time_t type.

  • CTime( int, int, etc.); Constructs a CTime object from local time components with each component constrained to the following ranges:
    Component | Range
    nYear | 1970–2038*
    nMonth | 1–12
    nDay | 1–31
    nHour | no constraint
    nMin | no constraint
    nSec | no constraint

    *The upper date limit is 1/18/2038. For a wider range of dates, see COleDateTime.

    This constructor makes the appropriate conversion to UTC. The Debug version of the Microsoft Foundation Class Library asserts if one or more of the year, month, or day components is out of range. It is your responsibility to validate the arguments prior to calling.

  • CTime( WORD, WORD ); Constructs a CTime object from the specified MS-DOS date and time values.

  • CTime( const SYSTEMTIME& ); Constructs a CTime object from a SYSTEMTIME structure.

  • CTime( const FILETIME& ); Constructs a CTime object from a FILETIME structure. You most likely will not use CTime FILETIME initialization directly. If you use a CFile object to manipulate a file, CFile::GetStatus retrieves the file time stamp for you via a CTime object initialized with a FILETIME structure.

For more information on the time_t data type, see the time function in the Run-Time Library Reference.

For more information, see the SYSTEMTIME and FILETIME structure in the Win32 SDK Programmer’s Reference.

For more information, see the MS-DOS Date and Time entry in the Win32 SDK documentation.

Example

// example for CTime::CTime
time_t osBinaryTime;  // C run-time time (defined in <time.h>)
time( &osBinaryTime ) ;  // Get the current time from the
                         // operating system.
CTime time1; // Empty CTime. (0 is illegal time value.)
CTime time2 = time1; // Copy constructor.
CTime time3( osBinaryTime );  // CTime from C run-time time
CTime time4( 1999, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1999

CTime Overview | Class Members | Hierarchy Chart

See Also CTime::GetTime, GetCurrentTime, operator =


CTime::Format

CString Format( LPCTSTR pFormat ) const;

CString Format( UINT nFormatID ) const;

Return Value

A CString that contains the formatted time.

Parameters

pFormat

A formatting string similar to the printf formatting string. Formatting codes, preceded by a percent (%) sign, are replaced by the corresponding CTime component. Other characters in the formatting string are copied unchanged to the returned string. See the run-time function strftime for details. The value and meaning of the formatting codes for Format are listed below:

  • %D Total days in this CTime

  • %H Hours in the current day

  • %M Minutes in the current hour

  • %S Seconds in the current minute

  • %% Percent sign

nFormatID

The ID of the string that identifies this format.

Remarks

Call this member function to create a formatted representation of the date/time value. If the status of this CTime object is null, the return value is an empty string. If the status of CTime is invalid, the return value is an empty string.

Example

// example for CTime::Format and CTime::FormatGmt
CTime t( 1999, 3, 19, 22, 15, 0 );
// 10:15PM March 19, 1999
CString s = t.Format( "%A, %B %d, %Y" );
ASSERT( s == "Friday, March 19, 1999" );

CTime Overview | Class Members | Hierarchy Chart

See Also CTime::FormatGmt


CTime::FormatGmt

CString FormatGmt( LPCTSTR pFormat ) const;

CString FormatGmt( UINT nFormatID ) const;

Return Value

A CString that contains the formatted time.

Parameters

pFormat

Specifies a formatting string similar to the printf formatting string. See the run-time function strftime for details.

nFormatID

The ID of the string that identifies this format.

Remarks

Generates a formatted string that corresponds to this CTime object. The time value is not converted and thus reflects UTC.

CTime Overview | Class Members | Hierarchy Chart

See Also CTime::Format


CTime::GetAsSystemTime

BOOL GetAsSystemTime( SYSTEMTIME& timeDest ) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

timeDest

A reference to a SYSTEMTIME structure to be converted to a date/time value and copied into the new CTime object.

Remarks

Call this member function to convert the time information stored in the CTime object to a Win32–compatible SYSTEMTIME structure. GetAsSystemTime stores the resulting time in the referenced timeDest object. The SYSTEMTIME data structure initialized by this function will have its wMilliseconds member set to zero.


CTime::GetCurrentTime

static CTime PASCAL GetCurrentTime( );

Remarks

Returns a CTime object that represents the current time.

Example

// example for CTime::GetCurrentTime
CTime t = CTime::GetCurrentTime();


CTime::GetDay

int GetDay( ) const;

Remarks

Returns the day of the month, based on local time, in the range 1 through 31. This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten as a result of calls to other CTime member functions.

Example

// example for CTime::GetDay, CTime::GetMonth, and CTime::GetYear
CTime t( 1999, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1999
ASSERT( t.GetDay() == 19 );
ASSERT( t.GetMonth() == 3 );
ASSERT( t.GetYear() == 1999 );

CTime Overview | Class Members | Hierarchy Chart

See Also CTime::GetDayOfWeek


CTime::GetDayOfWeek

int GetDayOfWeek( ) const;

Remarks

Returns the day of the week based on local time; 1 = Sunday, 2 = Monday, ..., 7 = Saturday. This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten as a result of calls to other CTime member functions.


CTime::GetGmtTm

struct tm* GetGmtTm( struct tm* ptm = NULL ) const;

Return Value

A pointer to a filled-in struct tm as defined in the include file TIME.H. The members and the values they store are as follows:

  • tm_sec Seconds

  • tm_min Minutes

  • tm_hour Hours (0–23)

  • tm_mday Day of month (1–31)

  • tm_mon Month (0–11; January = 0)

  • tm_year Year (actual year minus 1900)

  • tm_wday Day of week (1–7; Sunday = 1)

  • tm_yday Day of year (0–365; January 1 = 0)

  • tm_isdst Always 0

Note The year in struct tm is in the range 70 to 138; the year in the CTime interface is in the range January 1, 1970 to January 18, 2038 (inclusive).

Parameters

ptm

Points to a buffer that will receive the time data. If this pointer is NULL, an internal, statically allocated buffer is used. The data in this default buffer is overwritten as a result of calls to other CTime member functions.

Remarks

Gets a struct tm that contains a decomposition of the time contained in this CTime object. GetGmtTm returns UTC.

This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten as a result of calls to other CTime member functions.

Example

See the example for GetLocalTm.


CTime::GetHour

int GetHour( ) const;

Remarks

Returns the hour, based on local time, in the range 0 through 23. This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten as a result of calls to other CTime member functions.

Example

// example for CTime::GetHour, CTime::GetMinute, and CTime::GetSecond,
CTime t( 1999, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1999
ASSERT( t.GetSecond() == 0 );
ASSERT( t.GetMinute() == 15 );
ASSERT( t.GetHour() == 22 );


CTime::GetLocalTm

struct tm* GetLocalTm( struct tm* ptm = NULL ) const;

Return Value

A pointer to a filled-in struct tm as defined in the include file TIME.H. See GetGmtTm for the structure layout.

Parameters

ptm

Points to a buffer that will receive the time data. If this pointer is NULL, an internal, statically allocated buffer is used. The data in this default buffer is overwritten as a result of calls to other CTime member functions.

Remarks

Gets a struct tm containing a decomposition of the time contained in this CTime object. GetLocalTm returns local time.

Example

// example for CTime::GetLocalTm
CTime t( 1999, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1999
struct tm* osTime;  // A pointer to a structure containing time
                    // elements.
osTime = t.GetLocalTm( NULL );
ASSERT( osTime->tm_mon == 2 ); // Note zero-based month!


CTime::GetMinute

int GetMinute( ) const;

Remarks

Returns the minute, based on local time, in the range 0 through 59. This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten as a result of calls to other CTime member functions.


CTime::GetMonth

int GetMonth( ) const;

Remarks

Returns the month, based on local time, in the range 1 through 12 (1 = January). This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten as a result of calls to other CTime member functions.

Example

See the example for GetDay.


CTime::GetSecond

int GetSecond( ) const;

Remarks

Returns the second, based on local time, in the range 0 through 59. This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten as a result of calls to other CTime member functions.


CTime::GetTime

time_t GetTime( ) const;

Remarks

Returns a time_t value for the given CTime object.

Example

// example for CTime::GetTime
CTime t( 1999, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1999
time_t osBinaryTime = t.GetTime(); // time_t defined in <time.h>
printf( "time_t = %ld\n", osBinaryTime );

CTime Overview | Class Members | Hierarchy Chart

See Also CTime::CTime


CTime::GetYear

int GetYear( ) const;

Remarks

Returns the year, based on local time, in the range January 1,1970 to January 18, 2038 (inclusive). This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten as a result of calls to other CTime member functions.

Example

See the example for GetDay.

CTime Overview | Class Members | Hierarchy Chart

See Also CTime::CTime


CTime::operator =

const CTime& operator =( const CTime& timeSrc );

const CTime& operator =( time_t t );

Remarks

These overloaded assignment operators copy the source time into this CTime object.

The internal time storage in a CTime object is independent of time zone. Time-zone conversion is not necessary during assignment.

Example

// example for CTime::operator =
time_t osBinaryTime;  // C run-time time (defined in <time.h>)
CTime t1 = osBinaryTime; // Assignment from time_t
CTime t2 = t1; // Assignment from CTime

CTime Overview | Class Members | Hierarchy Chart

See Also CTime::CTime


CTime::operator +, -

CTime operator +( CTimeSpan timeSpan ) const;

CTime operator -( CTimeSpan timeSpan ) const;

CTimeSpan operator -( CTime time ) const;

Remarks

CTime objects represent absolute time. CTimeSpan objects represent relative time. The first two operators allow you to add and subtract CTimeSpan objects to and from CTime objects. The third allows you to subtract one CTime object from another to yield a CTimeSpan object.

Example

// example for CTime::operator  +, -
CTime t1( 1999, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1999
CTime t2( 1999, 3, 20, 22, 15, 0 ); // 10:15PM March 20, 1999
CTimeSpan ts = t2 - t1;  // Subtract 2 CTimes
ASSERT( ts.GetTotalSeconds() == 86400L );
ASSERT( ( t1 + ts ) == t2 );  // Add a CTimeSpan to a CTime.
ASSERT( ( t2 - ts ) == t1 );  // Subtract a CTimeSpan from a Ctime.


CTime::operator +=, -=

const CTime& operator +=( CTimeSpan timeSpan );

const CTime& operator -=( CTimeSpan timeSpan );

Remarks

These operators allow you to add and subtract a CTimeSpan object to and from this CTime object.

Example

// example for CTime::operator -=
CTime t( 1999, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1999
t += CTimeSpan( 0, 1, 0, 0 ); // 1 hour exactly
ASSERT( t.GetHour() == 23 );


CTime Comparison Operators

BOOL operator ==( CTime time ) const;

BOOL operator !=( CTime time ) const;

BOOL operator <( CTime time ) const;

BOOL operator >( CTime time ) const;

BOOL operator <=( CTime time ) const;

BOOL operator >=( CTime time ) const;

Remarks

These operators compare two absolute times and return nonzero if the condition is true; otherwise 0.

Example

// example for CTime comparison operators
CTime t1 = CTime::GetCurrentTime();
CTime t2 = t1 + CTimeSpan( 0, 1, 0, 0 );    // 1 hour later
ASSERT( t1 != t2 );
ASSERT( t1 < t2 );
ASSERT( t1 <= t2 );


CTime::operators <<, >>

friend CDumpContext& AFXAPI operator<<( CDumpContext& dc, CTime time );

friend CArchive& AFXAPI operator<<( CArchive& ar, CTime time );

friend CArchive& AFXAPI operator>>( CArchive& ar, CTime& rtime );

Remarks

The CTime insertion (<<) operator supports diagnostic dumping and storing to an archive. The extraction (>>) operator supports loading from an archive.

When you send a CTime object to the dump context, the local time is displayed in readable date-time format.

Example

// example for CTime::operators <<, >>
CTime t( 1999, 3, 19, 22, 15, 0 ); // 10:15PM March 19, 1999
afxDump << t << "\n"; // Prints 'CTime("Fri Mar 19 22:15:00 1999")'.

extern CArchive ar;
if( ar.IsLoading() )
  ar >> t;
else
  ar << t;

CTime Overview | Class Members | Hierarchy Chart

See Also CArchive, CDumpContext


CTimeSpan

CTimeSpan does not have a base class.

A CTimeSpan object represents a relative time span. The CTimeSpan class incorporates the ANSI time_t data type and its associated run-time functions. These functions convert seconds to various combinations of days, hours, minutes, and seconds.

A CTimeSpan object keeps time in seconds. Because the CTimeSpan object is stored as a signed number in 4 bytes, the maximum allowed span is approximately ± 68 years.

A companion class, CTime, represents an absolute time. A CTimeSpan is the difference between two CTime values.

The CTime and CTimeSpan classes are not designed for derivation. Because there are no virtual functions, the size of both CTime and CTimeSpan objects is exactly 4 bytes. Most member functions are inline.

For more information on using CTimeSpan, see the article Date and Time in Visual C++ Programmer’s Guide and Time Management in the Run-Time Library Reference.

#include <afx.h>

Class Members | Hierarchy Chart

See Also Run-time functions: asctime, _ftime, gmtime, localtime, strftime, time


CTimeSpan Class Members

Construction

CTimeSpan Constructs CTimeSpan objects in various ways.

Extraction

GetDays | Returns the number of complete days in this CTimeSpan.
GetHours | Returns the number of hours in the current day (–23 through 23).
GetTotalHours | Returns the total number of complete hours in this CTimeSpan.
GetMinutes | Returns the number of minutes in the current hour (–59 through 59).
GetTotalMinutes | Returns the total number of complete minutes in this CTimeSpan.
GetSeconds | Returns the number of seconds in the current minute (–59 through 59).
GetTotalSeconds | Returns the total number of complete seconds in this CTimeSpan.

Conversion

Format Converts a CTimeSpan into a formatted string.

Operators

operator = | Assigns new time-span values.
operator + – | Adds and subtracts CTimeSpan objects.
operator += –= | Adds and subtracts a CTimeSpan object to and from this CTimeSpan.
operator == < etc. | Compares two relative time values.

Archive/Dump

operator << | Outputs a CTimeSpan object to CArchive or CDumpContext.
operator >> | Inputs a CTimeSpan object from CArchive.


CTimeSpan::CTimeSpan

CTimeSpan( );

CTimeSpan( const CTimeSpan& timeSpanSrc );

CTimeSpan( time_t time );

CTimeSpan( LONG lDays, int nHours, int nMins, int nSecs );

Parameters

timeSpanSrc

A CTimeSpan object that already exists.

time

A time_t time value.

lDays, nHours, nMins, nSecs

Days, hours, minutes, and seconds, respectively.

Remarks

All these constructors create a new CTimeSpan object initialized with the specified relative time. Each constructor is described below:

  • CTimeSpan( ); Constructs an uninitialized CTimeSpan object.

  • CTimeSpan( const CTimeSpan& ); Constructs a CTimeSpan object from another CTimeSpan value.

  • CTimeSpan( time_t ); Constructs a CTimeSpan object from a time_t type. This value should be the difference between two absolute time_t values.

  • CTimeSpan( LONG, int, int, int ); Constructs a CTimeSpan object from components with each component constrained to the following ranges:
    Component | Range
    lDays | 0–25,000 (approximately)
    nHours | 0–23
    nMins | 0–59
    nSecs | 0–59

Note that the Debug version of the Microsoft Foundation Class Library asserts if one or more of the time-day components is out of range. It is your responsibility to validate the arguments prior to calling.

Example

// example for CTimeSpan::CTimeSpan
CTimeSpan ts1;  // Uninitialized time value
CTimeSpan ts2a( ts1 ); // Copy constructor
CTimeSpan ts2b = ts1; // Copy constructor again
CTimeSpan ts3( 100 ); // 100 seconds
CTimeSpan ts4( 0, 1, 5, 12 );    // 1 hour, 5 minutes, and 12 seconds


CTimeSpan::Format

CString Format( LPCSTR pFormat ) const;

CString Format( LPCTSTR pFormat ) const;

CString Format( UINT nID ) const;

Return Value

A CString object that contains the formatted time.

Parameters

pFormat

A formatting string similar to the printf formatting string. Formatting codes, preceded by a percent (%) sign, are replaced by the corresponding CTimeSpan component. Other characters in the formatting string are copied unchanged to the returned string. The value and meaning of the formatting codes for Format are listed below:

  • %D Total days in this CTimeSpan

  • %H Hours in the current day

  • %M Minutes in the current hour

  • %S Seconds in the current minute

  • %% Percent sign

nID

The ID of the string that identifies this format.

Remarks

Generates a formatted string that corresponds to this CTimeSpan.

The Debug version of the library checks the formatting codes and asserts if the code is not in the list above.

Example

// example for CTimeSpan::Format
CTimeSpan ts( 3, 1, 5, 12 ); // 3 days, 1 hour, 5 min, and 12 sec
CString s = ts.Format( "Total days: %D, hours: %H, mins: %M, secs: %S" );
ASSERT( s == "Total days: 3, hours: 01, mins: 05, secs: 12" );


CTimeSpan::GetDays

LONG GetDays( ) const;

Remarks

Returns the number of complete days. This value may be negative if the time span is negative.

Example

// example for CTimeSpan::GetDays
CTimeSpan ts( 3, 1, 5, 12 ); // 3 days, 1 hour, 5 min, and 12 sec
ASSERT( ts.GetDays() == 3 );


CTimeSpan::GetHours

int GetHours( ) const;

Remarks

Returns the number of hours in the current day. The range is –23 through 23.

Example

// example for CTimeSpan::GetHours
CTimeSpan ts( 3, 1, 5, 12 ); // 3 days, 1 hour, 5 min, and 12 sec
ASSERT( ts.GetHours() == 1 );
ASSERT( ts.GetMinutes() == 5 );
ASSERT( ts.GetSeconds() == 12 );


CTimeSpan::GetMinutes

int GetMinutes( ) const;

Remarks

Returns the number of minutes in the current hour. The range is –59 through 59.

Example

See the example for GetHours.


CTimeSpan::GetSeconds

int GetSeconds( ) const;

Remarks

Returns the number of seconds in the current minute. The range is –59 through 59.

Example

See the example for GetHours.


CTimeSpan::GetTotalHours

LONG GetTotalHours( ) const;

Remarks

Returns the total number of complete hours in this CTimeSpan.

Example

// example for CTimeSpan::GetTotalHours
CTimeSpan ts( 3, 1, 5, 12 ); // 3 days, 1 hour, 5 min, and 12 sec
ASSERT( ts.GetTotalHours() == 73 );
ASSERT( ts.GetTotalMinutes() == 4385 );
ASSERT( ts.GetTotalSeconds() == 263112 );


CTimeSpan::GetTotalMinutes

LONG GetTotalMinutes( ) const;

Remarks

Returns the total number of complete minutes in this CTimeSpan.

Example

See the example for GetTotalHours.


CTimeSpan::GetTotalSeconds

LONG GetTotalSeconds( ) const;

Remarks

Returns the total number of complete seconds in this CTimeSpan.

Example

See the example for GetTotalHours.


CTimeSpan::operator =

const CTimeSpan& operator =( const CTimeSpan& timeSpanSrc );

Remarks

The overloaded assignment operator copies the source CTimeSpan timeSpanSrc object into this CTimeSpan object.

Example

// example for CTimeSpan::operator =
CTimeSpan ts1;
CTimeSpan ts2( 3, 1, 5, 12 ); // 3 days, 1 hour, 5 min, and 12 sec
ts1 = ts2;
ASSERT( ts1 == ts2 );

CTimespan Overview | Class Members | Hierarchy Chart

See Also CTimeSpan::CTimeSpan


CTimeSpan::operator +, -

CTimeSpan operator +( CTimeSpan timeSpan ) const;

CTimeSpan operator -( CTimeSpan timeSpan ) const;

Remarks

These two operators allow you to add and subtract CTimeSpan objects to and from each other.

Example

// example for CTimeSpan::operator +, -
CTimeSpan ts1( 3, 1, 5, 12 ); // 3 days, 1 hour, 5 min, and 12 sec
CTimeSpan ts2( 100 ); // 100 seconds
CTimeSpan ts3 = ts1 + ts2;
ASSERT( ts3.GetSeconds() == 52 ); // 6 mins, 52 secs


CTimeSpan::operator +=, -=

const CTimeSpan& operator +=( CTimeSpan timeSpan );

const CTimeSpan& operator -=( CTimeSpan timeSpan );

Remarks

These operators allow you to add and subtract a CTimeSpan object to and from this CTimeSpan.

Example

// example for CTimeSpan::operator +=, -=
CTimeSpan ts1( 10 ); // 10 seconds
CTimeSpan ts2( 100 ); // 100 seconds
ts2 -= ts1;
ASSERT( ts2.GetTotalSeconds() == 90 );


CTimeSpan Comparison Operators

BOOL operator ==( CTimeSpan timeSpan ) const;

BOOL operator !=( CTimeSpan timeSpan ) const;

BOOL operator <( CTimeSpan timeSpan ) const;

BOOL operator >( CTimeSpan timeSpan ) const;

BOOL operator <=( CTimeSpan timeSpan ) const;

BOOL operator >=( CTimeSpan timeSpan ) const;

Remarks

These operators compare two relative time values. They return nonzero if the condition is true; otherwise 0.

Example

// example for CTimeSpan comparison operators
CTimeSpan ts1( 100 );
CTimeSpan ts2( 110 );
ASSERT( ( ts1 != ts2 ) && ( ts1 < ts2 ) && ( ts1 <= ts2 ) );


CTimeSpan::operators <<, >>

friend CDumpContext& AFXAPI operator<<( CDumpContext& dc, CTimeSpan timeSpan );

friend CArchive& AFXAPI operator<<( CArchive& ar, CTimeSpan timeSpan );

friend CArchive& AFXAPI operator>>( CArchive& ar, CTimeSpan& rtimeSpan );

Remarks

The CTimeSpan insertion (<<) operator supports diagnostic dumping and storing to an archive. The extraction (>>) operator supports loading from an archive.

When you send a CTimeSpan object to the dump context, the value is displayed in an alphanumeric format that shows days, hours, minutes, and seconds.

Example

// example for CTimeSpan::operators <<, >>
CTimeSpan ts( 3, 1, 5, 12 ); // 3 days, 1 hour, 5 min, and 12 sec
#ifdef _DEBUG
afxDump << ts << "\n";
#endif
// Prints 'CTimeSpan(3 days, 1 hours, 5 minutes and 12 seconds)'

extern CArchive ar;
if( ar.IsLoading( ))
  ar >> ts;
else
  ar << ts;


CToolBar

Objects of the class CToolBar are control bars that have a row of bitmapped buttons and optional separators. The buttons can act like pushbuttons, check-box buttons, or radio buttons. CToolBar objects are usually embedded members of frame-window objects derived from the class CFrameWnd or CMDIFrameWnd.

CToolBar::GetToolBarCtrl, a member function new to MFC 4.0, allows you to take advantage of the Windows common control's support for toolbar customization and additional functionality. CToolBar member functions give you most of the functionality of the Windows common controls; however, when you call GetToolBarCtrl, you can give your toolbars even more of the characteristics of Windows 95 toolbars. When you call GetToolBarCtrl, it will return a reference to a CToolBarCtrl object. See CToolBarCtrl for more information about designing toolbars using Windows common controls. For more general information about common controls, see Common Controls in the Windows 95 SDK Programmer’s Reference.

Visual C++ provides you with two methods to create a toolbar. To create a toolbar resource using the Resource Editor, follow these steps:

  1. Create a toolbar resource.

  2. Construct the CToolBar object.

  3. Call the Create (or CreateEx) function to create the Windows toolbar and attach it to the CToolBar object.

  4. Call LoadToolBar to load the toolbar resource.

Otherwise, follow these steps:

  1. Construct the CToolBar object.

  2. Call the Create (or CreateEx) function to create the Windows toolbar and attach it to the CToolBar object.

  3. Call LoadBitmap to load the bitmap that contains the toolbar button images.

  4. Call SetButtons to set the button style and associate each button with an image in the bitmap.

All the button images in the toolbar are taken from one bitmap, which must contain one image for each button. All images must be the same size; the default is 16 pixels wide and 15 pixels high. Images must be side by side in the bitmap.

The SetButtons function takes a pointer to an array of control IDs and an integer that specifies the number of elements in the array. The function sets each button’s ID to the value of the corresponding element of the array and assigns each button an image index, which specifies the position of the button’s image in the bitmap. If an array element has the value ID_SEPARATOR, no image index is assigned.

The order of the images in the bitmap is typically the order in which they are drawn on the screen, but you can use the SetButtonInfo function to change the relationship between image order and drawing order.

All buttons in a toolbar are the same size. The default is 24 x 22 pixels, in accordance with Windows Interface Guidelines for Software Design. Any additional space between the image and button dimensions is used to form a border around the image.

Each button has one image. The various button states and styles (pressed, up, down, disabled, disabled down, and indeterminate) are generated from that one image. Although bitmaps can be any color, you can achieve the best results with images in black and shades of gray.

Toolbar buttons imitate pushbuttons by default. However, toolbar buttons can also imitate check-box buttons or radio buttons. Check-box buttons have three states: checked, cleared, and indeterminate. Radio buttons have only two states: checked and cleared.

To set an individual button or separator style without pointing to an array, call GetButtonStyle to retrieve the style, and then call SetButtonStyle instead of SetButtons. SetButtonStyle is most useful when you want to change a button’s style at run time.

To assign text to appear on a button, call GetButtonText to retrieve the text to appear on the button, and then call SetButtonText to set the text.

To create a check-box button, assign it the style TBBS_CHECKBOX or use a CCmdUI object’s SetCheck member function in an ON_UPDATE_COMMAND_UI handler. Calling SetCheck turns a pushbutton into a check-box button. Pass SetCheck an argument of 0 for unchecked, 1 for checked, or 2 for indeterminate.

To create a radio button, call a CCmdUI object’s SetRadio member function from an ON_UPDATE_COMMAND_UI handler. Pass SetRadio an argument of 0 for unchecked or nonzero for checked. In order to provide a radio group’s mutually exclusive behavior, you must have ON_UPDATE_COMMAND_UI handlers for all of the buttons in the group.

For more information on using CToolBar, see the article Toolbars in Visual C++ Programmer’s Guide and Technical Note 31, Control Bars.

#include <afxext.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CTRLBARS | MFC Sample DLGCBR32 | MFC Sample DOCKTOOL

See Also CToolBarCtrl, CControlBar, CToolBar::Create, CToolBar::LoadBitmap, CToolBar::SetButtons, CCmdUI::SetCheck, CCmdUI::SetRadio


CToolBar Class Members

Construction

CToolBar | Constructs a CToolBar object.
Create | Creates the Windows toolbar and attaches it to the CToolBar object.
CreateEx | Creates a CToolBar object with additional styles for the embedded CToolBarCtrl object.
SetSizes | Sets the sizes of buttons and their bitmaps.
SetHeight | Sets the height of the toolbar.
LoadToolBar | Loads a toolbar resource created with the resource editor.
LoadBitmap | Loads the bitmap containing bitmap-button images.
SetBitmap | Sets a bitmapped image.
SetButtons | Sets button styles and an index of button images within the bitmap.

Attributes

CommandToIndex | Returns the index of a button with the given command ID.
GetItemID | Returns the command ID of a button or separator at the given index.
GetItemRect | Retrieves the display rectangle for the item at the given index.
GetButtonStyle | Retrieves the style for a button.
SetButtonStyle | Sets the style for a button.
GetButtonInfo | Retrieves the ID, style, and image number of a button.
SetButtonInfo | Sets the ID, style, and image number of a button.
GetButtonText | Retrieves the text that will appear on a button.
SetButtonText | Sets the text that will appear on a button.
GetToolBarCtrl | Allows direct access to the underlying common control.


CToolBar::CommandToIndex

int CommandToIndex( UINT nIDFind );

Return Value

The index of the button, or –1 if no button has the given command ID.

Parameters

nIDFind

Command ID of a toolbar button.

Remarks

This member function returns the index of the first toolbar button, starting at position 0, whose command ID matches nIDFind.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::GetItemId


CToolBar::Create

BOOL Create( CWnd* pParentWnd, DWORD dwStyle = WS_CHILD | WS_VISIBLE | CBRS_TOP, UINT nID = AFX_IDW_TOOLBAR );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pParentWnd

Pointer to the window that is the toolbar’s parent.

dwStyle

The toolbar style. Additional toolbar styles supported are:

  • CBRS_TOP Control bar is at top of the frame window.

  • CBRS_BOTTOM Control bar is at bottom of the frame window.

  • CBRS_NOALIGN Control bar is not repositioned when the parent is resized.

  • CBRS_TOOLTIPS Control bar displays tool tips.

  • CBRS_SIZE_DYNAMIC Control bar is dynamic.

  • CBRS_SIZE_FIXED Control bar is fixed.

  • CBRS_FLOATING Control bar is floating.

  • CBRS_FLYBY Status bar displays information about the button.

  • CBRS_HIDE_INPLACE Control bar is not displayed to the user.

nID

The toolbar’s child-window ID.

Remarks

This member function creates a Windows toolbar (a child window) and associates it with the CToolBar object. It also sets the toolbar height to a default value.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::CToolBar, CToolBar::LoadBitmap, CToolBar::SetButtons, CToolBar::LoadToolBar, CControlBar::CalcDynamicLayout, CControlBar::CalcFixedLayout


CToolBar::CreateEx

BOOL CreateEx(CWnd* pParentWnd, DWORD dwCtrlStyle = TBSTYLE_FLAT, DWORD dwStyle = WS_CHILD | WS_VISIBLE | CBRS_ALIGN_TOP, CRect rcBorders = CRect(0, 0, 0, 0), UINT nID = AFX_IDW_TOOLBAR);

Return Value

Nonzero if successful; otherwise 0.

Parameters

pParentWnd

Pointer to the window that is the toolbar’s parent.

dwCtrlStyle

Additional styles for the creation of the embedded CToolBarCtrl object. By default, this value is set to TBSTYLE_FLAT. For a complete list of toolbar styles, see dwStyle.

dwStyle

The toolbar style. See Toolbar Control and Button Styles in the Platform SDK for a list of appropriate styles.

rcBorders

A CRect object that defines the widths of the toolbar window borders. These borders are set to 0,0,0,0 by default, thereby resulting in a toolbar window with no borders.

nID

The toolbar’s child-window ID.

Remarks

Call this function to create a Windows toolbar (a child window) and associate it with the CToolBar object. It also sets the toolbar height to a default value.

Use CreateEx, instead of Create, when certain styles need to be present during the creation of the embedded tool bar control. For example, set dwCtrlStyle to TBSTYLE_FLAT | TBSTYLE_TRANSPARENT to create a toolbar that resembles the Internet Explorer 4 toolbars.


CToolBar::CToolBar

CToolBar( );

Remarks

This member function constructs a CToolBar object and sets the default sizes.

Call the Create member function to create the toolbar window.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::Create


CToolBar::GetButtonInfo

void GetButtonInfo( int nIndex, UINT& nID, UINT& nStyle, int& iImage ) const;

Parameters

nIndex

Index of the toolbar button or separator whose information is to be retrieved.

nID

Reference to a UINT that is set to the command ID of the button.

nStyle

Reference to a UINT that is set to the style of the button.

iImage

Reference to an integer that is set to the index of the button’s image within the bitmap.

Remarks

This member function retrieves the control ID, style, and image index of the toolbar button or separator at the location specified by nIndex. Those values are assigned to the variables referenced by nID, nStyle, and iImage. The image index is the position of the image within the bitmap that contains images for all the toolbar buttons. The first image is at position 0.

If nIndex specifies a separator, iImage is set to the separator width in pixels.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::SetButtonInfo, CToolBar::GetItemID


CToolBar::GetButtonStyle

UINT GetButtonStyle( int nIndex ) const;

Return Value

The style of the button or separator specified by nIndex.

Parameters

nIndex

The index of the toolbar button or separator style to be retrieved.

Remarks

Call this member function to retrieve the style of a button or separator on the toolbar. A button’s style determines how the button appears and how it responds to user input. See SetButtonStyle for examples of button styles.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::SetButtonStyle


CToolBar::GetButtonText

CString GetButtonText( int nIndex ) const;

void GetButtonText( int nIndex, CString& rString ) const;

Return Value

A CString object containing the button text.

Parameters

nIndex

Index of the text to be retrieved.

rString

A reference to a CString object that will contain the text to be retrieved.

Remarks

Call this member function to retrieve the text that appears on a button. The second form of this member function fills a CString object with the string text.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::SetButtonText


CToolBar::GetItemID

UINT GetItemID( int nIndex ) const;

Return Value

The command ID of the button or separator specified by nIndex.

Parameters

nIndex

Index of the item whose ID is to be retrieved.

Remarks

This member function returns the command ID of the button or separator specified by nIndex. Separators return ID_SEPARATOR.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::CommandToIndex, CControlBar::GetCount


CToolBar::GetItemRect

virtual void GetItemRect( int nIndex, LPRECT lpRect );

Parameters

nIndex

Index of the item (button or separator) whose rectangle coordinates are to be retrieved.

lpRect

Address of the RECT structure that will contain the item’s coordinates.

Remarks

This member function fills the RECT structure whose address is contained in lpRect with the coordinates of the button or separator specified by nIndex. Coordinates are in pixels relative to the upper-left corner of the toolbar.

Use GetItemRect to get the coordinates of a separator you want to replace with a combo box or other control.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::CommandToIndex


CToolBar::GetToolBarCtrl

CToolBarCtrl& GetToolBarCtrl( ) const;

Return Value

A reference to a CToolBarCtrl object.

Remarks

This member function allows direct access to the underlying common control.

Use GetToolBarCtrl to take advantage of the functionality of the Windows toolbar common control, and to take advantage of the support CToolBarCtrl provides for toolbar customization.

For more information about using common controls, see the article Control Topics in Visual C++ Programmer’s Guide and Common Controls in the Windows 95 SDK Programmer’s Reference.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl


CToolBar::LoadBitmap

BOOL LoadBitmap( LPCTSTR lpszResourceName );

BOOL LoadBitmap( UINT nIDResource );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszResourceName

Pointer to the resource name of the bitmap to be loaded.

nIDResource

Resource ID of the bitmap to be loaded.

Remarks

Call this member function to load the bitmap specified by lpszResourceName or nIDResource. The bitmap should contain one image for each toolbar button. If the images are not of the standard size (16 pixels wide and 15 pixels high), call SetSizes to set the button sizes and their images.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::Create, CToolBar::SetButtons, CToolBar::SetSizes, CToolBar::LoadToolBar


CToolbar::LoadToolBar

BOOL LoadToolBar( LPCTSTR lpszResourceName );

BOOL LoadToolBar( UINT nIDResource );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszResourceName Pointer to the resource name of the toolbar to be loaded.

nIDResource Resource ID of the toolbar to be loaded.

Remarks

Call this member function to load the toolbar specified by lpszResourceName or nIDResource.

See toolbar editor in the Visual C++ User’s Guide for more information about creating a toolbar resource.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::Create, CToolbar::LoadBitmap, CToolBar::SetButtons


CToolBar::SetBitmap

BOOL SetBitmap( HBITMAP hbmImageWell );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hbmImageWell

Handle of a bitmap image that is associated with a toolbar.

Remarks

Call this member function to set the bitmap image for the toolbar. For example, call SetBitmap to change the bitmapped image after the user takes an action on a document that changes the action of a button.


CToolBar::SetButtonInfo

void SetButtonInfo( int nIndex, UINT nID, UINT nStyle, int iImage );

Parameters

nIndex

Index of the button or separator whose information is to be set.

nID

The value to which the button’s command ID is set.

nStyle

The new button style. The following button styles are supported:

  • TBBS_BUTTON Standard pushbutton (default)

  • TBBS_SEPARATOR Separator

  • TBBS_CHECKBOX Auto check-box button

  • TBBS_GROUP Marks the start of a group of buttons

  • TBBS_CHECKGROUP Marks the start of a group of check-box buttons

iImage

New index for the button’s image within the bitmap.

Remarks

Call this member function to set the button's command ID, style, and image number. For separators, which have the style TBBS_SEPARATOR, this function sets the separator's width in pixels to the value stored in iImage.

For information on bitmap images and buttons, see the CToolBar Overview and CToolBar::LoadBitmap.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::GetButtonInfo


CToolBar::SetButtons

BOOL SetButtons( const UINT* lpIDArray, int nIDCount );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpIDArray

Pointer to an array of command Ids. It can be NULL to allocate empty buttons.

nIDCount

Number of elements in the array pointed to by lpIDArray.

Remarks

This member function sets each toolbar button's command ID to the value specified by the corresponding element of the array lpIDArray. If an element of the array has the value ID_SEPARATOR, a separator is created in the corresponding position of the toolbar. This function also sets each button's style to TBBS_BUTTON and each separator's style to TBBS_SEPARATOR, and assigns an image index to each button. The image index specifies the position of the button’s image within the bitmap.

You do not need to account for separators in the bitmap because this function does not assign image indexes for separators. If your toolbar has buttons at positions 0, 1, and 3 and a separator at position 2, the images at positions 0, 1, and 2 in your bitmap are assigned to the buttons at positions 0, 1, and 3, respectively.

If lpIDArray is NULL, this function allocates space for the number of items specified by nIDCount. Use SetButtonInfo to set each item’s attributes.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::Create, CToolBar::SetButtonInfo, CToolBar::SetButtonStyle, CToolBar::LoadToolBar


CToolBar::SetButtonStyle

void SetButtonStyle( int nIndex, UINT nStyle );

Parameters

nIndex

Index of the button or separator whose information is to be set.

nStyle

The button style. The following button styles are supported:

  • TBBS_BUTTON Standard pushbutton (default)

  • TBBS_SEPARATOR Separator

  • TBBS_CHECKBOX Auto check-box button

  • TBBS_GROUP Marks the start of a group of buttons

  • TBBS_CHECKGROUP Marks the start of a group of check-box buttons

Remarks

Call this member function to set the style of a button or separator, or to group buttons. A button's style determines how the button appears and how it responds to user input.

Before calling SetButtonStyle, call the GetButtonStyle member function to retrieve the button or separator style.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::GetButtonStyle


CToolBar::SetButtonText

BOOL SetButtonText( int nIndex, LPCTSTR lpszText );

Return Value

Nonzero if successful; otherwise 0.

Parameters

nIndex

Index of the button whose text is to be set.

lpszText

Points to the text to be set on a button.

Remarks

Call this function to set the text on a button.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::GetButtonText


CToolBar::SetHeight

void SetHeight( int cyHeight );

Parameters

cyHeight

The height in pixels of the toolbar.

Remarks

This member function sets the toolbar's height to the value, in pixels, specified in cyHeight.

After calling SetSizes, use this member function to override the standard toolbar height. If the height is too small, the buttons will be clipped at the bottom.

If this function is not called, the framework uses the size of the button to determine the toolbar height.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::SetSizes, CToolBar::SetButtonInfo, CToolBar::SetButtons


CToolBar::SetSizes

void SetSizes( SIZE sizeButton, SIZE sizeImage );

Parameters

sizeButton

The size in pixels of each button.

sizeImage

The size in pixels of each image.

Remarks

Call this member function to set the toolbar's buttons to the size, in pixels, specified in sizeButton. The sizeImage parameter must contain the size, in pixels, of the images in the toolbar's bitmap. The dimensions in sizeButton must be sufficient to hold the image plus 7 pixels extra in width and 6 pixels extra in height. This function also sets the toolbar height to fit the buttons.

Call this member function only for toolbars that do not follow Windows Interface Guidelines for Software Design recommendations for button and image sizes.

CToolBar Overview | Class Members | Hierarchy Chart

See Also CToolBar::LoadBitmap, CToolBar::SetButtonInfo, CToolBar::SetButtons,


CToolBarCtrl

The CToolBarCtrl class provides the functionality of the Windows toolbar common control. This control (and therefore the CToolBarCtrl class) is available only to programs running under Windows 95 and Windows NT version 3.51 and later.

A Windows toolbar common control is a rectangular child window that contains one or more buttons. These buttons can display a bitmap image, a string, or both. When the user chooses a button, it sends a command message to the toolbar’s owner window. Typically, the buttons in a toolbar correspond to items in the application’s menu; they provide a more direct way for the user to access an application’s commands.

CToolBarCtrl objects contain several important internal data structures: a list of button image bitmaps or an image list, a list of button label stings, and a list of TBBUTTON structures which associate an image and/or string with the position, style, state, and command ID of the button. Each of the elements of these data structures is referred to by a zero-based index. Before you can use a CToolBarCtrl object, you must set up these data structures. The list of strings can only be used for button labels; you cannot retrieve strings from the toolbar.

To use a CToolBarCtrl object, you will typically follow these steps:

  1. Construct the CToolBarCtrl object.

  2. Call Create to create the Windows toolbar common control and attach it to the CToolBarCtrl object. Indicate the style of toolbar by using styles, such as TBSTYLE_TRANSPARENT for a transparent toolbar or TBSTYLE_DROPDOWN for a toolbar that supports drop-down style buttons.

  3. Identify how you want the buttons on the toolbar displayed:
    • To use bitmap images for buttons, add the button bitmaps to the toolbar by calling AddBitmap.

    • To use images displayed from an image list for buttons, specify the image list by calling SetImageList, SetHotImageList, or SetDisabledImageList.

    • To use string labels for buttons, add the strings to the toolbar by calling AddString and/or AddStrings.
  4. Add button structures to the toolbar by calling AddButtons.

  5. If you want tool tips for a toolbar button in an owner window that is not a CFrameWnd, you need to handle the TTN_NEEDTEXT messages in the toolbar’s owner window as described in CToolBarCtrl: Handling Tool Tip Notifications. If the parent window of the toolbar is derived from CFrameWnd, tool tips are displayed without any extra effort from you because CFrameWnd provides a default handler.

  6. If you want your user to be able to customize the toolbar, handle customization notification messages in the owner window as described in CToolBarCtrl: Handling Customization Notifications.

You can use SaveState to save the current state of a toolbar control in the registry and RestoreState to restore the state based on information previously stored in the registry. In addition to saving the toolbar state between uses of the application, applications typically store the state before the user begins customizing the toolbar in case the user later wants to restore the toolbar to its original state.

Support for Internet Explorer Version 4.0 and Later

To support functionality introduced in Internet Explorer, version 4.0 and later, MFC provides image list support and transparent and flat styles for toolbar controls.

A transparent toolbar allows the client under the toolbar to show through. To create a transparent toolbar, use both TBSTYLE_FLAT and TBSTYLE_TRANSPARENT styles. Transparent toolbars feature hot tracking; that is, when the mouse pointer moves over a hot button on the toolbar, the button's appearance changes. Toolbars created with just the TBSTYLE_FLAT style will contain buttons that are not transparent.

Image list support allows a control greater flexibility for default behavior, hot images, and disabled images. Use GetImageList, GetHotImageList, and GetDisabledImageList with the transparent toolbar to manipulate the image according to its state:

For more information on using CToolBarCtrl, see Control Topics and Using CToolBarCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CMNCTRL1 | MFC Sample MFCIE

See Also CToolBar


CToolBarCtrl Class Members

Construction
Attributes
Operations

Construction

CToolBarCtrl | Constructs a CToolBarCtrl object.
Create | Creates a toolbar control and attaches it to a CToolBarCtrl object.

Attributes

IsButtonEnabled | Tells whether the specified button in a toolbar control is enabled.
IsButtonChecked | Tells whether the specified button in a toolbar control is checked.
IsButtonPressed | Tells whether the specified button in a toolbar control is pressed.
IsButtonHidden | Tells whether the specified button in a toolbar control is hidden.
IsButtonIndeterminate | Tells whether the state of the specified button in a toolbar control is indeterminate (gray).
SetState | Sets the state for the specified button in a toolbar control.
GetState | Retrieves information about the state of the specified button in a toolbar control, such as whether it is enabled, pressed, or checked.
GetButton | Retrieves information about the specified button in a toolbar control.
GetButtonCount | Retrieves a count of the buttons currently in the toolbar control.
GetItemRect | Retrieves the bounding rectangle of a button in a toolbar control.
GetRect | Retrieves the bounding rectangle for a specified toolbar button.
SetButtonStructSize | Specifies the size of the TBBUTTON structure.
GetButtonSize | Retrieves the current width and height of toolbar buttons, in pixels.
SetButtonSize | Sets the size of the buttons to be added to a toolbar control.
SetBitmapSize | Sets the size of the bitmapped images to be added to a toolbar control.
GetToolTips | Retrieves the handle of the tool tip control, if any, associated with the toolbar control.
SetToolTips | Associates a tool tip control with the toolbar control.
SetOwner | Sets the window to receive notification messages from the toolbar control.
SetRows | Sets the number of rows of buttons displayed in the toolbar.
GetRows | Retrieves the number of rows of buttons currently displayed in the toolbar.
SetCmdID | Sets the command identifier to be sent to the owner window when the specified button is pressed.
GetBitmapFlags | Gets flags associated with the toolbar’s bitmap.
GetDisabledImageList | Retrieves the image list that a toolbar control uses to display disabled buttons.
GetHotImageList | Retrieves the image list that a toolbar control uses to display "hot" buttons. A hot button appears highlighted when the mouse pointer is above it.
GetImageList | Retrieves the image list that a toolbar control uses to display buttons in their default state.
GetStyle | Retrieves the styles currently in use for a toolbar control.
GetMaxTextRows | Retrieves the maximum number of text rows displayed on a toolbar button.
IsButtonHighlighted | Checks the highlight state of the toolbar button.
SetButtonWidth | Sets the minimum and maximum button widths in the toolbar control.
SetDisabledImageList | Sets the image list that the toolbar control will use to display disabled buttons.
SetHotImageList | Sets the image list that the toolbar control will use to display "hot" buttons.
SetImageList | Sets the image list that the toolbar will use to display buttons that are in their default state.
GetDropTarget | Retrieves the IDropTarget interface for a toolbar control.
SetIndent | Sets the indentation for the first button in a toolbar control.
SetMaxTextRows | Sets the maximum number of text rows displayed on a toolbar button.
SetStyle | Sets the styles for a toolbar control.
GetAnchorHighlight | Retrieves the anchor highlight setting for a toolbar.
SetAnchorHighlight | Sets the anchor highlight setting for a toolbar.
GetHotItem | Retrieves the index of the hot item in a toolbar.
SetHotItem | Sets the hot item in a toolbar.
GetInsertMark | Retrieves the current insertion mark for the toolbar.
SetInsertMark | Sets the current insertion mark for the toolbar.
GetMaxSize | Retrieves the total size of all of the visible buttons and separators in the toolbar.
InsertMarkHitTest | Retrieves the insertion mark information for a point in a toolbar.
GetExtendedStyle | Retrieves the extended styles for a toolbar control.
SetExtendedStyle | Sets the extended styles for a toolbar control.
GetInsertMarkColor | Retrieves the color used to draw the insertion mark for the toolbar.
SetInsertMarkColor | Sets the color used to draw the insertion mark for the toolbar.
MapAccelerator | Maps an accelerator character to a toolbar button.
MoveButton | Moves a button from one index to another.
HitTest | Determines where a point lies in a toolbar control.

Operations

EnableButton | Enables or disables the specified button in a toolbar control.
CheckButton | Checks or clears a given button in a toolbar control.
PressButton | Presses or releases the specified button in a toolbar control.
GetButtonInfo | Retrieves the information for a button in a toolbar.
SetButtonInfo | Sets the information for an existing button in a toolbar.
SetDrawTextFlags | Sets the flags in the Win32 function DrawText, which is used to draw the text in the specified rectangle, formatted according to how the flags are set.
HideButton | Hides or shows the specified button in a toolbar control.
Indeterminate | Sets or clears the indeterminate (gray) state of the specified button in a toolbar control.
AddBitmap | Adds one or more bitmap button images to the list of button images available for a toolbar control.
AddButtons | Adds one or more buttons to a toolbar control.
InsertButton | Inserts a button in a toolbar control.
DeleteButton | Deletes a button from the toolbar control.
CommandToIndex | Retrieves the zero-based index for the button associated with the specified command identifier.
RestoreState | Restores the state of the toolbar control.
MarkButton | Sets the highlight state of a given button in a toolbar control.
LoadImages | Loads bitmaps into a toolbar control's image list.
SaveState | Saves the state of the toolbar control.
Customize | Displays the Customize Toolbar dialog box.
AddString | Adds a new string, passed as a resource ID, to the toolbar’s internal list of strings.
AddStrings | Adds a new string or strings, passed as a pointer to a buffer of null-separated strings, to the toolbar’s internal list of strings.
AutoSize | Resizes a toolbar control.


CToolBarCtrl: Handling Tool Tip Notifications

When you specify the TBSTYLE_TOOLTIPS style, the toolbar creates and manages a tool tip control. A tool tip is a small pop-up window that contains a line of text describing a toolbar button. The tool tip is hidden, appearing only when the user puts the cursor on a toolbar button and leaves it there for approximately one-half second. The tool tip is displayed near the cursor.

Before the tool tip is displayed, the TTN_NEEDTEXT notification message is sent to the toolbar’s owner window to retrieve the descriptive text for the button. If the toolbar's owner window is a CFrameWnd window, tool tips are displayed wihout any extra effort, because CFrameWnd has a default handler for the TTN_NEEDTEXT notification. If the toolbar’s owner window is not derived from CFrameWnd, such as a dialog box or form view, you must add an entry to your owner window's message map and provide a notification handler in the message map. The entry to your owner window’s message map is as follows:

ON_NOTIFY_EX( TTN_NEEDTEXT, 0, memberFxn )

memberFxn

The member function to be called when text is needed for this button.

Note that the id of a tool tip is always 0.

In addition to the TTN_NEEDTEXT notification, a tool tip control can send the following notifications to a toolbar control:

Notification | Meaning
TTN_NEEDTEXTA | Tool tip control requires ASCII text (Win95 only)
TTN_NEEDTEXTW | Tool tip control requires UNICODE text (Windows NT only)
TBN_HOTITEMCHANGE | Indicates that the hot (highlighted) item has changed.
NM_RCLICK | Indicates the user has right-clicked a button.
TBN_DRAGOUT | Indicates the user has clicked the button and dragged the pointer off the button. It allows an application to implement drag and drop from a toolbar button. When receiving this notification, the application will begin the drag and drop operation.
TBN_DROPDOWN | Indicates the user has clicked a button that uses the TBSTYLE_DROPDOWN style.
TBN_GETOBJECT | Indicates the user moved the pointer over a button ithat uses the TBSTYLE_DROPPABLE style. The message.

For an example handler function and more information about enabling tool tips, see Tool Tips in Visual C++ Programmer’s Guide.


CToolBarCtrl: Handling Customization Notifications

A Windows toolbar common control has built-in customization features, including a system-defined customization dialog box, which allow the user to insert, delete, or rearrange toolbar buttons. The application determines whether the customization features are available and controls the extent to which the user can customize the toolbar.

You can make these customization features available to the user by giving the toolbar the CCS_ADJUSTABLE 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. The application can display the dialog box by using the Customize member function.

The toolbar control sends notification 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 control determines the location of the mouse cursor. If the cursor is outside the toolbar, the button is deleted. If the cursor is on another toolbar button, the toolbar sends the TBN_QUERYINSERT notification message to the parent window to determine if a button may be inserted to the left of the given button. The button is inserted if the parent window returns TRUE; otherwise, it is not. The toolbar sends the TBN_TOOLBARCHANGE notification message to signal the end of the drag operation.

If the user begins a drag operation without holding down the SHIFT key, the toolbar control sends the TBN_BEGINDRAG notification message to the owner window. An application that implements its own button-dragging code can use this message as a signal to begin a drag operation. The toolbar sends the TBN_ENDDRAG notification message to signal the end of the drag operation.

A toolbar control 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 notification messages. If the parent window does not return TRUE for any button, the toolbar destroys the dialog box.

Next, the toolbar control determines if any buttons may be deleted from the toolbar 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 grays those that may not be deleted.

Whenever the toolbar control needs information about a button in the Customize Toolbar dialog box, it sends the TBN_GETBUTTONINFO notification message, specifying the index of the button for which it needs information and the address of a TBNOTIFY structure. The parent window must fill the structure with the relevant information.

The Customize Toolbar dialog box includes a Help button and a Reset button. When the user chooses the Help button, the toolbar control 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.

These messages are all WM_NOTIFY messages, and they can be handled in your owner window by adding message-map entries of the following form to your owner window’s message map:

ON_NOTIFY( wNotifyCode, idControl, memberFxn )

wNotifyCode

Notification message identifier code, such as TBN_BEGINADJUST.

idControl

The identifier of the control sending the notification.

memberFxn

The member function to be called when this notification is received.

Your member function would be declared with the following prototype:

afx_msg void memberFxn( NMHDR * pNotifyStruct, LRESULT * result );

If the notification message handler returns a value, it should put it in the LRESULT pointed to by result.

For each message, pNotifyStruct points to either an NMHDR structure or a TBNOTIFY structure. These structures are described below:

The NMHDR structure contains the following members:

typedef struct tagNMHDR {
HWND hwndFrom;  // handle of control sending message
UINT idFrom;// identifier of control sending message
UINT code;  // notification code; see below
} NMHDR;

hwndFrom

Window handle of the control that is sending the notification. To convert this handle to a CWnd pointer, use CWnd::FromHandle.

idFrom

Identifier of the control sending the notification.

code

Notification code. This member can be a value specific to a control type, such as TBN_BEGINADJUST or TTN_NEEDTEXT, or it can be one of the common notification values listed below:

  • NM_CLICK The user has clicked the left mouse button within the control.

  • NM_DBLCLK The user has double-clicked the left mouse button within the control.

  • NM_KILLFOCUS The control has lost the input focus.

  • NM_OUTOFMEMORY The control could not complete an operation because there is not enough memory available.

  • NM_RCLICK The user has clicked the right mouse button within the control.

  • NM_RDBLCLK The user has double-clicked the right mouse button within the control.

  • NM_RETURN The control has the input focus, and the user has pressed the ENTER key.

  • NM_SETFOCUS The control has received the input focus.

The TBNOTIFY structure contains the following members:

typedef struct {
NMHDR hdr; // information common to all WM_NOTIFY messages
int iItem; // index of button associated with notification
TBBUTTON tbButton; // info about button associated with notification
int cchText;   // count of characters in button text
LPSTR lpszText;// address of button text
} TBNOTIFY, FAR* LPTBNOTIFY;

hdr

Information common to all WM_NOTIFY messages.

iItem

Index of button associated with notification.

tbButton

TBBUTTON structure that contains information about the toolbar button associated with the notification.

cchText

Count of characters in button text.

lpszText

Pointer to button text.

The notifications the toolbar sends are as follows:

  • TBN_BEGINADJUST Sent when the user begins customizing a toolbar control. The pointer points to an NMHDR structure that contains information about the notification. The handler doesn’t need to return any specific value.

  • TBN_BEGINDRAG Sent when the user begins dragging a button in a toolbar control. The pointer points to a TBNOTIFY structure. The iItem member contains the zero-based index of the button being dragged. The handler doesn’t need to return any specific value.

  • TBN_CUSTHELP Sent when the user chooses the Help button in the Customize Toolbar dialog box. No return value. The pointer points to an NMHDR structure that contains information about the notification message. The handler doesn’t need to return any specific value.

  • TBN_ENDADJUST Sent when the user stops customizing a toolbar control. The pointer points to an NMHDR structure that contains information about the notification message. The handler doesn’t need to return any specific value.

  • TBN_ENDDRAG Sent when the user stops dragging a button in a toolbar control. The pointer points to a TBNOTIFY structure. The iItem member contains the zero-based index of the button being dragged. The handler doesn’t need to return any specific value.

  • TBN_GETBUTTONINFO Sent when the user is customizing a toolbar control. The toolbar uses this notification message to retrieve information needed by the Customize Toolbar dialog box. The pointer points to a TBNOTIFY structure. The iItem member specifies the zero-based index of a button. The pszText and cchText members specify the address and length, in characters, of the current button text. An application should fill the structure with information about the button. Return TRUE if button information was copied to the structure, or FALSE otherwise.

  • TBN_QUERYDELETE Sent while the user is customizing a toolbar to determine whether a button may be deleted from a toolbar control. The pointer points to a TBNOTIFY structure. The iItem member contains the zero-based index of the button to be deleted. Return TRUE to allow the button to be deleted or FALSE to prevent the button from being deleted.

  • TBN_QUERYINSERT Sent while the user is customizing a toolbar control to determine whether a button may be inserted to the left of the given button. The pointer points to a TBNOTIFY structure. The iItem member contains the zero-based index of the button to be inserted. Return TRUE to allow a button to be inserted in front of the given button or FALSE to prevent the button from being inserted.

  • TBN_RESET Sent when the user resets the content of the Customize Toolbar dialog box. The pointer points to an NMHDR structure that contains information about the notification message. The handler doesn’t need to return any specific value.

  • TBN_TOOLBARCHANGE Sent after the user has customized a toolbar control. The pointer points to an NMHDR structure that contains information about the notification message. The handler doesn’t need to return any specific value.


CToolBarCtrl::AddBitmap

int AddBitmap( int nNumButtons, UINT nBitmapID );

int AddBitmap( int nNumButtons, CBitmap* pBitmap );

Return Value

Zero-based index of the first new image if successful; otherwise – 1.

Parameters

nNumButtons

Number of button images in the bitmap.

nBitmapID

Resource identifier of the bitmap that contains the button image or images to add.

pBitmap

Pointer to the CBitmap object that contains the button image or images to add.

Remarks

Call this function to add one or more button images to the list of button images stored in the toolbar control. You can use the Windows API CreateMappedBitmap to map colors before adding the bitmap to the toolbar.

If you pass a pointer to a CBitMap object, you must ensure that the bitmap is not destroyed until after the toolbar is destroyed.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::AddButtons, CToolBarCtrl::InsertButton, CToolBarCtrl::AddString, CToolBarCtrl::AddStrings


CToolBarCtrl::AddButtons

BOOL AddButtons( int nNumButtons, LPTBBUTTON lpButtons );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nNumButtons

Number of buttons to add.

lpButtons

Address of an array of TBBUTTON structures that contains information about the buttons to add. There must be the same number of elements in the array as buttons specified by nNumButtons.

Remarks

Call this function to add one or more buttons to a toolbar control.

The lpButtons pointer points to an array of TBBUTTON structures. Each TBBUTTON structure associates the button being added with the button’s style, image and/or string, command ID, state, and user-defined data:

typedef struct _TBBUTTON {
int iBitmap;// zero-based index of button image
int idCommand;  // command to be sent when button pressed
BYTE fsState;   // button state--see below
BYTE fsStyle;   // button style--see below
DWORD dwData;   // application-defined value
int iString;// zero-based index of button label string
} TBBUTTON;

The members are as follows:

iBitmap

Zero-based index of button image. NULL if no image for this button.

idCommand

Command identifier associated with the button. This identifier is sent in a WM_COMMAND message when the button is chosen. If the fsStyle member has the TBSTYLE_SEP value, this member must be zero.

fsState

Button state flags. It can be a combination of the values listed below:

  • TBSTATE_CHECKED The button has the TBSTYLE_CHECKED style and is being pressed.

  • TBSTATE_ENABLED The button accepts user input. A button that does not have this state does not accept user input and is grayed.

  • TBSTATE_HIDDEN The button is not visible and cannot receive user input.

  • TBSTATE_INDETERMINATE The button is grayed.

  • TBSTATE_PRESSED The button is being pressed.

  • TBSTATE_WRAP A line break follows the button. The button must also have the TBSTATE_ENABLED state.

fsStyle

Button style. It can be a combination of the values listed below:

  • TBSTYLE_BUTTON Creates a standard push button.

  • TBSTYLE_CHECK Creates a button that toggles between the pressed and unpressed states each time the user clicks it. The button has a different background color when it is in the pressed state.

  • TBSTYLE_CHECKGROUP Creates a check button that stays pressed until another button in the group is pressed.

  • TBSTYLE_GROUP Creates a button that stays pressed until another button in the group is pressed.

  • TBSTYLE_SEP Creates a separator, providing a small gap between button groups. A button that has this style does not receive user input.

dwData

User-defined data.

iString

Zero-based index of the string to use as the button’s label. NULL if there is no string for this button.

The image and/or string whose index you provide must have previously been added to the toolbar control’s list using AddBitmap, AddString, and/or AddStrings.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::InsertButton, CToolBarCtrl::DeleteButton, CToolBarCtrl::AddBitmap, CToolBarCtrl::AddString, CToolBarCtrl::AddStrings


CToolBarCtrl::AddString

int AddString( UINT nStringID );

Return Value

The zero-based index of the first new string added if successful; otherwise –1.

Parameters

nStringID

Resource identifier of the string resource to add to the toolbar control’s string list.

Remarks

Call this function to add a new string, passed as a resource ID, to the toolbar’s internal list of strings.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::AddStrings, CToolBarCtrl::AddButtons, CToolBarCtrl::InsertButton, CToolBarCtrl::AddBitmap


CToolBarCtrl::AddStrings

int AddStrings( LPCTSTR lpszStrings );

Return Value

The zero-based index of the first new string added if successful; otherwise –1.

Parameters

lpszStrings

Address of a buffer that contains one or more null-terminated strings to add to the toolbar’s string list. The last string must be terminated with two null characters.

Remarks

Call this function to add a new string or strings to the list of strings available for a toolbar control. Strings in the buffer must be separated by a null character.

You must ensure that the last string has two null terminators. To properly format a constant string, you might write it as:

// one null added automatically
lpszStrings = "Only one string to add\0";

or:

// adds three strings with one call
lpszStrings = "String 1\0String 2\0String 3\0";

You should not pass a CString object to this function since it is not possible to have more than one null character in a CString.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::AddString, CToolBarCtrl::AddButtons, CToolBarCtrl::InsertButton, CToolBarCtrl::AddBitmap


CToolBarCtrl::AutoSize

void AutoSize( );

Remarks

Call this function to resize the entire toolbar control. You should call this function when the size of the parent window changes or when the size of the toolbar changes (such as when you set the button or bitmap size, or add strings).

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetBitmapSize, CToolBarCtrl::SetButtonSize, CToolBarCtrl::AddString, CToolBarCtrl::AddStrings


CToolBarCtrl::CheckButton

BOOL CheckButton( int nID, BOOL bCheck = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

Command identifier of the button to check or clear.

bCheck

TRUE to check the button, FALSE to clear it.

Remarks

Call this function to check or clear a given button in a toolbar control. When a button has been checked, it appears to have been pressed. If you want to change more than one button state, consider calling SetState instead.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::IsButtonChecked, CToolBarCtrl::EnableButton, CToolBarCtrl::PressButton, CToolBarCtrl::HideButton, CToolBarCtrl::Indeterminate, CToolBarCtrl::GetState, CToolBarCtrl::SetState


CToolBarCtrl::CommandToIndex

UINT CommandToIndex( UINT nID ) const;

Return Value

The zero-based index for the button associated with the command ID.

Parameters

nID

Command ID whose button index you want to find.

Remarks

Call this function to retrieve the zero-based index for the button associated with the specified command identifier.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetCmdID, CToolBarCtrl::GetButton, CToolBarCtrl::AddButtons, CToolBarCtrl::InsertButton


CToolBarCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if successful; otherwise zero.

Parameters

dwStyle

Specifies the toolbar control’s style. Toolbars must always have the WS_CHILD style. In addition, you can specify any combination of toolbar styles and window styles as described under Remarks.

rect

Optionally specifies the toolbar control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the toolbar control’s parent window. It must not be NULL.

nID

Specifies the toolbar control’s ID.

Remarks

You construct a CToolBarCtrl in two steps. First call the constructor, then call Create, which creates the toolbar control and attaches it to the CToolBarCtrl object.

The toolbar control 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 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.

Apply the following window styles to a toolbar control.

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

Next, you may want to apply one or more of the common control styles:

  • CCS_ADJUSTABLE Allows toolbars to be customized by the user. If this style is used, the toolbar’s owner window must handle the customization notification messages sent by the toolbar, as described in CToolBarCtrl: Handling Customization Notifications.

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

  • CCS_NODIVIDER Prevents a two-pixel highlight from being drawn at the top of the control.

  • CCS_NOHILITE Prevents a one-pixel highlight from being drawn at the top of the control.

  • CCS_NOMOVEY Causes the control to resize and move itself horizontally, but not vertically, in response to a WM_SIZE message. If the CCS_NORESIZE style is used, this style does not apply.

  • 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 window. If the CCS_TOP or CCS_BOTTOM style is also used, the height is adjusted to the default, but the position and width remain unchanged.

  • CCS_NORESIZE Prevents the control from using the default width and height when setting its initial size or a new size. Instead, the control uses the width and height specified in the request for creation or sizing.

  • CCS_TOP Causes the control to position itself at the top of the parent window’s client area and sets the width to be the same as the parent window’s width. Toolbars have this style by default.

Finally, apply a combination of toolbar styles to either the control or the buttons themselves. The styles are described in the topic Toolbar Control and Button Styles in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::CToolBarCtrl, CToolBarCtrl::SetButtonStructSize


CToolBarCtrl::CToolBarCtrl

CToolBarCtrl( );

Remarks

Constructs a CToolBarCtrl object. You must call Create to make the toolbar usable.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::Create


CToolBarCtrl::Customize

void Customize( );

Remarks

Call this function to display the Customize Toolbar dialog box. This dialog box allows the user to customize the toolbar by adding and deleting buttons.

To support customization, your toolbar’s parent window must handle the customization notification messages as described in CToolBarCtrl: Handling Customization Notifications. Your toolbar must also have been created with the CCS_ADJUSTABLE style, as described in CToolBarCtrl::Create.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl: Handling Customization Notifications


CToolBarCtrl::DeleteButton

BOOL DeleteButton( int nIndex );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nIndex

Zero-based index of the button to delete.

Remarks

Call this function to delete a button from the toolbar control.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::AddButtons, CToolBarCtrl::AutoSize, CToolBarCtrl::InsertButton


CToolBarCtrl::EnableButton

BOOL EnableButton( int nID, BOOL bEnable = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

Command identifier of the button to enable or disable.

bEnable

TRUE to enable the button; FALSE to disable the button.

Remarks

Call this function to enable or disable the specified button in a toolbar control. When a button has been enabled, it can be pressed and checked. If you want to change more than one button state, consider calling SetState instead.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::IsButtonEnabled, CToolBarCtrl::CheckButton, CToolBarCtrl::PressButton, CToolBarCtrl::HideButton, CToolBarCtrl::Indeterminate, CToolBarCtrl::GetState, CToolBarCtrl::SetState


CToolBarCtrl::GetAnchorHighlight

BOOL GetAnchorHighlight( ) const;

Return Value

If nonzero, anchor highlighting is enabled. If zero, anchor highlighting is disabled.

Remarks

This member function implements the behavior of the Win32 message TB_GETANCHORHIGHLIGHT, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetAnchorHighlight


CToolBarCtrl::GetBitmapFlags

UINT GetBitmapFlags( ) const;

Return Value

A UINT that has the TBBF_LARGE flag set if the display can support large toolbar bitmaps, clear otherwise.

Remarks

Call this function to retrieve the bitmap flags from the toolbar. You should call it after creating the toolbar but before adding bitmaps to the toolbar.

The return value indicates whether the display supports large bitmaps or not. If the display supports large bitmaps and if you choose to use them, call SetBitmapSize and SetButtonSize before adding your large bitmap using AddBitmap.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::AddBitmap, CToolBarCtrl::SetBitmapSize, CToolBarCtrl::SetButtonSize


CToolBarCtrl::GetButton

BOOL GetButton( int nIndex, LPTBBUTTON lpButton ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

nIndex

Zero-based index of the button for which to retrieve information.

lpButton

Address of the TBBUTTON structure that is to receive a copy of the button information. See CToolBarCtrl::AddButtons for information about the TBBUTTON structure.

Remarks

Call this function to retrieve information about the specified button in a toolbar control.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetState, CToolBarCtrl::SetState, CToolBarCtrl::GetButtonCount, CToolBarCtrl::GetItemRect, CToolBarCtrl::CommandToIndex, CToolBarCtrl::AddButtons, CToolBarCtrl::InsertButton


CToolBarCtrl::GetButtonCount

int GetButtonCount( ) const;

Return Value

The count of the buttons.

Remarks

Call this function to retrieve a count of the buttons currently in the toolbar control.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetButton, CToolBarCtrl::GetState, CToolBarCtrl::GetItemRect, CToolBarCtrl::AddButtons, CToolBarCtrl::InsertButton, CToolBarCtrl::DeleteButton


CToolBarCtrl::GetButtonInfo

BOOL GetButtonInfo( int nID, TBBUTTONINFO* ptbbi ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

The button identifier.

ptbbi

A pointer to a TBBUTTONINFO structure that receives the button information.

Remarks

This member function implements the behavior of the Win32 message TB_GETBUTTONINFO, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetButtonInfo


CToolBarCtrl::GetButtonSize

DWORD GetButtonSize( ) const;

Return Value

A DWORD value that contains the width and height values in the LOWORD and HIWORD, respectively.

Remarks

Call this member function to get the size of a toolbar button.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetButtonInfo


CToolBarCtrl::GetDisabledImageList

CImageList* GetDisabledImageList( ) const;

Return Value

A pointer to a CImageList object, or NULL if no disabled image list is set.

Remarks

This member function implements the behavior of the Win32 message TB_GETDISABLEDIMAGELIST, as described in the Platform SDK.

The MFC implementation of GetDisabledImageList uses a CImageList object containing the toolbar control's button images, rather than a handle to an image list.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetDisabledImageList, CToolBarCtrl::GetHotImageList, CToolBarCtrl::GetImageList


CToolBarCtrl::GetDropTarget

HRESULT GetDropTarget( IDropTarget** ppDropTarget ) const;

Return Value

Returns an HRESULT value indicating success or failure of the operation.

Parameters

ppDropTarget

A pointer to an IDropTarget interface pointer. If an error occurs, a NULL pointer is placed in this address.

Remarks

This member function implements the behavior of the Win32 message TB_GETOBJECT, as described in the Platform SDK.


CToolBarCtrl::GetExtendedStyle

DWORD GetExtendedStyle( ) const;

Return Value

A DWORD that represents the extended styles currently in use for the toolbar control. For a list of styles, see Toolbar Extended Styles, in the Platform SDK.

Remarks

This member function implements the behavior of the Win32 message TB_GETEXTENDEDSTYLE, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetExtendedStyle


CToolBarCtrl::GetHotImageList

CImageList* GetHotImageList( ) const;

Return Value

A pointer to a CImageList object, or NULL if no disabled image list is set.

Remarks

This member function implements the behavior of the Win32 message TB_GETHOTIMAGELIST, as described in the Platform SDK.

A hot button appears highlighted when the mouse pointer is above it.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetDisabledImageList, CToolBarCtrl::GetImageList


CToolBarCtrl::GetHotItem

int GetHotItem( ) const;

Return Value

The zero-based index of the hot item in a toolbar.

Remarks

This member function implements the behavior of the Win32 message TB_GETHOTITEM, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetHotItem


CToolBarCtrl::GetImageList

CImageList* GetImageList( ) const;

Return Value

A pointer to a CImageList object, or NULL if no disabled image list is set.

Remarks

This member function implements the behavior of the Win32 message TB_GETIMAGELIST, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetDisabledImageList, CToolBarCtrl::GetHotImageList


CToolBarCtrl::GetInsertMark

void GetInsertMark( TBINSERTMARK* ptbim ) const;

Parameters

ptbim

A pointer to a TBINSERTMARK structure that receives the insertion mark.

Remarks

This member function implements the behavior of the Win32 message TB_GETINSERTMARK, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetInsertMark


CToolBarCtrl::GetInsertMarkColor

COLORREF GetInsertMarkColor( ) const;

Return Value

A COLORREF value that contains the current insertion mark color.

Remarks

This member function implements the behavior of the Win32 message TB_GETINSERTMARKCOLOR, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetInsertMarkColor


CToolBarCtrl::GetItemRect

BOOL GetItemRect( int nIndex, LPRECT lpRect ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

nIndex

Zero-based index of the button for which to retrieve information.

lpRect

Address of a RECT structure or a CRect object that receives the coordinates of the bounding rectangle.

Remarks

Call this function to retrieve the bounding rectangle of a button in a toolbar control. This function does not retrieve the bounding rectangle for buttons whose state is set to TBSTATE_HIDDEN.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetButton, CToolBarCtrl::GetButtonCount, CToolBarCtrl::GetState, CToolBarCtrl::SetButtonSize, CToolBarCtrl::SetBitmapSize


CToolBarCtrl::GetMaxSize

BOOL GetMaxSize( LPSIZE pSize ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

pSize

A pointer to a SIZE structure that receives the size of the items.

Remarks

This member function implements the behavior of the Win32 message TB_GETMAXSIZE, as described in the Platform SDK.


CToolBarCtrl::GetMaxTextRows

int GetMaxTextRows( ) const;

Return Value

The maximum number of text rows displayed on a toolbar button.

Remarks

Call this member function to retrieve the maximum number of text rows displayed on a toolbar button.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetMaxTextRows


CToolBarCtrl::GetRect

BOOL GetRect( int nID, LPRECT lpRect ) const;

Return Value

TRUE if successful; otherwise FALSE.

Parameters

nID

The button identifier.

lpRect

A pointer to a RECT structure to receive the bounding rectangle information.

Remarks

This member function implements the behavior of the Win32 message TB_GETRECT, as described in the Platform SDK.


CToolBarCtrl::GetRows

int GetRows( ) const;

Return Value

Number of rows of buttons currently displayed on the toolbar.

Remarks

Call this function to retrieve the number of rows of buttons currently displayed by the toolbar control. Note that the number of rows will always be one unless the toolbar was created with the TBSTYLE_WRAPABLE style.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also TBSTYLE_WRAPABLE in CToolBarCtrl::Create, CToolBarCtrl::SetRows


CToolBarCtrl::GetState

int GetState( int nID ) const;

Return Value

The button state information if successful or – 1 otherwise. The button state information can be a combination of the values listed in CToolBarCtrl::AddButtons.

Parameters

nID

Command identifier of the button for which to retrieve information.

Remarks

Call this function to retrieve information about the state of the specified button in a toolbar control, such as whether it is enabled, pressed, or checked.

This function is especially handy if you want to retrieve more than one of the button states. To just retrieve one state, use one of the following member functions: IsButtonEnabled, IsButtonChecked, IsButtonPressed, IsButtonHidden, or IsButtonIndeterminate. However, the GetState member function is the only way to detect the TBSTATE_WRAP button state.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetState, CToolBarCtrl::GetItemRect, CToolBarCtrl::IsButtonEnabled, CToolBarCtrl::IsButtonChecked, CToolBarCtrl::IsButtonPressed, CToolBarCtrl::IsButtonHidden, CToolBarCtrl::IsButtonIndeterminate


CToolBarCtrl::GetStyle

DWORD GetStyle( ) const;

Return Value

A DWORD containing a combination of toolbar control styles, as described in the Platform SDK.

Remarks

Call this member function to get the styles currently applied to a toolbar control.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetStyle


CToolBarCtrl::GetToolTips

CToolTipCtrl* GetToolTips( ) const;

Return Value

A pointer to the CToolTipCtrl object associated with this toolbar or NULL if the toolbar has no associated tool tip control.

Remarks

Call this function to retrieve the handle of the tool tip control, if any, associated with the toolbar control. Since the toolbar control normally creates and maintains its own tool tip control, most programs don’t need to call this function.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetToolTips, CToolBarCtrl: Handling Tool Tip Notifications, CToolTipCtrl


CToolBarCtrl::HitTest

int HitTest( LPPOINT ppt ) const;

Return Value

An integer value indicating the location of a point on a toolbar. If the value is zero or a positive value, this return value 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.

Parameters

ppt

A pointer to 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.

Remarks

This member function implements the behavior of the Win32 message TB_HITTEST, as described in the Platform SDK.


CToolBarCtrl::HideButton

BOOL HideButton( int nID, BOOL bHide = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

Command identifier of the button to hide or show.

bHide

TRUE to hide the button, FALSE to show it.

Remarks

Call this function to hide or show the specified button in a toolbar control. If you want to change more than one button state, consider calling SetState instead.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::IsButtonHidden, CToolBarCtrl::EnableButton, CToolBarCtrl::CheckButton, CToolBarCtrl::PressButton, CToolBarCtrl::Indeterminate, CToolBarCtrl::GetState, CToolBarCtrl::SetState


CToolBarCtrl::Indeterminate

BOOL Indeterminate( int nID, BOOL bIndeterminate = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

Command identifier of the button whose indeterminate state is to be set or cleared.

bIndeterminate

TRUE to set the indeterminate state for the specified button, FALSE to clear it.

Remarks

Call this function to set or clear the indeterminate state of the specified button in a toolbar control. Indeterminate buttons are displayed grayed, such as the way the bold button on the toolbar of a word processor would look when the text selected contains both bold and regular characters.

If you want to change more than one button state, consider calling SetState instead.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also Button styles in CToolBarCtrl::AddButtons, CToolBarCtrl::IsButtonIndeterminate, CToolBarCtrl::EnableButton, CToolBarCtrl::CheckButton, CToolBarCtrl::PressButton, CToolBarCtrl::HideButton, CToolBarCtrl::GetState, CToolBarCtrl::SetState


CToolBarCtrl::InsertButton

BOOL InsertButton( int nIndex, LPTBBUTTON lpButton );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nIndex

Zero-based index of a button. This function inserts the new button to the left of this button.

lpButton

Address of a TBBUTTON structure containing information about the button to insert. See CToolBarCtrl::AddButtons for a description of the TBBUTTON structure.

Remarks

Call this function to insert a button in a toolbar control.

The image and/or string whose index you provide must have previously been added to the toolbar control’s list using AddBitmap, AddString, and/or AddStrings.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::AddButtons, CToolBarCtrl::DeleteButton, CToolBarCtrl::AddBitmap, CToolBarCtrl::AddString, CToolBarCtrl::AddStrings


CToolBarCtrl::InsertMarkHitTest

BOOL InsertMarkHitTest( LPPOINT ppt, LPTBINSERTMARK ptbim ) const;

Return Value

Nonzero if successful; otherwise zero.

Parameters

ppt

A pointer to a POINT structure that contains the hit test coordinates, relative to the client area of the toolbar.

ptbim

A pointer to a TBINSERTMARK structure that receives the insertion mark information.

Remarks

This member function implements the behavior of the Win32 message TB_INSERTMARKHITTEST, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetInsertMark, CToolBarCtrl::SetInsertMark


CToolBarCtrl::IsButtonChecked

BOOL IsButtonChecked( int nID ) const;

Return Value

Nonzero if the button is checked; otherwise zero.

Parameters

nID

Command identifier of the button in the toolbar.

Remarks

Call this function to determine whether the specified button in a toolbar control is checked. Consider calling GetState if you want to retrieve more than one button state.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::CheckButton, CToolBarCtrl::GetState, CToolBarCtrl::SetState, CToolBarCtrl::IsButtonEnabled, CToolBarCtrl::IsButtonPressed, CToolBarCtrl::IsButtonHidden, CToolBarCtrl::IsButtonIndeterminate, CToolBarCtrl::IsButtonHighlighted


CToolBarCtrl::IsButtonEnabled

BOOL IsButtonEnabled( int nID ) const;

Return Value

Nonzero if the button is enabled; otherwise zero.

Parameters

nID

Command identifier of the button in the toolbar.

Remarks

Call this function to determine whether the specified button in a toolbar control is enabled. Consider calling GetState if you want to retrieve more than one button state.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::EnableButton, CToolBarCtrl::GetState, CToolBarCtrl::SetState, CToolBarCtrl::IsButtonChecked, CToolBarCtrl::IsButtonPressed, CToolBarCtrl::IsButtonHidden, CToolBarCtrl::IsButtonIndeterminate, CToolBarCtrl::IsButtonHighlighted


CToolBarCtrl::IsButtonHidden

BOOL IsButtonHidden( int nID ) const;

Return Value

Nonzero if the button is hidden; otherwise zero.

Parameters

nID

Command identifier of the button in the toolbar.

Remarks

Call this function to determine whether the specified button in a toolbar control is hidden. Consider calling GetState if you want to retrieve more than one button state.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::HideButton, CToolBarCtrl::GetState, CToolBarCtrl::SetState, CToolBarCtrl::IsButtonEnabled, CToolBarCtrl::IsButtonChecked, CToolBarCtrl::IsButtonPressed, CToolBarCtrl::IsButtonIndeterminate, CToolBarCtrl::IsButtonHighlighted


CToolBarCtrl::IsButtonHighlighted

BOOL IsButtonHighlighted( int nID ) const;

Return Value

Nonzero if the button is highlighted; otherwise 0.

Parameters

nID

The command ID for the toolbar button.

Remarks

Call this member function to check the highlight state of a toolbar button.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::IsButtonChecked, CToolBarCtrl::IsButtonIndeterminate, CToolBarCtrl::IsButtonHidden, CToolBarCtrl::IsButtonEnabled, CToolBarCtrl::IsButtonPressed; CToolBarCtrl::MarkButton


CToolBarCtrl::IsButtonIndeterminate

BOOL IsButtonIndeterminate( int nID ) const;

Return Value

Nonzero if the button is indeterminate; otherwise zero.

Parameters

nID

Command identifier of the button in the toolbar.

Remarks

Call this function to determine whether the specified button in a toolbar control is indeterminate. Indeterminate buttons are displayed grayed, such as the way the bold button on the toolbar of a word processor would look when the text selected contains both bold and regular characters.

Consider calling GetState if you want to retrieve more than one button state.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::Indeterminate, CToolBarCtrl::GetState, CToolBarCtrl::SetState, CToolBarCtrl::IsButtonEnabled, CToolBarCtrl::IsButtonChecked, CToolBarCtrl::IsButtonPressed, CToolBarCtrl::IsButtonHidden, CToolBarCtrl::IsButtonHighlighted


CToolBarCtrl::IsButtonPressed

BOOL IsButtonPressed( int nID ) const;

Return Value

Nonzero if the button is pressed, otherwise zero.

Parameters

nID

Command identifier of the button in the toolbar.

Remarks

Call this function to determine whether the specified button in a toolbar control is pressed. Consider calling GetState if you want to retrieve more than one button state.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::PressButton, CToolBarCtrl::GetState, CToolBarCtrl::SetState, CToolBarCtrl::IsButtonEnabled, CToolBarCtrl::IsButtonChecked, CToolBarCtrl::IsButtonHidden, CToolBarCtrl::IsButtonIndeterminate, CToolBarCtrl::IsButtonHighlighted


CToolBarCtrl::LoadImages

void LoadImages( int iBitmapID, HINSTANCE hinst );

Parameters

iBitmapID

ID of a bitmap that contains the images to be loaded. To specify your own bitmap resource, set this parameter to the ID of a bitmap resource and set hInst to NULL. Your bitmap resource will be added to the image list as a single image. You can add standard, system-defined bitmaps by setting hinst to HINST_COMMCTRL and setting this parameter to one of the following IDs:

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.

Remarks

This member function implements the behavior of the Win32 message TB_LOADIMAGES, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetImageList, CToolBarCtrl::GetImageList


CToolBarCtrl::MapAccelerator

BOOL MapAccelerator( TCHAR chAccel, UINT* pIDBtn );

Return Value

Nonzero if successful; otherwise zero.

Parameters

chAccel

Accelerator character to be mapped. This character is the same character that is underlined in the button's text.

pIDBtn

A pointer to a UINT that receives the command identifier of the button that corresponds to the accelerator specified in chAccel.

Remarks

This member function implements the behavior of the Win32 message TB_MAPACCELERATOR, as described in the Platform SDK.


CToolBarCtrl::MarkButton

BOOL MarkButton( int nID, BOOL fHighlight = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

The button identifier.

fHighlight

Specifies the highlight state to be set. By default, TRUE. If set to FALSE, the button is set to its default state.

Remarks

This member function implements the behavior of the Win32 message TB_MARKBUTTON, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::IsButtonHighlighted


CToolBarCtrl::MoveButton

BOOL MoveButton( UINT nOldPos, UINT nNewPos );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nOldPos

The zero-based index of the button to be moved.

nNewPos

The zero-based index of the button's destination.

Remarks

This member function implements the behavior of the Win32 message TB_MOVEBUTTON, as described in the Platform SDK.


CToolBarCtrl::PressButton

BOOL PressButton( int nID, BOOL bPress = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

Command identifier of the button to press or release.

bPress

TRUE to press the specified button; FALSE to release the specified button.

Remarks

Call this function to press or release the specified button in a toolbar control. If you want to change more than one button state, consider calling SetState instead.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::IsButtonPressed, CToolBarCtrl::EnableButton, CToolBarCtrl::CheckButton, CToolBarCtrl::HideButton, CToolBarCtrl::Indeterminate, CToolBarCtrl::GetState, CToolBarCtrl::SetState


CToolBarCtrl::RestoreState

void RestoreState( HKEY hKeyRoot, LPCTSTR lpszSubKey, LPCTSTR lpszValueName );

Parameters

hKeyRoot

Identifies a currently open key in the registry or any of the following predefined reserved handle values:

  • HKEY_CLASSES_ROOT

  • HKEY_CURRENT_USER

  • HKEY_LOCAL_MACHINE

  • HKEY_USERS

lpszSubKey

Points to a null-terminated string containing the name of the subkey with which a value is associated. This parameter can be null or a pointer to an empty string. If the parameter is NULL, the value will be added to the key identified by the hKeyRoot parameter.

lpszValueName

Points to a string containing the name of the value to retrieve. If a value with this name is not already present in the key, the function adds it to the key.

Remarks

Call this function to restore the state of the toolbar control from the location in the registry specified by the parameters.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SaveState


CToolBarCtrl::SaveState

void SaveState( HKEY hKeyRoot, LPCTSTR lpszSubKey, LPCTSTR lpszValueName );

Parameters

hKeyRoot

Identifies a currently open key in the registry or any of the following predefined reserved handle values:

  • HKEY_CLASSES_ROOT

  • HKEY_CURRENT_USER

  • HKEY_LOCAL_MACHINE

  • HKEY_USERS

lpszSubKey

Points to a null-terminated string containing the name of the subkey with which a value is associated. This parameter can be null or a pointer to an empty string. If the parameter is NULL, the value will be added to the key identified by the hKeyRoot parameter.

lpszValueName

Points to a string containing the name of the value to set. If a value with this name is not already present in the key, the function adds it to the key.

Remarks

Call this function to save the state of the toolbar control in the location in the registry specified by the parameters.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::RestoreState


CToolBarCtrl::SetAnchorHighlight

BOOL SetAnchorHighlight( BOOL fAnchor = TRUE );

Return Value

Nonzero if successful; otherwise zero.

Parameters

fAnchor

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

Remarks

This member function implements the behavior of the Win32 message TB_SETANCHORHIGHLIGHT, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetAnchorHighlight


CToolBarCtrl::SetBitmapSize

BOOL SetBitmapSize( CSize size );

Return Value

Nonzero if successful; otherwise zero.

Parameters

size

Width and height, in pixels, of the bitmapped images.

Remarks

Call this function to set the size of the actual bitmapped images to be added to a toolbar control.

This function must be called only before adding any bitmaps to the toolbar. If the application does not explicitly set the bitmap size, it defaults to 16 by 15 pixels.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetButtonSize, CToolBarCtrl::GetItemRect


CToolBarCtrl::SetButtonInfo

BOOL SetButtonInfo( int nID, TBBUTTONINFO* ptbbi );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

The button identifier.

ptbbi

A pointer to a TBBUTTONINFO structure that receives the button information.

Remarks

The member function implements the behavior of the Win32 message TB_SETBUTTONINFO, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetButtonInfo


CToolBarCtrl::SetButtonSize

BOOL SetButtonSize( CSize size );

Return Value

Nonzero if successful; otherwise zero.

Parameters

size

Width and height, in pixels, of the buttons.

Remarks

Call this function to set the size of the buttons in the toolbar control. The button size must always be at least as large as the bitmap size it encloses.

This function must be called only before adding any bitmaps to the toolbar. If the application does not explicitly set the button size, it defaults to 24 by 22 pixels.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetBitmapSize, CToolBarCtrl::GetItemRect


CToolBarCtrl::SetButtonStructSize

void SetButtonStructSize( int nSize );

Parameters

nSize

Size, in bytes, of the TBBUTTON structure.

Remarks

Call this function to specify the size of the TBBUTTON structure. If you wanted to store extra data in the TBBUTTON structure, you could either derive a new structure from TBBUTTON, adding the members you needed, or create a new structure that contains a TBBUTTON structure as its first member. You would then call this function to tell the toolbar control the size of the new structure.

See CToolBarCtrl::AddButtons for more information on the TBBUTTON structure.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::Create, CToolBarCtrl::AddButtons, CToolBarCtrl::InsertButton, CToolBarCtrl::GetButton


CToolBarCtrl::SetButtonWidth

BOOL SetButtonWidth( int cxMin, int cxMax );

Return Value

Nonzero if successful; otherwise zero.

Parameters

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.

Remarks

This member function implements the behavior of the Win32 message TB_SETBUTTONWIDTH, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::SetButtonInfo


CToolBarCtrl::SetCmdID

BOOL SetCmdID( int nIndex, UINT nID );

Return Value

Returns nonzero if successful; otherwise zero.

Parameters

nIndex

The zero-based index of the button whose command ID is to be set.

nID

The command ID to set the selected button to.

Remarks

Call this function to set the command identifier which will be sent to the owner window when the specified button is pressed.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::CommandToIndex, CToolBarCtrl::GetButton, CToolBarCtrl::AddButtons, CToolBarCtrl::InsertButton


CToolBarCtrl::SetDisabledImageList

CImageList* SetDisabledImageList( CImageList* pImageList );

Return Value

A pointer to a CImageList object that was previously used by the toolbar control to display disabled button images.

Parameters

pImageList

A pointer to a CImageList object containing the images to be used by the toolbar control to display disabled button images.

Remarks

This member function implements the behavior of the Win32 message TB_SETDISABLEDIMAGELIST, as described in the Platform SDK.

The MFC implementation of SetDisabledImageList uses a CImageList object containing the toolbar control's disabled button images, rather than a handle to an image list.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetDisabledImageList, CToolBarCtrl::SetHotImageList, CToolBarCtrl::SetImageList


CToolBarCtrl::SetDrawTextFlags

DWORD SetDrawTextFlags( DWORD dwMask, DWORD dwDTFlags );

Return Value

A DWORD containing the previous text drawing flags.

Parameters

dwMask

A combination of one or more of the DT_ flags, specified in the Win32 function DrawText, that indicates which bits in dwDTFlags will be used when drawing the text.

dwDTFlags

A combination of one or more of the DT_ flags, specified in the Win32 function DrawText, that indicate how the button text will be drawn. This value is passed to DrawText when the button text is drawn.

Remarks

This member function implements the behavior of the Win32 message TB_SETDRAWTEXTFLAGS, as described in the Platform SDK.

This member function sets the flags in the Win32 function DrawText, which draws text in the specified rectangle, formatted according to how the flags are set.


CToolBarCtrl::SetExtendedStyle

DWORD SetExtendedStyle( DWORD dwExStyle ) const;

Return Value

A DWORD that represents the previous extended styles. For a list of styles, see Toolbar Extended Styles, in the Platform SDK.

Parameters

dwExStyle

A value specifying the new extended styles. This parameter can be a combination of the toolbar extended styles.

Remarks

This member function implements the behavior of the Win32 message TB_SETEXTENDEDSTYLE, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetExtendedStyle


CToolBarCtrl::SetHotImageList

CImageList* SetHotImageList( CImageList* pImageList );

Return Value

A pointer to a CImageList object that was previously used by the toolbar control to display hot button images.

Parameters

pImageList

A pointer to a CImageList object containing the images to be used by the toolbar control to display hot button images.

Remarks

This member function implements the behavior of the Win32 message TB_SETHOTIMAGELIST, as described in the Platform SDK.

The MFC implementation of SetHotImageList uses a CImageList object containing the toolbar control's hot button images, rather than a handle to an image list.

A hot button appears highlighted when the pointer is above it.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetHotImageList, CToolBarCtrl::SetDisabledImageList, CToolBarCtrl::SetImageList


CToolBarCtrl::SetHotItem

int SetHotItem( int nHot );

Return Value

The index of the previous hot item, or -1 if there was no hot item.

Parameters

nHot

The zero-based index number of the item that will be made hot. If this value is -1, none of the items will be hot.

Remarks

This member function implements the behavior of the Win32 message TB_SETHOTITEM, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetHotItem


CToolBarCtrl::SetImageList

CImageList* SetImageList( CImageList* pImageList );

Return Value

A pointer to a CImageList object that was previously used by the toolbar control to display button images in their default state.

Parameters

pImageList

A pointer to a CImageList object containing the images to be used by the toolbar control to display button images in their default state.

Remarks

This member function implements the behavior of the Win32 message TB_SETIMAGELIST, as described in the Platform SDK.

The MFC implementation of SetImageList uses a CImageList object containing the toolbar control's button images, rather than a handle to an image list.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetImageList, CToolBarCtrl::SetDisabledImageList, CToolBarCtrl::SetHotImageList


CToolBarCtrl::SetIndent

BOOL SetIndent( int iIndent );

Return Value

Nonzero if successful; otherwise zero.

Parameters

iIndent

The value specifying the indentation, in pixels.

Remarks

Call this member function to set the indentation for the first button in a toolbar control.


CToolBarCtrl::SetInsertMark

void SetInsertMark( TBINSERTMARK* ptbim );

Parameters

ptbim

A pointer to the TBINSERTMARK structure that contains the insertion mark.

Remarks

This member function implements the behavior of the Win32 message TB_SETINSERTMARK, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetInsertMark


CToolBarCtrl::SetInsertMarkColor

COLORREF SetInsertMarkColor( COLORREF clrNew );

Return Value

A COLORREF value that contains the previous insertion mark color.

Parameters

clrNew

A COLORREF value that contains the new insertion mark color.

Remarks

This member function implements the behavior of the Win32 message TB_SETINSERTMARKCOLOR, as described in the Platform SDK.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetInsertMarkColor


CToolBarCtrl::SetMaxTextRows

BOOL SetMaxTextRows( int iMaxRows );

Return Value

Nonzero if successful; otherwise zero.

Parameters

iMaxRows

Maximum number of rows to be set.

Remarks

Call this member function to set the maximum number of text rows displayed on a toolbar button.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetMaxTextRows


CToolBarCtrl::SetOwner

void SetOwner( CWnd* pWnd );

Parameters

pWnd

Pointer to the CWnd or CWnd-derived object that will be the new owner window for the toolbar control.

Remarks

Call this function to set the owner window for the toolbar control. The owner window is the window that receives notifications from the toolbar.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::Create


CToolBarCtrl::SetRows

void SetRows( int nRows, BOOL bLarger, LPRECT lpRect );

Parameters

nRows

Requested number of rows.

bLarger

Tells whether to use more rows or fewer rows if the toolbar cannot be resized to the requested number of rows.

lpRect

Points to the CRect object or RECT structure that will receive the new bounding rectangle of the toolbar.

Remarks

Call this function to ask the toolbar control to resize itself to the requested number of rows.

If the toolbar cannot resize itself to the requested number or rows, it will resize itself to either the next larger or next smaller valid size, depending on the value of bLarger. If bLarger is TRUE, the new number of rows will be larger than the number requested. If bLarger is FALSE, the new number of rows will be smaller than the number requested.

A given number of rows is valid for the toolbar if the buttons can be arranged such that all of the rows have the same number of buttons (except perhaps the last row). For example, a toolbar that contains four buttons could not be sized to three rows because the last two rows would have to be shorter. If you attempted to size it to three rows, you would get four rows if bLarger was TRUE and two rows if bLarger was FALSE.

If there are separators in the toolbar, the rules for when a given number of rows is valid are more complicated. The layout is computed such that button groups (buttons with a separator before the first and the last button in the group) are never broken up on several rows unless the group cannot fit on one row.

If a group does not fit on one row, the next group will start on the next row even if it would fit on the row where the large group ended. The purpose of this rule is to make the separation between large groups more noticeable. The resulting vertical separators are counted as rows.

Note also that the SetRows member function will always chose the layout that results in the smallest toolbar size. Creating a toolbar with the TBSTYLE_WRAPABLE style and then resizing the control will simply apply the method outlined above given the width of the control.

This function can only be called for toolbars that were created with the TBSTYLE_WRAPABLE style.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also Toolbar styles in CToolBarCtrl::Create, CToolBarCtrl::GetRows


CToolBarCtrl::SetState

BOOL SetState( int nID, UINT nState );

Return Value

Nonzero if successful; otherwise zero.

Parameters

nID

Command identifier of the button.

nState

State flags. It can be a combination of the values listed for button states in CToolBarCtrl::AddButtons.

Remarks

Call this function to set the state for the specified button in a toolbar control.

This function is especially handy if you want to set more than one of the button states. To just set one state, use one of the following member functions: EnableButton, CheckButton, HideButton, Indeterminate, or PressButton.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetState, CToolBarCtrl::AddButtons, CToolBarCtrl::EnableButton, CToolBarCtrl::CheckButton, CToolBarCtrl::HideButton, CToolBarCtrl::Indeterminate, CToolBarCtrl::PressButton


CToolBarCtrl::SetStyle

void SetStyle( DWORD dwStyle );

Parameters

dwStyle

A DWORD containing a combination of toolbar control styles, as described in the Platform SDK.

Remarks

Call this member function to set the styles for a toolbar control.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetStyle


CToolBarCtrl::SetToolTips

void SetToolTips( CToolTipCtrl* pTip );

Parameters

pTip

Pointer to the CToolTipCtrl object.

Remarks

Call this function to associate a tool tip control with a toolbar control.

CToolBarCtrl Overview | Class Members | Hierarchy Chart

See Also CToolBarCtrl::GetToolTips, CToolBarCtrl: Handling Tool Tip Notifications, CToolTipCtrl


CToolTipCtrl

The CToolTipCtrl class encapsulates the functionality of a “tool tip control,” a small pop-up window that displays a single line of text describing 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. A tool tip 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 tool tip appears near the cursor and disappears when the user clicks a mouse button or moves the cursor off the tool.

CToolTipCtrl provides the functionality to control the initial time and duration of the tool tip, the margin widths surrounding the tool tip text, the width of the tool tip window itself, and the background and text color of the tool tip. A single tool tip control can provide information for more than one tool.

The CToolTipCtrl class provides the functionality of the Windows common tool tip control. This control (and therefore the CToolTipCtrl class) is available only to programs running under Windows 95 and Windows NT versions 3.51 and later.

For more information about enabling tool tips, see Tool Tips in Visual C++ Programmer’s Guide.

For more information on using CToolTipCtrl, see Control Topics and Using CToolTipCtrl in the Visual C++ Programmer’s Guide.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

See Also CToolbar


CToolTipCtrl Class Members

Construction

CToolTipCtrl | Constructs a CToolTipCtrl object.
Create | Creates a tool tip control and attaches it to a CToolTipCtrl object.

Attributes

GetText | Retrieves the text that a tool tip control maintains for a tool.
GetToolInfo | Retrieves the information that a tool tip control maintains about a tool.
SetToolInfo | Sets the information that a tool tip maintains for a tool.
GetToolCount | Retrieves a count of the tools maintained by a tool tip control.
GetDelayTime | Retrieves the initial, pop-up, and reshow durations currently set for a tool tip control.
SetDelayTime | Sets the initial, pop-up, and reshow durations for a tool tip control.
GetMargin | Retrieves the top, left, bottom, and right margins set for a tool tip window.
SetMargin | Sets the top, left, bottom, and right margins for a tool tip window.
GetMaxTipWidth | Retrieves the maximum width for a tool tip window.
SetMaxTipWidth | Sets the maximum width for a tool tip window.
GetTipBkColor | Retrieves the background color in a tool tip window.
SetTipBkColor | Sets the background color in a tool tip window.
GetTipTextColor | Retrieves the text color in a tool tip window.
SetTipTextColor | Sets the text color in a tool tip window.

Operations

Activate | Activates and deactivates the tool tip control.
AddTool | Registers a tool with the tool tip control.
DelTool | Removes a tool from the tool tip control.
HitTest | Tests a point to determine whether it is within the bounding rectangle of the given tool and, if so, retrieves information about the tool.
RelayEvent | Passes a mouse message to a tool tip control for processing.
SetToolRect | Sets a new bounding rectangle for a tool.
UpdateTipText | Sets the tool tip text for a tool.
Update | Forces the current tool to be redrawn.
Pop | Removes a displayed tool tip window from view.


CToolTipCtrl::Activate

void Activate( BOOL bActivate );

Parameters

bActivate

Specifies whether the tool tip control is to be activated or deactivated.

Remarks

Call this function to activate or deactivate a tool tip control. If bActivate is TRUE, the control is activated; if FALSE, it is deactivated.

When a tool tip control is active, the tool tip information appears when the cursor is on a tool that is registered with the control; when it is inactive, the tool tip information does not appear, even when the cursor is on a tool.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::UpdateTipText, CToolTipCtrl::SetDelayTime


CToolTipCtrl::AddTool

BOOL AddTool( CWnd* pWnd, UINT nIDText, LPCRECT lpRectTool = NULL, UINT nIDTool = 0 );

BOOL AddTool( CWnd* pWnd, LPCTSTR lpszText = LPSTR_TEXTCALLBACK, LPCRECT lpRectTool = NULL, UINT nIDTool = 0 );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pWnd

Pointer to the window that contains the tool.

nIDText

ID of the string resource that contains the text for the tool.

lpRectTool

Pointer to a RECT structure containing coordinates of the tool’s bounding rectangle. The coordinates are relative to the upper-left corner of the client area of the window identified by pWnd.

nIDTool

ID of the tool.

lpszText

Pointer to the text for the tool. If this parameter contains the value LPSTR_TEXTCALLBACK, TTN_NEEDTEXT notification messages go to the parent of the window that pWnd points to.

Remarks

A tool tip control can be associated with more than one tool. Call this function to register a tool with the tool tip control, so that the information stored in the tool tip is displayed when the cursor is on the tool.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::DelTool


CToolTipCtrl::Create

BOOL Create( CWnd* pParentWnd, DWORD dwStyle = 0 );

Return Value

Nonzero if the CToolTipCtrl object is successfully created; otherwise 0.

Parameters

pParentWnd

Specifies the tool tip control’s parent window, usually a CDialog. It must not be NULL.

dwStyle

Specifies the tool tip control’s style. Apply any combination of control styles needed to the control.

Remarks

You construct a CToolTipCtrl in two steps. First call the constructor to construct the CToolTipCtrl object; then call Create to create the tool tip control and attach it to the CToolTipCtrl object.

The dwStyle parameter can be any combination of Window Styles. In addition, a tool tip control has two class-specific styles: TTS_ALWAYSTIP and TTS_NOPREFIX.

Style | Meaning
TTS_ALWAYSTIP | Specifies that the tool tip will appear when the cursor is on a tool, regardless of whether the tool tip control's owner window is active or inactive. Without this style, the tool tip control appears when the tool's owner window is active, but not when it is inactive.
TTS_NOPREFIX | This style prevents the system from stripping the ampersand (&) character from a string. If a tool tip control does not have the TTS_NOPREFIX style, the system automatically strips ampersand characters, allowing an application to use the same string as both a menu item and as text in a tool tip control.

A tool tip control has the WS_POPUP and WS_EX_TOOLWINDOW window styles, regardless of whether you specify them when creating the control.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::CToolTipCtrl


CToolTipCtrl::CToolTipCtrl

CToolTipCtrl( );

Remarks

Constructs a CToolTipCtrl object. You must call Create after constructing the object.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::Create


CToolTipCtrl::DelTool

void DelTool( CWnd* pWnd, UINT nIDTool = 0 );

Parameters

pWnd

Pointer to the window that contains the tool.

nIDTool

ID of the tool.

Remarks

Call this function to remove the tool specified by pWnd and nIDTool from the collection of tools supported by a tool tip control.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::AddTool


CToolTipCtrl::GetDelayTime

int GetDelayTime( DWORD dwDuration ) const;

Return Value

The specified delay time, in milliseconds

Parameters

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 tool tip 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 tool tip window appears.

  • TTDT_RESHOW Retrieve the length of time it takes for subsequent tool tip windows to appear as the pointer moves from one tool to another.

Remarks

This member function implements the behavior of the Win32 message TTM_GETDELAYTIME, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::SetDelayTime


CToolTipCtrl::GetMargin

void GetMargin( LPRECT lprc ) const;

Parameters

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:

Member | Representation
top | Distance between top border and top of tool tip text, in pixels.
left | Distance between left border and left end of tip text, in pixels.
bottom | Distance between bottom border and bottom of tip text, in pixels.
right | Distance between right border and right end of tip text, in pixels.

Remarks

This member function implements the behavior of the Win32 message TTM_GETMARGIN, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::SetMargin


CToolTipCtrl::GetMaxTipWidth

int GetMaxTipWidth( ) const;

Return Value

The maximum width for a tool tip window.

Remarks

This member function implements the behavior of the Win32 message TTM_GETMAXTIPWIDTH, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::SetMaxTipWidth


CToolTipCtrl::GetText

void GetText( CString& str, CWnd* pWnd, UINT nIDTool = 0 ) const;

Parameters

str

Reference to a CString object that receives the tool’s text.

pWnd

Pointer to the window that contains the tool.

nIDTool

ID of the tool.

Remarks

Call this function to retrieve the text that a tool tip control maintains for a tool. The pWnd and nIDTool parameters identify the tool. If that tool has been previously registered with the tool tip control through a previous call to CToolTip::AddTool, the object referenced by the str parameter is assigned the tool’s text.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::AddTool, CToolTipCtrl::DelTool


CToolTipCtrl::GetTipBkColor

COLORREF GetTipBkColor( ) const;

Return Value

A COLORREF value that represents the background color.

Remarks

This member function implements the behavior of the Win32 message TTM_GETTIPBKCOLOR, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::SetTipBkColor


CToolTipCtrl::GetTipTextColor

COLORREF GetTipTextColor( ) const;

Return Value

A COLORREF value that represents the text color.

Remarks

This member function implements the behavior of the Win32 message TTM_GETTIPTEXTCOLOR, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::SetTipTextColor


CToolTipCtrl::GetToolCount

int GetToolCount( ) const;

Return Value

A count of tools registered with the tool tip control.

Remarks

Call this function to retrieve a count of the tools registered with the tool tip control.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::AddTool, CToolTipCtrl::DelTool


CToolTipCtrl::GetToolInfo

BOOL GetToolInfo( CToolInfo& CToolInfo, CWnd* pWnd, UINT nIDTool = 0) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

CToolInfo Reference to a TOOLINFO object that receives the tool’s text.

pWnd

Pointer to the window that contains the tool.

nIDTool

ID of the tool.

Remarks

Call this function to retrieve the information that a tool tip control maintains about a tool. The hwnd and uId members of the TOOLINFO structure referenced by CToolInfo identify the tool. If that tool has been registered with the tool tip control through a previous call to AddTool, the TOOLINFO structure is filled with information about the tool.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::AddTool


CToolTipCtrl::HitTest

BOOL HitTest( CWnd* pWnd, CPoint pt, LPTOOLINFO lpToolInfo ) const;

Return Value

Nonzero if the point specified by the hit-test information is within the tool’s bounding rectangle; otherwise 0.

Parameters

pWnd

Pointer to the window that contains the tool.

pt

Pointer to a CPoint object containing the coordinates of the point to be tested.

lpToolInfo

Pointer to TOOLINFO structure that contains information about the tool.

Remarks

Call this function to test a point to determine whether it is within the bounding rectangle of the given tool and, if so, retrieve information about the tool.

If this function returns a nonzero value, the structure pointed to by lpToolInfo is filled with information on the tool within whose rectangle the point lies.

The TTHITTESTINFO structure is defined as follows:

typedef struct _TT_HITTESTINFO { // tthti
    HWND hwnd;   // handle of tool or window with tool
    POINT pt;    // client coordinates of point to test
    TOOLINFO ti; // receives information about the tool
} TTHITTESTINFO, FAR * LPHITTESTINFO;

hwnd

Specifies the tool’s handle.

pt

Specifies the coordinates of a point if the point is in the tool’s bounding rectangle.

ti

Information about the tool. For more information about the TOOLINFO structure, see CToolTipCtrl::GetToolInfo.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::GetToolInfo


CToolTipCtrl::Pop

void Pop( );

Remarks

Call this member function to remove a displayed tool tip window from the view.

This member function implements the behavior of the Win32 message TTM_POP, as described in the Platform SDK.


CToolTipCtrl::RelayEvent

void RelayEvent( LPMSG lpMsg );

Parameters

lpMsg

Pointer to a MSG structure that contains the message to relay.

Remarks

Call this function to pass a mouse message to a tool tip control for processing. A tool tip control processes only the following messages, which are sent to it by RelayEvent:

WM_LBUTTONDOWN | WM_MOUSEMOVE
WM_LBUTTONUP | WM_RBUTTONDOWN
WM_MBUTTONDOWN | WM_RBUTTONUP
WM_MBUTTONUP |

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CWnd::PreTranslateMessage, CWinApp::PreTranslateMessage


CToolTipCtrl::SetDelayTime

void SetDelayTime( UINT nDelay );

void SetDelayTime( DWORD dwDuration, int iTime );

Parameters

nDelay

Specifies the new delay time, in milliseconds.

dwDuration

Flag that specifies which duration value will be retrieved. See CToolTipCtrl::GetDelayTime for a description of the valid values.

iTime

The specified delay time, in milliseconds.

Remarks

Call this function to set the delay time for a tool tip control. The delay time is the length of time the cursor must remain on a tool before the tool tip window appears. The default delay time is 500 milliseconds.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::Activate, CToolTipCtrl::HitTest, CToolTipCtrl::GetDelayTime, TTM_SETDELAYTIME


CToolTipCtrl::SetMargin

void SetMargin( LPRECT lprc );

Parameters

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. See CToolTipCtrl::GetMargin for a description of the margin information.

Remarks

This member function implements the behavior of the Win32 message TTM_SETMARGIN, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::GetMargin


CToolTipCtrl::SetMaxTipWidth

int SetMaxTipWidth( int iWidth );

Return Value

The previous maximum tip width.

Parameters

iWidth

The maximum tool tip window width to be set.

Remarks

This member function implements the behavior of the Win32 message TTM_SETMAXTIPWIDTH, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::GetMaxTipWidth


CToolTipCtrl::SetTipBkColor

void SetTipBkColor( COLORREF clr );

Parameters

clr

The new background color.

Remarks

This member function implements the behavior of the Win32 message TTM_SETTIPBKCOLOR, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::GetTipBkColor


CToolTipCtrl::SetTipTextColor

void SetTipTextColor( COLORREF clr );

Parameters

clr

The new text color.

Remarks

This member function implements the behavior of the Win32 message TTM_SETTIPTEXTCOLOR, as described in the Platform SDK.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::GetTipTextColor


CToolTipCtrl::SetToolInfo

void SetToolInfo( LPTOOLINFO lpToolInfo );

Parameters

lpToolInfo

A pointer to a TOOLINFO structure that specifies the information to set.

Remarks

Call this function to set the information that a tool tip maintains for a tool.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::GetToolInfo


CToolTipCtrl::SetToolRect

void SetToolRect( CWnd* pWnd, UINT nIDTool, LPCRECT lpRect );

Parameters

pWnd

Pointer to the window that contains the tool.

nIDTool

ID of the tool.

lpRect

Pointer to a RECT structure specifying the new bounding rectangle.

Remarks

Call this function to set a new bounding rectangle for a tool.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::GetToolInfo


CToolTipCtrl::Update

void Update( );

Remarks

Call this member function to force the current tool to be redrawn.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::UpdateTipText


CToolTipCtrl::UpdateTipText

void UpdateTipText( LPCTSTR lpszText, CWnd* pWnd, UINT nIDTool = 0 );

void UpdateTipText( UINT nIDText, CWnd* pWnd, UINT nIDTool = 0 );

Parameters

lpszText

Pointer to the text for the tool.

pWnd

Pointer to the window that contains the tool.

nIDTool

ID of the tool.

nIDText

ID of the string resource that contains the text for the tool.

Remarks

Call this function to update the tool tip text for this control’s tools.

CToolTipCtrl Overview | Class Members | Hierarchy Chart

See Also CToolTipCtrl::GetToolInfo


CTreeCtrl

A “tree view control” is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it. By clicking an item, the user can expand and collapse the associated list of subitems.

The CTreeCtrl class provides the functionality of the Windows common tree view control. This control (and therefore the CTreeCtrl class) is available only to programs running under Windows 95 and Windows NT versions 3.51 and later.

For more information on using CTreeCtrl, see Control Topics, Using CTreeCtrl in the Visual C++ Programmer’s Guide,and Tree View Control Reference in the Platform SDK.

#include <afxcmn.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample CMNCTRL1 | MFC Sample FIRE | MFC Sample FTPTREE

See Also CImageList


CTreeCtrl Class Members

Construction
Attributes
Operations

Construction

CTreeCtrl | Constructs a CTreeCtrl object.
Create | Creates a tree view control and attaches it to a CTreeCtrl object.

Attributes

GetCount | Retrieves the number of tree items associated with a tree view control.
GetIndent | Retrieves the offset (in pixels) of a tree view item from its parent.
SetIndent | Sets the offset (in pixels) of a tree view item from its parent.
GetImageList | Retrieves the handle of the image list associated with a tree view control.
SetImageList | Sets the handle of the image list associated with a tree view control.
GetNextItem | Retrieves the next tree view item that matches a specified relationship.
ItemHasChildren | Returns nonzero if the specified item has child items.
GetChildItem | Retrieves the child of a specified tree view item.
GetNextSiblingItem | Retrieves the next sibling of the specified tree view item.
GetPrevSiblingItem | Retrieves the previous sibling of the specified tree view item.
GetParentItem | Retrieves the parent of the specified tree view item.
GetFirstVisibleItem | Retrieves the first visible item of the specified tree view item.
GetNextVisibleItem | Retrieves the next visible item of the specified tree view item.
GetPrevVisibleItem | Retrieves the previous visible item of the specified tree view item.
GetSelectedItem | Retrieves the currently selected tree view item.
GetDropHilightItem | Retrieves the target of a drag-and-drop operation.
GetRootItem | Retrieves the root of the specified tree view item.
GetItem | Retrieves the attributes of a specified tree view item.
SetItem | Sets the attributes of a specified tree view item.
GetItemState | Returns the state of an item.
SetItemState | Sets the state of an item.
GetItemImage | Retrieves the images associated with an item.
SetItemImage | Associates images with an item.
GetItemText | Returns the text of an item.
SetItemText | Sets the text of an item.
GetItemData | Returns the 32-bit application-specific value associated with an item.
SetItemData | Sets the 32-bit application-specific value associated with an item.
GetItemRect | Retrieves the bounding rectangle of a tree view item.
GetEditControl | Retrieves the handle of the edit control used to edit the specified tree view item.
GetVisibleCount | Retrieves the number of visible tree items associated with a tree view control.
GetToolTips | Retrieves the handle to the child ToolTip control used by a tree view control.
SetToolTips | Sets a tree view control's child ToolTip control.
GetBkColor | Retrieves the current background color of the control.
SetBkColor | Sets the background color of the control.
GetItemHeight | Retrieves the current height of the tree view items.
SetItemHeight | Sets the height of the tree view items.
GetTextColor | Retrieves the current text color of the control.
SetTextColor | Sets the text color of the control.
SetInsertMark | Sets the insertion mark in a tree view control.
GetCheck | Retrieves the check state of a tree control item.
SetCheck | Sets the check state of a tree control item.
GetInsertMarkColor | Retrieves the color used to draw the insertion mark for the tree view.
SetInsertMarkColor | Sets the color used to draw the insertion mark for the tree view.

Operations

InsertItem | Inserts a new item in a tree view control.
DeleteItem | Deletes a new item in a tree view control.
DeleteAllItems | Deletes all items in a tree view control.
Expand | Expands, or collapses, the child items of the specified tree view item.
Select | Selects, scrolls into view, or redraws a specified tree view item.
SelectItem | Selects a specified tree view item.
SelectDropTarget | Redraws the tree item as the target of a drag-and-drop operation.
SelectSetFirstVisible | Selects a specified tree view item as the first visible item.
EditLabel | Edits a specified tree view item in-place.
HitTest | Returns the current position of the cursor related to the CTreeCtrl object.
CreateDragImage | Creates a dragging bitmap for the specified tree view item.
SortChildren | Sorts the children of a given parent item.
EnsureVisible | Ensures that a tree view item is visible in its tree view control.
SortChildrenCB | Sorts the children of a given parent item using an application-defined sort function.


CTreeCtrl::Create

BOOL Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );

Return Value

Nonzero if initialization was successful; otherwise 0.

Parameters

dwStyle

Specifies the tree view control’s style. Apply any combination of tree view control styles to the control.

rect

Specifies the tree view control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the tree view control’s parent window, usually a CDialog. It must not be NULL.

nID

Specifies the tree view control’s ID.

Remarks

If you specify the tree control in a dialog box template, or if you are using CTreeView, your tree control is created automatically when the dialog box or view is created. If you want to create the tree control as a child window of some other window, use the Create member function. If you create the tree control using Create, you must pass it WS_VISIBLE, in addition to other tree view styles.

You construct a CTreeCtrl in two steps. First call the constructor, then call Create, which creates the tree view control and attaches it to the CTreeCtrl object.

The following styles can be applied to a tree view control:

  • TVS_HASLINES The tree view control has lines linking child items to their corresponding parent items.

  • TVS_LINESATROOT The tree view control has lines linking child items to the root of the hierarchy.

  • TVS_HASBUTTONS The tree view control adds a button to the left of each parent item.

  • TVS_EDITLABELS The tree view control allows the user to edit the labels of tree view items.

  • TVS_SHOWSELALWAYS Causes a selected item to remain selected when the tree-view control loses focus.

  • TVS_DISABLEDRAGDROP The tree-view control is prevented from sending TVN_BEGINDRAG notification messages.

  • TVS_NOTOOLTIPS The tree view control uses no tooltips.

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

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::CTreeCtrl, Tree View Control Window Styles in the Platform SDK


CTreeCtrl::CreateDragImage

CImageList* CreateDragImage( HTREEITEM hItem );

Return Value

Pointer to the image list to which the dragging bitmap was added, if successful; otherwise NULL.

Parameters

hItem

Handle of the tree item to be dragged.

Remarks

Call this function to create a dragging bitmap for the given item in a tree view control, create an image list for the bitmap, and add the bitmap to the image list. An application uses the image-list functions to display the image when the item is being dragged.

The CImageList object is permanent, and you must delete it when finished. For example:

CImageList* pImageList = MyTreeCtrl.CreateDragImage(nItem, &point);
   ...
   ...
   delete pImageList;

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SelectDropTarget, CTreeCtrl::GetDropHilightItem, CTreeCtrl::SetImageList


CTreeCtrl::CTreeCtrl

CTreeCtrl( );

Remarks

Constructs a CTreeCtrl object.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::Create


CTreeCtrl::DeleteAllItems

BOOL DeleteAllItems( );

Return Value

Nonzero if successful; otherwise 0.

Remarks

Call this function to delete all items from the tree view control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::DeleteItem, CTreeCtrl::InsertItem


CTreeCtrl::DeleteItem

BOOL DeleteItem( HTREEITEM hItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of the tree item to be deleted. If hitem has the TVI_ROOT value, all items are deleted from the tree view control.

Remarks

Call this function to delete an item from the tree view control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::DeleteAllItems, CTreeCtrl::InsertItem


CTreeCtrl::EditLabel

CEdit* EditLabel( HTREEITEM hItem );

Return Value

If successful, a pointer to the CEdit object that is used to edit the item text; otherwise NULL.

Parameters

hItem

Handle of the tree item to be edited.

Remarks

Call this function to begin in-place editing of the specified item’s text. The editing is accomplished by replacing the text of the item with a single-line edit control containing the text.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetEditControl


CTreeCtrl::EnsureVisible

BOOL EnsureVisible( HTREEITEM hItem );

Return Value

Returns TRUE if the system scrolled the items in the tree-view control to ensure that the specified item is visible. Otherwise, the return value is FALSE.

Parameters

hItem

Handle of the tree item being made visible.

Remarks

Call this function to ensure that a tree view item is visible. If necessary, the function expands the parent item or scrolls the tree view control so that the item is visible.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetFirstVisibleItem, CTreeCtrl::GetVisibleCount


CTreeCtrl::Expand

BOOL Expand( HTREEITEM hItem, UINT nCode );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of the tree item being expanded.

nCode

A flag indicating the type of action to be taken. This flag can have one of the following values:

  • TVE_COLLAPSE Collapses the list.

  • TVE_COLLAPSERESET Collapses the list and removes the child items.

  • TVE_EXPAND Expands the list.

  • TVE_TOGGLE Collapses the list if it is currently expanded or expands it if it is currently collapsed.

Remarks

Call this function to expand or collapse the list of child items, if any, associated with the given parent item.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::EnsureVisible


CTreeCtrl::GetBkColor

COLORREF GetBkColor( ) const;

Return Value

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.

Remarks

This member function implements the behavior of the Win32 message TVM_GETBKCOLOR, as described in the Platform SDK.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetBkColor


CTreeCtrl::GetCheck

BOOL GetCheck( HTREEITEM hItem ) const;

Return Value

Nonzero if the tree control item is checked; otherwise 0.

Parameters

hItem

The HTREEITEM about which to receive the state information.

Remarks

Call this member function to retrieve an item's check state.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetCheck


CTreeCtrl::GetChildItem

HTREEITEM GetChildItem( HTREEITEM hItem );

Return Value

The handle of the child item if successful; otherwise NULL.

Parameters

hItem

Handle of a tree item.

Remarks

Call this function to retrieve the tree view item that is the child of the item specified by hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItem, CTreeCtrl::GetParentItem, CTreeCtrl::SortChildren


CTreeCtrl::GetCount

UINT GetCount( );

Return Value

The number of items in the tree view control; otherwise – 1.

Remarks

Call this function to retrieve a count of the items in a tree view control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetVisibleCount


CTreeCtrl::GetDropHilightItem

HTREEITEM GetDropHilightItem( );

Return Value

The handle of the item dropped if successful; otherwise NULL.

Remarks

Call this function to retrieve the item that is the target of a drag-and-drop operation.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SelectDropTarget


CTreeCtrl::GetEditControl

CEdit* GetEditControl( );

Return Value

A pointer to the edit control used to edit the item text, if successful; otherwise NULL.

Remarks

Call this function to retrieve the handle of the edit control being used to edit a tree view item’s text.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::EditLabel


CTreeCtrl::GetFirstVisibleItem

HTREEITEM GetFirstVisibleItem( );

Return Value

The handle of the first visible item; otherwise NULL.

Remarks

Call this function to retrieve the first visible item of the tree view control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetNextVisibleItem, CTreeCtrl::GetPrevVisibleItem, CTreeCtrl::EnsureVisible, CTreeCtrl::GetVisibleCount


CTreeCtrl::GetImageList

CImageList* GetImageList( UINT nImage );

Return Value

Pointer to the control’s image list if successful; otherwise NULL.

Parameters

nImage

Type of image list to retrieve. The image list can be one of the following values:

  • TVSIL_NORMAL Retrieves the normal image list, which contains the selected and nonselected images for the tree view item.

  • TVSIL_STATE Retrieves the state image list, which contains the images for tree view items that are in a user-defined state.

Remarks

Call this function to retrieve the handle of the normal or state image list associated with the tree view control. Each item in a tree view control can have a pair of bitmapped images associated with it. One image is displayed when the item is selected, and the other is displayed when the item is not selected. For example, an item might display an open folder when it is selected and a closed folder when it is not selected.

For more information on image lists, see the CImageList class.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CImageList, CTreeCtrl::SetImageList


CTreeCtrl::GetIndent

UINT GetIndent( );

Return Value

The amount of indentation measured in pixels.

Remarks

Call this function to retrieve the amount, in pixels, that child items are indented relative to their parent items.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetIndent


CTreeCtrl::GetInsertMarkColor

COLORREF GetInsertMarkColor( ) const;

Return Value

A COLORREF value that contains the current insertion mark color.

Remarks

This member function implements the behavior of the Win32 message TVM_GETINSERTMARKCOLOR, as described in the Platform SDK.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetInsertMarkColor


CTreeCtrl::GetItem

BOOL GetItem( TVITEM* pItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pItem

A pointer to a TVITEM structure, as described in the Platform SDK.

Remarks

Call this function to retrieve the attributes of the specified tree view item.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetItem, CTreeCtrl::GetChildItem, CTreeCtrl::GetNextItem, CTreeCtrl::SelectItem


CTreeCtrl::GetItemData

DWORD GetItemData( HTREEITEM hItem ) const;

Return Value

A 32-bit application-specific value associated with the item specified by hItem.

Parameters

hItem

Handle of the item whose data is to be retrieved.

Remarks

Call this function to retrieve the 32-bit application-specific value associated with the specified item.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetItemData


CTreeCtrl::GetItemHeight

SHORT GetItemHeight( ) const;

Return Value

The height of the item, in pixels.

Remarks

This member function implements the behavior of the Win32 message TVM_GETITEMHEIGHT, as described in the Platform SDK.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetItemHeight


CTreeCtrl::GetItemImage

BOOL GetItemImage( HTREEITEM hItem, int& nImage, int& nSelectedImage ) const;

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

The handle of the item whose image is to be retrieved.

nImage

An integer that receives the index of the item’s image within the tree view control’s image list.

nSelectedImage

An integer that receives the index of the item’s selected image within the tree view control’s image list.

Remarks

Each item in a tree view control can have a pair of bitmapped images associated with it. The images appear on the left side of an item’s label. One image is displayed when the item is selected, and the other is displayed when the item is not selected. For example, an item might display an open folder when it is selected and a closed folder when it is not selected.

Call this function to retrieve the index of the item’s image and its selected image within the tree view control’s image list.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetItemImage, CImageList


CTreeCtrl::GetItemRect

BOOL GetItemRect( HTREEITEM hItem, LPRECT lpRect, BOOL bTextOnly );

Return Value

Nonzero if the item is visible, with the bounding rectangle contained in lpRect. Otherwise, 0 with lpRect uninitialized.

Parameters

hItem

The handle of a tree view control item.

lpRect

Pointer to a RECT structure that receives the bounding rectangle. The coordinates are relative to the upper-left corner of the tree view control.

bTextOnly

If this parameter is nonzero, 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.

Remarks

Call this function to retrieve the bounding rectangle for hItem and determine whether it is visible or not.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetVisibleCount, CTreeCtrl::GetNextVisibleItem, CTreeCtrl::GetPrevVisibleItem, CTreeCtrl::EnsureVisible


CTreeCtrl::GetItemState

UINT GetItemState( HTREEITEM hItem, UINT nStateMask ) const;

Return Value

A UINT specifying the item’s state. For information on possible values, see CTreeCtrl::GetItem.

Parameters

hItem

Handle of the item whose state is to be retrieved.

nStateMask

Mask indicating which states are to be retrieved. For more information on possible values for nStateMask, see the discussion of the state and stateMask members of the TVITEM structure in the Platform SDK.

Remarks

Returns the state of the item specified by hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItem


CTreeCtrl::GetItemText

CString GetItemText( HTREEITEM hItem ) const;

Return Value

A CString object containing the item’s text.

Parameters

hItem

Handle of the item whose text is to be retrieved.

Remarks

Returns the text of the item specified by hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetItemText


CTreeCtrl::GetNextItem

HTREEITEM GetNextItem( HTREEITEM hItem, UINT nCode );

Return Value

The handle of the next item if successful; otherwise NULL.

Parameters

hItem

Handle of a tree item.

nCode

A flag indicating the type of relation to hItem. This flag can be one of the following values:

  • TVGN_CARET Retrieves the currently selected item.

  • TVGN_CHILD Retrieves the first child item. The hItem parameter must be NULL.

  • TVGN_DROPHILITE Retrieves the item that is the target of a drag-and-drop operation.

  • TVGN_FIRSTVISIBLE Retrieves the first visible item.

  • TVGN_NEXT Retrieves the next sibling item.

  • TVGN_NEXTVISIBLE Retrieves the next visible item that follows the specified item.

  • TVGN_PARENT Retrieves the parent of the specified item.

  • TVGN_PREVIOUS Retrieves the previous sibling item.

  • TVGN_PREVIOUSVISIBLE Retrieves the first visible item that precedes the specified item.

  • TVGN_ROOT Retrieves the first child item of the root item of which the specified item is a part.

Remarks

Call this function to retrieve the tree view item that has the specified relationship, indicated by the nCode parameter, to hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetItem, CTreeCtrl::GetChildItem, CTreeCtrl::GetItem, CTreeCtrl::SelectItem, CTreeCtrl::GetPrevSiblingItem


CTreeCtrl::GetNextSiblingItem

HTREEITEM GetNextSiblingItem( HTREEITEM hItem );

Return Value

The handle of the next sibling item; otherwise NULL.

Parameters

hItem

Handle of a tree item.

Remarks

Call this function to retrieve the next sibling of hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetPrevSiblingItem, CTreeCtrl::GetChildItem, CTreeCtrl::GetItem, CTreeCtrl::SelectItem, CTreeCtrl::GetParentItem


CTreeCtrl::GetNextVisibleItem

HTREEITEM GetNextVisibleItem( HTREEITEM hItem );

Return Value

The handle of the next visible item; otherwise NULL.

Parameters

hItem

Handle of a tree item.

Remarks

Call this function to retrieve the next visible item of hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetPrevVisibleItem, CTreeCtrl::GetFirstVisibleItem, CTreeCtrl::EnsureVisible, CTreeCtrl::GetParentItem


CTreeCtrl::GetParentItem

HTREEITEM GetParentItem( HTREEITEM hItem );

Return Value

The handle of the parent item; otherwise NULL.

Parameters

hItem

Handle of a tree item.

Remarks

Call this function to retrieve the parent of hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetChildItem, CTreeCtrl::GetRootItem, CTreeCtrl::GetItem, CTreeCtrl::GetPrevSiblingItem


CTreeCtrl::GetPrevSiblingItem

HTREEITEM GetPrevSiblingItem( HTREEITEM hItem );

Return Value

The handle of the previous sibling; otherwise NULL.

Parameters

hItem

Handle of a tree item.

Remarks

Call this function to retrieve the previous sibling of hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetNextSiblingItem, CTreeCtrl::GetParentItem, CTreeCtrl::GetChildItem


CTreeCtrl::GetPrevVisibleItem

HTREEITEM GetPrevVisibleItem( HTREEITEM hItem );

Return Value

The handle of the previous visible item; otherwise NULL.

Parameters

hItem

Handle of a tree item.

Remarks

Call this function to retrieve the previous visible item of hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetNextVisibleItem, CTreeCtrl::GetFirstVisibleItem, CTreeCtrl::EnsureVisible, CTreeCtrl::GetVisibleCount


CTreeCtrl::GetRootItem

HTREEITEM GetRootItem( );

Return Value

The handle of the root item; otherwise NULL.

Remarks

Call this function to retrieve the root item of the tree view control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItem, CTreeCtrl::GetChildItem, CTreeCtrl::GetParentItem


CTreeCtrl::GetSelectedItem

HTREEITEM GetSelectedItem( );

Return Value

The handle of the selected item; otherwise NULL.

Remarks

Call this function to retrieve the currently selected item of the tree view control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::Select, CTreeCtrl::SelectDropTarget, CTreeCtrl::GetDropHilightItem


CTreeCtrl::GetTextColor

COLORREF GetTextColor( ) const;

Return Value

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.

Remarks

This member function implements the behavior of the Win32 message TVM_GETTEXTCOLOR, as described in the Platform SDK.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetTextColor


CTreeCtrl::GetToolTips

CToolTipCtrl* GetToolTips( );

Return Value

A pointer to a CToolTipCtrl object to be used by the tree control. If the Create member function uses the style TVS_NOTOOLTIPS, no tooltips are used, and NULL is returned.

Remarks

This member function implements the behavior of the Win32 message TVM_GETTOOLTIPS, as described in the Platform SDK.

The MFC implementation of GetToolTips returns a CToolTipCtrl object, which is used by the tree control, rather than a handle to a tooltip control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SetToolTips


CTreeCtrl::GetVisibleCount

UINT GetVisibleCount( );

Return Value

The number of visible items in the tree view control; otherwise – 1.

Remarks

Call this function to retrieve a count of the visible items in a tree view control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetCount, CTreeCtrl::EnsureVisible


CTreeCtrl::HitTest

HTREEITEM HitTest( CPoint pt, UINT* pFlags );

HTREEITEM HitTest( TVHITTESTINFO* pHitTestInfo );

Return Value

The handle of the tree view item that occupies the specified point or NULL if no item occupies the point.

Parameters

pt

Client coordinates of the point to test.

pFlags

Pointer to an integer that receives information about the results of the hit test. It can be one or more of the values listed under the flags member in the Remarks section.

pHitTestInfo

Address of a TVHITTESTINFO structure that contains the position to hit test and that receives information about the results of the hit test.

Remarks

Call this function to determine the location of the specified point relative to the client area of a tree view control.

When this function is called, the pt parameter specifies the coordinates of the point to test. The function returns the handle of the item at the specified point or NULL if no item occupies the point. In addition, the pFlags parameter contains a value that indicates the location of the specified point.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItemRect


CTreeCtrl::InsertItem

HTREEITEM InsertItem( LPTVINSERTSTRUCT lpInsertStruct );

HTREEITEM InsertItem(UINT nMask, LPCTSTR lpszItem, int nImage, int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam, HTREEITEM hParent, HTREEITEM hInsertAfter );

HTREEITEM InsertItem( LPCTSTR lpszItem, HTREEITEM hParent = TVI_ROOT, HTREEITEM hInsertAfter = TVI_LAST );

HTREEITEM InsertItem( LPCTSTR lpszItem, int nImage, int nSelectedImage, HTREEITEM hParent = TVI_ROOT, HTREEITEM hInsertAfter = TVI_LAST);

Return Value

Handle of the new item if successful; otherwise NULL.

Parameters

lpInsertStruct

A pointer to a TVINSERTSTRUCT that specifies the attributes of the tree view item to be inserted.

nMask

Integer specifying which attributes to set. See the TVITEM structure in the Platform SDK.

lpszItem

Address of a string containing the item’s text.

nImage

Index of the item’s image in the tree view control’s image list.

nSelectedImage

Index of the item’s selected image in the tree view control’s image list.

nState

Specifies values for the item’s states. See Tree View Control Item States in the Platform SDK for a list of appropriate states.

nStateMask

Specifies which states are to be set. See the TVITEM structure in the Platform SDK.

lParam

A 32-bit application-specific value associated with the item.

hParent

Handle of the inserted item’s parent.

hInsertAfter

Handle of the item after which the new item is to be inserted.

Remarks

Call this function to insert a new item in a tree view control.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::DeleteItem, CTreeCtrl::HitTest, CTreeCtrl::SelectDropTarget, CTreeCtrl::GetItem, Tree View Control Reference in the Platform SDK


CTreeCtrl::ItemHasChildren

BOOL ItemHasChildren( HTREEITEM hItem );

Return Value

Nonzero if the tree item specified by hItem has child items; 0 if it does not.

Parameters

hItem

Handle of a tree item.

Remarks

Use this function to determine whether the tree item specified by hItem has child items. If so, you can then use CTreeCtrl::GetChildItem to retrieve those child items.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetChildItem


CTreeCtrl::Select

BOOL Select( HTREEITEM hItem, UINT nCode );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of a tree item.

nCode

The type of action to take. This parameter can be one of the following values:

  • TVGN_CARET Sets the selection to the given item.

  • TVGN_DROPHILITE Redraws the given item in the style used to indicate the target of a drag-and-drop operation.

  • TVGN_FIRSTVISIBLE Scrolls the tree view vertically so that the given item is the first visible item.

Remarks

Call this function to select the given tree view item, scroll the item into view, or redraw the item in the style used to indicate the target of a drag-and-drop operation.

If nCode contains the value TVGN_CARET, the parent window receives the TVN_SELCHANGING and TVN_SELCHANGED notification messages. In addition, 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.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SelectItem, CTreeCtrl::GetSelectedItem, CTreeCtrl::SelectDropTarget


CTreeCtrl::SelectDropTarget

BOOL SelectDropTarget( HTREEITEM hItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of a tree item.

Remarks

Call this function to redraw the item in the style used to indicate the target of a drag-and-drop operation.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SelectItem, CTreeCtrl::GetDropHilightItem, CTreeCtrl::CreateDragImage


CTreeCtrl::SelectItem

BOOL SelectItem( HTREEITEM hItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of a tree item.

Remarks

Call this function to select the given tree view item. If hItem is NULL, then this function selects no item.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::Select, CTreeCtrl::GetSelectedItem, CTreeCtrl::SelectDropTarget


CTreeCtrl::SelectSetFirstVisible

BOOL SelectSetFirstVisible( HTREEITEM hItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of the tree item to be set as the first visible item.

Remarks

Call this function to scroll the tree view vertically so that the given item is the first visible item. The function sends a message to the window with the TVM_SELECTITEM and TVGN_FIRSTVISIBLE message parameters.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::Select, CTreeCtrl::SelectItem, CTreeCtrl::SelectDropTarget


CTreeCtrl::SetBkColor

COLORREF SetBkColor( COLORREF clr );

Return Value

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.

Parameters

clr

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

Remarks

This member function implements the behavior of the Win32 message TVM_SETBKCOLOR, as described in the Platform SDK.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetBkColor


CTreeCtrl::SetCheck

BOOL SetCheck( HTREEITEM hItem, BOOL fCheck = TRUE );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

The HTREEITEM to receive the check state change.

fCheck

Indicates whether the tree control item is to be checked or unchecked. By default, SetCheck sets the item to be checked.

Remarks

Call this member function to set the check state for a tree control item. When the tree control item is checked (fCheck set to TRUE), the item appears with an adjacent checkmark.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetCheck


CTreeCtrl::SetImageList

CImageList* SetImageList( CImageList * pImageList, int nImageListType );

Return Value

Pointer to the previous image list, if any; otherwise NULL.

Parameters

pImageList

Pointer to the image list to assign. If pImageList is NULL, all images are removed from the tree view control.

nImageListType

Type of image list to set. The image list can be one of the following values:

  • TVSIL_NORMAL Sets the normal image list, which contains the selected and nonselected images for the tree view item.

  • TVSIL_STATE Sets the state image list, which contains the images for tree view items that are in a user-defined state.

Remarks

Call this function to set the normal or state image list for a tree view control and redraw the control using the new images.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CImageList, CTreeCtrl::GetImageList


CTreeCtrl::SetIndent

void SetIndent( UINT nIndent );

Parameters

nIndent

Width, in pixels, of the indentation. If nIndent is less than the system-defined minimum width, the new width is set to the system-defined minimum.

Remarks

Call this function to set the width of indentation for a tree view control and redraw the control to reflect the new width.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetIndent, CTreeCtrl::GetItemRect


CTreeCtrl::SetInsertMark

BOOL SetInsertMark( HTREEITEM hItem, BOOL fAfter = TRUE );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

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.

Remarks

This member function implements the behavior of the Win32 message TVM_SETINSERTMARK, as described in the Platform SDK.


CTreeCtrl::SetInsertMarkColor

COLORREF SetInsertMarkColor( COLORREF clrNew );

Return Value

A COLORREF value that contains the previous insertion mark color.

Parameters

clrNew

A COLORREF value that contains the new insertion mark color.

Remarks

This member function implements the behavior of the Win32 message TVM_SETINSERTMARKCOLOR, as described in the Platform SDK.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetInsertMarkColor


CTreeCtrl::SetItem

BOOL SetItem( TVITEM* pItem );

BOOL SetItem( HTREEITEM hItem, UINT nMask, LPCTSTR lpszItem, int nImage, int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pItem

A pointer to a TVITEM structure that contains the new item attributes, as described in the Platform SDK.

hItem

Handle of the item whose attributes are to be set.

nMask

Integer specifying which attributes to set.

lpszItem

Address of a string containing the item’s text.

nImage

Index of the item’s image in the tree view control’s image list.

nSelectedImage

Index of the item’s selected image in the tree view control’s image list.

nState

Specifies values for the item’s states.

nStateMask

Specifies which states are to be set.

lParam

A 32-bit application-specific value associated with the item.

Remarks

Call this function to set the attributes of the specified tree view item.

In the TVITEM structure, the hItem member identifies the item, and the mask member specifies which attributes to set.

If the mask member or the nMask parameter specifies the TVIF_TEXT value, the pszText member or the lpszItem is the address of a null-terminated string and the cchTextMax member is ignored. If mask (or nMask) specifies the TVIF_STATE value, the stateMask member or the nStateMask parameter specifies which item states to change and the state member or nState parameter contains the values for those states.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItem


CTreeCtrl::SetItemData

BOOL SetItemData( HTREEITEM hItem, DWORD dwData );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of the item whose data is to be retrieved.

dwData

A 32-bit application-specific value associated with the item specified by hItem.

Remarks

Call this function to set the 32-bit application-specific value associated with the specified item.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItemData


CTreeCtrl::SetItemHeight

SHORT SetItemHeight( SHORT cyHeight );

Return Value

The previous height of the items, in pixels.

Parameters

cyHeight

Specifies the new height of every item in the tree view, in pixels. If this argument 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.

Remarks

This member function implements the behavior of the Win32 message TVM_SETITEMHEIGHT, as described in the Platform SDK.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItemHeight


CTreeCtrl::SetItemImage

BOOL SetItemImage( HTREEITEM hItem, int nImage, int nSelectedImage );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of the item whose image is to be set.

nImage

Index of the item’s image in the tree view control’s image list.

nSelectedImage

Index of the item’s selected image in the tree view control’s image list.

Remarks

Each item in a tree view control can have a pair of bitmapped images associated with it. The images appear on the left side of an item’s label. One image is displayed when the item is selected, and the other is displayed when the item is not selected. For example, an item might display an open folder when it is selected and a closed folder when it is not selected.

Call this function to set the index of the item’s image and its selected image within the tree view control’s image list.

For more information on images, see CImageList.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItemImage, CImageList


CTreeCtrl::SetItemState

BOOL SetItemState( HTREEITEM hItem, UINT nState, UINT nStateMask );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of the item whose state is to be set.

nState

Specifies new states for the item.

nStateMask

Specifies which states are to be changed.

Remarks

Sets the state of the item specified by hItem. For information on states, see CTreeCtrl::GetItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItem, CTreeCtrl::GetItemState


CTreeCtrl::SetItemText

BOOL SetItemText( HTREEITEM hItem, LPCTSTR lpszItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of the item whose text is to be set.

lpszItem

Address of a string containing the new text for the item

Remarks

Sets the text of the item specified by hItem.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetItemText


CTreeCtrl::SetTextColor

COLORREF SetTextColor( COLORREF clr );

Return Value

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.

Parameters

clr

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

Remarks

This member function implements the behavior of the Win32 message TVM_SETTEXTCOLOR, as described in the Platform SDK.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetTextColor


CTreeCtrl::SetToolTips

void SetToolTips( CToolTipCtrl* pWndTip );

CToolTipCtrl* SetToolTips( CToolTipCtrl* pWndTip );

Return Value

A pointer to a CToolTipCtrl object containing the tooltip previously used by the control, or NULL if no tooltips were used previously.

Parameters

pWndTip

A pointer to a CToolTipCtrl object that the tree control will use.

Remarks

This member function implements the behavior of the Win32 message TVM_SETTOOLTIPS, as described in the Platform SDK.

To use tooltips, indicate the TVS_NOTOOLTIPS style when you create the CTreeCtrl object.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::GetToolTips, CTreeCtrl::Create


CTreeCtrl::SortChildren

BOOL SortChildren( HTREEITEM hItem );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hItem

Handle of the parent item whose child items are to be sorted. If hItem is NULL, sorting will proceed from the root of the tree.

Remarks

Call this function to sort the child items of the given parent item in a tree view control. SortChildren will not recurse through the tree; only the immediate children of hItem will be sorted.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SortChildrenCB


CTreeCtrl::SortChildrenCB

BOOL SortChildrenCB( LPTVSORTCB pSort );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pSort

Pointer to a TVSORTCB structure.

Remarks

Call this function to sort tree view items using an application-defined callback function that compares the items.

The structure's comparison function, lpfnCompare, 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 the TV_SORTCB structure.

CTreeCtrl Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl::SortChildren


CTreeView

The CTreeView class simplifies use of the tree control and of CTreeCtrl, the class that encapsulates tree-control functionality, with MFC’s document-view architecture. For more information on this architecture, see the overview for the CView class and the cross-references cited there.

#include <afxcview.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample DBFETCH

See Also CView, CCtrlView, CTreeCtrl


CTreeView Class Members

Construction

CTreeView Constructs a CTreeView object.

Attributes

GetTreeCtrl Returns the tree control associated with the view.


CTreeView::CTreeView

CTreeView( );

Remarks

Constructs a CTreeView object.

CTreeView Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl


CTreeView::GetTreeCtrl

CTreeCtrl& GetTreeCtrl( ) const;

Remarks

Returns a reference to the tree control associated with the view.

CTreeView Overview | Class Members | Hierarchy Chart

See Also CTreeCtrl


CTypedPtrArray

template< class BASE_CLASS, class TYPE >
class CTypedPtrArray : public BASE_CLASS

Parameters

BASE_CLASS

Base class of the typed pointer array class; must be an array class (CObArray or CPtrArray).

TYPE

Type of the elements stored in the base-class array.

Remarks

The CTypedPtrArray class provides a type-safe “wrapper” for objects of class CPtrArray or CObArray. When you use CTypedPtrArray rather than CPtrArray or CObArray, the C++ type-checking facility helps eliminate errors caused by mismatched pointer types.

In addition, the CTypedPtrArray wrapper performs much of the casting that would be required if you used CObArray or CPtrArray.

Because all CTypedPtrArray functions are inline, use of this template does not significantly affect the size or speed of your code.

For more information on using CTypedPtrArray, see the articles Collections and Collections: Template-Based Classes in Visual C++ Programmer’s Guide.

#include <afxtempl.h>

Class Members | Hierarchy Chart

Sample MFC Sample COLLECT

See Also CPtrArray, CObArray


CTypedPtrArray Class Members

Element Access

GetAt | Returns the value at a given index.
ElementAt | Returns a temporary reference to the element pointer within the array.
SetAt | Sets the value for a given index; array not allowed to grow.
SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds a new element to the end of an array. Grows the array if necessary
Append | Adds the contents of one array to the end of another. Grows the array if necessary
Copy | Copies another array to the array; grows the array if necessary.
InsertAt | Inserts an element (or all the elements in another array) at a specified index.

Operators

operator[] Sets or gets the element at the specified index.


CTypedPtrArray::Add

int Add( TYPE newElement );

Return Value

The index of the added element.

Parameters

TYPE

Template parameter specifying the type of element to be added to the array.

newElement

The element to be added to this array.

Remarks

This member function calls BASE_CLASS::Add. For more detailed remarks, see CObArray::Add.


CTypedPtrArray::Append

int Append( const CTypedPtrArray<BASE_CLASS, TYPE>& src );

Return Value

The index of the first appended element.

Parameters

BASE_CLASS

Base class of the typed pointer array class; must be an array class (CObArray or CPtrArray).

TYPE

Type of the elements stored in the base-class array.

src

Source of the elements to be appended to an array.

Remarks

This member function calls BASE_CLASS::Append. For more detailed remarks, see CObArray::Append.


CTypedPtrArray::Copy

void Copy( const CTypedPtrArray<BASE_CLASS, TYPE>& src );

Parameters

BASE_CLASS

Base class of the typed pointer array class; must be an array class (CObArray or CPtrArray).

TYPE

Type of the elements stored in the base-class array.

src

Source of the elements to be copied to an array.

Remarks

This member function calls BASE_CLASS::Copy. For more detailed remarks, see CObArray::Copy.


CTypedPtrArray::ElementAt

TYPE& ElementAt( int nIndex );

Return Value

A temporary reference to the element at the location specified by nIndex. This element is of the type specified by the template parameter TYPE.

Parameters

TYPE

Template parameter specifying the type of elements stored in this array.

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by BASE_CLASS::GetUpperBound.

Remarks

This inline function calls BASE_CLASS::ElementAt. For more detailed remarks, see CObArray::ElementAt.

CTypedPtrArray Overview | Class Members | Hierarchy Chart

See Also CObArray::ElementAt, CObArray::GetUpperBound


CTypedPtrArray::GetAt

TYPE GetAt( int nIndex ) const;

Return Value

A copy of the element at the location specified by nIndex. This element is of the type specified by the template parameter TYPE.

Parameters

TYPE

Template parameter specifying the type of elements stored in the array.

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by BASE_CLASS::GetUpperBound.

Remarks

This inline function calls BASE_CLASS::GetAt. For more detailed remarks, see CObArray::GetAt

CTypedPtrArray Overview | Class Members | Hierarchy Chart

See Also CObArray::GetAt, CObArray::GetUpperBound


CTypedPtrArray::InsertAt

void InsertAt( int nIndex, TYPE newElement, int nCount = 1 );

void InsertAt( int nStartIndex, CTypedPtrArray<BASE_CLASS, TYPE>* pNewArray );

Parameters

nIndex

An integer index that may be greater than the value returned by CObArray::GetUpperBound.

TYPE

Type of the elements stored in the base-class array.

newElement

The object pointer to be placed in this array. A newElement of value NULL is allowed.

nCount

The number of times this element should be inserted (defaults to 1).

nStartIndex

An integer index that may be greater than the value returned by CObArray::GetUpperBound.

BASE_CLASS

Base class of the typed pointer array class; must be an array class (CObArray or CPtrArray).

pNewArray

Another array that contains elements to be added to this array.

Remarks

This member function calls BASE_CLASS::InsertAt. For more detailed remarks, see CObArray::InsertAt.


CTypedPtrArray::SetAt

void SetAt( int nIndex, TYPE ptr );

Parameters

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by CObArray::GetUpperBound.

TYPE

Type of the elements stored in the base-class array.

ptr

A pointer to the element to be inserted in the array at the nIndex. A NULL value is allowed.

Remarks

This member function calls BASE_CLASS::SetAt. For more detailed remarks, see CObArray::SetAt.


CTypedPtrArray::SetAtGrow

void SetAtGrow( int nIndex, TYPE newElement );

Parameters

nIndex

An integer index that is greater than or equal to 0.

TYPE

Type of the elements stored in the base-class array.

newElement

The object pointer to be added to this array. A NULL value is allowed.

Remarks

This member function calls BASE_CLASS::SetAtGrow. For more detailed remarks, see CObArray::SetAtGrow.


CTypedPtrArray::operator [ ]

TYPE& operator[ ]( int nIndex );

TYPE operator[ ]( int nIndex ) const;

Parameters

TYPE

Template parameter specifying the type of elements stored in the array.

nIndex

An integer index that is greater than or equal to 0 and less than or equal to the value returned by BASE_CLASS::GetUpperBound.

Remarks

These inline operators call BASE_CLASS::operator [ ].

The first operator, called for arrays that are not const, can be used on either the right (r-value) or the left (l-value) of an assignment statement. The second, invoked for const arrays, can be used only on the right.

The Debug version of the library asserts if the subscript (either on the left or right side of an assignment statement) is out of bounds.

CTypedPtrArray Overview | Class Members | Hierarchy Chart

See Also CObArray::operator []


CTypedPtrList

template< class BASE_CLASS, class TYPE >
class CTypedPtrList : public BASE_CLASS

Parameters

BASE_CLASS

Base class of the typed pointer list class; must be a pointer list class (CObList or CPtrList).

TYPE

Type of the elements stored in the base-class list.

Remarks

The CTypedPtrList class provides a type-safe “wrapper” for objects of class CPtrList. When you use CTypedPtrList rather than CObList or CPtrList, the C++ type-checking facility helps eliminate errors caused by mismatched pointer types.

In addition, the CTypedPtrList wrapper performs much of the casting that would be required if you used CObList or CPtrList.

Because all CTypedPtrList functions are inline, use of this template does not significantly affect the size or speed of your code.

Lists derived from CObList can be serialized, but those derived from CPtrList cannot.

When a CTypedPtrList object is deleted, or when its elements are removed, only the pointers are removed, not the entities they reference.

For more information on using CTypedPtrList, see the articles Collections and Collections: Template-Based Classes in Visual C++ Programmer’s Guide.

#include <afxtempl.h>

Class Members | Hierarchy Chart

Sample MFC Sample COLLECT

See Also CPtrList, CObList


CTypedPtrList Class Members

Head/Tail Access

GetHead | Returns the head element of the list (cannot be empty).
GetTail | Returns the tail element of the list (cannot be empty).

Operations

RemoveHead | Removes the element from the head of the list.
RemoveTail | Removes the element from the tail of the list.
AddHead | Adds an element (or all the elements in another list) to the head of the list (makes a new head).
AddTail | Adds an element (or all the elements in another list) to the tail of the list (makes a new tail).

Iteration

GetNext | Gets the next element for iterating.
GetPrev | Gets the previous element for iterating.

Retrieval/Modification

GetAt | Gets the element at a given position.
SetAt | Sets the element at a given position.


CTypedPtrList::AddHead

POSITION AddHead( TYPE newElement );

void AddHead( CTypedPtrList<BASE_CLASS, TYPE> *pNewList );

Return Value

The first version returns the POSITION value of the newly inserted element.

Parameters

TYPE

Type of the elements stored in the base-class list.

newElement

The object pointer to be added to this list. A NULL value is allowed.

BASE_CLASS

Base class of the typed pointer list class; must be a pointer list class (CObList or CPtrList).

pNewList

A pointer to another CTypedPtrList object. The elements in pNewList will be added to this list.

Remarks

This member function calls BASE_CLASS::AddHead. The first version adds a new element before the head of the list. The second version adds another list of elements before the head.


CTypedPtrList::AddTail

POSITION AddTail( TYPE newElement );

void AddTail( CTypedPtrList<BASE_CLASS, TYPE> *pNewList );

Return Value

The first version returns the POSITION value of the newly inserted element.

Parameters

TYPE

Type of the elements stored in the base-class list.

newElement

The object pointer to be added to this list. A NULL value is allowed.

BASE_CLASS

Base class of the typed pointer list class; must be a pointer list class (CObList or CPtrList).

pNewList

A pointer to another CTypedPtrList object. The elements in pNewList will be added to this list.

Remarks

This member function calls BASE_CLASS::AddTail. The first version adds a new element after the tail of the list. The second version adds another list of elements after the tail of the list.


CTypedPtrList::GetAt

TYPE& GetAt( POSITION position );

TYPE GetAt( POSITION position ) const;

Return Value

If the list is accessed through a pointer to a const CTypedPtrList, then GetAt returns a pointer of the type specified by the template parameter TYPE. This allows the function to be used only on the right side of an assignment statement and thus protects the list from modification.

If the list is accessed directly or through a pointer to a CTypedPtrList, then GetAt returns a reference to a pointer of the type specified by the template parameter TYPE. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Parameters

TYPE

Template parameter specifying the type of elements stored in the list.

position

A POSITION value returned by a previous GetHeadPosition or Find member function call.

Remarks

A variable of type POSITION is a key for the list. It is not the same as an index, and you cannot operate on a POSITION value yourself. GetAt retrieves the CObject pointer associated with a given position.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

This inline function calls BASE_CLASS::GetAt.

CTypedPtrList Overview | Class Members | Hierarchy Chart

See Also CObList::GetAt


CTypedPtrList::GetHead

TYPE& GetHead( );

TYPE GetHead( ) const;

Return Value

If the list is accessed through a pointer to a const CTypedPtrList, then GetHead returns a pointer of the type specified by the template parameter TYPE. This allows the function to be used only on the right side of an assignment statement and thus protects the list from modification.

If the list is accessed directly or through a pointer to a CTypedPtrList, then GetHead returns a reference to a pointer of the type specified by the template parameter TYPE. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Parameters

TYPE

Template parameter specifying the type of elements stored in the list.

Remarks

Gets the pointer that represents the head element of this list.

You must ensure that the list is not empty before calling GetHead. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

CTypedPtrList Overview | Class Members | Hierarchy Chart

See Also CPtrList::IsEmpty, CTypedPtrList::GetTail, CTypedPtrList::GetNext, CTypedPtrList::GetPrev


CTypedPtrList::GetNext

TYPE& GetNext( POSITION& rPosition );

TYPE GetNext( POSITION& rPosition ) const;

Return Value

If the list is accessed through a pointer to a const CTypedPtrList, then GetNext returns a pointer of the type specified by the template parameter TYPE. This allows the function to be used only on the right side of an assignment statement and thus protects the list from modification.

If the list is accessed directly or through a pointer to a CTypedPtrList, then GetNext returns a reference to a pointer of the type specified by the template parameter TYPE. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Parameters

TYPE

Template parameter specifying the type of elements contained in this list.

rPosition

A reference to a POSITION value returned by a previous GetNext, GetHeadPosition, or other member function call.

Remarks

Gets the list element identified by rPosition, then sets rPosition to the POSITION value of the next entry in the list. You can use GetNext in a forward iteration loop if you establish the initial position with a call to GetHeadPosition or CPtrList::Find.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

If the retrieved element is the last in the list, then the new value of rPosition is set to NULL.

It is possible to remove an element during an iteration. See the example for CObList::RemoveAt.

CTypedPtrList Overview | Class Members | Hierarchy Chart

See Also CObList::Find, CObList::GetHeadPosition, CObList::GetTailPosition, CTypedPtrList::GetPrev, CTypedPtrList::GetHead, CTypedPtrList::GetTail


CTypedPtrList::GetPrev

TYPE& GetPrev(POSITION& rPosition );

TYPE GetPrev( POSITION& rPosition ) const;

Return Value

If the list is accessed through a pointer to a const CTypedPtrList, then GetPrev returns a pointer of the type specified by the template parameter TYPE. This allows the function to be used only on the right side of an assignment statement and thus protects the list from modification.

If the list is accessed directly or through a pointer to a CTypedPtrList, then GetPrev returns a reference to a pointer of the type specified by the template parameter TYPE. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Parameters

TYPE

Template parameter specifying the type of elements contained in this list.

rPosition

A reference to a POSITION value returned by a previous GetPrev or other member function call.

Remarks

Gets the list element identified by rPosition, then sets rPosition to the POSITION value of the previous entry in the list. You can use GetPrev in a reverse iteration loop if you establish the initial position with a call to GetTailPosition or Find.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

If the retrieved element is the first in the list, then the new value of rPosition is set to NULL.

CTypedPtrList Overview | Class Members | Hierarchy Chart

See Also CPtrList::Find, CPtrList::GetTailPosition, CPtrList::GetHeadPosition, CTypedPtrList::GetNext, CTypedPtrList::GetHead, CTypedPtrList::GetTail


CTypedPtrList::GetTail

TYPE& GetTail( );

TYPE GetTail( ) const;

Return Value

If the list is accessed through a pointer to a const CTypedPtrList, then GetTail returns a pointer of the type specified by the template parameter TYPE. This allows the function to be used only on the right side of an assignment statement and thus protects the list from modification.

If the list is accessed directly or through a pointer to a CTypedPtrList, then GetTail returns a reference to a pointer of the type specified by the template parameter TYPE. This allows the function to be used on either side of an assignment statement and thus allows the list entries to be modified.

Parameters

TYPE

Template parameter specifying the type of elements stored in the list.

Remarks

Gets the pointer that represents the head element of this list.

You must ensure that the list is not empty before calling GetTail. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

CTypedPtrList Overview | Class Members | Hierarchy Chart

See Also CPtrList::IsEmpty, CPtrList::Find, CPtrList::GetTailPosition, CPtrList::GetHeadPosition, CTypedPtrList::GetPrev, CTypedPtrList::GetNext, CTypedPtrList::GetHead


CTypedPtrList::RemoveHead

TYPE RemoveHead( );

Return Value

The pointer previously at the head of the list. This pointer is of the type specified by the template parameter TYPE.

Parameters

TYPE

Template parameter specifying the type of elements stored in the list.

Remarks

Removes the element from the head of the list and returns it.

You must ensure that the list is not empty before calling RemoveHead. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

CTypedPtrList Overview | Class Members | Hierarchy Chart

See Also CTypedPtrList::RemoveTail, CPtrList::IsEmpty, CPtrList::GetHead, CPtrList::AddHead


CTypedPtrList::RemoveTail

TYPE RemoveTail( );

Return Value

The pointer previously at the tail of the list. This pointer is of the type specified by the template parameter TYPE.

Parameters

TYPE

Template parameter specifying the type of elements stored in the list.

Remarks

Removes the element from the tail of the list and returns it.

You must ensure that the list is not empty before calling RemoveTail. If the list is empty, then the Debug version of the Microsoft Foundation Class Library asserts. Use IsEmpty to verify that the list contains elements.

CTypedPtrList Overview | Class Members | Hierarchy Chart

See Also CTypedPtrList::RemoveHead, CPtrList::IsEmpty, CPtrList::GetTail, CPtrList::AddTail


CTypedPtrList::SetAt

void SetAt( POSITION pos, TYPE newElement );

Parameters

pos

The POSITION of the element to be set.

TYPE

Type of the elements stored in the base-class list.

newElement

The object pointer to be written to the list.

Remarks

This member function calls BASE_CLASS::SetAt.

A variable of type POSITION is a key for the list. It is not the same as an index, and you cannot operate on a POSITION value yourself. SetAt writes the object pointer to the specified position in the list.

You must ensure that your POSITION value represents a valid position in the list. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

For more detailed remarks, see CObList::SetAt.


CTypedPtrMap

template< class BASE_CLASS, class KEY, class VALUE >
class CTypedPtrMap : public BASE_CLASS

Parameters

BASE_CLASS

Base class of the typed pointer map class; must be a pointer map class (CMapPtrToPtr, CMapPtrToWord, CMapWordToPtr, or CMapStringToPtr).

KEY

Class of the object used as the key to the map.

VALUE

Class of the object stored in the map.

Remarks

The CTypedPtrMap class provides a type-safe “wrapper” for objects of the pointer-map classes CMapPtrToPtr, CMapPtrToWord, CMapWordToPtr, and CMapStringToPtr. When you use CTypedPtrMap, the C++ type-checking facility helps eliminate errors caused by mismatched pointer types.

Because all CTypedPtrMap functions are inline, use of this template does not significantly affect the size or speed of your code.

For more information on using CTypedPtrMap, see the articles Collections and Collections: Template-Based Classes in Visual C++ Programmer’s Guide.

#include <afxtempl.h>

Class Members | Hierarchy Chart

Sample MFC Sample COLLECT

See Also CMapPtrToPtr, CMapPtrToWord, CMapWordToPtr, CMapStringToPtr


CTypedPtrMap Class Members

Element Access

Lookup | Returns a KEY based on a VALUE.
GetNextAssoc | Gets the next element for iterating.
RemoveKey | Removes an element specified by a key.
SetAt | Inserts an element into the map; replaces an existing element if a matching key is found.

Operators

operator[] Inserts an element into the map.


CTypedPtrMap::GetNextAssoc

void GetNextAssoc( POSITION& rPosition, KEY& rKey, VALUE& rValue ) const;

Parameters

rPosition

Specifies a reference to a POSITION value returned by a previous GetNextAssoc or BASE_CLASS::GetStartPosition call.

KEY

Template parameter specifying the type of the map’s keys.

rKey

Specifies the returned key of the retrieved element.

VALUE

Template parameter specifying the type of the map’s values.

rValue

Specifies the returned value of the retrieved element.

Remarks

Retrieves the map element at rNextPosition, then updates rNextPosition to refer to the next element in the map. This function is most useful for iterating through all the elements in the map. Note that the position sequence is not necessarily the same as the key value sequence.

If the retrieved element is the last in the map, then the new value of rNextPosition is set to NULL.

This inline function calls BASE_CLASS::GetNextAssoc.

CTypedPtrMap Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::GetNextAssoc, CMapStringToOb::GetStartPosition


CTypedPtrMap::Lookup

BOOL Lookup( BASE_CLASS::BASE_ARG_KEY key, VALUE& rValue ) const;

Return Value

Nonzero if the element was found; otherwise 0.

Parameters

BASE_CLASS

Template parameter specifying the base class of this map’s class.

key

The key of the element to be looked up.

VALUE

Template parameter specifying the type of values stored in this map.

rValue

Specifies the returned value of the retrieved element.

Remarks

Lookup uses a hashing algorithm to quickly find the map element with a key that matches exactly.

This inline function calls BASE_CLASS::Lookup.

CTypedPtrMap Overview | Class Members | Hierarchy Chart

See Also CMapStringToOb::Lookup


CTypedPtrMap::RemoveKey

BOOL RemoveKey( KEY key );

Return Value

Nonzero if the entry was found and successfully removed; otherwise 0.

Parameters

KEY

Template parameter specifying the type of the map's keys.

key

Key for the element to be removed.

Remarks

This member function calls BASE_CLASS::RemoveKey. For more detailed remarks, see CMapStringToOb::RemoveKey.


CTypedPtrMap::SetAt

void SetAt( KEY key, VALUE newValue );

Parameters

KEY

Template parameter specifying the type of the map's keys.

key

Specifies the key value of the newValue.

newValue

Specifies the object pointer that is the value of the new element.

Remarks

This member function calls BASE_CLASS::SetAt. For more detailed remarks, see CMapStringToOb::SetAt.


CTypedPtrMap::operator [ ]

VALUE& operator [ ]( BASE_CLASS::BASE_ARG_KEY key );

Parameters

VALUE

Template parameter specifying the type of values stored in this map.

BASE_CLASS

Template parameter specifying the base class of this map’s class.

key

The key of the element to be looked up or created in the map.

Remarks

This operator can be used only on the left side of an assignment statement (an l-value). If there is no map element with the specified key, then a new element is created. There is no “right side” (r-value) equivalent to this operator because there is a possibility that a key may not be found in the map. Use the Lookup member function for element retrieval.

CTypedPtrMap Overview | Class Members | Hierarchy Chart

See Also CTypedPtrMap::Lookup


CUIntArray

The CUIntArray class supports arrays of unsigned integers. An unsigned integer, or UINT, differs from words and doublewords in that the physical size of a UINT can change depending on the target operating environment. Under Windows version 3.1, a UINT is the same size as a WORD. Under Windows NT and Windows 95, a UINT is the same size as a doubleword.

The member functions of CUIntArray are similar to the member functions of class CObArray. Because of this similarity, you can use the CObArray reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a UINT.

CObject* CObArray::GetAt( int <nIndex> ) const;

for example, translates to

UINT CUIntArray::GetAt( int <nIndex> ) const;

CUIntArray incorporates the IMPLEMENT_DYNAMIC macro to support run-time type access and dumping to a CDumpContext object. If you need a dump of individual unsigned integer elements, you must set the depth of the dump context to 1 or greater. Unsigned integer arrays cannot be serialized.

Note Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

For more information on using CUIntArray, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>


CUIntArray Class Members

Construction

CUIntArray Constructs an empty array for unsigned integers.

Bounds

GetSize | Gets the number of elements in this array.
GetUpperBound | Returns the largest valid index.
SetSize | Sets the number of elements to be contained in this array.

Operations

FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.

Element Access

GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; the array is not allowed to grow.
ElementAt | Returns a temporary reference to the element pointer within the array.
GetData | Allows access to elements in the array. Can be NULL.

Growing the Array

SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds an element to the end of the array; grows the array if necessary.
Append | Appends another array to the array; grows the array if necessary.
Copy | Copies another array to the array; grows the array if necessary.

Insertion/Removal

InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.

Operators

operator [ ] Sets or gets the element at the specified index.


CUserException

A CUserException is thrown to stop an end-user operation. Use CUserException when you want to use the throw/catch exception mechanism for application-specific exceptions. “User” in the class name can be interpreted as “my user did something exceptional that I need to handle.”

A CUserException is usually thrown after calling the global function AfxMessageBox to notify the user that an operation has failed. When you write an exception handler, handle the exception specially since the user usually has already been notified of the failure. The framework throws this exception in some cases. To throw a CUserException yourself, alert the user and then call the global function AfxThrowUserException.

In the example below, a function containing operations that may fail alerts the user and throws a CUserException. The calling function catches the exception and handles it specially:

void DoSomeOperation( )
{
    // Processing
    // If something goes wrong...
    AfxMessageBox( "The x operation failed" );
    AfxThrowUserException( );
}

BOOL TrySomething( )
{
    TRY
    {
        // Could throw a CUserException or other exception.
        DoSomeOperation( );
    }
    CATCH( CUserException, e )
    {
        return FALSE;    // User already notified.
    }
    AND_CATCH( CException, e )
    {
        // For other exception types, notify user here.
        AfxMessageBox( "Some operation failed" );
        return FALSE;
    }
    END_CATCH
    return TRUE;   // No exception thrown.
}

For more information on using CUserException, see the article Exceptions in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Base Class Members | Hierarchy Chart

See Also CException, AfxMessageBox, AfxThrowUserException


CView

The CView class provides the basic functionality for user-defined view classes. A view is attached to a document and acts as an intermediary between the document and the user: the view renders an image of the document on the screen or printer and interprets user input as operations upon the document.

A view is a child of a frame window. More than one view can share a frame window, as in the case of a splitter window. The relationship between a view class, a frame window class, and a document class is established by a CDocTemplate object. When the user opens a new window or splits an existing one, the framework constructs a new view and attaches it to the document.

A view can be attached to only one document, but a document can have multiple views attached to it at once — for example, if the document is displayed in a splitter window or in multiple child windows in a multiple document interface (MDI) application. Your application can support different types of views for a given document type; for example, a word-processing program might provide both a complete text view of a document and an outline view that shows only the section headings. These different types of views can be placed in separate frame windows or in separate panes of a single frame window if you use a splitter window.

A view may be responsible for handling several different types of input, such as keyboard input, mouse input or input via drag-and-drop, as well as commands from menus, toolbars, or scroll bars. A view receives commands forwarded by its frame window. If the view does not handle a given command, it forwards the command to its associated document. Like all command targets, a view handles messages via a message map.

The view is responsible for displaying and modifying the document’s data but not for storing it. The document provides the view with the necessary details about its data. You can let the view access the document’s data members directly, or you can provide member functions in the document class for the view class to call.

When a document’s data changes, the view responsible for the changes typically calls the CDocument::UpdateAllViews function for the document, which notifies all the other views by calling the OnUpdate member function for each. The default implementation of OnUpdate invalidates the view’s entire client area. You can override it to invalidate only those regions of the client area that map to the modified portions of the document.

To use CView, derive a class from it and implement the OnDraw member function to perform screen display. You can also use OnDraw to perform printing and print preview. The framework handles the print loop for printing and previewing your document.

A view handles scroll-bar messages with the CWnd::OnHScroll and CWnd::OnVScroll member functions. You can implement scroll-bar message handling in these functions, or you can use the CView derived class CScrollView to handle scrolling for you.

Besides CScrollView, the Microsoft Foundation Class Library provides nine other classes derived from CView:

  • CCtrlView, a view that allows usage of document - view architecture with tree, list, and rich edit controls.

  • CDaoRecordView, a view that displays database records in dialog-box controls.

  • CEditView, a view that provides a simple multiline text editor. You can use a CEditView object as a control in a dialog box as well as a view on a document.

  • CFormView, a scrollable view that contains dialog-box controls and is based on a dialog template resource.

  • CListView, a view that allows usage of document - view architecture with list controls.

  • CRecordView, a view that displays database records in dialog-box controls.

  • CRichEditView, a view that allows usage of document - view architecture with rich edit controls.

  • CScrollView, a view that automatically provides scrolling support.

  • CTreeView, a view that allows usage of document - view architecture with tree controls.

The CView class also has a derived implementation class named CPreviewView, which is used by the framework to perform print previewing. This class provides support for the features unique to the print-preview window, such as a toolbar, single- or double-page preview, and zooming, that is, enlarging the previewed image. You don’t need to call or override any of CPreviewView’s member functions unless you want to implement your own interface for print preview (for example, if you want to support editing in print preview mode). For more information on using CView, see Document/View Architecture Topics and Printing in Visual C++ Programmer’s Guide. In addition, see Technical Note 30 for more details on customizing print preview.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HELLO | MFC Sample MDIBIND | MFC Sample MDIDOCVW

See Also CWnd, CFrameWnd, CSplitterWnd, CDC, CDocTemplate, CDocument


CView Class Members

Operations

DoPreparePrinting | Displays Print dialog box and creates printer device context; call when overriding the OnPreparePrinting member function.
GetDocument | Returns the document associated with the view.

OLE Overridables

OnDragEnter | Called when an item is first dragged into the drag-and-drop region of a view.
OnDragLeave | Called when a dragged item leaves the drag-and-drop region of a view.
OnDragOver | Called when an item is dragged over the drag-and-drop region of a view.
OnDrop | Called when an item has been dropped into the drag-and-drop region of a view, default handler.
OnDropEx | Called when an item has been dropped into the drag-and-drop region of a view, primary handler.
OnDragScroll | Called to determine whether the cursor is dragged into the scroll region of the window.
OnInitialUpdate | Called after a view is first attached to a document.
OnScrollBy | Called when a view containing active in-place OLE items is scrolled.
OnScroll | Called when OLE items are dragged beyond the borders of the view.

Overridables

IsSelected | Tests whether a document item is selected. Required for OLE support.
OnActivateView | Called when a view is activated.
OnActivateFrame | Called when the frame window containing the view is activated or deactivated.
OnBeginPrinting | Called when a print job begins; override to allocate graphics device interface (GDI) resources.
OnDraw | Called to render an image of the document for screen display, printing, or print preview. Implementation required.
OnEndPrinting | Called when a print job ends; override to deallocate GDI resources.
OnEndPrintPreview | Called when preview mode is exited.
OnPrepareDC | Called before the OnDraw member function is called for screen display or the OnPrint member function is called for printing or print preview.
OnPreparePrinting | Called before a document is printed or previewed; override to initialize Print dialog box.
OnPrint | Called to print or preview a page of the document.
OnUpdate | Called to notify a view that its document has been modified.

Constructors

CView Constructs a CView object.


CView::CView

CView( );

Remarks

Constructs a CView object. The framework calls the constructor when a new frame window is created or a window is split. Override the OnInitialUpdate member function to initialize the view after the document is attached.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnInitialUpdate


CView::DoPreparePrinting

BOOL DoPreparePrinting( CPrintInfo* pInfo );

Return Value

Nonzero if printing or print preview can begin; 0 if the operation has been canceled.

Parameters

pInfo

Points to a CPrintInfo structure that describes the current print job.

Remarks

Call this function from your override of OnPreparePrinting to invoke the Print dialog box and create a printer device context.

This function’s behavior depends on whether it is being called for printing or print preview (specified by the m_bPreview member of the pInfo parameter). If a file is being printed, this function invokes the Print dialog box, using the values in the CPrintInfo structure that pInfo points to; after the user has closed the dialog box, the function creates a printer device context based on settings the user specified in the dialog box and returns this device context through the pInfo parameter. This device context is used to print the document.

If a file is being previewed, this function creates a printer device context using the current printer settings; this device context is used for simulating the printer during preview.

CView Overview | Class Members | Hierarchy Chart

See Also CPrintInfo, CView::OnPreparePrinting


CView::GetDocument

CDocument* GetDocument( ) const;

Return Value

A pointer to the CDocument object associated with the view. NULL if the view is not attached to a document.

Remarks

Call this function to get a pointer to the view’s document. This allows you to call the document’s member functions.

CView Overview | Class Members | Hierarchy Chart

See Also CDocument


CView::IsSelected

virtual BOOL IsSelected( const CObject* pDocItem ) const;

Return Value

Nonzero if the specified document item is selected; otherwise 0.

Parameters

pDocItem

Points to the document item being tested.

Remarks

Called by the framework to check whether the specified document item is selected. The default implementation of this function returns FALSE. Override this function if you are implementing selection using CDocItem objects. You must override this function if your view contains OLE items.

CView Overview | Class Members | Hierarchy Chart

See Also CDocItem, COleClientItem


CView::OnActivateFrame

virtual void OnActivateFrame( UINT nState, CFrameWnd* pFrameWnd );

Parameters

nState

Specifies whether the frame window is being activated or deactivated. It can be one of the following values:

  • WA_INACTIVE The frame window is being deactivated.

  • WA_ACTIVE The frame window is being activated through some method other than a mouse click (for example, by use of the keyboard interface to select the window).

  • WA_CLICKACTIVE The frame window is being activated by a mouse click

pFrameWnd

Pointer to the frame window that is to be activated.

Remarks

Called by the framework when the frame window containing the view is activated or deactivated. Override this member function if you want to perform special processing when the frame window associated with the view is activated or deactivated. For example, CFormView performs this override when it saves and restores the control that has focus.

CView Overview | Class Members | Hierarchy Chart

See Also CWnd::OnActivate, CFormView


CView::OnActivateView

virtual void OnActivateView( BOOL bActivate, CView* pActivateView, CView* pDeactiveView );

Parameters

bActivate

Indicates whether the view is being activated or deactivated.

pActivateView

Points to the view object that is being activated.

pDeactiveView

Points to the view object that is being deactivated.

Remarks

Called by the framework when a view is activated or deactivated. The default implementation of this function sets the focus to the view being activated. Override this function if you want to perform special processing when a view is activated or deactivated. For example, if you want to provide special visual cues that distinguish the active view from the inactive views, you would examine the bActivate parameter and update the view’s appearance accordingly.

The pActivateView and pDeactiveView parameters point to the same view if the application's main frame window is activated with no change in the active view — for example, if the focus is being transferred from another application to this one, rather than from one view to another within the application or when switching amongst MDI child windows. This allows a view to re-realize its palette, if needed.

These parameters differ when CFrameWnd::SetActiveView is called with a view that is different from what CFrameWnd::GetActiveView would return. This happens most often with splitter windows.

CView Overview | Class Members | Hierarchy Chart

See Also CWnd::OnActivate, CFrameWnd::SetActiveView, CFrameWnd::GetActiveView


CView::OnBeginPrinting

virtual void OnBeginPrinting( CDC* pDC, CPrintInfo* pInfo );

Parameters

pDC

Points to the printer device context.

pInfo

Points to a CPrintInfo structure that describes the current print job.

Remarks

Called by the framework at the beginning of a print or print preview job, after OnPreparePrinting has been called. The default implementation of this function does nothing. Override this function to allocate any GDI resources, such as pens or fonts, needed specifically for printing. Select the GDI objects into the device context from within the OnPrint member function for each page that uses them. If you are using the same view object to perform both screen display and printing, use separate variables for the GDI resources needed for each display; this allows you to update the screen during printing.

You can also use this function to perform initializations that depend on properties of the printer device context. For example, the number of pages needed to print the document may depend on settings that the user specified from the Print dialog box (such as page length). In such a situation, you cannot specify the document length in the OnPreparePrinting member function, where you would normally do so; you must wait until the printer device context has been created based on the dialog box settings. OnBeginPrinting is the first overridable function that gives you access to the CDC object representing the printer device context, so you can set the document length from this function. Note that if the document length is not specified by this time, a scroll bar is not displayed during print preview.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnEndPrinting, CView::OnPreparePrinting, CView::OnPrint


CView::OnDragEnter

virtual DROPEFFECT OnDragEnter( COleDataObject* pDataObject, DWORD dwKeyState, CPoint point );

Return Value

A value from the DROPEFFECT enumerated type, which indicates the type of drop that would occur if the user dropped the object at this position. The type of drop usually depends on the current key state indicated by dwKeyState. A standard mapping of keystates to DROPEFFECT values is:

  • DROPEFFECT_NONE The data object cannot be dropped in this window.

  • DROPEFFECT_LINK for MK_CONTROL | MK_SHIFT Creates a linkage between the object and its server.

  • DROPEFFECT_COPY for MK_CONTROL Creates a copy of the dropped object.

  • DROPEFFECT_MOVE for MK_ALT Creates a copy of the dropped object and delete the original object. This is typically the default drop effect, when the view can accept this data object.

For more information, see the MFC Advanced Concepts sample OCLIENT.

Parameters

pDataObject

Points to the COleDataObject being dragged into the drop area of the view.

dwKeyState

Contains the state of the modifier keys. This is a combination of any number of the following: MK_CONTROL, MK_SHIFT, MK_ALT, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.

point

The current mouse position relative to the client area of the view.

Remarks

Called by the framework when the mouse first enters the non-scrolling region of the drop target window. Default implementation is to do nothing and return DROPEFFECT_NONE.

Override this function to prepare for future calls to the OnDragOver member function. Any data required from the data object should be retrieved at this time for later use in the OnDragOver member function. The view should also be updated at this time to give the user visual feedback. For more information, see the article Drag and Drop: Implementing a Drop Target in Visual C++ Programmer’s Guide.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnDragOver, CView::OnDrop, CView::OnDropEx, CView::OnDragLeave, COleDropTarget::OnDragEnter


CView::OnDragLeave

virtual void OnDragLeave( );

Remarks

Called by the framework during a drag operation when the mouse is moved out of the valid drop area for that window.

Override this function if the current view needs to clean up any actions taken during OnDragEnter or OnDragOver calls, such as removing any visual user feedback while the object was dragged and dropped.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnDragEnter, CView::OnDragOver, CView::OnScroll, COleDropTarget::OnDragLeave


CView::OnDragOver

virtual DROPEFFECT OnDragOver( COleDataObject* pDataObject, DWORD dwKeyState, CPoint point );

Return Value

A value from the DROPEFFECT enumerated type, which indicates the type of drop that would occur if the user dropped the object at this position. The type of drop often depends on the current key state as indicated by dwKeyState. A standard mapping of keystates to DROPEFFECT values is:

  • DROPEFFECT_NONE The data object cannot be dropped in this window.

  • DROPEFFECT_LINK for MK_CONTROL | MK_SHIFT Creates a linkage between the object and its server.

  • DROPEFFECT_COPY for MK_CONTROL Creates a copy of the dropped object.

  • DROPEFFECT_MOVE for MK_ALT Creates a copy of the dropped object and delete the original object. This is typically the default drop effect, when the view can accept the data object.

For more information, see the MFC Advanced Concepts sample OCLIENT.

Parameters

pDataObject

Points to the COleDataObject being dragged over the drop target.

dwKeyState

Contains the state of the modifier keys. This is a combination of any number of the following: MK_CONTROL, MK_SHIFT, MK_ALT, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.

point

The current mouse position relative to the view client area.

Remarks

Called by the framework during a drag operation when the mouse is moved over the drop target window. The default implementation is to do nothing and return DROPEFFECT_NONE.

Override this function to give the user visual feedback during the drag operation. Since this function is called continuously, any code contained within it should be optimized as much as possible. For more information, see the article Drag and Drop: Implementing a Drop Target in Visual C++ Programmer’s Guide.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnDragEnter, CView::OnDrop, CView::OnDropEx, CView::OnDragLeave, COleDropTarget::OnDragOver


CView::OnDragScroll

virtual DROPEFFECT OnDragScroll( DWORD dwKeyState, CPoint point );

Return Value

A value from the DROPEFFECT enumerated type, which indicates the type of drop that would occur if the user dropped the object at this position. The type of drop usually depends on the current key state indicated by dwKeyState. A standard mapping of keystates to DROPEFFECT values is:

  • DROPEFFECT_NONE The data object cannot be dropped in this window.

  • DROPEFFECT_LINK for MK_CONTROL | MK_SHIFT Creates a linkage between the object and its server.

  • DROPEFFECT_COPY for MK_CONTROL Creates a copy of the dropped object.

  • DROPEFFECT_MOVE for MK_ALT Creates a copy of the dropped object and delete the original object.

  • DROPEFFECT_SCROLL Indicates that a drag scroll operation is about to occur or is occurring in the target view.

For more information, see the MFC Advanced Concepts sample OCLIENT.

Parameters

dwKeyState

Contains the state of the modifier keys. This is a combination of any number of the following: MK_CONTROL, MK_SHIFT, MK_ALT, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON.

point

Contains the location of the cursor, in pixels, relative to the screen.

Remarks

Called by the framework before calling OnDragEnter or OnDragOver to determine whether the point is in the scrolling region. Override this function when you want to provide special behavior for this event. The default implementation automatically scrolls windows when the cursor is dragged into the default scroll region inside the border of each window.For more information, see the article Drag and Drop: Implementing a Drop Target in Visual C++ Programmer’s Guide.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnDragEnter, CView::OnDragOver, CView::OnDrop, CView::OnDragLeave, COleDropTarget::OnDragScroll


CView::OnDraw

virtual void OnDraw( CDC* pDC ) = 0;

Parameters

pDC

Points to the device context to be used for rendering an image of the document.

Remarks

Called by the framework to render an image of the document. The framework calls this function to perform screen display, printing, and print preview, and it passes a different device context in each case. There is no default implementation.

You must override this function to display your view of the document. You can make graphic device interface (GDI) calls using the CDC object pointed to by the pDC parameter. You can select GDI resources, such as pens or fonts, into the device context before drawing and then deselect them afterwards. Often your drawing code can be device-independent; that is, it doesn’t require information about what type of device is displaying the image.

To optimize drawing, call the RectVisible member function of the device context to find out whether a given rectangle will be drawn. If you need to distinguish between normal screen display and printing, call the IsPrinting member function of the device context.

CView Overview | Class Members | Hierarchy Chart

See Also CDC::IsPrinting, CDC::RectVisible, CView::OnPrint, CWnd::OnCreate, CWnd::OnDestroy, CWnd::PostNcDestroy


CView::OnDrop

virtual BOOL OnDrop( COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point );

Return Value

Nonzero if the drop was successful; otherwise 0.

Parameters

pDataObject

Points to the COleDataObject that is dropped into the drop target.

dropEffect

The drop effect that the user has requested.

  • DROPEFFECT_COPY Creates a copy of the data object being dropped.

  • DROPEFFECT_MOVE Moves the data object to the current mouse location.

  • DROPEFFECT_LINK Creates a link between a data object and its server.

point

The current mouse position relative to the view client area.

Remarks

Called by the framework when the user releases a data object over a valid drop target. The default implementation does nothing and returns FALSE.

Override this function to implement the effect of an OLE drop into the client area of the view. The data object can be examined via pDataObject for Clipboard data formats and data dropped at the specified point.

Note The framework does not call this function if there is an override to OnDropEx in this view class.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnDragEnter, CView::OnDragOver, CView::OnDropEx, CView::OnDragLeave, COleDropTarget::OnDrop


CView::OnDropEx

virtual DROPEFFECT OnDropEx( COleDataObject* pDataObject, DROPEFFECT dropDefault, DROPEFFECT dropList, CPoint point );

Return Value

The drop effect that resulted from the drop attempt at the location specified by point. This must be one of the values indicated by dropEffectList. Drop effects are discussed in the Remarks section.

Parameters

pDataObject

Points to the COleDataObject that is dropped into the drop target.

dropDefault

The effect that the user chose for the default drop operation based on the current key state. It may be DROPEFFECT_NONE. Drop effects are discussed in the Remarks section.

dropList

A list of the drop effects that the drop source supports. Drop effect values can be combined using the bitwise OR (|) operation. Drop effects are discussed in the Remarks section.

point

The current mouse position relative to the view client area.

Remarks

Called by the framework when the user releases a data object over a valid drop target. The default implementation is to do nothing and return a dummy value ( -1 ) to indicate that the framework should call the OnDrop handler.

Override this function to implement the effect of an right mouse-button drag and drop. Right mouse-button drag and drop typically displays a menu of choices when the right mouse-button is released.

Your override of OnDropEx should query for the right mouse-button. You can call GetKeyState or store the right mouse-button state from your OnDragEnter handler.

  • If the right mouse-button is down, your override should display a popup menu which offers the drop effects support by the drop source.
    • Examine dropList to determine the drop effects supported by the drop source. Enable only these actions on the popup menu.

    • Use SetMenuDefaultItem to set the default action based on dropDefault.

    • Finally, take the action indicated by the user selection from the popup menu.
  • If the right mouse-button is not down, your override should process this as a standard drop request. Use the drop effect specified in dropDefault. Alternately, your override can return the dummy value ( -1 ) to indicate that OnDrop will handle this drop operation.

Use pDataObject to examine the COleDataObject for Clipboard data format and data dropped at the specified point.

Drop effects describe the action associated with a drop operation. See the following list of drop effects:

  • DROPEFFECT_NONE A drop would not be allowed.

  • DROPEFFECT_COPY A copy operation would be performed.

  • DROPEFFECT_MOVE A move operation would be performed.

  • DROPEFFECT_LINK A link from the dropped data to the original data would be established.

  • DROPEFFECT_SCROLL Indicates that a drag scroll operation is about to occur or is occurring in the target.

For more information on setting the default menu command, see SetMenuDefaultItem in the Win32 documentation and CMenu::GetSafeHmenu in this volume.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnDragEnter, CView::OnDragOver, CView::OnDrop, CView::OnDragLeave, COleDropTarget::OnDropEx


CView::OnEndPrinting

virtual void OnEndPrinting( CDC* pDC, CPrintInfo* pInfo );

Parameters

pDC

Points to the printer device context.

pInfo

Points to a CPrintInfo structure that describes the current print job.

Remarks

Called by the framework after a document has been printed or previewed. The default implementation of this function does nothing. Override this function to free any GDI resources you allocated in the OnBeginPrinting member function.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnBeginPrinting


CView::OnEndPrintPreview

virtual void OnEndPrintPreview( CDC* pDC, CPrintInfo* pInfo, POINT point, CPreviewView* pView );

Parameters

pDC

Points to the printer device context.

pInfo

Points to a CPrintInfo structure that describes the current print job.

point

Specifies the point on the page that was last displayed in preview mode.

pView

Points to the view object used for previewing.

Remarks

Called by the framework when the user exits print preview mode. The default implementation of this function calls the OnEndPrinting member function and restores the main frame window to the state it was in before print preview began. Override this function to perform special processing when preview mode is terminated. For example, if you want to maintain the user’s position in the document when switching from preview mode to normal display mode, you can scroll to the position described by the point parameter and the m_nCurPage member of the CPrintInfo structure that the pInfo parameter points to.

Always call the base class version of OnEndPrintPreview from your override, typically at the end of the function.

CView Overview | Class Members | Hierarchy Chart

See Also CPrintInfo, CView::OnEndPrinting


CView::OnInitialUpdate

virtual void OnInitialUpdate( );

Remarks

Called by the framework after the view is first attached to the document, but before the view is initially displayed. The default implementation of this function calls the OnUpdate member function with no hint information (that is, using the default values of 0 for the lHint parameter and NULL for the pHint parameter). Override this function to perform any one-time initialization that requires information about the document. For example, if your application has fixed-sized documents, you can use this function to initialize a view’s scrolling limits based on the document size. If your application supports variable-sized documents, use OnUpdate to update the scrolling limits every time the document changes.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnUpdate


CView::OnPrepareDC

virtual void OnPrepareDC( CDC* pDC, CPrintInfo* pInfo = NULL );

Parameters

pDC

Points to the device context to be used for rendering an image of the document.

pInfo

Points to a CPrintInfo structure that describes the current print job if OnPrepareDC is being called for printing or print preview; the m_nCurPage member specifies the page about to be printed. This parameter is NULL if OnPrepareDC is being called for screen display.

Remarks

Called by the framework before the OnDraw member function is called for screen display and before the OnPrint member function is called for each page during printing or print preview. The default implementation of this function does nothing if the function is called for screen display. However, this function is overridden in derived classes, such as CScrollView, to adjust attributes of the device context; consequently, you should always call the base class implementation at the beginning of your override.

If the function is called for printing, the default implementation examines the page information stored in the pInfo parameter. If the length of the document has not been specified, OnPrepareDC assumes the document to be one page long and stops the print loop after one page has been printed. The function stops the print loop by setting the m_bContinuePrinting member of the structure to FALSE.

Override OnPrepareDC for any of the following reasons:

  • To adjust attributes of the device context as needed for the specified page. For example, if you need to set the mapping mode or other characteristics of the device context, do so in this function.

  • To perform print-time pagination. Normally you specify the length of the document when printing begins, using the OnPreparePrinting member function. However, if you don’t know in advance how long the document is (for example, when printing an undetermined number of records from a database), override OnPrepareDC to test for the end of the document while it is being printed. When there is no more of the document to be printed, set the m_bContinuePrinting member of the CPrintInfo structure to FALSE.

  • To send escape codes to the printer on a page-by-page basis. To send escape codes from OnPrepareDC, call the Escape member function of the pDC parameter.

Call the base class version of OnPrepareDC at the beginning of your override.

CView Overview | Class Members | Hierarchy Chart

See Also CDC::Escape, CPrintInfo, CView::OnBeginPrinting, CView::OnDraw, CView::OnPreparePrinting, CView::OnPrint


CView::OnPreparePrinting

virtual BOOL OnPreparePrinting( CPrintInfo* pInfo );

Return Value

Nonzero to begin printing; 0 if the print job has been canceled.

Parameters

pInfo

Points to a CPrintInfo structure that describes the current print job.

Remarks

Called by the framework before a document is printed or previewed. The default implementation does nothing.

You must override this function to enable printing and print preview. Call the DoPreparePrinting member function, passing it the pInfo parameter, and then return its return value; DoPreparePrinting displays the Print dialog box and creates a printer device context. If you want to initialize the Print dialog box with values other than the defaults, assign values to the members of pInfo. For example, if you know the length of the document, pass the value to the SetMaxPage member function of pInfo before calling DoPreparePrinting. This value is displayed in the To: box in the Range portion of the Print dialog box.

DoPreparePrinting does not display the Print dialog box for a preview job. If you want to bypass the Print dialog box for a print job, check that the m_bPreview member of pInfo is FALSE and then set it to TRUE before passing it to DoPreparePrinting; reset it to FALSE afterwards.

If you need to perform initializations that require access to the CDC object representing the printer device context (for example, if you need to know the page size before specifying the length of the document), override the OnBeginPrinting member function.

If you want to set the value of the m_nNumPreviewPages or m_strPageDesc members of the pInfo parameter, do so after calling DoPreparePrinting. The DoPreparePrinting member function sets m_nNumPreviewPages to the value found in the application’s .INI file and sets m_strPageDesc to its default value.

Example

The following is an override of OnPreparePrinting provided by AppWizard if you select the printing option when you create a set of starter files. This override is sufficient unless you want to initialize the Print dialog box.

BOOL CMyView::OnPreparePrinting( CPrintInfo *pInfo )
{
   return DoPreparePrinting( pInfo );
}

CView Overview | Class Members | Hierarchy Chart

See Also CPrintInfo, CView::DoPreparePrinting, CView::OnBeginPrinting, CView::OnPrepareDC, CView::OnPrint


CView::OnPrint

virtual void OnPrint( CDC* pDC, CPrintInfo* pInfo );

Parameters

pDC

Points to the printer device context.

pInfo

Points to a CPrintInfo structure that describes the current print job.

Remarks

Called by the framework to print or preview a page of the document. For each page being printed, the framework calls this function immediately after calling the OnPrepareDC member function. The page being printed is specified by the m_nCurPage member of the CPrintInfo structure that pInfo points to. The default implementation calls the OnDraw member function and passes it the printer device context.

Override this function for any of the following reasons:

  • To allow printing of multipage documents. Render only the portion of the document that corresponds to the page currently being printed. If you’re using OnDraw to perform the rendering, you can adjust the viewport origin so that only the appropriate portion of the document is printed.

  • To make the printed image look different from the screen image (that is, if your application is not WYSIWYG). Instead of passing the printer device context to OnDraw, use the device context to render an image using attributes not shown on the screen.

    If you need GDI resources for printing that you don’t use for screen display, select them into the device context before drawing and deselect them afterwards. These GDI resources should be allocated in OnBeginPrinting and released in OnEndPrinting.

  • To implement headers or footers. You can still use OnDraw to do the rendering by restricting the area that it can print on.

Note that the m_rectDraw member of the pInfo parameter describes the printable area of the page in logical units.

Do not call OnPrepareDC in your override of OnPrint; the framework calls OnPrepareDC automatically before calling OnPrint.

Example

The following is a skeleton for an overridden OnPrint function:

void CMyView::OnPrint( CDC *pDC, CPrintInfo *pInfo )
{
   // Print headers and/or footers, if desired.
   // Find portion of document corresponding to pInfo->m_nCurPage.
   OnDraw( pDC );
}

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnBeginPrinting, CView::OnEndPrinting, CView::OnPrepareDC, CView::OnDraw


CView::OnScroll

virtual BOOL CView::OnScroll( UINT nScrollCode, UINT nPos, BOOL bDoScroll = TRUE );

Return Value

If bDoScroll is TRUE and the view was actually scrolled, then return nonzero; otherwise 0. If bDoScroll is FALSE, then return the value that you would have returned if bDoScroll were TRUE, even though you don’t actually do the scrolling.

Parameters

nScrollCode

A scroll-bar code that indicates the user’s scrolling request. This parameter is composed of two parts: a low-order byte, which determines the type of scrolling occurring horizontally, and a high-order byte, which determines the type of scrolling occurring vertically:

  • SB_BOTTOM Scrolls to bottom.

  • SB_LINEDOWN Scrolls one line down.

  • SB_LINEUP Scrolls one line up.

  • SB_PAGEDOWN Scrolls one page down.

  • SB_PAGEUP Scrolls one page up.

  • SB_THUMBTRACK Drags scroll box to specified position. The current position is specified in nPos.

  • SB_TOP Scrolls to top.

nPos

Contains the current scroll-box position if the scroll-bar code is SB_THUMBTRACK; otherwise it is not used. Depending on the initial scroll range, nPos may be negative and should be cast to an int if necessary.

bDoScroll

Determines whether you should actually do the specified scrolling action. If TRUE, then scrolling should take place; if FALSE, then scrolling should not occur.

Remarks

Called by the framework to determine whether scrolling is possible.

In one case this function is called by the framework with bDoScroll set to TRUE when the view receives a scrollbar message. In this case, you should actually scroll the view. In the other case this function is called with bDoScroll set to FALSE when an OLE item is initially dragged into the auto-scrolling region of a drop target before scrolling actually takes place. In this case, you should not actually scroll the view.

CView Overview | Class Members | Hierarchy Chart

See Also CView::OnScrollBy, COleClientItem


CView::OnScrollBy

BOOL CView::OnScrollBy( CSize sizeScroll, BOOL bDoScroll = TRUE );

Return Value

Nonzero if the view was able to be scrolled; otherwise 0.

Parameters

sizeScroll

Number of pixels scrolled horizontally and vertically.

bDoScroll

Determines whether scrolling of the view occurs. If TRUE, then scrolling takes place; if FALSE, then scrolling does not occur.

Remarks

Called by the framework when the user views an area beyond the present view of the document, either by dragging an OLE item against the view’s current borders or by manipulating the vertical or horizontal scrollbars. The default implementation does nothing. In derived classes the function checks to see whether the view is scrollable in the direction the user requested and then updates the new region if necessary. This function is automatically called by CWnd::OnHScroll and CWnd::OnVScroll to perform the actual scrolling request.


CView::OnUpdate

virtual void OnUpdate( CView* pSender, LPARAM lHint, CObject* pHint );

Parameters

pSender

Points to the view that modified the document, or NULL if all views are to be updated.

lHint

Contains information about the modifications.

pHint

Points to an object storing information about the modifications.

Remarks

Called by the framework after the view’s document has been modified; this function is called by CDocument::UpdateAllViews and allows the view to update its display to reflect those modifications. It is also called by the default implementation of OnInitialUpdate. The default implementation invalidates the entire client area, marking it for painting when the next WM_PAINT message is received. Override this function if you want to update only those regions that map to the modified portions of the document. To do this you must pass information about the modifications using the hint parameters.

To use lHint, define special hint values, typically a bitmask or an enumerated type, and have the document pass one of these values. To use pHint, derive a hint class from CObject and have the document pass a pointer to a hint object; when overriding OnUpdate, use the CObject::IsKindOf member function to determine the run-time type of the hint object.

Typically you should not perform any drawing directly from OnUpdate. Instead, determine the rectangle describing, in device coordinates, the area that requires updating; pass this rectangle to CWnd::InvalidateRect. This causes painting to occur the next time a WM_PAINT message is received.

If lHint is 0 and pHint is NULL, the document has sent a generic update notification. If a view receives a generic update notification, or if it cannot decode the hints, it should invalidate its entire client area.

CView Overview | Class Members | Hierarchy Chart

See Also CDocument::UpdateAllViews, CView::OnInitialUpdate, CWnd::Invalidate, CWnd::InvalidateRect


CWaitCursor

CWaitCursor does not have a base class.

The CWaitCursor class provides a one-line way to show a wait cursor, which is usually displayed as an hourglass, while you’re doing a lengthy operation. Good Windows programming practices require that you display a wait cursor whenever you’re performing an operation that takes a noticeable amount of time.

To display a wait cursor, just define a CWaitCursor variable before the code that performs the lengthy operation. The object’s constructor automatically causes the wait cursor to be displayed.

When the object goes out of scope (at the end of the block in which the CWaitCursor object is declared), its destructor sets the cursor to the previous cursor. In other words, the object performs the necessary clean-up automatically.

Note Because of how their constructors and destructors work, CWaitCursor objects are always declared as local variables — they’re never declared as global variables nor are they allocated with new.

If you perform an operation which might cause the cursor to be changed, such as displaying a message box or dialog box, call the Restore member function to restore the wait cursor. It is okay to call Restore even when a wait cursor is currently displayed.

Another way to display a wait cursor is to use the combination of CCmdTarget::BeginWaitCursor, CCmdTarget::EndWaitCursor, and perhaps CCmdTarget::RestoreWaitCursor. However, CWaitCursor is easier to use because you don’t need to set the cursor to the previous cursor when you’re done with the lengthy operation.

Note MFC sets and restores the cursor using the CWinApp::DoWaitCursor virtual function. You can override this function to provide custom behavior.

#include <afxwin.h>

Class Members | Hierarchy Chart

See Also CCmdTarget::BeginWaitCursor, CCmdTarget::EndWaitCursor, CCmdTarget::RestoreWaitCursor, CWinApp::DoWaitCursor


CWaitCursor Class Members

Construction/Destruction

CWaitCursor Constructs a CWaitCursor object and displays the wait cursor.

Operations

Restore Restores the wait cursor after it’s been changed.


CWaitCursor::CWaitCursor

CWaitCursor( );

Remarks

To display a wait cursor, just declare a CWaitCursor object before the code that performs the lengthy operation. The constructor automatically causes the wait cursor to be displayed.

When the object goes out of scope (at the end of the block in which the CWaitCursor object is declared), its destructor sets the cursor to the previous cursor. In other words, the object performs the necessary clean-up automatically.

You can take advantage of the fact that the destructor is called at the end of the block (which might be before the end of the function) to make the wait cursor active in only part of your function. This technique is shown in the second example below.

Note Because of how their constructors and destructors work, CWaitCursor objects are always declared as local variables — they’re never declared as global variables, nor are they allocated with new.

Example

// The following example illustrates the most common case
// of displaying the wait cursor during some lengthy
// processing.

void LengthyFunction( )
{
   // perhaps you display a dialog box before displaying a
   // wait cursor

   CWaitCursor wait;   // display wait cursor

   // do some lengthy processing

}  // destructor automatically removes the wait cursor

// This example shows using a CWaitCursor object inside a block
// so the wait cursor is displayed only while the program is
// performing a lengthy operation.

void ConditionalFunction( )
{
   if ( SomeCondition )
   {
      CWaitCursor wait;   // display wait cursor in this block only

      // do some lengthy processing

   }  // at this point, the destructor removes the wait cursor
   else
   {
      // no wait cursor--only quick processing
   }
}

CWaitCursor Overview | Hierarchy Chart

See Also CWaitCursor::Restore, CCmdTarget::BeginWaitCursor, CCmdTarget::EndWaitCursor


CWaitCursor::Restore

void Restore( );

Remarks

To restore the wait cursor, call this function after performing an operation, such as displaying a message box or dialog box, which might change the wait cursor to another cursor.

It is OK to call Restore even when the wait cursor is currently displayed.

If you need to restore the wait cursor while in a function other than the one in which the CWaitCursor object is declared, you can call CCmdTarget::RestoreWaitCursor.

Examples

// This example illustrates performing an operation
// which changes the wait cursor. You should call
// CWaitCursor::Restore to restore the wait
// cursor after an operation which changes the cursor.

void AnotherLengthyFunction( )
{
   CWaitCursor wait;   // display wait cursor

   // do some lengthy processing

   // The dialog box will normally change the cursor to
   // the standard arrow cursor.
   CSomeDialog dlg;
   dlg.DoModal( );

   // It is necessary to call Restore here in order
   // to change the cursor back to the wait cursor.
   wait.Restore( );

   // do some more lengthy processing

   // destructor automatically removes the wait cursor
}

// If the wait cursor is changed by a function called by
// the function which created the wait cursor, you
// can call CCmdTarget::RestoreWaitCursor to restore
// the wait cursor.
void CalledFunction()
{
   CSomeDialog dlg;
   dlg.DoModal();

   // Since CWinApp is derived from CCmdTarget, we can use a
   // pointer to our application object to make the call to
   // CCmdTarget::RestoreWaitCursor.
   AfxGetApp()->RestoreWaitCursor( );

   // Yet more lengthy processing...
}

CWaitCursor Overview | Hierarchy Chart

See Also CCmdTarget::RestoreWaitCursor


CWinApp

The CWinApp class is the base class from which you derive a Windows application object. An application object provides member functions for initializing your application (and each instance of it) and for running the application.

Each application that uses the Microsoft Foundation classes can only contain one object derived from CWinApp. This object is constructed when other C++ global objects are constructed and is already available when Windows calls the WinMain function, which is supplied by the Microsoft Foundation Class Library. Declare your derived CWinApp object at the global level.

When you derive an application class from CWinApp, override the InitInstance member function to create your application’s main window object.

In addition to the CWinApp member functions, the Microsoft Foundation Class Library provides the following global functions to access your CWinApp object and other global information:

  • AfxGetApp Obtains a pointer to the CWinApp object.

  • AfxGetInstanceHandle Obtains a handle to the current application instance.

  • AfxGetResourceHandle Obtains a handle to the application’s resources.

  • AfxGetAppName Obtains a pointer to a string containing the application’s name. Alternately, if you have a pointer to the CWinApp object, use m_pszExeName to get the application’s name.

See CWinApp: The Application Class in Visual C++ Programmer’s Guide for more on the CWinApp class, including an overview of the following:

  • CWinApp-derived code written by AppWizard.

  • CWinApp’s role in the execution sequence of your application.

  • CWinApp’s default member function implementations.

  • CWinApp’s key overridables.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample HELLOAPP | MFC Sample HELLO


CWinApp Class Members

Data Members
Construction
Operations
Overridables
Initialization
Command Handlers

Data Members

m_pszAppName | Specifies the name of the application.
m_hInstance | Identifies the current instance of the application.
m_hPrevInstance | Set to NULL in a 32-bit application.
m_lpCmdLine | Points to a null-terminated string that specifies the command line for the application.
m_nCmdShow | Specifies how the window is to be shown initially.
m_bHelpMode | Indicates if the user is in Help context mode (typically invoked with SHIFT+F1).
m_pActiveWnd | Pointer to the main window of the container application when an OLE server is in-place active.
m_pszExeName | The module name of the application.
m_pszHelpFilePath | The path to the application’s Help file.
m_pszProfileName | The application’s .INI filename.
m_pszRegistryKey | Used to determine the full registry key for storing application profile settings.

Construction

CWinApp Constructs a CWinApp object.

Operations

LoadCursor | Loads a cursor resource.
LoadStandardCursor | Loads a Windows predefined cursor that the IDC_ constants specify in WINDOWS.H.
LoadOEMCursor | Loads a Windows OEM predefined cursor that the OCR_ constants specify in WINDOWS.H.
LoadIcon | Loads an icon resource.
LoadStandardIcon | Loads a Windows predefined icon that the IDI_ constants specify in WINDOWS.H.
LoadOEMIcon | Loads a Windows OEM predefined icon that the OIC_ constants specify in WINDOWS.H.
RunAutomated | Tests the application’s command line for the /Automation option. Obsolete. Use the value in CCommandLineInfo::m_bRunEmbedded after calling ParseCommandLine. instead.
RunEmbedded | Tests the application’s command line for the /Embedding option. Obsolete. Use the value in CCommandLineInfo::m_bRunEmbedded after calling ParseCommandLine. instead.
ParseCommandLine | Parses individual parameters and flags in the command line.
ProcessShellCommand | Handles command-line arguments and flags.
GetProfileInt | Retrieves an integer from an entry in the application’s .INI file.
WriteProfileInt | Writes an integer to an entry in the application’s .INI file.
GetProfileString | Retrieves a string from an entry in the application’s .INI file.
WriteProfileString | Writes a string to an entry in the application’s .INI file.
AddDocTemplate | Adds a document template to the application’s list of available document templates.
GetFirstDocTemplatePosition | Retrieves the position of the first document template.
GetNextDocTemplate | Retrieves the position of a document template. Can be used recursively.
OpenDocumentFile | Called by the framework to open a document from a file.
AddToRecentFileList | Adds a filename to the most recently used (MRU) file list.
SelectPrinter | Selects a printer previously indicated by a user through a print dialog box.
CreatePrinterDC | Creates a printer device context.
GetPrinterDeviceDefaults | Retrieves the printer device defaults.

Overridables

InitInstance | Override to perform Windows instance initialization, such as creating your window objects.
Run | Runs the default message loop. Override to customize the message loop.
OnIdle | Override to perform application-specific idle-time processing.
ExitInstance | Override to clean up when your application terminates.
HideApplication | Hides the application before closing all documents.
CloseAllDocuments | Closes all open documents.
PreTranslateMessage | Filters messages before they are dispatched to the Windows functions ::TranslateMessage and ::DispatchMessage.
SaveAllModified | Prompts the user to save all modified documents.
DoMessageBox | Implements AfxMessageBox for the application.
ProcessMessageFilter | Intercepts certain messages before they reach the application.
ProcessWndProcException | Intercepts all unhandled exceptions thrown by the application’s message and command handlers.
DoWaitCursor | Turns the wait cursor on and off.
OnDDECommand | Called by the framework in response to a dynamic data exchange (DDE) execute command.
WinHelp | Calls the WinHelp Windows function.

Initialization

LoadStdProfileSettings | Loads standard .INI file settings and enables the MRU file list feature.
SetDialogBkColor | Sets the default background color for dialog boxes and message boxes.
SetRegistryKey | Causes application settings to be stored in the registry instead of .INI files.
EnableShellOpen | Allows the user to open data files from the Windows File Manager.
RegisterShellFileTypes | Registers all the application’s document types with the Windows File Manager.
Enable3dControls | Enables controls with three-dimensional appearance.
Enable3dControlsStatic | Enables controls with a three-dimensional appearance.

Command Handlers

OnFileNew | Implements the ID_FILE_NEW command.
OnFileOpen | Implements the ID_FILE_OPEN command.
OnFilePrintSetup | Implements the ID_FILE_PRINT_SETUP command.
OnContextHelp | Handles SHIFT+F1 Help within the application.
OnHelp | Handles F1 Help within the application (using the current context).
OnHelpIndex | Handles the ID_HELP_INDEX command and provides a default Help topic.
OnHelpFinder | Handles the ID_HELP_FINDER and ID_DEFAULT_HELP commands.
OnHelpUsing | Handles the ID_HELP_USING command.

See Also CWinApp Overview | Base Class Members | Hierarchy Chart


CWinApp::AddDocTemplate

void AddDocTemplate( CDocTemplate* pTemplate );

Parameters

pTemplate

A pointer to the CDocTemplate to be added.

Remarks

Call this member function to add a document template to the list of available document templates that the application maintains. You should add all document templates to an application before you call RegisterShellFileTypes.

Example

BOOL CMyApp::InitInstance()
{
   // ...
.   // The following code is produced by AppWizard when you
   // choose the MDI (multiple document interface) option.
   CMultiDocTemplate* pDocTemplate;
   pDocTemplate = new CMultiDocTemplate(
      IDR_MYTYPE,
      RUNTIME_CLASS(CMyDoc),
      RUNTIME_CLASS(CMDIChildWnd),        // standard MDI child frame
      RUNTIME_CLASS(CMyView));
   AddDocTemplate(pDocTemplate);
     // ...
}

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::RegisterShellFileTypes, CMultiDocTemplate, CSingleDocTemplate


CWinApp::AddToRecentFileList

virtual void AddToRecentFileList( LPCTSTR lpszPathName );

Parameters

lpszPathName

The path of the file.

Remarks

Call this member function to add lpszPathName to the MRU file list. You should call the LoadStdProfileSettings member function to load the current MRU file list before you use this member function.

The framework calls this member function when it opens a file or executes the Save As command to save a file with a new name.

Example

   // This adds the pathname c:\temp\test.doc to the top of
   // the most recently used (MRU) list in the File menu.
    AfxGetApp()->AddToRecentFileList("c:\\temp\\test.doc");

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadStdProfileSettings


CWinApp::CloseAllDocuments

void CloseAllDocuments( BOOL bEndSession );

Parameters

bEndSession

Specifies whether or not the Windows session is being ended. It is TRUE if the session is being ended; otherwise FALSE.

Remarks

Call this member function to close all open documents before exiting. Call HideApplication before calling CloseAllDocuments.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::SaveAllModified, CWinApp::HideApplication


CWinApp::CreatePrinterDC

BOOL CreatePrinterDC( CDC& dc );

Return Value

Nonzero if the printer device context is created successfully; otherwise 0.

Parameters

dc

A reference to a printer device context.

Remarks

Call this member function to create a printer device context (DC) from the selected printer. CreatePrinterDC initializes the device context that you pass in by reference, so you can use it to print.

If the function is successful, when you have finished printing, you must destroy the device context. You can let the destructor of the CDC object do it, or you can do it explicitly by calling CDC::DeleteDC.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::SelectPrinter


CWinApp::CWinApp

CWinApp( LPCTSTR lpszAppName = NULL );

Parameters

lpszAppName

A null-terminated string that contains the application name that Windows uses. If this argument is not supplied or is NULL, CWinApp uses the resource string AFX_IDS_APP_TITLE or the filename of the executable file.

Remarks

Constructs a CWinApp object and passes lpszAppName to be stored as the application name. You should construct one global object of your CWinApp-derived class. You can have only one CWinApp object in your application. The constructor stores a pointer to the CWinApp object so that WinMain can call the object’s member functions to initialize and run the application.


CWinApp::DoMessageBox

virtual int DoMessageBox( LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt );

Return Value

Returns the same values as AfxMessageBox.

Parameters

lpszPrompt

Address of text in the message box.

nType

The message box style.

nIDPrompt

An index to a Help context string.

Remarks

The framework calls this member function to implement a message box for the global function AfxMessageBox.

Do not call this member function to open a message box; use AfxMessageBox instead.

Override this member function to customize your application-wide processing of AfxMessageBox calls.

CWinApp Overview | Class Members | Hierarchy Chart

See Also AfxMessageBox, ::MessageBox


CWinApp::DoWaitCursor

virtual void DoWaitCursor( int nCode );

Parameters

nCode

If this parameter is 1, a wait cursor appears. If 0, the wait cursor is restored without incrementing the reference count. If –1, the wait cursor ends.

Remarks

This member function is called by the framework to implement CWaitCursor, CCmdTarget::BeginWaitCursor, CCmdTarget::EndWaitCursor, and CCmdTarget::RestoreWaitCursor. The default implements an hourglass cursor. DoWaitCursor maintains a reference count. When positive, the hourglass cursor is displayed.

While you would not normally call DoWaitCursor directly, you could override this member function to change the wait cursor or to do additional processing while the wait cursor is displayed.

For an easier, more streamlined way to implement a wait cursor, use CWaitCursor.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CCmdTarget::BeginWaitCursor, CCmdTarget::EndWaitCursor, CCmdTarget::RestoreWaitCursor, CWaitCursor


CWinApp::Enable3dControls

BOOL Enable3dControls( );

BOOL Enable3dControlsStatic( );

Note Both Enable3dControls and Enable3dControlsStatic are described in this topic.

Return Value

TRUE if the CTL3D32.DLL is loaded successfully; otherwise FALSE.

This function will return FALSE if the operating system supports the three-dimensional look for controls.

Remarks

Call either of these member functions from your override of the InitInstance member function to enable dialog boxes and windows whose controls have a three-dimensional appearance. These member functions load the CTL3D32.DLL and registers the application with the DLL. If you call Enable3dControls or Enable3dControlsStatic, you do not need to call the SetDialogBkColor member function.

Enable3dControls should be used when linking to the MFC DLLs. Enable3dControlsStatic should be used when statically linking to the MFC libraries.

Feature Only in Professional and Enterprise Editions Static linking to MFC is supported only in Visual C++ Professional and Enterprise Editions. For more information, see Visual C++ Editions.

MFC automatically provides 3D control effects for the following classes of windows:

  • CDialog

  • CDialogBar

  • CFormView

  • CPropertyPage

  • CPropertySheet

  • CControlBar

  • CToolBar

If the controls for which you want a 3D effect are in a window of any of these types, all you need is the enabling call to Enable3dControls or Enable3dControlsStatic. If you want to give a 3D effect to controls in windows based on other classes, you must call the CTL3D32 API functions directly.

Example

#ifdef _AFXDLL
    Enable3dControls( );   //Call Enable3dControls
#else
    Enable3dControlsStatic( );
//Call Enable3dControlsStatic
#endif

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::InitInstance, CWinApp::SetDialogBkColor


CWinApp::EnableShellOpen

void EnableShellOpen( );

Remarks

Call this function, typically from your InitInstance override, to enable your application’s users to open data files when they double-click the files from within the Windows File Manager. Call the RegisterShellFileTypes member function in conjunction with this function, or provide a .REG file with your application for manual registration of document types.

Example

BOOL CMyApp::InitInstance()
{
   // ...

   CMultiDocTemplate* pDocTemplate;
   pDocTemplate = new CMultiDocTemplate(
      IDR_MYTYPE,
      RUNTIME_CLASS(CMyDoc),
      RUNTIME_CLASS(CMDIChildWnd),        // standard MDI child frame
      RUNTIME_CLASS(CMyView));
   AddDocTemplate(pDocTemplate);

   // Create main MDI Frame window.
   CMainFrame* pMainFrame = new CMainFrame;
   if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
      return FALSE;
   // Save the pointer to the main frame window.  This is the
   // only way the framework will have knowledge of what the
   // main frame window is.
   m_pMainWnd = pMainFrame;

   // enable file manager drag/drop and DDE Execute open
   EnableShellOpen();
   RegisterShellFileTypes();
   // ...

   // Show the   main window using the nCmdShow parameter
   // passed to the application when it was first launched.
   pMainFrame->ShowWindow(m_nCmdShow);
   pMainFrame->UpdateWindow();

   // ...
}

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnDDECommand, CWinApp::RegisterShellFileTypes


CWinApp::ExitInstance

virtual int ExitInstance( );

Return Value

The application’s exit code; 0 indicates no errors, and values greater than 0 indicate an error. This value is used as the return value from WinMain.

Remarks

Called by the framework from within the Run member function to exit this instance of the application.

Do not call this member function from anywhere but within the Run member function.

The default implementation of this function writes framework options to the application’s .INI file. Override this function to clean up when your application terminates.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::Run, CWinApp::InitInstance


CWinApp::GetFirstDocTemplatePosition

POSITION GetFirstDocTemplatePosition( ) const;

Return Value

A POSITION value that can be used for iteration or object pointer retrieval; NULL if the list is empty.

Remarks

Gets the position of the first document template in the application. Use the POSITION value returned in a call to GetNextDocTemplate to get the first CDocTemplate object.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::AddDocTemplate, CWinApp::GetNextDocTemplate


CWinApp::GetNextDocTemplate

CDocTemplate* GetNextDocTemplate( POSITION& pos ) const;

Return Value

A pointer to a CDocTemplate object.

Parameters

pos

A reference to a POSITION value returned by a previous call to GetNextDocTemplate or GetFirstDocTemplatePosition. The value is updated to the next position by this call.

Remarks

Gets the document template identified by pos, then sets pos to the POSITION value. You can use GetNextDocTemplate in a forward iteration loop if you establish the initial position with a call to GetFirstDocTemplatePosition.

You must ensure that your POSITION value is valid. If it is invalid, then the Debug version of the Microsoft Foundation Class Library asserts.

If the retrieved document template is the last available, then the new value of pos is set to NULL.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::AddDocTemplate, CWinApp::GetFirstDocTemplatePosition


CWinApp::GetPrinterDeviceDefaults

BOOL GetPrinterDeviceDefaults( PRINTDLG* pPrintDlg );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pPrintDlg

A pointer to a PRINTDLG structure.

Remarks

Call this member function to prepare a printer device context for printing. Retrieves the current printer defaults from the Windows .INI file as necessary, or uses the last printer configuration set by the user in Print Setup.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CPrintDialog


CWinApp::GetProfileInt

UINT GetProfileInt( LPCTSTR lpszSection, LPCTSTR lpszEntry, int nDefault );

Return Value

The integer value of the string that follows the specified entry if the function is successful. The return value is the value of the nDefault parameter if the function does not find the entry. The return value is 0 if the value that corresponds to the specified entry is not an integer.

This member function supports hexadecimal notation for the value in the .INI file. When you retrieve a signed integer, you should cast the value into an int.

Parameters

lpszSection

Points to a null-terminated string that specifies the section containing the entry.

lpszEntry

Points to a null-terminated string that contains the entry whose value is to be retrieved.

nDefault

Specifies the default value to return if the framework cannot find the entry. This value can be an unsigned value in the range 0 through 65,535 or a signed value in the range –32,768 through 32,767.

Remarks

Call this member function to retrieve the value of an integer from an entry within a specified section of the application’s registry or .INI file.

The entries are stored as follows:

  • In Windows NT, the value is stored to a registry key.

  • In Windows 3.x, the value is stored in the WIN.INI file.

  • In Windows 95, the value is stored in a cached version of WIN.INI.

This member function is not case sensitive, so the strings in the lpszSection and lpszEntry parameters may differ in case.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::GetProfileString, CWinApp::WriteProfileInt, ::GetPrivateProfileInt


CWinApp::GetProfileString

CString GetProfileString( LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszDefault = NULL );

Return Value

The return value is the string from the application’s .INI file or lpszDefault if the string cannot be found. The maximum string length supported by the framework is _MAX_PATH. If lpszDefault is NULL, the return value is an empty string.

Parameters

lpszSection

Points to a null-terminated string that specifies the section containing the entry.

lpszEntry

Points to a null-terminated string that contains the entry whose string is to be retrieved. This value must not be NULL.

lpszDefault

Points to the default string value for the given entry if the entry cannot be found in the initialization file.

Remarks

Call this member function to retrieve the string associated with an entry within the specified section in the application’s registry or .INI file.

The entries are stored as follows:

  • In Windows NT, the value is stored to a registry key.

  • In Windows 3.x, the value is stored in the WIN.INI file.

  • In Windows 95, the value is stored in a cached version of WIN.INI.

Example

   CString strSection       = "My Section";
   CString strStringItem    = "My String Item";
   CString strIntItem       = "My Int Item";

   CWinApp* pApp = AfxGetApp();

   pApp->WriteProfileString(strSection, strStringItem, "test");

   CString strValue;
   strValue = pApp->GetProfileString(strSection, strStringItem);
   ASSERT(strValue == "test");

   pApp->WriteProfileInt(strSection, strIntItem, 1234);
   int nValue;
   nValue = pApp->GetProfileInt(strSection, strIntItem, 0);
   ASSERT(nValue == 1234);

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::GetProfileInt, CWinApp::WriteProfileString, ::GetPrivateProfileString


CWinApp::HideApplication

void HideApplication( );

Remarks

Call this member function to hide an application before closing the open documents.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::CloseAllDocuments


CWinApp::InitInstance

virtual BOOL InitInstance( );

Return Value

Nonzero if initialization is successful; otherwise 0.

Remarks

Windows allows several copies of the same program to run at the same time. Application initialization is conceptually divided into two sections: one-time application initialization that is done the first time the program runs, and instance initialization that runs each time a copy of the program runs, including the first time. The framework’s implementation of WinMain calls this function.

Override InitInstance to initialize each new instance of your application running under Windows. Typically, you override InitInstance to construct your main window object and set the CWinThread::m_pMainWnd data member to point to that window. For more information on overriding this member function, see CWinApp: The Application Class in Visual C++ Programmer’s Guide.

Example

// AppWizard implements the InitInstance overridable function
// according to options you select.  For example, the single document
// interface (SDI) option was chosen for the AppWizard code created
// below. You can add other per-instance initializations to the code
// created by AppWizard.

BOOL CMyApp::InitInstance()
{
   // Standard initialization
   // If you are not using these features and wish to reduce the size
   //  of your final executable, you should remove from the following
   //  the specific initialization routines you do not need.

   SetDialogBkColor();        // Set dialog background color to gray
   LoadStdProfileSettings();  // Load standard INI file options (including MRU)

   // Register the application's document templates.  Document templates
   //  serve as the connection between documents, frame windows and views.

   CSingleDocTemplate* pDocTemplate;
   pDocTemplate = new CSingleDocTemplate(
      IDR_MAINFRAME,
      RUNTIME_CLASS(CMyDoc),
      RUNTIME_CLASS(CMainFrame),     // main SDI frame window
      RUNTIME_CLASS(CMyView));
   AddDocTemplate(pDocTemplate);

   // create a new (empty) document
   OnFileNew();

   if (m_lpCmdLine[0] != '\0')
   {
      // TODO: add command line processing here
   }

   return TRUE;
}


CWinApp::LoadCursor

HCURSOR LoadCursor( LPCTSTR lpszResourceName ) const;

HCURSOR LoadCursor( UINT nIDResource ) const;

Return Value

A handle to a cursor if successful; otherwise NULL.

Parameters

lpszResourceName

Points to a null-terminated string that contains the name of the cursor resource. You can use a CString for this argument.

nIDResource

ID of the cursor resource. For a list of resources, see ::LoadCursor in the Platform SDK.

Remarks

Loads the cursor resource named by lpszResourceName or specified by nIDResource from the current executable file. LoadCursor loads the cursor into memory only if it has not been previously loaded; otherwise, it retrieves a handle of the existing resource.

Use the LoadStandardCursor or LoadOEMCursor member function to access the predefined Windows cursors.

Example

HCURSOR hCursor;

   // Load a cursor resource that was originally created using
   // the Graphics Editor and assigned the i.d. IDC_MYCURSOR.
   hCursor = AfxGetApp()->LoadCursor(IDC_MYCURSOR);

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadStandardCursor, CWinApp::LoadOEMCursor, ::LoadCursor


CWinApp::LoadIcon

HICON LoadIcon( LPCTSTR lpszResourceName ) const;

HICON LoadIcon( UINT nIDResource ) const;

Return Value

A handle to an icon if successful; otherwise NULL.

Parameters

lpszResourceName

Points to a null-terminated string that contains the name of the icon resource. You can also use a CString for this argument.

nIDResource

ID number of the icon resource.

Remarks

Loads the icon resource named by lpszResourceName or specified by nIDResource from the executable file. LoadIcon loads the icon only if it has not been previously loaded; otherwise, it retrieves a handle of the existing resource.

You can use the LoadStandardIcon or LoadOEMIcon member function to access the predefined Windows icons.

Note This member function calls the Win32 API function LoadIcon, which can only load an icon whose size conforms to the SM_CXICON and SM_CYICON system metric values.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadStandardIcon, CWinApp::LoadOEMIcon, ::LoadIcon


CWinApp::LoadOEMCursor

HCURSOR LoadOEMCursor( UINT nIDCursor ) const;

Return Value

A handle to a cursor if successful; otherwise NULL.

Parameters

nIDCursor

An OCR_ manifest constant identifier that specifies a predefined Windows cursor. You must have #define OEMRESOURCE before #include <afxwin.h> to gain access to the OCR_ constants in WINDOWS.H.

Remarks

Loads the Windows predefined cursor resource specified by nIDCursor.

Use the LoadOEMCursor or LoadStandardCursor member function to access the predefined Windows cursors.

Example

// In the stdafx.h file, add #define OEMRESOURCE to
// include the windows.h definitions of OCR_ values.
#define OEMRESOURCE
#include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions (including VB)

   HCURSOR hCursor;
   // Load the predefined WIndows "size all" cursor.
   hCursor = AfxGetApp()->LoadOEMCursor(OCR_SIZEALL);

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadCursor, CWinApp::LoadStandardCursor, ::LoadCursor


CWinApp::LoadOEMIcon

HICON LoadOEMIcon( UINT nIDIcon ) const;

Return Value

A handle to an icon if successful; otherwise NULL.

Parameters

nIDIcon

An OIC_ manifest constant identifier that specifies a predefined Windows icon. You must have #define OEMRESOURCE before #include <afxwin.h> to access the OIC_ constants in WINDOWS.H.

Remarks

Loads the Windows predefined icon resource specified by nIDIcon.

Use the LoadOEMIcon or LoadStandardIcon member function to access the predefined Windows icons.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadStandardIcon, CWinApp::LoadIcon, ::LoadIcon


CWinApp::LoadStandardCursor

HCURSOR LoadStandardCursor( LPCTSTR lpszCursorName ) const;

Return Value

A handle to a cursor if successful; otherwise NULL.

Parameters

lpszCursorName

An IDC_ manifest constant identifier that specifies a predefined Windows cursor. These identifiers are defined in WINDOWS.H. The following list shows the possible predefined values and meanings for lpszCursorName:

  • IDC_ARROW Standard arrow cursor

  • IDC_IBEAM Standard text-insertion cursor

  • IDC_WAIT Hourglass cursor used when Windows performs a time-consuming task

  • IDC_CROSS Cross-hair cursor for selection

  • IDC_UPARROW Arrow that points straight up

  • IDC_SIZE Obsolete and unsupported; use IDC_SIZEALL

  • IDC_SIZEALL A four-pointed arrow. The cursor to use to resize a window.

  • IDC_ICON Obsolete and unsupported. Use IDC_ARROW.

  • IDC_SIZENWSE Two-headed arrow with ends at upper left and lower right

  • IDC_SIZENESW Two-headed arrow with ends at upper right and lower left

  • IDC_SIZEWE Horizontal two-headed arrow

  • IDC_SIZENS Vertical two-headed arrow

Remarks

Loads the Windows predefined cursor resource that lpszCursorName specifies.

Use the LoadStandardCursor or LoadOEMCursor member function to access the predefined Windows cursors.

Example

HCURSOR hCursor;

   // Load the predefined Windows "up arrow" cursor.
   hCursor = AfxGetApp()->LoadStandardCursor(IDC_UPARROW);

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadOEMCursor, CWinApp::LoadCursor, ::LoadCursor


CWinApp::LoadStandardIcon

HICON LoadStandardIcon( LPCTSTR lpszIconName ) const;

Return Value

A handle to an icon if successful; otherwise NULL.

Parameters

lpszIconName

A manifest constant identifier that specifies a predefined Windows icon. These identifiers are defined in WINDOWS.H. The following list shows the possible predefined values and meanings for lpszIconName:

  • IDI_APPLICATION Default application icon

  • IDI_HAND Hand-shaped icon used in serious warning messages

  • IDI_QUESTION Question-mark shape used in prompting messages

  • IDI_EXCLAMATION Exclamation point shape used in warning messages

  • IDI_ASTERISK Asterisk shape used in informative messages

Remarks

Loads the Windows predefined icon resource that lpszIconName specifies.

Use the LoadStandardIcon or LoadOEMIcon member function to access the predefined Windows icons.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadOEMIcon, CWinApp::LoadIcon, ::LoadIcon


CWinApp::LoadStdProfileSettings

void LoadStdProfileSettings( UINT nMaxMRU = _AFX_MRU_COUNT );

Parameters

nMaxMRU

The number of recently used files to track.

Remarks

Call this member function from within the InitInstance member function to enable and load the list of most recently used (MRU) files and last preview state. If nMaxMRU is 0, no MRU list will be maintained.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnFileOpen, CWinApp::AddToRecentFileList


CWinApp::OnContextHelp

afx_msg void OnContextHelp( );

Remarks

You must add an

ON_COMMAND( ID_CONTEXT_HELP, OnContextHelp )

statement to your CWinApp class message map and also add an accelerator table entry, typically SHIFT+F1, to enable this member function.

OnContextHelp puts the application into Help mode. The cursor changes to an arrow and a question mark, and the user can then move the mouse pointer and press the left mouse button to select a dialog box, window, menu, or command button. This member function retrieves the Help context of the object under the cursor and calls the Windows function WinHelp with that Help context.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnHelp, CWinApp::WinHelp


CWinApp::OnDDECommand

virtual BOOL OnDDECommand( LPTSTR lpszCommand );

Return Value

Nonzero if the command is handled; otherwise 0.

Parameters

lpszCommand

Points to a DDE command string received by the application.

Remarks

Called by the framework when the main frame window receives a DDE execute message. The default implementation checks whether the command is a request to open a document and, if so, opens the specified document. The Windows File Manager usually sends such DDE command strings when the user double-clicks a data file. Override this function to handle other DDE execute commands, such as the command to print.

Example

BOOL CMyApp::OnDDECommand(LPTSTR lpszCommand)
{
   if (CWinApp::OnDDECommand(lpszCommand))
      return TRUE;

   // Handle any DDE commands recognized by your application
   // and return TRUE.  See implementation of CWinApp::OnDDEComand
   // for example of parsing the DDE command string.

   // Return FALSE for any DDE commands you do not handle.
   return FALSE;
 }

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::EnableShellOpen


CWinApp::OnFileNew

afx_msg void OnFileNew( );

Remarks

You must add an

ON_COMMAND( ID_FILE_NEW, OnFileNew )

statement to your CWinApp class message map to enable this member function.

If enabled, this function handles execution of the File New command.

See Technical Note 22 for information on default behavior and guidance on how to override this member function.

Example

// The following message map, produced by AppWizard, binds the
// File New, Open, and Print Setup menu commands to default
// framework implementations of these commands.
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
   //{{AFX_MSG_MAP(CMyApp)
   ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
      // NOTE - the ClassWizard will add and remove mapping macros here.
      //    DO NOT EDIT what you see in these blocks of generated code!
   //}}AFX_MSG_MAP
   // Standard file based document commands
   ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
   ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
   // Standard print setup command
   ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()

// The following message map illustrates how to rebind the
// File New, Open and Print Setup menu commands to handlers that
// you implement in your CWinApp-derived class.  You can use
// ClassWizard to bind the commands, as illustrated below, since
// the message map entries are bracketed by //{{AFX_MSG_MAP
// and //}}AFX_MSG_MAP.  Note, you can name the handler
// CMyApp::OnFileNew instead of CMyApp::OnMyFileNew, and likewise
// for the other handlers, if desired.
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
   //{{AFX_MSG_MAP(CMyApp)
   ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
   ON_COMMAND(ID_FILE_NEW, OnMyFileNew)
   ON_COMMAND(ID_FILE_OPEN, OnMyFileOpen)
   ON_COMMAND(ID_FILE_PRINT_SETUP, OnMyFilePrintSetup)
   //}}AFX_MSG_MAP
END_MESSAGE_MAP()

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnFileOpen


CWinApp::OnFileOpen

afx_msg void OnFileOpen( );

Remarks

You must add an

ON_COMMAND( ID_FILE_OPEN, OnFileOpen )

statement to your CWinApp class message map to enable this member function.

If enabled, this function handles execution of the File Open command.

For information on default behavior and guidance on how to override this member function, see Technical Note 22.

Example

// The following message map, produced by AppWizard, binds the
// File New, Open, and Print Setup menu commands to default
// framework implementations of these commands.
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
   //{{AFX_MSG_MAP(CMyApp)
   ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
      // NOTE - the ClassWizard will add and remove mapping macros here.
      //    DO NOT EDIT what you see in these blocks of generated code!
   //}}AFX_MSG_MAP
   // Standard file based document commands
   ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
   ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
   // Standard print setup command
   ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()

// The following message map illustrates how to rebind the
// File New, Open and Print Setup menu commands to handlers that
// you implement in your CWinApp-derived class.  You can use
// ClassWizard to bind the commands, as illustrated below, since
// the message map entries are bracketed by //{{AFX_MSG_MAP
// and //}}AFX_MSG_MAP.  Note, you can name the handler
// CMyApp::OnFileNew instead of CMyApp::OnMyFileNew, and likewise
// for the other handlers, if desired.
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
   //{{AFX_MSG_MAP(CMyApp)
   ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
   ON_COMMAND(ID_FILE_NEW, OnMyFileNew)
   ON_COMMAND(ID_FILE_OPEN, OnMyFileOpen)
   ON_COMMAND(ID_FILE_PRINT_SETUP, OnMyFilePrintSetup)
   //}}AFX_MSG_MAP
END_MESSAGE_MAP()

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnFileNew


CWinApp::OnFilePrintSetup

afx_msg void OnFilePrintSetup( );

Remarks

You must add an

ON_COMMAND( ID_FILE_PRINT_SETUP, OnFilePrintSetup )

statement to your CWinApp class message map to enable this member function.

If enabled, this function handles execution of the File Print command.

For information on default behavior and guidance on how to override this member function, see Technical Note 22.

Example

// The following message map, produced by AppWizard, binds the
// File New, Open, and Print Setup menu commands to default
// framework implementations of these commands.
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
   //{{AFX_MSG_MAP(CMyApp)
   ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
      // NOTE - the ClassWizard will add and remove mapping macros here.
      //    DO NOT EDIT what you see in these blocks of generated code!
   //}}AFX_MSG_MAP
   // Standard file based document commands
   ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
   ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
   // Standard print setup command
   ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()

// The following message map illustrates how to rebind the
// File New, Open and Print Setup menu commands to handlers that
// you implement in your CWinApp-derived class.  You can use
// ClassWizard to bind the commands, as illustrated below, since
// the message map entries are bracketed by //{{AFX_MSG_MAP
// and //}}AFX_MSG_MAP.  Note, you can name the handler
// CMyApp::OnFileNew instead of CMyApp::OnMyFileNew, and likewise
// for the other handlers, if desired.
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
   //{{AFX_MSG_MAP(CMyApp)
   ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
   ON_COMMAND(ID_FILE_NEW, OnMyFileNew)
   ON_COMMAND(ID_FILE_OPEN, OnMyFileOpen)
   ON_COMMAND(ID_FILE_PRINT_SETUP, OnMyFilePrintSetup)
   //}}AFX_MSG_MAP
END_MESSAGE_MAP()

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnFileNew


CWinApp::OnHelp

afx_msg void OnHelp( );

Remarks

You must add an

ON_COMMAND( ID_HELP, OnHelp )

statement to your CWinApp class message map to enable this member function. Usually you will also add an accelerator-key entry for the F1 key. Enabling the F1 key is only a convention, not a requirement.

If enabled, called by the framework when the user presses the F1 key.

The default implementation of this message-handler function determines the Help context that corresponds to the current window, dialog box, or menu item and then calls WINHELP.EXE. If no context is currently available, the function uses the default context.

Override this member function to set the Help context to something other than the window, dialog box, menu item, or toolbar button that currently has the focus. Call WinHelp with the desired Help context ID.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnContextHelp, CWinApp::OnHelpUsing, CWinApp::OnHelpIndex, CWinApp::WinHelp


CWinApp::OnHelpFinder

afx_msg void OnHelpFinder( );

Remarks

You must add an

ON_COMMAND( ID_HELP_FINDER, OnHelpFinder )

statement to your CWinApp class message map to enable this member function.

If enabled, the framework calls this message-handler function when the user of your application selects the Help Finder command to invoke WinHelp with the standard HELP_FINDER topic.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnHelp, CWinApp::OnHelpUsing, CWinApp::WinHelp, CWinApp::OnHelpIndex


CWinApp::OnHelpIndex

afx_msg void OnHelpIndex( );

Remarks

You must add an

ON_COMMAND( ID_HELP_INDEX, OnHelpIndex )

statement to your CWinApp class message map to enable this member function.

If enabled, the framework calls this message-handler function when the user of your application selects the Help Index command to invoke WinHelp with the standard HELP_INDEX topic.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnHelp, CWinApp::OnHelpUsing, CWinApp::WinHelp


CWinApp::OnHelpUsing

afx_msg void OnHelpUsing( );

Remarks

You must add an

ON_COMMAND( ID_HELP_USING, OnHelpUsing )

statement to your CWinApp class message map to enable this member function.

The framework calls this message-handler function when the user of your application selects the Help Using command to invoke the WinHelp application with the standard HELP_HELPONHELP topic.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnHelp, CWinApp::OnHelpIndex, CWinApp::WinHelp


CWinApp::OnIdle

virtual BOOL OnIdle( LONG lCount );

Return Value

Nonzero to receive more idle processing time; 0 if no more idle time is needed.

Parameters

lCount

A counter incremented each time OnIdle is called when the application’s message queue is empty. This count is reset to 0 each time a new message is processed. You can use the lCount parameter to determine the relative length of time the application has been idle without processing a message.

Remarks

Override this member function to perform idle-time processing. OnIdle is called in the default message loop when the application’s message queue is empty. Use your override to call your own background idle-handler tasks.

OnIdle should return 0 to indicate that no idle processing time is required. The lCount parameter is incremented each time OnIdle is called when the message queue is empty and resets to 0 each time a new message is processed. You can call your different idle routines based on this count.

The following summarizes idle loop processing:

  1. If the message loop in the Microsoft Foundation Class Library checks the message queue and finds no pending messages, it calls OnIdle for the application object and supplies 0 as the lCount argument.

  2. OnIdle performs some processing and returns a nonzero value to indicate it should be called again to do further processing.

  3. The message loop checks the message queue again. If no messages are pending, it calls OnIdle again, incrementing the lCount argument.

  4. Eventually, OnIdle finishes processing all its idle tasks and returns 0. This tells the message loop to stop calling OnIdle until the next message is received from the message queue, at which point the idle cycle restarts with the argument set to 0.

Do not perform lengthy tasks during OnIdle because your application cannot process user input until OnIdle returns.

Note The default implementation of OnIdle updates command user-interface objects such as menu items and toolbar buttons, and it performs internal data structure cleanup. Therefore, if you override OnIdle, you must call CWinApp::OnIdle with the lCount in your overridden version. First call all base-class idle processing (that is, until the base class OnIdle returns 0). If you need to perform work before the base-class processing completes, review the base-class implementation to select the proper lCount during which to do your work.

Example

The following two examples show how to use OnIdle. The first example processes two idle tasks using the lCount argument to prioritize the tasks. The first task is high priority, and you should do it whenever possible. The second task is less important and should be done only when there is a long pause in user input. Note the call to the base-class version of OnIdle. The second example manages a group of idle tasks with different priorities.

BOOL CMyApp::OnIdle(LONG lCount)
{
    BOOL bMore = CWinApp::OnIdle(lCount);

    if (lCount == 0)
    {
    TRACE("App idle for short period of time\n");
    bMore = TRUE;
    }
    else if (lCount == 10)
    {
    TRACE("App idle for longer amount of time\n");
        bMore = TRUE;
    }
    else if (lCount == 100)
    {
        TRACE("App idle for even longer amount of time\n");
        bMore = TRUE;
    }
    else if (lCount == 1000)
    {
        TRACE("App idle for quite a long period of time\n");
     // bMore is not set to TRUE, no longer need idle
     // IMPORTANT: bMore is not set to FALSE since CWinApp::OnIdle may
     // have more idle tasks to complete.
    }

    return bMore;
     // return TRUE as long as there is any more idle tasks
}

Second Example

// In this example, four idle loop tasks are given various
// opportunities to run:
// Task1 is always given a chance to run during idle time, provided
//   that no message has queued up while the framework was processing
//   its own idle loop tasks (at lCount levels 0 and 1).
// Task2 is given a chance to run only if Task1 has already run,
//   provided that no message has queued up while Task1 was running.
// Task3 and Task4 are given a chance to run only if both Task1 and
//   Task2 have already run, and no message has queued up in the mean
//   time.  If Task3 gets its chance to run, then Task4 always gets
//   a chance to run immediately after Task3.

BOOL CMyApp::OnIdle(LONG lCount)
{
   // In this example, as in most applications, you should let the
   // base class CWinApp::OnIdle complete its processing before you
   // attempt any additional idle loop processing.
   if (CWinApp::OnIdle(lCount))
      return TRUE;

   // The base class CWinApp::OnIdle reserves the lCount values 0
   // and 1 for the framework's own idle processing.   If you wish to
   // share idle processing time at a peer level with the framework,
   // then replace the above if-statement with a straight call to
   // CWinApp::OnIdle; and then add a case statement for lCount value
   // 0 and/or 1. Study the base class implementation first to
   // understand how your idle loop tasks will compete with the
   // framework's idle loop processing.

   switch (lCount)
   {
      case 2:
         Task1();
         return TRUE; // next time give Task2 a chance
      case 3:
         Task2();
         return TRUE; // next time give Task3 and Task4 a chance
      case 4:
         Task3();
         Task4();
         return FALSE; // cycle through the idle loop tasks again
   }
   return FALSE;
}


CWinApp::OpenDocumentFile

virtual CDocument* OpenDocumentFile( LPCTSTR lpszFileName );

Return Value

A pointer to a CDocument if successful; otherwise NULL.

Parameters

lpszFileName

The name of the file to be opened.

Remarks

The framework calls this member function to open the named CDocument file for the application. If a document with that name is already open, the first frame window that contains that document will be activated. If an application supports multiple document templates, the framework uses file extension to find the appropriate document template to attempt to load the document. If successful, the document template then creates a frame window and view for the document.

Example

BOOL CMyApp::InitInstance()
{
   // ...
   if (m_lpCmdLine[0] == '\0')
   {
      // Create a new (empty) document.
      OnFileNew();
   }
   else
   {
      // Open a file passed as the first command line parameter.
      OpenDocumentFile(m_lpCmdLine);
   }

   // ...
}


CWinApp::ParseCommandLine

void ParseCommandLine( CCommandLineInfo& rCmdInfo );

Parameters

rCmdInfo

A reference to a CCommandLineInfo object.

Remarks

Call this member function to parse the command line and send the parameters, one at a time, to CCommandLineInfo::ParseParam.

When you start a new MFC project using AppWizard, AppWizard will create a local instance of CCommandLineInfo, and then call ProcessShellCommand and ParseCommandLine in the InitInstance member function. A command line follows the route described below:

  1. After being created in InitInstance, the CCommandLineInfo object is passed to ParseCommandLine.

  2. ParseCommandLine then calls CCommandLineInfo::ParseParam repeatedly, once for each parameter.

  3. ParseParam fills the CCommandLineInfo object, which is then passed to ProcessShellCommand.

  4. ProcessShellCommand handles the command-line arguments and flags.

Note that you can call ParseCommandLine directly as needed.

For a description of the command-line flags, see CCommandLineInfo::m_nShellCommand.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CCommandLineInfo, CWinApp::InitInstance, CCommandLineInfo::ParseParam, CWinApp::ProcessShellCommand, CCommandLineInfo::m_nShellCommand


CWinApp::PreTranslateMessage

virtual BOOL PreTranslateMessage( MSG* pMsg );

Return Value

Nonzero if the message was fully processed in PreTranslateMessage and should not be processed further. Zero if the message should be processed in the normal way.

Parameters

pMsg

A pointer to a MSG structure that contains the message to process.

Remarks

Override this function to filter window messages before they are dispatched to the Windows functions TranslateMessage and DispatchMessage The default implementation performs accelerator-key translation, so you must call the CWinApp::PreTranslateMessage member function in your overridden version.

CWinApp Overview | Class Members | Hierarchy Chart

See Also ::DispatchMessage, ::TranslateMessage


CWinApp::ProcessMessageFilter

virtual BOOL ProcessMessageFilter( int code, LPMSG lpMsg );

Return Value

Nonzero if the message is processed; otherwise 0.

Parameters

code

Specifies a hook code. This member function uses the code to determine how to process lpMsg.

lpMsg

A pointer to a Windows MSG structure.

Remarks

The framework’s hook function calls this member function to filter and respond to certain Windows messages. A hook function processes events before they are sent to the application’s normal message processing.

If you override this advanced feature, be sure to call the base-class version to maintain the framework’s hook processing.

CWinApp Overview | Class Members | Hierarchy Chart

See Also MessageProc, WH_MSGFILTER


CWinApp::ProcessShellCommand

BOOL ProcessShellCommand( CCommandLineInfo& rCmdInfo );

Return Value

Nonzero if the shell command is processed successfully. If 0, return FALSE from InitInstance.

Parameters

rCmdInfo

A reference to a CCommandLineInfo object.

Remarks

This member function is called by InitInstance to accept the parameters passed from the CCommandLineInfo object identified by rCmdInfo, and perform the indicated action.

When you start a new MFC project using AppWizard, AppWizard will create a local instance of CCommandLineInfo, and then call ProcessShellCommand and ParseCommandLine in the InitInstance member function. A command line follows the route described below:

  1. After being created in InitInstance, the CCommandLineInfo object is passed to ParseCommandLine.

  2. ParseCommandLine then calls CCommandLineInfo::ParseParam repeatedly, once for each parameter.

  3. ParseParam fills the CCommandLineInfo object, which is then passed to ProcessShellCommand.

  4. ProcessShellCommand handles the command-line arguments and flags.

The data members of the CCommandLineInfo object, identified by CCommandLineInfo::m_nShellCommand, are of the following enumerated type, which is defined within the CCommandLineInfo class.

enum{
   FileNew,
   FileOpen,
   FilePrint,
   FilePrintTo,
   FileDDE,
};

For a brief description of each of these values, see CCommandLineInfo::m_nShellCommand.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::ParseCommandLine, CCommandLineInfo, CCommandLineInfo::ParseParam, CCommandLineInfo::m_nShellCommand


CWinApp::ProcessWndProcException

virtual LRESULT ProcessWndProcException( CException* e, const MSG* pMsg );

Return Value

The value that should be returned to Windows. Normally this is 0L for windows messages, 1L (TRUE) for command messages.

Parameters

e

A pointer to an uncaught exception.

pMsg

A MSG structure that contains information about the windows message that caused the framework to throw an exception.

Remarks

The framework calls this member function whenever the handler does not catch an exception thrown in one of your application’s message or command handlers.

Do not call this member function directly.

The default implementation of this member function creates a message box. If the uncaught exception originates with a menu, toolbar, or accelerator command failure, the message box displays a “Command failed” message; otherwise, it displays an “Internal application error” message.

Override this member function to provide global handling of your exceptions. Only call the base functionality if you wish the message box to be displayed.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWnd::WindowProc, CException


CWinApp::RegisterShellFileTypes

void RegisterShellFileTypes( BOOL bCompat = FALSE );

Parameters

bCompat

TRUE adds registration entries for shell commands Print and Print To, allowing a user to print files directly from the shell, or by dragging the file to a printer object. It also adds a DefaultIcon key. By default, this parameter is FALSE for backward compatibility.

Remarks

Call this member function to register all of your application’s document types with the Windows File Manager. This allows the user to open a data file created by your application by double-clicking it from within File Manager. Call RegisterShellFileTypes after you call AddDocTemplate for each of the document templates in your application. Also call the EnableShellOpen member function when you call RegisterShellFileTypes.

RegisterShellFileTypes iterates through the list of CDocTemplate objects that the application maintains and, for each document template, adds entries to the registration database that Windows maintains for file associations. File Manager uses these entries to open a data file when the user double-clicks it. This eliminates the need to ship a .REG file with your application.

If the registration database already associates a given filename extension with another file type, no new association is created. See the CDocTemplate class for the format of strings necessary to register this information.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CDocTemplate, CWinApp::EnableShellOpen, CWinApp::AddDocTemplate


CWinApp::Run

virtual int Run( );

Return Value

An int value that is returned by WinMain.

Remarks

Provides a default message loop. Run acquires and dispatches Windows messages until the application receives a WM_QUIT message. If the application’s message queue currently contains no messages, Run calls OnIdle to perform idle-time processing. Incoming messages go to the PreTranslateMessage member function for special processing and then to the Windows function TranslateMessage for standard keyboard translation; finally, the DispatchMessage Windows function is called.

Run is rarely overridden, but you can override it to provide special behavior.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::PreTranslateMessage, WM_QUIT, ::DispatchMessage, ::TranslateMessage


CWinApp::RunAutomated

BOOL RunAutomated( );

Return Value

Nonzero if the option was found; otherwise 0.

Remarks

Call this function to determine whether the “/Automation” or “-Automation” option is present, which indicates whether the server application was launched by a client application. If present, the option is removed from the command line. For more information on OLE Automation, see the article Automation Servers in Visual C++ Programmer’s Guide.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::RunEmbedded


CWinApp::RunEmbedded

BOOL RunEmbedded( );

Return Value

Nonzero if the option was found; otherwise 0.

Remarks

Call this function to determine whether the “/Embedding” or “-Embedding” option is present, which indicates whether the server application was launched by a client application. If present, the option is removed from the command line. For more information on embedding, see the article Servers: Implementing a Server in Visual C++ Programmer’s Guide.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::RunAutomated


CWinApp::SaveAllModified

virtual BOOL SaveAllModified( );

Return Value

Nonzero if safe to terminate the application; 0 if not safe to terminate the application.

Remarks

Called by the framework to save all documents when the application’s main frame window is to be closed, or through a WM_QUERYENDSESSION message.

The default implementation of this member function calls the CDocument::SaveModified member function in turn for all modified documents within the application.


CWinApp::SelectPrinter

void SelectPrinter( HANDLE hDevNames, HANDLE hDevMode, BOOL bFreeOld = TRUE );

Parameters

hDevNames

A handle to a DEVNAMES structure that identifies the driver, device, and output port names of a specific printer.

hDevMode

A handle to a DEVMODE structure that specifies information about the device initialization and environment of a printer.

bFreeOld

Frees the previously-selected printer.

Remarks

Call this member function to select a specific printer, and release the printer that was previously selected in the Print Dialog box.

If both hDevMode and hDevNames are NULL, SelectPrinter uses the current default printer.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CPrintDialog, DEVMODE, DEVNAMES


CWinApp::SetDialogBkColor

void SetDialogBkColor( COLORREF clrCtlBk = RGB(192, 192, 192), COLORREF clrCtlText = RGB(0, 0, 0) );

Parameters

clrCtlBk

The dialog background color for the application.

clrCtlText

The dialog control color for the application.

Remarks

Call this member function from within the InitInstance member function to set the default background and text color for dialog boxes and message boxes within your application.

Example

BOOL CMyApp::InitInstance()
{
   // Standard initialization

   SetDialogBkColor();        // Set dialog background color to gray
   LoadStdProfileSettings();  // Load standard INI file options (including MRU)

   // ...
}


CWinApp::SetRegistryKey

void SetRegistryKey( LPCTSTR lpszRegistryKey );

void SetRegistryKey( UINT nIDRegistryKey );

Parameters

lpszRegistryKey

Pointer to a string containing the name of the key.

nIDRegistryKey

ID/index of a key in the registry.

Remarks

Causes application settings to be stored in the registry instead of INI files. This function sets m_pszRegistryKey, which is then used by the GetProfileInt, GetProfileString, WriteProfileInt, and WriteProfileString member functions of CWinApp. If this function has been called, the list of most recently-used (MRU) files is also stored in the registry. The registry key is usually the name of a company. It is stored in a key of the following form: HKEY_CURRENT_USER\Software\<company name>\<application name>\<section name>\<value name>.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::InitInstance, CWinApp::GetProfileInt, CWinApp::GetProfileString, CWinApp::WriteProfileInt, CWinApp::WriteProfileString


CWinApp::WinHelp

virtual void WinHelp( DWORD dwData, UINT nCmd = HELP_CONTEXT );

Parameters

dwData

Specifies additional data. The value used depends on the value of the nCmd parameter.

nCmd

Specifies the type of help requested. For a list of possible values and how they affect the dwData parameter, see the WinHelp Windows function.

Remarks

Call this member function to invoke the WinHelp application. The framework also calls this function to invoke the WinHelp application.

The framework will automatically close the WinHelp application when your application terminates.

Example

// Header File: HELPIDS.H
//
// This example header file is #include'd twice:
// (1) It is #include'd by the .CPP file that passes the DWORD
//     context i.d. to CWinApp::WinHelp.
// (2) It is #include'd in the [MAP] section of the .HPJ file,
//     to associate the help context string "HID_MYTOPIC" with
//     the help context numeric i.d., 101.
// The help context string "HID_MYTOPIC" is what identifies the
// help topic in the help .RTF source file, in the "#" footnote:
//     # HID_MYTOPIC
//
// Note, it is not necessary to manage help context id's this way
// for help topics associated with command id's and user interface
// id's defined in your RESOURCE.H file; you should use the MAKEHM
// tool via the custom build rule on your resource.h file to produce
// a help map (.HM) file for these id's.  It is necessary to manage
// help context id's as illustrated here only for help topics not
// associated with command id's or user interface id's.

#define HID_MYTOPIC 101

   // Show the custom help topic that has the context string
   // "HID_MYTOPIC" in the help .RTF file, and which is mapped
   // to the DWORD i.d. HID_MYTOPIC in the above HELPIDS.H file.
   AfxGetApp()->WinHelp(HID_MYTOPIC);

// The following is one line of code in the help map (.HM)
// file produced by the MAKEHM tool, which is called by the custom
// build rule on the resource.h file.  The MAKEHM tool reads the
// following #define in the application's RESOURCE.H file:
//    #define ID_MYCOMMAND 0x08004
// and adds a help id offset value of 0x10000 to create the
// help context DWORD value 0x18004.  See MFC Tech Note 28
// for more information on help id offset values.

HID_MYCOMMAND                           0x18004

   // Rarely will you need to directly call WinHelp yourself
   // with the help context i.d. for a command or user interface
   // object. The framework will call WinHelp automatically when
   // the user, for example, hits F1 when the focus is on a
   // My Command menu item. However, if you do want to directly
   // call WinHelp for the help topic associated with the command,
   // here is how you would do it:

   AfxGetApp()->WinHelp(0x10000 + ID_MYCOMMAND);

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnContextHelp, CWinApp::OnHelpUsing, CWinApp::OnHelp, CWinApp::OnHelpIndex, ::WinHelp


CWinApp::WriteProfileInt

BOOL WriteProfileInt( LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszSection

Points to a null-terminated string that specifies the section containing the entry. If the section does not exist, it is created. The name of the section is case independent; the string may be any combination of uppercase and lowercase letters.

lpszEntry

Points to a null-terminated string that contains the entry into which the value is to be written. If the entry does not exist in the specified section, it is created.

nValue

Contains the value to be written.

Remarks

Call this member function to write the specified value into the specified section of the application’s registry or .INI file.

The entries are stored as follows:

  • In Windows NT, the value is stored to a registry key.

  • In Windows 3.x, the value is stored in the WIN.INI file.

  • In Windows 95, the value is stored in a cached version of WIN.INI.

Example

   CString strSection       = "My Section";
   CString strStringItem    = "My String Item";
   CString strIntItem       = "My Int Item";

   CWinApp* pApp = AfxGetApp();

   pApp->WriteProfileString(strSection, strStringItem, "test");

   CString strValue;
   strValue = pApp->GetProfileString(strSection, strStringItem);
   ASSERT(strValue == "test");

   pApp->WriteProfileInt(strSection, strIntItem, 1234);
   int nValue;
   nValue = pApp->GetProfileInt(strSection, strIntItem, 0);
   ASSERT(nValue == 1234);

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::GetProfileInt, CWinApp::WriteProfileString, CWinApp::SetRegistryKey


CWinApp::WriteProfileString

BOOL WriteProfileString( LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszValue );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszSection

Points to a null-terminated string that specifies the section containing the entry. If the section does not exist, it is created. The name of the section is case independent; the string may be any combination of uppercase and lowercase letters.

lpszEntry

Points to a null-terminated string that contains the entry into which the value is to be written. If the entry does not exist in the specified section, it is created.

lpszValue

Points to the string to be written. If this parameter is NULL, the entry specified by the lpszEntry parameter is deleted.

Remarks

Call this member function to write the specified string into the specified section of the application’s registry or .INI file.

The entries are stored as follows:

  • In Windows NT, the value is stored to a registry key.

  • In Windows 3.x, the value is stored in the WIN.INI file.

  • In Windows 95, the value is stored in a cached version of WIN.INI.

Example

   CString strSection       = "My Section";
   CString strStringItem    = "My String Item";
   CString strIntItem       = "My Int Item";

   CWinApp* pApp = AfxGetApp();

   pApp->WriteProfileString(strSection, strStringItem, "test");

   CString strValue;
   strValue = pApp->GetProfileString(strSection, strStringItem);
   ASSERT(strValue == "test");

   pApp->WriteProfileInt(strSection, strIntItem, 1234);
   int nValue;
   nValue = pApp->GetProfileInt(strSection, strIntItem, 0);
   ASSERT(nValue == 1234);

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::GetProfileString, CWinApp::WriteProfileInt, ::WritePrivateProfileString, CWinApp::SetRegistryKey


CWinApp::m_bHelpMode

Remarks

TRUE if the application is in Help context mode (conventionally invoked with SHIFT + F1); otherwise FALSE. In Help context mode, the cursor becomes a question mark and the user can move it about the screen. Examine this flag if you want to implement special handling when in the Help mode. m_bHelpMode is a public variable of type BOOL.


CWinApp::m_hInstance

Remarks

Corresponds to the hInstance parameter passed by Windows to WinMain. The m_hInstance data member is a handle to the current instance of the application running under Windows. This is returned by the global function AfxGetInstanceHandle. m_hInstance is a public variable of type HINSTANCE.

Example

   // Typically you do not need to pass the application's hInstance
   // to Windows APIs directly because there are equivalent MFC
   // member functions that pass the hInstance for you.  The following
   // example is not typical:

   HCURSOR hCursor;
   hCursor = ::LoadCursor(AfxGetApp()->m_hInstance,
      MAKEINTRESOURCE(IDC_MYCURSOR));

   // A more direct way to get the application's hInstance is to
   // call AfxGetInstanceHandle:
   hCursor = ::LoadCursor(AfxGetInstanceHandle(),
      MAKEINTRESOURCE(IDC_MYCURSOR));

   // If you need the hInstance to load a resource, it is better
   // to call AfxGetResourceHandle instead of AfxGetInstanceHandle:
   hCursor = ::LoadCursor(AfxGetResourceHandle(),
      MAKEINTRESOURCE(IDC_MYCURSOR));

   // A better way to load the cursor resource is to call
   // CWinApp::LoadCursor
   hCursor = AfxGetApp()->LoadCursor(IDC_MYCURSOR);


CWinApp::m_hPrevInstance

Remarks

Corresponds to the hPrevInstance parameter passed by Windows to WinMain.

The m_hPrevInstance data member is always set to NULL in a Win32 application. To find previous instances of an application, use CWnd::FindWindow.


CWinApp::m_lpCmdLine

Remarks

Corresponds to the lpCmdLine parameter passed by Windows to WinMain. Points to a null-terminated string that specifies the command line for the application. Use m_lpCmdLine to access any command-line arguments the user entered when the application was started. m_lpCmdLine is a public variable of type LPTSTR.

Example

BOOL CMyApp::InitInstance()
{
   // ...

   if (m_lpCmdLine[0] == _T('\0'))
   {
      // Create a new (empty) document.
      OnFileNew();
   }
   else
   {
      // Open a file passed as the first command line parameter.
      OpenDocumentFile(m_lpCmdLine);
   }

   // ...
}


CWinApp::m_nCmdShow

Remarks

Corresponds to the nCmdShow parameter passed by Windows to WinMain. You should pass m_nCmdShow as an argument when you call CWnd::ShowWindow for your application’s main window. m_nCmdShow is a public variable of type int.

Example

BOOL CMyApp::InitInstance()
{
   // ...

   // Create main MDI Frame window.
   CMainFrame* pMainFrame = new CMainFrame;
   if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
      return FALSE;
   // Save the pointer to the main frame window.  This is the
   // only way the framework will have knowledge of what the
   // main frame window is.
   m_pMainWnd = pMainFrame;

   // Show the   main window using the nCmdShow parameter
   // passed to the application when it was first launched.
   pMainFrame->ShowWindow(m_nCmdShow);
   pMainFrame->UpdateWindow();

   // ...
}


CWinApp::m_pActiveWnd

Remarks

Use this data member to store a pointer to the main window of the OLE container application that has your OLE server application in-place activated. If this data member is NULL, the application is not in-place active.

The framework sets this member variable when the frame window is in-place activated by an OLE container application.

CWinApp Overview | Class Members | Hierarchy Chart

See Also AfxGetMainWnd, CWinThread::m_pMainWnd


CWinApp::m_pszAppName

Remarks

Specifies the name of the application. The application name can come from the parameter passed to the CWinApp constructor, or, if not specified, to the resource string with the ID of AFX_IDS_APP_TITLE. If the application name is not found in the resource, it comes from the program’s .EXE filename.

Returned by the global function AfxGetAppName. m_pszAppName is a public variable of type const char*.

Note If you assign a value to m_pszAppName, it must be dynamically allocated on the heap. The CWinApp destructor calls free( ) with this pointer. You many want to use the _tcsdup( ) run-time library function to do the allocating. Also, free the memory associated with the current pointer before assigning a new value. For example:

//First free the string allocated by MFC at CWinApp startup.
//The string is allocated before InitInstance is called.
free((void*)m_pszAppName);
//Change the name of the application file.
//The CWinApp destructor will free the memory.
m_pszAppName=_tcsdup(_T(“d:\\somedir\\myapp.exe”));

Example

CWnd* pWnd;
   // Set pWnd to some CWnd object whose window has already
   // been created.

   // The following call to CWnd::MessageBox uses the application
   // title as the message box caption.
   pWnd->MessageBox("Some message", AfxGetApp()->m_pszAppName);

   // A more direct way to get the application title is to
   // call AfxGetAppName:
   pWnd->MessageBox("Some message", AfxGetAppName());

   // An easier way to display a message box using the application
   // title as the message box caption is to call AfxMessageBox:
   AfxMessageBox("Some message");


CWinApp::m_pszExeName

Remarks

Contains the name of the application’s executable file without an extension. Unlike m_pszAppName, this name cannot contain blanks. m_pszExeName is a public variable of type const char*.

Note If you assign a value to m_pszExeName, it must be dynamically allocated on the heap. The CWinApp destructor calls free( ) with this pointer. You many want to use the _tcsdup( ) run-time library function to do the allocating. Also, free the memory associated with the current pointer before assigning a new value. For example:

//First free the string allocated by MFC at CWinApp startup.
//The string is allocated before InitInstance is called.
free((void*)m_pszExeName);
//Change the name of the .EXE file.
//The CWinApp destructor will free the memory.
m_pszExeName=_tcsdup(_T(“d:\\somedir\\myapp”));


CWinApp::m_pszHelpFilePath

Remarks

Contains the path to the application’s Help file. By default, the framework initializes m_pszHelpFilePath to the name of the application with ".HLP" appended. To change the name of the help file, set m_pszHelpFilePath to point to a string that contains the complete name of the desired help file. A convenient place to do this is in the application's InitInstance function. m_pszHelpFilePath is a public variable of type const char*.

Note If you assign a value to m_pszHelpFilePath, it must be dynamically allocated on the heap. The CWinApp destructor calls free( ) with this pointer. You many want to use the _tcsdup( ) run-time library function to do the allocating. Also, free the memory associated with the current pointer before assigning a new value. For example:

//First free the string allocated by MFC at CWinApp startup.
//The string is allocated before InitInstance is called.
free((void*)m_pszHelpFilePath);
//Change the name of the .HLP file.
//The CWinApp destructor will free the memory.
m_pszHelpFilePath=_tcsdup(_T(“d:\\somedir\\myhelp.hlp”));


CWinApp::m_pszProfileName

Remarks

Contains the name of the application’s .INI file. m_pszProfileName is a public variable of type const char*.

Note If you assign a value to m_pszProfileName, it must be dynamically allocated on the heap. The CWinApp destructor calls free( ) with this pointer. You many want to use the _tcsdup( ) run-time library function to do the allocating. Also, free the memory associated with the current pointer before assigning a new value. For example:

//First free the string allocated by MFC at CWinApp startup.
//The string is allocated before InitInstance is called.
free((void*)m_pszProfileName);
//Change the name of the .INI file.
//The CWinApp destructor will free the memory.
m_pszProfileName=_tcsdup(_T(“d:\\somedir\\myini.ini”));

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::GetProfileString, CWinApp::GetProfileInt, CWinApp::WriteProfileInt, CWinApp::WriteProfileString


CWinApp::m_pszRegistryKey

LPCTSTR m_pszRegistryKey;

Remarks

Used to determine where, in the registry or INI file, application profile settings are stored. Normally, this data member is treated as read-only.

Registry entries are stored as follows:

  • In Windows NT, the value is stored to a registry key. The name for the application profile setting is appended to the following registry key: HKEY_CURRENT_USER/Software/LocalAppWizard-Generated/.

  • In Windows 3.x, the value is stored in the WIN.INI file.

  • In Windows 95, the value is stored in a cached version of WIN.INI.

If you assign a value to m_pszRegistryKey, it must be dynamically allocated on the heap. The CWinApp destructor calls free( ) with this pointer. You many want to use the _tcsdup( ) run-time library function to do the allocating. Also, free the memory associated with the current pointer before assigning a new value. For example:

//First free the string allocated by MFC at CWinApp startup.
//The string is allocated before InitInstance is called.
free((void*)m_pszRegistryKey);
//Change the name of the registry key.
//The CWinApp destructor will free the memory.
m_pszRegistryKey=_tcsdup(_T(“HKEY_CURRENT_USER\\Software\\mycompany\\myapp\\thissection\\thisvalue”));

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::SetRegistryKey


CWindowDC

The CWindowDC class is derived from CDC. It calls the Windows functions GetWindowDC at construction time and ReleaseDC at destruction time. This means that a CWindowDC object accesses the entire screen area of a CWnd (both client and nonclient areas).

For more information on using CWindowDC, see Device Contexts in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

See Also CDC


CWindowDC Class Members

Construction

CWindowDC Constructs a CWindowDC object.

Data Members

m_hWnd The HWND to which this CWindowDC is attached.


CWindowDC::CWindowDC

CWindowDC( CWnd* pWnd );
throw( CResourceException );

Parameters

pWnd

The window whose client area the device-context object will access.

Remarks

Constructs a CWindowDC object that accesses the entire screen area (both client and nonclient) of the CWnd object pointed to by pWnd. The constructor calls the Windows function GetWindowDC.

An exception (of type CResourceException) is thrown if the Windows GetWindowDC call fails. A device context may not be available if Windows has already allocated all of its available device contexts. Your application competes for the five common display contexts available at any given time under Windows.

CWindowDC Overview | Class Members | Hierarchy Chart

See Also CDC, CClientDC, CWnd


CWindowDC::m_hWnd

Remarks

The HWND of the CWnd pointer is used to construct the CWindowDC object. m_hWnd is a protected variable of type HWND.


CWinThread

A CWinThread object represents a thread of execution within an application. The main thread of execution is usually provided by an object derived from CWinApp; CWinApp is derived from CWinThread. Additional CWinThread objects allow multiple threads within a given application.

There are two general types of threads that CWinThread supports: worker threads and user-interface threads. Worker threads have no message pump: for example, a thread that performs background calculations in a spreadsheet application. User-interface threads have a message pump and process messages received from the system. CWinApp and classes derived from it are examples of user-interface threads. Other user-interface threads can also be derived directly from CWinThread.

Objects of class CWinThread typically exist for the duration of the thread. If you wish to modify this behavior, set m_bAutoDelete to FALSE.

The CWinThread class is necessary to make your code and MFC fully thread-safe. Thread-local data used by the framework to maintain thread-specific information is managed by CWinThread objects. Because of this dependence on CWinThread to handle thread-local data, any thread that uses MFC must be created by MFC. For example, a thread created by the run-time function _beginthreadex cannot use any MFC APIs.

To create a thread, call AfxBeginThread. There are two forms, depending on whether you want a worker or user-interface thread. If you want a user-interface thread, pass to AfxBeginThread a pointer to the CRuntimeClass of your CWinThread-derived class. If you want to create a worker thread, pass to AfxBeginThread a pointer to the controlling function and the parameter to the controlling function. For both worker threads and user-interface threads, you can specify optional parameters that modify priority, stack size, creation flags, and security attributes. AfxBeginThread will return a pointer to your new CWinThread object.

Instead of calling AfxBeginThread, you can construct a CWinThread-derived object and then call CreateThread. This two-stage construction method is useful if you want to reuse the CWinThread object between successive creation and terminations of thread executions.

For more information on CWinThread, see the articles Multithreading with C++ and MFC, Multithreading: Creating User-Interface Threads, Multithreading: Creating Worker Threads, and Multithreading: How to Use the Synchronization Classes in Visual C++ Programmer’s Guide.

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample MTGDI

See Also CWinApp, CCmdTarget


CWinThread Class Members

Data Members

m_bAutoDelete | Specifies whether to destroy the object at thread termination.
m_hThread | Handle to the current thread.
m_nThreadID | ID of the current thread.
m_pMainWnd | Holds a pointer to the application’s main window.
m_pActiveWnd | Pointer to the main window of the container application when an OLE server is in-place active.

Construction

CWinThread | Constructs a CWinThread object.
CreateThread | Starts execution of a CWinThread object.

Operations

GetMainWnd | Retrieves a pointer to the main window for the thread.
GetThreadPriority | Gets the priority of the current thread.
PostThreadMessage | Posts a message to another CWinThread object.
ResumeThread | Decrements a thread’s suspend count.
SetThreadPriority | Sets the priority of the current thread.
SuspendThread | Increments a thread’s suspend count.

Overridables

ExitInstance | Override to clean up when your thread terminates.
InitInstance | Override to perform thread instance initialization.
OnIdle | Override to perform thread-specific idle-time processing.
PreTranslateMessage | Filters messages before they are dispatched to the Windows functions TranslateMessage and DispatchMessage.
IsIdleMessage | Checks for special messages.
ProcessWndProcException | Intercepts all unhandled exceptions thrown by the thread’s message and command handlers.
ProcessMessageFilter | Intercepts certain messages before they reach the application.
Run | Controlling function for threads with a message pump. Override to customize the default message loop.


CWinThread::CreateThread

BOOL CreateThread( DWORD dwCreateFlags = 0, UINT nStackSize = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );

Return Value

Nonzero if the thread is created successfully; otherwise 0.

Parameters

dwCreateFlags

Specifies an additional flag that controls the creation of the thread. This flag can contain one of two values:

  • CREATE_SUSPENDED Start the thread with a suspend count of one. The thread will not execute until ResumeThread is called.

  • 0 Start the thread immediately after creation.

nStackSize

Specifies the size in bytes of the stack for the new thread. If 0, the stack size defaults to the same size as that of the process’s primary thread.

lpSecurityAttrs

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the thread.

Remarks

Creates a thread to execute within the address space of the calling process. Use AfxBeginThread to create a thread object and execute it in one step. Use CreateThread if you want to reuse the thread object between successive creation and termination of thread executions.

CWinThread Overview | Class Members | Hierarchy Chart

See Also AfxBeginThread, CWinThread::CWinThread, ::CreateThread


CWinThread::CWinThread

CWinThread( );

Remarks

Constructs a CWinThread object. To begin the thread’s execution, call the CreateThread member function. You will usually create threads by calling AfxBeginThread, which will call this constructor and CreateThread.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinThread::CreateThread


CWinThread::ExitInstance

virtual int ExitInstance( );

Return Value

The thread’s exit code; 0 indicates no errors, and values greater than 0 indicate an error. This value can be retrieved by calling ::GetExitCodeThread.

Remarks

Called by the framework from within a rarely overridden Run member function to exit this instance of the thread, or if a call to InitInstance fails.

Do not call this member function from anywhere but within the Run member function. This member function is used only in user-interface threads.

The default implementation of this function deletes the CWinThread object if m_bAutoDelete is TRUE. Override this function if you wish to perform additional clean-up when your thread terminates. Your implementation of ExitInstance should call the base class’s version after your code is executed.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinApp::ExitInstance


CWinThread::GetMainWnd

virtual CWnd * GetMainWnd( );

Return Value

This function returns a pointer to one of two types of windows. If your thread is part of an OLE server and has an object that is in-place active inside an active container, this function returns the CWinApp::m_pActiveWnd data member of the CWinThread object.

If there is no object that is in-place active within a container or your application is not an OLE server, this function returns the m_pMainWnd data member of your thread object.

Remarks

If your application is an OLE server, call this function to retrieve a pointer to the active main window of the application instead of directly referring to the m_pMainWnd member of the application object. For user-interface threads, this is equivalent to directly referring to the m_pActiveWnd member of your application object.

If your application is not an OLE server, then calling this function is equivalent to directly referring to the m_pMainWnd member of your application object.

Override this function to modify the default behavior.

CWinThread Overview | Class Members | Hierarchy Chart

See Also AfxGetMainWnd


CWinThread::GetThreadPriority

int GetThreadPriority( );

Return Value

The current thread priority level within its priority class. The value returned will be one of the following, listed from highest priority to lowest:

  • THREAD_PRIORITY_TIME_CRITICAL

  • THREAD_PRIORITY_HIGHEST

  • THREAD_PRIORITY_ABOVE_NORMAL

  • THREAD_PRIORITY_NORMAL

  • THREAD_PRIORITY_BELOW_NORMAL

  • THREAD_PRIORITY_LOWEST

  • THREAD_PRIORITY_IDLE

For more information on these priorities, see ::SetThreadPriority in the Win32 SDK Programmer’s Reference, Volume 4.

Remarks

Gets the current thread priority level of this thread.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinThread::SetThreadPriority, ::GetThreadPriority


CWinThread::InitInstance

virtual BOOL InitInstance( );

Return Value

Nonzero if initialization is successful; otherwise 0.

Remarks

InitInstance must be overridden to initialize each new instance of a user-interface thread. Typically, you override InitInstance to perform tasks that must be completed when a thread is first created.

This member function is used only in user-interface threads. Perform initialization of worker threads in the controlling function passed to AfxBeginThread.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinApp::InitInstance


CWinThread::IsIdleMessage

virtual BOOL IsIdleMessage( MSG* pMsg );

Return Value

Nonzero if OnIdle should be called after processing message; otherwise 0.

Parameters

pMsg Points to the current message being processed.

Remarks

Override this function to keep OnIdle from being called after specific messages are generated. The default implementation does not call OnIdle after redundant mouse messages and messages generated by blinking carets.

If an application has created a short timer, OnIdle will be called frequently, causing performance problems. To improve such an application’s performance, override IsIdleMessage in the application’s CWinApp-derived class to check for WM_TIMER messages as follows:

BOOL CMyApp::IsIdleMessage( MSG* pMsg )
{
   if (!CWinApp::IsIdleMessage( pMsg ) ||
       pMsg->message == WM_TIMER)
      return FALSE;
   else
      return TRUE;
}

Handling WM_TIMER in this fashion will improve performance of applications that use short timers.


CWinThread::OnIdle

virtual BOOL OnIdle( LONG lCount );

Return Value

Nonzero to receive more idle processing time; 0 if no more idle processing time is needed.

Parameters

lCount

A counter incremented each time OnIdle is called when the thread’s message queue is empty. This count is reset to 0 each time a new message is processed. You can use the lCount parameter to determine the relative length of time the thread has been idle without processing a message.

Remarks

Override this member function to perform idle-time processing. OnIdle is called in the default message loop when the thread’s message queue is empty. Use your override to call your own background idle-handler tasks.

OnIdle should return 0 to indicate that no additional idle processing time is required. The lCount parameter is incremented each time OnIdle is called when the message queue is empty and is reset to 0 each time a new message is processed. You can call your different idle routines based on this count.

The default implementation of this member function frees temporary objects and unused dynamic link libraries from memory.

This member function is used only in user-interface threads.

Because the application cannot process messages until OnIdle returns, do not perform lengthy tasks in this function.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnIdle


CWinThread::PostThreadMessage

BOOL PostThreadMessage( UINT message , WPARAM wParam, LPARAM lParam );

Return Value

Nonzero if successful; otherwise 0.

Parameters

message

ID of the user-defined message.

wParam

First message parameter.

lParam

Second message parameter.

Remarks

Called to post a user-defined message to another CWinThread object. The posted message is mapped to the proper message handler by the message map macro ON_THREAD_MESSAGE.

CWinThread Overview | Class Members | Hierarchy Chart

See Also ON_THREAD_MESSAGE


CWinThread::PreTranslateMessage

virtual BOOL PreTranslateMessage( MSG *pMsg );

Return Value

Nonzero if the message was fully processed in PreTranslateMessage and should not be processed further. Zero if the message should be processed in the normal way.

Parameters

pMsg

Points to a MSG structure containing the message to process.

Remarks

Override this function to filter window messages before they are dispatched to the Windows functions ::TranslateMessage and ::DispatchMessage.

This member function is used only in user-interface threads.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinApp::PreTranslateMessage


CWinThread::ProcessMessageFilter

virtual BOOL ProcessMessageFilter( int code, LPMSG lpMsg );

Return Value

Nonzero if the message is processed; otherwise 0.

Parameters

code

Specifies a hook code. This member function uses the code to determine how to process lpMsg.

lpMsg

A pointer to a Windows MSG structure.

Remarks

The framework’s hook function calls this member function to filter and respond to certain Windows messages. A hook function processes events before they are sent to the application’s normal message processing.

If you override this advanced feature, be sure to call the base-class version to maintain the framework’s hook processing.

CWinApp Overview | Class Members | Hierarchy Chart

See Also MessageProc, WH_MSGFILTER


CWinThread::ProcessWndProcException

virtual LRESULT ProcessWndProcException( CException *e, const MSG *pMsg );

Return Value

–1 if a WM_CREATE exception is generated; otherwise 0.

Parameters

e

Points to an unhandled exception.

pMsg

Points to a MSG structure containing information about the windows message that caused the framework to throw an exception.

Remarks

The framework calls this member function whenever the handler does not catch an exception thrown in one of your thread’s message or command handlers.

Do not call this member function directly.

The default implementation of this member function handles only exceptions generated from the following messages:

Command | Action
WM_CREATE | Fail.
WM_PAINT | Validate the affected window, thus preventing another WM_PAINT message from being generated.

Override this member function to provide global handling of your exceptions. Call the base functionality only if you wish to display the default behavior.

This member function is used only in threads that have a message pump.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinApp::ProcessWndProcException


CWinThread::ResumeThread

DWORD ResumeThread( );

Return Value

The thread’s previous suspend count if successful; 0xFFFFFFFF otherwise. If the return value is zero, the current thread was not suspended. If the return value is one, the thread was suspended, but is now restarted. Any return value greater than one means the thread remains suspended.

Remarks

Called to resume execution of a thread that was suspended by the SuspendThread member function, or a thread created with the CREATE_SUSPENDED flag. The suspend count of the current thread is reduced by one. If the suspend count is reduced to zero, the thread resumes execution; otherwise the thread remains suspended.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinThread::SuspendThread, ::ResumeThread


CWinThread::Run

virtual int Run( );

Return Value

An int value that is returned by the thread. This value can be retrieved by calling ::GetExitCodeThread.

Remarks

Provides a default message loop for user-interface threads. Run acquires and dispatches Windows messages until the application receives a WM_QUIT message. If the thread’s message queue currently contains no messages, Run calls OnIdle to perform idle-time processing. Incoming messages go to the PreTranslateMessage member function for special processing and then to the Windows function ::TranslateMessage for standard keyboard translation. Finally, the ::DispatchMessage Windows function is called.

Run is rarely overridden, but you can override it to implement special behavior.

This member function is used only in user-interface threads.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinApp::Run


CWinThread::SetThreadPriority

BOOL SetThreadPriority( int nPriority );

Return Value

Nonzero if function was successful; otherwise 0.

Parameters

nPriority

Specifies the new thread priority level within its priority class. This parameter must be one of the following values, listed from highest priority to lowest:

  • THREAD_PRIORITY_TIME_CRITICAL

  • THREAD_PRIORITY_HIGHEST

  • THREAD_PRIORITY_ABOVE_NORMAL

  • THREAD_PRIORITY_NORMAL

  • THREAD_PRIORITY_BELOW_NORMAL

  • THREAD_PRIORITY_LOWEST

  • THREAD_PRIORITY_IDLE

For more information on these priorities, see ::SetThreadPriority in the Win32 SDK Programmer’s Reference, Volume 4.

Remarks

This function sets the priority level of the current thread within its priority class. It can only be called after CreateThread successfully returns.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinThread::GetThreadPriority, ::SetThreadPriority


CWinThread::SuspendThread

DWORD SuspendThread( );

Return Value

The thread’s previous suspend count if successful; 0xFFFFFFFF otherwise.

Remarks

Increments the current thread’s suspend count. If any thread has a suspend count above zero, that thread does not execute. The thread can be resumed by calling the ResumeThread member function.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinThread::ResumeThread, ::SuspendThread


CWinThread::m_bAutoDelete

Remarks

Specifies whether the CWinThread object should be automatically deleted at thread termination. The m_bAutoDelete data member is a public variable of type BOOL.


CWinThread::m_hThread

Remarks

Handle to the thread attached to this CWinThread. The m_hThread data member is a public variable of type HANDLE. It is only valid if underlying thread currently exists.


CWinThread::m_nThreadID

Remarks

ID of the thread attached to this CWinThread. The m_nThreadID data member is a public variable of type DWORD. It is only valid if underlying thread currently exists.


CWinThread::m_pActiveWnd

Remarks

Use this data member to store a pointer to your thread’s active window object. The Microsoft Foundation Class Library will automatically terminate your thread when the window referred to by m_pActiveWnd is closed. If this thread is the primary thread for an application, the application will also be terminated. If this data member is NULL, the active window for the application’s CWinApp object will be inherited. m_pActiveWnd is a public variable of type CWnd*.

Typically, you set this member variable when you override InitInstance. In a worker thread, the value of this data member is inherited from its parent thread.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinThread::InitInstance, CWinThread::m_pMainWnd


CWinThread::m_pMainWnd

Remarks

Use this data member to store a pointer to your thread’s main window object. The Microsoft Foundation Class Library will automatically terminate your thread when the window referred to by m_pMainWnd is closed. If this thread is the primary thread for an application, the application will also be terminated. If this data member is NULL, the main window for the application’s CWinApp object will be used to determine when to terminate the thread. m_pMainWnd is a public variable of type CWnd*.

Typically, you set this member variable when you override InitInstance. In a worker thread, the value of this data member is inherited from its parent thread.

CWinThread Overview | Class Members | Hierarchy Chart

See Also CWinThread::InitInstance


CWnd

The CWnd class provides the base functionality of all window classes in the Microsoft Foundation Class Library.

A CWnd object is distinct from a Windows window, but the two are tightly linked. A CWnd object is created or destroyed by the CWnd constructor and destructor. The Windows window, on the other hand, is a data structure internal to Windows that is created by a Create member function and destroyed by the CWnd virtual destructor. The DestroyWindow function destroys the Windows window without destroying the object.

The CWnd class and the message-map mechanism hide the WndProc function. Incoming Windows notification messages are automatically routed through the message map to the proper On Message CWnd member functions. You override an On Message member function to handle a member’s particular message in your derived classes.

The CWnd class also lets you create a Windows child window for your application. Derive a class from CWnd, then add member variables to the derived class to store data specific to your application. Implement message-handler member functions and a message map in the derived class to specify what happens when messages are directed to the window.

You create a child window in two steps. First, call the constructor CWnd to construct the CWnd object, then call the Create member function to create the child window and attach it to the CWnd object.

When the user terminates your child window, destroy the CWnd object, or call the DestroyWindow member function to remove the window and destroy its data structures.

Within the Microsoft Foundation Class Library, further classes are derived from CWnd to provide specific window types. Many of these classes, including CFrameWnd, CMDIFrameWnd, CMDIChildWnd, CView, and CDialog, are designed for further derivation. The control classes derived from CWnd, such as CButton, can be used directly or can be used for further derivation of classes.

For more information on using CWnd, see Frame Window Topics and Window Object Topics in Visual C++ Programmer’s Guide.

#include <afxwin.h>

Class Members | Base Class | Hierarchy Chart

Samples MFC Sample BINDENRL | MFC Sample EXTBIND | MFC Sample VCTERM

See Also CFrameWnd, CView


CWnd Class Members

Initialization | Dialog-Box Item Functions | Initialization Message Handlers
Window State Functions | Data-Binding Functions | System Message Handlers
Window Size and Position | Menu Functions | General Message Handlers
Window Access Functions | Tool Tip Functions | Control Message Handlers
Update/Painting Functions | Timer Functions | Input Message Handlers
Coordinate Mapping Functions | Alert Functions | Nonclient-Area Message Handlers
Window Text Functions | Window Message Functions | MDI Message Handlers
Scrolling Functions | Clipboard Functions | Clipboard Message Handlers
Drag-Drop Functions | OLE Controls | Menu Loop Notification
Caret Functions | Overridables |

Data Members

m_hWnd Indicates the HWND attached to this CWnd.

Construction/Destruction

CWnd | Constructs a CWnd object.
DestroyWindow | Destroys the attached Windows window.

Initialization

Create | Creates and initializes the child window associated with the CWnd object.
PreCreateWindow | Called before the creation of the Windows window attached to this CWnd object.
CalcWindowRect | Called to calculate the window rectangle from the client rectangle.
GetStyle | Returns the current window style.
GetExStyle | Returns the window’s extended style.
Attach | Attaches a Windows handle to a CWnd object.
Detach | Detaches a Windows handle from a CWnd object and returns the handle.
PreSubclassWindow | Allows other necessary subclassing to occur before SubclassWindow is called.
SubclassWindow | Attaches a window to a CWnd object and makes it route messages through the CWnd’s message map.
UnsubclassWindow | Detaches a window from a CWnd object
FromHandle | Returns a pointer to a CWnd object when given a handle to a window. If a CWnd object is not attached to the handle, a temporary CWnd object is created and attached.
FromHandlePermanent | Returns a pointer to a CWnd object when given a handle to a window. If a CWnd object is not attached to the handle, NULL is returned.
DeleteTempMap | Called automatically by the CWinApp idle-time handler and deletes any temporary CWnd objects created by FromHandle.
GetSafeHwnd | Returns m_hWnd, or NULL if the this pointer is NULL.
CreateEx | Creates a Windows overlapped, pop-up, or child window and attaches it to a CWnd object.
CreateControl | Create an OLE control that will be represented in an MFC program by a CWnd object.

Window State Functions

IsWindowEnabled | Determines whether the window is enabled for mouse and keyboard input.
EnableWindow | Enables or disables mouse and keyboard input.
GetActiveWindow | Retrieves the active window.
SetActiveWindow | Activates the window.
GetCapture | Retrieves the CWnd that has the mouse capture.
SetCapture | Causes all subsequent mouse input to be sent to the CWnd.
GetFocus | Retrieves the CWnd that currently has the input focus.
SetFocus | Claims the input focus.
GetDesktopWindow | Retrieves the Windows desktop window.
GetForegroundWindow | Returns a pointer to the foreground window (the top-level window with which the user is currently working).
SetForegroundWindow | Puts the thread that created the window into the foreground and activates the window.
GetIcon | Retrieves the handle to an icon.
SetIcon | Sets the handle to a specific icon.
GetWindowContextHelpId | Retrieves the help context identifier.
SetWindowContextHelpId | Sets the help context identifier.
ModifyStyle | Modifies the current window style.
ModifyStyleEx | Modifies the window’s extended style.

Window Size and Position

GetWindowPlacement | Retrieves the show state and the normal (restored), minimized, and maximized positions of a window.
SetWindowPlacement | Sets the show state and the normal (restored), minimized, and maximized positions for a window.
GetWindowRgn | Retrieves a copy of the window region of a window.
SetWindowRgn | Sets the region of a window.
IsIconic | Determines whether CWnd is minimized (iconic).
IsZoomed | Determines whether CWnd is maximized.
MoveWindow | Changes the position and dimensions of CWnd.
SetWindowPos | Changes the size, position, and ordering of child, pop-up, and top-level windows.
ArrangeIconicWindows | Arranges all the minimized (iconic) child windows.
BringWindowToTop | Brings CWnd to the top of a stack of overlapping windows.
GetWindowRect | Gets the screen coordinates of CWnd.
GetClientRect | Gets the dimensions of the CWnd client area.

Window Access Functions

ChildWindowFromPoint | Determines which, if any, of the child windows contains the specified point.
FindWindow | Returns the handle of the window, which is identified by its window name and window class.
GetNextWindow | Returns the next (or previous) window in the window manager’s list.
GetOwner | Retrieves a pointer to the owner of a CWnd.
SetOwner | Changes the owner of a CWnd.
GetTopWindow | Returns the first child window that belongs to the CWnd.
GetWindow | Returns the window with the specified relationship to this window.
GetLastActivePopup | Determines which pop-up window owned by CWnd was most recently active.
IsChild | Indicates whether CWnd is a child window or other direct descendant of the specified window.
GetParent | Retrieves the parent window of CWnd (if any).
GetSafeOwner | Retrieves the safe owner for the given window.
SetParent | Changes the parent window.
WindowFromPoint | Identifies the window that contains the given point.
GetDlgItem | Retrieves the control with the specified ID from the specified dialog box.
GetDlgCtrlID | If the CWnd is a child window, calling this function returns its ID value.
SetDlgCtrlID | Sets the window or control ID for the window (which can be any child window, not only a control in a dialog box).
GetDescendantWindow | Searches all descendant windows and returns the window with the specified ID.
GetParentFrame | Retrieves the CWnd object’s parent frame window.
SendMessageToDescendants | Sends a message to all descendant windows of the window.
GetTopLevelParent | Retrieves the window’s top-level parent.
GetTopLevelOwner | Retrieves the top-level window.
GetParentOwner | Returns a pointer to a child window’s parent window.
GetTopLevelFrame | Retrieves the window’s top-level frame window.
UpdateDialogControls | Call to update the state of dialog buttons and other controls.
UpdateData | Initializes or retrieves data from a dialog box.
CenterWindow | Centers a window relative to its parent.

Update/Painting Functions

BeginPaint | Prepares CWnd for painting.
EndPaint | Marks the end of painting.
Print | Draws the current window in the specified device context.
PrintClient | Draws any window in the specified device context (usually a printer device context).
LockWindowUpdate | Disables or reenables drawing in the given window.
UnlockWindowUpdate | Unlocks a window that was locked with CWnd::LockWindowUpdate.
GetDC | Retrieves a display context for the client area.
GetDCEx | Retrieves a display context for the client area, and enables clipping while drawing.
RedrawWindow | Updates the specified rectangle or region in the client area.
GetWindowDC | Retrieves the display context for the whole window, including the caption bar, menus, and scroll bars.
ReleaseDC | Releases client and window device contexts, freeing them for use by other applications.
UpdateWindow | Updates the client area.
SetRedraw | Allows changes in CWnd to be redrawn or prevents changes from being redrawn.
GetUpdateRect | Retrieves the coordinates of the smallest rectangle that completely encloses the CWnd update region.
GetUpdateRgn | Retrieves the CWnd update region.
Invalidate | Invalidates the entire client area.
InvalidateRect | Invalidates the client area within the given rectangle by adding that rectangle to the current update region.
InvalidateRgn | Invalidates the client area within the given region by adding that region to the current update region.
ValidateRect | Validates the client area within the given rectangle by removing the rectangle from the current update region.
ValidateRgn | Validates the client area within the given region by removing the region from the current update region.
ShowWindow | Shows or hides the window.
IsWindowVisible | Determines whether the window is visible.
ShowOwnedPopups | Shows or hides all pop-up windows owned by the window.
EnableScrollBar | Enables or disables one or both arrows of a scroll bar.

Coordinate Mapping Functions

MapWindowPoints | Converts (maps) a set of points from the coordinate space of the CWnd to the coordinate space of another window.
ClientToScreen | Converts the client coordinates of a given point or rectangle on the display to screen coordinates.
ScreenToClient | Converts the screen coordinates of a given point or rectangle on the display to client coordinates.

Window Text Functions

SetWindowText | Sets the window text or caption title (if it has one) to the specified text.
GetWindowText | Returns the window text or caption title (if it has one).
GetWindowTextLength | Returns the length of the window’s text or caption title.
SetFont | Sets the current font.
GetFont | Retrieves the current font.

Scrolling Functions

GetScrollPos | Retrieves the current position of a scroll box.
GetScrollRange | Copies the current minimum and maximum scroll-bar positions for the given scroll bar.
ScrollWindow | Scrolls the contents of the client area.
ScrollWindowEx | Scrolls the contents of the client area. Similar to ScrollWindow, with additional features.
GetScrollInfo | Retrieves the information that the SCROLLINFO structure maintains about a scroll bar.
GetScrollLimit | Retrieves the limit of the scroll bar.
SetScrollInfo | Sets information about the scroll bar.
SetScrollPos | Sets the current position of a scroll box and, if specified, redraws the scroll bar to reflect the new position.
SetScrollRange | Sets minimum and maximum position values for the given scroll bar.
ShowScrollBar | Displays or hides a scroll bar.
EnableScrollBarCtrl | Enables or disables a sibling scroll-bar control.
GetScrollBarCtrl | Returns a sibling scroll-bar control.
RepositionBars | Repositions control bars in the client area.

Drag-Drop Functions

DragAcceptFiles Indicates the window will accept dragged files.

Caret Functions

CreateCaret | Creates a new shape for the system caret and gets ownership of the caret.
CreateSolidCaret | Creates a solid block for the system caret and gets ownership of the caret.
CreateGrayCaret | Creates a gray block for the system caret and gets ownership of the caret.
GetCaretPos | Retrieves the client coordinates of the caret’s current position.
SetCaretPos | Moves the caret to a specified position.
HideCaret | Hides the caret by removing it from the display screen.
ShowCaret | Shows the caret on the display at the caret’s current position. Once shown, the caret begins flashing automatically.

Dialog-Box Item Functions

CheckDlgButton | Places a check mark next to or removes a check mark from a button control.
CheckRadioButton | Checks the specified radio button and removes the check mark from all other radio buttons in the specified group of buttons.
GetCheckedRadioButton | Returns the ID of the currently checked radio button in a group of buttons.
DlgDirList | Fills a list box with a file or directory listing.
DlgDirListComboBox | Fills the list box of a combo box with a file or directory listing.
DlgDirSelect | Retrieves the current selection from a list box.
DlgDirSelectComboBox | Retrieves the current selection from the list box of a combo box.
GetDlgItemInt | Translates the text of a control in the given dialog box to an integer value.
GetDlgItemText | Retrieves the caption or text associated with a control.
GetNextDlgGroupItem | Searches for the next (or previous) control within a group of controls.
GetNextDlgTabItem | Retrieves the first control with the WS_TABSTOP style that follows (or precedes) the specified control.
IsDlgButtonChecked | Determines whether a button control is checked.
IsDialogMessage | Determines whether the given message is intended for the modeless dialog box and, if so, processes it.
SendDlgItemMessage | Sends a message to the specified control.
SetDlgItemInt | Sets the text of a control to the string that represents an integer value.
SetDlgItemText | Sets the caption or text of a control in the specified dialog box.
SubclassDlgItem | Attaches a Windows control to a CWnd object and makes it route messages through the CWnd’s message map.
ExecuteDlgInit | Initiates a dialog resource.
RunModalLoop | Retrieves, translates, or dispatches messages for a window that is in modal status.
ContinueModal | Continues a window’s modal status.
EndModalLoop | Ends a window’s modal status.

Data-Binding Functions

BindDefaultProperty | Binds the calling object’s default simple bound property, as marked in the type library, to a cursor associated with a data-source control.
BindProperty | Binds a cursour-bound property on a data-bound control to a data-source control and registers that relationship with the MFC binding manager.
GetDSCCursor | Retrieves a pointer to the underlying cursor that is defined by the DataSource, UserName, Password, and SQL properties of a data-source control.

Menu Functions

GetMenu | Retrieves a pointer to the specified menu.
SetMenu | Sets the menu to the specified menu.
DrawMenuBar | Redraws the menu bar.
GetSystemMenu | Allows the application to access the Control menu for copying and modification.
HiliteMenuItem | Highlights or removes the highlighting from a top-level (menu-bar) menu item.

ToolTip Functions

EnableToolTips | Enables the tooltip control.
CancelToolTips | Disables the tooltip control.
FilterToolTipMessage | Retrieves the title or text associated with a control in a dialog box.
OnToolHitTest | Detemines whether a point is in the bounding rectangle of the specified tool and retrieves information about the tool.

Timer Functions

SetTimer | Installs a system timer that sends a WM_TIMER message when triggered.
KillTimer | Kills a system timer.

Alert Functions

FlashWindow | Flashes the window once.
MessageBox | Creates and displays a window that contains an application-supplied message and caption.

Window Message Functions

GetCurrentMessage | Returns a pointer to the message this window is currently processing. Should only be called when in an On Message message-handler member function.
Default | Calls the default window procedure, which provides default processing for any window messages that an application does not process.
PreTranslateMessage | Used by CWinApp to filter window messages before they are dispatched to the TranslateMessage and DispatchMessage Windows functions.
SendMessage | Sends a message to the CWnd object and does not return until it has processed the message.
PostMessage | Places a message in the application queue, then returns without waiting for the window to process the message.
SendNotifyMessage | Sends the specified message to the window and returns as soon as possible, depending on whether the calling thread created the window.

Clipboard Functions

ChangeClipboardChain | Removes CWnd from the chain of Clipboard viewers.
SetClipboardViewer | Adds CWnd to the chain of windows that are notified whenever the contents of the Clipboard are changed.
OpenClipboard | Opens the Clipboard. Other applications will not be able to modify the Clipboard until the Windows CloseClipboard function is called.
GetClipboardOwner | Retrieves a pointer to the current owner of the Clipboard.
GetOpenClipboardWindow | Retrieves a pointer to the window that currently has the Clipboard open.
GetClipboardViewer | Retrieves a pointer to the first window in the chain of Clipboard viewers.

OLE Controls

SetProperty | Sets an OLE control property.
OnAmbientProperty | Implement ambient property values.
GetControlUnknown | Retrieves a pointer to an unknown OLE control.
GetProperty | Retrieves an OLE control property.
InvokeHelper | Invokes an OLE control method or property.

Overridables

WindowProc | Provides a window procedure for a CWnd. The default dispatches messages through the message map.
DefWindowProc | Calls the default window procedure, which provides default processing for any window messages that an application does not process.
PostNcDestroy | This virtual function is called by the default OnNcDestroy function after the window has been destroyed.
OnNotify | Called by the framework to inform a parent window an event has occurred in one of its controls or that the control needs information.
OnChildNotify | Called by a parent window to give a notifying control a chance to respond to a control notification.
DoDataExchange | For dialog data exchange and validation. Called by UpdateData.

Initialization Message Handlers

OnInitMenu | Called when a menu is about to become active.
OnInitMenuPopup | Called when a pop-up menu is about to become active.

System Message Handlers

OnSysChar | Called when a keystroke translates to a system character.
OnSysCommand | Called when the user selects a command from the Control menu, or when the user selects the Maximize or Minimize button.
OnSysDeadChar | Called when a keystroke translates to a system dead character (such as accent characters).
OnSysKeyDown | Called when the user holds down the ALT key and then presses another key.
OnSysKeyUp | Called when the user releases a key that was pressed while the ALT key was held down.
OnCompacting | Called when Windows detects that system memory is low.
OnDevModeChange | Called for all top-level windows when the user changes device-mode settings.
OnFontChange | Called when the pool of font resources changes.
OnPaletteIsChanging | Informs other applications when an application is going to realize its logical palette.
OnPaletteChanged | Called to allow windows that use a color palette to realize their logical palettes and update their client areas.
OnSysColorChange | Called for all top-level windows when a change is made in the system color setting.
OnWindowPosChanging | Called when the size, position, or Z-order is about to change as a result of a call to SetWindowPos or another window-management function.
OnWindowPosChanged | Called when the size, position, or Z-order has changed as a result of a call to SetWindowPos or another window-management function.
OnDropFiles | Called when the user releases the left mouse button over a window that has registered itself as the recipient of dropped files.
OnSpoolerStatus | Called from Print Manager whenever a job is added to or removed from the Print Manager queue.
OnTimeChange | Called for all top-level windows after the system time changes.
OnWinIniChange | Called for all top-level windows after the Windows initialization file, WIN.INI, is changed.

General Message Handlers

OnCommand | Called when the user selects a command.
OnActivate | Called when CWnd is being activated or deactivated.
OnActivateApp | Called when the application is about to be activated or deactivated.
OnCancelMode | Called to allow CWnd to cancel any internal modes, such as mouse capture.
OnChildActivate | Called for multiple document interface (MDI) child windows whenever the size or position of CWnd changes or CWnd is activated.
OnClose | Called as a signal that CWnd should be closed.
OnCopyData | Copies data from one application to another.
OnCreate | Called as a part of window creation.
OnCtlColor | Called if CWnd is the parent of a control when the control is about to be drawn.
OnDestroy | Called when CWnd is being destroyed.
OnEnable | Called when CWnd is enabled or disabled.
OnEndSession | Called when the session is ending.
OnEnterIdle | Called to inform an application’s main window procedure that a modal dialog box or a menu is entering an idle state.
OnEraseBkgnd | Called when the window background needs erasing.
OnGetMinMaxInfo | Called whenever Windows needs to know the maximized position or dimensions, or the minimum or maximum tracking size.
OnIconEraseBkgnd | Called when CWnd is minimized (iconic) and the background of the icon must be filled before painting the icon.
OnKillFocus | Called immediately before CWnd loses the input focus.
OnMenuChar | Called when the user presses a menu mnemonic character that doesn’t match any of the predefined mnemonics in the current menu.
OnMenuSelect | Called when the user selects a menu item.
OnMove | Called after the position of the CWnd has been changed.
OnMoving | Indicates that a user is moving a CWnd object.
OnDeviceChange | Notifies an application or device driver of a change to the hardware configuration of a device or the computer.
OnStyleChanged | Indicates that the ::SetWindowLong Windows function has changed one or more of the window's styles.
OnStyleChanging | Indicates that the ::SetWindowLong Windows function is about to change one or more of the window's styles.
OnPaint | Called to repaint a portion of the window.
OnParentNotify | Called when a child window is created or destroyed, or when the user clicks a mouse button while the cursor is over the child window.
OnQueryDragIcon | Called when a minimized (iconic) CWnd is about to be dragged by the user.
OnQueryEndSession | Called when the user chooses to end the Windows session.
OnQueryNewPalette | Informs CWnd that it is about to receive the input focus.
OnQueryOpen | Called when CWnd is an icon and the user requests that the icon be opened.
OnSetFocus | Called after CWnd gains the input focus.
OnShowWindow | Called when CWnd is to be hidden or shown.
OnSize | Called after the size of CWnd has changed.
OnSizing | Indicates that the user is resizing the rectangle.
OnStyleChanged | Indicates that one or more of the window's styles has changed.
OnStyleChanging | Indicates that one or more of the window's styles is about to change.

Control Message Handlers

OnCharToItem | Called by a child list box with the LBS_WANTKEYBOARDINPUT style in response to a WM_CHAR message.
OnCompareItem | Called to determine the relative position of a new item in a child sorted owner-draw combo box or list box.
OnDeleteItem | Called when an owner-draw child list box or combo box is destroyed or when items are removed from the control.
OnDrawItem | Called when a visual aspect of an owner-draw child button control, combo-box control, list-box control, or menu needs to be drawn.
OnDSCNotify | Called in response to an event that a data-source control fires when a control to which the data-source control is bound modifies or attempts to modify the underlying cursor.
OnGetDlgCode | Called for a control so the control can process arrow-key and TAB-key input itself.
OnMeasureItem | Called for an owner-draw child combo box, list box, or menu item when the control is created. CWnd informs Windows of the dimensions of the control.
SendChildNotifyLastMsg | Provides a notification message to a child window, from the parent window, so the child window can handle a task.
ReflectChildNotify | Helper function which reflects a message to its source.
OnWndMsg | Indicates if a windows message was handled.
ReflectLastMsg | Reflects the last message to the child window.
OnVKeyToItem | Called by a list box owned by CWnd in response to a WM_KEYDOWN message.

Input Message Handlers

OnChar | Called when a keystroke translates to a nonsystem character.
OnDeadChar | Called when a keystroke translates to a nonsystem dead character (such as accent characters).
OnHScroll | Called when the user clicks the horizontal scroll bar of CWnd.
OnKeyDown | Called when a nonsystem key is pressed.
OnKeyUp | Called when a nonsystem key is released.
OnLButtonDblClk | Called when the user double-clicks the left mouse button.
OnLButtonDown | Called when the user presses the left mouse button.
OnLButtonUp | Called when the user releases the left mouse button.
OnMButtonDblClk | Called when the user double-clicks the middle mouse button.
OnMButtonDown | Called when the user presses the middle mouse button.
OnMButtonUp | Called when the user releases the middle mouse button.
OnMouseActivate | Called when the cursor is in an inactive window and the user presses a mouse button.
OnMouseMove | Called when the mouse cursor moves.
OnMouseWheel | Called when a user rotates the mouse wheel. Uses Windows NT 4.0 message handling.
OnRegisteredMouseWheel | Called when a user rotates the mouse wheel. Uses Windows 95 and Windows NT 3.51 message-handling.
OnRButtonDblClk | Called when the user double-clicks the right mouse button.
OnRButtonDown | Called when the user presses the right mouse button.
OnRButtonUp | Called when the user releases the right mouse button.
OnSetCursor | Called if mouse input is not captured and the mouse causes cursor movement within a window.
OnTimer | Called after each interval specified in SetTimer.
OnVScroll | Called when the user clicks the window’s vertical scroll bar.
OnCaptureChanged | Sends a message to the window that is losing the mouse capture.

Nonclient-Area Message Handlers

OnNcActivate | Called when the nonclient area needs to be changed to indicate an active or inactive state.
OnNcCalcSize | Called when the size and position of the client area need to be calculated.
OnNcCreate | Called prior to OnCreate when the nonclient area is being created.
OnNcDestroy | Called when the nonclient area is being destroyed.
OnNcHitTest | Called by Windows every time the mouse is moved if CWnd contains the cursor or has captured mouse input with SetCapture.
OnNcLButtonDblClk | Called when the user double-clicks the left mouse button while the cursor is within a nonclient area of CWnd.
OnNcLButtonDown | Called when the user presses the left mouse button while the cursor is within a nonclient area of CWnd.
OnNcLButtonUp | Called when the user releases the left mouse button while the cursor is within a nonclient area of CWnd.
OnNcMButtonDblClk | Called when the user double-clicks the middle mouse button while the cursor is within a nonclient area of CWnd.
OnNcMButtonDown | Called when the user presses the middle mouse button while the cursor is within a nonclient area of CWnd.
OnNcMButtonUp | Called when the user releases the middle mouse button while the cursor is within a nonclient area of CWnd.
OnNcMouseMove | Called when the cursor is moved within a nonclient area of CWnd.
OnNcPaint | Called when the nonclient area needs painting.
OnNcRButtonDblClk | Called when the user double-clicks the right mouse button while the cursor is within a nonclient area of CWnd.
OnNcRButtonDown | Called when the user presses the right mouse button while the cursor is within a nonclient area of CWnd.
OnNcRButtonUp | Called when the user releases the right mouse button while the cursor is within a nonclient area of CWnd.

MDI Message Handlers

OnMDIActivate Called when an MDI child window is activated or deactivated.

Clipboard Message Handlers

OnAskCbFormatName | Called by a Clipboard viewer application when a Clipboard owner will display the Clipboard contents.
OnChangeCbChain | Notifies that a specified window is being removed from the chain.
OnDestroyClipboard | Called when the Clipboard is emptied through a call to the Windows EmptyClipboard function.
OnDrawClipboard | Called when the contents of the change.
OnHScrollClipboard | Called when a Clipboard owner should scroll the Clipboard image, invalidate the appropriate section, and update the scroll-bar values.
OnPaintClipboard | Called when the client area of the Clipboard viewer needs repainting.
OnRenderAllFormats | Called when the owner application is being destroyed and needs to render all its formats.
OnRenderFormat | Called for the Clipboard owner when a particular format with delayed rendering needs to be rendered.
OnSizeClipboard | Called when the size of the client area of the Clipboard-viewer window has changed.
OnVScrollClipboard | Called when the owner should scroll the Clipboard image, invalidate the appropriate section, and update the scroll-bar values.

Menu Loop Notification

OnEnterMenuLoop | Called when a menu modal loop has been entered.
OnExitMenuLoop | Called when a menu modal loop has been exited.


CWnd::ArrangeIconicWindows

UINT ArrangeIconicWindows( );

Return Value

The height of one row of icons if the function is successful; otherwise 0.

Remarks

Arranges all the minimized (iconic) child windows.

This member function also arranges icons on the desktop window, which covers the entire screen. The GetDesktopWindow member function retrieves a pointer to the desktop window object.

To arrange iconic MDI child windows in an MDI client window, call CMDIFrameWnd::MDIIconArrange.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDesktopWindow, CMDIFrameWnd::MDIIconArrange, ::ArrangeIconicWindows


CWnd::Attach

BOOL Attach( HWND hWndNew );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hWndNew

Specifies a handle to a Windows window.

Remarks

Attaches a Windows window to a CWnd object.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Detach, CWnd::m_hWnd, CWnd::SubclassWindow


CWnd::BeginPaint

CDC* BeginPaint( LPPAINTSTRUCT lpPaint );

Return Value

Identifies the device context for CWnd. The pointer may be temporary and should not be stored beyond the scope of EndPaint.

Parameters

lpPaint

Points to the PAINTSTRUCT structure that is to receive painting information.

Remarks

Prepares CWnd for painting and fills a PAINTSTRUCT data structure with information about the painting.

The paint structure contains a RECT data structure that has the smallest rectangle that completely encloses the update region and a flag that specifies whether the background has been erased.

The update region is set by the Invalidate, InvalidateRect, or InvalidateRgn member functions and by the system after it sizes, moves, creates, scrolls, or performs any other operation that affects the client area. If the update region is marked for erasing, BeginPaint sends an WM_ONERASEBKGND message.

Do not call the BeginPaint member function except in response to a WM_PAINT message. Each call to the BeginPaint member function must have a matching call to the EndPaint member function. If the caret is in the area to be painted, the BeginPaint member function automatically hides the caret to prevent it from being erased.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::EndPaint, CWnd::Invalidate, CWnd::InvalidateRgn, ::BeginPaint, CPaintDC


CWnd::BindDefaultProperty

void BindDefaultProperty( DISPID dwDispID, VARTYPE vtProp, LPCTSTR szFieldName, CWnd * pDSCWnd );

Parameters

dwDispID

Specifies the DISPID of a property on a data-bound control that is to be bound to a data-source control.

vtProp

Specifies the type of the property to be bound — for example, VT_BSTR, VT_VARIANT, and so on.

szFieldName

Specifies the name of the column, in the cursor provided by the data-source control, to which the property will be bound.

pDSCWnd

Points to the window that hosts the data-source control to which the property will be bound. Call GetDlgItem with the resource ID of the DCS’s host window to retrieve this pointer.

Remarks

Binds the calling object’s default simple bound property (such as an edit control), as marked in the type library, to the underlying cursor that is defined by the DataSource, UserName, Password, and SQL properties of the data-source control. The CWnd object on which you call this function must be a data-bound control. BindDefaultProperty might be used in the following context:

BOOL CMyDlg::OnInitDialog()
{
   ...
   CWnd* pDSC = GetDlgItem(IDC_REMOTEDATACONTROL);
   CWnd* pList = GetDlgItem(IDC_DBLISTBOX);
   pList->BindDefaultProperty(0x2,
      VT_BSTR, _T("CourseID"), pDSC);
   CWnd* pEdit = GetDlgItem(IDC_MASKEDBOX);
   pEdit->BindDefaultProperty(0x16,
      VT_BSTR, _T("InstuctorID"), pDSC);
   ...
   return TRUE;
}

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDSCCursor, CWnd::BindProperty


CWnd::BindProperty

void BindProperty( DISPID dwDispID, CWnd * pWndDSC );

Parameters

dwDispID

Specifies the DISPID of a property on a data-bound control that is to be bound to a data-source control.

pWndDSC

Points to the window that hosts the data-source control to which the property will be bound. Call GetDlgItem with the resource ID of the DCS’s host window to retrieve this pointer.

Remarks

Binds a cursor-bound property on a data-bound control (such as a grid control) to a data-source control and registers that relationship with the MFC binding manager. The CWnd object on which you call this function must be a data-bound control. BindProperty might be used in the following context:

BOOL CMyDlg::OnInitDialog()
{
   ...
   CWnd* pDSC = GetDlgItem(IDC_REMOTEDATACONTROL);
   CWnd* pList= GetDlgItem(IDC_DBLISTBOX);
   pList.BindProperty(0x9, pDSC);
   ...
   return TRUE;
}

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDSCCursor, CWnd::BindDefaultProperty


CWnd::BringWindowToTop

void BringWindowToTop( );

Remarks

Brings CWnd to the top of a stack of overlapping windows. In addition, BringWindowToTop activates pop-up, top-level, and MDI child windows. The BringWindowToTop member function should be used to uncover any window that is partially or completely obscured by any overlapping windows.

Calling this function is similar to calling the SetWindowPos function to change a window’s position in the Z-order. The BringWindowToTop function does not change the window style to make it a top-level window of the desktop.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::BringWindowToTop


CWnd::CalcWindowRect

virtual void CalcWindowRect( LPRECT lpClientRect, UINT nAdjustType = adjustBorder );

Parameters

lpClientRect

Points to a RECT structure or CRect object that contains the resultant value of the window rectangle.

nAdjustType

An enumerated type used for in-place editing. It can have the following values: CWnd::adjustBorder = 0, which means that scroll-bar sizes are ignored in calculation; and CWnd::adjustOutside = 1, which means that they are added into the final measurements of the rectangle.

Remarks

Call this member function to compute the required size of the window rectangle based on the desired client-rectangle size. The resulting window rectangle (contained in lpClientRect) can then be passed to the Create member function to create a window whose client area is the desired size.

Called by the framework to size windows prior to creation.

A client rectangle is the smallest rectangle that completely encloses a client area. A window rectangle is the smallest rectangle that completely encloses the window.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::AdjustWindowRectEx


CWnd::CancelToolTips

static void PASCAL CancelToolTips( BOOL bKeys = FALSE );

Parameters

bKeys

TRUE to cancel tooltips when a key is pressed and set the status bar text to the default; otherwise FALSE.

Remarks

Call this member function to remove a tooltip from the screen if a tooltip is currently displayed.

Note Using this member function has no effect on tooltips managed by your code. It only affects the tooltip control managed by CWnd::EnableToolTips.

CWnd Overview | Class Members | Hierarchy Chart

See Also EnableToolTips, TTM_ACTIVATE


CWnd::CenterWindow

void CenterWindow( CWnd* pAlternateOwner = NULL );

Parameters

pAlternateOwner

Pointer to an alternate window relative to which it will be centered (other than the parent window).

Remarks

Centers a window relative to its parent. Usually called from CDialog::OnInitDialog to center dialog boxes relative to the main window of the application. By default, the function centers child windows relative to their parent window, and pop-up windows relative to their owner. If the pop-up window is not owned, it is centered relative to the screen. To center a window relative to a specific window which is not the owner or parent, the pAlternateOwner parameter may be set to a valid window. To force centering relative to the screen, pass the value returned by CWnd::GetDesktopWindow as pAlternateOwner.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDesktopWindow, CDialog::OnInitDialog


CWnd::ChangeClipboardChain

BOOL ChangeClipboardChain( HWND hWndNext );

Return Value

Nonzero if successful; otherwise 0.

Parameters

hWndNext

Identifies the window that follows CWnd in the Clipboard-viewer chain.

Remarks

Removes CWnd from the chain of Clipboard viewers and makes the window specified by hWndNext the descendant of the CWnd ancestor in the chain.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetClipboardViewer, ::ChangeClipboardChain


CWnd::CheckDlgButton

void CheckDlgButton( int nIDButton, UINT nCheck );

Parameters

nIDButton

Specifies the button to be modified.

nCheck

Specifies the action to take. If nCheck is nonzero, the CheckDlgButton member function places a check mark next to the button; if 0, the check mark is removed. For three-state buttons, if nCheck is 2, the button state is indeterminate.

Remarks

Selects (places a check mark next to) or clears (removes a check mark from) a button, or it changes the state of a three-state button.

The CheckDlgButton function sends a BM_SETCHECK message to the specified button.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::IsDlgButtonChecked, CButton::SetCheck, ::CheckDlgButton


CWnd::CheckRadioButton

void CheckRadioButton( int nIDFirstButton, int nIDLastButton, int nIDCheckButton );

Parameters

nIDFirstButton

Specifies the integer identifier of the first radio button in the group.

nIDLastButton

Specifies the integer identifier of the last radio button in the group.

nIDCheckButton

Specifies the integer identifier of the radio button to be checked.

Remarks

Selects (adds a check mark to) a given radio button in a group and clears (removes a check mark from) all other radio buttons in the group.

The CheckRadioButton function sends a BM_SETCHECK message to the specified radio button.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetCheckedRadioButton, CButton::SetCheck, ::CheckRadioButton


CWnd::ChildWindowFromPoint

CWnd* ChildWindowFromPoint( POINT point ) const;

CWnd* ChildWindowFromPoint( POINT point, UINT nFlags ) const;

Return Value

Identifies the child window that contains the point. It is NULL if the given point lies outside of the client area. If the point is within the client area but is not contained within any child window, CWnd is returned.

This member function will return a hidden or disabled child window that contains the specified point.

More than one window may contain the given point. However, this function returns only the CWnd* of the first window encountered that contains the point.

The CWnd* that is returned may be temporary and should not be stored for later use.

Parameters

point

Specifies the client coordinates of the point to be tested.

nflags

Specifies which child windows to skip. This parameter can be a combination of the following values:

Value | Meaning
CWP_ALL | Do not skip any child windows
CWP_SKIPINVISIBLE | Skip invisible child windows
CWP_SKIPDISABLED | Skip disabled child windows
CWP_SKIPTRANSPARENT | Skip transparent child windows

Remarks

Determines which, if any, of the child windows belonging to CWnd contains the specified point.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::WindowFromPoint, ::ChildWindowFromPoint


CWnd::ClientToScreen

void ClientToScreen( LPPOINT lpPoint ) const;

void ClientToScreen( LPRECT lpRect ) const;

Parameters

lpPoint

Points to a POINT structure or CPoint object that contains the client coordinates to be converted.

lpRect

Points to a RECT structure or CRect object that contains the client coordinates to be converted.

Remarks

Converts the client coordinates of a given point or rectangle on the display to screen coordinates. The ClientToScreen member function uses the client coordinates in the POINT or RECT structure or the CPoint or CRect object pointed to by lpPoint or lpRect to compute new screen coordinates; it then replaces the coordinates in the structure with the new coordinates. The new screen coordinates are relative to the upper-left corner of the system display.

The ClientToScreen member function assumes that the given point or rectangle is in client coordinates.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ScreenToClient, ::ClientToScreen


CWnd::ContinueModal

BOOL ContinueModal( );

Return Value

Nonzero if modal loop is to be continued; 0 when EndModalLoop is called.

Remarks

This member function is called by RunModalLoop to determine when the modal state should be exited. By default, it returns non-zero until EndModalLoop is called.

CWnd Overview | Class Members | Hierarchy Chart

See Also RunModalLoop, EndModalLoop


CWnd::Create

virtual BOOL Create( LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL);

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszClassName

Points to a null-terminated character string that names the Windows class (a WNDCLASS structure). The class name can be any name registered with the global AfxRegisterWndClass function or any of the predefined control-class names. If NULL, uses the default CWnd attributes.

lpszWindowName

Points to a null-terminated character string that contains the window name.

dwStyle

Specifies the window style attributes. WS_POPUP cannot be used. If you wish to create a pop-up window, use CWnd::CreateEx instead.

rect

The size and position of the window, in client coordinates of pParentWnd.

pParentWnd

The parent window.

nID

The ID of the child window.

pContext

The create context of the window.

Remarks

Creates a Windows child window and attaches it to the CWnd object.

You construct a child window in two steps. First, call the constructor, which constructs the CWnd object. Then call Create, which creates the Windows child window and attaches it to CWnd. Create initializes the window’s class name and window name and registers values for its style, parent, and ID.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::CWnd, CWnd::CreateEx


CWnd::CreateCaret

void CreateCaret( CBitmap* pBitmap );

Parameters

pBitmap

Identifies the bitmap that defines the caret shape.

Remarks

Creates a new shape for the system caret and claims ownership of the caret.

The bitmap must have previously been created by the CBitmap::CreateBitmap member function, the CreateDIBitmap Windows function, or the CBitmap::LoadBitmap member function.

CreateCaret automatically destroys the previous caret shape, if any, regardless of which window owns the caret. Once created, the caret is initially hidden. To show the caret, the ShowCaret member function must be called.

The system caret is a shared resource. CWnd should create a caret only when it has the input focus or is active. It should destroy the caret before it loses the input focus or becomes inactive.

CWnd Overview | Class Members | Hierarchy Chart

See Also CBitmap::CreateBitmap, ::CreateDIBitmap, ::DestroyCaret, CBitmap::LoadBitmap, CWnd::ShowCaret, ::CreateCaret


CWnd::CreateControl

BOOL CWnd::CreateControl( LPCTSTR lpszClass, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CFile* pPersist = NULL, BOOL bStorage = FALSE, BSTR bstrLicKey = NULL );

BOOL CWnd::CreateControl( REFCLSID clsid, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CFile* pPersist = NULL, BOOL bStorage = FALSE, BSTR bstrLicKey = NULL );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpszClass

This string may contain the OLE "short name" (ProgID) for the class, e.g., "CIRC3.Circ3Ctrl.1". The name needs to match the same name registered by the control. Alternatively, the string may contain the string form of a CLSID, contained in braces, e.g., "{9DBAFCCF-592F-101B-85CE-00608CEC297B}". In either case, CreateControl converts the string to the corresponding class ID.

lpszWindowName

A pointer to the text to be displayed in the control. Sets the value of the control's Caption or Text property (if any). If NULL, the control's Caption or Text property is not changed.

dwStyle

Windows styles. The available styles are listed under Remarks.

rect

Specifies the control’s size and position. It can be either a CRect object or a RECT structure.

pParentWnd

Specifies the control’s parent window. It must not be NULL.

nID

Specifies the control’s ID.

pPersist

A pointer to a CFile containing the persistent state for the control. The default value is NULL, indicating that the control initializes itself without restoring its state from any persistent storage. If not NULL, it should be a pointer to a CFile-derived object which contains the control’s persistent data, in the form of either a stream or a storage. This data could have been saved in a previous activation of the client. The CFile can contain other data, but must have its read-write pointer set to the first byte of persistent data at the time of the call to CreateControl.

bStorage

Indicates whether the data in pPersist should be interpreted as IStorage or IStream data. If the data in pPersist is a storage, bStorage should be TRUE. If the data in pPersist is a stream, bStorage should be FALSE. The default value is FALSE.

bstrLicKey

Optional license key data. This data is needed only for creating controls that require a run-time license key. If the control supports licensing, you must provide a license key for the creation of the control to succeed. The default value is NULL.

clsid

The unique class ID of the control.

Remarks

Use this member function to create an OLE control that will be represented in the MFC program by a CWnd object. CreateControl is a direct analog of the CWnd::Create function, which creates the window for a CWnd. CreateControl creates an OLE control instead of an ordinary window.

Only a subset of the Windows dwStyle flags are supported for CreateControl:

  • WS_VISIBLE Creates a window that is initially visible. Required if you want the control to be visible immediately, like ordinary windows.

  • WS_DISABLED Creates a window that is initially disabled. A disabled window cannot receive input from the user. Can be set if the control has an Enabled property.

  • WS_BORDER Creates a window with a thin-line border. Can be set if control has a BorderStyle property.

  • WS_GROUP Specifies the first control of a group of controls. The user can change the keyboard focus from one control in the group to the next by using the direction keys. All controls defined with the WS_GROUP style after the first control belong to the same group. The next control with the WS_GROUP style ends the group and starts the next group.

  • WS_TABSTOP Specifies a control that can receive the keyboard focus when the user presses the TAB key. Pressing the TAB key changes the keyboard focus to the next control of the WS_TABSTOP style.

CWnd Overview | Class Members | Hierarchy Chart

See Also In Visual C++ Programmer’s Guide: ActiveX Control Topics


CWnd::CreateEx

BOOL CreateEx( DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hwndParent, HMENU nIDorHMenu, LPVOID lpParam = NULL );

BOOL CreateEx(DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, LPVOID lpParam = NULL);

Return Value

Nonzero if successful; otherwise 0.

Parameters

dwExStyle

Specifies the extended style of the CWnd being created. Apply any of the extended window styles to the window.

lpszClassName

Points to a null-terminated character string that names the Windows class (a WNDCLASS structure). The class name can be any name registered with the global AfxRegisterWndClass function or any of the predefined control-class names. It must not be NULL.

lpszWindowName

Points to a null-terminated character string that contains the window name.

dwStyle

Specifies the window style attributes. See Window Styles and CWnd::Create for a description of the possible values.

x

Specifies the initial x-position of the CWnd window.

y

Specifies the initial top position of the CWnd window.

nWidth

Specifies the width (in device units) of the CWnd window.

nHeight

Specifies the height (in device units) of the CWnd window.

hwndParent

Identifies the parent or owner window of the CWnd window being created. Use NULL for top-level windows.

nIDorHMenu

Identifies a menu or a child-window identifier. The meaning depends on the style of the window.

lpParam

Points to the data referenced by the lpCreateParams field of the CREATESTRUCT structure.

rect

The size and position of the window, in client coordinates of pParentWnd.

pParentWnd

The parent window.

nID

The ID of the child window.

Remarks

Creates an overlapped, pop-up, or child window with the extended style specified in dwExStyle.

The CreateEx parameters specify the WNDCLASS, window title, window style, and (optionally) initial position and size of the window. CreateEx also specifies the window’s parent (if any) and ID.

When CreateEx executes, Windows sends the WM_GETMINMAXINFO, WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE messages to the window.

To extend the default message handling, derive a class from CWnd, add a message map to the new class, and provide member functions for the above messages. Override OnCreate, for example, to perform needed initialization for a new class.

Override further On Message message handlers to add further functionality to your derived class.

If the WS_VISIBLE style is given, Windows sends the window all the messages required to activate and show the window. If the window style specifies a title bar, the window title pointed to by the lpszWindowName parameter is displayed in the title bar.

The dwStyle parameter can be any combination of window styles.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Create, ::CreateWindowEx


CWnd::CreateGrayCaret

void CreateGrayCaret( int nWidth, int nHeight );

Parameters

nWidth

Specifies the width of the caret (in logical units). If this parameter is 0, the width is set to the system-defined window-border width.

nHeight

Specifies the height of the caret (in logical units). If this parameter is 0, the height is set to the system-defined window-border height.

Remarks

Creates a gray rectangle for the system caret and claims ownership of the caret. The caret shape can be a line or a block.

The parameters nWidth and nHeight specify the caret’s width and height (in logical units); the exact width and height (in pixels) depend on the mapping mode.

The system’s window-border width or height can be retrieved by the GetSystemMetrics Windows function with the SM_CXBORDER and SM_CYBORDER indexes. Using the window-border width or height ensures that the caret will be visible on a high-resolution display.

The CreateGrayCaret member function automatically destroys the previous caret shape, if any, regardless of which window owns the caret. Once created, the caret is initially hidden. To show the caret, the ShowCaret member function must be called.

The system caret is a shared resource. CWnd should create a caret only when it has the input focus or is active. It should destroy the caret before it loses the input focus or becomes inactive.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::DestroyCaret, ::GetSystemMetrics, CWnd::ShowCaret, ::CreateCaret


CWnd::CreateSolidCaret

void CreateSolidCaret( int nWidth, int nHeight );

Parameters

nWidth

Specifies the width of the caret (in logical units). If this parameter is 0, the width is set to the system-defined window-border width.

nHeight

Specifies the height of the caret (in logical units). If this parameter is 0, the height is set to the system-defined window-border height.

Remarks

Creates a solid rectangle for the system caret and claims ownership of the caret. The caret shape can be a line or block.

The parameters nWidth and nHeight specify the caret’s width and height (in logical units); the exact width and height (in pixels) depend on the mapping mode.

The system’s window-border width or height can be retrieved by the GetSystemMetrics Windows function with the SM_CXBORDER and SM_CYBORDER indexes. Using the window-border width or height ensures that the caret will be visible on a high-resolution display.

The CreateSolidCaret member function automatically destroys the previous caret shape, if any, regardless of which window owns the caret. Once created, the caret is initially hidden. To show the caret, the ShowCaret member function must be called.

The system caret is a shared resource. CWnd should create a caret only when it has the input focus or is active. It should destroy the caret before it loses the input focus or becomes inactive.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::DestroyCaret, ::GetSystemMetrics, CWnd::ShowCaret, ::CreateCaret


CWnd::CWnd

CWnd( );

Remarks

Constructs a CWnd object. The Windows window is not created and attached until the CreateEx or Create member function is called.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::CreateEx, CWnd::Create


CWnd::Default

LRESULT Default( );

Return Value

Depends on the message sent.

Remarks

Calls the default window procedure. The default window procedure provides default processing for any window message that an application does not process. This member function ensures that every message is processed.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DefWindowProc, ::DefWindowProc


CWnd::DefWindowProc

virtual LRESULT DefWindowProc( UINT message, WPARAM wParam, LPARAM lParam );

Return Value

Depends on the message sent.

Parameters

message

Specifies the Windows message to be processed.

wParam

Specifies additional message-dependent information.

lParam

Specifies additional message-dependent information.

Remarks

Calls the default window procedure, which provides default processing for any window message that an application does not process. This member function ensures that every message is processed. It should be called with the same parameters as those received by the window procedure.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Default, ::DefWindowProc


CWnd::DeleteTempMap

static void PASCAL DeleteTempMap( );

Remarks

Called automatically by the idle time handler of the CWinApp object. Deletes any temporary CWnd objects created by the FromHandle member function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::FromHandle


CWnd::DestroyWindow

virtual BOOL DestroyWindow( );

Return Value

Nonzero if the window is destroyed; otherwise 0.

Remarks

Destroys the Windows window attached to the CWnd object. The DestroyWindow member function sends appropriate messages to the window to deactivate it and remove the input focus. It also destroys the window’s menu, flushes the application queue, destroys outstanding timers, removes Clipboard ownership, and breaks the Clipboard-viewer chain if CWnd is at the top of the viewer chain. It sends WM_DESTROY and WM_NCDESTROY messages to the window. It does not destroy the CWnd object.

DestroyWindow is a place holder for performing cleanup. Because DestroyWindow is a virtual function, it is shown in any CWnd-derived class in ClassWizard. But even though you override this function in your CWnd-derived class, DestroyWindow is not necessarily called. If DestroyWindow is not called in the MFC code, then you have to explicitly call it in your own code if you want it to be called.

Assume, for example, you have overridden DestroyWindow in a CView-derived class. Since MFC source code does not call DestroyWindow in any of its CFrameWnd-derived classes, your overridden DestroyWindow will not be called unless you call it explicitly.

If the window is the parent of any windows, these child windows are automatically destroyed when the parent window is destroyed. The DestroyWindow member function destroys child windows first and then the window itself.

The DestroyWindow member function also destroys modeless dialog boxes created by CDialog::Create.

If the CWnd being destroyed is a child window and does not have the WS_EX_NOPARENTNOTIFY style set, then the WM_PARENTNOTIFY message is sent to the parent.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnDestroy, CWnd::Detach, ::DestroyWindow


CWnd::Detach

HWND Detach( );

Return Value

A HWND to the Windows object.

Remarks

Detaches a Windows handle from a CWnd object and returns the handle.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Attach


CWnd::DlgDirList

int DlgDirList( LPTSTR lpPathSpec, int nIDListBox, int nIDStaticPath, UINT nFileType );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpPathSpec

Points to a null-terminated string that contains the path or filename. DlgDirList modifies this string, which should be long enough to contain the modifications. For more information, see the following “Remarks” section.

nIDListBox

Specifies the identifier of a list box. If nIDListBox is 0, DlgDirList assumes that no list box exists and does not attempt to fill one.

nIDStaticPath

Specifies the identifier of the static-text control used to display the current drive and directory. If nIDStaticPath is 0, DlgDirList assumes that no such text control is present.

nFileType

Specifies the attributes of the files to be displayed. It can be any combination of the following values:

  • DDL_READWRITE Read-write data files with no additional attributes.

  • DDL_READONLY Read-only files.

  • DDL_HIDDEN Hidden files.

  • DDL_SYSTEM System files.

  • DDL_DIRECTORY Directories.

  • DDL_ARCHIVE Archives.

  • DDL_POSTMSGS LB_DIR flag. If the LB_DIR flag is set, Windows places the messages generated by DlgDirList in the application’s queue; otherwise, they are sent directly to the dialog-box procedure.

  • DDL_DRIVES Drives. If the DDL_DRIVES flag is set, the DDL_EXCLUSIVE flag is set automatically. Therefore, to create a directory listing that includes drives and files, you must call DlgDirList twice: once with the DDL_DRIVES flag set and once with the flags for the rest of the list.

  • DDL_EXCLUSIVE Exclusive bit. If the exclusive bit is set, only files of the specified type are listed; otherwise normal files and files of the specified type are listed.

Remarks

Fills a list box with a file or directory listing. DlgDirList sends LB_RESETCONTENT and LB_DIR messages to the list box. It fills the list box specified by nIDListBox with the names of all files that match the path given by lpPathSpec.

The lpPathSpec parameter has the following form:

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

In this example, drive is a drive letter, directory is a valid directory name, and filename is a valid filename that must contain at least one wildcard. The wildcards are a question mark (?), which means match any character, and an asterisk (*), meaning match any number of characters.

If you specify a 0-length string for lpPathSpec, or if you specify only a directory name but do not include any file specification, the string will be changed to “*.*”.

If lpPathSpec includes a drive and/or directory name, the current drive and directory are changed to the designated drive and directory before the list box is filled. The text control identified by nIDStaticPath is also updated with the new drive and/or directory name.

After the list box is filled, lpPathSpec is updated by removing the drive and/or directory portion of the path.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DlgDirListComboBox, ::DlgDirList


CWnd::DlgDirListComboBox

int DlgDirListComboBox( LPTSTR lpPathSpec, int nIDComboBox, int nIDStaticPath, UINT nFileType );

Return Value

Specifies the outcome of the function. It is nonzero if a listing was made, even an empty listing. A 0 return value implies that the input string did not contain a valid search path.

Parameters

lpPathSpec

Points to a null-terminated string that contains the path or filename. DlgDirListComboBox modifies this string, which should be long enough to contain the modifications. For more information, see the following “Remarks” section.

nIDComboBox

Specifies the identifier of a combo box in a dialog box. If nIDComboBox is 0, DlgDirListComboBox assumes that no combo box exists and does not attempt to fill one.

nIDStaticPath

Specifies the identifier of the static-text control used to display the current drive and directory. If nIDStaticPath is 0, DlgDirListComboBox assumes that no such text control is present.

nFileType

Specifies DOS file attributes of the files to be displayed. It can be any combination of the following values:

  • DDL_READWRITE Read-write data files with no additional attributes.

  • DDL_READONLY Read-only files.

  • DDL_HIDDEN Hidden files.

  • DDL_SYSTEM System files.

  • DDL_DIRECTORY Directories.

  • DDL_ARCHIVE Archives.

  • DDL_POSTMSGS CB_DIR flag. If the CB_DIR flag is set, Windows places the messages generated by DlgDirListComboBox in the application’s queue; otherwise, they are sent directly to the dialog-box procedure.

  • DDL_DRIVES Drives. If the DDL_DRIVES flag is set, the DDL_EXCLUSIVE flag is set automatically. Therefore, to create a directory listing that includes drives and files, you must call DlgDirListComboBox twice: once with the DDL_DRIVES flag set and once with the flags for the rest of the list.

  • DDL_EXCLUSIVE Exclusive bit. If the exclusive bit is set, only files of the specified type are listed; otherwise normal files and files of the specified type are listed.

Remarks

Fills the list box of a combo box with a file or directory listing. DlgDirListComboBox sends CB_RESETCONTENT and CB_DIR messages to the combo box. It fills the list box of the combo box specified by nIDComboBox with the names of all files that match the path given by lpPathSpec.

The lpPathSpec parameter has the following form:

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

In this example, drive is a drive letter, directory is a valid directory name, and filename is a valid filename that must contain at least one wildcard. The wildcards are a question mark (?), which means match any character, and an asterisk (*), which means match any number of characters.

If you specify a zero-length string for lpPathSpec, or if you specify only a directory name but do not include any file specification, the string will be changed to “*.*”.

If lpPathSpec includes a drive and/or directory name, the current drive and directory are changed to the designated drive and directory before the list box is filled. The text control identified by nIDStaticPath is also updated with the new drive and/or directory name.

After the combo-box list box is filled, lpPathSpec is updated by removing the drive and/or directory portion of the path.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DlgDirList, CWnd::DlgDirSelect, ::DlgDirListComboBox


CWnd::DlgDirSelect

BOOL DlgDirSelect( LPTSTR lpString, int nIDListBox );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpString

Points to a buffer that is to receive the current selection in the list box.

nIDListBox

Specifies the integer ID of a list box in the dialog box.

Remarks

Retrieves the current selection from a list box. It assumes that the list box has been filled by the DlgDirList member function and that the selection is a drive letter, a file, or a directory name.

The DlgDirSelect member function copies the selection to the buffer given by lpString. If there is no selection, lpString does not change.

DlgDirSelect sends LB_GETCURSEL and LB_GETTEXT messages to the list box.

It does not allow more than one filename to be returned from a list box. The list box must not be a multiple-selection list box.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DlgDirList, CWnd::DlgDirListComboBox, CWnd::DlgDirSelectComboBox, ::DlgDirSelectEx


CWnd::DlgDirSelectComboBox

BOOL DlgDirSelectComboBox( LPTSTR lpString, int nIDComboBox );

Return Value

Nonzero if successful; otherwise 0.

Parameters

lpString

Points to a buffer that is to receive the selected path.

nIDComboBox

Specifies the integer ID of the combo box in the dialog box.

Remarks

Retrieves the current selection from the list box of a combo box. It assumes that the list box has been filled by the DlgDirListComboBox member function and that the selection is a drive letter, a file, or a directory name.

The DlgDirSelectComboBox member function copies the selection to the specified buffer. If there is no selection, the contents of the buffer are not changed.

DlgDirSelectComboBox sends CB_GETCURSEL and CB_GETLBTEXT messages to the combo box.

It does not allow more than one filename to be returned from a combo box.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DlgDirListComboBox, ::DlgDirSelectComboBoxEx


CWnd::DoDataExchange

virtual void DoDataExchange( CDataExchange* pDX );

Parameters

pDX

A pointer to a CDataExchange object.

Remarks

Called by the framework to exchange and validate dialog data.

Never call this function directly. It is called by the UpdateData member function. Call UpdateData to initialize a dialog box’s controls or retrieve data from a dialog box.

When you derive an application-specific dialog class from CDialog, you need to override this member function if you wish to utilize the framework’s automatic data exchange and validation. ClassWizard will write an overridden version of this member function for you containing the desired “data map” of dialog data exchange (DDX) and validation (DDV) global function calls.

To automatically generate an overridden version of this member function, first create a dialog resource with the dialog editor, then derive an application-specific dialog class. Then call ClassWizard and use it to associate variables, data, and validation ranges with various controls in the new dialog box. ClassWizard then writes the overridden DoDataExchange, which contains a data map. The following is an example DDX/DDV code block generated by ClassWizard:

void CPenWidthsDlg::DoDataExchange(CDataExchange* pDX)
{
   CDialog::DoDataExchange(pDX);
   //{{AFX_DATA_MAP(CPenWidthsDlg)

      DDX_Text(pDX, IDC_THIN_PEN_WIDTH, m_nThinWidth);

      DDV_MinMaxInt(pDX, m_nThinWidth, 1, 20);

      DDX_Text(pDX, IDC_THICK_PEN_WIDTH, m_nThickWidth);

      DDV_MinMaxInt(pDX, m_nThickWidth, 1, 20);
   //}}AFX_DATA_MAP
}

ClassWizard will maintain the code within the \\{{ and \\}} delimiters. You should not modify this code.

The DoDataExchange overridden member function must precede the macro statements in your source file.

For more information on dialog data exchange and validation, see Displaying and Manipulating Data in a Form in the article ODBC and MFC, Dialog Data Exchange and Validation, and Using ClassWizard in the Visual C++ Programmer's Guide. For a description of the DDX_ and DDV_ macros generated by ClassWizard, see Technical Note 26.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::UpdateData


CWnd::DragAcceptFiles

void DragAcceptFiles( BOOL bAccept = TRUE );

Parameters

bAccept Flag that indicates whether dragged files are accepted.

Remarks

Call this member function from within a window, using a CWnd pointer, in your application’s CWinApp::InitInstance function to indicate that the window accepts dropped files from the Windows File Manager or Windows Explorer.

Only the window that calls DragAcceptFiles with the bAccept parameter set to TRUE has identified itself as able to process the Windows message WM_DROPFILES. For example, in an MDI application, if the CMDIFrameWnd window pointer is used in the DragAcceptFiles function call, only the CMDIFrameWnd window gets the WM_DROPFILES message. This message is not sent to all open CMDIChildWnd windows. For a CMDIChildWnd window to receive this message, you must call DragAcceptFiles with the CMDIChildWnd window pointer.

To discontinue receiving dragged files, call the member function with bAccept set to FALSE.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::DragAcceptFiles, WM_DROPFILES


CWnd::DrawMenuBar

void DrawMenuBar( );

Remarks

Redraws the menu bar. If a menu bar is changed after Windows has created the window, call this function to draw the changed menu bar.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::DrawMenuBar


CWnd::EnableScrollBar

BOOL EnableScrollBar( int nSBFlags, UINT nArrowFlags = ESB_ENABLE_BOTH );

Return Value

Nonzero if the arrows are enabled or disabled as specified. Otherwise it is 0, which indicates that the arrows are already in the requested state or that an error occurred.

Parameters

nSBFlags

Specifies the scroll-bar type. Can have one of the following values:

  • SB_BOTH Enables or disables the arrows of the horizontal and vertical scroll bars associated with the window.

  • SB_HORZ Enables or disables the arrows of the horizontal scroll bar associated with the window.

  • SB_VERT Enables or disables the arrows of the vertical scroll bar associated with the window.

nArrowFlags

Specifies whether the scroll-bar arrows are enabled or disabled and which arrows are enabled or disabled. Can have one of the following values:

  • ESB_ENABLE_BOTH Enables both arrows of a scroll bar (default).

  • ESB_DISABLE_LTUP Disables the left arrow of a horizontal scroll bar or the up arrow of a vertical scroll bar.

  • ESB_DISABLE_RTDN Disables the right arrow of a horizontal scroll bar or the down arrow of a vertical scroll bar.

  • ESB_DISABLE_BOTH Disables both arrows of a scroll bar.

Remarks

Enables or disables one or both arrows of a scroll bar.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ShowScrollBar, CScrollBar::EnableScrollBar


CWnd::EnableScrollBarCtrl

void EnableScrollBarCtrl( int nBar, BOOL bEnable = TRUE );

Parameters

nBar

The scroll-bar identifier.

bEnable

Specifies whether the scroll bar is to be enabled or disabled.

Remarks

Call this member function to enable or disable the scroll bar for this window. If the window has a sibling scroll-bar control, that scroll bar is used; otherwise the window’s own scroll bar is used.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetScrollBarCtrl


CWnd::EnableToolTips

BOOL EnableToolTips( BOOL bEnable );

Return Value

TRUE if tooltips are enabled; otherwise FALSE.

Parameters

bEnable

Specifies whether the tooltip control is enabled or disabled. TRUE enables the control; FALSE disables the control.

Remarks

Call this member function to enable tooltips for the given window. Override OnToolHitTest to provide the TOOLINFO struct(s) for the window.

Note Some windows, such as CToolBar, provide a built-in implementation of OnToolHitTest.

See TOOLINFO in the Win32 SDK Programmer’s Reference for more information on this structure.

Simply calling EnableToolTips is not enough to display tool tips for your child controls unless the parent window is derived from CFrameWnd. This is because CFrameWnd provides a default handler for the TTN_NEEDTEXT notification. If your parent window is not derived from CFrameWnd, that is, if it is a dialog box or a form view, tool tips for your child controls will not display correctly unless you provide a handler for the TTN_NEEDTEXT tool tip notification. See Tool Tips in Visual C++ Programmer’s Guide for a sample handler.

The default tool tips provided for your windows by EnableToolTips do not have text associated with them. In order to retrieve text for the tool tip to display, the TTN_NEEDTEXT notification is sent to the tool tip control's parent window just before the tool tip window is displayed. If there is no handler for this message to assign some value to the pszText member of the TOOLTIPTEXT structure, there will be no text displayed for the tool tip.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::CancelToolTips, CWnd::OnToolHitTest, CToolBar, TOOLINFO


CWnd::EnableWindow

BOOL EnableWindow( BOOL bEnable = TRUE );

Return Value

Indicates the state before the EnableWindow member function was called. The return value is nonzero if the window was previously disabled. The return value is 0 if the window was previously enabled or an error occurred.

Parameters

bEnable

Specifies whether the given window is to be enabled or disabled. If this parameter is TRUE, the window will be enabled. If this parameter is FALSE, the window will be disabled.

Remarks

Enables or disables mouse and keyboard input. When input is disabled, input such as mouse clicks and keystrokes is ignored. When input is enabled, the window processes all input.

If the enabled state is changing, the WM_ENABLE message is sent before this function returns.

If disabled, all child windows are implicitly disabled, although they are not sent WM_ENABLE messages.

A window must be enabled before it can be activated. For example, if an application is displaying a modeless dialog box and has disabled its main window, the main window must be enabled before the dialog box is destroyed. Otherwise, another window will get the input focus and be activated. If a child window is disabled, it is ignored when Windows tries to determine which window should get mouse messages.

By default, a window is enabled when it is created. An application can specify the WS_DISABLED style in the Create or CreateEx member function to create a window that is initially disabled. After a window has been created, an application can also use the EnableWindow member function to enable or disable the window.

An application can use this function to enable or disable a control in a dialog box. A disabled control cannot receive the input focus, nor can a user access it.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::EnableWindow, CWnd::OnEnable


CWnd::EndModalLoop

void EndModalLoop( int nResult );

Parameters

nResult Contains the value to be returned to the caller of RunModalLoop.

Remarks

Call this member function to terminate a call to RunModalLoop. The nResult parameter is propagated to the return value from RunModalLoop.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::RunModalLoop, CWnd::ContinueModal


CWnd::EndPaint

void EndPaint( LPPAINTSTRUCT lpPaint );

Parameters

lpPaint

Points to a PAINTSTRUCT structure that contains the painting information retrieved by the BeginPaint member function.

Remarks

Marks the end of painting in the given window. The EndPaint member function is required for each call to the BeginPaint member function, but only after painting is complete.

If the caret was hidden by the BeginPaint member function, EndPaint restores the caret to the screen.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, ::EndPaint, CPaintDC


CWnd::ExecuteDlgInit

BOOL ExecuteDlgInit( LPCTSTR lpszResourceName );

BOOL ExecuteDlgInit( LPVOID lpResource );

Return Value

TRUE if a dialog resource is executed; otherwise FALSE.

Parameters

lpszResourceName

A pointer to a null-terminated string specifying the name of the resource.

lpResource

A pointer to a resource.

Remarks

Call this member function to initiate a dialog resource.

ExecuteDlgInit will use resources bound to the executing module, or resources from other sources. To accomplish this, ExecuteDlgInit finds a resource handle by calling AfxFindResourceHandle. If your MFC application does not use the shared DLL (MFCx0[U][D].DLL), AfxFindResourceHandle calls AfxGetResourceHandle, which returns the current resource handle for the executable. If your MFC application that uses MFCx0[U][D].DLL, AfxFindResourceHandle traverses the CDynLinkLibrary object list of shared and extension DLLs looking for the correct resource handle.

CWnd Overview | Class Members | Hierarchy Chart

See Also CDialog::OnInitDialog, ::WM_INITDIALOG


CWnd::FilterToolTipMessage

void FilterToolTipMessage( MSG* pMsg );

Parameters

pMsg A pointer to the tooltip message.

Remarks

This member function is called by the framework to to display the tooltip message associated with a button on the toolbar. It is normally called from PreTranslateMessage.

Call it when the framework does not call it for you.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnToolHitTest


CWnd::FindWindow

static CWnd* PASCAL FindWindow( LPCTSTR lpszClassName, LPCTSTR lpszWindowName );

Return Value

Identifies the window that has the specified class name and window name. It is NULL if no such window is found.

The CWnd* may be temporary and should not be stored for later use.

Parameters

lpszClassName

Points to a null-terminated string that specifies the window’s class name (a WNDCLASS structure). If lpClassName is NULL, all class names match.

lpszWindowName

Points to a null-terminated string that specifies the window name (the window’s title). If lpWindowName is NULL, all window names match.

Remarks

Returns the top-level CWnd whose window class is given by lpszClassName and whose window name, or title, is given by lpszWindowName. This function does not search child windows.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::FindWindow


CWnd::FlashWindow

BOOL FlashWindow( BOOL bInvert );

Return Value

Nonzero if the window was active before the call to the FlashWindow member function; otherwise 0.

Parameters

bInvert

Specifies whether the CWnd is to be flashed or returned to its original state. The CWnd is flashed from one state to the other if bInvert is TRUE. If bInvert is FALSE, the window is returned to its original state (either active or inactive).

Remarks

Flashes the given window once. For successive flashing, create a system timer and repeatedly call FlashWindow. Flashing the CWnd means changing the appearance of its title bar as if the CWnd were changing from inactive to active status, or vice versa. (An inactive title bar changes to an active title bar; an active title bar changes to an inactive title bar.)

Typically, a window is flashed to inform the user that it requires attention but that it does not currently have the input focus.

The bInvert parameter should be FALSE only when the window is getting the input focus and will no longer be flashing; it should be TRUE on successive calls while waiting to get the input focus.

This function always returns nonzero for minimized windows. If the window is minimized, FlashWindow will simply flash the window’s icon; bInvert is ignored for minimized windows.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::FlashWindow


CWnd::FromHandle

static CWnd* PASCAL FromHandle( HWND hWnd );

Return Value

Returns a pointer to a CWnd object when given a handle to a window. If a CWnd object is not attached to the handle, a temporary CWnd object is created and attached.

The pointer may be temporary and should not be stored for later use.

Parameters

hWnd

An HWND of a Windows window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DeleteTempMap


CWnd::FromHandlePermanent

static CWnd* PASCAL FromHandlePermanent( HWND hWnd );

Return Value

A pointer to a CWnd object.

Parameters

hWnd

An HWND of a Windows window.

Remarks

Returns a pointer to a CWnd object when given a handle to a window. If a CWnd object is not attached to the handle, NULL is returned.

This function, unlike FromHandle, does not create temporary objects.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::FromHandle


CWnd::GetActiveWindow

static CWnd* PASCAL GetActiveWindow( );

Return Value

The active window or NULL if no window was active at the time of the call. The pointer may be temporary and should not be stored for later use.

Remarks

Retrieves a pointer to the active window. The active window is either the window that has the current input focus or the window explicitly made active by the SetActiveWindow member function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetActiveWindow, ::GetActiveWindow


CWnd::GetCapture

static CWnd* PASCAL GetCapture( );

Return Value

Identifies the window that has the mouse capture. It is NULL if no window has the mouse capture.

The return value may be temporary and should not be stored for later use.

Remarks

Retrieves the window that has the mouse capture. Only one window has the mouse capture at any given time. A window receives the mouse capture when the SetCapture member function is called. This window receives mouse input whether or not the cursor is within its borders.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetCapture, ::GetCapture


CWnd::GetCaretPos

static CPoint PASCAL GetCaretPos( );

Return Value

CPoint object containing the coordinates of the caret’s position.

Remarks

Retrieves the client coordinates of the caret’s current position and returns them as a CPoint.

The caret position is given in the client coordinates of the CWnd window.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetCaretPos


CWnd::GetCheckedRadioButton

int GetCheckedRadioButton( int nIDFirstButton, int nIDLastButton );

Return Value

ID of the checked radio button, or 0 if none is selected.

Parameters

nIDFirstButton

Specifies the integer identifier of the first radio button in the group.

nIDLastButton

Specifies the integer identifier of the last radio button in the group.

Remarks

Retrieves the ID of the currently checked radio button in the specified group.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::CheckRadioButton


CWnd::GetClientRect

void GetClientRect( LPRECT lpRect ) const;

Parameters

lpRect

Points to a RECT structure or a CRect object to receive the client coordinates. The left and top members will be 0. The right and bottom members will contain the width and height of the window.

Remarks

Copies the client coordinates of the CWnd client area into the structure pointed to by lpRect. The client coordinates specify the upper-left and lower-right corners of the client area. Since client coordinates are relative to the upper-left corners of the CWnd client area, the coordinates of the upper-left corner are (0,0).

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetWindowRect, ::GetClientRect


CWnd::GetClipboardOwner

static CWnd* PASCAL GetClipboardOwner( );

Return Value

Identifies the window that owns the Clipboard if the function is successful. Otherwise, it is NULL.

The returned pointer may be temporary and should not be stored for later use.

Remarks

Retrieves the current owner of the Clipboard.

The Clipboard can still contain data even if it is not currently owned.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetClipboardViewer, ::GetClipboardOwner


CWnd::GetClipboardViewer

static CWnd* PASCAL GetClipboardViewer( );

Return Value

Identifies the window currently responsible for displaying the Clipboard if successful; otherwise NULL (for example, if there is no viewer).

The returned pointer may be temporary and should not be stored for later use.

Remarks

Retrieves the first window in the Clipboard-viewer chain.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetClipboardOwner, ::GetClipboardViewer


CWnd::GetControlUnknown

LPUNKNOWN GetControlUnknown( );

Return Value

A pointer to the IUnknown interface of the OLE control represented by this CWnd object. If this object does not represent an OLE control, the return value is NULL.

Remarks

Call this member function to retrieve a pointer to an unknown OLE control. You should not release this IUnknown pointer. Typically, you would use to obtain a specific interface of the control.

The interface pointer returned by GetControlUnknown is not reference-counted. Do not call IUnknown::Release on the pointer unless you have previously called IUnknown::AddRef on it.

CWnd Overview | Class Members | Hierarchy Chart

See Also IUnknown::Release, IUnknown::QueryInterface


CWnd::GetCurrentMessage

static const MSG* PASCAL GetCurrentMessage( );

Return Value

Returns a pointer to the MSG structure that contains the message the window is currently processing. Should only be called when in an On Message handler.


CWnd::GetDC

CDC* GetDC( );

Return Value

Identifies the device context for the CWnd client area if successful; otherwise, the return value is NULL. The pointer may be temporary and should not be stored for later use.

Remarks

Retrieves a pointer to a common, class, or private device context for the client area depending on the class style specified for the CWnd. For common device contexts, GetDC assigns default attributes to the context each time it is retrieved. For class and private contexts, GetDC leaves the previously assigned attributes unchanged. The device context can be used in subsequent graphics device interface (GDI) functions to draw in the client area.

Unless the device context belongs to a window class, the ReleaseDC member function must be called to release the context after painting. Since only five common device contexts are available at any given time, failure to release a device context can prevent other applications from accessing a device context.

A device context belonging to the CWnd class is returned by the GetDC member function if CS_CLASSDC, CS_OWNDC, or CS_PARENTDC was specified as a style in the WNDCLASS structure when the class was registered.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDCEx, CWnd::ReleaseDC, CWnd::GetWindowDC, ::GetDC, CClientDC


CWnd::GetDCEx

CDC* GetDCEx( CRgn* prgnClip, DWORD flags );

Return Value

The device context for the specified window if the function is successful; otherwise NULL.

Parameters

prgnClip

Identifies a clipping region that may be combined with the visible region of the client window.

flags

Can have one of the following preset values:

  • DCX_CACHE Returns a device context from the cache rather than the OWNDC or CLASSDC window. Overrides CS_OWNDC and CS_CLASSDC.

  • DCX_CLIPCHILDREN Excludes the visible regions of all child windows below the CWnd window.

  • DCX_CLIPSIBLINGS Excludes the visible regions of all sibling windows above the CWnd window.

  • DCX_EXCLUDERGN Excludes the clipping region identified by prgnClip from the visible region of the returned device context.

  • DCX_INTERSECTRGN Intersects the clipping region identified by prgnClip within the visible region of the returned device context.

  • DCX_LOCKWINDOWUPDATE Allows drawing even if there is a LockWindowUpdate call in effect that would otherwise exclude this window. This value is used for drawing during tracking.

  • DCX_PARENTCLIP Uses the visible region of the parent window and ignores the parent window’s WS_CLIPCHILDREN and WS_PARENTDC style bits. This value sets the device context’s origin to the upper-left corner of the CWnd window.

  • DCX_WINDOW Returns a device context that corresponds to the window rectangle rather than the client rectangle.

Remarks

Retrieves the handle of a device context for the CWnd window. The device context can be used in subsequent GDI functions to draw in the client area.

This function, which is an extension to the GetDC function, gives an application more control over how and whether a device context for a window is clipped.

Unless the device context belongs to a window class, the ReleaseDC function must be called to release the context after drawing. Since only five common device contexts are available at any given time, failure to release a device context can prevent other applications from gaining access to a device context.

In order to obtain a cached device context, an application must specify DCX_CACHE. If DCX_CACHE is not specified and the window is neither CS_OWNDC nor CS_CLASSDC, this function returns NULL.

A device context with special characteristics is returned by the GetDCEx function if the CS_CLASSDC, CS_OWNDC, or CS_PARENTDC style was specified in the WNDCLASS structure when the class was registered.

For more information about these characteristics, see the description of the WNDCLASS structure in the Win32 SDK documentation.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, CWnd::GetDC, CWnd::GetWindowDC, CWnd::ReleaseDC, ::GetDCEx


CWnd::GetDescendantWindow

CWnd* GetDescendantWindow( int nID, BOOL bOnlyPerm = FALSE ) const;

Return Value

A pointer to a CWnd object, or NULL if no child window is found.

Parameters

nID

Specifies the identifier of the control or child window to be retrieved.

bOnlyPerm

Specifies whether the window to be returned can be temporary. If TRUE, only a permanent window can be returned; if FALSE, the function can return a temporary window. For more information on temporary windows see Technical Note 3.

Remarks

Call this member function to find the descendant window specified by the given ID. This member function searches the entire tree of child windows, not only the windows that are immediate children.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetParentFrame, CWnd::IsChild, CWnd::GetDlgItem


CWnd::GetDesktopWindow

static CWnd* PASCAL GetDesktopWindow( );

Return Value

Identifies the Windows desktop window. This pointer may be temporary and should not be stored for later use.

Remarks

Returns the Windows desktop window. The desktop window covers the entire screen and is the area on top of which all icons and other windows are painted.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetDesktopWindow


CWnd::GetDlgCtrlID

int GetDlgCtrlID( ) const;

Return Value

The numeric identifier of the CWnd child window if the function is successful; otherwise 0.

Remarks

Returns the window or control ID value for any child window, not only that of a control in a dialog box. Since top-level windows do not have an ID value, the return value of this function is invalid if the CWnd is a top-level window.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetDlgCtrlID


CWnd::GetDlgItem

CWnd* GetDlgItem( int nID ) const;

void CWnd::GetDlgItem( int nID, HWND* phWnd ) const;

Return Value

A pointer to the given control or child window. If no control with the integer ID given by the nID parameter exists, the value is NULL.

The returned pointer may be temporary and should not be stored for later use.

Parameters

nID

Specifies the identifier of the control or child window to be retrieved.

phWnd

A pointer to a child window.

Remarks

Retrieves a pointer to the specified control or child window in a dialog box or other window. The pointer returned is usually cast to the type of control identified by nID.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetWindow, CWnd::GetDescendantWindow, CWnd::GetWindow, ::GetDlgItem


CWnd::GetDlgItemInt

UINT GetDlgItemInt( int nID, BOOL* lpTrans = NULL, BOOL bSigned = TRUE ) const;

Return Value

Specifies the translated value of the dialog-box item text. Since 0 is a valid return value, lpTrans must be used to detect errors. If a signed return value is desired, cast it as an int type.

The function returns 0 if the translated number is greater than 32,767 (for signed numbers) or 65,535 (for unsigned).

When errors occur, such as encountering nonnumeric characters and exceeding the above maximum, GetDlgItemInt copies 0 to the location pointed to by lpTrans. If there are no errors, lpTrans receives a nonzero value. If lpTrans is NULL, GetDlgItemInt does not warn about errors.

Parameters

nID

Specifies the integer identifier of the dialog-box control to be translated.

lpTrans

Points to the Boolean variable that is to receive the translated flag.

bSigned

Specifies whether the value to be retrieved is signed.

Remarks

Retrieves the text of the control identified by nID. It translates the text of the specified control in the given dialog box into an integer value by stripping any extra spaces at the beginning of the text and converting decimal digits. It stops the translation when it reaches the end of the text or encounters any nonnumeric character.

If bSigned is TRUE, GetDlgItemInt checks for a minus sign (–) at the beginning of the text and translates the text into a signed number. Otherwise, it creates an unsigned value.

It sends a WM_GETTEXT message to the control.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDlgItemText, ::GetDlgItemInt


CWnd::GetDlgItemText

int GetDlgItemText( int nID, LPTSTR lpStr, int nMaxCount ) const;

int GetDlgItemText( int nID, CString& rString ) const;

Return Value

Specifies the actual number of bytes copied to the buffer, not including the terminating null character. The value is 0 if no text is copied.

Parameters

nID

Specifies the integer identifier of the control whose title is to be retrieved.

lpStr

Points to the buffer to receive the control’s title or text.

nMaxCount

Specifies the maximum length (in bytes) of the string to be copied to lpStr. If the string is longer than nMaxCount, it is truncated.

rString

A reference to a CString.

Remarks

Call this member function to retrieve the title or text associated with a control in a dialog box. The GetDlgItemText member function copies the text to the location pointed to by lpStr and returns a count of the number of bytes it copies.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDlgItem, CWnd::GetDlgItemInt, ::GetDlgItemText, WM_GETTEXT


CWnd::GetDSCCursor

IUnknown * GetDSCCursor( );

Return Value

A pointer to a cursor that is defined by a data-source control. MFC takes care of calling AddRef for the pointer.

Remarks

Call this member function to retrieve a pointer to the underlying cursor that is defined by the DataSource, UserName, Password, and SQL properties of the data-source control. Use the returned pointer to set the ICursor property of a complex data-bound control, such as the data-bound grid control. A data-source control will not become active until the first bound control requests its cursor. This can happen either explicitly by a call to GetDSCCursor or implicitly by the MFC binding manager. In either case, you can force a data-source control to become active by calling GetDSCCursor and then calling Release on the returned pointer to IUnknown. Activation will cause the data-source control to attempt to connect to the underlying data source. The returned pointer might be used in the following context:

BOOL CMyDlg::OnInitDialog()
{
   // Find the child controls on the dialog
   CWnd* pDSC = GetDlgItem(IDC_REMOTEDATACONTROL);
   CDBListBox* pList = (CDBListBox*)
   GetDlgItem(IDC_DBLISTBOX);

   // Tell the MFC binding manager that we are
   // binding DISPID 3 to the data-source control.
   pList->BindProperty(0x3, pDSC);

   // Tell the listbox which field to expose as its
   // bound column
   pList->SetBoundColumn(_T("CourseID"));

   // Tell the listbox which cursor and column
   // to populate its list from
   pList->SetListField(_T("CourseID"));
   IPUNKNOWN *pcursor = pDSC->GetDSCCursor();
   ...
   if (!pcursor)
   {
   // The pointer was not successfully assigned.
      return FALSE;
   }
   // The pointer was successfully assigned,
   pList->SetRowSource(pcursor);
   ...
   pcursor->Release();
   return TRUE;
}

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BindDefaultProperty, CWnd::BindProperty


CWnd::GetExStyle

DWORD GetExStyle( ) const;

Return Value

The window’s extended style.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetStyle, ::GetWindowLong


CWnd::GetFocus

static CWnd* PASCAL GetFocus( );

Return Value

A pointer to the window that has the current focus, or NULL if there is no focus window.

The pointer may be temporary and should not be stored for later use.

Remarks

Retrieves a pointer to the CWnd that currently has the input focus.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetActiveWindow, CWnd::GetCapture, CWnd::SetFocus, ::GetFocus


CWnd::GetFont

CFont* GetFont( ) const;

Return Value

A pointer to a CFont that contains the current font.

The pointer may be temporary and should not be stored for later use.

Remarks

Gets the current font for this window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetFont, WM_GETFONT, CFont


CWnd::GetForegroundWindow

static CWnd* PASCAL GetForegroundWindow( );

Return Value

A pointer to the foreground window. This may be a temporary CWnd object.

Remarks

Returns a pointer to the foreground window (the window with which the user is currently working). The foreground window applies only to top-level windows (frame windows or dialog boxes).

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetForegroundWindow


CWnd::GetIcon

HICON GetIcon( BOOL bBigIcon ) const;

Return Value

A handle to an icon. If unsuccessful, returns NULL.

Parameters

bBigIcon

Specifies a 32 pixel by 32 pixel icon if TRUE; specifies a 16 pixel by 16 pixel icon if FALSE.

Remarks

Call this member function to get the handle to either a big (32x32) or the handle to a small (16x16) icon, as indicated by bBigIcon.

CWnd Overview | Class Members | Hierarchy Chart

See Also SetIcon


CWnd::GetLastActivePopup

CWnd* GetLastActivePopup( ) const;

Return Value

Identifies the most recently active pop-up window. The return value will be the window itself if any of the following conditions are met:

  • The window itself was most recently active.

  • The window does not own any pop-up windows.

  • The window is not a top-level window or is owned by another window.

The pointer may be temporary and should not be stored for later use.

Remarks

Determines which pop-up window owned by CWnd was most recently active.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetLastActivePopup


CWnd::GetMenu

CMenu* GetMenu( ) const;

Return Value

Identifies the menu. The value is NULL if CWnd has no menu. The return value is undefined if CWnd is a child window.

The returned pointer may be temporary and should not be stored for later use.

Remarks

Retrieves a pointer to the menu for this window. This function should not be used for child windows because they do not have a menu.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetMenu


CWnd::GetNextDlgGroupItem

CWnd* GetNextDlgGroupItem( CWnd* pWndCtl, BOOL bPrevious = FALSE ) const;

Return Value

Pointer to the previous (or next) control in the group if the member function is successful.

The returned pointer may be temporary and should not be stored for later use.

Parameters

pWndCtl

Identifies the control to be used as the starting point for the search.

bPrevious

Specifies how the function is to search the group of controls in the dialog box. If TRUE, the function searches for the previous control in the group; if FALSE, it searches for the next control in the group.

Remarks

Searches for the previous (or next) control within a group of controls in a dialog box. A group of controls begins with a control that was created with the WS_GROUP style and ends with the last control that was not created with the WS_GROUP style.

By default, the GetNextDlgGroupItem member function returns a pointer to the next control in the group. If pWndCtl identifies the first control in the group and bPrevious is TRUE, GetNextDlgGroupItem returns a pointer to the last control in the group.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetNextDlgTabItem, ::GetNextDlgGroupItem


CWnd::GetNextDlgTabItem

CWnd* GetNextDlgTabItem( CWnd* pWndCtl, BOOL bPrevious = FALSE ) const;

Return Value

Pointer to the previous (or next) control that has the WS_TABSTOP style, if the member function is successful.

The returned pointer may be temporary and should not be stored for later use.

Parameters

pWndCtl

Identifies the control to be used as the starting point for the search.

bPrevious

Specifies how the function is to search the dialog box. If TRUE, the function searches for the previous control in the dialog box; if FALSE, it searches for the next control.

Remarks

Retrieves a pointer to the first control that was created with the WS_TABSTOP style and that precedes (or follows) the specified control.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetNextDlgGroupItem, ::GetNextDlgTabItem


CWnd::GetNextWindow

CWnd* GetNextWindow( UINT nFlag = GW_HWNDNEXT ) const;

Return Value

Identifies the next (or the previous) window in the window manager’s list if the member function is successful.

The returned pointer may be temporary and should not be stored for later use.

Parameters

nFlag

Specifies whether the function returns a pointer to the next window or the previous window. It can be either GW_HWNDNEXT, which returns the window that follows the CWnd object on the window manager’s list, or GW_HWNDPREV, which returns the previous window on the window manager’s list.

Remarks

Searches for the next (or previous) window in the window manager’s list. The window manager’s list contains entries for all top-level windows, their associated child windows, and the child windows of any child windows.

If CWnd is a top-level window, the function searches for the next (or previous) top-level window; if CWnd is a child window, the function searches for the next (or previous) child window.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetNextWindow


CWnd::GetOpenClipboardWindow

static CWnd* PASCAL GetOpenClipboardWindow( );

Return Value

The handle of the window that currently has the Clipboard open if the function is successful; otherwise NULL.

Remarks

Retrieves the handle of the window that currently has the Clipboard open.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetClipboardOwner, CWnd::GetClipboardViewer, CWnd::OpenClipboard, ::GetOpenClipboardWindow


CWnd::GetOwner

CWnd* GetOwner( ) const;

Return Value

A pointer to a CWnd object.

Remarks

Retrieves a pointer to the owner of the window. If the window has no owner, then a pointer to the parent window object is returned by default. Note that the relationship between the owner and the owned differs from the parent-child aspect in several important aspects. For example, a window with a parent is confined to its parent window’s client area. Owned windows can be drawn at any location on the desktop.

The ownership concept of this function is different from the ownership concept of GetWindow.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetParent, CWnd::SetOwner


CWnd::GetParent

CWnd* GetParent( ) const;

Return Value

Identifies the parent window if the member function is successful. Otherwise, the value is NULL, which indicates an error or no parent window.

The returned pointer may be temporary and should not be stored for later use.

Remarks

Call this function to get a pointer to a child window’s parent window (if any). The GetParent function returns a pointer the immediate parent. In contrast, the GetParentOwner function returns a pointer to the most immediate parent or owner window that is not a child window (does not have the WS_CHILD style). If you have a child window within a child window GetParent and GetParentOwner return different results.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetParentOwner, CWnd::GetOwner, CWnd::SetOwner, CWnd::SetParent, ::GetParent


CWnd::GetParentFrame

CFrameWnd* GetParentFrame( ) const;

Return Value

A pointer to a frame window if successful; otherwise NULL.

Remarks

Call this member function to retrieve the parent frame window. The member function searches up the parent chain until a CFrameWnd (or derived class) object is found.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDescendantWindow, CWnd::GetParent, CFrameWnd::GetActiveView


CWnd::GetParentOwner

CWnd* GetParentOwner( ) const;

Return Value

A pointer to a CWnd object. If a CWnd object is not attached to the handle, a temporary CWnd object is created and attached. The pointer may be temporary and should not be stored for later use.

Remarks

Call this member function to get a pointer to a child window’s parent window or owner window. GetParentOwner returns a pointer to the most immediate parent or owner window that is not a child window (does not have the WS_CHILD style). The current owner window can be set with SetOwner. By default, the parent of a window is its owner.

In contrast, the GetParent function returns a pointer to the immediate parent, whether it is a child window or not. If you have a child window within a child window GetParent and GetParentOwner return different results.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetParent, CWnd::GetOwner, CWnd::SetOwner, CWnd::SetParent, ::GetParent


CWnd::GetProperty

void GetProperty( DISPID dwDispID, VARTYPE vtProp, void* pvProp )const;

Parameters

dwDispID

Identifies the property to be retrieved. This value is usually supplied by Component Gallery.

vtProp

Specifies the type of the property to be retrieved. For possible values, see the Remarks section for COleDispatchDriver::InvokeHelper.

pvProp

Address of the variable that will that will receive the property value. It must match the type specified by vtProp.

Remarks

Call this member function to get the OLE control property specified by dwDispID. GetProperty then returns the value through pvProp.

Note This function should be called only on a CWnd object that represents an OLE control.

For more information about using this member function with OLE Control Containers, see the article ActiveX Control Containers: Programming ActiveX Controls in an ActiveX Control Container, in Visual C++ Programmer’s Guide.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::InvokeHelper, COleDispatchDriver, CWnd::CreateControl


CWnd::GetSafeHwnd

HWND GetSafeHwnd( ) const;

Return Value

Returns the window handle for a window. Returns NULL if the CWnd is not attached to a window or if it is used with a NULL CWnd pointer.


CWnd::GetSafeOwner

CWnd* PASCAL GetSafeOwner( CWnd* pParent, HWND* pWndTop );

Return Value

A pointer to the safe owner for the given window.

Parameters

pParent

A pointer to a parent CWnd window.

pWndTop

A pointer to the window that is currently on top. May be NULL.

Remarks

Call this member function to retrieve the owner window that should be used for dialog boxes or other modal windows. The safe owner is the first non-child parent window of pParentWnd. If pParentWnd is NULL, the thread’s main window (retrieved via AfxGetMainWnd) is used to find an owner.

Note The framework itself uses this function to determine the correct owner window for dialog boxes and property sheets where the owner is not specified.

CWnd Overview | Class Members | Hierarchy Chart

See Also AfxGetMainWnd


CWnd::GetScrollBarCtrl

virtual CScrollBar* GetScrollBarCtrl( int nBar ) const;

Return Value

A sibling scroll-bar control, or NULL if none.

Parameters

nBar

Specifies the type of scroll bar. The parameter can take one of the following values:

  • SB_HORZ Retrieves the position of the horizontal scroll bar.

  • SB_VERT Retrieves the position of the vertical scroll bar.

Remarks

Call this member function to obtain a pointer to the specified sibling scroll bar or splitter window.

This member function does not operate on scroll bars created when the WS_HSCROLL or WS_VSCROLL bits are set during the creation of a window. The CWnd implementation of this function simply returns NULL. Derived classes, such as CView, implement the described functionality.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::EnableScrollBarCtrl


CWnd::GetScrollInfo

BOOL GetScrollInfo( int nBar, LPSCROLLINFO lpScrollInfo, UINT nMask = SIF_ALL );

Return Value

If the message retrieved any values, the return is TRUE. Otherwise, it is FALSE.

Parameters

nBar

Specifies whether the scroll bar is a control or part of a window’s nonclient area. If it is part of the nonclient area, nBar also indicates whether the scroll bar is positioned horizontally, vertically, or both. It must be one of the following:

  • SB_CTL Contains the parameters for a scroll bar control. The m_hWnd data member must be the handle of the scroll bar control.

  • SB_HORZ Specifies that the window is a horizontal scroll bar.

  • SB_VERT Specifies that the window is a vertical scroll bar.

lpScrollInfo

A pointer to a SCROLLINFO structure. See the Win32 SDK Programmer’s Reference for more information about this structure.

nMask

Specifies the scroll bar parameters to retrieve. The default specifies a combination of SIF_PAGE, SIF_POS, SIF_TRACKPOS, and SIF_RANGE. See SCROLLINFO for more information on the nMask values.

Remarks

Call this member function to retrieve the information that the SCROLLINFO structure maintains about a scroll bar. GetScrollInfo enables applications to use 32-bit scroll positions.

The SCROLLINFO structure contains information about a scroll bar, including the minimum and maximum scrolling positions, the page size, and the position of the scroll box (the thumb). See the SCROLLINFO structure topic in the Win32 SDK Programmer’s Reference for more information about changing the structure defaults.

The MFC Windows message handlers that indicate scroll-bar position, CWnd::OnHScroll and CWnd::OnVScroll, provide only 16 bits of position data. GetScrollInfo and SetScrollInfo provide 32 bits of scroll-bar position data. Thus, an application can call GetScrollInfo while processing either CWnd::OnHScroll or CWnd::OnVScroll to obtain 32-bit scroll-bar position data.

CWnd Overview | Class Members | Hierarchy Chart

See Also CScrollBar::GetScrollInfo, CWnd::SetScrollInfo, CWnd::SetScrollPos, CWnd::OnVScroll, CWnd::OnHScroll, SCROLLINFO


CWnd::GetScrollLimit

int GetScrollLimit( int nBar );

Return Value

Specifies the maximum position of a scroll bar if successful; otherwise 0.

Parameters

nBar

Specifies the type of scroll bar. The parameter can take one of the following values:

  • SB_HORZ Retrieves the scroll limit of the horizontal scroll bar.

  • SB_VERT Retrieves the scroll limit of the vertical scroll bar.

Remarks

Call this member function to retrieve the maximum scrolling position of the scroll bar.

CWnd Overview | Class Members | Hierarchy Chart

See Also CScrollBar::GetScrollLimit


CWnd::GetScrollPos

int GetScrollPos( int nBar ) const;

Return Value

Specifies the current position of the scroll box in the scroll bar if successful; otherwise 0.

Parameters

nBar

Specifies the scroll bar to examine. The parameter can take one of the following values:

  • SB_HORZ Retrieves the position of the horizontal scroll bar.

  • SB_VERT Retrieves the position of the vertical scroll bar.

Remarks

Retrieves the current position of the scroll box of a scroll bar. The current position is a relative value that depends on the current scrolling range. For example, if the scrolling range is 50 to 100 and the scroll box is in the middle of the bar, the current position is 75.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetScrollPos, CScrollBar::GetScrollPos


CWnd::GetScrollRange

void GetScrollRange( int nBar, LPINT lpMinPos, LPINT lpMaxPos ) const;

Parameters

nBar

Specifies the scroll bar to examine. The parameter can take one of the following values:

  • SB_HORZ Retrieves the position of the horizontal scroll bar.

  • SB_VERT Retrieves the position of the vertical scroll bar.

lpMinPos

Points to the integer variable that is to receive the minimum position.

lpMaxPos

Points to the integer variable that is to receive the maximum position.

Remarks

Copies the current minimum and maximum scroll-bar positions for the given scroll bar to the locations specified by lpMinPos and lpMaxPos. If CWnd does not have a scroll bar, then the GetScrollRange member function copies 0 to lpMinPos and lpMaxPos.

The default range for a standard scroll bar is 0 to 100. The default range for a scroll-bar control is empty (both values are 0).

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetScrollRange


CWnd::GetStyle

DWORD GetStyle( ) const;

Return Value

The window’s style.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetWindowLong


CWnd::GetSystemMenu

CMenu* GetSystemMenu( BOOL bRevert ) const;

Return Value

Identifies a copy of the Control menu if bRevert is FALSE. If bRevert is TRUE, the return value is undefined.

The returned pointer may be temporary and should not be stored for later use.

Parameters

bRevert

Specifies the action to be taken. If bRevert is FALSE, GetSystemMenu returns a handle to a copy of the Control menu currently in use. This copy is initially identical to the Control menu but can be modified. If bRevert is TRUE, GetSystemMenu resets the Control menu back to the default state. The previous, possibly modified, Control menu, if any, is destroyed. The return value is undefined in this case.

Remarks

Allows the application to access the Control menu for copying and modification.

Any window that does not use GetSystemMenu to make its own copy of the Control menu receives the standard Control menu.

The pointer returned by the GetSystemMenu member function can be used with the CMenu::AppendMenu, CMenu::InsertMenu, or CMenu::ModifyMenu functions to change the Control menu.

The Control menu initially contains items identified with various ID values such as SC_CLOSE, SC_MOVE, and SC_SIZE. Items on the Control menu generate WM_SYSCOMMAND messages. All predefined Control-menu items have ID numbers greater than 0xF000. If an application adds items to the Control menu, it should use ID numbers less than F000.

Windows may automatically dim items on the standard Control menu. CWnd can carry out its own checking or dimming by responding to the WM_INITMENU messages, which are sent before any menu is displayed.

CWnd Overview | Class Members | Hierarchy Chart

See Also CMenu::AppendMenu, CMenu::InsertMenu, CMenu::ModifyMenu, ::GetSystemMenu


CWnd::GetTopLevelFrame

CFrameWnd* GetTopLevelFrame( ) const;

Return Value

Identifies the top-level frame window of the window.

The returned pointer may be temporary and should not be stored for later use.

Remarks

Call this member function to retrieve the window’s top level frame window, if any. If CWnd has no attached window, or its top-level parent is not a CFrameWnd-derived object, this function returns NULL.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetTopLevelOwner, CWnd::GetTopLevelParent


CWnd::GetTopLevelOwner

CWnd* GetTopLevelOwner( ) const;

Return Value

Identifies the top-level window. The returned pointer may be temporary and should not be stored for later use.

Remarks

Call this member function to retrieve the top-level window. The top-level window is the window that is a child of the desktop. If CWnd has no attached window, this function returns NULL.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetTopLevelFrame, CWnd::GetTopLevelParent


CWnd::GetTopLevelParent

CWnd* GetTopLevelParent( ) const;

Return Value

Identifies the top-level parent window of the window.

The returned pointer may be temporary and should not be stored for later use.

Remarks

Call this member function to retrieve the window’s top-level parent. GetTopLevelParent is similar to GetTopLevelFrame and GetTopLevelOwner; however, it ignores the value set as the current owner window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetTopLevelOwner, CWnd::GetTopLevelFrame, CWnd::GetOwner, CWnd::SetOwner


CWnd::GetTopWindow

CWnd* GetTopWindow( ) const;

Return Value

Identifies the top-level child window in a CWnd linked list of child windows. If no child windows exist, the value is NULL.

The returned pointer may be temporary and should not be stored for later use.

Remarks

Searches for the top-level child window that belongs to CWnd. If CWnd has no children, this function returns NULL.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetTopWindow


CWnd::GetUpdateRect

BOOL GetUpdateRect( LPRECT lpRect, BOOL bErase = FALSE );

Return Value

Specifies the status of the update region. The value is nonzero if the update region is not empty; otherwise 0.

If the lpRect parameter is set to NULL, the return value is nonzero if an update region exists; otherwise 0.

Parameters

lpRect

Points to a CRect object or RECT structure that is to receive the client coordinates of the update that encloses the update region.

Set this parameter to NULL to determine whether an update region exists within the CWnd. If lpRect is NULL, the GetUpdateRect member function returns nonzero if an update region exists and 0 if one does not. This provides a way to determine whether a WM_PAINT message resulted from an invalid area. Do not set this parameter to NULL in Windows version 3.0 and earlier.

bErase

Specifies whether the background in the update region is to be erased.

Remarks

Retrieves the coordinates of the smallest rectangle that completely encloses the update region. If CWnd was created with the CS_OWNDC style and the mapping mode is not MM_TEXT, the GetUpdateRect member function gives the rectangle in logical coordinates. Otherwise, GetUpdateRect gives the rectangle in client coordinates. If there is no update region, GetUpdateRect sets the rectangle to be empty (sets all coordinates to 0).

The bErase parameter specifies whether GetUpdateRect should erase the background of the update region. If bErase is TRUE and the update region is not empty, the background is erased. To erase the background, GetUpdateRect sends the WM_ERASEBKGND message.

The update rectangle retrieved by the BeginPaint member function is identical to that retrieved by the GetUpdateRect member function.

The BeginPaint member function automatically validates the update region, so any call to GetUpdateRect made immediately after a call to BeginPaint retrieves an empty update region.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, ::GetUpdateRect, CWnd::OnPaint, CWnd::RedrawWindow


CWnd::GetUpdateRgn

int GetUpdateRgn( CRgn* pRgn, BOOL bErase = FALSE );

Return Value

Specifies a short-integer flag that indicates the type of resulting region. The value can take any one of the following:

  • SIMPLEREGION The region has no overlapping borders.

  • COMPLEXREGION The region has overlapping borders.

  • NULLREGION The region is empty.

  • ERROR No region was created.

Parameters

pRgn

Identifies the update region.

bErase

Specifies whether the background will be erased and nonclient areas of child windows will be drawn. If the value is FALSE, no drawing is done.

Remarks

Retrieves the update region into a region identified by pRgn. The coordinates of this region are relative to the upper-left corner (client coordinates).

The BeginPaint member function automatically validates the update region, so any call to GetUpdateRgn made immediately after a call to BeginPaint retrieves an empty update region.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, ::GetUpdateRgn


CWnd::GetWindow

CWnd* GetWindow( UINT nCmd ) const;

Return Value

Returns a pointer to the window requested, or NULL if none.

The returned pointer may be temporary and should not be stored for later use.

Parameters

nCmd

Specifies the relationship between CWnd and the returned window. It can take one of the following values:

  • GW_CHILD Identifies the CWnd first child window.

  • GW_HWNDFIRST If CWnd is a child window, returns the first sibling window. Otherwise, it returns the first top-level window in the list.

  • GW_HWNDLAST If CWnd is a child window, returns the last sibling window. Otherwise, it returns the last top-level window in the list.

  • GW_HWNDNEXT Returns the next window on the window manager’s list.

  • GW_HWNDPREV Returns the previous window on the window manager’s list.

  • GW_OWNER Identifies the CWnd owner.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetParent, CWnd::GetNextWindow, ::GetWindow


CWnd::GetWindowContextHelpId

DWORD GetWindowContextHelpId( ) const;

Return Value

The help context identifier. Returns 0 if the window has none.

Remarks

Call this member function to retrieve the help context identifier, if any, associated with the window.


CWnd::GetWindowDC

CDC* GetWindowDC( );

Return Value

Identifies the display context for the given window if the function is successful; otherwise NULL.

The returned pointer may be temporary and should not be stored for later use. ReleaseDC should be called once for each successful call to GetWindowDC.

Remarks

Retrieves the display context for the entire window, including caption bar, menus, and scroll bars. A window display context permits painting anywhere in CWnd, since the origin of the context is the upper-left corner of CWnd instead of the client area.

Default attributes are assigned to the display context each time it retrieves the context. Previous attributes are lost.

GetWindowDC is intended to be used for special painting effects within the CWnd nonclient area. Painting in nonclient areas of any window is not recommended.

The GetSystemMetrics Windows function can be used to retrieve the dimensions of various parts of the nonclient area, such as the caption bar, menu, and scroll bars.

After painting is complete, the ReleaseDC member function must be called to release the display context. Failure to release the display context will seriously affect painting requested by applications due to limitations on the number of device contexts that can be open at the same time.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetSystemMetrics, CWnd::ReleaseDC, ::GetWindowDC, CWnd::GetDC, CWindowDC


CWnd::GetWindowPlacement

BOOL GetWindowPlacement( WINDOWPLACEMENT* lpwndpl ) const;

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpwndpl

Points to the WINDOWPLACEMENT structure that receives the show state and position information.

Remarks

Retrieves the show state and the normal (restored), minimized, and maximized positions of a window.

The flags member of the WINDOWPLACEMENT structure retrieved by this function is always 0. If CWnd is maximized, the showCmd member of WINDOWPLACEMENT is SW_SHOWMAXIMIZED. If the window is minimized, it is SW_SHOWMINIMIZED. It is SW_SHOWNORMAL otherwise.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetWindowPlacement, ::GetWindowPlacement


CWnd::GetWindowRect

void GetWindowRect( LPRECT lpRect ) const;

Parameters

lpRect

Points to a CRect object or a RECT structure that will receive the screen coordinates of the upper-left and lower-right corners.

Remarks

Copies the dimensions of the bounding rectangle of the CWnd object to the structure pointed to by lpRect. The dimensions are given in screen coordinates relative to the upper-left corner of the display screen. The dimensions of the caption, border, and scroll bars, if present, are included.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetClientRect, CWnd::MoveWindow, CWnd::SetWindowPos, ::GetWindowRect


CWnd::GetWindowRgn

int GetWindowRgn( HRGN hRgn )const;

Return Value

The return value specifies the type of the region that the function obtains. It can be one of the following values:

  • NULLREGION The region is empty.

  • SIMPLEREGION The region is a single rectangle.

  • COMPLEXREGION The region is more than one rectangle.

  • ERROR An error occurred; the region is unaffected.

Parameters

hRgn

A handle to a window region.

Remarks

Call this member function to get the window region of a window. The window region determines the area within the window where the operating system permits drawing. The operating system does not display any portion of a window that lies outside of the window region.

The coordinates of a window’s window region are relative to the upper-left corner of the window, not the client area of the window.

To set the window region of a window, call CWnd::SetWindowRgn.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetWindowRgn


CWnd::GetWindowText

int GetWindowText( LPTSTR lpszStringBuf, int nMaxCount ) const;

void GetWindowText( CString& rString ) const;

Return Value

Specifies the length, in bytes, of the copied string, not including the terminating null character. It is 0 if CWnd has no caption or if the caption is empty.

Parameters

lpszStringBuf

Points to the buffer that is to receive the copied string of the window’s title.

nMaxCount

Specifies the maximum number of characters to be copied to the buffer. If the string is longer than the number of characters specified in nMaxCount, it is truncated.

rString

A CString object that is to receive the copied string of the window’s title.

Remarks

Copies the CWnd caption title (if it has one) into the buffer pointed to by lpszStringBuf or into the destination string rString. If the CWnd object is a control, the GetWindowText member function copies the text within the control instead of copying the caption.

This member function causes the WM_GETTEXT message to be sent to the CWnd object.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetWindowText, WM_GETTEXT, CWnd::GetWindowTextLength


CWnd::GetWindowTextLength

int GetWindowTextLength( ) const;

Return Value

Specifies the text length, not including any null-termination character. The value is 0 if no such text exists.

Remarks

Returns the length of the CWnd object caption title. If CWnd is a control, the GetWindowTextLength member function returns the length of the text within the control instead of the caption.

This member function causes the WM_GETTEXTLENGTH message to be sent to the CWnd object.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetWindowTextLength, WM_GETTEXTLENGTH, CWnd::GetWindowText


CWnd::HideCaret

void HideCaret( );

Remarks

Hides the caret by removing it from the display screen. Although the caret is no longer visible, it can be displayed again by using the ShowCaret member function. Hiding the caret does not destroy its current shape.

Hiding is cumulative. If HideCaret has been called five times in a row, the ShowCaret member function must be called five times before the caret will be shown.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ShowCaret, ::HideCaret


CWnd::HiliteMenuItem

BOOL HiliteMenuItem( CMenu* pMenu, UINT nIDHiliteItem, UINT nHilite );

Return Value

Specifies whether the menu item was highlighted. Nonzero if the item was highlighted; otherwise 0.

Parameters

pMenu

Identifies the top-level menu that contains the item to be highlighted.

nIDHiliteItem

Specifies the menu item to be highlighted, depending on the value of the nHilite parameter.

nHilite

Specifies whether the menu item is highlighted or the highlight is removed. It can be a combination of MF_HILITE or MF_UNHILITE with MF_BYCOMMAND or MF_BYPOSITION. The values can be combined using the bitwise OR operator. These values have the following meanings:

  • MF_BYCOMMAND Interprets nIDHiliteItem as the menu-item ID (the default interpretation).

  • MF_BYPOSITION Interprets nIDHiliteItem as the zero-based offset of the menu item.

  • MF_HILITE Highlights the item. If this value is not given, the highlight is removed from the item.

  • MF_UNHILITE Removes the highlight from the item.

Remarks

Highlights or removes the highlight from a top-level (menu-bar) menu item.

The MF_HILITE and MF_UNHILITE flags can be used only with this member function; they cannot be used with the CMenu::ModifyMenu member function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CMenu::ModifyMenu, ::HiliteMenuItem


CWnd::Invalidate

void Invalidate( BOOL bErase = TRUE );

Parameters

bErase

Specifies whether the background within the update region is to be erased.

Remarks

Invalidates the entire client area of CWnd. The client area is marked for painting when the next WM_PAINT message occurs. The region can also be validated before a WM_PAINT message occurs by the ValidateRect or ValidateRgn member function.

The bErase parameter specifies whether the background within the update area is to be erased when the update region is processed. If bErase is TRUE, the background is erased when the BeginPaint member function is called; if bErase is FALSE, the background remains unchanged. If bErase is TRUE for any part of the update region, the background in the entire region, not just in the given part, is erased.

Windows sends a WM_PAINT message whenever the CWnd update region is not empty and there are no other messages in the application queue for that window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, CWnd::ValidateRect, CWnd::ValidateRgn, ::InvalidateRect


CWnd::InvalidateRect

void InvalidateRect( LPCRECT lpRect, BOOL bErase = TRUE );

Parameters

lpRect

Points to a CRect object or a RECT structure that contains the rectangle (in client coordinates) to be added to the update region. If lpRect is NULL, the entire client area is added to the region.

bErase

Specifies whether the background within the update region is to be erased.

Remarks

Invalidates the client area within the given rectangle by adding that rectangle to the CWnd update region. The invalidated rectangle, along with all other areas in the update region, is marked for painting when the next WM_PAINT message is sent. The invalidated areas accumulate in the update region until the region is processed when the next WM_PAINT call occurs, or until the region is validated by the ValidateRect or ValidateRgn member function.

The bErase parameter specifies whether the background within the update area is to be erased when the update region is processed. If bErase is TRUE, the background is erased when the BeginPaint member function is called; if bErase is FALSE, the background remains unchanged. If bErase is TRUE for any part of the update region, the background in the entire region is erased, not just in the given part.

Windows sends a WM_PAINT message whenever the CWnd update region is not empty and there are no other messages in the application queue for that window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, CWnd::ValidateRect, CWnd::ValidateRgn, ::InvalidateRect


CWnd::InvalidateRgn

void InvalidateRgn( CRgn* pRgn, BOOL bErase = TRUE );

Parameters

pRgn

A pointer to a CRgn object that identifies the region to be added to the update region. The region is assumed to have client coordinates. If this parameter is NULL, the entire client area is added to the update region.

bErase

Specifies whether the background within the update region is to be erased.

Remarks

Invalidates the client area within the given region by adding it to the current update region of CWnd. The invalidated region, along with all other areas in the update region, is marked for painting when the WM_PAINT message is next sent. The invalidated areas accumulate in the update region until the region is processed when a WM_PAINT message is next sent, or until the region is validated by the ValidateRect or ValidateRgn member function.

The bErase parameter specifies whether the background within the update area is to be erased when the update region is processed. If bErase is TRUE, the background is erased when the BeginPaint member function is called; if bErase is FALSE, the background remains unchanged. If bErase is TRUE for any part of the update region, the background in the entire region, not just in the given part, is erased.

Windows sends a WM_PAINT message whenever the CWnd update region is not empty and there are no other messages in the application queue for that window.

The given region must have been previously created by one of the region functions.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, CWnd::ValidateRect, CWnd::ValidateRgn, ::InvalidateRgn


CWnd::InvokeHelper

void InvokeHelper( DISPID dwDispID, WORD wFlags, VARTYPE vtRet, void* pvRet, const BYTE* pbParamInfo, ... );
throw( COleException );
throw( COleDispatchException );

Parameters

dwDispID

Identifies the method or property to be invoked. This value is usually supplied by Component Gallery.

wFlags

Flags describing the context of the call to IDispatch::Invoke. For possible wFlags values, see IDispatch::Invoke in the Win32 SDK OLE Programmer's Reference.

vtRet

Specifies the type of the return value. For possible values, see the Remarks section for COleDispatchDriver::InvokeHelper.

pvRet

Address of the variable that will that will receive the property value or return value. It must match the type specified by vtRet.

pbParamInfo

Pointer to a null-terminated string of bytes specifying the types of the parameters following pbParamInfo. For possible values, see the Remarks section for COleDispatchDriver::InvokeHelper.

...

Variable List of parameters, of types specified in pbParamInfo.

Remarks

Call this member function to invoke the OLE control method or property specified by dwDispID, in the context specified by wFlags. The pbParamInfo parameter specifies the types of the parameters passed to the method or property. The variable list of arguments is represented by ... in the syntax declaration.

This function converts the parameters to VARIANTARG values, then invokes the IDispatch::Invoke method on the OLE control. If the call to IDispatch::Invoke fails, this function will throw an exception. If the SCODE (status code) returned by IDispatch::Invoke is DISP_E_EXCEPTION, this function throws a COleException object, otherwise it throws a COleDispatchException.

Note This function should be called only on a CWnd object that represents an OLE control.

For more information about using this member function with OLE Control Containers, see the article ActiveX Control Containers: Programming ActiveX Controls in an ActiveX Control Container, in Visual C++ Programmer’s Guide.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetProperty, CWnd::SetProperty, COleDispatchDriver, CWnd::CreateControl


CWnd::IsChild

BOOL IsChild( const CWnd* pWnd ) const;

Return Value

Specifies the outcome of the function. The value is nonzero if the window identified by pWnd is a child window of CWnd; otherwise 0.

Parameters

pWnd

Identifies the window to be tested.

Remarks

Indicates whether the window specified by pWnd is a child window or other direct descendant of CWnd. A child window is the direct descendant of CWnd if the CWnd object is in the chain of parent windows that leads from the original pop-up window to the child window.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::IsChild


CWnd::IsDialogMessage

BOOL IsDialogMessage( LPMSG lpMsg );

Return Value

Specifies whether the member function has processed the given message. It is nonzero if the message has been processed; otherwise 0. If the return is 0, call the CWnd::PreTranslateMessage member function of the base class to process the message. In an override of the CWnd::PreTranslateMessage member function the code looks like this :

BOOL CMyDlg::PreTranslateMessage( msg )
{
    if( IsDialogMessage( msg ) )
        return TRUE;
    else
        return CWnd::PreTranslateMessage( msg );
}

Parameters

lpMsg

Points to an MSG structure that contains the message to be checked.

Remarks

Call this member function to determine whether the given message is intended for a modeless dialog box; if it is, this function processes the message. When the IsDialogMessage function processes a message, it checks for keyboard messages and converts them to selection commands for the corresponding dialog box. For example, the TAB key selects the next control or group of controls, and the DOWN ARROW key selects the next control in a group.

You must not pass a message processed by IsDialogMessage to the ::TranslateMessage or ::DispatchMessage Windows functions, because it has already been processed.

CwND Overview | Class Members | Hierarchy Chart

See Also ::DispatchMessage, ::TranslateMessage, ::GetMessage, CWnd::PreTranslateMessage, ::IsDialogMessage


CWnd::IsDlgButtonChecked

UINT IsDlgButtonChecked( int nIDButton ) const;

Return Value

Nonzero if the given control is checked, and 0 if it is not checked. Only radio buttons and check boxes can be checked. For three-state buttons, the return value can be 2 if the button is indeterminate. This member function returns 0 for a pushbutton.

Parameters

nIDButton

Specifies the integer identifier of the button control.

Remarks

Determines whether a button control has a check mark next to it. If the button is a three-state control, the member function determines whether it is dimmed, checked, or neither.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::IsDlgButtonChecked, CButton::GetCheck


CWnd::IsIconic

BOOL IsIconic( ) const;

Return Value

Nonzero if CWnd is minimized; otherwise 0.

Remarks

Specifies whether CWnd is minimized (iconic).

CWnd Overview | Class Members | Hierarchy Chart

See Also ::IsIconic


CWnd::IsWindowEnabled

BOOL IsWindowEnabled( ) const;

Return Value

Nonzero if CWnd is enabled; otherwise 0.

Remarks

Specifies whether CWnd is enabled for mouse and keyboard input.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::IsWindowEnabled


CWnd::IsWindowVisible

BOOL IsWindowVisible( ) const;

Return Value

Nonzero if CWnd is visible (has the WS_VISIBLE style bit set, and parent window is visible). Because the return value reflects the state of the WS_VISIBLE style bit, the return value may be nonzero even though CWnd is totally obscured by other windows.

Remarks

Determines the visibility state of the given window.

A window possesses a visibility state indicated by the WS_VISIBLE style bit. When this style bit is set with a call to the ShowWindow member function, the window is displayed and subsequent drawing to the window is displayed as long as the window has the style bit set.

Any drawing to a window that has the WS_VISIBLE style will not be displayed if the window is covered by other windows or is clipped by its parent window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ShowWindow, ::IsWindowVisible


CWnd::IsZoomed

BOOL IsZoomed( ) const;

Return Value

Nonzero if CWnd is maximized; otherwise 0.

Remarks

Determines whether CWnd has been maximized.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::IsZoomed


CWnd::KillTimer

BOOL KillTimer( int nIDEvent );

Return Value

Specifies the outcome of the function. The value is nonzero if the event was killed. It is 0 if the KillTimer member function could not find the specified timer event.

Parameters

nIDEvent

The value of the timer event passed to SetTimer.

Remarks

Kills the timer event identified by nIDEvent from the earlier call to SetTimer. Any pending WM_TIMER messages associated with the timer are removed from the message queue.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetTimer, ::KillTimer


CWnd::LockWindowUpdate

BOOL LockWindowUpdate( );

Return Value

Nonzero if the function is successful. It is 0 if a failure occurs or if the LockWindowUpdate function has been used to lock another window.

Remarks

Disables drawing in the given window. A locked window cannot be moved. Only one window can be locked at a time. To unlock a window locked with LockWindowUpdate, call UnlockWindowUpdate.

If an application with a locked window (or any locked child windows) calls the GetDC, GetDCEx, or BeginPaint Windows function, the called function returns a device context whose visible region is empty. This will occur until the application unlocks the window by calling the UnlockWindowUpdate member function.

While window updates are locked, the system keeps track of the bounding rectangle of any drawing operations to device contexts associated with a locked window. When drawing is reenabled, this bounding rectangle is invalidated in the locked window and its child windows to force an eventual WM_PAINT message to update the screen. If no drawing has occurred while the window updates were locked, no area is invalidated.

The LockWindowUpdate member function does not make the given window invisible and does not clear the WS_VISIBLE style bit.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDCEx, ::LockWindowUpdate


CWnd::MapWindowPoints

void MapWindowPoints( CWnd* pwndTo, LPRECT lpRect ) const;

void MapWindowPoints( CWnd* pwndTo, LPPOINT lpPoint, UINT nCount ) const;

Parameters

pwndTo

Identifies the window to which points are converted. If this parameter is NULL, the points are converted to screen coordinates.

lpRect

Specifies the rectangle whose points are to be converted. The first version of this function is available only for Windows 3.1 and later.

lpPoint

A pointer to an array of POINT structures that contain the set of points to be converted.

nCount

Specifies the number of POINT structures in the array pointed to by lpPoint.

Remarks

Converts (maps) a set of points from the coordinate space of the CWnd to the coordinate space of another window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ClientToScreen, CWnd::ScreenToClient, ::MapWindowPoints


CWnd::MessageBox

int MessageBox( LPCTSTR lpszText, LPCTSTR lpszCaption = NULL, UINT nType = MB_OK );

Return Value

Specifies the outcome of the function. It is 0 if there is not enough memory to create the message box.

Parameters

lpszText

Points to a CString object or null-terminated string containing the message to be displayed.

lpszCaption

Points to a CString object or null-terminated string to be used for the message-box caption. If lpszCaption is NULL, the default caption “Error” is used.

nType

Specifies the contents and behavior of the message box.

Remarks

Creates and displays a window that contains an application-supplied message and caption, plus a combination of the predefined icons and pushbuttons described in the Message-Box Styles list. Use the global function AfxMessageBox instead of this member function to implement a message box in your application.

The following shows the various system icons that can be used in a message box:

MB_ICONHAND, MB_ICONSTOP, and MB_ICONERROR
MB_ICONQUESTION
MB_ICONEXCLAMATION and MB_ICONWARNING
MB_ICONASTERISK and MB_ICONINFORMATION

CWnd Overview | Class Members | Hierarchy Chart

See Also ::MessageBox, AfxMessageBox


CWnd::ModifyStyle

BOOL ModifyStyle( DWORD dwRemove, DWORD dwAdd, UINT nFlags = 0 );

Return Value

Nonzero if style was successfully modified; otherwise, 0.

Parameters

dwRemove

Specifies window styles to be removed during style modification.

dwAdd

Specifies window styles to be added during style modification.

nFlags

Flags to be passed to SetWindowPos, or zero if SetWindowPos should not be called. The default is zero. See the Remarks section for a list of preset flags.

Remarks

Call this member function to modify a window’s style. Styles to be added or removed can be combined by using the bitwise OR (|) operator. See the topics General Window Styles and ::CreateWindow in the Win32 SDK Programmer’s Reference for information about the available window styles.

If nFlags is nonzero, ModifyStyle calls the Windows API function ::SetWindowPos and redraws the window by combining nFlags with the following four preset flags:

  • SWP_NOSIZE Retains the current size.

  • SWP_NOMOVE Retains the current position.

  • SWP_NOZORDER Retains the current Z order.

  • SWP_NOACTIVATE Does not activate the window.

To modify a window’s extended styles, see ModifyStyleEx.

CWnd Overview | Class Members | Hierarchy Chart

See Also SetWindowPos, CWnd::ModifyStyleEx, General Window Styles, ::SetWindowPos


CWnd::ModifyStyleEx

BOOL ModifyStyleEx( DWORD dwRemove, DWORD dwAdd, UINT nFlags = 0 );

Return Value

Nonzero if style was successfully modified; otherwise, 0.

Parameters

dwRemove

Specifies extended styles to be removed during style modification.

dwAdd

Specifies extended styles to be added during style modification.

nFlags

Flags to be passed to SetWindowPos, or zero if SetWindowPos should not be called. The default is zero. See the Remarks section for a list of preset flags.

Remarks

Call this member function to modify a window’s extended style. Styles to be added or removed can be combined by using the bitwise OR (|) operator. See the topics Extended Window Styles in this book and ::CreateWindowEx in the Win32 SDK Programmer’s Reference for information about the available extended styles

If nFlags is nonzero, ModifyStyleEx calls the Windows API function ::SetWindowPos and redraws the window by combining nFlags with the following four preset flags:

  • SWP_NOSIZE Retains the current size.

  • SWP_NOMOVE Retains the current position.

  • SWP_NOZORDER Retains the current Z order.

  • SWP_NOACTIVATE Does not activate the window.

To modify windows using regular window styles, see ModifyStyle.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ModifyStyle, CreateWindowEx


CWnd::MoveWindow

void MoveWindow( int x, int y, int nWidth, int nHeight, BOOL bRepaint = TRUE );

void MoveWindow( LPCRECT lpRect, BOOL bRepaint = TRUE );

Parameters

x

Specifies the new position of the left side of the CWnd.

y

Specifies the new position of the top of the CWnd.

nWidth

Specifies the new width of the CWnd.

nHeight

Specifies the new height of the CWnd.

bRepaint

Specifies whether CWnd is to be repainted. If TRUE, CWnd receives a WM_PAINT message in its OnPaint message handler as usual. If this parameter is FALSE, no repainting of any kind occurs. This applies to the client area, to the nonclient area (including the title and scroll bars), and to any part of the parent window uncovered as a result of Cwnd’s move. When this parameter is FALSE, the application must explicitly invalidate or redraw any parts of CWnd and parent window that must be redrawn.

lpRect

The CRect object or RECT structure that specifies the new size and position.

Remarks

Changes the position and dimensions.

For a top-level CWnd object, the x and y parameters are relative to the upper-left corner of the screen. For a child CWnd object, they are relative to the upper-left corner of the parent window’s client area.

The MoveWindow function sends the WM_GETMINMAXINFO message. Handling this message gives CWnd the opportunity to modify the default values for the largest and smallest possible windows. If the parameters to the MoveWindow member function exceed these values, the values can be replaced by the minimum or maximum values in the WM_GETMINMAXINFO handler.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetWindowPos, WM_GETMINMAXINFO, ::MoveWindow


CWnd::OnActivate

afx_msg void OnActivate( UINT nState, CWnd* pWndOther, BOOL bMinimized );

Parameters

nState

Specifies whether the CWnd is being activated or deactivated. It can be one of the following values:

  • WA_INACTIVE The window is being deactivated.

  • WA_ACTIVE The window is being activated through some method other than a mouse click (for example, by use of the keyboard interface to select the window).

  • WA_CLICKACTIVE The window is being activated by a mouse click.

pWndOther

Pointer to the CWnd being activated or deactivated. The pointer can be NULL, and it may be temporary.

bMinimized

Specifies the minimized state of the CWnd being activated or deactivated. A value of TRUE indicates the window is minimized.

If TRUE, the CWnd is being activated; otherwise deactivated.

Remarks

The framework calls this member function when a CWnd object is being activated or deactivated. First, the main window being deactivated has OnActivate called, and then the main window being activated has OnActivate called.

If the CWnd object is activated with a mouse click, it will also receive an OnMouseActivate member function call.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_MOUSEACTIVATE, WM_NCACTIVATE, WM_ACTIVATE


CWnd::OnActivateApp

afx_msg void OnActivateApp( BOOL bActive, HTASK hTask );

Parameters

bActive

Specifies whether the CWnd is being activated or deactivated. TRUE means the CWnd is being activated. FALSE means the CWnd is being deactivated.

hTask

Specifies a task handle. If bActive is TRUE, the handle identifies the task that owns the CWnd being deactivated. If bActive is FALSE, the handle identifies the task that owns the CWnd being activated.

Remarks

The framework calls this member function to all top-level windows of the task being activated and for all top-level windows of the task being deactivated.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_ACTIVATEAPP


CWnd::OnAmbientProperty

BOOL OnAmbientProperty( COleControlSite* pSite, DISPID dispid, VARIANT* pvar )

Return Value

TRUE if the ambient property is supported; FALSE if not.

Parameters

pSite

Pointer to the site of the control that requested the ambient property.

dispid

The dispatch ID of the requested ambient property.

pvar

Pointer to a caller-allocated VARIANT structure, through which the ambient property's value will be returned.

Remarks

The framework calls this member function to obtain ambient property values from a window that contains OLE controls. Override this function to alter the default ambient property values returned by an OLE control container to its controls. Any ambient property requests not handled by an overriding function should be forwarded to the base class implementation.


CWnd::OnAskCbFormatName

afx_msg void OnAskCbFormatName( UINT nMaxCount, LPTSTR lpszString );

Parameters

nMaxCount

Specifies the maximum number of bytes to copy.

lpszString

Points to the buffer where the copy of the format name is to be stored.

Remarks

The framework calls this member function when the Clipboard contains a data handle for the CF_OWNERDISPLAY format (that is, when the Clipboard owner will display the Clipboard contents). The Clipboard owner should provide a name for its format.

Override this member function and copy the name of the CF_OWNERDISPLAY format into the specified buffer, not exceeding the maximum number of bytes specified.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_ASKCBFORMATNAME


CWnd::OnCancelMode

afx_msg void OnCancelMode( );

Remarks

The framework calls this member function to inform CWnd to cancel any internal mode. If the CWnd object has the focus, its OnCancelMode member function is called when a dialog box or message box is displayed. This gives the CWnd the opportunity to cancel modes such as mouse capture.

The default implementation responds by calling the ReleaseCapture Windows function. Override this member function in your derived class to handle other modes.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Default, ::ReleaseCapture, WM_CANCELMODE


CWnd::OnCaptureChanged

afx_msg void OnCaptureChanged( CWnd* pWnd );

Parameters

pWnd

A pointer to the window to gain mouse capture

Remarks

The framework calls this member function to notify the window that is losing the mouse capture.

A window receives this message even if it calls ::ReleaseCapture itself. An application should not attempt to set the mouse capture in response to this message. When it receives this message, a window should redraw itself, if necessary, to reflect the new mouse-capture state.

See the Win32 SDK Programmer’s Reference for information on the ReleaseCapture Windows function.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_CAPTURECHANGED


CWnd::OnChangeCbChain

afx_msg void OnChangeCbChain( HWND hWndRemove, HWND hWndAfter );

Parameters

hWndRemove

Specifies the window handle that is being removed from the Clipboard-viewer chain.

hWndAfter

Specifies the window handle that follows the window being removed from the Clipboard-viewer chain.

Remarks

The framework calls this member function for each window in the Clipboard-viewer chain to notify it that a window is being removed from the chain.

Each CWnd object that receives an OnChangeCbChain call should use the SendMessage Windows function to send the WM_CHANGECBCHAIN message to the next window in the Clipboard-viewer chain (the handle returned by SetClipboardViewer). If hWndRemove is the next window in the chain, the window specified by hWndAfter becomes the next window, and Clipboard messages are passed on to it.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ChangeClipboardChain, ::SendMessage


CWnd::OnChar

afx_msg void OnChar( UINT nChar, UINT nRepCnt, UINT nFlags );

Parameters

nChar

Contains the character code value of the key.

nRepCnt

Contains the repeat count, the number of times the keystroke is repeated when user holds down the key.

nFlags

Contains the scan code, key-transition code, previous key state, and context code, as shown in the following list:

Value | Meaning
0-15 | Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key.
16-23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM)
24 | Specifies whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25-28 | Used internally by Windows.
29 | Specifies the context code. The value is 1 if the ALT key is held down while the key is pressed; otherwise, the value is 0.
30 | Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31 | Specifies the transition state. The value is 1 if the key is being released, or it is 0 if the key is being pressed.

Remarks

The framework calls this member function when a keystroke translates to a nonsystem character. This function is called before the OnKeyUp member function and after the OnKeyDown member function are called. OnChar contains the value of the keyboard key being pressed or released.

Because there is not necessarily a one-to-one correspondence between keys pressed and OnChar calls generated, the information in nFlags is generally not useful to applications. The information in nFlags applies only to the most recent call to the OnKeyUp member function or the OnKeyDown member function that precedes the call to OnChar.

For IBM Enhanced 101- and 102-key keyboards, enhanced keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; and the slash (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in nFlags.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_CHAR, WM_KEYDOWN, WM_KEYUP


CWnd::OnCharToItem

afx_msg int OnCharToItem( UINT nChar, CListBox* pListBox, UINT nIndex );

Return Value

The framework calls this member function to specify the action that the application performed in response to the call. A return value of –2 indicates that the application handled all aspects of selecting the item and wants no further action by the list box. A return value of –1 indicates that the list box should perform the default action in response to the keystroke. A return value of 0 or greater specifies the zero-based index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

Parameters

nChar

Specifies the value of the key pressed by the user.

pListBox

Specifies a pointer to the list box. It may be temporary.

nIndex

Specifies the current caret position.

Remarks

Called when a list box with the LBS_WANTKEYBOARDINPUT style sends its owner a WM_CHARTOITEM message in response to a WM_CHAR message.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_CHAR, WM_CHARTOITEM


CWnd::OnChildActivate

afx_msg void OnChildActivate( );

Remarks

If the CWnd object is a multiple document interface (MDI) child window, OnChildActivate is called by the framework when the user clicks the window’s title bar or when the window is activated, moved, or sized.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetWindowPos, WM_CHILDACTIVATE


CWnd::OnChildNotify

virtual BOOL OnChildNotify( UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult );

Return Value

Nonzero if this window is responsible for handling the message sent to its parent; otherwise 0.

Parameters

message

A Windows message number sent to a parent window.

wParam

The wparam associated with the message.

lParam

The lparam associated with the message.

pLResult

A pointer to a value to be returned from the parent’s window procedure. This pointer will be NULL if no return value is expected.

Remarks

This member function is called by this window’s parent window when it receives a notification message that applies to this window.

Never call this member function directly.

The default implementation of this member function returns 0, which means that the parent should handle the message.

Override this member function to extend the manner in which a control responds to notification messages.


CWnd::OnClose

afx_msg void OnClose( );

Remarks

The framework calls this member function as a signal that the CWnd or an application is to terminate. The default implementation calls DestroyWindow.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DestroyWindow, WM_CLOSE


CWnd::OnCommand

virtual BOOL OnCommand( WPARAM wParam, LPARAM lParam );

Return Value

An application returns nonzero if it processes this message; otherwise 0.

Parameters

wParam

The low-order word of wParam identifies the command ID of the menu item, control, or accelerator. The high-order word of wParam specifies the notification message if the message is from a control. If the message is from an accelerator, the high-order word is 1. If the message is from a menu, the high-order word is 0.

lParam

Identifies the control that sends the message if the message is from a control. Otherwise, lParam is 0.

Remarks

The framework calls this member function when the user selects an item from a menu, when a child control sends a notification message, or when an accelerator keystroke is translated.

OnCommand processes the message map for control notification and ON_COMMAND entries, and calls the appropriate member function.

Override this member function in your derived class to handle the WM_COMMAND message. An override will not process the message map unless the base class OnCommand is called.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_COMMAND, CCmdTarget::OnCmdMsg


CWnd::OnCompacting

afx_msg void OnCompacting( UINT nCpuTime );

Parameters

nCpuTime

Specifies the ratio of CPU time currently spent by Windows compacting memory to CPU time spent performing other operations. For example, 8000h represents 50 percent of CPU time spent compacting memory.

Remarks

The framework calls this member function for all top-level windows when Windows detects that more than 12.5 percent of system time over a 30- to 60-second interval is being spent compacting memory. This indicates that system memory is low.

When a CWnd object receives this call, it should free as much memory as possible, taking into account the current level of activity of the application and the total number of applications running in Windows. The application can call the Windows function to determine how many applications are running.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_COMPACTING


CWnd::OnCompareItem

afx_msg int OnCompareItem( int nIDCtl, LPCOMPAREITEMSTRUCT lpCompareItemStruct );

Return Value

Indicates the relative position of the two items. It may be any of the following values:

Value | Meaning
–1 | Item 1 sorts before item 2.
0 | Item 1 and item 2 sort the same.
1 | Item 1 sorts after item 2.

Parameters

nIDCtl

The identifier of the control that sent the WM_COMPAREITEM message.

lpCompareItemStruct

Contains a long pointer to a COMPAREITEMSTRUCT data structure that contains the identifiers and application-supplied data for two items in the combo or list box.

Remarks

The framework calls this member function to specify the relative position of a new item in a child sorted owner-draw combo or list box.

If a combo or list box is created with the CBS_SORT or LBS_SORT style, Windows sends the combo-box or list-box owner a WM_COMPAREITEM message whenever the application adds a new item.

Two items in the combo or list box are reformed in a COMPAREITEMSTRUCT structure pointed to by lpCompareItemStruct. OnCompareItem should return a value that indicates which of the items should appear before the other. Typically, Windows makes this call several times until it determines the exact position for the new item.

If the hwndItem member of the COMPAREITEMSTRUCT structure belongs to a CListBox or CComboBox object, then the CompareItem virtual function of the appropriate class is called. Override CComboBox::CompareItem or CListBox::CompareItem in your derived CListBox or CComboBox class to do the item comparison.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also COMPAREITEMSTRUCT, WM_COMPAREITEM, CListBox::CompareItem, CComboBox::CompareItem


CWnd::OnContextMenu

afx_msg void OnContextMenu( CWnd* pWnd, CPoint pos );

Parameters

pWnd

Handle to the window in which the user right clicked the mouse. This can be a child window of the window receiving the message. For more information about processing this message, see the Remarks section.

pos

Position of the cursor, in screen coordinates, at the time of the mouse click.

Remarks

Called by the framework when the user has clicked the right mouse button (right clicked) in the window. You can process this message by displaying a context menu using the TrackPopupMenu.

If you do not display a context menu you should pass this message onto the DefWindowProc function. If your window is a child window, DefWindowProc sends the message to the parent. Otherwise, DefWindowProc displays a default context menu if the specified position is in the window's caption.


CWnd::OnCopyData

afx_msg BOOL OnCopyData( CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct );

Return Value

Returns TRUE if the receiving application successfully accepts the data. Otherwise, returns FALSE.

Parameters

pWnd

A pointer to a CWnd object that is sending the data.

pCopyDataStruct

A pointer to a COPYDATASTRUCT structure that contains the data being sent.

Remarks

This member function is called by the framework to copy data from one application to another.

The data being passed must not contain pointers or other references to objects not accessible to the application receiving the data.

While the data is being copied, it must not be changed by another thread of the sending process.

The receiving application should consider the data read-only. The structure pointed to by the parameter pCopyDataStruct is valid only during the transfer of data; however, the receiving application should not free the memory associated with the structure.

If the receiving application needs access to the data after this function returns, it must copy the data received to a local buffer.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_COPYDATA


CWnd::OnCreate

afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct );

Return Value

OnCreate must return 0 to continue the creation of the CWnd object. If the application returns –1, the window will be destroyed.

Parameters

lpCreateStruct

Points to a CREATESTRUCT structure that contains information about the CWnd object being created.

Remarks

The framework calls this member function when an application requests that the Windows window be created by calling the Create or CreateEx member function. The CWnd object receives this call after the window is created but before it becomes visible. OnCreate is called before the Create or CreateEx member function returns.

Override this member function to perform any needed initialization of a derived class.

The CREATESTRUCT structure contains copies of the parameters used to create the window.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::CreateEx, CWnd::OnNcCreate, WM_CREATE, CWnd::Default, CWnd::FromHandle


CWnd::OnCtlColor

afx_msg HBRUSH OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor );

Return Value

OnCtlColor must return a handle to the brush that is to be used for painting the control background.

Parameters

pDC

Contains a pointer to the display context for the child window. May be temporary.

pWnd

Contains a pointer to the control asking for the color. May be temporary.

nCtlColor

Contains one of the following values, specifying the type of control:

  • CTLCOLOR_BTN Button control

  • CTLCOLOR_DLG Dialog box

  • CTLCOLOR_EDIT Edit control

  • CTLCOLOR_LISTBOX List-box control

  • CTLCOLOR_MSGBOX Message box

  • CTLCOLOR_SCROLLBAR Scroll-bar control

  • CTLCOLOR_STATIC Static control

Remarks

The framework calls this member function when a child control is about to be drawn. Most controls send this message to their parent (usually a dialog box) to prepare the pDC for drawing the control using the correct colors.

To change the text color, call the SetTextColor member function with the desired red, green, and blue (RGB) values.

To change the background color of a single-line edit control, set the brush handle in both the CTLCOLOR_EDIT and CTLCOLOR_MSGBOX message codes, and call the CDC::SetBkColor function in response to the CTLCOLOR_EDIT code.

OnCtlColor will not be called for the list box of a drop-down combo box because the drop-down list box is actually a child of the combo box and not a child of the window. To change the color of the drop-down list box, create a CComboBox with an override of OnCtlColor that checks for CTLCOLOR_LISTBOX in the nCtlColor parameter. In this handler, the SetBkColor member function must be used to set the background color for the text.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CDC::SetBkColor


CWnd::OnDeadChar

afx_msg void OnDeadChar( UINT nChar, UINT nRepCnt, UINT nFlags );

Parameters

nChar

Specifies the dead-key character value.

nRepCnt

Specifies the repeat count.

nFlags

Specifies the scan code, key-transition code, previous key state, and context code, as shown in the following list:

Value | Description
0–7 | Scan code (OEM-dependent value). Low byte of high-order word.
8 | Extended key, such as a function key or a key on the numeric keypad (1 if it is an extended key; otherwise 0).
9–10 | Not used.
11–12 | Used internally by Windows.
13 | Context code (1 if the ALT key is held down while the key is pressed; otherwise 0).
14 | Previous key state (1 if the key is down before the call, 0 if the key is up).
15 | Transition state (1 if the key is being released, 0 if the key is being pressed).

Remarks

The framework calls this member function when the OnKeyUp member function and the OnKeyDown member functions are called. This member function can be used to specify the character value of a dead key. A dead key is a key, such as the umlaut (double-dot) character, that is combined with other characters to form a composite character. For example, the umlaut-O character consists of the dead key, umlaut, and the O key.

An application typically uses OnDeadChar to give the user feedback about each key pressed. For example, an application can display the accent in the current character position without moving the caret.

Since there is not necessarily a one-to-one correspondence between keys pressed and OnDeadChar calls, the information in nFlags is generally not useful to applications. The information in nFlags applies only to the most recent call to the OnKeyUp member function or the OnKeyDown member function that precedes the OnDeadChar call.

For IBM Enhanced 101- and 102-key keyboards, enhanced keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; and the slash (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in nFlags.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_DEADCHAR


CWnd::OnDeleteItem

afx_msg void OnDeleteItem( int nIDCtl, LPDELETEITEMSTRUCT lpDeleteItemStruct );

Parameters

nIDCtl

The identifier of the control that sent the WM_DELETEITEM message.

lpDeleteItemStruct

Specifies a long pointer to a DELETEITEMSTRUCT data structure that contains information about the deleted list box item.

Remarks

The framework calls this member function to inform the owner of an owner-draw list box or combo box that the list box or combo box is destroyed or that items have been removed by CComboBox::DeleteString, CListBox::DeleteString, CComboBox::ResetContent, or CListBox::ResetContent.

If the hwndItem member of the DELETEITEMSTRUCT structure belongs to a combo box or list box, then the DeleteItem virtual function of the appropriate class is called. Override the DeleteItem member function of the appropriate control’s class to delete item-specific data.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CComboBox::DeleteString, CListBox::DeleteString, CComboBox::ResetContent, CListBox::ResetContent, WM_DELETEITEM, CListBox::DeleteItem, CComboBox::DeleteItem


CWnd::OnDestroy

afx_msg void OnDestroy( );

Remarks

The framework calls this member function to inform the CWnd object that it is being destroyed. OnDestroy is called after the CWnd object is removed from the screen.

OnDestroy is called first for the CWnd being destroyed, then for the child windows of CWnd as they are destroyed. It can be assumed that all child windows still exist while OnDestroy runs.

If the CWnd object being destroyed is part of the Clipboard-viewer chain (set by calling the SetClipboardViewer member function), the CWnd must remove itself from the Clipboard-viewer chain by calling the ChangeClipboardChain member function before returning from the OnDestroy function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ChangeClipboardChain, CWnd::DestroyWindow, CWnd::SetClipboardViewer


CWnd::OnDestroyClipboard

afx_msg void OnDestroyClipboard( );

Remarks

The framework calls this member function for the Clipboard owner when the Clipboard is emptied through a call to the EmptyClipboard Windows function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::EmptyClipboard, WM_DESTROYCLIPBOARD


CWnd::OnDeviceChange

afx_msg BOOL OnDeviceChange( UINT nEventType, DWORD dwData );

Parameters

nEventType

An event type. See the Remarks section for a description of the available values

dwData

The address of a structure that contains event-specific data. Its meaning depends on the given event.

Remarks

The framework calls this member function to notify an application or device driver of a change to the hardware configuration of a device or the computer.

For devices that offer software-controllable features, such as ejection and locking, the operating system typically sends a DBT_DEVICEREMOVEPENDING message to let applications and device drivers end their use of the device gracefully.

If the operating system forcefully removes of a device, it may not send a DBT_DEVICEQUERYREMOVE message before doing so.

The nEvent parameter can be one of these values:

  • DBT_DEVICEARRIVAL A device has been inserted and is now available.

  • DBT_DEVICEQUERYREMOVE Permission to remove a device is requested. Any application can deny this request and cancel the removal.

  • DBT_DEVICEQUERYREMOVEFAILED Request to remove a device has been canceled.

  • DBT_DEVICEREMOVEPENDING Device is about to be removed. Cannot be denied.

  • DBT_DEVICEREMOVECOMPLETE Device has been removed.

  • DBT_DEVICETYPESPECIFIC Device-specific event.

  • DBT_CONFIGCHANGED Current configuration has changed.

  • DBT_DEVNODES_CHANGED Device node has changed.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_DEVICECHANGE


CWnd::OnDevModeChange

afx_msg void OnDevModeChange( LPTSTR lpDeviceName );

Parameters

lpDeviceName

Points to the device name specified in the Windows initialization file, WIN.INI.

Remarks

The framework calls this member function for all top-level CWnd objects when the user changes device-mode settings.

Applications that handle the WM_DEVMODECHANGE message may reinitialize their device-mode settings. Applications that use the Windows ExtDeviceMode function to save and restore device settings typically do not process this function.

This function is not called when the user changes the default printer from Control Panel. In this case, the OnWinIniChange function is called.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_DEVMODECHANGE


CWnd::OnDrawClipboard

afx_msg void OnDrawClipboard( );

Remarks

The framework calls this member function for each window in the Clipboard-viewer chain when the contents of the Clipboard change. Only applications that have joined the Clipboard-viewer chain by calling the SetClipboardViewer member function need to respond to this call.

Each window that receives an OnDrawClipboard call should call the SendMessage Windows function to pass a WM_DRAWCLIPBOARD message on to the next window in the Clipboard-viewer chain. The handle of the next window is returned by the SetClipboardViewer member function; it may be modified in response to an OnChangeCbChain member function call.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SendMessage, CWnd::SetClipboardViewer, WM_CHANGECBCHAIN, WM_DRAWCLIPBOARD


CWnd::OnDrawItem

afx_msg void OnDrawItem( int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct );

Parameters

nIDCtl

Contains the identifier of the control that sent the WM_DRAWITEM message. If a menu sent the message, nIDCtl contains 0.

lpDrawItemStruct

Specifies a long pointer to a DRAWITEMSTRUCT data structure that contains information about the item to be drawn and the type of drawing required.

Remarks

The framework calls this member function for the owner of an owner-draw button control, combo-box control, list-box control, or menu when a visual aspect of the control or menu has changed.

The itemAction member of the DRAWITEMSTRUCT structure defines the drawing operation that is to be performed. The data in this member allows the owner of the control to determine what drawing action is required.

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

If the hwndItem member belongs to a CButton, CMenu, CListBox, or CComboBox object, then the DrawItem virtual function of the appropriate class is called. Override the DrawItem member function of the appropriate control’s class to draw the item.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also DRAWITEMSTRUCT, WM_DRAWITEM, CButton::DrawItem, CMenu::DrawItem, CListBox::DrawItem, CComboBox::DrawItem


CWnd::OnDropFiles

afx_msg void OnDropFiles( HDROP hDropInfo );

Parameters

hDropInfo

A pointer to an internal data structure that describes the dropped files. This handle is used by the DragFinish, DragQueryFile, and DragQueryPoint Windows functions to retrieve information about the dropped files.

Remarks

The framework calls this member function when the user releases the left mouse button over a window that has registered itself as the recipient of dropped files.

Typically, a derived class will be designed to support dropped files and it will register itself during window construction.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DragAcceptFiles, WM_DROPFILES, ::DragAcceptFiles, ::DragFinish, ::DragQueryFile, ::DragQueryPoint


CWnd::OnDSCNotify

afx_msg BOOL OnDSCNotify( DSCSTATE nState, DSCREASON nReason, BOOL pBool );

Return Value

Returns TRUE if the operation represented by nReason and nState was handled. Otherwise, returns FALSE.

Parameters

nState

One of the named constants found in the DSCSTATE enumerator, which are listed under Remarks.

nReason

One of the named constants found in the DSCREASON enumerator, which are listed under Remarks.

pBool

A Boolean answer indicating whether the operation represented by nState and nReason should continue.

Remarks

This sink notification is called in response to an event that a data-source control fires when a control to which the data-source control is bound modifies or attempts to modify the underlying cursor. Use it to trap reasons (nReason) and states (nState) generated by a data-source control. All combinations of states and reasons are allowed by default. Write your code to test the states and reasons that are important to your application and return TRUE or FALSE as appropriate.

To use OnDSCNotify, declare a sink map and a handler for the sink notification in the header of the class that wishes to receive the sink notification as follows:

class CMyDlg : public CDialog
{
   ...
   DECLARE_EVENTSINK_MAP()
   BOOL OnDSCNotify(DSCSTATE nState,
             DSCREASON nReason, BOOL* pBool);
   ...
};

Then, in the implementation of your class, define the sink map and specify the function to receive the events as follows:

BEGIN_EVENTSINK_MAP(CMyDlg, CDialog)
   ON_DSCNOTIFY(CMyDlg, IDC_RDCCTRL1, OnDSCNotify)
END_EVENTSINK_MAP()

The notification callback function, your implementation of OnDSCNotify, will be called when the following events occur inside the data-source control:

enum DSCREASON
{
   dscNoReason = 0,
   dscClose, dscCommit, dscDelete,
   dscEdit, dscInsert, dscModify, dscMove
};

It will also be called multiple times for each of the following states:

enum DSCSTATE
{
   dscNoState = 0,
   dscOKToDo,
   dscCancelled,
   dscSyncBefore,
   dscAboutToDo,
   dscFailedToDo,
   dscSyncAfter,
   dscDidEvent
};

The multiple calls allow you to trap an event at different times. For example, since events are usually generated in response to modification of the cursor state by a control, the first thing that the data-source control will do is to fire events asking if it is okay to actually perform that action; hence the reason for the dscOKToDo state. If all clients that monitor the event (the data control, your application, and so on) accept the event, the data-source control will then move into the dscSyncBefore state, at which time all outstanding data will be flushed, if necessary. For example, if the content of an edit field has changed, the change will be committed to the cursor. Following this event, the data-source control moves into the dscAboutToDo and dscSyncAfter states and finally into the dscDidEvent state. These provide you with further opportunities to catch notifications from the data-source control.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDSCCursor, CWnd::BindDefaultProperty, CWnd::BindProperty


CWnd::OnEnable

afx_msg void OnEnable( BOOL bEnable );

Parameters

bEnable

Specifies whether the CWnd object has been enabled or disabled. This parameter is TRUE if the CWnd has been enabled; it is FALSE if the CWnd has been disabled.

Remarks

The framework calls this member function when an application changes the enabled state of the CWnd object. OnEnable is called before the EnableWindow member function returns, but after the window enabled state (WS_DISABLED style bit) has changed.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::EnableWindow, WM_ENABLE


CWnd::OnEndSession

afx_msg void OnEndSession( BOOL bEnding );

Parameters

bEnding

Specifies whether or not the session is being ended. It is TRUE if the session is being ended; otherwise FALSE.

Remarks

The framework calls this member function after the CWnd object has returned a nonzero value from a OnQueryEndSession member function call. The OnEndSession call informs the CWnd object whether the session is actually ending.

If bEnding is TRUE, Windows can terminate any time after all applications have returned from processing this call. Consequently, have an application perform all tasks required for termination within OnEndSession.

You do not need to call the DestroyWindow member function or PostQuitMessage Windows function when the session is ending.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DestroyWindow, CWnd::OnQueryEndSession, ::ExitWindows, ::PostQuitMessage, WM_QUERYENDSESSION, CWnd::Default, WM_ENDSESSION


CWnd::OnEnterIdle

afx_msg void OnEnterIdle( UINT nWhy, CWnd* pWho );

Parameters

nWhy

Specifies whether the message is the result of a dialog box or a menu being displayed. This parameter can be one of the following values:

  • MSGF_DIALOGBOX The system is idle because a dialog box is being displayed.

  • MSGF_MENU The system is idle because a menu is being displayed.

pWho

Specifies a pointer to the dialog box (if nWhy is MSGF_DIALOGBOX), or the window that contains the displayed menu (if nWhy is MSGF_MENU). This pointer may be temporary and should not be stored for later use.

Remarks

The framework calls this member function to inform an application’s main window procedure that a modal dialog box or a menu is entering an idle state. A modal dialog box or menu enters an idle state when no messages are waiting in its queue after it has processed one or more previous messages.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_ENTERIDLE


CWnd::OnEnterMenuLoop

afx_msg void OnEnterMenuLoop( BOOL bIsTrackPopupMenu );

Parameters

bIsTrackPopupMenu

Specifies whether the menu involved is a popup menu. Has a nonzero value if the function is successful; otherwise 0.

Remarks

The framework calls this member function when a menu modal loop has been entered.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnExitMenuLoop, WM_ENTERMENULOOP


CWnd::OnEraseBkgnd

afx_msg BOOL OnEraseBkgnd( CDC* pDC );

Return Value

Nonzero if it erases the background; otherwise 0.

Parameters

pDC

Specifies the device-context object.

Remarks

The framework calls this member function when the CWnd object background needs erasing (for example, when resized). It is called to prepare an invalidated region for painting.

The default implementation erases the background using the window class background brush specified by the hbrBackground member of the window class structure.

If the hbrBackground member is NULL, your overridden version of OnEraseBkgnd should erase the background color. Your version should also align the origin of the intended brush with the CWnd coordinates by first calling UnrealizeObject for the brush, and then selecting the brush.

An overridden OnEraseBkgnd should return nonzero in response to WM_ERASEBKGND if it processes the message and erases the background; this indicates that no further erasing is required. If it returns 0, the window will remain marked as needing to be erased. (Typically, this means that the fErase member of the PAINTSTRUCT structure will be TRUE.)

Windows assumes the background is computed with the MM_TEXT mapping mode. If the device context is using any other mapping mode, the area erased may not be within the visible part of the client area.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_ICONERASEBKGND, CGdiObject::UnrealizeObject, WM_ERASEBKGND


CWnd::OnExitMenuLoop

afx_msg void OnExitMenuLoop( BOOL bIsTrackPopupMenu );

Parameters

bIsTrackPopupMenu

Specifies whether the menu involved is a pop-up menu. Has a nonzero value if the function is successful; otherwise 0.

Remarks

The framework calls this member function when a menu modal loop has been exited.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnEnterMenuLoop; WM_EXITMENULOOP


CWnd::OnFontChange

afx_msg void OnFontChange( );

Remarks

All top-level windows in the system receive an OnFontChange call from the framework after the application changes the pool of font resources.

An application that adds or removes fonts from the system (for example, through the AddFontResource or RemoveFontResource Windows function) should send the WM_FONTCHANGE message to all top-level windows.

To send this message, use the SendMessage Windows function with the hWnd parameter set to HWND_BROADCAST.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::AddFontResource, ::RemoveFontResource, ::SendMessage, WM_FONTCHANGE


CWnd::OnGetDlgCode

afx_msg UINT OnGetDlgCode( );

Return Value

One or more of the following values, indicating which type of input the application processes:

  • DLGC_BUTTON Button (generic).

  • DLGC_DEFPUSHBUTTON Default pushbutton.

  • DLGC_HASSETSEL EM_SETSEL messages.

  • DLGC_UNDEFPUSHBUTTON No default pushbutton processing. (An application can use this flag with DLGC_BUTTON to indicate that it processes button input but relies on the system for default pushbutton processing.)

  • DLGC_RADIOBUTTON Radio button.

  • DLGC_STATIC Static control.

  • DLGC_WANTALLKEYS All keyboard input.

  • DLGC_WANTARROWS Arrow keys.

  • DLGC_WANTCHARS WM_CHAR messages.

  • DLGC_WANTMESSAGE All keyboard input. The application passes this message on to the control.

  • DLGC_WANTTAB TAB key.

Remarks

Normally, Windows handles all arrow-key and TAB-key input to a CWnd control. By overriding OnGetDlgCode, a CWnd control can choose a particular type of input to process itself.

The default OnGetDlgCode functions for the predefined control classes return a code appropriate for each class.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_GETDLGCODE


CWnd::OnGetMinMaxInfo

afx_msg void OnGetMinMaxInfo( MINMAXINFO FAR* lpMMI );

Parameters

lpMMI

Points to a MINMAXINFO structure that contains information about a window’s maximized size and position and its minimum and maximum tracking size. For more about this structure, see the MINMAXINFO structure.

Remarks

The framework calls this member function whenever Windows needs to know the maximized position or dimensions, or the minimum or maximum tracking size. The maximized size is the size of the window when its borders are fully extended. The maximum tracking size of the window is the largest window size that can be achieved by using the borders to size the window. The minimum tracking size of the window is the smallest window size that can be achieved by using the borders to size the window.

Windows fills in an array of points specifying default values for the various positions and dimensions. The application may change these values in OnGetMinMaxInfo.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_GETMINMAXINFO


CWnd::OnHelpInfo

afx_msg BOOL OnHelpInfo( HELPINFO* lpHelpInfo );

Parameters

lpHelpInfo

Pointer to a HELPINFO structure that contains information about the menu item, control, dialog box, or window for which help is requested.

Remarks

Called by the framework when the user presses 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.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWinApp::OnHelp, CWinApp::WinHelp


CWnd::OnHScroll

afx_msg void OnHScroll( UINT nSBCode, UINT nPos, CScrollBar* pScrollBar );

Parameters

nSBCode

Specifies a scroll-bar code that indicates the user’s scrolling request. This parameter can be one of the following:

  • SB_LEFT Scroll to far left.

  • SB_ENDSCROLL End scroll.

  • SB_LINELEFT Scroll left.

  • SB_LINERIGHT Scroll right.

  • SB_PAGELEFT Scroll one page left.

  • SB_PAGERIGHT Scroll one page right.

  • SB_RIGHT Scroll to far right.

  • SB_THUMBPOSITION Scroll to absolute position. The current position is specified by the nPos parameter.

  • SB_THUMBTRACK Drag scroll box to specified position. The current position is specified by the nPos parameter.

nPos

Specifies the scroll-box position if the scroll-bar code is SB_THUMBPOSITION or SB_THUMBTRACK; otherwise, not used. Depending on the initial scroll range, nPos may be negative and should be cast to an int if necessary.

pScrollBar

If the scroll message came from a scroll-bar control, contains a pointer to the control. If the user clicked a window’s scroll bar, this parameter is NULL. The pointer may be temporary and should not be stored for later use.

Remarks

The framework calls this member function when the user clicks a window’s horizontal scroll bar.

The SB_THUMBTRACK scroll-bar code typically is used by applications that give some feedback while the scroll box is being dragged.

If an application scrolls the contents controlled by the scroll bar, it must also reset the position of the scroll box with the SetScrollPos member function.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetScrollPos, WM_VSCROLL, WM_HSCROLL


CWnd::OnHScrollClipboard

afx_msg void OnHScrollClipboard( CWnd* pClipAppWnd, UINT nSBCode, UINT nPos );

Parameters

pClipAppWnd

Specifies a pointer to a Clipboard-viewer window. The pointer may be temporary and should not be stored for later use.

nSBCode

Specifies one of the following scroll-bar codes in the low-order word:

  • SB_BOTTOM Scroll to lower right.

  • SB_ENDSCROLL End scroll.

  • SB_LINEDOWN Scroll one line down.

  • SB_LINEUP Scroll one line up.

  • SB_PAGEDOWN Scroll one page down.

  • SB_PAGEUP Scroll one page up.

  • SB_THUMBPOSITION Scroll to the absolute position. The current position is provided in nPos.

  • SB_TOP Scroll to upper left.

nPos

Contains the scroll-box position if the scroll-bar code is SB_THUMBPOSITION; otherwise not used.

Remarks

The Clipboard owner’s OnHScrollClipboard member function is called by the Clipboard viewer when the Clipboard data has the CF_OWNERDISPLAY format and there is an event in the Clipboard viewer’s horizontal scroll bar. The owner should scroll the Clipboard image, invalidate the appropriate section, and update the scroll-bar values.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnVScrollClipboard, WM_HSCROLLCLIPBOARD


CWnd::OnIconEraseBkgnd

afx_msg void OnIconEraseBkgnd( CDC* pDC );

Parameters

pDC

Specifies the device-context object of the icon. May be temporary and should not be stored for later use.

Remarks

The framework calls this member function for a minimized (iconic) CWnd object when the background of the icon must be filled before painting the icon. CWnd receives this call only if a class icon is defined for the window default implementation; otherwise OnEraseBkgnd is called.

The DefWindowProc member function fills the icon background with the background brush of the parent window.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnEraseBkgnd, WM_ICONERASEBKGND


CWnd::OnInitMenu

afx_msg void OnInitMenu( CMenu* pMenu );

Parameters

pMenu

Specifies the menu to be initialized. May be temporary and should not be stored for later use.

Remarks

The framework calls this member function when a menu is about to become active. The call occurs when the user clicks an item on the menu bar or presses a menu key. Override this member function to modify the menu before it is displayed.

OnInitMenu is only called when a menu is first accessed; OnInitMenu is called only once for each access. This means, for example, that moving the mouse across several menu items while holding down the button does not generate new calls. This call does not provide information about menu items.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnInitMenuPopup, WM_INITMENU


CWnd::OnInitMenuPopup

afx_msg void OnInitMenuPopup( CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu );

Parameters

pPopupMenu

Specifies the menu object of the pop-up menu. May be temporary and should not be stored for later use.

nIndex

Specifies the index of the pop-up menu in the main menu.

bSysMenu

TRUE if the pop-up menu is the Control menu; otherwise FALSE.

Remarks

The framework calls this member function when a pop-up menu is about to become active. This allows an application to modify the pop-up menu before it is displayed without changing the entire menu.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnInitMenu, WM_INITMENUPOPUP


CWnd::OnKeyDown

afx_msg void OnKeyDown( UINT nChar, UINT nRepCnt, UINT nFlags );

Parameters

nChar

Specifies the virtual-key code of the given key.

nRepCnt

Repeat count (the number of times the keystroke is repeated as a result of the user holding down the key).

nFlags

Specifies the scan code, key-transition code, previous key state, and context code, as shown in the following list:

Value | Description
0–7 | Scan code (OEM-dependent value).
8 | Extended key, such as a function key or a key on the numeric keypad (1 if it is an extended key).
9–10 | Not used.
11–12 | Used internally by Windows.
13 | Context code (1 if the ALT key is held down while the key is pressed; otherwise 0).
14 | Previous key state (1 if the key is down before the call, 0 if the key is up).
15 | Transition state (1 if the key is being released, 0 if the key is being pressed).

For a WM_KEYDOWN message, the key-transition bit (bit 15) is 0 and the context-code bit (bit 13) is 0.

Remarks

The framework calls this member function when a nonsystem key is pressed. A nonsystem key is a keyboard key that is pressed when the ALT key is not pressed or a keyboard key that is pressed when CWnd has the input focus.

Because of auto-repeat, more than one OnKeyDown call may occur before an OnKeyUp member function call is made. The bit that indicates the previous key state can be used to determine whether the OnKeyDown call is the first down transition or a repeated down transition.

For IBM Enhanced 101- and 102-key keyboards, enhanced keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; and the slash (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in nFlags.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_CHAR, WM_KEYUP, WM_KEYDOWN


CWnd::OnKeyUp

afx_msg void OnKeyUp( UINT nChar, UINT nRepCnt, UINT nFlags );

Parameters

nChar

Specifies the virtual-key code of the given key.

nRepCnt

Repeat count (the number of times the keystroke is repeated as a result of the user holding down the key).

nFlags

Specifies the scan code, key-transition code, previous key state, and context code, as shown in the following list:

Value | Description
0–7 | Scan code (OEM-dependent value). Low byte of high-order word.
8 | Extended key, such as a function key or a key on the numeric keypad (1 if it is an extended key; otherwise 0).
9–10 | Not used.
11–12 | Used internally by Windows.
13 | Context code (1 if the ALT key is held down while the key is pressed; otherwise 0).
14 | Previous key state (1 if the key is down before the call, 0 if the key is up).
15 | Transition state (1 if the key is being released, 0 if the key is being pressed).

For a WM_KEYUP message, the key-transition bit (bit 15) is 1 and the context-code bit (bit 13) is 0.

Remarks

The framework calls this member function when a nonsystem key is released. A nonsystem key is a keyboard key that is pressed when the ALT key is not pressed or a keyboard key that is pressed when the CWnd has the input focus.

For IBM Enhanced 101- and 102-key keyboards, enhanced keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; and the slash (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in nFlags.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_CHAR, WM_KEYUP, CWnd::Default, WM_KEYDOWN


CWnd::OnKillFocus

afx_msg void OnKillFocus( CWnd* pNewWnd );

Parameters

pNewWnd

Specifies a pointer to the window that receives the input focus (may be NULL or may be temporary).

Remarks

The framework calls this member function immediately before losing the input focus.

If the CWnd object is displaying a caret, the caret should be destroyed at this point.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetFocus, WM_KILLFOCUS


CWnd::OnLButtonDblClk

afx_msg void OnLButtonDblClk( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if the CTRL key is down.

  • MK_LBUTTON Set if the left mouse button is down.

  • MK_MBUTTON Set if the middle mouse button is down.

  • MK_RBUTTON Set if the right mouse button is down.

  • MK_SHIFT Set if the SHIFT key is down.

point

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user double-clicks the left mouse button.

Only windows that have the CS_DBLCLKS WNDCLASS style will receive OnLButtonDblClk calls. This is the default for Microsoft Foundation Class windows. Windows calls OnLButtonDblClk when the user presses, releases, and then presses the left mouse button again within the system’s double-click time limit. Double-clicking the left mouse button actually generates four events: WM_LBUTTONDOWN, WM_LBUTTONUP messages, the WM_LBUTTONDBLCLK call, and another WM_LBUTTONUP message when the button is released.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnLButtonDown, CWnd::OnLButtonUp, WM_LBUTTONDBLCLK


CWnd::OnLButtonDown

afx_msg void OnLButtonDown( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if the CTRL key is down.

  • MK_LBUTTON Set if the left mouse button is down.

  • MK_MBUTTON Set if the middle mouse button is down.

  • MK_RBUTTON Set if the right mouse button is down.

  • MK_SHIFT Set if the SHIFT key is down.

point

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user presses the left mouse button.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnLButtonDblClk, CWnd::OnLButtonUp, WM_LBUTTONDOWN


CWnd::OnLButtonUp

afx_msg void OnLButtonUp( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if the CTRL key is down.

  • MK_MBUTTON Set if the middle mouse button is down.

  • MK_RBUTTON Set if the right mouse button is down.

  • MK_SHIFT Set if the SHIFT key is down.

point

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user releases the left mouse button.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnLButtonDblClk, CWnd::OnLButtonDown, WM_LBUTTONUP


CWnd::OnMButtonDblClk

afx_msg void OnMButtonDblClk( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if the CTRL key is down.

  • MK_LBUTTON Set if the left mouse button is down.

  • MK_MBUTTON Set if the middle mouse button is down.

  • MK_RBUTTON Set if the right mouse button is down.

  • MK_SHIFT Set if the SHIFT key is down.

point

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user double-clicks the middle mouse button.

Only windows that have the CS_DBLCLKS WNDCLASS style will receive OnMButtonDblClk calls. This is the default for all Microsoft Foundation Class windows. Windows generates an OnMButtonDblClk call when the user presses, releases, and then presses the middle mouse button again within the system’s double-click time limit. Double-clicking the middle mouse button actually generates four events: WM_MBUTTONDOWN and WM_MBUTTONUP messages, the WM_MBUTTONDBLCLK call, and another WM_MBUTTONUP message.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnMButtonDown, CWnd::OnMButtonUp, WM_MBUTTONDBLCLK


CWnd::OnMButtonDown

afx_msg void OnMButtonDown( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if the CTRL key is down.

  • MK_LBUTTON Set if the left mouse button is down.

  • MK_MBUTTON Set if the middle mouse button is down.

  • MK_RBUTTON Set if the right mouse button is down.

  • MK_SHIFT Set if the SHIFT key is down.

point

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user presses the middle mouse button.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnMButtonDblClk, CWnd::OnMButtonUp, WM_MBUTTONDOWN


CWnd::OnMButtonUp

afx_msg void OnMButtonUp( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if the CTRL key is down.

  • MK_LBUTTON Set if the left mouse button is down.

  • MK_RBUTTON Set if the right mouse button is down.

  • MK_SHIFT Set if the SHIFT key is down.

point

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user releases the middle mouse button.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnMButtonDblClk, CWnd::OnMButtonDown, WM_MBUTTONUP


CWnd::OnMDIActivate

afx_msg void OnMDIActivate( BOOL bActivate, CWnd* pActivateWnd, CWnd* pDeactivateWnd );

Parameters

bActivate

TRUE if the child is being activated and FALSE if it is being deactivated.

pActivateWnd

Contains a pointer to the MDI child window to be activated. When received by an MDI child window, pActivateWnd contains a pointer to the child window being activated. This pointer may be temporary and should not be stored for later use.

pDeactivateWnd

Contains a pointer to the MDI child window being deactivated. This pointer may be temporary and should not be stored for later use.

Remarks

The framework calls this member function for the child window being deactivated and the child window being activated.

An MDI child window is activated independently of the MDI frame window. When the frame becomes active, the child window that was last activated with a OnMDIActivate call receives an WM_NCACTIVATE message to draw an active window frame and caption bar, but it does not receive another OnMDIActivate call.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CMDIFrameWnd::MDIActivate, WM_MDIACTIVATE


CWnd::OnMeasureItem

afx_msg void OnMeasureItem( int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct );

Parameters

nIDCtl

The ID of the control.

lpMeasureItemStruct

Points to a MEASUREITEMSTRUCT data structure that contains the dimensions of the owner-draw control.

Remarks

The framework calls this member function by the framework for the owner of an owner-draw button, combo box, list box, or menu item when the control is created.

Override this member function and fill in the MEASUREITEMSTRUCT data structure pointed to by lpMeasureItemStruct and return; this informs Windows of the dimensions of the control and allows Windows to process user interaction with the control correctly.

If a list box or combo box is created with the LBS_OWNERDRAWVARIABLE or CBS_OWNERDRAWVARIABLE style, the framework calls this function for the owner for each item in the control; otherwise this function is called once.

Windows initiates the call to OnMeasureItem for the owner of combo boxes and list boxes created with the OWNERDRAWFIXED style before sending the WM_INITDIALOG message. As a result, when the owner receives this call, Windows has not yet determined the height and width of the font used in the control; function calls and calculations that require these values should occur in the main function of the application or library.

If the item being measured is a CMenu, CListBox or CComboBox object, then the MeasureItem virtual function of the appropriate class is called. Override the MeasureItem member function of the appropriate control’s class to calculate and set the size of each item.

OnMeasureItem will be called only if the control's class is created at run time, or it is created with the LBS_OWNERDRAWVARIABLE or CBS_OWNERDRAWVARIABLE style. If the control is created by the dialog editor, OnMeasureItem will not be called. This is because the WM_MEASUREITEM message is sent early in the creation process of the control. If you subclass by using DDX_Control, SubclassDlgItem, or SubclassWindow, the subclassing usually occurs after the creation process. Therefore, there is no way to handle the WM_MEASUREITEM message in the control's OnChildNotify function, which is the mechanism MFC uses to implement ON_WM_MEASUREITEM_REFLECT.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CMenu::MeasureItem, CListBox::MeasureItem, CComboBox::MeasureItem, WM_MEASUREITEM


CWnd::OnMenuChar

afx_msg LRESULT OnMenuChar( UINT nChar, UINT nFlags, CMenu* pMenu );

Return Value

The high-order word of the return value should contain one of the following command codes:

Value | Description
0 | Tells Windows to discard the character that the user pressed and creates a short beep on the system speaker.
1 | Tells Windows to close the current menu.
2 | Informs Windows that the low-order word of the return value contains the item number for a specific item. This item is selected by Windows.

The low-order word is ignored if the high-order word contains 0 or 1. Applications should process this message when accelerator (shortcut) keys are used to select bitmaps placed in a menu.

Parameters

nChar

Depending on the build settings, specifies the ANSI or Unicode character that the user pressed.

nFlags

Contains the MF_POPUP flag if the menu is a pop-up menu. It contains the MF_SYSMENU flag if the menu is a Control menu.

pMenu

Contains a pointer to the selected CMenu. The pointer may be temporary and should not be stored.

Remarks

The framework calls this member function when the user presses a menu mnemonic character that doesn’t match any of the predefined mnemonics in the current menu. It is sent to the CWnd that owns the menu. OnMenuChar is also called when the user presses ALT and any other key, even if the key does not correspond to a mnemonic character. In this case, pMenu points to the menu owned by the CWnd, and nFlags is 0.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_MENUCHAR


CWnd::OnMenuSelect

afx_msg void OnMenuSelect( UINT nItemID, UINT nFlags HMENU hSysMenu );

Parameters

nItemID

Identifies the item selected. If the selected item is a menu item, nItemID contains the menu-item ID. If the selected item contains a pop-up menu, nItemID contains the pop-up menu index, and hSysMenu contains the handle of the main (clicked-on) menu.

nFlags

Contains a combination of the following menu flags:

  • MF_BITMAP Item is a bitmap.

  • MF_CHECKED Item is checked.

  • MF_DISABLED Item is disabled.

  • MF_GRAYED Item is dimmed.

  • MF_MOUSESELECT Item was selected with a mouse.

  • MF_OWNERDRAW Item is an owner-draw item.

  • MF_POPUP Item contains a pop-up menu.

  • MF_SEPARATOR Item is a menu-item separator.

  • MF_SYSMENU Item is contained in the Control menu.

hSysMenu

If nFlags contains MF_SYSMENU, identifies the menu associated with the message. If nFlags contains MF_POPUP, identifies the handle of the main menu. If nFlags contains neither MF_SYSMENU nor MF_POPUP, it is unused.

Remarks

If the CWnd object is associated with a menu, OnMenuSelect is called by the framework when the user selects a menu item.

If nFlags contains 0xFFFF and hSysMenu contains 0, Windows has closed the menu because the user pressed the ESC key or clicked outside the menu.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_MENUSELECT


CWnd::OnMouseActivate

afx_msg int OnMouseActivate( CWnd* pDesktopWnd, UINT nHitTest, UINT message );

Return Value

Specifies whether to activate the CWnd and whether to discard the mouse event. It must be one of the following values:

  • MA_ACTIVATE Activate CWnd object.

  • MA_NOACTIVATE Do not activate CWnd object.

  • MA_ACTIVATEANDEAT Activate CWnd object and discard the mouse event.

  • MA_NOACTIVATEANDEAT Do not activate CWnd object and discard the mouse event.

Parameters

pDesktopWnd

Specifies a pointer to the top-level parent window of the window being activated. The pointer may be temporary and should not be stored.

nHitTest

Specifies the hit-test area code. A hit test is a test that determines the location of the cursor.

message

Specifies the mouse message number.

Remarks

The framework calls this member function when the cursor is in an inactive window and the user presses a mouse button.

The default implementation passes this message to the parent window before any processing occurs. If the parent window returns TRUE, processing is halted.

For a description of the individual hit-test area codes, see the OnNcHitTest member function

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, WM_MOUSEACTIVATE


CWnd::OnMouseMove

afx_msg void OnMouseMove( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if the CTRL key is down.

  • MK_LBUTTON Set if the left mouse button is down.

  • MK_MBUTTON Set if the middle mouse button is down.

  • MK_RBUTTON Set if the right mouse button is down.

  • MK_SHIFT Set if the SHIFT key is down.

point

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the mouse cursor moves. If the mouse is not captured, the WM_MOUSEMOVE message is received by the CWnd object beneath the mouse cursor; otherwise, the message goes to the window that has captured the mouse.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetCapture, CWnd::OnNCHitTest, WM_MOUSEMOVE


CWnd::OnMouseWheel

afx_msg BOOL OnMouseWheel( UINT nFlags, short zDelta, CPoint pt );

Return Value

Nonzero if mouse wheel scrolling is enabled; otherwise 0.

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if the CTRL key is down.

  • MK_LBUTTON Set if the left mouse button is down.

  • MK_MBUTTON Set if the middle mouse button is down.

  • MK_RBUTTON Set if the right mouse button is down.

  • MK_SHIFT Set if the SHIFT key is down.

zDelta

Indicates distance rotated. The zDelta value is expressed in multiples or divisions of WHEEL_DELTA, which is 120. A value less than zero indicates rotating back (toward the user) while a value greater than zero indicates rotating forward (away from the user). The user can reverse this response by changing the Wheel setting in the mouse software. See the Remarks for more information about this parameter.

pt

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function as a user rotates the mouse wheel and encounters the wheel's next notch. Unless overridden, OnMouseWheel calls the default of WM_MOUSEWHEEL. Windows automatically routes the message to the control or child window that has the focus. The Win32 function DefWindowProc propagates the message up the parent chain to the window that processes it.

The zDelta parameter is a multiple of WHEEL_DELTA, which is set at 120. This value is the threshold for an action to be taken, and one such action (for example, scrolling forward one notch) should occur for each delta.

The delta was set to 120 to allow for future finer-resolution wheels, such as a freely-rotating wheel with no notches. Such a device might send more messages per rotation, but with a smaller value in each message. To support this possibility, either aggregate the incoming delta values until WHEEL_DELTA is reached (so you get the same response for a given delta-rotation), or scroll partial lines in response to the more frequent messages. You could also choose your scroll granularity and accumulate deltas until WHEEL_DELTA is reached.

Override this member function to provide your own mouse-wheel scrolling behavior.

Note OnMouseWheel handles messages for Windows NT 4.0. For Windows 95 or Windows NT 3.51 message handling, use OnRegisteredMouseWheel.

CWnd Overview | Class Members | Hierarchy Chart

See Also mouse_event


CWnd::OnMove

afx_msg void OnMove( int x, int y );

Parameters

x

Specifies the new x-coordinate location of the upper-left corner of the client area. This new location is given in screen coordinates for overlapped and pop-up windows, and parent-client coordinates for child windows.

y

Specifies the new y-coordinate location of the upper-left corner of the client area. This new location is given in screen coordinates for overlapped and pop-up windows, and parent-client coordinates for child windows.

Remarks

The framework calls this member function after the CWnd object has been moved.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_MOVE


CWnd::OnMoving

afx_msg void OnMoving( UINT nSide, LPRECT lpRect );

Parameters

nSide

The edge of window to be moved.

lpRect

Address of the CRect or RECT structure that will contain the item’s coordinates.

Remarks

The framework calls this member function while a user is moving a CWnd object.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_MOVING


CWnd::OnNcActivate

afx_msg BOOL OnNcActivate( BOOL bActive );

Return Value

Nonzero if Windows should proceed with default processing; 0 to prevent the caption bar or icon from being deactivated.

Parameters

bActive

Specifies when a caption bar or icon needs to be changed to indicate an active or inactive state. The bActive parameter is TRUE if an active caption or icon is to be drawn. It is FALSE for an inactive caption or icon.

Remarks

The framework calls this member function when the nonclient area needs to be changed to indicate an active or inactive state. The default implementation draws the title bar and title-bar text in their active colors if bActive is TRUE and in their inactive colors if bActive is FALSE.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Default, WM_NCACTIVATE


CWnd::OnNcCalcSize

afx_msg void OnNcCalcSize( BOOL bCalcValidRects, NCCALCSIZE_PARAMS* lpncsp );

Parameters

bCalcValidRects

Specifies whether the application should specify which part of the client area contains valid information. Windows will copy the valid information to the specified area within the new client area. If this parameter is TRUE, the application should specify which part of the client area is valid.

lpncsp

Points to a NCCALCSIZE_PARAMS data structure that contains information an application can use to calculate the new size and position of the CWnd rectangle (including client area, borders, caption, scroll bars, and so on).

Remarks

The framework calls this member function when the size and position of the client area needs to be calculated. By processing this message, an application can control the contents of the window’s client area when the size or position of the window changes.

Regardless of the value of bCalcValidRects, the first rectangle in the array specified by the rgrc structure member of the NCCALCSIZE_PARAMS structure contains the coordinates of the window. For a child window, the coordinates are relative to the parent window’s client area. For top-level windows, the coordinates are screen coordinates. An application should modify the rgrc[0] rectangle to reflect the size and position of the client area.

The rgrc[1] and rgrc[2] rectangles are valid only if bCalcValidRects is TRUE. In this case, the rgrc[1] rectangle contains the coordinates of the window before it was moved or resized. The rgrc[2] rectangle contains the coordinates of the window’s client area before the window was moved. All coordinates are relative to the parent window or screen.

The default implementation calculates the size of the client area based on the window characteristics (presence of scroll bars, menu, and so on), and places the result in lpncsp.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_NCCALCSIZE, CWnd::MoveWindow, CWnd::SetWindowPos


CWnd::OnNcCreate

afx_msg BOOL OnNcCreate( LPCREATESTRUCT lpCreateStruct );

Return Value

Nonzero if the nonclient area is created. It is 0 if an error occurs; the Create function will return failure in this case.

Parameters

lpCreateStruct

Points to the CREATESTRUCT data structure for CWnd.

Remarks

The framework calls this member function prior to the WM_CREATE message when the CWnd object is first created.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Create, CWnd::CreateEx, WM_NCCREATE


CWnd::OnNcDestroy

afx_msg void OnNcDestroy( );

Remarks

Called by the framework when the nonclient area is being destroyed, and is the last member function called when the Windows window is destroyed. The default implementation performs some cleanup, then calls the virtual member function PostNcDestroy.

Override PostNcDestroy if you want to perform your own cleanup, such as a delete this operation. If you override OnNcDestroy, you must call OnNcDestroy in your base class to ensure that any memory internally allocated for the window is freed.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DestroyWindow, CWnd::OnNcCreate, WM_NCDESTROY, CWnd::Default, CWnd::PostNcDestroy


CWnd::OnNcHitTest

afx_msg UINT OnNcHitTest( CPoint point );

Return Value

One of the mouse hit-test enumerated values listed below.

Parameters

point

Contains the x- and y-coordinates of the cursor. These coordinates are always screen coordinates.

Remarks

The framework calls this member function for the CWnd object that contains the cursor (or the CWnd object that used the SetCapture member function to capture the mouse input) every time the mouse is moved.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetCapture, WM_NCHITTEST

Mouse Enumerated Values

  • HTBORDER In the border of a window that does not have a sizing border.

  • HTBOTTOM In the lower horizontal border of the window.

  • HTBOTTOMLEFT In the lower-left corner of the window border.

  • HTBOTTOMRIGHT In the lower-right corner of the window border.

  • HTCAPTION In a title-bar area.

  • HTCLIENT In a client area.

  • HTERROR On the screen background or on a dividing line between windows (same as HTNOWHERE except that the DefWndProc Windows function produces a system beep to indicate an error).

  • HTGROWBOX In a size box.

  • HTHSCROLL In the horizontal scroll bar.

  • HTLEFT In the left border of the window.

  • HTMAXBUTTON In a Maximize button.

  • HTMENU In a menu area.

  • HTMINBUTTON In a Minimize button.

  • HTNOWHERE On the screen background or on a dividing line between windows.

  • HTREDUCE In a Minimize button.

  • HTRIGHT In the right border of the window.

  • HTSIZE In a size box (same as HTGROWBOX).

  • HTSYSMENU In a Control menu or in a Close button in a child window.

  • HTTOP In the upper horizontal border of the window.

  • HTTOPLEFT In the upper-left corner of the window border.

  • HTTOPRIGHT In the upper-right corner of the window border.

  • HTTRANSPARENT In a window currently covered by another window.

  • HTVSCROLL In the vertical scroll bar.

  • HTZOOM In a Maximize button.


CWnd::OnNcLButtonDblClk

afx_msg void OnNcLButtonDblClk( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user double-clicks the left mouse button while the cursor is within a nonclient area of CWnd.

If appropriate, the WM_SYSCOMMAND message is sent.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_NCLBUTTONDBLCLK, CWnd::OnNcHitTest


CWnd::OnNcLButtonDown

afx_msg void OnNcLButtonDown( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user presses the left mouse button while the cursor is within a nonclient area of the CWnd object.

If appropriate, the WM_SYSCOMMAND is sent.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received.If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnNcLButtonDblClk, CWnd::OnNcLButtonUp, CWnd::OnSysCommand, WM_NCLBUTTONDOWN, CWnd::Default


CWnd::OnNcLButtonUp

afx_msg void OnNcLButtonUp( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user releases the left mouse button while the cursor is within a nonclient area.

If appropriate, WM_SYSCOMMAND is sent.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnNcLButtonDown, CWnd::OnSysCommand, WM_NCLBUTTONUP


CWnd::OnNcMButtonDblClk

afx_msg void OnNcMButtonDblClk( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user double-clicks the middle mouse button while the cursor is within a nonclient area.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnNcMButtonDown, CWnd::OnNcMButtonUp, WM_NCMBUTTONDBLCLK


CWnd::OnNcMButtonDown

afx_msg void OnNcMButtonDown( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user presses the middle mouse button while the cursor is within a nonclient area.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnNcMButtonDblClk, CWnd::OnNcMButtonUp, WM_NCMBUTTONDOWN


CWnd::OnNcMButtonUp

afx_msg void OnNcMButtonUp( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user releases the middle mouse button while the cursor is within a nonclient area.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnNcMButtonDblClk, CWnd::OnNcMButtonDown, WM_NCMBUTTONUP


CWnd::OnNcMouseMove

afx_msg void OnNcMouseMove( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the cursor is moved within a nonclient area. If appropriate, the WM_SYSCOMMAND message is sent.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnSysCommand, WM_NCMOUSEMOVE


CWnd::OnNcPaint

afx_msg void OnNcPaint( );

Remarks

The framework calls this member function when the nonclient area needs to be painted. The default implementation paints the window frame.

An application can override this call and paint its own custom window frame. The clipping region is always rectangular, even if the shape of the frame is altered.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_NCPAINT


CWnd::OnNcRButtonDblClk

afx_msg void OnNcRButtonDblClk( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user double-clicks the right mouse button while the cursor is within a nonclient area of CWnd.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnNcRButtonDown, CWnd::OnNcRButtonUp, WM_NCRBUTTONDBLCLK


CWnd::OnNcRButtonDown

afx_msg void OnNcRButtonDown( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user presses the right mouse button while the cursor is within a nonclient area.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnNcRButtonDblClk, CWnd::OnNcRButtonUp


CWnd::OnNcRButtonUp

afx_msg void OnNcRButtonUp( UINT nHitTest, CPoint point );

Parameters

nHitTest

Specifies the hit-test code. A hit test is a test that determines the location of the cursor.

point

Specifies a CPoint object that contains the x and y screen coordinates of the cursor position. These coordinates are always relative to the upper-left corner of the screen.

Remarks

The framework calls this member function when the user releases the right mouse button while the cursor is within a nonclient area.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, CWnd::OnNcRButtonDblClk, CWnd::OnNcRButtonDown, WM_NCRBUTTONUP


CWnd::OnNotify

virtual BOOL CWnd::OnNotify( WPARAM wParam, LPARAM lParam, LRESULT* pResult );

Return Value

An application returns nonzero if it processes this message; otherwise 0.

Parameters

wParam

Identifies the control that sends the message if the message is from a control. Otherwise, wParam is 0.

lParam

Pointer to a notification message (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.

pResult

Pointer to an LRESULT variable in which to store the result code if the message is handled.

Remarks

The framework calls this member function to inform the parent window of a control that an event has occurred in the control or that the control requires some kind of information.

OnNotify processes the message map for control notification.

Override this member function in your derived class to handle the WM_NOTIFY message. An override will not process the message map unless the base class OnNotify is called.

For more information on the WM_NOTIFY message, see Technical Note 61 (TN061), ON_NOTIFY and WM_NOTIFY messages. You may also be interested the related topics described in TN060, The New Windows Common Controls, and TN062, Message Reflection for Windows Controls.


CWnd::OnPaint

afx_msg void OnPaint( );

Remarks

The framework calls this member function when Windows or an application makes a request to repaint a portion of an application’s window. The WM_PAINT message is sent when the UpdateWindow or RedrawWindow member function is called.

A window may receive internal paint messages as a result of calling the RedrawWindow member function with the RDW_INTERNALPAINT flag set. In this case, the window may not have an update region. An application should call the GetUpdateRect member function to determine whether the window has an update region. If GetUpdateRect returns 0, the application should not call the BeginPaint and EndPaint member functions.

It is an application’s responsibility to check for any necessary internal repainting or updating by looking at its internal data structures for each WM_PAINT message because a WM_PAINT message may have been caused by both an invalid area and a call to the RedrawWindow member function with the RDW_INTERNALPAINT flag set.

An internal WM_PAINT message is sent only once by Windows. After an internal WM_PAINT message is sent to a window by the UpdateWindow member function, no further WM_PAINT messages will be sent or posted until the window is invalidated or until the RedrawWindow member function is called again with the RDW_INTERNALPAINT flag set.

For information on rendering an image in document/view applications, see CView::OnDraw.

For more information about using WM_Paint, see the following topics in the Win32 SDK Programmer’s Reference:

  • The WM_PAINT Message

  • Using the WM_PAINT Message

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, CWnd::EndPaint, CWnd::RedrawWindow, CPaintDC, CView::OnDraw


CWnd::OnPaintClipboard

afx_msg void OnPaintClipboard( CWnd* pClipAppWnd, HGLOBAL hPaintStruct );

Parameters

pClipAppWnd

Specifies a pointer to the Clipboard-application window. The pointer may be temporary and should not be stored for later use.

hPaintStruct

Identifies a PAINTSTRUCT data structure that defines what part of the client area to paint.

Remarks

A Clipboard owner’s OnPaintClipboard member function is called by a Clipboard viewer when the Clipboard owner has placed data on the Clipboard in the CF_OWNERDISPLAY format and the Clipboard viewer’s client area needs repainting.

To determine whether the entire client area or just a portion of it needs repainting, the Clipboard owner must compare the dimensions of the drawing area given in the rcpaint member of the PAINTSTRUCT structure to the dimensions given in the most recent OnSizeClipboard member function call.

OnPaintClipboard should use the GlobalLock Windows function to lock the memory that contains the PAINTSTRUCT data structure and unlock that memory with the GlobalUnlock Windows function before it exits.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GlobalLock, ::GlobalUnlock, CWnd::OnSizeClipboard, WM_PAINTCLIPBOARD


CWnd::OnPaletteChanged

afx_msg void OnPaletteChanged( CWnd* pFocusWnd );

Parameters

pFocusWnd

Specifies a pointer to the window that caused the system palette to change. The pointer may be temporary and should not be stored.

Remarks

The framework calls this member function for all top-level windows after the window with input focus has realized its logical palette, thereby changing the system palette. This call allows a window without the input focus that uses a color palette to realize its logical palettes and update its client area.

The OnPaletteChanged member function is called for all top-level and overlapped windows, including the one that changed the system palette and caused the WM_PALETTECHANGED message to be sent. If any child window uses a color palette, this message must be passed on to it.

To avoid an infinite loop, the window shouldn’t realize its palette unless it determines that pFocusWnd does not contain a pointer to itself.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::RealizePalette, WM_PALETTECHANGED, CWnd::OnPaletteIsChanging, CWnd::OnQueryNewPalette


CWnd::OnPaletteIsChanging

afx_msg void OnPaletteIsChanging( CWnd* pRealizeWnd );

Parameters

pRealizeWnd

Specifies the window that is about to realize its logical palette.

Remarks

The framework calls this member function to inform applications that an application is going to realize its logical palette.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnPaletteChanged, CWnd::OnQueryNewPalette, WM_PALETTEISCHANGING


CWnd::OnParentNotify

afx_msg void OnParentNotify( UINT message, LPARAM lParam );

Parameters

message

Specifies the event for which the parent is being notified and the identifier of the child window. The event is the low-order word of message. If the event is WM_CREATE or WM_DESTROY, the high-order word of message is the identifier of the child window; otherwise, the high-order word is undefined. The event (low-order word of message) can be any of these values:

  • WM_CREATE The child window is being created.

  • WM_DESTROY The child window is being destroyed.

  • WM_LBUTTONDOWN The user has placed the mouse cursor over the child window and clicked the left mouse button.

  • WM_MBUTTONDOWN The user has placed the mouse cursor over the child window and clicked the middle mouse button.

  • WM_RBUTTONDOWN The user has placed the mouse cursor over the child window and clicked the right mouse button.

lParam

If the event (low-order word) of message is WM_CREATE or WM_DESTROY, lParam specifies the window handle of the child window; otherwise lParam contains the x and y coordinates of the cursor. The x coordinate is in the low-order word and the y coordinate is in the high-order word.

Remarks

A parent’s OnParentNotify member function is called by the framework when its child window is created or destroyed, or when the user clicks a mouse button while the cursor is over the child window. When the child window is being created, the system calls OnParentNotify just before the Create member function that creates the window returns. When the child window is being destroyed, the system calls OnParentNotify before any processing takes place to destroy the window.

OnParentNotify is called for all ancestor windows of the child window, including the top-level window.

All child windows except those that have the WS_EX_NOPARENTNOTIFY style send this message to their parent windows. By default, child windows in a dialog box have the WS_EX_NOPARENTNOTIFY style unless the child window was created without this style by calling the CreateEx member function.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnCreate, CWnd::OnDestroy, CWnd::OnLButtonDown, CWnd::OnMButtonDown, CWnd::OnRButtonDown, WM_PARENTNOTIFY


CWnd::OnQueryDragIcon

afx_msg HCURSOR OnQueryDragIcon( );

Return Value

A doubleword value that contains a cursor or icon handle in the low-order word. The cursor or icon must be compatible with the display driver’s resolution. If the application returns NULL, the system displays the default cursor. The default return value is NULL.

Remarks

The framework calls this member function by a minimized (iconic) window that does not have an icon defined for its class. The system makes this call to obtain the cursor to display while the user drags the minimized window.

If an application returns the handle of an icon or cursor, the system converts it to black-and-white.

If an application returns a handle, the handle must identify a monochrome cursor or icon compatible with the display driver’s resolution. The application can call the CWinApp::LoadCursor or CWinApp::LoadIcon member functions to load a cursor or icon from the resources in its executable file and to obtain this handle.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWinApp::LoadCursor, CWinApp::LoadIcon, WM_QUERYDRAGICON


CWnd::OnQueryEndSession

afx_msg BOOL OnQueryEndSession( );

Return Value

Nonzero if an application can be conveniently shut down; otherwise 0.

Remarks

The framework calls this member function when the user chooses to end the Windows session or when an application calls the ExitWindows Windows function. If any application returns 0, the Windows session is not ended. Windows stops calling OnQueryEndSession as soon as one application returns 0 and sends the WM_ENDSESSION message with a parameter value of FALSE for any application that has already returned nonzero.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::ExitWindows, CWnd::OnEndSession, WM_QUERYENDSESSION


CWnd::OnQueryNewPalette

afx_msg BOOL OnQueryNewPalette( );

Return Value

Nonzero if the CWnd realizes its logical palette; otherwise 0.

Remarks

The framework calls this member function when the CWnd object is about to receive the input focus, giving the CWnd an opportunity to realize its logical palette when it receives the focus.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Default, CWnd::OnPaletteChanged, WM_QUERYNEWPALETTE


CWnd::OnQueryOpen

afx_msg BOOL OnQueryOpen( );

Return Value

Nonzero if the icon can be opened, or 0 to prevent the icon from being opened.

Remarks

The framework calls this member function when the CWnd object is minimized and the user requests that the CWnd be restored to its preminimized size and position.

While in OnQueryOpen, CWnd should not perform any action that would cause an activation or focus change (for example, creating a dialog box).

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_QUERYOPEN


CWnd::OnRButtonDblClk

afx_msg void OnRButtonDblClk( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if CTRL key is down.

  • MK_LBUTTON Set if left mouse button is down.

  • MK_MBUTTON Set if middle mouse button is down.

  • MK_RBUTTON Set if right mouse button is down.

  • MK_SHIFT Set if SHIFT key is down.

point

Specifies the x and y coordinates of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user double-clicks the right mouse button.

Only windows that have the CS_DBLCLKS WNDCLASS style can receive OnRButtonDblClk calls. This is the default for windows within the Microsoft Foundation Class Library. Windows calls OnRButtonDblClk when the user presses, releases, and then again presses the right mouse button within the system’s double-click time limit. Double-clicking the right mouse button actually generates four events: WM_RBUTTONDOWN and WM_RBUTTONUP messages, the OnRButtonDblClk call, and another WM_RBUTTONUP message when the button is released.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnRButtonDown, CWnd::OnRButtonUp, WM_RBUTTONDBLCLK


CWnd::OnRButtonDown

afx_msg void OnRButtonDown( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if CTRL key is down.

  • MK_LBUTTON Set if left mouse button is down.

  • MK_MBUTTON Set if middle mouse button is down.

  • MK_RBUTTON Set if right mouse button is down.

  • MK_SHIFT Set if SHIFT key is down.

point

Specifies the x and y coordinates of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user presses the right mouse button.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnRButtonDblClk, CWnd::OnRButtonUp, WM_RBUTTONDOWN


CWnd::OnRButtonUp

afx_msg void OnRButtonUp( UINT nFlags, CPoint point );

Parameters

nFlags

Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

  • MK_CONTROL Set if CTRL key is down.

  • MK_LBUTTON Set if left mouse button is down.

  • MK_MBUTTON Set if middle mouse button is down.

  • MK_SHIFT Set if SHIFT key is down.

point

Specifies the x and y coordinates of the cursor. These coordinates are always relative to the upper-left corner of the window.

Remarks

The framework calls this member function when the user releases the right mouse button.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnRButtonDblClk, CWnd::OnRButtonDown, WM_RBUTTONUP


CWnd::OnRegisteredMouseWheel

afx_msg LRESULT OnRegisteredMouseWheel( WPARAM wParam, LPARAM lParam );

Return Value

Insignificant at this time. Always zero.

Parameters

wParam

Horizontal position of the pointer.

lParam

Vertical position of the pointer.

Remarks

The framework calls this member function as a user rotates the mouse wheel and encounters the wheel's next notch. Unless overridden, OnRegisteredMouseWheel registers the Windows message, routes the message to the appropriate window, and calls the WM_MOUSEWHEEL handler for that window.

Override this member function to provide your own message routing or to alter the mouse-wheel scrolling behavior.

Note OnRegisteredMouseWheel handles messages for Windows 95 and Windows NT 3.51. For Windows NT 4.0 message handling, use OnMouseWheel.

CWnd Overview | Class Members | Hierarchy Chart

See Also RegisterWindowMessage


CWnd::OnRenderAllFormats

afx_msg void OnRenderAllFormats( );

Remarks

The Clipboard owner’s OnRenderAllFormats member function is called by the framework when the owner application is being destroyed.

The Clipboard owner should render the data in all the formats it is capable of generating and pass a data handle for each format to the Clipboard by calling the SetClipboardData Windows function. This ensures that the Clipboard contains valid data even though the application that rendered the data is destroyed. The application should call the OpenClipboard member function before calling the SetClipboardData Windows function and call the CloseClipboard Windows function afterward.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::CloseClipboard, CWnd::OpenClipboard, ::SetClipboardData, CWnd::OnRenderFormat, WM_RENDERALLFORMATS


CWnd::OnRenderFormat

afx_msg void OnRenderFormat( UINT nFormat );

Parameters

nFormat

Specifies the Clipboard format.

Remarks

The Clipboard owner’s OnRenderFormat member function is called by the framework when a particular format with delayed rendering needs to be rendered. The receiver should render the data in that format and pass it to the Clipboard by calling the SetClipboardData Windows function.

Do not call the OpenClipboard member function or the CloseClipboard Windows function from within OnRenderFormat.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::CloseClipboard, CWnd::OpenClipboard, ::SetClipboardData, WM_RENDERFORMAT


CWnd::OnSetCursor

afx_msg BOOL OnSetCursor( CWnd* pWnd, UINT nHitTest, UINT message );

Return Value

Nonzero to halt further processing, or 0 to continue.

Parameters

pWnd

Specifies a pointer to the window that contains the cursor. The pointer may be temporary and should not be stored for later use.

nHitTest

Specifies the hit-test area code. The hit test determines the cursor’s location.

message

Specifies the mouse message number.

Remarks

The framework calls this member function if mouse input is not captured and the mouse causes cursor movement within the CWnd object.

The default implementation calls the parent window’s OnSetCursor before processing. If the parent window returns TRUE, further processing is halted. Calling the parent window gives the parent window control over the cursor’s setting in a child window.

The default implementation sets the cursor to an arrow if it is not in the client area or to the registered-class cursor if it is.

If nHitTest is HTERROR and message is a mouse button-down message, the MessageBeep member function is called.

The message parameter is 0 when CWnd enters menu mode.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcHitTest, WM_SETCURSOR


CWnd::OnSetFocus

afx_msg void OnSetFocus( CWnd* pOldWnd );

Parameters

pOldWnd

Contains the CWnd object that loses the input focus (may be NULL). The pointer may be temporary and should not be stored for later use.

Remarks

The framework calls this member function after gaining the input focus. To display a caret, CWnd should call the appropriate caret functions at this point.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_SETFOCUS


CWnd::OnShowWindow

afx_msg void OnShowWindow( BOOL bShow, UINT nStatus );

Parameters

bShow

Specifies whether a window is being shown. It is TRUE if the window is being shown; it is FALSE if the window is being hidden.

nStatus

Specifies the status of the window being shown. It is 0 if the message is sent because of a ShowWindow member function call; otherwise nStatus is one of the following:

  • SW_PARENTCLOSING Parent window is closing (being made iconic) or a pop-up window is being hidden.

  • SW_PARENTOPENING Parent window is opening (being displayed) or a pop-up window is being shown.

Remarks

The framework calls this member function when the CWnd object is about to be hidden or shown. A window is hidden or shown when the ShowWindow member function is called, when an overlapped window is maximized or restored, or when an overlapped or pop-up window is closed (made iconic) or opened (displayed on the screen). When an overlapped window is closed, all pop-up windows associated with that window are hidden.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_SHOWWINDOW


CWnd::OnSize

afx_msg void OnSize( UINT nType, int cx, int cy );

Parameters

nType

Specifies the type of resizing requested. This parameter can be one of the following values:

  • SIZE_MAXIMIZED Window has been maximized.

  • SIZE_MINIMIZED Window has been minimized.

  • SIZE_RESTORED Window has been resized, but neither SIZE_MINIMIZED nor SIZE_MAXIMIZED applies.

  • SIZE_MAXHIDE Message is sent to all pop-up windows when some other window is maximized.

  • SIZE_MAXSHOW Message is sent to all pop-up windows when some other window has been restored to its former size.

cx

Specifies the new width of the client area.

cy

Specifies the new height of the client area.

Remarks

The framework calls this member function after the window’s size has changed.

If the SetScrollPos or MoveWindow member function is called for a child window from OnSize, the bRedraw parameter of SetScrollPos or MoveWindow should be nonzero to cause the CWnd to be repainted.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::MoveWindow, CWnd::SetScrollPos, WM_SIZE


CWnd::OnSizeClipboard

afx_msg void OnSizeClipboard( CWnd* pClipAppWnd, HGLOBAL hRect );

Parameters

pClipAppWnd

Identifies the Clipboard-application window. The pointer may be temporary and should not be stored.

hRect

Identifies a global memory object. The memory object contains a RECT data structure that specifies the area for the Clipboard owner to paint.

Remarks

The Clipboard owner’s OnSizeClipboard member function is called by the Clipboard viewer when the Clipboard contains data with the CF_OWNERDISPLAY attribute and the size of the client area of the Clipboard-viewer window has changed.

The OnSizeClipboard member function is called with a null rectangle (0,0,0,0) as the new size when the Clipboard application is about to be destroyed or minimized. This permits the Clipboard owner to free its display resources.

Within OnSizeClipboard, an application must use the GlobalLock Windows function to lock the memory that contains the RECT data structure. Have the application unlock that memory with the GlobalUnlock Windows function before it yields or returns control.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GlobalLock, ::GlobalUnlock, ::SetClipboardData, CWnd::SetClipboardViewer, WM_SIZECLIPBOARD


CWnd::OnSizing

afx_msg void OnSizing( UINT nSide, LPRECT lpRect );

Parameters

nSide

The edge of window to be moved.

lpRect

Address of the CRect or RECT structure that will contain the item’s coordinates.

Remarks

The framework calls this member function to indicate that the user is resizing the rectangle. By processing this message, an application can monitor the size and position of the drag rectangle and, if needed, change its size or position.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.


CWnd::OnSpoolerStatus

afx_msg void OnSpoolerStatus( UINT nStatus, UINT nJobs );

Parameters

nStatus

Specifies the SP_JOBSTATUS flag.

nJobs

Specifies the number of jobs remaining in the Print Manager queue.

Remarks

The framework calls this member function from Print Manager whenever a job is added to or removed from the Print Manager queue.

This call is for informational purposes only.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_SPOOLERSTATUS


CWnd::OnStyleChanged

afx_msg void OnStyleChanged( int nStyleType, LPSTYLESTRUCT lpStyleStruct );

Parameters

nStyleType

Specifies whether the window's extended or nonextended styles have changed. This parameter can be a combination of the following values:

  • GWL_EXSTYLE The window's extended styles have changed.

  • GWL_STYLE The window's nonextended styles have changed.

lpStyleStruct

Points to a STYLESTRUCT structure that contains the new styles for the window. An application can examine the styles, but it can not change them.

Remarks

The framework calls this member function after the ::SetWindowLong function has changed one or more of the window's styles.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_STYLECHANGED


CWnd::OnStyleChanging

afx_msg void OnStyleChanging( int nStyleType, LPSTYLESTRUCT lpStyleStruct );

Parameters

nStyleType

Specifies whether the window's extended or nonextended styles have changed. This parameter can be a combination of the following values:

  • GWL_EXSTYLE The window's extended styles have changed.

  • GWL_STYLE The window's nonextended styles have changed.

lpStyleStruct

Points to a STYLESTRUCT structure that contains the new styles for the window. An application can examine the styles and change them.

Remarks

The framework calls this member function when the ::SetWindowLong function is about to change one or more of the window's styles.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.


CWnd::OnSysChar

afx_msg void OnSysChar( UINT nChar, UINT nRepCnt, UINT nFlags );

Parameters

nChar

Specifies the ASCII-character key code of a Control-menu key.

nRepCnt

Specifies the repeat count (the number of times the keystroke is repeated as a result of the user holding down the key).

nFlags

The nFlags parameter can have these values:

Value | Meaning
0-15 | Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key..
16-23 | Specifies the scan code. The value depends on the original equipment manufacturer (OEM)
24 | Specifies whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.
25-28 | Used internally by Windows.
29 | Specifies the context code. The value is 1 if the ALT key is held down while the key is pressed; otherwise, the value is 0.
30 | Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.
31 | Specifies the transition state. The value is 1 if the key is being released, or it is 0 if the key is being pressed.

Remarks

The framework calls this member function if CWnd has the input focus and the WM_SYSKEYUP and WM_SYSKEYDOWN messages are translated. It specifies the virtual-key code of the Control-menu key.

When the context code is 0, WM_SYSCHAR can pass the WM_SYSCHAR message to the TranslateAccelerator Windows function, which will handle it as though it were a normal key message instead of a system character-key. This allows accelerator keys to be used with the active window even if the active window does not have the input focus.

For IBM Enhanced 101- and 102-key keyboards, enhanced keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; and the slash (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in nFlags.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::TranslateAccelerator, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_SYSCHAR


CWnd::OnSysColorChange

afx_msg void OnSysColorChange( );

Remarks

The framework calls this member function for all top-level windows when a change is made in the system color setting.

Windows calls OnSysColorChange for any window that is affected by a system color change.

Applications that have brushes that use the existing system colors should delete those brushes and re-create them with the new system colors.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SetSysColors, WM_SYSCOLORCHANGE


CWnd::OnSysCommand

afx_msg void OnSysCommand( UINT nID, LPARAM lParam );

Parameters

nID

Specifies the type of system command requested. This parameter can be any one of the following values:

  • SC_CLOSE Close the CWnd object.

  • SC_HOTKEY Activate the CWnd object associated with the application-specified hot key. The low-order word of lParam identifies the HWND of the window to activate.

  • SC_HSCROLL Scroll horizontally.

  • SC_KEYMENU Retrieve a menu through a keystroke.

  • SC_MAXIMIZE (or SC_ZOOM) Maximize the CWnd object.

  • SC_MINIMIZE (or SC_ICON) Minimize the CWnd object.

  • SC_MOUSEMENU Retrieve a menu through a mouse click.

  • SC_MOVE Move the CWnd object.

  • SC_NEXTWINDOW Move to the next window.

  • SC_PREVWINDOW Move to the previous window.

  • SC_RESTORE Restore window to normal position and size.

  • SC_SCREENSAVE Executes the screen-saver application specified in the [boot] section of the SYSTEM.INI file.

  • SC_SIZE Size the CWnd object.

  • SC_TASKLIST Execute or activate the Windows Task Manager application.

  • SC_VSCROLL Scroll vertically.

lParam

If a Control-menu command is chosen with the mouse, lParam contains the cursor coordinates. The low-order word contains the x coordinate, and the high-order word contains the y coordinate. Otherwise this parameter is not used.

  • SC_HOTKEY Activate the window associated with the application-specified hot key. The low-order word of lParam identifies the window to activate.

  • SC_SCREENSAVE Execute the screen-save application specified in the Desktop section of Control Panel.

Remarks

The framework calls this member function when the user selects a command from the Control menu, or when the user selects the Maximize or the Minimize button.

By default, OnSysCommand carries out the Control-menu request for the predefined actions specified in the preceding table.

In WM_SYSCOMMAND messages, the four low-order bits of the nID parameter are used internally by Windows. When an application tests the value of nID, it must combine the value 0xFFF0 with the nID value by using the bitwise-AND operator to obtain the correct result.

The menu items in a Control menu can be modified with the GetSystemMenu, AppendMenu, InsertMenu, and ModifyMenu member functions. Applications that modify the Control menu must process WM_SYSCOMMAND messages, and any WM_SYSCOMMAND messages not handled by the application must be passed on to OnSysCommand. Any command values added by an application must be processed by the application and cannot be passed to OnSysCommand.

An application can carry out any system command at any time by passing a WM_SYSCOMMAND message to OnSysCommand.

Accelerator (shortcut) keystrokes that are defined to select items from the Control menu are translated into OnSysCommand calls; all other accelerator keystrokes are translated into WM_COMMAND messages.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_SYSCOMMAND


CWnd::OnSysDeadChar

afx_msg void OnSysDeadChar( UINT nChar, UINT nRepCnt, UINT nFlags );

Parameters

nChar

Specifies the dead-key character value.

nRepCnt

Specifies the repeat count.

nFlags

Specifies the scan code, key-transition code, previous key state, and context code, as shown in the following list:

Value | Meaning
0–7 | Scan code (OEM-dependent value). Low byte of high-order word.
8 | Extended key, such as a function key or a key on the numeric keypad (1 if it is an extended key; otherwise 0).
9–10 | Not used.
11–12 | Used internally by Windows.
13 | Context code (1 if the ALT key is held down while the key is pressed; otherwise 0).
14 | Previous key state (1 if the key is down before the call, 0 if the key is up).
15 | Transition state (1 if the key is being released, 0 if the key is being pressed).

Remarks

The framework calls this member function if the CWnd object has the input focus when the OnSysKeyUp or OnSysKeyDown member function is called. It specifies the character value of a dead key.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnSysKeyDown, CWnd::OnSysKeyUp, WM_SYSDEADCHAR, CWnd::OnDeadChar


CWnd::OnSysKeyDown

afx_msg void OnSysKeyDown( UINT nChar, UINT nRepCnt, UINT nFlags );

Parameters

nChar

Specifies the virtual-key code of the key being pressed.

nRepCnt

Specifies the repeat count.

nFlags

Specifies the scan code, key-transition code, previous key state, and context code, as shown in the following list:

Value | Meaning
0–7 | Scan code (OEM-dependent value). Low byte of high-order word.
8 | Extended key, such as a function key or a key on the numeric keypad (1 if it is an extended key; otherwise 0).
9–10 | Not used.
11–12 | Used internally by Windows.
13 | Context code (1 if the ALT key is held down while the key is pressed, 0 otherwise).
14 | Previous key state (1 if the key is down before the message is sent, 0 if the key is up).
15 | Transition state (1 if the key is being released, 0 if the key is being pressed).

For OnSysKeyDown calls, the key-transition bit (bit 15) is 0. The context-code bit (bit 13) is 1 if the ALT key is down while the key is pressed; it is 0 if the message is sent to the active window because no window has the input focus.

Remarks

If the CWnd object has the input focus, the OnSysKeyDown member function is called by the framework when the user holds down the ALT key and then presses another key. If no window currently has the input focus, the active window’s OnSysKeyDown member function is called. The CWnd object that receives the message can distinguish between these two contexts by checking the context code in nFlags.

When the context code is 0, the WM_SYSKEYDOWN message received by OnSysKeyDown can be passed to the TranslateAccelerator Windows function, which will handle it as though it were a normal key message instead of a system-key message. This allows accelerator keys to be used with the active window even if the active window does not have the input focus.

Because of auto-repeat, more than one OnSysKeyDown call may occur before the WM_SYSKEYUP message is received. The previous key state (bit 14) can be used to determine whether the OnSysKeyDown call indicates the first down transition or a repeated down transition.

For IBM Enhanced 101- and 102-key keyboards, enhanced keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; and the slash (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in nFlags.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::TranslateAccelerator, WM_SYSKEYUP, WM_SYSKEYDOWN


CWnd::OnSysKeyUp

afx_msg void OnSysKeyUp( UINT nChar, UINT nRepCnt, UINT nFlags );

Parameters

nChar

Specifies the virtual-key code of the key being pressed.

nRepCnt

Specifies the repeat count.

nFlags

Specifies the scan code, key-transition code, previous key state, and context code, as shown in the following list:

Value | Meaning
0–7 | Scan code (OEM-dependent value). Low byte of high-order word.
8 | Extended key, such as a function key or a key on the numeric keypad (1 if it is an extended key; otherwise 0).
9–10 | Not used.
11–12 | Used internally by Windows.
13 | Context code (1 if the ALT key is held down while the key is pressed, 0 otherwise).
14 | Previous key state (1 if the key is down before the message is sent, 0 if the key is up).
15 | Transition state (1 if the key is being released, 0 if the key is being pressed).

For OnSysKeyUp calls, the key-transition bit (bit 15) is 1. The context-code bit (bit 13) is 1 if the ALT key is down while the key is pressed; it is 0 if the message is sent to the active window because no window has the input focus.

Remarks

If the CWnd object has the focus, the OnSysKeyUp member function is called by the framework when the user releases a key that was pressed while the ALT key was held down. If no window currently has the input focus, the active window’s OnSysKeyUp member function is called. The CWnd object that receives the call can distinguish between these two contexts by checking the context code in nFlags.

When the context code is 0, the WM_SYSKEYUP message received by OnSysKeyUp can be passed to the TranslateAccelerator Windows function, which will handle it as though it were a normal key message instead of a system-key message. This allows accelerator (shortcut) keys to be used with the active window even if the active window does not have the input focus.

For IBM Enhanced 101- and 102-key keyboards, enhanced keys are the right ALT and the right CTRL keys on the main section of the keyboard; the INS, DEL, HOME, END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to the left of the numeric keypad; and the slash (/) and ENTER keys in the numeric keypad. Some other keyboards may support the extended-key bit in nFlags.

For non-U.S. Enhanced 102-key keyboards, the right ALT key is handled as the CTRL+ALT key combination. The following shows the sequence of messages and calls that result when the user presses and releases this key:

Sequence | Function Accessed | Message Passed
1. | WM_KEYDOWN | VK_CONTROL
2. | WM_KEYDOWN | VK_MENU
3. | WM_KEYUP | VK_CONTROL
4. | WM_SYSKEYUP | VK_MENU

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::TranslateAccelerator, WM_SYSKEYDOWN, WM_SYSKEYUP


CWnd::OnTCard

afx_msg void OnTCard( UINT idAction, DWORD dwActionData );

Parameters

idAction

Indicates the action the user has taken. This parameter 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 dwActionData 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.

Remarks

The framework calls this member function when the user clicks an authorable button. This function is called only when an application has initiated a training card with Windows Help. An application initiates a training card by specifying the HELP_TCARD command in a call to the WinHelp function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::WinHelp, CWinApp::WinHelp


CWnd::OnTimeChange

afx_msg void OnTimeChange( );

Remarks

The framework calls this member function after the system time is changed.

Have any application that changes the system time send this message to all top-level windows. To send the WM_TIMECHANGE message to all top-level windows, an application can use the SendMessage Windows function with its hwnd parameter set to HWND_BROADCAST.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SendMessage, WM_TIMECHANGE


CWnd::OnTimer

afx_msg void OnTimer( UINT nIDEvent );

Parameters

nIDEvent

Specifies the identifier of the timer.

Remarks

The framework calls this member function after each interval specified in the SetTimer member function used to install a timer.

The DispatchMessage Windows function sends a WM_TIMER message when no other messages are in the application’s message queue.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetTimer, WM_TIMER


CWnd::OnToolHitTest

virtual int CWnd::OnToolHitTest( CPoint point, TOOLINFO* pTI ) const;

Return Value

If 1, the tooltip control was found; If -1, the tooltip control was not found.

Parameters

point

Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window

pTI

A pointer to a TOOLINFO structure. The following structure values are set by default:

  • hwnd = m_hWnd Handle to a window

  • uId = (UINT)hWndChild Handle to a child window

  • uFlags |= TTF_IDISHWND Handle of the tool

  • lpszText = LPSTR_TEXTCALLBACK Pointer to the string that is to be displayed in the specified window

Remarks

The framework calls this member function to detemine whether a point is in the bounding rectangle of the specified tool. If the point is in the rectangle, it retrieves information about the tool.

If the area with which the tooltip is associated is not a button, OnToolHitTest sets the structure flags to TTF_NOTBUTTON and TTF_CENTERTIP.

Override OnToolHitTest to provide different information than the default provides.

See TOOLINFO, in the Win32 SDK Programmer’s Reference, for more information about the structure.

CWnd Overview | Class Members | Hierarchy Chart

See Also TOOLINFO, CWnd::FilterTooltipMessage


CWnd::OnVKeyToItem

protafx_msg int OnVKeyToItem( UINT nKey, CListBox* pListBox, UINT nIndex );

Return Value

Specifies the action that the application performed in response to the message. A return value of –2 indicates that the application handled all aspects of selecting the item and requires no further action by the list box. A return value of –1 indicates that the list box should perform the default action in response to the keystroke. A return value of 0 or greater specifies the zero-based index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

Parameters

nKey

Specifies the virtual-key code of the key that the user pressed.

pListBox

Specifies a pointer to the list box. The pointer may be temporary and should not be stored for later use.

nIndex

Specifies the current caret position.

Remarks

If the CWnd object owns a list box with the LBS_WANTKEYBOARDINPUT style, the list box will send the WM_VKEYTOITEM message in response to a WM_KEYDOWN message.

This member function is called by the framework only for list boxes that have the LBS_HASSTRINGS style.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_KEYDOWN, WM_VKEYTOITEM


CWnd::OnVScroll

afx_msg void OnVScroll( UINT nSBCode, UINT nPos, CScrollBar* pScrollBar );

Parameters

nSBCode

Specifies a scroll-bar code that indicates the user’s scrolling request. This parameter can be one of the following:

  • SB_BOTTOM Scroll to bottom.

  • SB_ENDSCROLL End scroll.

  • SB_LINEDOWN Scroll one line down.

  • SB_LINEUP Scroll one line up.

  • SB_PAGEDOWN Scroll one page down.

  • SB_PAGEUP Scroll one page up.

  • SB_THUMBPOSITION Scroll to the absolute position. The current position is provided in nPos.

  • SB_THUMBTRACK Drag scroll box to specified position. The current position is provided in nPos.

  • SB_TOP Scroll to top.

nPos

Contains the current scroll-box position if the scroll-bar code is SB_THUMBPOSITION or SB_THUMBTRACK; otherwise not used. Depending on the initial scroll range, nPos may be negative and should be cast to an int if necessary.

pScrollBar

If the scroll message came from a scroll-bar control, contains a pointer to the control. If the user clicked a window’s scroll bar, this parameter is NULL. The pointer may be temporary and should not be stored for later use.

Remarks

The framework calls this member function when the user clicks the window’s vertical scroll bar.

OnVScroll typically is used by applications that give some feedback while the scroll box is being dragged.

If OnVScroll scrolls the contents of the CWnd object, it must also reset the position of the scroll box with the SetScrollPos member function.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetScrollPos, CWnd::OnHScroll, WM_VSCROLL


CWnd::OnVScrollClipboard

afx_msg void OnVScrollClipboard( CWnd* pClipAppWnd, UINT nSBCode, UINT nPos );

Parameters

pClipAppWnd

Specifies a pointer to a Clipboard-viewer window. The pointer may be temporary and should not be stored for later use.

nSBCode

Specifies one of the following scroll-bar values:

  • SB_BOTTOM Scroll to bottom.

  • SB_ENDSCROLL End scroll.

  • SB_LINEDOWN Scroll one line down.

  • SB_LINEUP Scroll one line up.

  • SB_PAGEDOWN Scroll one page down.

  • SB_PAGEUP Scroll one page up.

  • SB_THUMBPOSITION Scroll to the absolute position. The current position is provided in nPos.

  • SB_TOP Scroll to top.

nPos

Contains the scroll-box position if the scroll-bar code is SB_THUMBPOSITION; otherwise nPos is not used.

Remarks

The Clipboard owner’s OnVScrollClipboard member function is called by the Clipboard viewer when the Clipboard data has the CF_OWNERDISPLAY format and there is an event in the Clipboard viewer’s vertical scroll bar. The owner should scroll the Clipboard image, invalidate the appropriate section, and update the scroll-bar values.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Invalidate, CWnd::OnHScrollClipboard, CWnd::InvalidateRect, WM_VSCROLLCLIPBOARD, CWnd::Default


CWnd::OnWindowPosChanged

afx_msg void OnWindowPosChanged( WINDOWPOS* lpwndpos );

Parameters

lpwndpos

Points to a WINDOWPOS data structure that contains information about the window’s new size and position.

Remarks

The framework calls this member function when the size, position, or Z-order has changed as a result of a call to the SetWindowPos member function or another window-management function.

The default implementation sends the WM_SIZE and WM_MOVE messages to the window. These messages are not sent if an application handles the OnWindowPosChanged call without calling its base class. It is more efficient to perform any move or size change processing during the call to OnWindowPosChanged without calling its base class.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_WINDOWPOSCHANGED


CWnd::OnWindowPosChanging

afx_msg void OnWindowPosChanging( WINDOWPOS* lpwndpos );

Parameters

lpwndpos

Points to a WINDOWPOS data structure that contains information about the window’s new size and position.

Remarks

The framework calls this member function when the size, position, or Z-order is about to change as a result of a call to the SetWindowPos member function or another window-management function.

An application can prevent changes to the window by setting or clearing the appropriate bits in the flags member of the WINDOWPOS structure.

For a window with the WS_OVERLAPPED or WS_THICKFRAME style, the default implementation sends a WM_GETMINMAXINFO message to the window. This is done to validate the new size and position of the window and to enforce the CS_BYTEALIGNCLIENT and CS_BYTEALIGN client styles. An application can override this functionality by not calling its base class.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnWindowPosChanged, WM_WINDOWPOSCHANGING


CWnd::OnWinIniChange

afx_msg void OnWinIniChange( LPCTSTR lpszSection );

Parameters

lpszSection

Points to a string that specifies the name of the section that has changed. (The string does not include the square brackets that enclose the section name.)

Remarks

The framework calls this member function after a change has been made to the Windows initialization file, WIN.INI.

The SystemParametersInfo Windows function calls OnWinIniChange after an application uses the function to change a setting in the WIN.INI file.

To send the WM_WININICHANGE message to all top-level windows, an application can use the SendMessage Windows function with its hwnd parameter set to HWND_BROADCAST.

If an application changes many different sections in WIN.INI at the same time, the application should send one WM_WININICHANGE message with lpszSection set to NULL. Otherwise, an application should send WM_WININICHANGE each time it makes a change to WIN.INI.

If an application receives an OnWinIniChange call with lpszSection set to NULL, the application should check all sections in WIN.INI that affect the application.

Note This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SendMessage, ::SystemParametersInfo, WM_WININICHANGE


CWnd::OnWndMsg

virtual BOOL OnWndMsg( UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult );

Return Value

Nonzero if message was handled; otherwise 0.

Parameters

message

Specifies the message to be sent.

wParam

Specifies additional message-dependent information.

lParam

Specifies additional message-dependent information.

pResult

The return value of WindowProc. Depends on the message; may be NULL.

Remarks

This member function is called by WindowProc, or is called during message reflection.

For more information about message reflection, see Handling Reflected Messages in the Visual C++ Programmer’s Guide.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnChildNotify, CWnd::SendChildNotifyLastMsg, CWnd::ReflectChildNotify, CCmdTarget::OnCmdMsg, CWnd::ReflectLastMsg


CWnd::OpenClipboard

BOOL OpenClipboard( );

Return Value

Nonzero if the Clipboard is opened via CWnd, or 0 if another application or window has the Clipboard open.

Remarks

Opens the Clipboard. Other applications will not be able to modify the Clipboard until the CloseClipboard Windows function is called.

The current CWnd object will not become the owner of the Clipboard until the EmptyClipboard Windows function is called.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::CloseClipboard, ::EmptyClipboard, ::OpenClipboard


CWnd::PostMessage

BOOL PostMessage( UINT message, WPARAM wParam = 0, LPARAM lParam = 0 );

Return Value

Nonzero if the message is posted; otherwise 0.

Parameters

message

Specifies the message to be posted.

wParam

Specifies additional message information. The content of this parameter depends on the message being posted.

lParam

Specifies additional message information. The content of this parameter depends on the message being posted.

Remarks

Places a message in the window’s message queue and then returns without waiting for the corresponding window to process the message. Messages in a message queue are retrieved by calls to the GetMessage or PeekMessage Windows function.

The Windows PostMessage function can be used to access another application.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::GetMessage, ::PeekMessage, ::PostMessage, ::PostAppMessage, CWnd::SendMessage


CWnd::PostNcDestroy

virtual void PostNcDestroy( );

Remarks

Called by the default OnNcDestroy member function after the window has been destroyed. Derived classes can use this function for custom cleanup such as the deletion of the this pointer.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnNcDestroy


CWnd::PreCreateWindow

virtual BOOL PreCreateWindow( CREATESTRUCT& cs );

Return Value

Nonzero if the window creation should continue; 0 to indicate creation failure.

Parameters

cs

A CREATESTRUCT structure.

Remarks

Called by the framework before the creation of the Windows window attached to this CWnd object.

Never call this function directly.

The default implementation of this function checks for a NULL window class name and substitutes an appropriate default. Override this member function to modify the CREATESTRUCT structure before the window is created.

Each class derived from CWnd adds its own functionality to its override of PreCreateWindow. By design, these derivations of PreCreateWindow are not documented. To determine the styles appropriate to each class and the interdependencies between the styles, you can examine the MFC source code for your application’s base class. If you choose to override PreCreateWindow, you can determine whether the styles used in your application’s base class provide the functionality you need by using information gathered from the MFC source code.

For more information on changing window styles, see the Changing the Styles of a Window Created by MFC in Visual C++ Programmer’s Guide.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Create, CWnd::CreateEx, CREATESTRUCT


CWnd::PreSubclassWindow

virtual void PreSubclassWindow( );

Remarks

This member function is called by the framework to allow other necessary subclassing to occur before the window is subclassed. Overriding this member function allows for dynamic subclassing of controls. It is an advanced overridable.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SubclassWindow, CWnd::UnsubclassWindow, CWnd::GetSuperWndProcAddr, CWnd::DefWindowProc, CWnd::SubclassDlgItem, CWnd::Attach, CWnd::PreCreateWindow


CWnd::PreTranslateMessage

virtual BOOL PreTranslateMessage( MSG* pMsg );

Return Value

Nonzero if the message was translated and should not be dispatched; 0 if the message was not translated and should be dispatched.

Parameters

pMsg

Points to a MSG structure that contains the message to process.

Remarks

Used by class CWinApp to translate window messages before they are dispatched to the TranslateMessage and DispatchMessage Windows functions.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::TranslateMessage, ::IsDialogMessage, CWinApp::PreTranslateMessage


CWnd::Print

void Print( CDC* pDC, DWORD dwFlags ) const;

Parameters

pDC

A pointer to a device context.

dwFlags

Specifies the drawing options. This parameter can be one or more of these flags:

  • PRF_CHECKVISIBLE Draw the window only if it is visible.

  • PRF_CHILDREN Draw all visible children windows.

  • PRF_CLIENT Draw the client area of the window.

  • PRF_ERASEBKGND Erase the background before drawing the window.

  • PRF_NONCLIENT Draw the nonclient area of the window.

  • PRF_OWNED Draw all owned windows.

Remarks

Call this member function to draw the current window in the specified device context, which is most commonly in a printer device context.

CWnd::DefWindowProc function processes this message based on which drawing option is specified:

  • If PRF_CHECKVISIBLE is specified and the window is not visible, do nothing.

  • If PRF_NONCLIENT is specified, draw the nonclient area in the given device context.

  • If PRF_ERASEBKGND is specified, send the window a WM_ERASEBKGND message.

  • If PRF_PRINTCLIENT is specified, send the window a WM_PRINTCLIENT message.

  • If PRF_PRINTCHILDREN is set, send each visible child window a WM_PRINT message.

  • If PRF_OWNED is set, send each visible owned window a WM_PRINT message.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_PRINT, WM_PRINTCLIENT


CWnd::PrintClient

void PrintClient( CDC* pDC, DWORD dwFlags ) const;

Parameters

pDC

A pointer to a device context.

dwFlags

Specifies drawing options. This parameter can be one or more of these flags:

  • PRF_CHECKVISIBLE Draw the window only if it is visible.

  • PRF_CHILDREN Draw all visible children windows.

  • PRF_CLIENT Draw the client area of the window.

  • PRF_ERASEBKGND Erase the background before drawing the window.

  • PRF_NONCLIENT Draw the nonclient area of the window.

  • PRF_OWNED Draw all owned windows.

Remarks

Call this member function to draw any window in the specified device context (usually a printer device context).

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_PRINTCLIENT


CWnd::RedrawWindow

BOOL RedrawWindow( LPCRECT lpRectUpdate = NULL, CRgn* prgnUpdate = NULL, UINT flags = RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE );

Return Value

Nonzero if the window was redrawn successfully; otherwise 0.

Parameters

lpRectUpdate

Points to a RECT structure containing the coordinates of the update rectangle. This parameter is ignored if prgnUpdate contains a valid region handle.

prgnUpdate

Identifies the update region. If both prgnUpdate and lpRectUpdate are NULL, the entire client area is added to the update region.

flags

The following flags are used to invalidate the window:

  • RDW_ERASE Causes the window to receive a WM_ERASEBKGND message when the window is repainted. The RDW_INVALIDATE flag must also be specified; otherwise RDW_ERASE has no effect.

  • RDW_FRAME Causes any part of the nonclient area of the window that intersects the update region to receive a WM_NCPAINT message. The RDW_INVALIDATE flag must also be specified; otherwise RDW_FRAME has no effect.

  • RDW_INTERNALPAINT Causes a WM_PAINT message to be posted to the window regardless of whether the window contains an invalid region.

  • RDW_INVALIDATE Invalidate lpRectUpdate or prgnUpdate (only one may be not NULL). If both are NULL, the entire window is invalidated.

    The following flags are used to validate the window:

  • RDW_NOERASE Suppresses any pending WM_ERASEBKGND messages.

  • RDW_NOFRAME Suppresses any pending WM_NCPAINT messages. This flag must be used with RDW_VALIDATE and is typically used with RDW_NOCHILDREN. This option should be used with care, as it could prevent parts of a window from painting properly.

  • RDW_NOINTERNALPAINT Suppresses any pending internal WM_PAINT messages. This flag does not affect WM_PAINT messages resulting from invalid areas.

  • RDW_VALIDATE Validates lpRectUpdate or prgnUpdate (only one may be not NULL). If both are NULL, the entire window is validated. This flag does not affect internal WM_PAINT messages.

    The following flags control when repainting occurs. Painting is not performed by the RedrawWindow function unless one of these bits is specified.

  • RDW_ERASENOW Causes the affected windows (as specified by the RDW_ALLCHILDREN and RDW_NOCHILDREN flags) to receive WM_NCPAINT and WM_ERASEBKGND messages, if necessary, before the function returns. WM_PAINT messages are deferred.

  • RDW_UPDATENOW Causes the affected windows (as specified by the RDW_ALLCHILDREN and RDW_NOCHILDREN flags) to receive WM_NCPAINT, WM_ERASEBKGND, and WM_PAINT messages, if necessary, before the function returns.

    By default, the windows affected by the RedrawWindow function depend on whether the specified window has the WS_CLIPCHILDREN style. The child windows of WS_CLIPCHILDREN windows are not affected. However, those windows that are not WS_CLIPCHILDREN windows are recursively validated or invalidated until a WS_CLIPCHILDREN window is encountered. The following flags control which windows are affected by the RedrawWindow function:

  • RDW_ALLCHILDREN Includes child windows, if any, in the repainting operation.

  • RDW_NOCHILDREN Excludes child windows, if any, from the repainting operation.

Remarks

Updates the specified rectangle or region in the given window’s client area.

When the RedrawWindow member function is used to invalidate part of the desktop window, that window does not receive a WM_PAINT message. To repaint the desktop, an application should use CWnd::ValidateRgn, CWnd::InvalidateRgn, CWnd::UpdateWindow, or ::RedrawWindow


CWnd::ReflectChildNotify

BOOL ReflectChildNotify( UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult );

Return Value

TRUE if message was reflected; otherwise FALSE.

Parameters

message

Specifies the message to be reflected.

wParam

Specifies additional message-dependent information.

lParam

Specifies additional message-dependent information.

pResult

The result generated by the child window to be returned by the parent window. Can be NULL.

Remarks

This message function is called by the framework from OnChildNotify. It is a helper function which reflects message to its source.

Reflected messages are sent directly to CWnd::OnWndMsg or CCmdTarget::OnCmdMsg.

For more information about message reflection, see Handling Reflected Messages in the Visual C++ Programmer’s Guide.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnChildNotify, CWnd::SendChildNotifyLastMsg, CWnd::OnWndMsg, CCmdTarget::OnCmdMsg, CWnd::ReflectLastMsg


CWnd::ReflectLastMsg

static BOOL PASCAL ReflectLastMsg( HWND hWndChild, LRESULT* pResult = NULL );

Return Value

Nonzero if the message was handled; otherwise 0.

Parameters

hWndChild

A handle to a child window.

pResult

The result generated by the child window to be returned by the parent window. Can be NULL.

Remarks

This member function is called by the framework to reflect the last message to the child window.

This member function calls SendChildNotifyLastMsg if the window identified by hWndChild is an OLE control or a window in the permanent map.

For more information about message reflection, see Handling Reflected Messages in the Visual C++ Programmer’s Guide.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnChildNotify, CWnd::SendChildNotifyLastMsg, CWnd::ReflectChildNotify, CCmdTarget::OnCmdMsg


CWnd::ReleaseDC

int ReleaseDC( CDC* pDC );

Return Value

Nonzero if successful; otherwise 0.

Parameters

pDC

Identifies the device context to be released.

Remarks

Releases a device context, freeing it for use by other applications. The effect of the ReleaseDC member function depends on the device-context type.

The application must call the ReleaseDC member function for each call to the GetWindowDC member function and for each call to the GetDC member function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDC, CWnd::GetWindowDC, ::ReleaseDC


CWnd::RepositionBars

void RepositionBars( UINT nIDFirst, UINT nIDLast, UINT nIDLeftOver, UINT nFlag = CWnd::reposDefault, LPRECT lpRectParam = NULL, LPCRECT lpRectClient = NULL, BOOL bStretch = TRUE );

Parameters

nIDFirst

The ID of the first in a range of control bars to reposition and resize.

nIDLast

The ID of the last in a range of control bars to reposition and resize.

nIDLeftOver

Specifies ID of pane that fills the rest of the client area.

nFlag

Can have one of the following values:

  • CWnd::reposDefault Performs the layout of the control bars. lpRectParam is not used and can be NULL.

  • CWnd::reposQuery The layout of the control bars is not done; instead lpRectParam is initialized with the size of the client area, as if the layout had actually been done.

  • CWnd::reposExtra Adds the values of lpRectParam to the client area of nIDLast and also performs the layout.

lpRectParam

Points to a RECT structure; the usage of which depends on the value of nFlag.

lpRectClient

Points to a RECT structure containing the available client area. If NULL, the window’s client area will be used.

bStretch

Indicates whether the bar should be stretched to the size of the frame.

Remarks

Called to reposition and resize control bars in the client area of a window. The nIDFirst and nIDLast parameters define a range of control-bar IDs to be repositioned in the client area. The nIDLeftOver parameter specifies the ID of the child window (normally the view) which is repositioned and resized to fill the rest of the client area not filled by control bars.

CWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::RecalcLayout


CWnd::RunModalLoop

int RunModalLoop( DWORD dwFlags );

Return Value

Specifies the value of the nResult parameter passed to the EndModalLoop member function, which is then used to end the modal loop.

Parameters

dwFlags

Specifies the Windows message to be sent. Can be one of the following values:

  • MLF_NOIDLEMSG Don’t send WM_ENTERIDLE messages to the parent.

  • MLF_NOKICKIDLE Don’t send WM_KICKIDLE messages to the window.

  • MLF_SHOWONIDLE Show the window when message queue goes idle.

Remarks

Call this member function to retrieve, translate, or dispatch messages until ContinueModal returns FALSE. By default, ContinueModal returns FALSE after EndModalLoop is called. Returns the value provided as nResult to EndModalLoop.

CWnd Overview | Class Members | Hierarchy Chart

See Also EndModalLoop, WM_ENTERIDLE


CWnd::ScreenToClient

void ScreenToClient( LPPOINT lpPoint ) const;

void ScreenToClient( LPRECT lpRect ) const;

Parameters

lpPoint

Points to a CPoint object or POINT structure that contains the screen coordinates to be converted.

lpRect

Points to a CRect object or RECT structure that contains the screen coordinates to be converted.

Remarks

Converts the screen coordinates of a given point or rectangle on the display to client coordinates.

The ScreenToClient member function replaces the screen coordinates given in lpPoint or lpRect with client coordinates. The new coordinates are relative to the upper-left corner of the CWnd client area.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ClientToScreen, ::ScreenToClient


CWnd::ScrollWindow

void ScrollWindow( int xAmount, int yAmount, LPCRECT lpRect = NULL, LPCRECT lpClipRect = NULL );

Parameters

xAmount

Specifies the amount, in device units, of horizontal scrolling. This parameter must be a negative value to scroll to the left.

yAmount

Specifies the amount, in device units, of vertical scrolling. This parameter must be a negative value to scroll up.

lpRect

Points to a CRect object or RECT structure that specifies the portion of the client area to be scrolled. If lpRect is NULL, the entire client area is scrolled. The caret is repositioned if the cursor rectangle intersects the scroll rectangle.

lpClipRect

Points to a CRect object or RECT structure that specifies the clipping rectangle to scroll. Only bits inside this rectangle are scrolled. Bits outside this rectangle are not affected even if they are in the lpRect rectangle. If lpClipRect is NULL, no clipping is performed on the scroll rectangle.

Remarks

Scrolls the contents of the client area of the current CWnd object.

If the caret is in the CWnd being scrolled, ScrollWindow automatically hides the caret to prevent it from being erased and then restores the caret after the scroll is finished. The caret position is adjusted accordingly.

The area uncovered by the ScrollWindow member function is not repainted but is combined into the current CWnd object’s update region. The application will eventually receive a WM_PAINT message notifying it that the region needs repainting. To repaint the uncovered area at the same time the scrolling is done, call the UpdateWindow member function immediately after calling ScrollWindow.

If lpRect is NULL, the positions of any child windows in the window are offset by the amount specified by xAmount and yAmount, and any invalid (unpainted) areas in the CWnd are also offset. ScrollWindow is faster when lpRect is NULL.

If lpRect is not NULL, the positions of child windows are not changed, and invalid areas in CWnd are not offset. To prevent updating problems when lpRect is not NULL, call the UpdateWindow member function to repaint CWnd before calling ScrollWindow.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::UpdateWindow, ::ScrollWindow


CWnd::ScrollWindowEx

int ScrollWindowEx( int dx, int dy, LPCRECT lpRectScroll, LPCRECT lpRectClip, CRgn* prgnUpdate, LPRECT lpRectUpdate, UINT flags );

Return Value

The return value is SIMPLEREGION (rectangular invalidated region), COMPLEXREGION (nonrectangular invalidated region; overlapping rectangles), or NULLREGION (no invalidated region), if the function is successful; otherwise the return value is ERROR.

Parameters

dx

Specifies the amount, in device units, of horizontal scrolling. This parameter must have a negative value to scroll to the left.

dy

Specifies the amount, in device units, of vertical scrolling. This parameter must have a negative value to scroll up.

lpRectScroll

Points to a RECT structure that specifies the portion of the client area to be scrolled. If this parameter is NULL, the entire client area is scrolled.

lpRectClip

Points to a RECT structure that specifies the clipping rectangle to scroll. This structure takes precedence over the rectangle pointed to by lpRectScroll. Only bits inside this rectangle are scrolled. Bits outside this rectangle are not affected even if they are in the lpRectScroll rectangle. If this parameter is NULL, no clipping is performed on the scroll rectangle.

prgnUpdate

Identifies the region that is modified to hold the region invalidated by scrolling. This parameter may be NULL.

lpRectUpdate

Points to a RECT structure that will receive the boundaries of the rectangle invalidated by scrolling. This parameter may be NULL.

flags

Can have one of the following values:

  • SW_ERASE When specified with SW_INVALIDATE, erases the newly invalidated region by sending a WM_ERASEBKGND message to the window.

  • SW_INVALIDATE Invalidates the region identified by prgnUpdate after scrolling.

  • SW_SCROLLCHILDREN Scrolls all child windows that intersect the rectangle pointed to by lpRectScroll by the number of pixels specified in dx and dy. Windows sends a WM_MOVE message to all child windows that intersect lpRectScroll, even if they do not move. The caret is repositioned when a child window is scrolled and the cursor rectangle intersects the scroll rectangle.

Remarks

Scrolls the contents of a window’s client area. This function is similar to the ScrollWindow function, with some additional features.

If SW_INVALIDATE and SW_ERASE are not specified, the ScrollWindowEx member function does not invalidate the area that is scrolled away from. If either of these flags is set, ScrollWindowEx invalidates this area. The area is not updated until the application calls the UpdateWindow member function, calls the RedrawWindow member function (specifying RDW_UPDATENOW or RDW_ERASENOW), or retrieves the WM_PAINT message from the application queue.

If the window has the WS_CLIPCHILDREN style, the returned areas specified by prgnUpdate and lpRectUpdate represent the total area of the scrolled window that must be updated, including any areas in child windows that need updating.

If the SW_SCROLLCHILDREN flag is specified, Windows will not properly update the screen if part of a child window is scrolled. The part of the scrolled child window that lies outside the source rectangle will not be erased and will not be redrawn properly in its new destination. Use the DeferWindowPos Windows function to move child windows that do not lie completely within the lpRectScroll rectangle. The cursor is repositioned if the SW_SCROLLCHILDREN flag is set and the caret rectangle intersects the scroll rectangle.

All input and output coordinates (for lpRectScroll, lpRectClip, lpRectUpdate, and prgnUpdate) are assumed to be in client coordinates, regardless of whether the window has the CS_OWNDC or CS_CLASSDC class style. Use the LPtoDP and DPtoLP Windows functions to convert to and from logical coordinates, if necessary.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::RedrawWindow, CDC::ScrollDC, CWnd::ScrollWindow, CWnd::UpdateWindow, ::DeferWindowPos, ::ScrollWindowEx


CWnd::SendChildNotifyLastMsg

BOOL SendChildNotifyLastMsg( LRESULT* pResult = NULL );

Return Value

Nonzero if the child window has handled the message sent to its parent; otherwise 0.

Parameters

pResult

The result generated by the child window to be returned by the parent window.

Remarks

This member function is called by the framework to provide a notification message to a child window, from the parent window, so the child window can handle a task.

SendChildNotifyLastMsg send the current message to the source if it is a message that is reflected.

For more information about message reflection, see Handling Reflected Messages in the Visual C++ Programmer's Guide.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::OnChildNotify


CWnd::SendDlgItemMessage

LRESULT SendDlgItemMessage( int nID, UINT message, WPARAM wParam = 0, LPARAM lParam = 0 );

Return Value

Specifies the value returned by the control’s window procedure, or 0 if the control was not found.

Parameters

nID

Specifies the identifier of the dialog control that will receive the message.

message

Specifies the message to be sent.

wParam

Specifies additional message-dependent information.

lParam

Specifies additional message-dependent information.

Remarks

Sends a message to a control.

The SendDlgItemMessage member function does not return until the message has been processed.

Using SendDlgItemMessage is identical to obtaining a CWnd* to the given control and calling the SendMessage member function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SendMessage, ::SendDlgItemMessage


CWnd::SendMessage

LRESULT SendMessage( UINT message, WPARAM wParam = 0, LPARAM lParam = 0 );

Return Value

The result of the message processing; its value depends on the message sent.

Parameters

message

Specifies the message to be sent.

wParam

Specifies additional message-dependent information.

lParam

Specifies additional message-dependent information.

Remarks

Sends the specified message to this window. The SendMessage member function calls the window procedure directly and does not return until that window procedure has processed the message. This is in contrast to the PostMessage member function, which places the message into the window’s message queue and returns immediately.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::InSendMessage, CWnd::PostMessage, CWnd::SendDlgItemMessage, ::SendMessage


CWnd::SendMessageToDescendants

void SendMessageToDescendants( UINT message, WPARAM wParam = 0, LPARAM lParam = 0, BOOL bDeep = TRUE, BOOL bOnlyPerm = FALSE );

Parameters

message

Specifies the message to be sent.

wParam

Specifies additional message-dependent information.

lParam

Specifies additional message-dependent information.

bDeep

Specifies the level to which to search. If TRUE, recursively search all children; if FALSE, search only immediate children.

bOnlyPerm

Specifies whether the message will be received by temporary windows. If TRUE, temporary windows can receive the message; if FALSE, only permanent windows receive the message. For more information on temporary windows see Technical Note 3.

Remarks

Call this member function to send the specified Windows message to all descendant windows.

If bDeep is FALSE, the message is sent just to the immediate children of the window; otherwise the message is sent to all descendant windows.

If bDeep and bOnlyPerm are TRUE, the search continues below temporary windows. In this case, only permanent windows encountered during the search receive the message. If bDeep is FALSE, the message is sent only to the immediate children of the window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SendMessage, CWnd::FromHandlePermanent, CWnd::FromHandle


CWnd::SendNotifyMessage

BOOL SendNotifyMessage( UINT message, WPARAM wParam, LPARAM lParam );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

message

Specifies the message to be sent.

wParam

Specifies additional message-dependent information.

lParam

Specifies additional message-dependent information.

Remarks

Sends the specified message to the window. If the window was created by the calling thread, SendNotifyMessage calls the window procedure for the window and does not return until the window procedure has processed the message. If the window was created by a different thread, SendNotifyMessage passes the message to the window procedure and returns immediately; it does not wait for the window procedure to finish processing the message.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SendMessage, ::SendNotifyMessage


CWnd::SetActiveWindow

CWnd* SetActiveWindow( );

Return Value

The window that was previously active.

The returned pointer may be temporary and should not be stored for later use.

Remarks

Makes CWnd the active window.

The SetActiveWindow member function should be used with care since it allows an application to arbitrarily take over the active window and input focus. Normally, Windows takes care of all activation.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SetActiveWindow, CWnd::GetActiveWindow


CWnd::SetCapture

CWnd* SetCapture( );

Return Value

A pointer to the window object that previously received all mouse input. It is NULL if there is no such window. The returned pointer may be temporary and should not be stored for later use.

Remarks

Causes all subsequent mouse input to be sent to the current CWnd object regardless of the position of the cursor.

When CWnd no longer requires all mouse input, the application should call the ReleaseCapture function so that other windows can receive mouse input.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::ReleaseCapture, ::SetCapture, CWnd::GetCapture


CWnd::SetCaretPos

static void PASCAL SetCaretPos( POINT point );

Parameters

point

Specifies the new x and y coordinates (in client coordinates) of the caret.

Remarks

Sets the position of the caret.

The SetCaretPos member function moves the caret only if it is owned by a window in the current task. SetCaretPos moves the caret whether or not the caret is hidden.

The caret is a shared resource. A window should not move the caret if it does not own the caret.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetCaretPos, ::SetCaretPos


CWnd::SetClipboardViewer

HWND SetClipboardViewer( );

Return Value

A handle to the next window in the Clipboard-viewer chain if successful. Applications should save this handle (it can be stored as a member variable) and use it when responding to Clipboard-viewer chain messages.

Remarks

Adds this window to the chain of windows that are notified (by means of the WM_DRAWCLIPBOARD message) whenever the content of the Clipboard is changed.

A window that is part of the Clipboard-viewer chain must respond to WM_DRAWCLIPBOARD, WM_CHANGECBCHAIN, and WM_DESTROY messages and pass the message to the next window in the chain.

This member function sends a WM_DRAWCLIPBOARD message to the window. Since the handle to the next window in the Clipboard-viewer chain has not yet been returned, the application should not pass on the WM_DRAWCLIPBOARD message that it receives during the call to SetClipboardViewer.

To remove itself from the Clipboard-viewer chain, an application must call the ChangeClipboardChain member function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::ChangeClipboardChain, ::SetClipboardViewer


CWnd::SetDlgCtrlID

int SetDlgCtrlID( int nID );

Return Value

The previous identifier of the window, if successful; otherwise 0.

Parameters

nID

The new value to set for the control’s identifier.

Remarks

Sets the window ID or control ID for the window to a new value. The window can be any child window, not only a control in a dialog box. The window cannot be a top-level window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDlgCtrlID, CWnd::Create, CWnd::CreateEx, CWnd::GetDlgItem


CWnd::SetDlgItemInt

void SetDlgItemInt( int nID, UINT nValue, BOOL bSigned = TRUE );

Parameters

nID

Specifies the integer ID of the control to be changed.

nValue

Specifies the integer value used to generate the item text.

bSigned

Specifies whether the integer value is signed or unsigned. If this parameter is TRUE, nValue is signed. If this parameter is TRUE and nValue is less than 0, a minus sign is placed before the first digit in the string. If this parameter is FALSE, nValue is unsigned.

Remarks

Sets the text of a given control in a dialog box to the string representation of a specified integer value.

SetDlgItemInt sends a WM_SETTEXT message to the given control.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetDlgItemInt, ::SetDlgItemInt, WM_SETTEXT


CWnd::SetDlgItemText

void SetDlgItemText( int nID, LPCTSTR lpszString );

Parameters

nID

Identifies the control whose text is to be set.

lpszString

Points to a CString object or null-terminated string that contains the text to be copied to the control.

Remarks

Sets the caption or text of a control owned by a window or dialog box.

SetDlgItemText sends a WM_SETTEXT message to the given control.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SetDlgItemText, WM_SETTEXT, CWnd::GetDlgItemText


CWnd::SetForegroundWindow

BOOL SetForegroundWindow( );

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

Puts the thread that created the window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. The foreground window is the window with which the user is currently working. The foreground window applies only to top-level windows (frame windows or dialogs boxes).

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetForegroundWindow


CWnd::SetFocus

CWnd* SetFocus( );

Return Value

A pointer to the window object that previously had the input focus. It is NULL if there is no such window. The returned pointer may be temporary and should not be stored.

Remarks

Claims the input focus. The input focus directs all subsequent keyboard input to this window. Any window that previously had the input focus loses it.

The SetFocus member function sends a WM_KILLFOCUS message to the window that loses the input focus and a WM_SETFOCUS message to the window that receives the input focus. It also activates either the window or its parent.

If the current window is active but does not have the focus (that is, no window has the focus), any key pressed will produce the messages WM_SYSCHAR, WM_SYSKEYDOWN, or WM_SYSKEYUP.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SetFocus, CWnd::GetFocus


CWnd::SetFont

void SetFont( CFont* pFont, BOOL bRedraw = TRUE );

Parameters

pFont

Specifies the new font.

bRedraw

If TRUE, redraw the CWnd object.

Remarks

Sets the window’s current font to the specified font. If bRedraw is TRUE, the window will also be redrawn.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetFont, WM_SETFONT


CWnd::SetIcon

HICON SetIcon( HICON hIcon, BOOL bBigIcon );

Return Value

A handle to an icon.

Parameters

hIcon

A handle to a previous icon.

bBigIcon

Specifies a 32 pixel by 32 pixel icon if TRUE; specifies a 16 pixel by 16 pixel icon if FALSE.

Remarks

Call this member function to set the handle to a specific icon, as identified by hIcon. When the window class is registered, it selects an icon.

CWnd Overview | Class Members | Hierarchy Chart

See Also GetIcon


CWnd::SetMenu

BOOL SetMenu( CMenu* pMenu );

Return Value

Nonzero if the menu is changed; otherwise 0.

Parameters

pMenu

Identifies the new menu. If this parameter is NULL, the current menu is removed.

Remarks

Sets the current menu to the specified menu. Causes the window to be redrawn to reflect the menu change.

SetMenu will not destroy a previous menu. An application should call the CMenu::DestroyMenu member function to accomplish this task.

CWnd Overview | Class Members | Hierarchy Chart

See Also CMenu::DestroyMenu, CMenu::LoadMenu, ::SetMenu, CWnd::GetMenu


CWnd::SetOwner

void SetOwner( CWnd* pOwnerWnd );

Parameters

pOwnerWnd

Identifies the new owner of the window object. If this parameter is NULL, the window object has no owner.

Remarks

Sets the current window’s owner to the specified window object. This owner can then receive command messages from the current window object. By default, the parent of the current window is its owner.

It is often useful to establish connections between window objects that are unrelated to the window hierarchy. For example, CToolBar sends notifications to its owner instead of to its parent. This allows the toolbar to become the child of one window (such as an OLE container application window) while sending notifications to another window (such as the in-place frame window). Furthermore, when a server window is deactivated or activated during in-place editing, any window owned by the frame window is hidden or shown. This ownership is explicitly set with a call to SetOwner.

The ownership concept of this function is different from the ownership concept of GetWindow.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetOwner, CToolBar


CWnd::SetParent

CWnd* SetParent( CWnd* pWndNewParent );

Return Value

A pointer to the previous parent window object if successful. The returned pointer may be temporary and should not be stored for later use.

Parameters

pWndNewParent

Identifies the new parent window.

Remarks

Changes the parent window of a child window.

If the child window is visible, Windows performs the appropriate redrawing and repainting.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SetParent, CWnd::GetParent


CWnd::SetProperty

void SetProperty( DISPID dwDispID, VARTYPE vtProp, ... );

Parameters

dwDispID

Identifies the property to be set. This value is usually supplied by Component Gallery.

vtProp

Specifies the type of the property to be set. For possible values, see the Remarks section for COleDispatchDriver::InvokeHelper.

...

A single parameter of the type specified by vtProp.

Remarks

Call this member function to set the OLE control property specified by dwDispID.

Note This function should be called only on a CWnd object that represents an OLE control.

For more information about using this member function with OLE Control Containers, see the article ActiveX Control Containers: Programming ActiveX Controls in an ActiveX Control Container in Visual C++ Programmer’s Guide.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::InvokeHelper, COleDispatchDriver, CWnd::CreateControl


CWnd::SetRedraw

void SetRedraw( BOOL bRedraw = TRUE );

Parameters

bRedraw

Specifies the state of the redraw flag. If this parameter is TRUE, the redraw flag is set; if FALSE, the flag is cleared.

Remarks

An application calls SetRedraw to allow changes to be redrawn or to prevent changes from being redrawn.

This member function sets or clears the redraw flag. While the redraw flag is cleared, the contents will not be updated after each change and will not be repainted until the redraw flag is set. For example, an application that needs to add several items to a list box can clear the redraw flag, add the items, and then set the redraw flag. Finally, the application can call the Invalidate or InvalidateRect member function to cause the list box to be repainted.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_SETREDRAW


CWnd::SetScrollInfo

BOOL SetScrollInfo( int nBar, LPSCROLLINFO lpScrollInfo, BOOL bRedraw = TRUE );

Return Value

If successful, the return is TRUE. Otherwise, it is FALSE.

Parameters

nBar

Specifies whether the scroll bar is a control or part of a window’s nonclient area. If it is part of the nonclient area, nBar also indicates whether the scroll bar is positioned horizontally, vertically, or both. It must be one of the following:

  • SB_CTL Contains the parameters for a scroll bar control. The m_hWnd data member must be the handle of the scroll bar control.

  • SB_HORZ Specifies that the window is a horizontal scroll bar.

  • SB_VERT Specifies that the window is a vertical scroll bar.

lpScrollInfo

A pointer to a SCROLLINFO structure. See the Win32 SDK Programmer’s Reference for more information about this structure.

bRedraw

Specifies whether the scroll bar should be redrawn to reflect the new position. If bRedraw is TRUE, the scroll bar is redrawn. If it is FALSE, it is not redrawn. The scroll bar is redrawn by default.

Remarks

Call this member function to set the information that the SCROLLINFO structure maintains about a scroll bar.

The SCROLLINFO structure contains information about a scroll bar, including the minimum and maximum scrolling positions, the page size, and the position of the scroll box (the thumb). See the SCROLLINFO structure topic in the Win32 SDK Programmer’s Reference for more information about changing the structure defaults.

The MFC Windows message handlers that indicate scroll-bar position, CWnd::OnHScroll and CWnd::OnVScroll, provide only 16 bits of position data. GetScrollInfo and SetScrollInfo provide 32 bits of scroll-bar position data. Thus, an application can call GetScrollInfo while processing either CWnd::OnHScroll or CWnd::OnVScroll to obtain 32-bit scroll-bar position data.

Note CWnd::GetScrollInfo enables applications to use 32-bit scroll-bar positions.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetScrollInfo, CWnd::SetScrollPos, CWnd::OnVScroll, CWnd::OnHScroll, SCROLLINFO


CWnd::SetScrollPos

int SetScrollPos( int nBar, int nPos, BOOL bRedraw = TRUE );

Return Value

The previous position of the scroll box.

Parameters

nBar

Specifies the scroll bar to be set. This parameter can be either of the following:

  • SB_HORZ Sets the position of the scroll box in the horizontal scroll bar of the window.

  • SB_VERT Sets the position of the scroll box in the vertical scroll bar of the window.

nPos

Specifies the new position of the scroll box. It must be within the scrolling range.

bRedraw

Specifies whether the scroll bar should be repainted to reflect the new scroll-box position. If this parameter is TRUE, the scroll bar is repainted; if FALSE, the scroll bar is not repainted.

Remarks

Sets the current position of a scroll box and, if requested, redraws the scroll bar to reflect the new position of the scroll box.

Setting bRedraw to FALSE is useful whenever the scroll bar will be redrawn by a subsequent call to another function.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SetScrollPos, CWnd::GetScrollPos, CScrollBar::SetScrollPos


CWnd::SetScrollRange

void SetScrollRange( int nBar, int nMinPos, int nMaxPos, BOOL bRedraw = TRUE );

Parameters

nBar

Specifies the scroll bar to be set. This parameter can be either of the following values:

  • SB_HORZ Sets the range of the horizontal scroll bar of the window.

  • SB_VERT Sets the range of the vertical scroll bar of the window.

nMinPos

Specifies the minimum scrolling position.

nMaxPos

Specifies the maximum scrolling position.

bRedraw

Specifies whether the scroll bar should be redrawn to reflect the change. If bRedraw is TRUE, the scroll bar is redrawn; if FALSE, the scroll bar is not redrawn.

Remarks

Sets minimum and maximum position values for the given scroll bar. It can also be used to hide or show standard scroll bars.

An application should not call this function to hide a scroll bar while processing a scroll-bar notification message.

If the call to SetScrollRange immediately follows a call to the SetScrollPos member function, the bRedraw parameter in the SetScrollPos member function should be 0 to prevent the scroll bar from being drawn twice.

The default range for a standard scroll bar is 0 through 100. The default range for a scroll bar control is empty (both the nMinPos and nMaxPos values are 0). The difference between the values specified by nMinPos and nMaxPos must not be greater than INT_MAX.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SetScrollPos, ::SetScrollRange, CWnd::GetScrollRange


CWnd::SetTimer

UINT SetTimer( UINT nIDEvent, UINT nElapse, void (CALLBACK EXPORT* lpfnTimer)(HWND, UINT, UINT, DWORD) );

Return Value

The timer identifier of the new timer if the function is successful. An application passes this value to the KillTimer member function to kill the timer. Nonzero if successful; otherwise 0.

Parameters

nIDEvent

Specifies a nonzero timer identifier.

nElapse

Specifies the time-out value, in milliseconds.

lpfnTimer

Specifies the address of the application-supplied TimerProc callback function that processes the WM_TIMER messages. If this parameter is NULL, the WM_TIMER messages are placed in the application’s message queue and handled by the CWnd object.

Remarks

Installs a system timer. A time-out value is specified, and every time a time-out occurs, the system posts a WM_TIMER message to the installing application’s message queue or passes the message to an application-defined TimerProc callback function.

The lpfnTimer callback function need not be named TimerProc, but it must be defined as follows:

void CALLBACK EXPORT TimerProc(
   HWND hWnd,      // handle of CWnd that called SetTimer
   UINT nMsg,      // WM_TIMER
   UINT nIDEvent   // timer identification
   DWORD dwTime    // system time
);

Timers are a limited global resource; therefore it is important that an application check the value returned by the SetTimer member function to verify that a timer is actually available.

CWnd Overview | Class Members | Hierarchy Chart

See Also WM_TIMER, CWnd::KillTimer, ::SetTimer


CWnd::SetWindowContextHelpId

BOOL SetWindowContextHelpId( DWORD dwContextHelpId );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

dwContextHelpId

The help context identifier.

Remarks

Call this member function to associate a help context identifier with the specified window.

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.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetWindowContextHelpId


CWnd::SetWindowPlacement

BOOL SetWindowPlacement( const WINDOWPLACEMENT*lpwndpl );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpwndpl

Points to a WINDOWPLACEMENT structure that specifies the new show state and positions.

Remarks

Sets the show state and the normal (restored), minimized, and maximized positions for a window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetWindowPlacement, ::SetWindowPlacement


CWnd::SetWindowPos

BOOL SetWindowPos( const CWnd* pWndInsertAfter, int x, int y, int cx, int cy, UINT nFlags );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

pWndInsertAfter

Identifies the CWnd object that will precede this CWnd object in the Z-order. This parameter can be a pointer to a CWnd or a Pointer to one of the following values:

  • wndBottom Places the window at the bottom of the Z-order. If this CWnd is a topmost window, the window loses its topmost status; the system places the window at the bottom of all other windows.

  • wndTop Places the window at the top of the Z-order.

  • wndTopMost Places the window above all nontopmost windows. The window maintains its topmost position even when it is deactivated.

  • wndNoTopMost Repositions the window to the top of all nontopmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a nontopmost window.

    See the “Remarks” section for this function for rules about how this parameter is used.

x

Specifies the new position of the left side of the window.

y

Specifies the new position of the top of the window.

cx

Specifies the new width of the window.

cy

Specifies the new height of the window.

nFlags

Specifies sizing and positioning options. This parameter can be a combination of the following:

  • SWP_DRAWFRAME Draws a frame (defined when the window was created) around the window.

  • SWP_FRAMECHANGED Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.

  • SWP_HIDEWINDOW Hides the window.

  • SWP_NOACTIVATE Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or the nontopmost group (depending on the setting of the pWndInsertAfter parameter).

  • SWP_NOCOPYBITS Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.

  • SWP_NOMOVE Retains current position (ignores the x and y parameters).

  • SWP_NOOWNERZORDER Does not change the owner window’s position in the Z-order.

  • SWP_NOREDRAW Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title and scroll bars), and any part of the parent window uncovered as a result of the moved window. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that must be redrawn.

  • SWP_NOREPOSITION Same as SWP_NOOWNERZORDER.

  • SWP_NOSENDCHANGING Prevents the window from receiving the WM_WINDOWPOSCHANGING message.

  • SWP_NOSIZE Retains current size (ignores the cx and cy parameters).

  • SWP_NOZORDER Retains current ordering (ignores pWndInsertAfter).

  • SWP_SHOWWINDOW Displays the window.

Remarks

Call this member function to change the size, position, and Z-order of child, pop-up, and top-level windows.

Windows are ordered on the screen according to their Z-order; the window at the top of the Z-order appears on top of all other windows in the order.

All coordinates for child windows are client coordinates (relative to the upper-left corner of the parent window’s client area).

A window can be moved to the top of the Z-order either by setting the pWndInsertAfter parameter to &wndTopMost and ensuring that the SWP_NOZORDER flag is not set or by setting a window’s Z-order so that it is above any existing topmost windows. When a nontopmost window is made topmost, its owned windows are also made topmost. Its owners are not changed.

A topmost window is no longer topmost if it is repositioned to the bottom (&wndBottom) of the Z-order or after any nontopmost window. When a topmost window is made nontopmost, all of its owners and its owned windows are also made nontopmost windows.

If neither SWP_NOACTIVATE nor SWP_NOZORDER is specified (that is, when the application requests that a window be simultaneously activated and placed in the specified Z-order), the value specified in pWndInsertAfter is used only in the following circumstances:

  • Neither &wndTopMost nor &wndNoTopMost is specified in the pWndInsertAfter parameter.

  • This window is not the active window.

An application cannot activate an inactive window without also bringing it to the top of the Z-order. Applications can change the Z-order of an activated window without restrictions.

A nontopmost window may own a topmost window, but not vice versa. Any window (for example, a dialog box) owned by a topmost window is itself made a topmost window to ensure that all owned windows stay above their owner.

With Windows versions 3.1 and later, windows can be moved to the top of the Z-order and locked there by setting their WS_EX_TOPMOST styles. Such a topmost window maintains its topmost position even when deactivated. For example, selecting the WinHelp Always On Top command makes the Help window topmost, and it then remains visible when you return to your application.

To create a topmost window, call SetWindowPos with the pWndInsertAfter parameter equal to &wndTopMost, or set the WS_EX_TOPMOST style when you create the window.

If the Z-order contains any windows with the WS_EX_TOPMOST style, a window moved with the &wndTopMost value is placed at the top of all nontopmost windows, but below any topmost windows. When an application activates an inactive window without the WS_EX_TOPMOST bit, the window is moved above all nontopmost windows but below any topmost windows.

If SetWindowPos is called when the pWndInsertAfter parameter is &wndBottom and CWnd is a topmost window, the window loses its topmost status (WS_EX_TOPMOST is cleared), and the system places the window at the bottom of the Z-order.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::DeferWindowPos, ::SetWindowPos


CWnd::SetWindowRgn

int SetWindowRgn( HRGN hRgn, BOOL bRedraw );

Return Value

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.

Parameters

hRgn

A handle to a region.

bRedraw

If TRUE, the operating system redraws the window after setting the region; otherwise, it does not. Typically, set bRedraw to TRUE if the window is visible. If set to TRUE, the system sends the WM_WINDOWPOSCHANGING and WM_WINDOWPOSCHANGED messages to the window.

Remarks

Call this member function to set a window's region.

The coordinates of a window’s window region are relative to the upper-left corner of the window, not the client area of the window.

After a successful call to SetWindowRgn, the operating system owns the region specified by the region handle hRgn. The operating system does not make a copy of the region, so do not make any further function calls with this region handle, and do not close this region handle.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::SetWindowRgn, CWnd::GetWindowRgn


CWnd::SetWindowText

void SetWindowText( LPCTSTR lpszString );

Parameters

lpszString

Points to a CString object or null-terminated string to be used as the new title or control text.

Remarks

Sets the window’s title to the specified text. If the window is a control, the text within the control is set.

This function causes a WM_SETTEXT message to be sent to this window.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetWindowText, ::SetWindowText


CWnd::ShowCaret

void ShowCaret( );

Remarks

Shows the caret on the screen at the caret’s current position. Once shown, the caret begins flashing automatically.

The ShowCaret member function shows the caret only if it has a current shape and has not been hidden two or more times consecutively. If the caret is not owned by this window, the caret is not shown.

Hiding the caret is cumulative. If the HideCaret member function has been called five times consecutively, ShowCaret must be called five times to show the caret.

The caret is a shared resource. The window should show the caret only when it has the input focus or is active.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::HideCaret, ::ShowCaret


CWnd::ShowOwnedPopups

void ShowOwnedPopups( BOOL bShow = TRUE );

Parameters

bShow

Specifies whether pop-up windows are to be shown or hidden. If this parameter is TRUE, all hidden pop-up windows are shown. If this parameter is FALSE, all visible pop-up windows are hidden.

Remarks

Shows or hides all pop-up windows owned by this window.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::ShowOwnedPopups


CWnd::ShowScrollBar

void ShowScrollBar( UINT nBar, BOOL bShow = TRUE );

Parameters

nBar

Specifies whether the scroll bar is a control or part of a window’s nonclient area. If it is part of the nonclient area, nBar also indicates whether the scroll bar is positioned horizontally, vertically, or both. It must be one of the following:

  • SB_BOTH Specifies the horizontal and vertical scroll bars of the window.

  • SB_HORZ Specifies that the window is a horizontal scroll bar.

  • SB_VERT Specifies that the window is a vertical scroll bar.

bShow

Specifies whether Windows shows or hides the scroll bar. If this parameter is TRUE, the scroll bar is shown; otherwise the scroll bar is hidden.

Remarks

Shows or hides a scroll bar.

An application should not call ShowScrollBar to hide a scroll bar while processing a scroll-bar notification message.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::ShowScrollBar, CScrollBar::ShowScrollBar


CWnd::ShowWindow

BOOL ShowWindow( int nCmdShow );

Return Value

Nonzero if the window was previously visible; 0 if the CWnd was previously hidden.

Parameters

nCmdShow

Specifies how the CWnd is to be shown. It must be one of the following values:

  • SW_HIDE Hides this window and passes activation to another window.

  • SW_MINIMIZE Minimizes the window and activates the top-level window in the system’s list.

  • SW_RESTORE Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position.

  • SW_SHOW Activates the window and displays it in its current size and position.

  • SW_SHOWMAXIMIZED Activates the window and displays it as a maximized window.

  • SW_SHOWMINIMIZED Activates the window and displays it as 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 the window in its most recent size and position. The window that is currently active remains active.

  • SW_SHOWNORMAL Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position.

Remarks

Sets the visibility state of the window.

ShowWindow must be called only once per application for the main window with CWinApp::m_nCmdShow. Subsequent calls to ShowWindow must use one of the values listed above instead of the one specified by CWinApp::m_nCmdShow.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::ShowWindow, CWnd::OnShowWindow, CWnd::ShowOwnedPopups


CWnd::SubclassDlgItem

BOOL SubclassDlgItem( UINT nID, CWnd* pParent );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

nID

The control’s ID.

pParent

The control’s parent (usually a dialog box).

Remarks

Call this member function to “dynamically subclass” a control created from a dialog template and attach it to this CWnd object. When a control is dynamically subclassed, windows messages will route through the CWnd’s message map and call message handlers in the CWnd’s class first. Messages that are passed to the base class will be passed to the default message handler in the control.

This member function attaches the Windows control to a CWnd object and replaces the control’s WndProc and AfxWndProc functions. The function stores the old WndProc in the location returned by the GetSuperWndProcAddr member function.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetSuperWndProcAddr, CWnd::DefWindowProc, CWnd::SubclassWindow, CWnd::Attach


CWnd::SubclassWindow

BOOL SubclassWindow( HWND hWnd );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

hWnd

A handle to the window.

Remarks

Call this member function to "dynamically subclass" a window and attach it to this CWnd object. When a window is dynamically subclassed, windows messages will route through the CWnd’s message map and call message handlers in the CWnd’s class first. Messages that are passed to the base class will be passed to the default message handler in the window.

This member function attaches the Windows control to a CWnd object and replaces the window’s WndProc and AfxWndProc functions. The function stores a pointer to the old WndProc in the CWnd object.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::GetSuperWndProcAddr, CWnd::DefWindowProc, CWnd::SubclassDlgItem, CWnd::Attach, CWnd::PreSubclassWindow, CWnd::UnsubclassWindow


CWnd::UnlockWindowUpdate

void CWnd::UnlockWindowUpdate();

Remarks

Call this member function to unlock a window that was locked with CWnd::LockWindowUpdate.

Only one window at a time can be locked using LockWindowUpdate. See CWnd::LockWindowUpdate or the Win32 function LockWindowUpdate for more information on locking windows.


CWnd::UnsubclassWindow

HWND UnsubclassWindow( );

Return Value

A handle to the unsubclassed window.

Remarks

Call this member function to set WndProc back to its original value and detach the window identified by HWND from the CWnd object.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::SubclassWindow, CWnd::PreSubclassWindow, CWnd::GetSuperWndProcAddr, CWnd::DefWindowProc, CWnd::SubclassDlgItem, CWnd::Attach


CWnd::UpdateData

BOOL UpdateData( BOOL bSaveAndValidate = TRUE );

Return Value

Nonzero if the operation is successful; otherwise 0. If bSaveAndValidate is TRUE, then a return value of nonzero means that the data is successfully validated.

Parameters

bSaveAndValidate

Flag that indicates whether dialog box is being initialized (FALSE) or data is being retrieved (TRUE).

Remarks

Call this member function to initialize data in a dialog box, or to retrieve and validate dialog data.

The framework automatically calls UpdateData with bSaveAndValidate set to FALSE when a modal dialog box is created in the default implementation of CDialog::OnInitDialog. The call occurs before the dialog box is visible. The default implementation of CDialog::OnOK calls this member function with bSaveAndValidate set to TRUE to retrieve the data, and if successful, will close the dialog box. (If the Cancel button is clicked in the dialog box, the dialog box is closed without the data being retrieved.)

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::DoDataExchange


CWnd::UpdateDialogControls

void UpdateDialogControls( CCmdTarget* pTarget, BOOL bDisableIfNoHndler );

Parameters

pTarget

Points to the main frame window of the application, and is used for routing update messages.

bDisableIfNoHndler

Flag that indicates whether a control that has no update handler should be automatically displayed as disabled.

Remarks

Call this member function to update the state of dialog buttons and other controls in a dialog box or window that uses the ON_UPDATE_COMMAND_UI callback mechanism.

If a child control does not have a handler and bDisableIfNoHndler is TRUE, then the child control will be disabled.

The framework calls this member function for controls in dialog bars or toolbars as part of the application’s idle processing.

CWnd Overview | Class Members | Hierarchy Chart

See Also CFrameWnd::m_bAutoMenuEnable


CWnd::UpdateWindow

void UpdateWindow( );

Remarks

Updates the client area by sending a WM_PAINT message if the update region is not empty. The UpdateWindow member function sends a WM_PAINT message directly, bypassing the application queue. If the update region is empty, WM_PAINT is not sent.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::UpdateWindow, CWnd::RedrawWindow


CWnd::ValidateRect

void ValidateRect( LPCRECT lpRect );

Parameters

lpRect

Points to a CRect object or RECT structure that contains client coordinates of the rectangle to be removed from the update region. If lpRect is NULL, the entire window is validated.

Remarks

Validates the client area within the given rectangle by removing the rectangle from the update region of the window. The BeginPaint member function automatically validates the entire client area. Neither the ValidateRect nor the ValidateRgn member function should be called if a portion of the update region needs to be validated before WM_PAINT is next generated.

Windows continues to generate WM_PAINT messages until the current update region is validated.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::BeginPaint, ::ValidateRect, CWnd::ValidateRgn


CWnd::ValidateRgn

void ValidateRgn( CRgn* pRgn );

Parameters

pRgn

A pointer to a CRgn object that identifies a region that defines the area to be removed from the update region. If this parameter is NULL, the entire client area is removed.

Remarks

Validates the client area within the given region by removing the region from the current update region of the window. The given region must have been created previously by a region function. The region coordinates are assumed to be client coordinates.

The BeginPaint member function automatically validates the entire client area. Neither the ValidateRect nor the ValidateRgn member function should be called if a portion of the update region must be validated before the next WM_PAINT message is generated.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::ValidateRgn, CWnd::ValidateRect


CWnd::WindowFromPoint

static CWnd* PASCAL WindowFromPoint( POINT point );

Return Value

A pointer to the window object in which the point lies. It is NULL if no window exists at the given point. The returned pointer may be temporary and should not be stored for later use.

Parameters

point

Specifies a CPoint object or POINT data structure that defines the point to be checked.

Remarks

Retrieves the window that contains the specified point; point must specify the screen coordinates of a point on the screen.

WindowFromPoint does not retrieve a hidden or disabled window, even if the point is within the window. An application should use the ChildWindowFromPoint member function for a nonrestrictive search.

CWnd Overview | Class Members | Hierarchy Chart

See Also ::WindowFromPoint, CWnd::ChildWindowFromPoint


CWnd::WindowProc

virtual LRESULT WindowProc( UINT message, WPARAM wParam, LPARAM lParam );

Return Value

The return value depends on the message.

Parameters

message

Specifies the Windows message to be processed.

wParam

Provides additional information used in processing the message. The parameter value depends on the message.

lParam

Provides additional information used in processing the message. The parameter value depends on the message.

Remarks

Provides a Windows procedure (WindowProc) for a CWnd object. It dispatches messages through the window’s message map.


CWnd::m_hWnd

Remarks

The handle of the Windows window attached to this CWnd. The m_hWnd data member is a public variable of type HWND.

CWnd Overview | Class Members | Hierarchy Chart

See Also CWnd::Attach, CWnd::Detach, CWnd::FromHandle


CWordArray

The CWordArray class supports arrays of 16-bit words.

The member functions of CWordArray are similar to the member functions of class CObArray. Because of this similarity, you can use the CObArray reference documentation for member function specifics. Wherever you see a CObject pointer as a function parameter or return value, substitute a WORD.

CObject* CObArray::GetAt( int <nIndex> ) const;

for example, translates to

WORD CWordArray::GetAt( int <nIndex> ) const;

CWordArray incorporates the IMPLEMENT_SERIAL macro to support serialization and dumping of its elements. If an array of words is stored to an archive, either with an overloaded insertion operator or with the CObject::Serialize member function, each element is, in turn, serialized.

Note Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.

If you need a dump of individual elements in the array, you must set the depth of the dump context to 1 or greater.

For more information on using CWordArray, see the article Collections in Visual C++ Programmer’s Guide.

#include <afxcoll.h>

Class Members | Base Class | Hierarchy Chart

Sample MFC Sample COLLECT


CWordArray Class Members

Construction

CWordArray Constructs an empty array for words.

Bounds

GetSize | Gets number of elements in this array.
GetUpperBound | Returns the largest valid index.
SetSize | Sets the number of elements to be contained in this array.

Operations

FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.

Element Access

GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; array is not allowed to grow.
ElementAt | Returns a temporary reference to the element pointer within the array.
GetData | Allows access to elements in the array. Can be NULL.

Growing the Array

SetAtGrow | Sets the value for a given index; grows the array if necessary.
Add | Adds an element to the end of the array; grows the array if necessary.
Append | Appends another array to the array; grows the array if necessary.
Copy | Copies another array to the array; grows the array if necessary.

Insertion/Removal

InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.

Operators

operator [] Sets or gets the element at the specified index.


MFC Macros and Globals

The Microsoft Foundation Class Library can be divided into two major sections: (1) the MFC classes and (2) macros and globals. If a function or variable is not a member of a class, it is a global function or variable.

The MFC library and the Active Template library (ATL) share string conversion macros. See String Conversion Macros in the ATL documentation for a discussion of these macros.

The MFC macros and globals offer functionality in the following categories:

General MFC

  • Data types

  • Type Casting of MFC Class Objects

  • Run-time object model services

  • Diagnostic services

  • Exception processing

  • CString formatting and message-box display

  • Message maps

  • Application information and management

  • Standard command and window IDs

  • Collection class helpers

  • ClassWizard comment delimiters

Database

  • Record Field Exchange (RFX) functions and Bulk Record Field Exchange (Bulk RFX) functions for the MFC ODBC classes

  • Record Field Exchange (DFX) functions for the MFC DAO classes

  • Dialog Data Exchange (DDX) functions for CRecordView and CDaoRecordView (MFC ODBC and DAO classes)

  • Dialog Data Exchange (DDX) functions for OLE controls

  • Macros and globals to aid in calling Open Database Connectivity (ODBC) API functions directly

  • DAO Database Engine Initialization and Termination

Internet

  • Internet Server API (ISAPI) Parse Maps

  • Internet URL Parsing Globals

  • Internet Server API (ISAPI) Diagnostic Macros

OLE

  • OLE initialization

  • Application control

  • Dispatch maps

In addition, MFC provides a function, called AfxEnableControlContainer, that enables any OLE container, developed with MFC 4.0, to fully support embedded OLE controls.

OLE Controls

  • Variant parameter type constants

  • Type library access

  • Property pages

  • Event maps

  • Event sink maps

  • Connection maps

  • Registering OLE controls

  • Class factories and licensing

  • Persistence of OLE controls

The first part of this section briefly discusses each of the above categories and lists each global and macro in the category, along with a brief description of what it does. Following this — in alphabetical order — are complete descriptions of the global functions, global variables, and macros in the MFC library.

The main supporting reference for the MFC Macros and Globals section is Visual C++ Programmer's Guide. This is usually the first place you should look to find more information on macros and globals. When necessary, the appropriate article in Visual C++ Programmer's Guide is mentioned with the function or macro description.

Note Many global functions start with the prefix "Afx" — but some, such as the dialog data exchange (DDX) functions and many of the database functions, deviate from this convention. All global variables start with "afx" as a prefix. Macros do not start with any particular prefix, but they are written all in uppercase.


Data Types

This topic lists the data types most commonly used in the Microsoft Foundation Class Library. Most of the data types are exactly the same as those in the Windows Software Development Kit (SDK), while others are unique to MFC.

Commonly used Windows SDK and MFC data types are as follows:

  • BOOL A Boolean value.

  • BSTR A 32-bit character pointer.

  • BYTE An 8-bit integer that is not signed.

  • COLORREF A 32-bit value used as a color value.

  • DWORD A 32-bit unsigned integer or the address of a segment and its associated offset.

  • LONG A 32-bit signed integer.

  • LPARAM A 32-bit value passed as a parameter to a window procedure or callback function.

  • LPCSTR A 32-bit pointer to a constant character string.

  • LPSTR A 32-bit pointer to a character string.

  • LPCTSTR A 32-bit pointer to a constant character string that is portable for Unicode and DBCS.

  • LPTSTR A 32-bit pointer to a character string that is portable for Unicode and DBCS.

  • LPVOID A 32-bit pointer to an unspecified type.

  • LRESULT A 32-bit value returned from a window procedure or callback function.

  • UINT A 16-bit unsigned integer on Windows versions 3.0 and 3.1; a 32-bit unsigned integer on Win32.

  • WNDPROC A 32-bit pointer to a window procedure.

  • WORD A 16-bit unsigned integer.

  • WPARAM A value passed as a parameter to a window procedure or callback function: 16 bits on Windows versions 3.0 and 3.1; 32 bits on Win32.

Data types unique to the Microsoft Foundation Class Library include the following:

  • POSITION A value used to denote the position of an element in a collection; used by MFC collection classes.

  • LPCRECT A 32-bit pointer to a constant (nonmodifiable) RECT structure.


Type Casting of MFC Class Objects

Type casting macros provide a way to cast a given pointer to a pointer that points to an object of specific class, with or without checking that the cast is legal.

The following table lists the MFC type casting macros.

Macros that Cast Pointers to MFC Class Objects

DYNAMIC_DOWNCAST | Casts a pointer to a pointer to a class object while checking to see if the cast is legal.
STATIC_DOWNCAST | Casts a pointer to an object from one class to a pointer of a related type. In a debug build, causes an ASSERT if the object is not a "kind of" the target type.


Run-Time Object Model Services

The classes CObject and CRuntimeClass encapsulate several object services, including access to run-time class information, serialization, and dynamic object creation. All classes derived from CObject inherit this functionality.

Access to run-time class information enables you to determine information about an object's class at run time. The ability to determine the class of an object at run time is useful when you need extra type-checking of function arguments and when you must write special-purpose code based on the class of an object. Run-time class information is not supported directly by the C++ language.

Serialization is the process of writing or reading an object's contents to or from a file. You can use serialization to store an object's contents even after the application exits. The object can then be read from the file when the application is restarted. Such data objects are said to be "persistent."

Dynamic object creation enables you to create an object of a specified class at run time. For example, document, view, and frame objects must support dynamic creation because the framework needs to create them dynamically.

The following table lists the MFC macros that support run-time class information, serialization, and dynamic creation.

For more information on these run-time object services and serialization, see the article CObject Class: Accessing Run-Time Class Information in Visual C++ Programmer's Guide.

Run-Time Object Model Services Macros

DECLARE_DYNAMIC | Enables access to run-time class information (must be used in the class declaration).
DECLARE_DYNCREATE | Enables dynamic creation and access to run-time class information (must be used in the class declaration).
DECLARE_SERIAL | Enables serialization and access to run-time class information (must be used in the class declaration).
IMPLEMENT_DYNAMIC | Enables access to run-time class information (must be used in the class implementation).
IMPLEMENT_DYNCREATE | Enables dynamic creation and access to run-time information (must be used in the class implementation).
IMPLEMENT_SERIAL | Permits serialization and access to run-time class information (must be used in the class implementation).
RUNTIME_CLASS | Returns the CRuntimeClass structure that corresponds to the named class.

OLE frequently requires the dynamic creation of objects at run time. For example, an OLE server application must be able to create OLE items dynamically in response to a request from a client. Similarly, an automation server must be able to create items in response to requests from automation clients.

The Microsoft Foundation Class Library provides two macros specific to OLE.

Dynamic Creation of OLE Objects

DECLARE_OLECREATE | Enables objects to be created through OLE automation.
IMPLEMENT_OLECREATE | Enables objects to be created by the OLE system.


Diagnostic Services

The Microsoft Foundation Class Library supplies many diagnostic services that make debugging your programs easier. These diagnostic services include macros and global functions that allow you to track your program's memory allocations, dump the contents of objects during run time, and print debugging messages during run time. The macros and global functions for diagnostic services are grouped into the following categories:

  • General diagnostic macros

  • General diagnostic functions and variables

  • Object diagnostic functions

These macros and functions are available for all classes derived from CObject in the Debug and Release versions of MFC. However, all except DEBUG_NEW and VERIFY do nothing in the Release version.

In the Debug library, all allocated memory blocks are bracketed with a series of "guard bytes." If these bytes are disturbed by an errant memory write, then the diagnostic routines can report a problem. If you include the line

#define new DEBUG_NEW

in your implementation file, all calls to new will store the filename and line number where the memory allocation took place. The function CMemoryState::DumpAllObjectsSince will display this extra information, allowing you to identify memory leaks. Refer also to the class CDumpContext for additional information on diagnostic output.

In addition, the C run-time library also supports a set of diagnostic functions you can use to debug your applications. For more information, see Debug Routines in the Run-Time Library Reference.

MFC General Diagnostic Macros

ASSERT | Prints a message and then aborts the program if the specified expression evaluates to FALSE in the Debug version of the library.
ASSERT_KINDOF | Tests that an object is an object of the specified class or of a class derived from the specified class.
ASSERT_VALID | Tests the internal validity of an object by calling its AssertValid member function; typically overridden from CObject.
DEBUG_NEW | Supplies a filename and line number for all object allocations in Debug mode to help find memory leaks.
TRACE | Provides printf-like capability in the Debug version of the library.
TRACE0 | Similar to TRACE but takes a format string with no arguments.
TRACE1 | Similar to TRACE but takes a format string with a single argument.
TRACE2 | Similar to TRACE but takes a format string with two arguments.
TRACE3 | Similar to TRACE but takes a format string with three arguments.
VERIFY | Similar to ASSERT but evaluates the expression in the Release version of the library as well as in the Debug version.

MFC General Diagnostic Variables and Functions

afxDump | Global variable that sends CDumpContext information to the debugger output window or to the debug terminal.
afxMemDF | Global variable that controls the behavior of the debugging memory allocator.
afxTraceEnabled | Global variable used to enable or disable output from the TRACE macro.
afxTraceFlags | Global variable used to turn on the built-in reporting features of MFC.
AfxCheckError | Global variable used to test the passed SCODE to see if it is an error and, if so, throws the appropriate error.
AfxCheckMemory | Checks the integrity of all currently allocated memory.
AfxDump | If called while in the debugger, dumps the state of an object while debugging.
AfxDumpStack | Generate an image of the current stack. This function is always linked statically.
AfxEnableMemoryTracking | Turns memory tracking on and off.
AfxIsMemoryBlock | Verifies that a memory block has been properly allocated.
AfxIsValidAddress | Verifies that a memory address range is within the program's bounds.
AfxIsValidString | Determines whether a pointer to a string is valid.
AfxSetAllocHook | Enables the calling of a function on each memory allocation.

MFC Object Diagnostic Functions

AfxDoForAllClasses | Performs a specified function on all CObject-derived classes that support run-time type checking.
AfxDoForAllObjects | Performs a specified function on all CObject-derived objects that were allocated with new.


Exception Processing

When a program executes, a number of abnormal conditions and errors called "exceptions" can occur. These may include running out of memory, resource allocation errors, and failure to find files.

The Microsoft Foundation Class Library uses an exception-handling scheme that is modeled closely after the one proposed by the ANSI standards committee for C++. An exception handler must be set up before calling a function that may encounter an abnormal situation. If the function encounters an abnormal condition, it throws an exception and control is passed to the exception handler.

Several macros included with the Microsoft Foundation Class Library will set up exception handlers. A number of other global functions help to throw specialized exceptions and terminate programs, if necessary. These macros and global functions fall into the following categories:

  • Exception macros, which structure your exception handler

  • Exception-throwing functions, which generate exceptions of specific types

  • Termination functions, which cause program termination

For examples and more details, see the article Exceptions in Visual C++ Programmer's Guide.

Exception Macros

TRY | Designates a block of code for exception processing.
CATCH | Designates a block of code for catching an exception from the preceding TRY block.
CATCH_ALL | Designates a block of code for catching all exceptions from the preceding TRY block.
AND_CATCH | Designates a block of code for catching additional exception types from the preceding TRY block.
AND_CATCH_ALL | Designates a block of code for catching all other additional exception types thrown in a preceding TRY block.
END_CATCH | Ends the last CATCH or AND_CATCH code block.
END_CATCH_ALL | Ends the last CATCH_ALL code block.
THROW | Throws a specified exception.
THROW_LAST | Throws the currently handled exception to the next outer handler.

Exception-Throwing Functions

AfxThrowArchiveException | Throws an archive exception.
AfxThrowFileException | Throws a file exception.
AfxThrowMemoryException | Throws a memory exception.
AfxThrowNotSupportedException | Throws a not-supported exception.
AfxThrowResourceException | Throws a Windows resource-not-found exception.
AfxThrowUserException | Throws an exception in a user-initiated program action.

MFC provides two exception-throwing functions specifically for OLE exceptions:

OLE Exception Functions

AfxThrowOleDispatchException | Throws an exception within an OLE automation function.
AfxThrowOleException | Throws an OLE exception.

To support database exceptions, the database classes provide two exception classes, CDBException and CDaoException, and global functions to support the exception types:

DAO Exception Functions

AfxThrowDAOException | Throws a CDaoException from your own code.
AfxThrowDBException | Throws a CDBException from your own code.

MFC provides the following termination function:

Termination Functions

AfxAbort Called to terminate an application when a fatal error occurs.

See Also CException


CString Formatting and Message-Box Display

A number of functions are provided to format and parse CString objects. You can use these functions whenever you have to manipulate CString objects, but they are particularly useful for formatting strings that will appear in message-box text.

This group of functions also includes a global routine for displaying a message box.

CString Functions

AfxFormatString1 | Substitutes a given string for the format characters "%1" in a string contained in the string table.
AfxFormatString2 | Substitutes two strings for the format characters "%1" and "%2" in a string contained in the string table.
AfxMessageBox | Displays a message box.

See Also CString


Application Information and Management

When you write an application, you create a single CWinApp-derived object. At times, you may wish to get information about this object from outside the CWinApp-derived object.

The Microsoft Foundation Class Library provides the following global functions to help you accomplish these tasks:

Application Information and Management Functions

AfxFreeLibrary | Decrements the reference count of the loaded dynamic-link library (DLL) module; when the reference count reaches zero, the module is unmapped.
AfxGetApp | Returns a pointer to the application's single CWinApp object.
AfxGetAppName | Returns a string containing the application's name.
AfxGetInstanceHandle | Returns an HINSTANCE representing this instance of the application.
AfxGetMainWnd | Returns a pointer to the current "main" window of a non-OLE application, or the in-place frame window of a server application.
AfxGetResourceHandle | Returns an HINSTANCE to the source of the application's default resources. Use this to access the application's resources directly.
AfxInitRichEdit | Initializes the rich edit control for the application and initializes the common controls library, if the library hasn't already been initialized for the process.
AfxLoadLibrary | Maps a DLL module and returns a handle that can be used to get the address of a DLL function.
AfxRegisterWndClass | Registers a Windows window class to supplement those registered automatically by MFC.
AfxSocketInit | Called in a CWinApp::InitInstance override to initialize Windows Sockets.
AfxSetResourceHandle | Sets the HINSTANCE handle where the default resources of the application are loaded.
AfxRegisterClass | Registers a window class in a DLL that uses MFC.
AfxBeginThread | Creates a new thread.
AfxEndThread | Terminates the current thread.
AfxGetThread | Retrieves a pointer to the current CWinThread object.
AfxWinInit | Called by the MFC-supplied WinMain function, as part of the CWinApp initialization of a GUI-based application, to initialize MFC. Must be called directly for console applications using MFC.

See Also CWinApp


Standard Command and Window IDs

The Microsoft Foundation Class Library defines a number of standard command and window IDs in AFXRES.H. These IDs are most commonly used within the resource editors and ClassWizard to map messages to your handler functions. All standard commands have an ID_ prefix. For example, when you use the menu editor, you normally bind the File Open menu item to the standard ID_FILE_OPEN command ID.

For most standard commands, application code does not need to refer to the command ID, because the framework itself handles the commands through message maps in its primary framework classes (CWinThread, CWinApp, CView, CDocument, and so forth).

In addition to standard command IDs, a number of other standard IDs are defined which have a prefix of AFX_ID. These IDs include standard window IDs (prefix AFX_IDW_), string IDs (prefix AFX_IDS_), and several other types.

IDs that begin with the AFX_ID prefix are rarely used by programmers, but you might need to refer to these IDs when overriding framework functions which also refer to the AFX_IDs.

IDs are not individually documented in this reference. You can find more information on them in Technical Notes 20, 21, and 22.

Note The header file AFXRES.H is indirectly included in AFXWIN.H. You must explicitly include the statement

#include afxres.h

in your application's resource script (.RC) file.


Collection Class Helpers

The collection classes CMap, CList, and CArray use templated global helper functions for such purposes as constructing, destroying, and serializing elements. As part of your implementation of classes based on CMap, CList, and CArray, you must override these functions as necessary with versions tailored to the type of data stored in your map, list, or array. For information on overriding ConstructElements, DestructElements, and SerializeElements, see the article Collections: How to Make a Type-Safe Collection in Visual C++ Programmer's Guide.

The Microsoft Foundation Class Library provides the following global functions to help you customize your collection classes:

Collection Class Helpers

CompareElements | Indicates whether elements are the same.
ConstructElements | Performs any action necessary when an element is constructed.
CopyElements | Copies elements from one array to another.
DestructElements | Performs any action necessary when an element is destroyed.
DumpElements | Provides stream-oriented diagnostic output.
HashKey | Calculates a hash key.
SerializeElements | Stores or retrieves elements to or from an archive.

See Also CMap, CList, CArray


Record Field Exchange Functions

This topic lists the Record Field Exchange (RFX, Bulk RFX, and DFX) functions used to automate the transfer of data between a recordset object and its data source and to perform other operations on the data.

If you are using the ODBC-based classes and you have implemented bulk row fetching, you must manually override the DoBulkFieldExchange member function of CRecordset by calling the Bulk RFX functions for each data member corresponding to a data source column.

If you have not implemented bulk row fetching in the ODBC-based classes, or if you are using the DAO-based classes, then ClassWizard will override the DoFieldExchange member function of CRecordset or CDaoRecordset by calling the RFX functions (for ODBC classes) or the DFX functions (for DAO classes) for each field data member in your recordset.

The record field exchange functions transfer data each time the framework calls DoFieldExchange or DoBulkFieldExchange. Each function transfers a specific data type.

For more information about how these functions are used, see the articles Record Field Exchange: How RFX Works (ODBC) and DAO Record Field Exchange: How DFX Works. For more information about bulk row fetching, see the article Recordset: Fetching Records in Bulk (ODBC). The articles are found in Visual C++ Programmer's Guide.

For columns of data that you bind dynamically, you can also call the RFX or DFX functions yourself, rather than using ClassWizard, as explained in the articles Recordset: Dynamically Binding Data Columns (ODBC) and DAO: Binding Records Dynamically. The articles are found in Visual C++ Programmer's Guide. Note that dynamic binding in DAO is different from dynamic binding in ODBC. Additionally, you can write your own custom RFX or DFX routines, as explained in Technical Note 43 (for ODBC) and Technical Note 53 (for DAO).

For an example of RFX and Bulk RFX functions as they appear in the DoFieldExchange and DoBulkFieldExchange functions, see RFX_Text and RFX_Text_Bulk. DFX functions are very similar to the RFX functions.

RFX Functions (ODBC)

RFX_Binary | Transfers arrays of bytes of type CByteArray.
RFX_Bool | Transfers Boolean data.
RFX_Byte | Transfers a single byte of data.
RFX_Date | Transfers time and date data using CTime or TIMESTAMP_STRUCT.
RFX_Double | Transfers double-precision float data.
RFX_Int | Transfers integer data.
RFX_Long | Transfers long integer data.
RFX_LongBinary | Transfers binary large object (BLOB) data via an object of the CLongBinary class.
RFX_Single | Transfers float data.
RFX_Text | Transfers string data.

Bulk RFX Functions (ODBC)

RFX_Binary_Bulk | Transfers arrays of byte data.
RFX_Bool_Bulk | Transfers arrays of Boolean data.
RFX_Byte_Bulk | Transfers arrays of single bytes.
RFX_Date_Bulk | Transfers arrays of data of type TIMESTAMP_STRUCT.
RFX_Double_Bulk | Transfers arrays of double-precision floating-point data.
RFX_Int_Bulk | Transfers arrays of integer data.
RFX_Long_Bulk | Transfers arrays of long integer data.
RFX_Single_Bulk | Transfers arrays of floating-point data.
RFX_Text_Bulk | Transfers arrays of data of type LPSTR.

DFX Functions (DAO)

DFX_Binary | Transfers arrays of bytes of type CByteArray.
DFX_Bool | Transfers Boolean data.
DFX_Byte | Transfers a single byte of data.
DFX_Currency | Transfers currency data, of type COleCurrency.
DFX_DateTime | Transfers time and date data, of type COleDateTime.
DFX_Double | Transfers double-precision float data.
DFX_Long | Transfers long integer data.
DFX_LongBinary | Transfers binary-large object (BLOB) data via an object of the CLongBinary class. For DAO, it is recommended that you use DFX_Binary instead.
DFX_Short | Transfers short integer data.
DFX_Single | Transfers float data.
DFX_Text | Transfers string data.

See Also CRecordset::DoFieldExchange, CRecordset::DoBulkFieldExchange, CDaoRecordset::DoFieldExchange


Dialog Data Exchange Functions for CRecordView and CDaoRecordView

This topic lists the DDX_Field functions used to exchange data between a CRecordset and a CRecordView form or a CDaoRecordset and a CDaoRecordView form.

Important DDX_Field functions are like DDX functions in that they exchange data with controls in a form. But unlike DDX, they exchange data with the fields of the view's associated recordset object rather than with fields of the record view itself. For more information, see classes CRecordView and CDaoRecordView and the article ClassWizard: Mapping Form Controls to Recordset Fields in Visual C++ Programmer's Guide.

DDX_Field Functions

DDX_FieldCBIndex | Transfers integer data between a recordset field data member and the index of the current selection in a combo box in a CRecordView or CDaoRecordView.
DDX_FieldCBString | Transfers CString data between a recordset field data member and the edit control of a combo box in a CRecordView or CDaoRecordView. When moving data from the recordset to the control, this function selects the item in the combo box that begins with the characters in the specified string.
DDX_FieldCBStringExact | Transfers CString data between a recordset field data member and the edit control of a combo box in a CRecordView or CDaoRecordView. When moving data from the recordset to the control, this function selects the item in the combo box that exactly matches the specified string.
DDX_FieldCheck | Transfers Boolean data between a recordset field data member and a check box in a CRecordView or CDaoRecordView.
DDX_FieldLBIndex | Transfers integer data between a recordset field data member and the index of the current selection in a list box in a CRecordView or CDaoRecordView.
DDX_FieldLBString | Manages the transfer of CString data between a list-box control and the field data members of a recordset. When moving data from the recordset to the control, this function selects the item in the list box that begins with the characters in the specified string.
DDX_FieldLBStringExact | Manages the transfer of CString data between a list-box control and the field data members of a recordset. When moving data from the recordset to the control, this function selects the first item that exactly matches the specified string.
DDX_FieldRadio | Transfers integer data between a recordset field data member and a group of radio buttons in a CRecordView or CDaoRecordView.
DDX_FieldScroll | Sets or gets the scroll position of a scroll bar control in a CRecordView or CDaoRecordView. Call from your DoFieldExchange function.
DDX_FieldText | Overloaded versions are available for transferring int, UINT, long, DWORD, CString, float, double, short, COleDateTime, and COleCurrency data between a recordset field data member and an edit box in a CRecordView or CDaoRecordView.


Dialog Data Exchange Functions for OLE Controls

This topic lists the DDX_OC functions used to exchange data between a property of an OLE control in a dialog box, form view, or control view object and a data member of the dialog box, form view, or control view object.

DDX_OC Functions

DDX_OCBool | Manages the transfer of BOOL data between a property of an OLE control and a BOOL data member.
DDX_OCBoolRO | Manages the transfer of BOOL data between a read-only property of an OLE control and a BOOL data member.
DDX_OCColor | Manages the transfer of OLE_COLOR data between a property of an OLE control and an OLE_COLOR data member.
DDX_OCColorRO | Manages the transfer of OLE_COLOR data between a read-only property of an OLE control and an OLE_COLOR data member.
DDX_OCFloat | Manages the transfer of float (or double) data between a property of an OLE control and a float (or double) data member.
DDX_OCFloatRO | Manages the transfer of float (or double) data between a read-only property of an OLE control and a float (or double) data member.
DDX_OCInt | Manages the transfer of int (or long) data between a property of an OLE control and an int (or long) data member.
DDX_OCIntRO | Manages the transfer of int (or long) data between a read-only property of an OLE control and an int (or long) data member.
DDX_OCShort | Manages the transfer of short data between a property of an OLE control and a short data member.
DDX_OCShortRO | Manages the transfer of short data between a read-only property of an OLE control and a short data member.
DDX_OCText | Manages the transfer of CString data between a property of an OLE control and a CString data member.
DDX_OCTextRO | Manages the transfer of CString data between a read-only property of an OLE control and a CString data member.


Database Macros and Globals

The macros and globals listed below apply to ODBC-based database applications. They are not used with DAO-based applications.

Prior to MFC 4.2, the macros AFX_SQL_ASYNC and AFX_SQL_SYNC gave asynchronous operations an opportunity to yield time to other processes. Beginning with MFC 4.2, the implementation of these macros changed because the MFC ODBC classes used only synchronous operations. The macro AFX_ODBC_CALL was new to MFC 4.2.

Database Macros

AFX_ODBC_CALL | Use this macro to call an ODBC API function that returns SQL_STILL_EXECUTING. AFX_ODBC_CALL will repeatedly call the function until it no longer returns SQL_STILL_EXECUTING.
AFX_SQL_ASYNC | Simply calls AFX_ODBC_CALL.
AFX_SQL_SYNC | Use this macro to calls an ODBC API function that does not return SQL_STILL_EXECUTING.

Database Globals

AfxGetHENV Use this global to retrieve a handle to the ODBC environment currently in use by MFC. You can use this handle in direct ODBC calls.


DAO Database Engine Initialization and Termination

When using MFC DAO objects, the DAO database engine must first be initialized and then terminated before your application or DLL quits. Two functions, AfxDaoInit and AfxDaoTerm, perform these tasks.

DAO Database Engine Initialization and Termination

AfxDaoInit | Initializes the DAO database engine.
AfxDaoTerm | Terminates the DAO database engine.


OLE Initialization

Before an application can use OLE system services, it must initialize the OLE system DLLs and verify that the DLLs are the correct version. The AfxOleInit function initializes the OLE system DLLs.

OLE Initialization

AfxOleInit Initializes the OLE libraries.


Application Control

OLE requires substantial control over applications and their objects. The OLE system DLLs must be able to launch and release applications automatically, coordinate their production and modification of objects, and so on. The functions in this topic meet those requirements. In addition to being called by the OLE system DLLs, these functions must sometimes be called by applications as well.

Application Control

AfxOleCanExitApp | Indicates whether the application can terminate.
AfxOleGetMessageFilter | Retrieves the application's current message filter.
AfxOleGetUserCtrl | Retrieves the current user-control flag.
AfxOleSetUserCtrl | Sets or clears the user-control flag.
AfxOleLockApp | Increments the framework's global count of the number of active objects in an application.
AfxOleUnlockApp | Decrements the framework's count of the number of active objects in an application.
AfxOleRegisterServerClass | Registers a server in the OLE system registry.
AfxOleSetEditMenu | Implements the user interface for the typename Object command.


Dispatch Maps

OLE Automation provides ways to call methods and to access properties across applications. The mechanism supplied by the Microsoft Foundation Class Library for dispatching these requests is the "dispatch map," which designates the internal and external names of object functions and properties, as well as the data types of the properties themselves and of function arguments.

Dispatch Maps

DECLARE_DISPATCH_MAP | Declares that a dispatch map will be used to expose a class's methods and properties (must be used in the class declaration).
BEGIN_DISPATCH_MAP | Starts the definition of a dispatch map.
END_DISPATCH_MAP | Ends the definition of a dispatch map.
DISP_FUNCTION | Used in a dispatch map to define an OLE automation function.
DISP_PROPERTY | Defines an OLE automation property.
DISP_PROPERTY_EX | Defines an OLE automation property and names the "get" and "set" functions.
DISP_PROPERTY_NOTIFY | Defines an OLE automation property with notification.
DISP_PROPERTY_PARAM | Defines an OLE automation property that takes parameters and names the "get" and "set" functions.
DISP_DEFVALUE | Makes an existing property the default value of an object.


Variant Parameter Type Constants

This topic lists new constants that indicate variant parameter types designed for use with the OLE control classes of the Microsoft Foundation Class Library.

The following is a list of class constants:

Variant Data Constants

  • VTS_COLOR A 32-bit integer used to represent a RGB color value.

  • VTS_FONT A pointer to the IFontDisp interface of an OLE font object.

  • VTS_HANDLE A Windows handle value.

  • VTS_PICTURE A pointer to the IPictureDisp interface of an OLE picture object.

  • VTS_OPTEXCLUSIVE A 16-bit value used for a control intended to be used in a group of controls, such as radio buttons. This type tells the container that if one control in a group has a TRUE value, all others must be FALSE.

  • VTS_TRISTATE A 16-bit signed integer used for properties that can have one of three possible values (checked, unchecked, gray), for example, a check box.

  • VTS_XPOS_HIMETRIC A 32-bit unsigned integer used to represent a position along the x-axis in HIMETRIC units.

  • VTS_YPOS_HIMETRIC A 32-bit unsigned integer used to represent a position along the y-axis in HIMETRIC units.

  • VTS_XPOS_PIXELS A 32-bit unsigned integer used to represent a position along the x-axis in pixels.

  • VTS_YPOS_PIXELS A 32-bit unsigned integer used to represent a position along the y-axis in pixels.

  • VTS_XSIZE_PIXELS A 32-bit unsigned integer used to represent the width of a screen object in pixels.

  • VTS_YSIZE_PIXELS A 32-bit unsigned integer used to represent the height of a screen object in pixels.

  • VTS_XSIZE_HIMETRIC A 32-bit unsigned integer used to represent the width of a screen object in HIMETRIC units.

  • VTS_YSIZE_HIMETRIC A 32-bit unsigned integer used to represent the height of a screen object in HIMETRIC units.

Note Additional variant constants have been defined for all variant types, with the exception of VTS_FONT and VTS_PICTURE, that provide a pointer to the variant data constant. These constants are named using the VTS_P constantname convention. For example, VTS_PCOLOR is a pointer to a VTS_COLOR constant.


Type Library Access

Type libraries expose the interfaces of an OLE control to other OLE-aware applications. Each OLE control must have a type library if one or more interfaces are to be exposed.

The following macros allow an OLE control to provide access to its own type library:

Type Library Access

DECLARE_OLETYPELIB | Declares a GetTypeLib member function of an OLE control (must be used in the class declaration).
IMPLEMENT_OLETYPELIB | Implements a GetTypeLib member function of an OLE control (must be used in the class implementation).


Property Pages

Property pages display the current values of specific OLE control properties in a customizable, graphical interface for viewing and editing by supporting a data-mapping mechanism based on dialog data exchange (DDX).

This data-mapping mechanism maps property page controls to the individual properties of the OLE control. The value of the control property reflects the status or content of the property page control. The mapping between property page controls and properties is specified by DDP_ function calls in the property page's DoDataExchange member function. The following is a list of DDP_ functions that exchange data entered using the property page of your control:

Property Page Data Transfer

DDP_CBIndex | Use this function to link the selected string's index in a combo box with a control's property.
DDP_CBString | Use this function to link the selected string in a combo box with a control's property. The selected string can begin with the same letters as the property's value but need not match it fully.
DDP_CBStringExact | Use this function to link the selected string in a combo box with a control's property. The selected string and the property's string value must match exactly.
DDP_Check | Use this function to link a check box in the control's property page with a control's property.
DDP_LBIndex | Use this function to link the selected string's index in a list box with a control's property.
DDP_LBString | Use this function to link the selected string in a list box with a control's property. The selected string can begin with the same letters as the property's value but need not match it fully.
DDP_LBStringExact | Use this function to link the selected string in a list box with a control's property. The selected string and the property's string value must match exactly.
DDP_PostProcessing | Use this function to finish the transfer of property values from your control.
DDP_Radio | Use this function to link a radio button group in the control's property page with a control's property.
DDP_Text | Use this function to link a control in the control's property page with a control's property. This function handles several different types of properties, such as double, short, BSTR, and long.

For more information about the DoDataExchange function and property pages, see the article ActiveX Controls: Property Pages in Visual C++ Programmer's Guide.

The following is a list of macros used to create and manage property pages for an OLE control:

Property Pages

BEGIN_PROPPAGEIDS | Begins the list of property page IDs.
END_PROPPAGEIDS | Ends the list of property page IDs.
PROPPAGEID | Declares a property page of the control class.


Event Maps

Whenever a control wishes to notify its container that some action (determined by the control developer) has happened (such as a keystroke, mouse click, or a change to the control's state) it calls an event-firing function. This function notifies the control container that some important action has occurred by firing the related event.

The Microsoft Foundation Class Library offers a programming model optimized for firing events. In this model, "event maps" are used to designate which functions fire which events for a particular control. Event maps contain one macro for each event. For example, an event map that fires a stock Click event might look like this:

BEGIN_EVENT_MAP(CSampleCtrl, COleControl)
   //{{AFX_EVENT_MAP(CSampleCtrl)
   EVENT_STOCK_CLICK( )
   //}}AFX_EVENT_MAP
END_EVENT_MAP()

The EVENT_STOCK_CLICK macro indicates that the control will fire a stock Click event every time it detects a mouse click. For a more detailed listing of other stock events, see the article ActiveX Controls: Events in Visual C++ Programmer's Guide. Macros are also available to indicate custom events.

Although event-map macros are important, you generally don't insert them directly. This is because ClassWizard automatically creates event-map entries in your source files when you use it to associate event-firing functions with events. Any time you want to edit or add an event-map entry, you can use ClassWizard.

To support event maps, MFC provides the following macros:

Event Map Declaration and Demarcation

DECLARE_EVENT_MAP | Declares that an event map will be used in a class to map events to event-firing functions (must be used in the class declaration).
BEGIN_EVENT_MAP | Begins the definition of an event map (must be used in the class implementation).
END_EVENT_MAP | Ends the definition of an event map (must be used in the class implementation).

Event Mapping Macros

EVENT_CUSTOM | Indicates which event-firing function will fire the specified event.
EVENT_CUSTOM_ID | Indicates which event-firing function will fire the specified event, with a designated dispatch ID.

Message Mapping Macros

ON_OLEVERB | Indicates a custom verb handled by the OLE control.
ON_STDOLEVERB | Overrides a standard verb mapping of the OLE control.


Event Sink Maps

When an embedded OLE control fires an event, the control's container receives the event using a mechanism, called an "event sink map," supplied by MFC. This event sink map designates handler functions for each specific event, as well as parameters of those events. For more information on event sink maps, see the article ActiveX Control Containers in Visual C++ Programmer's Guide.

Event Sink Maps

BEGIN_EVENTSINK_MAP | Starts the definition of an event sink map.
DECLARE_EVENTSINK_MAP | Declares an event sink map.
END_EVENTSINK_MAP | Ends the definition of an event sink map.
ON_EVENT | Defines an event handler for a specific event.
ON_EVENT_RANGE | Defines an event handler for a specific event fired from a set of OLE controls.
ON_EVENT_REFLECT | Receives events fired by the control before they are handled by the control's container.
ON_PROPNOTIFY | Defines a handler for handling property notifications from an OLE control.
ON_PROPNOTIFY_RANGE | Defines a handler for handling property notifications from a set of OLE controls.
ON_PROPNOTIFY_REFLECT | Receives property notifications sent by the control before they are handled by the control's container.


Connection Maps

OLE controls are able to expose interfaces to other applications. These interfaces only allow access from a container into that control. If an OLE control wants to access external interfaces of other OLE objects, a connection point must be established. This connection point allows a control outgoing access to external dispatch maps, such as event maps or notification functions.

The Microsoft Foundation Class Library offers a programming model that supports connection points. In this model, "connection maps" are used to designate interfaces (or connection points) for the OLE control. Connection maps contain one macro for each connection point. For more information on connection maps, see the CConnectionPoint class.

Typically, a control will support just two connection points: one for events and one for property notifications. These are implemented by the COleControl base class and require no additional work by the control writer. Any additional connection points you wish to implement in your class must be added by hand. To support connection maps and points, MFC provides the following macros:

Connection Map Declaration and Demarcation

BEGIN_CONNECTION_PART | Declares an embedded class that implements an additional connection point (must be used in the class declaration).
END_CONNECTION_PART | Ends the declaration of a connection point (must be used in the class declaration).
CONNECTION_IID | Specifies the interface ID of the control's connection point.
DECLARE_CONNECTION_MAP | Declares that a connection map will be used in a class (must be used in the class declaration).
BEGIN_CONNECTION_MAP | Begins the definition of a connection map (must be used in the class implementation).
END_CONNECTION_MAP | Ends the definition of a connection map (must be used in the class implementation).
CONNECTION_PART | Specifies a connection point in the control's connection map.

The following functions assist a sink in establishing and disconnecting a connection using connection points:

Initialization/Termination of Connection Points

AfxConnectionAdvise | Establishes a connection between a source and a sink.
AfxConnectionUnadvise | Breaks a connection between a source and a sink.


Registering OLE Controls

OLE controls, like other OLE server objects, can be accessed by other OLE-aware applications. This is achieved by registering the control's type library and class.

The following functions allow you to add and remove the control's class, property pages, and type library in the Windows registration database:

Registering OLE Controls

AfxOleRegisterControlClass | Adds the control's class to the registration database.
AfxOleRegisterPropertyPageClass | Adds a control property page to the registration database.
AfxOleRegisterTypeLib | Adds the control's type library to the registration database.
AfxOleUnregisterClass | Removes a control class or a property page class from the registration database.
AfxOleUnregisterTypeLib | Removes the control's type library from the registration database.

AfxOleRegisterTypeLib is typically called in a control DLL's implementation of DllRegisterServer. Similarly, AfxOleUnregisterTypeLib is called by DllUnregisterServer. AfxOleRegisterControlClass, AfxOleRegisterPropertyPageClass, and AfxOleUnregisterClass are typically called by the UpdateRegistry member function of a control's class factory or property page.


Class Factories and Licensing

To create an instance of your OLE control, a container application calls a member function of the control's class factory. Because your control is an actual OLE object, the class factory is responsible for creating instances of your control. Every OLE control class must have a class factory.

Another important feature of OLE controls is their ability to enforce a license. ControlWizard allows you to incorporate licensing during the creation of your control project. For more information on control licensing, see the article ActiveX Controls: Licensing An ActiveX Control in Visual C++ Programmer's Guide.

The following table lists several macros and functions used to declare and implement your control's class factory and for licensing of your control.

Class Factories and Licensing

DECLARE_OLECREATE_EX | Declares the class factory for an OLE control or property page.
IMPLEMENT_OLECREATE_EX | Implements the control's GetClassID function and declares an instance of the class factory.
BEGIN_OLEFACTORY | Begins the declaration of any licensing functions.
END_OLEFACTORY | Ends the declaration of any licensing functions.
AfxVerifyLicFile | Verifies whether a control is licensed for use on a particular computer.


Persistence of OLE Controls

One capability of OLE controls is property persistence (or serialization), which allows the OLE control to read or write property values to and from a file or stream. A container application can use serialization to store a control's property values even after the application has destroyed the control. The property values of the OLE control can then be read from the file or stream when a new instance of the control is created at a later time.

Persistence of OLE Controls

PX_Blob | Exchanges a control property that stores binary-large object (BLOB) data.
PX_Bool | Exchanges a control property of type BOOL.
PX_Color | Exchanges a color property of a control.
PX_Currency | Exchanges a control property of type CY.
PX_DataPath | Exchanges a control property of type CDataPathProperty.
PX_Double | Exchanges a control property of type double.
PX_Font | Exchanges a font property of a control.
PX_Float | Exchanges a control property of type float.
PX_IUnknown | Exchanges a control property of undefined type.
PX_Long | Exchanges a control property of type long.
PX_Picture | Exchanges a picture property of a control.
PX_Short | Exchanges a control property of type short.
PX_ULong | Exchanges a control property of type ULONG.
PX_UShort | Exchanges a control property of type USHORT.
PX_String | Exchanges a character string control property.
PX_VBXFontConvert | Exchanges a VBX control's font-related properties into an OLE control font property.

In addition, the AfxOleTypeMatchGuid global function is provided to test for a match between a TYPEDESC and a given GUID.


Internet Server API (ISAPI) Parse Maps

The Internet Server API, an extended open API set, provides you with the ability to create add-ons for, and run internet server applications on, your Microsoft Internet Information Server. When a client sends a query to the internet server, the server processes the query by sending it through a series of parsing macros in the "parse map." The parse map maps the client queries to a CHttpServer-derived class's functions and parameters.

ISAPI Parse Maps

BEGIN_PARSE_MAP | Starts the definition of a parse map.
ON_PARSE_COMMAND | Parses the client's command
ON_PARSE_COMMAND_PARAMS | Defines a command to an CHttpServer object from a client.
DEFAULT_PARSE_COMMAND | Calls the default page that's identified by the FnName parameter.
END_PARSE_MAP | Ends the definition of a parse map.


Internet URL Parsing Globals

The Internet Server API, an extended open API set, provides you with the ability to create add-ons for, and run internet server applications on, your Microsoft Internet Information Server. When a client sends a query to the internet server, you can use one of the URL parsing globals to extract information about the client.

Internet URL Parsing Globals

AfxParseURL | Parses a URL string and returns the type of service and its components.
AfxParseURLEx | Parses a URL string and returns the type of service and its components, as well as providing the user's name and password.


Internet Server API (ISAPI) Diagnostic Macros

The Microsoft Internet Information Server requires the same diagnostic services that MFC programs need; however, the programs written for the Internet Server don't require MFC. The ISAPI macros described below provide the same level of debugging functionality for both MFC programs and programs not written with MFC.

ISAPI Diagnostic Macros

ISAPIASSERT | Provides ASSERT functionality.
ISAPITRACE | Provides TRACE functionality.
ISAPITRACE0 | Provides TRACE0 functionality.
ISAPITRACE1 | Provides TRACE1 functionality.
ISAPITRACE2 | Provides TRACE2 functionality.
ISAPITRACE3 | Provides TRACE3 functionality.
ISAPIVERIFY | Provides VERIFY functionality.


Macros, Global Functions, and Global Variables

The topics in this section provide descriptions of the global functions, global variables, and macros in the MFC library.

Note Many global functions start with the prefix "Afx" — but some, such as the dialog data exchange (DDX) functions and many of the database functions, deviate from this convention. All global variables start with the prefix "afx". Macros do not start with any particular prefix, but they are written all in uppercase.

The MFC library and the Active Template library (ATL) share string conversion macros. See String Conversion Macros in the ATL documentation for a discussion of these macros.

For information on the debug version of the C run-time library and diagnostic functions, see Debug Routines, in the Run-Time Library Reference.


AfxAbort

void AfxAbort( );

Remarks

The default termination function supplied by MFC. AfxAbort is called internally by MFC member functions when there is a fatal error, such as an uncaught exception that cannot be handled. You can call AfxAbort in the rare case when you encounter a catastrophic error from which you cannot recover.


AfxBeginThread

CWinThread* AfxBeginThread( AFX_THREADPROC pfnThreadProc, LPVOID pParam, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );

CWinThread* AfxBeginThread( CRuntimeClass* pThreadClass, int nPriority = THREAD_PRIORITY_NORMAL, UINT nStackSize = 0, DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );

Return Value

Pointer to the newly created thread object.

Parameters

pfnThreadProc

Points to the controlling function for the worker thread. Cannot be NULL. This function must be declared as follows:

UINT MyControllingFunction( LPVOID pParam );

pThreadClass

The RUNTIME_CLASS of an object derived from CWinThread.

pParam

Parameter to be passed to the controlling function as shown in the parameter to the function declaration in pfnThreadProc.

nPriority

The desired priority of the thread. If 0, the same priority as the creating thread will be used. For a full list and description of the available priorities, see SetThreadPriority in the Win32 Programmer’s Reference.

nStackSize

Specifies the size in bytes of the stack for the new thread. If 0, the stack size defaults to the same size stack as the creating thread.

dwCreateFlags

Specifies an additional flag that controls the creation of the thread. This flag can contain one of two values:

  • CREATE_SUSPENDED Start the thread with a suspend count of one. The thread will not execute until ResumeThread is called.

  • 0 Start the thread immediately after creation.

lpSecurityAttrs

Points to a SECURITY_ATTRIBUTES structure that specifies the security attributes for the thread. If NULL, the same security attributes as the creating thread will be used. For more information on this structure, see the Win32 Programmer’s Reference.

Remarks

Call this function to create a new thread. The first form of AfxBeginThread creates a worker thread. The second form creates a user-interface thread.

AfxBeginThread creates a new CWinThread object, calls its CreateThread function to start executing the thread, and returns a pointer to the thread. Checks are made throughout the procedure to make sure all objects are deallocated properly should any part of the creation fail. To end the thread, call AfxEndThread from within the thread, or return from the controlling function of the worker thread.

For more information on AfxBeginThread, see the articles Multithreading: Creating Worker Threads and Multithreading: Creating User-Interface Threads in Visual C++ Programmer’s Guide.

See Also AfxGetThread


AfxCheckError

void AFXAPI AfxCheckError( SCODE sc );
throw CMemoryException*
throw COleException*

Remarks

This function tests the passed SCODE to see if it is an error. If it is an error, the function throws an exception. If the passed SCODE is E_OUTOFMEMORY, the function throws a CMemoryException by calling AfxThrowMemoryException. Otherwise, the function throws a COleException by calling AfxThrowOleException.

This function can be used to check the return values of calls to OLE functions in your application. By testing the return value with this function in your application, you can properly react to error conditions with a minimal amount of code.

Note This function has the same effect in debug and non-debug builds.

Example

LPDISPATCH pDisp = NULL;
AfxCheckError(CoCreateInstance(CLSID,
 NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch,
 (LPVOID) &pDisp));
// if there was an error, an exception has already been thrown
// we can start using the returned pointer
COleDispatchDriver disp(pDisp);
// and so on...


AfxCheckMemory

BOOL AfxCheckMemory( );

Return Value

Nonzero if no memory errors; otherwise 0.

Remarks

This function validates the free memory pool and prints error messages as required. If the function detects no memory corruption, it prints nothing.

All memory blocks currently allocated on the heap are checked, including those allocated by new but not those allocated by direct calls to underlying memory allocators, such as the malloc function or the GlobalAlloc Windows function. If any block is found to be corrupted, a message is printed to the debugger output.

If you include the line

#define new DEBUG_NEW

in a program module, then subsequent calls to AfxCheckMemory show the filename and line number where the memory was allocated.

Note If your module contains one or more implementations of serializable classes, then you must put the #define line after the last IMPLEMENT_SERIAL macro call.

This function works only in the Debug version of MFC.

Example

// example for AfxCheckMemory
CAge* pcage = new CAge( 21 );  // CAge is derived from CObject.
Age* page = new Age( 22 );     // Age is NOT derived from CObject.
*(((char*) pcage) - 1) = 99;   // Corrupt preceding guard byte
*(((char*) page) - 1) = 99;    // Corrupt preceding guard byte
AfxCheckMemory();

The results from the program are as follows:

memory check error at $0067495F = $63, should be $FD
DAMAGE: before Non-Object block at $00674960
Non-Object allocated at file test02.cxx(48)
Non-Object located at $00674960 is 2 bytes long
memory check error at $00674905 = $63, should be $FD
DAMAGE: before Object block at $00674906
Object allocated at file test02.cxx(47)
Object located at $00674906 is 6 bytes long


AfxConnectionAdvise

BOOL AFXAPI AfxConnectionAdvise( LPUNKNOWN pUnkSrc, REFIID iid, LPUNKNOWN pUnkSink, BOOL bRefCount, DWORD FAR* pdwCookie );

Return Value

Nonzero if a connection was established; otherwise 0.

Parameters

pUnkSrc

A pointer to the object that calls the interface.

pUnkSink

A pointer to the object that implements the interface.

iid

The interface ID of the connection.

bRefCount

TRUE indicates that creating the connection should cause the reference count of pUnkSink to be incremented. FALSE indicates that the reference count should not be incremented.

pdwCookie

A pointer to a DWORD where a connection identifier is returned. This value should be passed as the dwCookie parameter to AfxConnectionUnadvise when disconnecting the connection.

Remarks

Call this function to establish a connection between a source, specified by pUnkSrc, and a sink, specified by pUnkSink.

See Also AfxConnectionUnadvise


AfxConnectionUnadvise

BOOL AFXAPI AfxConnectionUnadvise( LPUNKNOWN pUnkSrc, REFIID iid, LPUNKNOWN pUnkSink, BOOL bRefCount, DWORD dwCookie );

Return Value

Nonzero if a connection was disconnected; otherwise 0.

Parameters

pUnkSrc

A pointer to the object that calls the interface.

pUnkSink

A pointer to the object that implements the interface.

iid

The interface ID of the connection point interface.

bRefCount

TRUE indicates that disconnecting the connection should cause the reference count of pUnkSink to be decremented. FALSE indicates that the reference count should not be decremented.

dwCookie

The connection identifier returned by AfxConnectionAdvise.

Remarks

Call this function to disconnect a connection between a source, specified by pUnkSrc, and a sink, specified by pUnkSink.

See Also AfxConnectionAdvise


AfxDaoInit

void AfxDaoInit( );
throw( CDaoException );

Remarks

This function initializes the DAO database engine. In most cases, you don't need to call AfxDaoInit because the application automatically calls it when it is needed.

For related information, and for an example of calling AfxDaoInit, see Technical Note 54.

See Also AfxDaoTerm


AfxDaoTerm

void AfxDaoTerm( );

Remarks

This function terminates the DAO database engine. Typically, you only need to call this function in a regular DLL; an application will automatically call AfxDaoTerm when it is needed.

In regular DLLs, call AfxDaoTerm before the ExitInstance function, but after all MFC DAO objects have been destroyed.

For more information about calling AfxDaoTerm, see the article DAO: Using DAO in DLLs in Visual C++ Programmer’s Guide. For related information, see Technical Note 54.

See Also AfxDaoInit


AfxDbInitModule

void AFXAPI AfxDbInitModule( );

#include <afxdll_.h>

For MFC database (or DAO) support from a regular DLL that is dynamically linked to MFC, add a call to this function in your regular DLL's CWinApp::InitInstance function to initialize the MFC database DLL. Make sure this call occurs before any base-class call or any added code which accesses the MFC database DLL.The MFC database DLL is an extension DLL; in order for an extension DLL to get wired into a CDynLinkLibrary chain, it must create a CDynLinkLibrary object in the context of every module that will be using it. AfxDbInitModule creates the CDynLinkLibrary object in your regular DLL's context so that it gets wired into the CDynLinkLibrary object chain of the regular DLL.


AfxDoForAllClasses

void AFXAPI AfxDoForAllClasses( void (*pfn)(const CRuntimeClass* pClass, void* pContext), void* pContext );

Parameters

pfn

Points to an iteration function to be called for each class. The function arguments are a pointer to a CRuntimeClass object and a void pointer to extra data that the caller supplies to the function.

pContext

Points to optional data that the caller can supply to the iteration function. This pointer can be NULL.

Remarks

Calls the specified iteration function for all serializable CObject-derived classes in the application's memory space. Serializable CObject-derived classes are classes derived using the DECLARE_SERIAL macro. The pointer that is passed to AfxDoForAllClasses in pContext is passed to the specified iteration function each time it is called.

Note This function works only in the Debug version of MFC.

See Also DECLARE_SERIAL


AfxDoForAllObjects

void AfxDoForAllObjects( void (*pfn)(CObject* pObject, void* pContext), void* pContext );

Parameters

pfn

Points to an iteration function to execute for each object. The function arguments are a pointer to a CObject and a void pointer to extra data that the caller supplies to the function.

pContext

Points to optional data that the caller can supply to the iteration function. This pointer can be NULL.

Remarks

Executes the specified iteration function for all objects derived from CObject that have been allocated with new. Stack, global, or embedded objects are not enumerated. The pointer passed to AfxDoForAllObjects in pContext is passed to the specified iteration function each time it is called.

Note This function works only in the Debug version of MFC.


afxDump

CDumpContext afxDump;

Remarks

Use this variable to provide basic object-dumping capability in your application. afxDump is a predefined CDumpContext object that allows you to send CDumpContext information to the debugger output window or to a debug terminal. Typically, you supply afxDump as a parameter to CObject::Dump.

Under Windows NT and Windows 95 (and earlier versions of Windows), afxDump output is sent to the Output-Debug window of Visual C++ when you debug your application.

This variable is defined only in the Debug version of MFC. For more information on afxDump, see MFC Debugging Support in Visual C++ Programmer’s Guide. Technical Note 7 and Technical Note 12 contain additional information.

Note This function works only in the Debug version of MFC.

Example

// example for afxDump
CPerson myPerson = new CPerson;
// set some fields of the CPerson object...
//..
// now dump the contents
#ifdef _DEBUG
afxDump << "Dumping myPerson:\n";
myPerson->Dump( afxDump );
afxDump << "\n";
#endif

See Also CObject::Dump, AfxDump


AfxDump

void AfxDump( const CObject* pOb );

Parameters

pOb

A pointer to an object of a class derived from CObject.

Remarks

Call this function while in the debugger to dump the state of an object while debugging. AfxDump calls an object’s Dump member function and sends the information to the location specified by the afxDump variable. AfxDump is available only in the Debug version of MFC.

Your program code should not call AfxDump, but should instead call the Dump member function of the appropriate object.

See Also CObject::Dump, afxDump


AfxDumpStack

void AFXAPI AfxDumpStack(DWORD dwTarget = AFX_STACK_DUMP_TARGET_DEFAULT);

Parameters

dwTarget

Indicates the target of the dump output. Possible values, which can be combined using the bitwise-OR (|) operator, are as follows:

  • AFX_STACK_DUMP_TARGET_TRACE Sends output via the TRACE macro. The TRACE macro generates output in debug builds only; it generates no output in release builds. Also, TRACE can be redirected to other targets besides the debugger.

  • AFX_STACK_DUMP_TARGET_DEFAULT Sends dump output to the default target. For a debug build, output goes to the TRACE macro. In a release build, output goes to the Clipboard.

  • AFX_STACK_DUMP_TARGET_CLIPBOARD Sends output to the Clipboard only. The data is placed on the Clipboard as plain text using the CF_TEXT Clipboard format.

  • AFX_STACK_DUMP_TARGET_BOTH Sends output to the Clipboard and to the TRACE macro, simultaneously.

  • AFX_STACK_DUMP_TARGET_ODS Sends output directly to the debugger via the Win32 function OutputDebugString(). This option will generate debugger output in both debug and release builds when a debugger is attached to the process. AFX_STACK_DUMP_TARGET_ODS always reaches the debugger (if it is attached) and cannot be redirected.

Remarks

This global function can be used to generate an image of the current stack. The example below reflects a single line of the output generated from calling AfxDumpStack from a button handler in an MFC dialog applicaton:

=== begin AfxDumpStack output ===
…
BFF928E0: WINDOWS\SYSTEM\KERNEL32.DLL! UTUnRegister + 2492 bytes

=== end AfxDumpStack() output ===

The following table describes the above line of output:

Output | Description
BFF928E0: | The return address of the last function call.
WINDOWS\SYSTEM\KERNEL32.DLL! | The full path name of the module that contains the function call.
UTUnRegister | The function prototype called.
+ 2492 bytes | The offset in bytes from the address of the function prototype (in this case, UTUnRegister) to the return address (in this case, BFF928E0).

AfxDumpStack is available in debug and nondebug versions of the MFC libraries; however, the function is always linked statically, even when your executable file uses MFC in a shared DLL. In shared-library implementations, the function is found in the MFCS42.LIB library (and its variants).

To use this function successfully:

  • The file IMAGEHLP.DLL must be on your path. If you do not have this DLL, the function will display an error message. IMAGEHLP.DLL is a redistributable DLL that ships with the Win32 SDK, and with Windows. Look for it in C:\[windows]\system[32]. See Portable Executable File Manipulation for an introduction to the function set provided by IMAGEHLP.

  • The modules that have frames on the stack must include debugging information. If they do not contain debugging information, the function will still generate a stack trace, but the trace will be less detailed.

See Also afxDump


AfxEnableControlContainer

void AfxEnableControlContainer( );

Remarks

Call this function in your application object's InitInstance function to enable support for containment of OLE controls.

For more information about OLE controls (now called ActiveX controls), see ActiveX Control Topics in the Visual C++ Programmer's Guide.


AfxEnableMemoryTracking

BOOL AfxEnableMemoryTracking( BOOL bTrack );

Return Value

The previous setting of the tracking-enable flag.

Parameters

bTrack

Setting this value to TRUE turns on memory tracking; FALSE turns it off.

Remarks

Diagnostic memory tracking is normally enabled in the Debug version of MFC. Use this function to disable tracking on sections of your code that you know are allocating blocks correctly.

For more information on AfxEnableMemoryTracking, see MFC Debugging Support in Visual C++ Programmer’s Guide.

Note This function works only in the Debug version of MFC.


AfxEndThread

void AfxEndThread( UINT nExitCode );

Parameters

nExitCode

Specifies the exit code of the thread.

Remarks

Call this function to terminate the currently executing thread. Must be called from within the thread to be terminated.

For more information on AfxEndThread, see the article Multithreading: Terminating Threads in Visual C++ Programmer’s Guide.

See Also AfxBeginThread


AFX_EXT_CLASS

Remarks

Extension DLLs use the macro AFX_EXT_CLASS to export classes; the executables that link to the extension DLL use the macro to import classes. With the AFX_EXT_CLASS macro, the same header file(s) used to build the extension DLL can be used with the executables that link to the DLL.

In the header file for your DLL, add the AFX_EXT_CLASS keyword to the declaration of your class as follows:

class AFX_EXT_CLASS CMyClass : public CDocument
{
// <body of class>
};

For more information, see Export and Import Using AFX_EXT_CLASS.


AfxFormatString1

void AfxFormatString1( CString& rString, UINT nIDS, LPCTSTR lpsz1 );

Parameters

rString

A reference to a CString object that will contain the resultant string after the substitution is performed.

nIDS

The resource ID of the template string on which the substitution will be performed.

lpsz1

A string that will replace the format characters “%1” in the template string.

Remarks

Loads the specified string resource and substitutes the characters "%1" for the string pointed to by lpsz1. The newly formed string is stored in rString. For example, if the string in the string table is "File %1 not found", and lpsz1 is equal to "C:\MYFILE.TXT", then rString will contain the string “File C:\MYFILE.TXT not found”. This function is useful for formatting strings sent to message boxes and other windows.

If the format characters "%1" appear in the string more than once, multiple substitutions will be made.

See Also AfxFormatString2


AfxFormatString2

void AfxFormatString2( CString& rString, UINT nIDS, LPCTSTR lpsz1, LPCTSTR lpsz2 );

Parameters

rString

A reference to the CString that will contain the resultant string after the substitution is performed.

nIDS

The string table ID of the template string on which the substitution will be performed.

lpsz1

A string that will replace the format characters "%1" in the template string.

lpsz2

A string that will replace the format characters "%2" in the template string.

Remarks

Loads the specified string resource and substitutes the characters "%1" and "%2" for the strings pointed to by lpsz1 and lpsz2. The newly formed string is stored in rString. For example, if the string in the string table is "File %1 not found in directory %2", lpsz1 points to "MYFILE.TXT", and lpsz2 points to "C:\MYDIR", then rString will contain the string "File MYFILE.TXT not found in directory C:\MYDIR"

If the format characters "%1" or "%2" appear in the string more than once, multiple substitutions will be made. They do not have to be in numerical order.

See Also AfxFormatString1


AfxFreeLibrary

BOOL AFXAPI AfxFreeLibrary( HINSTANCE hInstLib );

Return Value

TRUE if the function succeeds; otherwise, FALSE.

Parameters

hInstLib

A handle of the loaded library module. AfxLoadLibrary returns this handle.

Remarks

Both AfxFreeLibrary and AfxLoadLibrary maintain a reference count for each loaded library module. AfxFreeLibrary decrements the reference count of the loaded dynamic-link library (DLL) module. When the reference count reaches zero, the module is unmapped from the address space of the calling process and the handle is no longer valid. This reference count is incremented each time AfxLoadLibrary is called.

Before unmapping a library module, the system enables the DLL to detach from the processes using it. Doing so gives the DLL an opportunity to clean up resources allocated on behalf of the current process. After the entry-point function returns, the library module is removed from the address space of the current process.

Use AfxLoadLibrary to map a DLL module.

Be sure to use AfxFreeLibrary and AfxLoadLibrary (instead of the Win32 functions FreeLibrary and LoadLibrary) if your application uses multiple threads. Using AfxLoadLibrary and AfxFreeLibrary ensures that the startup and shutdown code that executes when the extension DLL is loaded and unloaded does not corrupt the global MFC state.

See Also AfxLoadLibrary


AfxGetApp

CWinApp* AfxGetApp( );

Return Value

A pointer to the single CWinApp object for the application.

Remarks

The pointer returned by this function can be used to access application information such as the main message-dispatch code or the topmost window.


AfxGetAppName

LPCTSTR AfxGetAppName( );

Return Value

A null-terminated string containing the application’s name.

Remarks

The string returned by this function can be used for diagnostic messages or as a root for temporary string names.


AfxGetHENV

HENV AFXAPI AfxGetHENV( );

Return Value

The handle to the ODBC environment currently in use by MFC. Can be SQL_HENV_NULL if there are no CDatabase objects and no CRecordset objects in use.

Remarks

You can use the returned handle in direct ODBC calls, but you must not close the handle or assume that the handle is still valid and available after any existing CDatabase- or CRecordset-derived objects have been destroyed.


AfxGetInstanceHandle

HINSTANCE AfxGetInstanceHandle( );

Return Value

An HINSTANCE to the current instance of the application. If called from within a DLL linked with the USRDLL version of MFC, an HINSTANCE to the DLL is returned.

Remarks

This function allows you to retrieve the instance handle of the current application. AfxGetInstanceHandle always returns the HINSTANCE of your executable file (.EXE) unless it is called from within a DLL linked with the USRDLL version of MFC. In this case, it returns an HINSTANCE to the DLL.

See Also AfxGetResourceHandle, AfxSetResourceHandle


AfxGetInternetHandleType

DWORD AFXAPI AfxGetInternetHandleType( HINTERNET hQuery );

Return Value

Any of the Internet service types defined by WININET.H. See the Remarks section for a list of these Internet services. If the handle is NULL or not recognized, the function returns AFX_INET_SERVICE_UNK.

Parameters

hQuery

A handle to an Internet query.

Remarks

Use this global function to determine the type of an Internet handle.

The following list includes possible Internet types returned by AfxGetInternetHandleType.

  • INTERNET_HANDLE_TYPE_INTERNET

  • INTERNET_HANDLE_TYPE_CONNECT_FTP

  • INTERNET_HANDLE_TYPE_CONNECT_GOPHER

  • INTERNET_HANDLE_TYPE_CONNECT_HTTP

  • INTERNET_HANDLE_TYPE_FTP_FIND

  • INTERNET_HANDLE_TYPE_FTP_FIND_HTML

  • INTERNET_HANDLE_TYPE_FTP_FILE

  • INTERNET_HANDLE_TYPE_FTP_FILE_HTML

  • INTERNET_HANDLE_TYPE_GOPHER_FIND

  • INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML

  • INTERNET_HANDLE_TYPE_GOPHER_FILE

  • INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML

  • INTERNET_HANDLE_TYPE_HTTP_REQUEST

Note In order to call this function, your project must include AFXINET.H.

See Also AfxParseURL


AfxGetMainWnd

CWnd* AfxGetMainWnd( );

Return Value

If the server has an object that is in-place active inside a container, and this container is active, this function returns a pointer to the frame window object that contains the in-place active document.

If there is no object that is in-place active within a container, or your application is not an OLE server, this function simply returns the m_pMainWnd of your application object.

If AfxGetMainWnd is called from the application's primary thread, it returns the application's main window according to the above rules. If the function is called from a secondary thread in the application, the function returns the main window associated with the thread that made the call.

Remarks

If your application is an OLE server, call this function to retrieve a pointer to the active main window of the application instead of directly referring to the m_pMainWnd member of the application object.

If your application is not an OLE server, then calling this function is equivalent to directly referring to the m_pMainWnd member of your application object.

See Also CWinThread::m_pMainWnd


AfxGetResourceHandle

HINSTANCE AfxGetResourceHandle( );

Return Value

An HINSTANCE handle where the default resources of the application are loaded.

Remarks

Use the HINSTANCE handle returned by this function to access the application’s resources directly, for example, in calls to the Windows function FindResource.

See Also AfxGetInstanceHandle, AfxSetResourceHandle


AfxGetStaticModuleState

AFX_MODULE_STATE* AFXAPI AfxGetStaticModuleState( );

Return Value

A pointer to an AFX_MODULE_STATE structure.

Remarks

Call this function to set the module state before initialization and/or to restore the previous module state after cleanup. The AFX_MODULE_STATE structure contains global data for the module, that is, the portion of the module state that is pushed or popped.

By default, MFC uses the resource handle of the main application to load the resource template. If you have an exported function in a DLL, such as one that launches a dialog box in the DLL, this template is actually stored in the DLL module. You need to switch the module state for the correct handle to be used. You can do this by adding the following code to the beginning of the function:

AFX_MANAGE_STATE(AfxGetStaticModuleState( ));

This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope.

For more information on module states and MFC, see "Managing the State Data of MFC Modules" in Creating New Documents, Windows, and Views in Visual C++ Programmer’s Guide and Technical Note 58.

See Also AFX_MANAGE_STATE


AfxGetThread

CWinThread* AfxGetThread( );

Return Value

Pointer to the currently executing thread.

Remarks

Call this function to get a pointer to the CWinThread object representing the currently executing thread. Must be called from within the desired thread.

See Also AfxBeginThread


AfxInitExtensionModule

BOOL AFXAPI AfxInitExtensionModule( AFX_EXTENSION_MODULE& state, HMODULE hModule );

Return Value

TRUE if the extension DLL is successfully initialized; otherwise, FALSE.

Parameters

state

A reference to the AFX_EXTENSION_MODULE structure that will contain the state of extension DLL module after the initialization. The state includes a copy of the runtime class objects that have been initialized by the extension DLL as part of normal static object construction executed before DllMain is entered.

hModule

A handle of the extension DLL module.

Remarks

Call this function in an extension DLL's DllMain to initialize the DLL. For example:

static AFX_EXTENSION_MODULE extensionDLL;
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
   if (dwReason == DLL_PROCESS_ATTACH)
   {
      // Extension DLL one-time initialization
      if (!AfxInitExtensionModule(extensionDLL, hInstance))
         return 0;
...

AfxInitExtensionModule makes a copy of the DLL's HMODULE and captures the DLL's runtime-classes (CRuntimeClass structures) as well as its object factories (COleObjectFactory objects) for use later when the CDynLinkLibrary object is created.

MFC extension DLLs need to do two things in their DllMain function:

  • Call AfxInitExtensionModule and check the return value.

  • Create a CDynLinkLibrary object if the DLL will be exporting CRuntimeClass objects or has its own custom resources.

You can call AfxTermExtensionModule to clean up the extension DLL when each process detaches from the extension DLL (which happens when the process exits, or when the DLL is unloaded as a result of an AfxFreeLibrary call).

See Also AfxTermExtensionModule


AfxInitRichEdit

BOOL AFXAPI AfxInitRichEdit( );

Remarks

Call this function to initialize the rich edit control for the application. It will also initialize the common controls library, if the library hasn’t already been initialized for the process. If you use the rich edit control directly from your MFC application, you should call this function to assure that MFC has properly initialized the rich edit control runtime. If you use rich edit via CRichEditCtrl, CRichEditView, or CRichEditDoc, you don't need to call this function.


AfxIsMemoryBlock

BOOL AfxIsMemoryBlock( const void* p, UINT nBytes, LONG* plRequestNumber = NULL );

Return Value

Nonzero if the memory block is currently allocated and the length is correct; otherwise 0.

Parameters

p

Points to the block of memory to be tested.

nBytes

Contains the length of the memory block in bytes.

plRequestNumber

Points to a long integer that will be filled in with the memory block’s allocation sequence number. The variable pointed to by plRequestNumber will only be filled in if AfxIsMemoryBlock returns nonzero.

Remarks

Tests a memory address to make sure it represents a currently active memory block that was allocated by the diagnostic version of new. It also checks the specified size against the original allocated size. If the function returns nonzero, the allocation sequence number is returned in plRequestNumber. This number represents the order in which the block was allocated relative to all other new allocations.

Example

// example for AfxIsMemoryBlock
CAge* pcage = new CAge( 21 ); // CAge is derived from CObject.
ASSERT( AfxIsMemoryBlock( pcage, sizeof( CAge ) ) )

See Also AfxIsValidAddress


AfxIsValidAddress

BOOL AfxIsValidAddress( const void* lp, UINT nBytes, BOOL bReadWrite = TRUE );

Return Value

Nonzero if the specified memory block is contained entirely within the program’s memory space; otherwise 0.

Parameters

lp

Points to the memory address to be tested.

nBytes

Contains the number of bytes of memory to be tested.

bReadWrite

Specifies whether the memory is both for reading and writing (TRUE) or just reading (FALSE).

Remarks

Tests any memory address to ensure that it is contained entirely within the program’s memory space. The address is not restricted to blocks allocated by new.

See Also AfxIsMemoryBlock, AfxIsValidString


AfxIsValidString

BOOL AfxIsValidString( LPCSTR lpsz, int nLength = -1 );

Return Value

Nonzero if the specified pointer points to a string of the specified size; otherwise 0.

Parameters

lpsz

The pointer to test.

nLength

Specifies the length of the string to be tested, in bytes. A value of –1 indicates that the string will be null-terminated.

Remarks

Use this function to determine whether a pointer to a string is valid.

See Also AfxIsMemoryBlock, AfxIsValidAddress


AfxLoadLibrary

HINSTANCE AFXAPI AfxLoadLibrary( LPCTSTR lpszModuleName );

Return Value

If the function succeeds, the return value is a handle to the module. If the function fails, the return value is NULL.

Parameters

lpszModuleName

Points to a null-terminated string that contains the name of the module (either a .DLL or .EXE file). The name specified is the filename of the module.

If the string specifies a path but the file does not exist in the specified directory, the function fails.

If a path is not specified and the filename extension is omitted, the default extension .DLL is appended. However, the filename string can include a trailing point character (.) to indicate that the module name has no extension. When no path is specified, the function searches for the file in the following sequence:

  • The directory from which the application loaded.

  • The current directory.

  • Windows 95: The Windows system directory. Windows NT: The 32-bit Windows system directory. The name of this directory is SYSTEM32.

  • Windows NT only: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.

  • The Windows directory.

  • The directories that are listed in the PATH environment variable.

Remarks

Use AfxLoadLibrary to map a DLL module. It returns a handle that can be used in GetProcAddress to get the address of a DLL function. AfxLoadLibrary can also be used to map other executable modules.

Each process maintains a reference count for each loaded library module. This reference count is incremented each time AfxLoadLibrary is called and is decremented each time AfxFreeLibrary is called. When the reference count reaches zero, the module is unmapped from the address space of the calling process and the handle is no longer valid.

Be sure to use AfxLoadLibrary and AfxFreeLibrary (instead of the Win32 functions LoadLibrary and FreeLibrary) if your application uses multiple threads. Using AfxLoadLibrary and AfxFreeLibrary insures that the startup and shutdown code that executes when the extension DLL is loaded and unloaded does not corrupt the global MFC state.

See Also AfxFreeLibrary


AFX_MANAGE_STATE

AFX_MANAGE_STATE( AFX_MODULE_STATE* pModuleState )

Parameters

pModuleState

A pointer to an AFX_MODULE_STATE structure.

Remarks

Call this macro to protect an exported function in a DLL. When this macro is invoked, pModuleState is the effective module state for the remainder of the immediate containing scope. Upon leaving the scope, the previous effective module state will be automatically restored.

The AFX_MODULE_STATE structure contains global data for the module, that is, the portion of the module state that is pushed or popped.

By default, MFC uses the resource handle of the main application to load the resource template. If you have an exported function in a DLL, such as one that launches a dialog box in the DLL, this template is actually stored in the DLL module. You need to switch the module state for the correct handle to be used. You can do this by adding the following code to the beginning of the function:

AFX_MANAGE_STATE(AfxGetStaticModuleState( ));

This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope.

For more information on module states and MFC, see "Managing the State Data of MFC Modules" in Creating New Documents, Windows, and Views in Visual C++ Programmer’s Guide and Technical Note 58.

See Also AfxGetStaticModuleState


afxMemDF

int afxMemDF;

Remarks

This variable is accessible from a debugger or your program and allows you to tune allocation diagnostics. It can have the following values as specified by the enumeration afxMemDF:

  • allocMemDF Turns on debugging allocator (default setting in Debug library).

  • delayFreeMemDF Delays freeing memory. While your program frees a memory block, the allocator does not return that memory to the underlying operating system. This will place maximum memory stress on your program.

  • checkAlwaysMemDF Calls AfxCheckMemory every time memory is allocated or freed. This will significantly slow memory allocations and deallocations.

Example

// example for afxMemDF
afxMemDF = allocMemDF | checkAlwaysMemDF;


AfxMessageBox

int AfxMessageBox( LPCTSTR lpszText, UINT nType = MB_OK, UINT nIDHelp = 0 );

int AFXAPI AfxMessageBox( UINT nIDPrompt, UINT nType = MB_OK, UINT nIDHelp = (UINT) -1 );

Return Value

Zero if there is not enough memory to display the message box; otherwise one of the following values is returned:

  • IDABORT The Abort button was selected.

  • IDCANCEL The Cancel button was selected.

  • IDIGNORE The Ignore button was selected.

  • IDNO The No button was selected.

  • IDOK The OK button was selected.

  • IDRETRY The Retry button was selected.

  • IDYES The Yes button was selected.

If a message box has a Cancel button, the IDCANCEL value will be returned if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing the ESC key has no effect.

The functions AfxFormatString1 and AfxFormatString2 can be useful in formatting text that appears in a message box.

Parameters

lpszText

Points to a CString object or null-terminated string containing the message to be displayed in the message box.

nType

The style of the message box. Apply any of the message-box styles to the box.

nIDHelp

The Help-context ID for the message; 0 indicates the application’s default Help context will be used.

nIDPrompt

A unique ID used to reference a string in the string table.

Remarks

Displays a message box on the screen. The first form of this overloaded function displays a text string pointed to by lpszText in the message box and uses nIDHelp to describe a Help context. The Help context is used to jump to an associated Help topic when the user presses the Help key (typically F1).

The second form of the function uses the string resource with the ID nIDPrompt to display a message in the message box. The associated Help page is found through the value of nIDHelp. If the default value of nIDHelp is used (– 1), the string resource ID, nIDPrompt, is used for the Help context. For more information about defining Help contexts, see the article Help Topics in Visual C++ Programmer’s Guide and Technical Note 28.

See Also CWnd::MessageBox


AfxNetInitModule

void AFXAPI AfxNetInitModule( );

#include <afxdll_.h>

Remarks

For MFC Sockets support from a regular DLL that is dynamically linked to MFC, add a call to this function in your regular DLL's CWinApp::InitInstance function to initialize the MFC Sockets DLL. The MFC Sockets DLL is an extension DLL; in order for an extension DLL to get wired into a CDynLinkLibrary chain, it must create a CDynLinkLibrary object in the context of every module that will be using it. AfxNetInitModule creates the CDynLinkLibrary object in your regular DLL’s context so that it gets wired into the CDynLinkLibrary object chain of the regular DLL.


AFX_ODBC_CALL

AFX_ODBC_CALL( SQLFunc )

Parameters

SQLFunc

An ODBC API function. For more information about ODBC API functions, see the ODBC SDK Programmer’s Reference.

Remarks

Use this macro to call any ODBC API function that may return SQL_STILL_EXECUTING. AFX_ODBC_CALL repeatedly calls the function until it no longer returns SQL_STILL_EXECUTING.

Before invoking AFX_ODBC_CALL, you must declare a variable, nRetCode, of type RETCODE. You can use CRecordset::Check to check the value of nRetCode after the macro call.

Note that the MFC ODBC classes now use only synchronous processing. In order to perform an asynchronous operation, you must call the ODBC API function SQLSetConnectOption. For more information, see the topic "Executing Functions Asynchronously" in the ODBC SDK Programmer's Reference.

Example

This example uses AFX_ODBC_CALL to call the SQLColumns ODBC API function, which returns a list of the columns in the table named by strTableName. Note the declaration of nRetCode and the use of recordset data members to pass parameters to the function. The example also illustrates checking the results of the call with Check, a member function of class CRecordset. The variable prs is a pointer to a CRecordset object, declared elsewhere.

// example for AFX_ODBC_CALL

RETCODE nRetCode;

AFX_ODBC_CALL( ::SQLColumns( prs->m_hstmt,
         (UCHAR *)NULL, SQL_NTS, (UCHAR *)NULL,
         SQL_NTS, (UCHAR *)(constchar*)strTableName,
         SQL_NTS, (UCHAR *)NULL, SQL_NTS ) );

if ( !prs->Check( nRetCode ) )
{
   AfxThrowDBException( nRetCode, prs->m_pdb,
                        prs->m_hstmt );
   TRACE( "SQLColumns failed\n" );
}

See Also AFX_SQL_ASYNC, AFX_SQL_SYNC


AfxOleCanExitApp

BOOL AFXAPI AfxOleCanExitApp( );

#include <afxdisp.h>

Return Value

Nonzero if the application can exit; otherwise 0.

Remarks

Indicates whether the application can terminate. An application should not terminate if there are outstanding references to its objects. The global functions AfxOleLockApp and AfxOleUnlockApp increment and decrement, respectively, a counter of references to the application’s objects. The application should not terminate when this counter is nonzero. If the counter is nonzero, the application’s main window is hidden (not destroyed) when the user chooses Close from the system menu or Exit from the File menu. The framework calls this function in CFrameWnd::OnClose.

See Also AfxOleLockApp, AfxOleUnlockApp


AfxOleGetMessageFilter

COleMessageFilter* AFXAPI AfxOleGetMessageFilter( );

#include <afxwin.h>

Return Value

A pointer to the current message filter.

Remarks

Retrieves the application’s current message filter. Call this function to access the current COleMessageFilter-derived object, just as you would call AfxGetApp to access the current application object.

Example

COleMessageFilter* pFilter = AfxOleGetMessageFilter();
ASSERT_VALID(pFilter);
pFilter->BeginBusyState();
// do things requiring a busy state
pFilter->EndBusyState();

See Also COleMessageFilter, AfxGetApp


AfxOleGetUserCtrl

BOOL AFXAPI AfxOleGetUserCtrl( );

#include <afxdisp.h>

Return Value

Nonzero if the user is in control of the application; otherwise 0.

Remarks

Retrieves the current user-control flag. The user is “in control” of the application when the user has explicitly opened or created a new document. The user is also in control if the application was not launched by the OLE system DLLs — in other words, if the user launched the application with the system shell.

See Also AfxOleSetUserCtrl


AfxOleInit

BOOL AFXAPI AfxOleInit( );

#include <afxdisp.h>

Return Value

Nonzero if successful; 0 if initialization fails, possibly because incorrect versions of the OLE system DLLs are installed.

Remarks

Initializes the OLE DLLs.


AfxOleInitModule

void AFXAPI AfxOleInitModule( );

#include <afxdll_.h>

Remarks

For OLE support from a regular DLL that is dynamically linked to MFC, call this function in your regular DLL's CWinApp::InitInstance function to initialize the MFC OLE DLL. The MFC OLE DLL is an extension DLL; in order for an extension DLL to get wired into a CDynLinkLibrary chain, it must create a CDynLinkLibrary object in the context of every module that will be using it. AfxOleInitModule creates the CDynLinkLibrary object in your regular DLL’s context so that it gets wired into the CDynLinkLibrary object chain of the regular DLL.

If you are building an OLE control and are using COleControlModule, you should not call AfxOleInitModule because the InitInstance member function for COleControlModule calls AfxOleInitModule.


AfxOleLockApp

void AFXAPI AfxOleLockApp( );

#include <afxdisp.h>

Remarks

Increments the framework’s global count of the number of active objects in the application.

The framework keeps a count of the number of objects active in an application. The AfxOleLockApp and AfxOleUnlockApp functions, respectively, increment and decrement this count.

When the user attempts to close an application that has active objects — an application for which the count of active objects is nonzero — the framework hides the application from the user’s view instead of completely shutting it down. The AfxOleCanExitApp function indicates whether the application can terminate.

Call AfxOleLockApp from any object that exposes OLE interfaces, if it would be undesirable for that object to be destroyed while still being used by a client application. Also call AfxOleUnlockApp in the destructor of any object that calls AfxOleLockApp in the constructor. By default, COleDocument (and derived classes) automatically lock and unlock the application.

See Also AfxOleUnlockApp, AfxOleCanExitApp, COleDocument


AfxOleLockControl

BOOL AFXAPI AfxOleLockControl( REFCLSID clsid );

BOOL AFXAPI AfxOleLockControl( LPCTSTR lpszProgID );

#include <afxwin.h>

Return Value

Nonzero if the class factory of the control was successfully locked; otherwise 0.

Parameters

clsid

The unique class ID of the control.

lpszProgID

The unique program ID of the control.

Remarks

Locks the class factory of the specified control so that dynamically created data associated with the control remains in memory. This can significantly speed up display of the controls. For example, once you create a control in a dialog box and lock the control with AfxOleLockControl, you do not need to create and kill it again every time the dialog is shown or destroyed. If the user opens and closes a dialog box repeatedly, locking your controls can significantly enhance performance. When you are ready to destroy the control, call AfxOleUnlockControl.

See Also AfxOleUnlockControl


AfxOleRegisterControlClass

BOOL AFXAPI AfxOleRegisterControlClass( HINSTANCE hInstance, REFCLSID clsid, LPCTSTR pszProgID, UINT idTypeName, UINT idBitmap, int nRegFlags, DWORD dwMiscStatus, REFGUID tlid, WORD wVerMajor, WORD wVerMinor );

#include <afxctl.h>

Return Value

Nonzero if the control class was registered; otherwise 0.

Parameters

hInstance

The instance handle of the module associated with the control class.

clsid

The unique class ID of the control.

pszProgID

The unique program ID of the control.

idTypeName

The resource ID of the string that contains a user-readable type name for the control.

idBitmap

The resource ID of the bitmap used to represent the OLE control in a toolbar or palette.

nRegFlags

Contains one or more of the following flags:

  • afxRegInsertable Allows the control to appear in the Insert Object dialog box for OLE objects.

  • afxRegApartmentThreading Sets the threading model in the registry to ThreadingModel=Apartment.

Note In MFC versions prior to MFC 4.2, the int nRegFlags parameter was a BOOL parameter, bInsertable, that allowed or disallowed the control to be inserted from the Insert Object dialog box.

dwMiscStatus

Contains one or more of the following status flags (for a description of the flags, see OLEMISC enumeration in the OLE Programmer's Reference):

  • OLEMISC_RECOMPOSEONRESIZE

  • OLEMISC_ONLYICONIC

  • OLEMISC_INSERTNOTREPLACE

  • OLEMISC_STATIC

  • OLEMISC_CANTLINKINSIDE

  • OLEMISC_CANLINKBYOLE1

  • OLEMISC_ISLINKOBJECT

  • OLEMISC_INSIDEOUT

  • OLEMISC_ACTIVATEWHENVISIBLE

  • OLEMISC_RENDERINGISDEVICEINDEPENDENT

  • OLEMISC_INVISIBLEATRUNTIME

  • OLEMISC_ALWAYSRUN

  • OLEMISC_ACTSLIKEBUTTON

  • OLEMISC_ACTSLIKELABEL

  • OLEMISC_NOUIACTIVATE

  • OLEMISC_ALIGNABLE

  • OLEMISC_IMEMODE

  • OLEMISC_SIMPLEFRAME

  • OLEMISC_SETCLIENTSITEFIRST

tlid

The unique ID of the control class.

wVerMajor

The major version number of the control class.

wVerMinor

The minor version number of the control class.

Remarks

Registers the control class with the Windows registration database. This allows the control to be used by containers that are OLE-control aware. AfxOleRegisterControlClass updates the registry with the control’s name and location on the system and also sets the threading model that the control supports in the registry. For more information, see Technical Note 64, "Apartment-Model Threading in OLE Controls," and About Processes and Threads in the Win32 SDK.

Example

// Member function implementation of class COleObjectFactory::UpdateRegistry
//
BOOL CMyApartmentAwareCtrl::CApartmentCtrlFactory::UpdateRegistry(BOOL bRegister)
{
// TODO: Verify that your control follows
// apartment-model threading rules.
// Refer to MFC TechNote 64 for more information.
// If your control does not conform to the
// apartment-model rules, then you must modify the
// code below, changing the 6th parameter from
// afxRegInsertable | afxRegApartmentThreading to
// afxRegInsertable.

   if (bRegister)
      return AfxOleRegisterControlClass()
         AfxGetInstanceHandle(),
         m_clsid,
         m_lpszProgID,
         IDS_APARTMENT,
         IDB_APARTMENT,
         afxRegInsertable | afxRegApartmentThreading,
         _dwApartmentOleMisc,
         _tlid,
         _wVerMajor,
         _wVerMinor);
   else
      return AfxOleUnregisterClass(m_clsid, m_lpszProgID);

The above example demonstrates how AfxOleRegisterControlClass is called with the flag for insertable and the flag for apartment model ORed together to create the sixth parameter:

   afxRegInsertable | afxRegApartmentThreading,

The control will show up in the Insert Object dialog box for enabled containers, and it will be apartment model-aware. Apartment model-aware controls must ensure that static class data is protected by locks, so that while a control in one apartment is accessing the static data, it isn’t disabled by the scheduler before it is finished, and another instance of the same class starts using the same static data. Any accesses to the static data will be surrounded by critical section code.

See Also AfxOleRegisterPropertyPageClass, AfxOleRegisterTypeLib, AfxOleUnregisterClass, AfxOleUnregisterTypeLib


AfxOleRegisterPropertyPageClass

BOOL AFXAPI AfxOleRegisterPropertyPageClass( HINSTANCE hInstance, REFCLSID clsid, UINT idTypeName, int nRegFlags )

#include <afxctl.h>

Return value

Nonzero if the control class was registered; otherwise 0.

Parameters

hInstance

The instance handle of the module associated with the property page class.

clsid

The unique class ID of the property page.

idTypeName

The resource ID of the string that contains a user-readable name for the property page.

nRegFlags

May contain the flag

  • afxRegApartmentThreading Sets the threading model in the registry to ThreadingModel = Apartment.

Note: In MFC versions prior to MFC 4.2, the int nRegFlags parameter was not available. Note also that the afxRegInsertable flag is not a valid option for property pages and will cause an ASSERT in MFC if it is set

Remarks

Registers the property page class with the Windows registration database. This allows the property page to be used by containers that are OLE-control aware. AfxOleRegisterPropertyPageClass updates the registry with the property page name and its location on the system and also sets the threading model that the control supports in the registry. For more information, see Technical Note 64, "Apartment-Model Threading in OLE Controls," and About Processes and Threads in the Win32 SDK.

See Also AfxOleRegisterControlClass, AfxOleRegisterTypeLib


AfxOleRegisterServerClass

BOOL AFXAPI AfxOleRegisterServerClass( REFCLSID clsid, LPCTSTR lpszClassName, LPCTSTR lpszShortTypeName, LPCTSTR lpszLongTypeName, OLE_APPTYPE nAppType = OAT_SERVER, LPCTSTR* rglpszRegister = NULL, LPCTSTR* rglpszOverwrite = NULL );

#include <afxdisp.h>

Return Value

Nonzero if the server class is successfully registered; otherwise 0.

Parameters

clsid

Reference to the server’s OLE class ID.

lpszClassName

Pointer to a string containing the class name of the server’s objects.

lpszShortTypeName

Pointer to a string containing the short name of the server’s object type, such as “Chart.”

lpszLongTypeName

Pointer to a string containing the long name of the server’s object type, such as “Microsoft Excel 5.0 Chart.”

nAppType

A value, taken from the OLE_APPTYPE enumeration, specifying the type of OLE application. Possible values are the following:

  • OAT_INPLACE_SERVER Server has full server user-interface.

  • OAT_SERVER Server supports only embedding.

  • OAT_CONTAINER Container supports links to embeddings.

  • OAT_DISPATCH_OBJECT IDispatch-capable object.

rglpszRegister

Array of pointers to strings representing the keys and values to be added to the OLE system registry if no existing values for the keys are found.

rglpszOverwrite

Array of pointers to strings representing the keys and values to be added to the OLE system registry if the registry contains existing values for the given keys.

Remarks

This function allows you to register your server in the OLE system registry. Most applications can use COleTemplateServer::Register to register the application’s document types. If your application’s system-registry format does not fit the typical pattern, you can use AfxOleRegisterServerClass for more control.

The registry consists of a set of keys and values. The rglpszRegister and rglpszOverwrite arguments are arrays of pointers to strings, each consisting of a key and a value separated by a NULL character ('\0'). Each of these strings can have replaceable parameters whose places are marked by the character sequences %1 through %5.

The symbols are filled in as follows:

Symbol | Value
%1 | Class ID, formatted as a string
%2 | Class name
%3 | Path to executable file
%4 | Short type name
%5 | Long type name

See Also COleTemplateServer::UpdateRegistry


AfxOleRegisterTypeLib

BOOL AfxOleRegisterTypeLib( HINSTANCE hInstance, REFGUID tlid, LPCTSTR pszFileName = NULL, LPCTSTR pszHelpDir = NULL );

Return Value

Nonzero if the type library was registered; otherwise 0.

Parameters

hInstance

The instance handle of the application associated with the type library.

tlid

The unique ID of the type library.

pszFileName

Points to the optional filename of a localized type library (.TLB) file for the control.

pszHelpDir

The name of the directory where the help file for the type library can be found. If NULL, the help file is assumed to be in the same directory as the type library itself.

Remarks

Registers the type library with the Windows registration database and allows the type library to be used by other containers that are OLE-control aware. This function updates the registry with the type library name and its location on the system.

See Also AfxOleUnregisterTypeLib, AfxOleRegisterControlClass, AfxOleUnregisterClass


AfxOleSetEditMenu

void AFXAPI AfxOleSetEditMenu( COleClientItem* pClient, CMenu* pMenu, UINT iMenuItem, UINT nIDVerbMin, UINT nIDVerbMax = 0, UINT nIDConvert = 0 );

#include <afxole.h>

Parameters

pClient

A pointer to the client OLE item.

pMenu

A pointer to the menu object to be updated.

iMenuItem

The index of the menu item to be updated.

nIDVerbMin

The command ID that corresponds to the primary verb.

nIDVerbMax

The command ID that corresponds to the last verb.

nIDConvert

ID for the Convert menu item.

Remarks

Implements the user interface for the typename Object command. If the server recognizes only a primary verb, the menu item becomes “verb typename Object” and the nIDVerbMin command is sent when the user chooses the command. If the server recognizes several verbs, then the menu item becomes “typename Object” and a submenu listing all the verbs appears when the user chooses the command. When the user chooses a verb from the submenu, nIDVerbMin is sent if the first verb is chosen, nIDVerbMin + 1 is sent if the second verb is chosen, and so forth. The default COleDocument implementation automatically handles this feature.

You must have the following statement in your client’s application resource script (.RC) file:

#include <afxolecl.rc>

See Also COleDocument


AfxOleSetUserCtrl

void AFXAPI AfxOleSetUserCtrl( BOOL bUserCtrl );

#include <afxdisp.h>

Parameters

bUserCtrl

Specifies whether the user-control flag is to be set or cleared.

Remarks

Sets or clears the user-control flag, which is explained in the reference for AfxOleGetUserCtrl. The framework calls this function when the user creates or loads a document, but not when a document is loaded or created through an indirect action such as loading an embedded object from a container application.

Call this function if other actions in your application should put the user in control of the application.

See Also AfxOleGetUserCtrl


AfxOleTypeMatchGuid

BOOL AfxOleTypeMatchGuid( LPTYPEINFO pTypeInfo, TYPEDESC FAR* pTypeDesc, REFGUID guidType, ULONG cIndirectionLevels );

Return Value

Nonzero if the match was successful; otherwise 0.

Parameters

pTypeInfo

Pointer to the type info object from which pTypeDesc was obtained.

pTypeDesc

Pointer to a TYPEDESC structure.

guidType

The unique ID of the type.

cIndirectionLevels

The number of indirection levels.

Remarks

Call this function to determine whether a type descriptor (obtained from the type info) describes the type indicated by guidType with the given number of levels of indirection.

Example

To check whether typedesc refers to a pointer to a IFontDisp:

AfxOleTypeMatchGuid( ptypeinfo, &typedesc, IID_IFontDisp, 1);

where IID_IFontDisp refers to the type and the number of indirection levels is 1 (because the sample is checking for a simple pointer).


AfxOleUnlockApp

void AFXAPI AfxOleUnlockApp( );

#include <afxdisp.h>

Remarks

Decrements the framework’s count of active objects in the application. See AfxOleLockApp for further information.

When the number of active objects reaches zero, AfxOleOnReleaseAllObjects is called.

See Also AfxOleLockApp, CCmdTarget::OnFinalRelease


AfxOleUnlockControl

BOOL AFXAPI AfxOleUnlockControl( REFCLSID clsid );

BOOL AFXAPI AfxOleUnlockControl( LPCTSTR lpszProgID );

#include <afxwin.h>

Return Value

Nonzero if the class factory of the control was successfully unlocked; otherwise 0.

Parameters

clsid

The unique class ID of the control.

lpszProgID

The unique program ID of the control.

Remarks

Unlocks the class factory of the specified control. A control is locked with AfxOleLockControl, so that dynamically created data associated with the control remains in memory. This can significantly speed up display of the control because the control need not be created and destroyed every time it is displayed. When you are ready to destroy the control, call AfxOleUnlockControl.

See Also AfxOleLockControl


AfxOleUnregisterClass

BOOL AFXAPI AfxOleUnregisterClass( REFCLSID clsID, LPCSTR pszProgID );

Return Value

Nonzero if the control or property page class was successfully unregistered; otherwise 0.

Parameters

clsID

The unique class ID of the control or property page.

pszProgID

The unique program ID of the control or property page.

Remarks

Removes the control or property page class entry from the Windows registration database.

See Also AfxOleRegisterPropertyPageClass, AfxOleRegisterControlClass, AfxOleRegisterTypeLib


AfxOleUnregisterTypeLib

BOOL AFXAPI AfxOleUnregisterTypeLib( REFGUID tlID );

Return Value

Nonzero if the type library was successfully unregistered; otherwise 0.

Parameters

tlID

The unique ID of the type library.

Remarks

Call this function to remove the type library entry from the Windows registration database.

See Also AfxOleUnregisterClass, AfxOleRegisterTypeLib


AfxParseURL

BOOL AFXAPI AfxParseURL( LPCTSTR pstrURL, DWORD& dwServiceType, CString& strServer, CString& strObject, INTERNET_PORT& nPort );

Return Value

Nonzero if the URL was successfully parsed; otherwise, 0 if it is empty or does not contain a known Internet service type.

Parameters

pstrURL

A pointer to a string containing the URL to be parsed.

dwServiceType

Indicates the type of Internet service. Possible values are as follows:

  • AFX_INET_SERVICE_FTP

  • AFX_INET_SERVICE_HTTP

  • AFX_INET_SERVICE_HTTPS

  • AFX_INET_SERVICE_GOPHER

  • AFX_INET_SERVICE_FILE

  • AFX_INET_SERVICE_MAILTO

  • AFX_INET_SERVICE_NEWS

  • AFX_INET_SERVICE_NNTP

  • AFX_INET_SERVICE_TELNET

  • AFX_INET_SERVICE_WAIS

  • AFX_INET_SERVICE_MID

  • AFX_INET_SERVICE_CID

  • AFX_INET_SERVICE_PROSPERO

  • AFX_INET_SERVICE_AFS

  • AFX_INET_SERVICE_UNK

strServer

The first segment of the URL following the service type.

strObject

An object that the URL refers to (may be empty).

nPort

Determined from either the Server or Object portions of the URL, if either exists.

Remarks

This global is used in CInternetSession::OpenURL. It parses a URL string and returns the type of service and its components.

For example, AfxParseURL parses URLs of the form service://server/dir/dir/object.ext:port and returns its components stored as follows:

strServer == "server"

strObject == "/dir/dir/object/object.ext"

nPort == #port

dwServiceType == #service

Note In order to call this function, your project must include AFXINET.H.

See Also AfxGetInternetHandleType,


AfxParseURLEx

BOOL AFXAPI AfxParseURLEx( LPCTSTR pstrURL, DWORD& dwServiceType, CString& strServer, CString& strObject, INTERNET_PORT& nPort, CString& strUsername, CString& strPassword, DWORD dwFlags = 0 );

Return Value

Nonzero if the URL was successfully parsed; otherwise, 0 if it is empty or does not contain a known Internet service type.

Parameters

pstrURL

A pointer to a string containing the URL to be parsed.

dwServiceType

Indicates the type of Internet service. Possible values are as follows:

  • AFX_INET_SERVICE_FTP

  • AFX_INET_SERVICE_HTTP

  • AFX_INET_SERVICE_HTTPS

  • AFX_INET_SERVICE_GOPHER

  • AFX_INET_SERVICE_FILE

  • AFX_INET_SERVICE_MAILTO

  • AFX_INET_SERVICE_NEWS

  • AFX_INET_SERVICE_NNTP

  • AFX_INET_SERVICE_TELNET

  • AFX_INET_SERVICE_WAIS

  • AFX_INET_SERVICE_MID

  • AFX_INET_SERVICE_CID

  • AFX_INET_SERVICE_PROSPERO

  • AFX_INET_SERVICE_AFS

  • AFX_INET_SERVICE_UNK

strServer

The first segment of the URL following the service type.

strObject

An object that the URL refers to (may be empty).

nPort

Determined from either the Server or Object portions of the URL, if either exists.

strUsername

A reference to a CString object containing the name of the user.

strPassword

A reference to a CString object containing the password of the user.

dwFlags

The flags controlling how to parse the URL. Can be a combination of the following values:

Value | Meaning
ICU_DECODE | Convert %XX escape sequences to characters.
ICU_NO_ENCODE | Do not convert unsafe characters to escape sequence.
ICU_NO_META | Do not remove meta sequences (such as "\ ." and "\ ..") from the URL.
ICU_ENCODE_SPACES_ONLY | Encode spaces only.
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.

If you use the MFC default, which is no flags, the function converts all unsafe characters and meta sequences (such as \.,\ .., and \...) to escape sequences.

Remarks

This global function is the extended version of AfxParseURL and is used in CInternetSession::OpenURL. It parses a URL string and returns the type of service and its components, as well as providing the user's name and password. The flags indicate how unsafe characters are handled.

Note In order to call this function, your project must include AFXINET.H.

See Also AfxGetInternetHandleType


AfxRegisterClass

BOOL AFXAPI AfxRegisterClass( WNDCLASS* lpWndClass );

Return Value

TRUE if the class is successfully registered; otherwise FALSE.

Parameters

lpWndClass

Pointer to a WNDCLASS structure containing information about the window class to be registered. For more information on this structure, see the Win32 SDK documentation.

Remarks

Use this function to register window classes in a DLL that uses MFC. If you use this function, the class is automatically unregistered when the DLL is unloaded.

In non-DLL builds, the AfxRegisterClass identifier is defined as a macro that maps to the Windows function RegisterClass, since classes registered in an application are automatically unregistered. If you use AfxRegisterClass instead of RegisterClass, your code can be used without change both in an application and in a DLL.


AfxRegisterWndClass

LPCTSTR AFXAPI AfxRegisterWndClass( UINT nClassStyle, HCURSOR hCursor = 0, HBRUSH hbrBackground = 0, HICON hIcon = 0 );

Return Value

A null-terminated string containing the class name. You can pass this class name to the Create member function in CWnd or other CWnd-derived classes to create a window. The name is generated by the Microsoft Foundation Class Library.

Note The return value is a pointer to a static buffer. To save this string, assign it to a CString variable.

Parameters

nClassStyle

Specifies the Windows class style or combination of styles, created by using the bitwise-OR (|) operator, for the window class. For a list of class styles, see the WNDCLASS structure in the Win32 SDK documentation. If NULL, the defaults will be set as follows:

  • Sets the mouse style to CS_DBLCLKS, which sends double-click messages to the window procedure when the user double-clicks the mouse.

  • Sets the arrow cursor style to the Windows standard IDC_ARROW.

  • Sets the background brush to NULL, so the window will not erase its background.

  • Sets the icon to the standard, waving-flag Windows logo icon.

hCursor

Specifies a handle to the cursor resource to be installed in each window created from the window class. If you use the default of 0, you will get the standard IDC_ARROW cursor.

hbrBackground

Specifies a handle to the brush resource to be installed in each window created from the window class. If you use the default of 0, you will have a NULL background brush, and your window will, by default, not erase its background while processing WM_ERASEBKGND.

hIcon

Specifies a handle to the icon resource to be installed in each window created from the window class. If you use the default of 0, you will get the standard, waving-flag Windows logo icon.

Remarks

The Microsoft Foundation Class Library automatically registers several standard window classes for you. Call this function if you want to register your own window classes.

The name registered for a class by AfxRegisterWndClass depends solely on the parameters. If you call AfxRegisterWndClass multiple times with identical parameters, it only registers a class on the first call. Subsequent calls to AfxRegisterWndClass with identical parameters simply return the already-registered classname.

If you call AfxRegisterWndClass for multiple CWnd-derived classes with identical parameters, instead of getting a separate window class for each class, each class shares the same window class. This can cause problems if the CS_CLASSDC class style is used. Instead of multiple CS_CLASSDC window classes, you end up with one CS_CLASSDC window class, and all C++ windows that use that class share the same DC. To avoid this problem, call AfxRegisterClass to register the class.

See Also CWnd::Create, CWnd::PreCreateWindow, WNDCLASS AfxRegisterClass


AfxSetAllocHook

AFX_ALLOC_HOOK AfxSetAllocHook( AFX_ALLOC_HOOK pfnAllocHook );

Return Value

Nonzero if you want to permit the allocation; otherwise 0.

Parameters

pfnAllocHook

Specifies the name of the function to call. See the Remarks for the prototype of an allocation function.

Remarks

Sets a hook that enables calling of the specified function before each memory block is allocated. The Microsoft Foundation Class Library debug-memory allocator can call a user-defined hook function to allow the user to monitor a memory allocation and to control whether the allocation is permitted. Allocation hook functions are prototyped as follows:

BOOL AFXAPI AllocHook( size_t nSize, BOOL bObject, LONG lRequestNumber );

nSize

The size of the proposed memory allocation.

bObject

TRUE if the allocation is for a CObject-derived object; otherwise FALSE.

lRequestNumber

The memory allocation’s sequence number.

Note that the AFXAPI calling convention implies that the callee must remove the parameters from the stack.


AfxSetResourceHandle

void AfxSetResourceHandle( HINSTANCE hInstResource );

Parameters

hInstResource

The instance or module handle to an .EXE or DLL file from which the application’s resources are loaded.

Remarks

Use this function to set the HINSTANCE handle that determines where the default resources of the application are loaded.

See Also AfxGetInstanceHandle, AfxGetResourceHandle


AfxSocketInit

BOOL AfxSocketInit( WSADATA* lpwsaData = NULL );

Return Value

Nonzero if the function is successful; otherwise 0.

Parameters

lpwsaData

A pointer to a WSADATA structure. If lpwsaData is not equal to NULL, then the address of the WSADATA structure is filled by the call to ::WSAStartup. This function also ensures that ::WSACleanup is called for you before the application terminates.

Remarks

Call this function in your CWinApp::InitInstance override to initialize Windows Sockets.

See Also CWinApp::InitInstance


AFX_SQL_ASYNC

AFX_SQL_ASYNC( prs, SQLFunc )

Parameters

prs

A pointer to a CRecordset object or a CDatabase object. Beginning with MFC 4.2, this parameter value is ignored.

SQLFunc

An ODBC API function. For more information about ODBC API functions, see the ODBC SDK Programmer’s Reference.

Remarks

The implementation of this macro changed in MFC 4.2. AFX_SQL_ASYNC simply calls the macro AFX_ODBC_CALL and ignores the prs parameter. In versions of MFC prior to 4.2, AFX_SQL_ASYNC was used to call ODBC API functions that might return SQL_STILL_EXECUTING. If an ODBC API function did return SQL_STILL_EXECUTING, then AFX_SQL_ASYNC would call prs->OnWaitForDataSource.

Note The MFC ODBC classes now use only synchronous processing. In order to perform an asynchronous operation, you must call the ODBC API function SQLSetConnectOption. For more information, see the topic "Executing Functions Asynchronously" in the ODBC SDK Programmer's Reference.

See Also AFX_ODBC_CALL, AFX_SQL_SYNC


AFX_SQL_SYNC

AFX_SQL_SYNC( SQLFunc )

Parameters

SQLFunc

An ODBC API function. For more information about these functions, see the ODBC SDK Programmer’s Reference.

Remarks

The AFX_SQL_SYNC macro simply calls the function SQLFunc. Use this macro to call ODBC API functions that will not return SQL_STILL_EXECUTING.

Before calling AFX_SQL_SYNC, you must declare a variable, nRetCode, of type RETCODE. You can check the value of nRetCode after the macro call.

Note that the implementation of AFX_SQL_SYNC changed in MFC 4.2. Because checking the server status was no longer required, AFX_SQL_SYNC simply assigns a value to nRetCode. For example, instead of making the call

   AFX_SQL_SYNC( ::SQLGetInfo( .. ) )

you can simply make the assignment

   nRetCode = ::SQLGetInfo( .. );

See Also AFX_SQL_ASYNC, AFX_ODBC_CALL


AfxTermExtensionModule

void AFXAPI AfxTermExtensionModule( AFX_EXTENSION_MODULE& state, BOOL bAll = FALSE );

Parameters

state

A reference to the AFX_EXTENSION_MODULE structure that contains the state of extension DLL module.

bAll If TRUE, cleanup all extension DLL modules. Otherwise, cleanup only the current DLL module.

Remarks

Call this function to allow MFC to cleanup the extension DLL when each process detaches from the DLL (which happens when the process exits, or when the DLL is unloaded as a result of a AfxFreeLibrary call). AfxTermExtensionModule will delete any local storage attached to the module and remove any entries from the message map cache. For example:

static AFX_EXTENSION_MODULE extensionDLL;
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
   if (dwReason == DLL_PROCESS_ATTACH)
   {
      // Extension DLL one-time initialization
      if (!AfxInitExtensionModule( extensionDLL, hInstance))
         return 0;
      // TODO: perform other initialization tasks here
   }
   else if (dwReason == DLL_PROCESS_DETACH)
   {
      // Extension DLL per-process termination
      AfxTermExtensionModule(extensionDLL);
     // TODO: perform other cleanup tasks here
   }
   return 1;   // ok
}

If your application loads and frees extension DLLs dynamically, be sure to call AfxTermExtensionModule. Since most extension DLLs are not dynamically loaded (usually, they are linked via their import libraries), the call to AfxTermExtensionModule is usually not necessary.

MFC extension DLLs need to call AfxInitExtensionModule in their DllMain. If the DLL will be exporting CRuntimeClass objects or has its own custom resources, you also need to create a CDynLinkLibrary object in DllMain.

See Also AfxInitExtensionModule


AfxThrowArchiveException

void AfxThrowArchiveException( int cause, LPCTSTR lpszArchiveName );

Parameters

cause

Specifies an integer that indicates the reason for the exception. For a list of the possible values, see CArchiveException::m_cause.

lpszArchiveName

Points to a string containing the name of the CArchive object that caused the exception (if available).

Remarks

Throws an archive exception.

See Also CArchiveException, THROW


AfxThrowDaoException

void AFXAPI AfxThrowDaoException( int nAfxDaoError = NO_AFX_DAO_ERROR, SCODE scode = S_OK );

Parameters

nAfxDaoError

An integer value representing a DAO extended error code, which can be one of the values listed under CDaoException::m_nAfxDaoError.

scode

An OLE error code from DAO, of type SCODE. For information, see CDaoException::m_scode.

Remarks

Call this function to throw an exception of type CDaoException from your own code. The framework also calls AfxThrowDaoException. In your call, you can pass one of the parameters or both. For example, if you want to raise one of the errors defined in CDaoException::nAfxDaoError but you do not care about the scode parameter, pass a valid code in the nAfxDaoError parameter and accept the default value for scode.

For information about exceptions related to the MFC DAO classes, see class CDaoException in this book and the article Exceptions: Database Exceptions in Visual C++ Programmer’s Guide.

See Also CException


AfxThrowDBException

void AfxThrowDBException( RETCODE nRetCode, CDatabase* pdb, HSTMT hstmt );

Parameters

nRetCode

A value of type RETCODE, defining the type of error that caused the exception to be thrown.

pdb

A pointer to the CDatabase object that represents the data source connection with which the exception is associated.

hstmt

An ODBC HSTMT handle that specifies the statement handle with which the exception is associated.

Remarks

Call this function to throw an exception of type CDBException from your own code. The framework calls AfxThrowDBException when it receives an ODBC RETCODE from a call to an ODBC API function and interprets the RETCODE as an exceptional condition rather than an expectable error. For example, a data access operation might fail because of a disk read error.

For information about the RETCODE values defined by ODBC, see Chapter 8, “Retrieving Status and Error Information,” in the ODBC SDK Programmer’s Reference. For information about MFC extensions to these codes, see class CDBException.

See Also CDBException::m_nRetCode


AfxThrowFileException

void AfxThrowFileException( int cause, LONG lOsError = -1, LPCTSTR lpszFileName = NULL );

Parameters

cause

Specifies an integer that indicates the reason for the exception. For a list of the possible values, see CFileException::m_cause.

lOsError

Contains the operating-system error number (if available) that states the reason for the exception. See your operating-system manual for a listing of error codes.

lpszFileName

Points to a string containing the name of the file that caused the exception (if available).

Remarks

Throws a file exception. You are responsible for determining the cause based on the operating-system error code.

See Also CFileException::ThrowOsError, THROW


AfxThrowInternetException

void AFXAPI AfxThrowInternetException( DWORD dwContext, DWORD dwError = 0 );

Parameters

dwContext

The context identifier for the operation that caused the error. The default value of dwContext is specified originally in CInternetSession and is passed to CInternetConnection- and CInternetFile-derived classes. For specific operations performed on a connection or a file, you usually override the default with a dwContext of your own. This value then is returned to CInternetSession::OnStatusCallback to identify the specific operation’s status. For more information on context identifiers, see the article Internet First Steps: WinInet.

dwError

The error that caused the exception.

Remarks

Throws an Internet exception. You are responsible for determining the cause based on the operating-system error code.

Note In order to call this function, your project must include AFXINET.H.

See Also CInternetException, THROW


AfxThrowMemoryException

void AfxThrowMemoryException( );

Remarks

Throws a memory exception. Call this function if calls to underlying system memory allocators (such as malloc and the GlobalAlloc Windows function) fail. You do not need to call it for new because new will throw a memory exception automatically if the memory allocation fails.

See Also CMemoryException, THROW


AfxThrowNotSupportedException

void AfxThrowNotSupportedException( );

Remarks

Throws an exception that is the result of a request for an unsupported feature.

See Also CNotSupportedException, THROW


AfxThrowOleDispatchException

void AFXAPI AfxThrowOleDispatchException( WORD wCode, LPCSTR lpszDescription, UINT nHelpID = 0 );

void AFXAPI AfxThrowOleDispatchException( WORD wCode, UINT nDescriptionID, UINT nHelpID = -1 );

#include <afxdisp.h>

Parameters

wCode

An error code specific to your application.

lpszDescription

Verbal description of the error.

nDescriptionID

Resource ID for the verbal error description.

nHelpID

A help context for your application’s help (.HLP) file.

Remarks

Use this function to throw an exception within an OLE automation function. The information provided to this function can be displayed by the driving application (Microsoft Visual Basic or another OLE automation client application).

See Also COleException


AfxThrowOleException

void AFXAPI AfxThrowOleException( SCODE sc );

void AFXAPI AfxThrowOleException( HRESULT hr );

#include <afxdisp.h>

Parameters

sc

An OLE status code that indicates the reason for the exception.

hr

Handle to a result code that indicates the reason for the exception.

Remarks

Creates an object of type COleException and throws an exception. The version that takes an HRESULT as an argument converts that result code into the corresponding SCODE. For more information on HRESULT and SCODE, see Structure of COM Error Codes in the Platform SDK.

See Also COleException, THROW


AfxThrowResourceException

void AfxThrowResourceException( );

Remarks

Throws a resource exception. This function is normally called when a Windows resource cannot be loaded.

See Also CResourceException, THROW


AfxThrowUserException

void AfxThrowUserException( );

Remarks

Throws an exception to stop an end-user operation. This function is normally called immediately after AfxMessageBox has reported an error to the user.

See Also CUserException, THROW, AfxMessageBox


afxTraceEnabled

BOOL afxTraceEnabled;

Remarks

A global variable used to enable or disable output from the TRACE macro.

By default, output from the TRACE macro is disabled. Set afxTraceEnabled to a nonzero value if you want TRACE macros in your program to produce output. Set it to 0 if you don’t want TRACE macros in your program to produce output.

Usually, the value of afxTraceEnabled is set in your AFX.INI file. Alternately, you can set the value of afxTraceEnabled with the TRACER.EXE utility.For more information on afxTraceEnabled, see Technical Note 7.

See Also afxTraceFlags, TRACE


afxTraceFlags

int afxTraceFlags;

Remarks

Used to turn on the built-in reporting features of the Microsoft Foundation Class Library.

This variable can be set under program control or while using the debugger. Each bit of afxTraceFlags selects a trace reporting option. You can turn any one of these bits on or off as desired using TRACER.EXE. There is never a need to set these flags manually.

The following is a list of the bit patterns and the resulting trace report option:

  • 0x01 Multiapplication debugging. This will prefix each TRACE output with the name of the application and affects both the explicit TRACE output of your program as well as the additional report options described below.

  • 0x02 Main message pump. Reports each message received in the main CWinApp message-handling mechanism. Lists the window handle, the message name or number, wParam, and lParam.

    The report is made after the Windows GetMessage call but before any message translation or dispatch occurs.

    Dynamic data exchange (DDE) messages will display additional data that can be used for some debugging scenarios in OLE.

    This flag displays only messages that are posted, not those that are sent.

  • 0x04 Main message dispatch. Like option 0x02 above but applies to messages dispatched in CWnd::WindowProc, and therefore handles both posted and sent messages that are about to be dispatched.

  • 0x08 WM_COMMAND dispatch. A special case used for extended WM_COMMAND/OnCommand handling to report progress of the command-routing mechanism.

    Also reports which class receives the command (when there is a matching message-map entry), and when classes do not receive a command (when there is no matching message map entry). This report is especially useful to track the flow of command messages in multiple document interface (MDI) applications.

  • 0x10 OLE tracing. Reports significant OLE notifications or requests.

    Turn this option on for an OLE client or server to track communication between the OLE DLLs and an OLE application.

  • 0x20 Database tracing. Reports warnings for both ODBC and DAO classes, plus additional information for DAO. Turn this option on if you want tracing for either the MFC ODBC classes or the MFC DAO classes. For ODBC, you get only warnings, such as type mismatches in your DFX calls. For DAO, you get information for all exceptions, including the line and function in DAO or in the MFC DAO classes where a failure occurred.

For more information, see Technical Note 7.

See Also afxTraceEnabled, TRACE


AfxVerifyLicFile

BOOL AFXAPI AfxVerifyLicFile( HINSTANCE hInstance, LPCTSTR pszLicFileName, LPOLESTR pszLicFileContents, UINT cch = -1 );

Return Value

Nonzero if the license file exists and begins with the character sequence in pszLicFileContents; otherwise 0.

Parameters

hInstance

The instance handle of the DLL associated with the licensed control.

pszLicFileName

Points to a null-terminated character string containing the license filename.

pszLicFileContents

Points to a byte sequence that must match the sequence found at the beginning of the license file.

cch

Number of characters in pszLicFileContents.

Remarks

Call this function to verify that the license file named by pszLicFileName is valid for the OLE control. If cch is – 1, this function uses:

_tcslen(pszLicFileContents)

See Also COleObjectFactory::VerifyUserLicense


AfxWinInit

BOOL AFXAPI AfxWinInit( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )

Parameters

hInstance

The handle of the currently running module.

hPrevInstance

A handle to a previous instance of the application. For a Win32-based application, this parameter is always NULL.

lpCmdLine

Points to a null-terminated string specifying the command line for the application.

nCmdShow

Specifies how the main window of a GUI application would be shown.

Remarks

This function is called by the MFC-supplied WinMain function, as part of the CWinApp initialization of a GUI-based application, to initialize MFC. For a console application, which does not use the MFC-supplied WinMain function, you must call AfxWinInit directly to initialize MFC.

If you call AfxWinInit yourself, you should declare an instance of a CWinApp class. For a console application, you might choose not to derive your own class from CWinApp and instead use an instance of CWinApp directly. This technique is appropriate if you decide to leave all functionality for your application in your implementation of main.

The TEAR sample shows how to make a console application using MFC.

Example

// this file must be compiled with the /GX and /MT options:
//      cl /GX /MT thisfile.cpp

#include <afx.h>
#include <afxdb.h>
#include <iostream.h>

int main()
{
   // try to initialize MFC

   if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
   {
      cerr << "MFC failed to initialize!" << endl;
      return 1;
   }

   // try to connect to an ODBC database that doesn't exist
   // (this wouldn't work at all without initializing MFC)

   CDatabase db;
   try
   {
      db.Open("This Databsae Doesn't Exist");

      // we shouldn't realistically get here

      cout << "Successful!" << endl;
      cout << "Closing ... ";
      db.Close();
      cout << "Closed!" << endl;
   }
   catch (CDBException* pEx)
   {
      // we got an exception! print an error message
      // (this wouldn't work without initializing MFC)

      char sz[1024];

      cout << "Error: ";
      if (pEx->GetErrorMessage(sz, 1024))
         cout << sz;
      else
         cout << "No error message was available";
      cout << endl;

      pEx->Delete();
      return 1;
   }

   return 0;
}

See Also CWinApp, CWinApp: The Application Class, main, WinMain


AND_CATCH

AND_CATCH( exception_class, exception_object_pointer_name )

Parameters

exception_class

Specifies the exception type to test for. For a list of standard exception classes, see class CException.

exception_object_pointer_name

A name for an exception-object pointer that will be created by the macro. You can use the pointer name to access the exception object within the AND_CATCH block. This variable is declared for you.

Remarks

Defines a block of code for catching additional exception types thrown in a preceding TRY block. Use the CATCH macro to catch one exception type, then the AND_CATCH macro to catch each subsequent type. End the TRY block with an END_CATCH macro.

The exception-processing code can interrogate the exception object, if appropriate, to get more information about the specific cause of the exception. Call the THROW_LAST macro within the AND_CATCH block to shift processing to the next outer exception frame. AND_CATCH marks the end of the preceding CATCH or AND_CATCH block.

Note The AND_CATCH block is defined as a C++ scope (delineated by curly braces). If you declare variables in this scope, remember that they are accessible only within that scope. This also applies to the exception_object_pointer_name variable.

See Also TRY, CATCH, END_CATCH, THROW, THROW_LAST, AND_CATCH_ALL, CException


AND_CATCH_ALL

AND_CATCH_ALL( exception_object_pointer_name )

Parameters

exception_object_pointer_name

A name for an exception-object pointer that will be created by the macro. You can use the pointer name to access the exception object within the AND_CATCH_ALL block. This variable is declared for you.

Remarks

Defines a block of code for catching additional exception types thrown in a preceding TRY block. Use the CATCH macro to catch one exception type, then the AND_CATCH_ALL macro to catch all other subsequent types. If you use AND_CATCH_ALL, end the TRY block with an END_CATCH_ALL macro.

The exception-processing code can interrogate the exception object, if appropriate, to get more information about the specific cause of the exception. Call the THROW_LAST macro within the AND_CATCH_ALL block to shift processing to the next outer exception frame. AND_CATCH_ALL marks the end of the preceding CATCH or AND_CATCH_ALL block.

Note The AND_CATCH_ALL block is defined as a C++ scope (delineated by curly braces). If you declare variables in this scope, remember that they are accessible only within that scope.

See Also TRY, CATCH_ALL, END_CATCH_ALL, THROW, THROW_LAST, AND_CATCH, CException


ASSERT

ASSERT( booleanExpression )

Parameters

booleanExpression

Specifies an expression (including pointer values) that evaluates to nonzero or 0.

Remarks

Evaluates its argument. If the result is 0, the macro prints a diagnostic message and aborts the program. If the condition is nonzero, it does nothing.

The diagnostic message has the form

assertion failed in file <name> in line <num>

where name is the name of the source file, and num is the line number of the assertion that failed in the source file.

In the Release version of MFC, ASSERT does not evaluate the expression and thus will not interrupt the program. If the expression must be evaluated regardless of environment, use the VERIFY macro in place of ASSERT.

Note This function is available only in the Debug version of MFC.

Example

// example for ASSERT
CAge* pcage = new CAge( 21 ); // CAge is derived from CObject.
ASSERT( pcage!= NULL )
ASSERT( pcage->IsKindOf( RUNTIME_CLASS( CAge ) ) )
// Terminates program only if pcage is NOT a CAge*.

See Also VERIFY


ASSERT_KINDOF

ASSERT_KINDOF( classname, pobject )

Parameters

classname

The name of a CObject-derived class.

pobject

A pointer to a class object.

Remarks

This macro asserts that the object pointed to is an object of the specified class, or is an object of a class derived from the specified class. The pobject parameter should be a pointer to an object and can be const. The object pointed to and the class must support CObject run-time class information. As an example, to ensure that pDocument is a pointer to an object of the CMyDocument class, or any of its derivatives, you could code:

ASSERT_KINDOF(CMyDocument, pDocument)

Using the ASSERT_KINDOF macro is exactly the same as coding:

ASSERT(pobject->IsKindOf(RUNTIME_CLASS(classname)));

This function works only for classes declared with the DECLARE_DYNAMIC or DECLARE_SERIAL macro.

Note This function is available only in the Debug version of MFC.

See Also ASSERT


ASSERT_VALID

ASSERT_VALID( pObject )

Parameters

pObject

Specifies an object of a class derived from CObject that has an overriding version of the AssertValid member function.

Remarks

Use to test your assumptions about the validity of an object’s internal state. ASSERT_VALID calls the AssertValid member function of the object passed as its argument.

In the Release version of MFC, ASSERT_VALID does nothing. In the Debug version, it validates the pointer, checks against NULL, and calls the object’s own AssertValid member functions. If any of these tests fails, this displays an alert message in the same manner as ASSERT.

Note This function is available only in the Debug version of MFC.

For more information and examples, see MFC Debugging Support in Visual C++ Programmer’s Guide.

See Also ASSERT, VERIFY, CObject, CObject::AssertValid


BASED_CODE

Remarks

Under Win32, this macro expands to nothing and is provided for backward compatibility. Under 16-bit MFC, the macro ensures that data will be placed in the code segment rather than in the data segment. The result is less impact on your data segment.


BEGIN_CONNECTION_MAP

BEGIN_CONNECTION_MAP( theClass, theBase )

Parameters

theClass

Specifies the name of the control class whose connection map this is.

theBase

Specifies the name of the base class of theClass.

Remarks

Each COleControl-derived class in your program can provide a connection map to specify connection points that your control will support. In the implementation (.CPP) file that defines the member functions for your class, start the connection map with the BEGIN_CONNECTION_MAP macro, then add macro entries for each of your connection points using the CONNECTION_PART macro. Finally, complete the connection map with the END_CONNECTION_MAP macro.

See Also BEGIN_CONNECTION_PART, DECLARE_CONNECTION_MAP


BEGIN_CONNECTION_PART

BEGIN_CONNECTION_PART( theClass, localClass )

Parameters

theClass

Specifies the name of the control class whose connection point this is.

localClass

Specifies the name of the local class that implements the connection point.

Remarks

Use the BEGIN_CONNECTION_PART macro to begin the definition of additional connection points beyond the event and property notification connection points.

In the declaration (.H) file that defines the member functions for your class, start the connection point with the BEGIN_CONNECTION_PART macro, then add the CONNECTION_IID macro and any other member functions you wish to implement, and complete the connection point map with the END_CONNECTION_PART macro.

See Also BEGIN_CONNECTION_MAP, END_CONNECTION_PART, DECLARE_CONNECTION_MAP


BEGIN_DISPATCH_MAP

BEGIN_DISPATCH_MAP( theClass, baseClass )

#include <afxdisp.h>

Parameters

theClass

Specifies the name of the class that owns this dispatch map.

baseClass

Specifies the base class name of theClass.

Remarks

Use the BEGIN_DISPATCH_MAP macro to declare the definition of your dispatch map.

In the implementation (.CPP) file that defines the member functions for your class, start the dispatch map with the BEGIN_DISPATCH_MAP macro, add macro entries for each of your dispatch functions and properties, and complete the dispatch map with the END_DISPATCH_MAP macro.

See Also Dispatch Maps, DECLARE_DISPATCH_MAP, END_DISPATCH_MAP, DISP_FUNCTION, DISP_PROPERTY, DISP_PROPERTY_EX, DISP_DEFVALUE


BEGIN_EVENT_MAP

BEGIN_EVENT_MAP( theClass, baseClass )

Parameters

theClass

Specifies the name of the control class whose event map this is.

baseClass

Specifies the name of the base class of theClass.

Remarks

Use the BEGIN_EVENT_MAP macro to begin the definition of your event map.

In the implementation (.CPP) file that defines the member functions for your class, start the event map with the BEGIN_EVENT_MAP macro, then add macro entries for each of your events, and complete the event map with the END_EVENT_MAP macro.

For more information on event maps and the BEGIN_EVENT_MAP macro, see the article ActiveX Controls: Events in Visual C++ Programmer’s Guide.

See Also DECLARE_EVENT_MAP, END_EVENT_MAP


BEGIN_EVENTSINK_MAP

BEGIN_EVENTSINK_MAP( theClass, baseClass )

Parameters

theClass

Specifies the name of the control class whose event sink map this is.

baseClass

Specifies the name of the base class of theClass.

Remarks

Use the BEGIN_EVENTSINK_MAP macro to begin the definition of your event sink map.

In the implementation (.CPP) file that defines the member functions for your class, start the event sink map with the BEGIN_EVENTSINK_MAP macro, then add macro entries for each event to be notified of, and complete the event sink map with the END_EVENTSINK_MAP macro.

For more information on event sink maps and OLE control containers, see the article ActiveX Control Containers in Visual C++ Programmer’s Guide.

See Also DECLARE_EVENTSINK_MAP, END_EVENTSINK_MAP


BEGIN_MESSAGE_MAP

BEGIN_MESSAGE_MAP( theClass, baseClass )

Parameters

theClass

Specifies the name of the class whose message map this is.

baseClass

Specifies the name of the base class of theClass.

Remarks

Use the BEGIN_MESSAGE_MAP macro to begin the definition of your message map.

In the implementation (.CPP) file that defines the member functions for your class, start the message map with the BEGIN_MESSAGE_MAP macro, then add macro entries for each of your message-handler functions, and complete the message map with the END_MESSAGE_MAP macro.

For more information on message maps and the BEGIN_MESSAGE_MAP macro, see Adding a Dialog Box in Visual C++ Tutorials.

Example

// example for BEGIN_MESSAGE_MAP
BEGIN_MESSAGE_MAP( CMyWindow, CFrameWnd )
   //{{AFX_MSG_MAP( CMyWindow )
    ON_WM_PAINT()
    ON_COMMAND( IDM_ABOUT, OnAbout )
   //}}AFX_MSG_MAP
END_MESSAGE_MAP( )

See Also DECLARE_MESSAGE_MAP, END_MESSAGE_MAP


BEGIN_OLEFACTORY

BEGIN_OLEFACTORY( class_name )

Parameters

class_name

Specifies the name of the control class whose class factory this is.

Remarks

In the header file of your control class, use the BEGIN_OLEFACTORY macro to begin the declaration of your class factory. Declarations of class factory licensing functions should begin immediately after BEGIN_OLEFACTORY.

See Also END_OLEFACTORY, DECLARE_OLECREATE_EX


BEGIN_PARSE_MAP

BEGIN_PARSE_MAP( theClass, baseClass )

Parameters

theClass

Specifies the name of the class that owns this parse map.

baseClass

Specifies the base class name of theClass. Must be a class derived from CHttpServer.

Remarks

Use the BEGIN_PARSE_MAP macro to begin the definition of your parse map.

When a client command is received by a CHttpServer object, the parse maps associate the command to its class member function and parameters. Only one parse map is created per CHttpServer object.

In the implementation (.CPP) file that defines the member functions for your class, start the parse map with the BEGIN_PARSE_MAP macro, add macro entries for each of your parse functions and properties, and complete the parse map with the END_PARSE_MAP macro.

See ON_PARSE_COMMAND for a parse map example.

See Also ON_PARSE_COMMAND, ON_PARSE_COMMAND_PARAMS, DEFAULT_PARSE_COMMAND, END_PARSE_MAP, CHttpServer


BEGIN_PROPPAGEIDS

BEGIN_PROPPAGEIDS( class_name, count )

Parameters

class_name

The name of the control class for which property pages are being specified.

count

The number of property pages used by the control class.

Remarks

Use the BEGIN_PROPPAGEIDS macro to begin the definition of your control’s list of property page IDs.

In the implementation (.CPP) file that defines the member functions for your class, start the property page list with the BEGIN_PROPPAGEIDS macro, then add macro entries for each of your property pages, and complete the property page list with the END_PROPPAGEIDS macro.

For more information on property pages, see the article ActiveX Controls: Property Pages in Visual C++ Programmer’s Guide.

See Also END_PROPPAGEIDS, DECLARE_PROPPAGEIDS, PROPPAGEID


CATCH

CATCH( exception_class, exception_object_pointer_name )

Parameters

exception_class

Specifies the exception type to test for. For a list of standard exception classes, see class CException.

exception_object_pointer_name

Specifies a name for an exception-object pointer that will be created by the macro. You can use the pointer name to access the exception object within the CATCH block. This variable is declared for you.

Remarks

Use this macro to define a block of code that catches the first exception type thrown in the preceding TRY block. The exception-processing code can interrogate the exception object, if appropriate, to get more information about the specific cause of the exception. Invoke the THROW_LAST macro to shift processing to the next outer exception frame. End the TRY block with an END_CATCH macro.

If exception_class is the class CException, then all exception types will be caught. You can use the CObject::IsKindOf member function to determine which specific exception was thrown. A better way to catch several kinds of exceptions is to use sequential AND_CATCH statements, each with a different exception type.

The exception object pointer is created by the macro. You do not need to declare it yourself.

Note The CATCH block is defined as a C++ scope (delineated by curly braces). If you declare variables in this scope, remember that they are accessible only within that scope. This also applies to exception_object_pointer_name.

For more information on exceptions and the CATCH macro, see the article Exceptions in Visual C++ Programmer’s Guide.

See Also TRY, AND_CATCH, END_CATCH, THROW, THROW_LAST, CATCH_ALL, CException


CATCH_ALL

CATCH_ALL( exception_object_pointer_name )

Parameters

exception_object_pointer_name

Specifies a name for an exception-object pointer that will be created by the macro. You can use the pointer name to access the exception object within the CATCH_ALL block. This variable is declared for you.

Remarks

Use this macro to define a block of code that catches all exception types thrown in the preceding TRY block. The exception-processing code can interrogate the exception object, if appropriate, to get more information about the specific cause of the exception. Invoke the THROW_LAST macro to shift processing to the next outer exception frame. If you use CATCH_ALL, end the TRY block with an END_CATCH_ALL macro.

Note The CATCH_ALL block is defined as a C++ scope (delineated by curly braces). If you declare variables in this scope, remember that they are accessible only within that scope.

For more information on exceptions, see the article Exceptions in Visual C++ Programmer’s Guide.

See Also TRY, AND_CATCH_ALL, END_CATCH_ALL, THROW, THROW_LAST, CATCH, CException


CompareElements

template< class TYPE, class ARG_TYPE >
BOOL AFXAPI CompareElements( const TYPE* pElement1,
const ARG_TYPE* pElement2 );

Return Value

Nonzero if the object pointed to by pElement1 is equal to the object pointed to by pElement2; otherwise 0.

Parameters

TYPE

The type of the first element to be compared.

pElement1

Pointer to the first element to be compared.

ARG_TYPE

The type of the second element to be compared.

pElement2

Pointer to the second element to be compared.

Remarks

This function is called directly by CList::Find and indirectly by CMap::Lookup and CMap::operator []. The CMap calls use the CMap template parameters KEY and ARG_KEY.

The default implementation returns the result of the comparison of *pElement1 and *pElement2. Override this function so that it compares the elements in a way that is appropriate for your application.

The C++ language defines the comparison operator (==) for simple types (char, int, float, and so on) but does not define a comparison operator for classes and structures. If you want to use CompareElements or to instantiate one of the collection classes that uses it, you must either define the comparison operator or overload CompareElements with a version that returns appropriate values.

See Also CList, CMap


ConstructElements

template< class TYPE >
void AFXAPI ConstructElements( TYPE* pElements, int nCount );

Parameters

TYPE

Template parameter specifying the type of the elements to be constructed.

pElements

Pointer to the elements.

nCount

Number of elements to be constructed.

Remarks

This function is called when new array, list, and map elements are constructed. The default version initializes all bits of the new elements to 0.

For information on implementing this and other helper functions, see the article Collections: How to Make a Type-Safe Collection in Visual C++ Programmer’s Guide.

See Also CArray, CList, CMap


CopyElements

template< class TYPE >
void AFXAPI CopyElements( TYPE* pDest, const TYPE* pSrc, int nCount );

Parameters

TYPE

Template parameter specifying the type of elements to be copied.

pDest

Pointer to the destination where the elements will be copied.

pSrc

Pointer to the source of the elements to be copied.

nCount

Number of elements to be copied.

Remarks

This function is called directly by CArray::Append and CArray::Copy. The default implementation uses the simple assignment operator ( = ) to perform the copy operation. If the type being copied does not have an overloaded operator=, then the default implementation performs a bitwise copy.

For information on implementing this and other helper functions, see the article Collections: How to Make a Type-Safe Collection in Visual C++ Programmer’s Guide.

See Also CArray


CONNECTION_IID

CONNECTION_IID( iid )

Parameters

iid

The interface ID of the interface called by the connection point.

Remarks

Use the CONNECTION_IID macro between the BEGIN_CONNECTION_PART and END_CONNECTION_PART macros to define an interface ID for a connection point supported by your OLE control.

The iid argument is an interface ID used to identify the interface that the connection point will call on its connected sinks. For example:

CONNECTION_IID(IID_ISinkInterface)

specifies a connection point that calls the ISinkInterface interface.

See Also BEGIN_CONNECTION_PART, DECLARE_CONNECTION_MAP, END_CONNECTION_PART


CONNECTION_PART

CONNECTION_PART( theClass, iid, localClass )

Parameters

theClass

Specifies the name of the control class whose connection point this is.

iid

The interface ID of the interface called by the connection point.

localClass

Specifies the name of the local class that implements the connection point.

Remarks

Use the CONNECTION_PART macro to map a connection point for your OLE control to a specific interface ID.

For example:

BEGIN_CONNECTION_MAP(CSampleCtrl, COleControl)
    CONNECTION_PART(CSampleCtrl, IID_ISinkInterface, MyConnPt)
END_CONNECTION_MAP()

implements a connection map, with a connection point, that calls the IID_ISinkInterface interface .

See Also BEGIN_CONNECTION_PART, DECLARE_CONNECTION_MAP, BEGIN_CONNECTION_MAP, CONNECTION_IID


DDP_CBIndex

void AFXAPI DDP_CBIndex( CDataExchange* pDX, int id, int& member, LPCTSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the combo box control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the combo box control specified by id.

Remarks

Call this function in your property page’s DoDataExchange function to synchronize the value of an integer property with the index of the current selection in a combo box on the property page. This function should be called before the corresponding DDX_CBIndex function call.

See Also DDP_CBString, DDP_Text, COleControl::DoPropExchange, DDX_CBIndex


DDP_CBString

void AFXAPI DDP_CBString( CDataExchange* pDX, int id, CString& member, LPCTSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the combo box control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the combo box string specified by id.

Remarks

Call this function in your property page’s DoDataExchange function to synchronize the value of a string property with the current selection in a combo box on the property page. This function should be called before the corresponding DDX_CBString function call.

See Also DDP_CBStringExact, DDP_CBIndex, COleControl::DoPropExchange, DDX_CBString


DDP_CBStringExact

void AFXAPI DDP_CBStringExact( CDataExchange* pDX, int id, CString& member, LPCTSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the combo box control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the combo box string specified by id.

Remarks

Call this function in your property page’s DoDataExchange function to synchronize the value of a string property that exactly matches the current selection in a combo box on the property page. This function should be called before the corresponding DDX_CBStringExact function call.

See Also DDP_CBString, DDP_CBIndex, COleControl::DoPropExchange, DDX_CBStringExact


DDP_Check

void AFXAPI DDP_Check( CDataExchange*pDX, int id, int &member, LPCSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the check box control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the check box control specified by id.

Remarks

Call this function in your property page’s DoDataExchange function to synchronize the value of the property with the associated property page check box control. This function should be called before the corresponding DDX_Check function call.

See Also DDP_Radio, DDP_Text, COleControl::DoPropExchange, DDX_Check


DDP_LBIndex

void AFXAPI DDP_LBIndex( CDataExchange* pDX, int id, int& member, LPCTSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the list box control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the list box string specified by id.

Remarks

Call this function in your property page’s DoDataExchange function to synchronize the value of an integer property with the index of the current selection in a list box on the property page. This function should be called before the corresponding DDX_LBIndex function call.

See Also DDP_LBString, DDP_CBIndex, COleControl::DoPropExchange, DDX_LBIndex


DDP_LBString

void AFXAPI DDP_LBString( CDataExchange* pDX, int id, CString& member, LPCTSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the list box control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the list box string specified by id.

Remarks

Call this function in your property page’s DoDataExchange function to synchronize the value of a string property with the current selection in a list box on the property page. This function should be called before the corresponding DDX_LBString function call.

See Also DDP_LBStringExact, DDP_LBIndex, COleControl::DoPropExchange, DDX_LBString


DDP_LBStringExact

void AFXAPI DDP_LBStringExact( CDataExchange* pDX, int id, CString& member, LPCTSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the list box control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the list box string specified by id.

Remarks

Call this function in your property page’s DoDataExchange function to synchronize the value of a string property that exactly matches the current selection in a list box on the property page. This function should be called before the corresponding DDX_LBStringExact function call.

See Also DDP_LBString, DDP_LBIndex, COleControl::DoPropExchange, DDX_LBStringExact


DDP_PostProcessing

void AFXAPI DDP_PostProcessing( CDataExchange *pDX );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

Remarks

Call this function in your property page’s DoDataExchange function, to finish the transfer of property values from the property page to your control when property values are being saved.

This function should be called after all data exchange functions are completed. For example:

void CSamplePage::DoDataExchange(CDataExchange* pDX)
{
   //{{AFX_DATA_MAP(CSpindialPropPage)
   DDP_Text(pDX, IDC_POSITIONEDIT, m_NeedlePosition,
          _T("NeedlePosition"));
   DDX_Text(pDX, IDC_POSITIONEDIT, m_NeedlePosition);
   DDV_MinMaxInt(pDX, m_NeedlePosition, 0, 3);
   //}}AFX_DATA_MAP
   DDP_PostProcessing(pDX);
}

See Also COleControl::DoPropExchange


DDP_Radio

void AFXAPI DDP_Radio( CDataExchange*pDX, int id, int &member, LPCTSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the radio button control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the radio button control specified by id.

Remarks

Call this function in your control’s DoPropExchange function to synchronize the value of the property with the associated property page radio button control. This function should be called before the corresponding DDX_Radio function call.

See Also DDP_Check, DDP_Text, COleControl::DoPropExchange, DDX_Radio


DDP_Text

void AFXAPI DDP_Text( CDataExchange*pDX, int id, BYTE &member, LPCTSTR pszPropName );

void AFXAPI DDP_Text( CDataExchange*pDX, int id, int &member, LPCTSTR pszPropName );

void AFXAPI DDP_Text( CDataExchange*pDX, int id, UINT &member, LPCTSTR pszPropName );

void AFXAPI DDP_Text( CDataExchange*pDX, int id, long &member, LPCTSTR pszPropName );

void AFXAPI DDP_Text( CDataExchange*pDX, int id, DWORD &member, LPCTSTR pszPropName );

void AFXAPI DDP_Text( CDataExchange*pDX, int id, float &member, LPCTSTR pszPropName );

void AFXAPI DDP_Text( CDataExchange*pDX, int id, double &member, LPCTSTR pszPropName );

void AFXAPI DDP_Text( CDataExchange*pDX, int id, CString &member, LPCTSTR pszPropName );

Parameters

pDX

Pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

id

The resource ID of the control associated with the control property specified by pszPropName.

member

The member variable associated with the property page control specified by id and the property specified by pszPropName.

pszPropName

The property name of the control property to be exchanged with the control specified by id.

Remarks

Call this function in your control’s DoDataExchange function to synchronize the value of the property with the associated property page control. This function should be called before the corresponding DDX_Text function call.

See Also DDP_Check, DDP_Radio, COleControl::DoPropExchange, DDX_Text


DDV_MaxChars

void AFXAPI DDV_MaxChars( CDataExchange* pDX, CString const& value, int nChars );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is validated.

nChars

Maximum number of characters allowed.

Remarks

Call DDV_MaxChars to verify that the amount of characters in the control associated with value does not exceed nChars.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDV_MinMaxByte

void AFXAPI DDV_MinMaxByte( CDataExchange* pDX, BYTE value, BYTE minVal, BYTE maxVal );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is validated.

minVal

Minimum value (of type BYTE) allowed.

maxVal

Maximum value (of type BYTE) allowed.

Remarks

Call DDV_MinMaxByte to verify that the value in the control associated with value falls between minVal and maxVal.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDV_MinMaxDateTime

void AFXAPI DDV_MinMaxDateTime( CDataExchange* pDX, CTime& refValue, const CTime* refMinRange, const CTime* refMaxRange );

void AFXAPI DDV_MinMaxDateTime( CDataExchange* pDX, COleDateTime& refValue, const COleDateTime* refMinRange, const COleDateTime* refMaxRange );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction. You don’t need to delete this object.

refValue

A reference to a CTime or COleDateTime object associated with a member variable of the dialog box, form view, or control view object. This object contains the data to be validated.

refMinRange

Minimum date/time value allowed.

refMaxRange

Maximum date/time value allowed.

Remarks

Call DDV_MinMaxDateTime to verify that the time/date value in the date and time picker control (CDateTimeCtrl) associated with refValue falls between refMinRange and refMaxRange.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_DateTimeCtrl, DDV_MinMaxMonth


DDV_MinMaxDouble

void AFXAPI DDV_MinMaxDouble( CDataExchange* pDX, double const& value, double minVal, double maxVal );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is validated.

minVal

Minimum value (of type double) allowed.

maxVal

Maximum value (of type double) allowed.

Remarks

Call DDV_MinMaxDouble to verify that the value in the control associated with value falls between minVal and maxVal.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDV_MinMaxDWord

void AFXAPI DDV_MinMaxDWord( CDataExchange* pDX, DWORD const& value, DWORD minVal, DWORD maxVal );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is validated.

minVal

Minimum value (of type DWORD) allowed.

maxVal

Maximum value (of type DWORD) allowed.

Remarks

Call DDV_MinMaxDWord to verify that the value in the control associated with value falls between minVal and maxVal.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDV_MinMaxFloat

void AFXAPI DDV_MinMaxFloat( CDataExchange* pDX, float value, float minVal, float maxVal );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is validated.

minVal

Minimum value (of type float) allowed.

maxVal

Maximum value (of type float) allowed.

Remarks

Call DDV_MinMaxFloat to verify that the value in the control associated with value falls between minVal and maxVal.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDV_MinMaxInt

void AFXAPI DDV_MinMaxInt( CDataExchange* pDX, int value, int minVal, int maxVal );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is validated.

minVal

Minimum value (of type int) allowed.

maxVal

Maximum value (of type int) allowed.

Remarks

Call DDV_MinMaxInt to verify that the value in the control associated with value falls between minVal and maxVal.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDV_MinMaxLong

void AFXAPI DDV_MinMaxLong( CDataExchange* pDX, long value, long minVal, long maxVal );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is validated.

minVal

Minimum value (of type long) allowed.

maxVal

Maximum value (of type long) allowed.

Remarks

Call DDV_MinMaxLong to verify that the value in the control associated with value falls between minVal and maxVal.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDV_MinMaxMonth

void AFXAPI DDV_MinMaxMonth( CDataExchange* pDX, CTime& refValue, const CTime* refMinRange, const CTime* refMaxRange );

void AFXAPI DDV_MinMaxMonth( CDataExchange* pDX, COleDateTime& refValue, const COleDateTime* refMinRange, const COleDateTime* refMaxRange );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

refValue

A reference to an object of type CTime or COleDateTime associated with a member variable of the dialog box, form view, or control view object. This object contains the data to be validated. MFC passes this reference when DDV_MinMaxMonth is called.

refMinRange

Minimum date/time value allowed.

refMaxRange

Maximum date/time value allowed.

Remarks

Call DDV_MinMaxMonth to verify that the time/date value in the month calendar control (CMonthCalCtrl) associated with refValue falls between refMinRange and refMaxRange.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_DateTimeCtrl, DDV_MinMaxMonth


DDV_MinMaxSlider

void AFXAPI DDV_MinMaxSlider( CDataExchange* pDX, DWORD value, DWORD minVal, DWORD maxVal );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to the value to be validated. This parameter holds or sets the slider control’s current thumb position.

minVal

Minimum value allowed.

maxVal

Maximum value allowed.

Remarks

Call DDV_MinMaxSlider to verify that the value in the control associated with value falls between minVal and maxVal.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For information about slider controls, see Using CSliderCtrl in Visual C++ Programmer’s Guide.

See Also DDX_Slider, DDX_FieldSlider


DDV_MinMaxUnsigned

void AFXAPI DDV_MinMaxUnsigned( CDataExchange* pDX, unsigned value, unsigned minVal, unsigned maxVal );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is validated.

minVal

Minimum value (of type unsigned ) allowed.

maxVal

Maximum value (of type unsigned ) allowed.

Remarks

Call DDV_MinMaxUnsigned to verify that the value in the control associated with value falls between minVal and maxVal.

For more information about DDV, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDX_CBIndex

void AFXAPI DDX_CBIndex( CDataExchange* pDX, int nIDC, int& index );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the combo box control associated with the control property.

index

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_CBIndex function manages the transfer of int data between a combo box control in a dialog box, form view, or control view object and a int data member of the dialog box, form view, or control view object.

When DDX_CBIndex is called, index is set to the index of the current combo box selection. If no item is selected, index is set to 0.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDP_CBIndex


DDX_CBString

void AFXAPI DDX_CBString( CDataExchange* pDX, int nIDC, CString& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the combo box control associated with the control property.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_CBString function manages the transfer of CString data between the edit control of a combo box control in a dialog box, form view, or control view object and a CString data member of the dialog box, form view, or control view object.

When DDX_CBString is called, value is set to the current combo box selection. If no item is selected, value is set to a string of zero length.

Note If the combo box is a drop-down list box, the value exchanged is limited to 255 characters.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDP_CBString


DDX_CBStringExact

void AFXAPI DDX_CBStringExact( CDataExchange* pDX, int nIDC, CString& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the combo box control associated with the control property.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_CBStringExact function manages the transfer of CString data between the edit control of a combo box control in a dialog box, form view, or control view object and a CString data member of the dialog box, form view, or control view object.

When DDX_CBStringExact is called, value is set to the current combo box selection. If no item is selected, value is set to a string of zero length.

Note If the combo box is a drop-down list box, the value exchanged is limited to 255 characters.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDP_CBStringExact


DDX_Check

void AFXAPI DDX_Check( CDataExchange* pDX, int nIDC, int& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the check box control associated with the control property.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_Check function manages the transfer of int data between a check box control in a dialog box, form view, or control view object and a int data member of the dialog box, form view, or control view object.

When DDX_Check is called, value is set to the current state of the check box control.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDP_Check


DDX_Control

void AFXAPI DDX_Control( CDataExchange* pDX, int nIDC, CWnd& rControl );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the subclassed control associated with the control property.

rControl

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_Control function manages the transfer of data between a subclassed control in a dialog box, form view, or control view object and a CWnd data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDX_DateTimeCtrl

void AFXAPI DDX_DateTimeCtrl( CDataExchange* pDX, int nIDC, CTime& value );

void AFXAPI DDX_DateTimeCtrl( CDataExchange* pDX, int nIDC, COleDateTime& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction. You don’t need to delete this object.

nIDC

The resource ID of the date and time picker control associated with the member variable.

value

A reference to a CTime or COleDateTime member variable, dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_DateTimeCtrl function manages the transfer of date and/or time data between a date and time picker control (CDateTimeCtrl) in a dialog box or form view object and either a CTime or a COleDateTime data member of the dialog box or form view object.

When DDX_DateTimeCtrl is called, value is set to the current state of the date and time picker control, or the control is set to value, depending on the direction of the exchange.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also CDateTimeCtrl, CDateTimeCtrl::SetRange, CDateTimeCtrl::GetRange, DDV_MinMaxDateTime


DDX_FieldCBIndex

void AFXAPI DDX_FieldCBIndex( CDataExchange* pDX, int nIDC, int& index, CRecordset* pRecordset );

void AFXAPI DDX_FieldCBIndex( CDataExchange* pDX, int nIDC, int& index, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of a control in the CRecordView or CDaoRecordView object.

index

A reference to a field data member in the associated CRecordset or CDaoRecordset object.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldCBIndex function synchronizes the index of the selected item in the list box control of a combo box control in a record view and an int field data member of a recordset associated with the record view. When moving data from the recordset to the control, this function sets the selection in the control based on the value specified in index. On a transfer from the recordset to the control, if the recordset field is Null, MFC sets the value of the index to 0. On a transfer from control to recordset, if the control is empty or if no item is selected, the recordset field is set to 0.

Use the first version if you are working with the ODBC-based classes. Use the second version if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorialsand Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example. The example would be similar for DDX_FieldCBIndex.

See Also DDX_FieldText, DDX_FieldRadio, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBStringExact, DDX_FieldLBIndex, DDX_FieldScroll, DDX_CBIndex


DDX_FieldCBString

void AFXAPI DDX_FieldCBString( CDataExchange* pDX, int nIDC, CString& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldCBString( CDataExchange* pDX, int nIDC, CString& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of a control in the CRecordView or CDaoRecordView object.

value

A reference to a field data member in the associated CRecordset or CDaoRecordset object.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldCBString function manages the transfer of CString data between the edit control of a combo box control in a record view and a CString field data member of a recordset associated with the record view. When moving data from the recordset to the control, this function sets the current selection in the combo box to the first row that begins with the characters in the string specified in value. On a transfer from the recordset to the control, if the recordset field is Null, any selection is removed from the combo box and the edit control of the combo box is set to empty. On a transfer from control to recordset, if the control is empty, the recordset field is set to Null if the field permits.

Use the first version if you are working with the ODBC-based classes. Use the second version if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example. The example includes a call to DDX_FieldCBString.

See Also DDX_FieldText, DDX_FieldRadio, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBStringExact


DDX_FieldCBStringExact

void AFXAPI DDX_FieldCBStringExact( CDataExchange* pDX, int nIDC, CString& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldCBStringExact( CDataExchange* pDX, int nIDC, CString& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of a control in the CRecordView or CDaoRecordView object.

value

A reference to a field data member in the associated CRecordset or CDaoRecordset object.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldCBStringExact function manages the transfer of CString data between the edit control of a combo box control in a record view and a CString field data member of a recordset associated with the record view. When moving data from the recordset to the control, this function sets the current selection in the combo box to the first row that exactly matches the string specified in value. On a transfer from the recordset to the control, if the recordset field is Null, any selection is removed from the combo box and the edit box of the combo box is set to empty. On a transfer from control to recordset, if the control is empty, the recordset field is set to Null.

Use the first version if you are working with the ODBC-based classes. Use the second version if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example. Calls to DDX_FieldCBStringExact would be similar.

See Also DDX_FieldText, DDX_FieldRadio, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBString


DDX_FieldCheck

void AFXAPI DDX_FieldCheck( CDataExchange* pDX, int nIDC, int& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldCheck( CDataExchange* pDX, int nIDC, int& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the check box control associated with the control property.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldCheck function manages the transfer of int data between a check box control in a dialog box, form view, or control view object and an int data member of the dialog box, form view, or control view object.

When DDX_FieldCheck is called, value is set to the current state of the check box control, or the control’s state is set to value, depending on the direction of transfer.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_FieldText, DDX_FieldRadio, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBString


DDX_FieldLBIndex

void AFXAPI DDX_FieldLBIndex( CDataExchange* pDX, int nIDC, int& index, CRecordset* pRecordset );

void AFXAPI DDX_FieldLBIndex( CDataExchange* pDX, int nIDC, int& index, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of a control in the CRecordView or CDaoRecordView object.

index

A reference to a field data member in the associated CRecordset or CDaoRecordset object.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldLBIndex function synchronizes the index of the selected item in a list box control in a record view and an int field data member of a recordset associated with the record view. When moving data from the recordset to the control, this function sets the selection in the control based on the value specified in index. On a transfer from the recordset to the control, if the recordset field is Null, MFC sets the value of the index to 0. On a transfer from control to recordset, if the control is empty, the recordset field is set to 0.

Use the first version if you are working with the ODBC-based classes. Use the second version if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example.

See Also DDX_FieldText, DDX_FieldRadio, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBStringExact, DDX_FieldCBIndex, DDX_FieldScroll, DDX_LBIndex


DDX_FieldLBString

void AFXAPI DDX_FieldLBString( CDataExchange* pDX, int nIDC, CString& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldLBString( CDataExchange* pDX, int nIDC, CString& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of a control in the CRecordView or CDaoRecordView object.

value

A reference to a field data member in the associated CRecordset or CDaoRecordset object.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldLBString copies the current selection of a list box control in a record view to a CString field data member of a recordset associated with the record view. In the reverse direction, this function sets the current selection in the list box to the first row that begins with the characters in the string specified by value. On a transfer from the recordset to the control, if the recordset field is Null, any selection is removed from the list box. On a transfer from control to recordset, if the control is empty, the recordset field is set to Null.

Use the first version if you are working with the ODBC-based classes. Use the second version if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example. Calls to DDX_FieldLBString would be similar.

See Also DDX_FieldText, DDX_FieldRadio, DDX_FieldLBStringExact, DDX_FieldCBString, DDX_FieldCBStringExact, DDX_FieldCBIndex, DDX_FieldLBIndex, DDX_FieldScroll


DDX_FieldLBStringExact

void AFXAPI DDX_FieldLBStringExact( CDataExchange* pDX, int nIDC, CString& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldLBStringExact( CDataExchange* pDX, int nIDC, CString& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of a control in the CRecordView or CDaoRecordView object.

value

A reference to a field data member in the associated CRecordset or CDaoRecordset object.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldLBStringExact function copies the current selection of a list box control in a record view to a CString field data member of a recordset associated with the record view. In the reverse direction, this function sets the current selection in the list box to the first row that exactly matches the string specified in value. On a transfer from the recordset to the control, if the recordset field is Null, any selection is removed from the list box. On a transfer from control to recordset, if the control is empty, the recordset field is set to Null.

Use the first version if you are working with the ODBC-based classes. Use the second version if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example. Calls to DDX_FieldLBStringExact would be similar.

See Also DDX_FieldText, DDX_FieldRadio, DDX_FieldLBString, DDX_FieldCBString, DDX_FieldCBStringExact, DDX_FieldCBIndex, DDX_FieldLBIndex, DDX_FieldScroll


DDX_FieldSlider

void AFXAPI DDX_FieldSlider( CDataExchange* pDX, int nIDC, int& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldSlider( CDataExchange* pDX, int nIDC, int& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the slider control.

value

A reference to the value to be exchanged. This parameter holds or will be used to set the slider control’s current thumb position.

pRecordset

A pointer to the associated CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldSlider function synchronizes the thumb position of a slider control in a record view and an int field data member of a recordset associated with the record view (or with whatever integer variable you choose to map it to). When moving data from the recordset to the slider, this function sets the position of the slider to the value specified in value. On a transfer from the recordset to the control, if the recordset field is Null, the slider control’s position is set to 0. On a transfer from the control to the recordset, if the control is empty, the value of the recordset field is 0.

DDX_FieldSlider does not exchange range information with slider controls capable of setting a range rather than simply a position.

Use the first override of the function if you are working with the ODBC-based classes. Use the second override with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see Record Views in Visual C++ Programmer’s Guide. For information about slider controls, see Using CSliderCtrl in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example. Calls to DDX_FieldSlider would be similar.

See Also DDX_Slider, DDV_MinMaxSlider, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBString, DDX_FieldCBStringExact, DDX_FieldCBIndex, DDX_FieldLBIndex


DDX_FieldRadio

void AFXAPI DDX_FieldRadio( CDataExchange* pDX, int nIDC, int& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldRadio( CDataExchange* pDX, int nIDC, int& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of the first in a group (with style WS_GROUP) of adjacent radio button controls in the CRecordView or CDaoRecordView object.

value

A reference to a field data member in the associated CRecordset or CDaoRecordset object.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldRadio function associates a zero-based int member variable of a record view’s recordset with the currently selected radio button in a group of radio buttons in the record view. When transferring from the recordset field to the view, this function turns on the nth radio button (zero-based) and turns off the other buttons. In the reverse direction, this function sets the recordset field to the ordinal number of the radio button that is currently on (checked). On a transfer from the recordset to the control, if the recordset field is Null, no button is selected. On a transfer from control to recordset, if no control is selected, the recordset field is set to Null if the field permits that.

Use the first version if you are working with the ODBC-based classes. Use the second version if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example. Calls to DDX_FieldRadio would be similar.

See Also DDX_FieldText, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBString, DDX_FieldCBStringExact, DDX_FieldCBIndex, DDX_FieldLBIndex, DDX_FieldScroll


DDX_FieldScroll

void AFXAPI DDX_FieldScroll( CDataExchange* pDX, int nIDC, int& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldScroll( CDataExchange* pDX, int nIDC, int& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of the first in a group (with style WS_GROUP) of adjacent radio button controls in the CRecordView or CDaoRecordView object.

value

A reference to a field data member in the associated CRecordset or CDaoRecordset object.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged.

Remarks

The DDX_FieldScroll function synchronizes the scroll position of a scroll bar control in a record view and an int field data member of a recordset associated with the record view (or with whatever integer variable you choose to map it to). When moving data from the recordset to the control, this function sets the scroll position of the scroll bar control to the value specified in value. On a transfer from the recordset to the control, if the recordset field is Null, the scroll bar control is set to 0. On a transfer from control to recordset, if the control is empty, the value of the recordset field is 0.

Use the first version if you are working with the ODBC-based classes. Use the second version if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

See DDX_FieldText for a general DDX_Field example. Calls to DDX_FieldScroll would be similar.

See Also DDX_FieldText, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBString, DDX_FieldCBStringExact, DDX_FieldCBIndex, DDX_FieldLBIndex, DDX_Scroll


DDX_FieldText

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, BYTE& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, int& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, UINT& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, long& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, DWORD& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, CString& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, float& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, double& value, CRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, short& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, BOOL& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, BYTE& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, long& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, DWORD& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, CString& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, float& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, double& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, COleDateTime& value, CDaoRecordset* pRecordset );

void AFXAPI DDX_FieldText( CDataExchange* pDX, int nIDC, COleCurrency& value, CDaoRecordset* pRecordset );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of a control in the CRecordView or CDaoRecordView object.

value

A reference to a field data member in the associated CRecordset or CDaoRecordset object. The data type of value depends on which of the overloaded versions of DDX_FieldText you use.

pRecordset

A pointer to the CRecordset or CDaoRecordset object with which data is exchanged. This pointer enables DDX_FieldText to detect and set Null values.

Remarks

The DDX_FieldText function manages the transfer of int, short, long, DWORD, CString, float, double, BOOL, or BYTE data between an edit box control and the field data members of a recordset. For CDaoRecordset objects, DDX_FieldText also manages transferring COleDateTime, and COleCurrency values. An empty edit box control indicates a Null value. On a transfer from the recordset to the control, if the recordset field is Null, the edit box is set to empty. On a transfer from control to recordset, if the control is empty, the recordset field is set to Null.

Use the versions with CRecordset parameters if you are working with the ODBC-based classes. Use the versions with CDaoRecordset parameters if you are working with the DAO-based classes.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For examples and more information about DDX for CRecordView and CDaoRecordView fields, see the article Record Views in Visual C++ Programmer’s Guide.

Example

The following DoDataExchange function for a CRecordView contains DDX_FieldText function calls for three data types: IDC_COURSELIST is a combo box; the other two controls are edit boxes. For DAO programming, the m_pSet parameter is a pointer to a CRecordset or CDaoRecordset.

//Example for DDX_FieldText
void CSectionForm::DoDataExchange( CDataExchange* pDX )
{
    CRecordView::DoDataExchange( pDX );
    //{{AFX_DATA_MAP(CSectionForm)
    DDX_FieldCBString( pDX, IDC_COURSELIST,
                    m_pSet->m_strCourseID, m_pSet);
    DDX_FieldText( pDX, IDC_ROOM, m_pSet->m_nRoomNo,
                    m_pSet );
    DDX_FieldText( pDX, IDC_TUITION,
                    m_pSet->m_dwTuition, m_pSet );
    //}}AFX_DATA_MAP
}

See Also DDX_FieldRadio, DDX_FieldLBString, DDX_FieldLBStringExact, DDX_FieldCBString, DDX_FieldCBStringExact, DDX_FieldCBIndex, DDX_FieldLBIndex, DDX_FieldScroll


DDX_LBIndex

void AFXAPI DDX_LBIndex( CDataExchange* pDX, int nIDC, int& index );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the list box control associated with the control property.

index

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_LBIndex function manages the transfer of int data between a list box control in a dialog box, form view, or control view object and an int data member of the dialog box, form view, or control view object.

When DDX_LBIndex is called, index is set to the index of the current list box selection. If no item is selected, index is set to 0.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDP_LBIndex


DDX_LBString

void AFXAPI DDX_LBString( CDataExchange* pDX, int nIDC, CString& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the list box control associated with the control property.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_LBString function manages the transfer of CString data between the edit control of a list box control in a dialog box, form view, or control view object and a CString data member of the dialog box, form view, or control view object.

When DDX_LBString is called, value is set to the current list box selection. If no item is selected, value is set to a string of zero length.

Note If the list box is a drop-down list box, the value exchanged is limited to 255 characters.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDP_LBString


DDX_LBStringExact

void AFXAPI DDX_LBStringExact( CDataExchange* pDX, int nIDC, CString& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the list box control associated with the control property.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_CBStringExact function manages the transfer of CString data between the edit control of a list box control in a dialog box, form view, or control view object and a CString data member of the dialog box, form view, or control view object.

When DDX_CBStringExact is called, value is set to the current list box selection. If no item is selected, value is set to a string of zero length.

Note If the list box is a drop-down list box, the value exchanged is limited to 255 characters.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDX_MonthCalCtrl

void AFXAPI DDX_MonthCalCtrl( CDataExchange* pDX, int nIDC, CTime& value );

void AFXAPI DDX_MonthCalCtrl( CDataExchange* pDX, int nIDC, COleDateTime& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction. You don’t need to delete this object.

nIDC

The resource ID of the month calendar control associated with the member variable.

value

A reference to a CTime or COleDateTime member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_MonthCalCtrl function manages the transfer of date data between a month calendar control (CMonthCalCtrl) in a dialog box, form view, or control view object and either a CTime or a COleDateTime data member of the dialog box, form view, or control view object.

Note The control manages a date value only. The time fields in the time object are set to reflect the creation time of the control window, or whatever time was set in the control with a call to CMonthCalCtrl::SetCurSel.

When DDX_MonthCalCtrl is called, value is set to the current state of the month calendar control.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_DateTimeCtrl, CMonthCalCtrl, CMonthCalCtrl::GetCurSel, CMonthCalCtrl::SetCurSel


DDX_OCBool

void AFXAPI DDX_OCBool( CDataExchange* pDX, int nIDC, DISPID dispid, BOOL& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCBool function manages the transfer of BOOL data between a property of an OLE control in a dialog box, form view, or control view object and a BOOL data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCBoolRO


DDX_OCBoolRO

void AFXAPI DDX_OCBoolRO( CDataExchange* pDX, int nIDC, DISPID dispid, BOOL& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCBoolRO function manages the transfer of BOOL data between a read-only property of an OLE control in a dialog box, form view, or control view object and a BOOL data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCBool


DDX_OCColor

void AFXAPI DDX_OCColor( CDataExchange* pDX, int nIDC, DISPID dispid, OLE_COLOR& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCColor function manages the transfer of OLE_COLOR data between a property of an OLE control in a dialog box, form view, or control view object and a OLE_COLOR data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCColorRO


DDX_OCColorRO

void AFXAPI DDX_OCColorRO( CDataExchange* pDX, int nIDC, DISPID dispid, OLE_COLOR & value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCColorRO function manages the transfer of OLE_COLOR data between a read-only property of an OLE control in a dialog box, form view, or control view object and a OLE_COLOR data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCColor


DDX_OCFloat

void AFXAPI DDX_OCFloat( CDataExchange* pDX, int nIDC, DISPID dispid, float& value );

void AFXAPI DDX_OCFloat( CDataExchange* pDX, int nIDC, DISPID dispid, double& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCFloat function manages the transfer of float (or double) data between a property of an OLE control in a dialog box, form view, or control view object and a float (or double) data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCFloatRO


DDX_OCFloatRO

void AFXAPI DDX_OCFloatRO( CDataExchange* pDX, int nIDC, DISPID dispid, float& value );

void AFXAPI DDX_OCFloatRO( CDataExchange* pDX, int nIDC, DISPID dispid, double& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCFloatRO function manages the transfer of float (or double) data between a read-only property of an OLE control in a dialog box, form view, or control view object and a float (or double) data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCFloat


DDX_OCInt

void AFXAPI DDX_OCInt( CDataExchange* pDX, int nIDC, DISPID dispid, int& value );

void AFXAPI DDX_OCInt( CDataExchange* pDX, int nIDC, DISPID dispid, long& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCInt function manages the transfer of int (or long) data between a property of an OLE control in a dialog box, form view, or control view object and a int (or long) data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCIntRO


DDX_OCIntRO

void AFXAPI DDX_OCIntRO( CDataExchange* pDX, int nIDC, DISPID dispid, int& value );

void AFXAPI DDX_OCIntRO( CDataExchange* pDX, int nIDC, DISPID dispid, long& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCIntRO function manages the transfer of int (or long) data between a read-only property of an OLE control in a dialog box, form view, or control view object and a int (or long) data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCInt


DDX_OCShort

void AFXAPI DDX_OCShort( CDataExchange* pDX, int nIDC, DISPID dispid, short& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCShort function manages the transfer of short data between a property of an OLE control in a dialog box, form view, or control view object and a short data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCShortRO


DDX_OCShortRO

void AFXAPI DDX_OCShortRO( CDataExchange* pDX, int nIDC, DISPID dispid, short& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCShortRO function manages the transfer of short data between a read-only property of an OLE control in a dialog box, form view, or control view object and a short data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCShort


DDX_OCText

void AFXAPI DDX_OCText( CDataExchange* pDX, int nIDC, DISPID dispid, CString& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCText function manages the transfer of CString data between a property of an OLE control in a dialog box, form view, or control view object and a CString data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCTextRO


DDX_OCTextRO

void AFXAPI DDX_OCTextRO( CDataExchange* pDX, int nIDC, DISPID dispid, CString& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an OLE control in the dialog box, form view, or control view object.

dispid

The dispatch ID of a property of the control.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_OCTextRO function manages the transfer of CString data between a read-only property of an OLE control in a dialog box, form view, or control view object and a CString data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.

See Also DDX_OCText


DDX_Radio

void AFXAPI DDX_Radio( CDataExchange* pDX, int nIDC, int& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the radio control associated with the control property.

value

A reference to a member variable of the dialog box, form view, or control view object with which data is exchanged.

Remarks

The DDX_Radio function manages the transfer of int data between a radio control group in a dialog box, form view, or control view object and a int data member of the dialog box, form view, or control view object.

When DDX_Radio is called, value is set to the current state of the radio control group.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDX_Scroll

void AFXAPI DDX_Scroll( CDataExchange* pDX, int nIDC, int& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the scroll-bar control associated with the control property.

value

A reference to a member variable of the dialog box, form view or control view object with which data is exchanged.

Remarks

The DDX_Scroll function manages the transfer of int data between a scroll-bar control in a dialog box, form view, or control view object and an int data member of the dialog box, form view, or control view object.

When DDX_Scroll is called, value is set to the current position of the control’s thumb.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DDX_Slider

void AFXAPI DDX_Slider( CDataExchange* pDX, int nIDC, int& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The resource ID of the slider control.

value

A reference to the value to be exchanged. This parameter holds or sets the slider control’s current position.

Remarks

The DDX_Slider function manages the transfer of int data between a slider control in a dialog box or form view and an int data member of the dialog box or form view object.

When DDX_Slider is called, value is set to the current position of the control’s thumb, or the value receives the position, depending on the direction of the exchange.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide. For information about slider controls, see Using CSliderCtrl in Visual C++ Programmer’s Guide.

See Also DDX_FieldSlider, DDV_MinMaxSlider


DDX_Text

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, BYTE& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, short& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, int& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, UINT& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, long& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, DWORD& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, CString& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, float& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, double& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, COleCurrency& value );

void AFXAPI DDX_Text( CDataExchange* pDX, int nIDC, COleDateTime& value );

Parameters

pDX

A pointer to a CDataExchange object. The framework supplies this object to establish the context of the data exchange, including its direction.

nIDC

The ID of an edit control in the dialog box, form view, or control view object.

value

A reference to a data member in the dialog box, form view, or control view object. The data type of value depends on which of the overloaded versions of DDX_Text you use.

Remarks

The DDX_Text function manages the transfer of int, UINT, long, DWORD, CString, float, or double data between an edit control in a dialog box, form view, or control view and a CString data member of the dialog box, form view, or control view object.

For more information about DDX, see Adding a Dialog Box in Visual C++ Tutorials and Dialog Data Exchange and Validation in Visual C++ Programmer’s Guide.


DEBUG_NEW

#define new DEBUG_NEW

Remarks

Assists in finding memory leaks. You can use DEBUG_NEW everywhere in your program that you would ordinarily use the new operator to allocate heap storage.

In debug mode (when the _DEBUG symbol is defined), DEBUG_NEW keeps track of the filename and line number for each object that it allocates. Then, when you use the CMemoryState::DumpAllObjectsSince member function, each object allocated with DEBUG_NEW is shown with the filename and line number where it was allocated.

To use DEBUG_NEW, insert the following directive into your source files:

#define new DEBUG_NEW

Once you insert this directive, the preprocessor will insert DEBUG_NEW wherever you use new, and MFC does the rest. When you compile a release version of your program, DEBUG_NEW resolves to a simple new operation, and the filename and line number information is not generated.

Note In previous versions of MFC (4.1 and earlier) you needed to put the #define statement after all statements that called the IMPLEMENT_DYNCREATE or IMPLEMENT_SERIAL macros. This is no longer necessary.

For more information on the DEBUG_NEW macro, see MFC Debugging Support in Visual C++ Programmer’s Guide.


DECLARE_CONNECTION_MAP

DECLARE_CONNECTION_MAP( )

Remarks

Each COleControl-derived class in your program can provide a connection map to specify additional connection points that your control supports.

If your control supports additional points, use the DECLARE_CONNECTION_MAP macro at the end of your class declaration. Then, in the .CPP file that defines the member functions for the class, use the BEGIN_CONNECTION_MAP macro, CONNECTION_PART macros for each of the control’s connection points, and the END_CONNECTION_MAP macro to declare the end of the connection map.

See Also BEGIN_CONNECTION_PART, BEGIN_CONNECTION_MAP, CONNECTION_IID


DECLARE_DISPATCH_MAP

DECLARE_DISPATCH_MAP( )

Remarks

If a CCmdTarget-derived class in your program supports OLE Automation, that class must provide a dispatch map to expose its methods and properties. Use the DECLARE_DISPATCH_MAP macro at the end of your class declaration. Then, in the .CPP file that defines the member functions for the class, use the BEGIN_DISPATCH_MAP macro. Then include macro entries for each of your class’s exposed methods and properties (DISP_FUNCTION, DISP_PROPERTY, and so on). Finally, use the END_DISPATCH_MAP macro.

Note If you declare any members after DECLARE_DISPATCH_MAP, you must specify a new access type (public, private, or protected) for them.

AppWizard and ClassWizard assist in creating Automation classes and in maintaining dispatch maps: see the articles on AppWizard and ClassWizard: Automation Support. For more information on dispatch maps, see Automation Servers. All of these articles are in Visual C++ Programmer’s Guide.

Example

// example for DECLARE_DISPATCH_MAP
class CMyDoc : public CDocument
{
    // Member declarations

    DECLARE_DISPATCH_MAP()
};

See Also Dispatch Maps, BEGIN_DISPATCH_MAP, END_DISPATCH_MAP, DISP_FUNCTION, DISP_PROPERTY, DISP_PROPERTY_EX, DISP_DEFVALUE


DECLARE_DYNAMIC

DECLARE_DYNAMIC( class_name )

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

Remarks

When deriving a class from CObject, this macro adds the ability to access run-time information about an object’s class.

Add the DECLARE_DYNAMIC macro to the header (.H) module for the class, then include that module in all .CPP modules that need access to objects of this class.

If you use the DECLARE_DYNAMIC and IMPLEMENT_DYNAMIC macros as described, you can then use the RUNTIME_CLASS macro and the CObject::IsKindOf function to determine the class of your objects at run time.

If DECLARE_DYNAMIC is included in the class declaration, then IMPLEMENT_DYNAMIC must be included in the class implementation.

For more information on the DECLARE_DYNAMIC macro, see CObject Class Topics in Visual C++ Programmer’s Guide.

See Also IMPLEMENT_DYNAMIC, DECLARE_DYNCREATE, DECLARE_SERIAL, RUNTIME_CLASS, CObject::IsKindOf


DECLARE_DYNCREATE

DECLARE_DYNCREATE( class_name )

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

Remarks

Use the DECLARE_DYNCREATE macro to enable objects of CObject-derived classes to be created dynamically at run time. The framework uses this ability to create new objects dynamically, for example, when it reads an object from disk during serialization. Document, view, and frame classes should support dynamic creation because the framework needs to create them dynamically.

Add the DECLARE_DYNCREATE macro in the .H module for the class, then include that module in all .CPP modules that need access to objects of this class.

If DECLARE_DYNCREATE is included in the class declaration, then IMPLEMENT_DYNCREATE must be included in the class implementation.

For more information on the DECLARE_DYNCREATE macro, see CObject Class Topics in Visual C++ Programmer’s Guide.

See Also DECLARE_DYNAMIC, IMPLEMENT_DYNAMIC, IMPLEMENT_DYNCREATE, RUNTIME_CLASS, CObject::IsKindOf


DECLARE_EVENT_MAP

DECLARE_EVENT_MAP( )

Remarks

Each COleControl-derived class in your program can provide an event map to specify the events your control will fire. Use the DECLARE_EVENT_MAP macro at the end of your class declaration. Then, in the .CPP file that defines the member functions for the class, use the BEGIN_EVENT_MAP macro, macro entries for each of the control’s events, and the END_EVENT_MAP macro to declare the end of the event list.

For more information on event maps, see the article ActiveX Controls: Events in Visual C++ Programmer’s Guide.

See Also BEGIN_EVENT_MAP, END_EVENT_MAP, EVENT_CUSTOM, EVENT_CUSTOM_ID


DECLARE_EVENTSINK_MAP

DECLARE_EVENTSINK_MAP( )

Remarks

An OLE container can provide an event sink map to specify the events your container will be notified of. Use the DECLARE_EVENTSINK_MAP macro at the end of your class declaration. Then, in the .CPP file that defines the member functions for the class, use the BEGIN_EVENTSINK_MAP macro, macro entries for each of the events to be notified of, and the END_EVENTSINK_MAP macro to declare the end of the event sink list.

For more information on event sink maps, see the article ActiveX Control Containers in Visual C++ Programmer’s Guide.

See Also BEGIN_EVENTSINK_MAP, END_EVENTSINK_MAP, ON_EVENT, ON_PROPNOTIFY


DECLARE_MESSAGE_MAP

DECLARE_MESSAGE_MAP( )

Remarks

Each CCmdTarget-derived class in your program must provide a message map to handle messages. Use the DECLARE_MESSAGE_MAP macro at the end of your class declaration. Then, in the .CPP file that defines the member functions for the class, use the BEGIN_MESSAGE_MAP macro, macro entries for each of your message-handler functions, and the END_MESSAGE_MAP macro.

Note If you declare any member after DECLARE_MESSAGE_MAP, you must specify a new access type (public, private, or protected) for them.

For more information on message maps and the DECLARE_MESSAGE_MAP macro, see Message Handling and Mapping Topics in Visual C++ Programmer’s Guide.

Example

// example for DECLARE_MESSAGE_MAP
class CMyWnd : public CFrameWnd
{
    // Member declarations

    DECLARE_MESSAGE_MAP( )
};

See Also BEGIN_MESSAGE_MAP, END_MESSAGE_MAP


DECLARE_OLECREATE

DECLARE_OLECREATE( class_name )

#include <afxdisp.h>

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

Remarks

Use the DECLARE_OLECREATE macro to enable objects of CCmdTarget-derived classes to be created through OLE automation. This macro enables other OLE-enabled applications to create objects of this type.

Add the DECLARE_OLECREATE macro in the .H module for the class, then include that module in all .CPP modules that need access to objects of this class.

If DECLARE_OLECREATE is included in the class declaration, then IMPLEMENT_OLECREATE must be included in the class implementation. A class declaration using DECLARE_OLECREATE must also use DECLARE_DYNCREATE or DECLARE_SERIAL.

See Also IMPLEMENT_OLECREATE, DECLARE_DYNCREATE, DECLARE_SERIAL


DECLARE_OLECREATE_EX

DECLARE_OLECREATE_EX( class_name )

Parameters

class_name

The name of the control class.

Remarks

Declares a class factory and the GetClassID member function of your control class. Use this macro in the control class header file for a control that does not support licensing.

Note that this macro serves the same purpose as the following code sample:

   BEGIN_OLEFACTORY(CSampleCtrl)
   END_OLEFACTORY(CSampleCtrl)

See Also BEGIN_OLEFACTORY, END_OLEFACTORY


DECLARE_OLETYPELIB

DECLARE_OLETYPELIB( class_name )

Parameters

class_name

The name of the control class related to the type library.

Remarks

Declares the GetTypeLib member function of your control class. Use this macro in the control class header file.

See Also IMPLEMENT_OLETYPELIB


DECLARE_PROPPAGEIDS

DECLARE_PROPPAGEIDS( class_name )

Parameters

class_name

The name of the control class that owns the property pages.

Remarks

An OLE control can provide a list of property pages to display its properties. Use the DECLARE_PROPPAGEIDS macro at the end of your class declaration. Then, in the .CPP file that defines the member functions for the class, use the BEGIN_PROPPAGEIDS macro, macro entries for each of your control’s property pages, and the END_PROPPAGEIDS macro to declare the end of the property page list.

For more information on property pages, see the article ActiveX Controls: Property Pages in Visual C++ Programmer’s Guide.

See Also BEGIN_PROPPAGEIDS, END_PROPPAGEIDS


DECLARE_SERIAL

DECLARE_SERIAL( class_name )

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

Remarks

DECLARE_SERIAL generates the C++ header code necessary for a CObject-derived class that can be serialized. Serialization is the process of writing or reading the contents of an object to and from a file.

Use the DECLARE_SERIAL macro in a .H module, then include that module in all .CPP modules that need access to objects of this class.

If DECLARE_SERIAL is included in the class declaration, then IMPLEMENT_SERIAL must be included in the class implementation.

The DECLARE_SERIAL macro includes all the functionality of DECLARE_DYNAMIC and DECLARE_DYNCREATE.

You can use the AFX_API macro to automatically export the CArchive extraction operator for classes that use the DECLARE_SERIAL and IMPLEMENT_SERIAL macros. Bracket the class declarations (located in the .H file) with the following code:

#undef AFX_API
#define AFX_API AFX_EXT_CLASS

<your class declarations here>

#undef AFX_API
#define AFX_API

For more information on the DECLARE_SERIAL macro, see CObject Class Topics in Visual C++ Programmer’s Guide.

See Also DECLARE_DYNAMIC, IMPLEMENT_SERIAL, RUNTIME_CLASS, CObject::IsKindOf


DEFAULT_PARSE_COMMAND

DEFAULT_PARSE_COMMAND( FnName, mapClass )

Parameters

FnName

The name of the member function. Also the name of the command.

mapClass

The class name to map the function to.

Remarks

If the request from a client to the CHttpServer object does not contain a command, the DEFAULT_PARSE_COMMAND macro directs the framework to call the default page that’s identified by the FnName parameter.

The DEFAULT_PARSE_COMMAND macro can appear anywhere in the parse map.

See ON_PARSE_COMMAND for a parse map example.

See Also BEGIN_PARSE_MAP, ON_PARSE_COMMAND, ON_PARSE_COMMAND_PARAMS, END_PARSE_MAP, CHttpServer


DestructElements

template< class TYPE >
void AFXAPI DestructElements( TYPE* pElements, int nCount );

Parameters

TYPE

Template parameter specifying the type of the elements to be destroyed.

pElements

Pointer to the elements.

nCount

Number of elements to be destroyed.

Remarks

The CArray, CList, and CMap class members call this function when elements are destroyed.

The default implementation calls the destructor for each element. For information on implementing this and other helper functions, see the article Collections: How to Make a Type-Safe Collection in Visual C++ Programmer’s Guide.

See Also CArray, CList, CMap


DFX_Binary

void AFXAPI DFX_Binary( CDaoFieldExchange* pFX, LPCTSTR szName, CByteArray& value, int nPreAllocSize = AFX_DAO_BINARY_DEFAULT_SIZE, DWORD dwBindOptions = 0 );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For additional information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type CByteArray, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

nPreAllocSize

The framework preallocates this amount of memory. If your data is larger, the framework will allocated more space as needed. For better performance, set this size to a value large enough to prevent reallocations. The default size is defined in the AFXDAO.H file as AFX_DAO_BINARY_DEFAULT_SIZE.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_DISABLE_FIELD_CACHE, does not use double buffering and you must call SetFieldDirty and SetFieldNull yourself. The other possible value, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering, and you do not have to do extra work to mark fields dirty or Null. For performance and memory reasons, avoid this value unless your binary data is relatively small.

These options are explained further in the article DAO Record Field Exchange: Double Buffering Records in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered for all fields by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_Binary function transfers arrays of bytes between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_BYTES in DAO and type CByteArray in the recordset.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_Currency, DFX_Long, DFX_Short, DFX_Single, DFX_Double, DFX_DateTime, DFX_Byte, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_Bool

void AFXAPI DFX_Bool( CDaoFieldExchange* pFX, LPCTSTR szName, BOOL& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For additional information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type BOOL, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_BOOL function transfers Boolean data between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_BOOL in DAO and type BOOL in the recordset.

Example

See DFX_Text.

See Also DFX_Text, DFX_Long, DFX_Currency, DFX_Short, DFX_Single, DFX_Double, DFX_DateTime, DFX_Byte, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_Byte

void AFXAPI DFX_Byte( CDaoFieldExchange* pFX, LPCTSTR szName, BYTE& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type BYTE, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_Byte function transfers single bytes between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_BYTES in DAO and type BYTE in the recordset.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_Currency, DFX_Long, DFX_Short, DFX_Single, DFX_Double, DFX_DateTime, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_Currency

void AFXAPI DFX_Currency( CDaoFieldExchange* pFX, LPCTSTR szName, COleCurrency& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, this value is taken from the specified data member, of type COleCurrency. For a transfer from data source to recordset, the value is stored in the specified data member.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_Currency function transfers currency data between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_CURRENCY in DAO and type COleCurrency in the recordset.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_DateTime, DFX_Long, DFX_Short, DFX_Single, DFX_Double, DFX_Byte, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_DateTime

void AFXAPI DFX_DateTime( CDaoFieldExchange* pFX, LPCTSTR szName, COleDateTime& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. The function takes a reference to a COleDateTime object. For a transfer from recordset to data source, this value is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_DateTime function transfers time and date data between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_DATE in DAO and type COleDateTime in the recordset.

Note COleDateTime replaces CTime and TIMESTAMP_STRUCT for this purpose in the DAO classes. CTime and TIMESTAMP_STRUCT are still used for the ODBC-based data access classes.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_Currency, DFX_Long, DFX_Short, DFX_Single, DFX_Double, DFX_Byte, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_Double

void AFXAPI DFX_Double( CDaoFieldExchange* pFX, LPCTSTR szName, double& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type double, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_Double function transfers double float data between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_R8 in DAO and type double float in the recordset.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_Currency, DFX_Long, DFX_Short, DFX_Single, DFX_DateTime, DFX_Byte, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_Long

void AFXAPI DFX_Long( CDaoFieldExchange* pFX, LPCTSTR szName, long& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type long, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_Long function transfers long integer data between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_I4 in DAO and type long in the recordset.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_Currency, DFX_Short, DFX_Single, DFX_Double, DFX_DateTime, DFX_Byte, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_LongBinary

void AFXAPI DFX_LongBinary( CDaoFieldExchange* pFX, LPCTSTR szName, CLongBinary& value, DWORD dwPreAllocLength = AFX_DAO_LONGBINARY_DEFAULT_SIZE, DWORD dwBindOptions = 0 );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type CLongBinary, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

nPreAllocSize

The framework preallocates this amount of memory. If your data is larger, the framework will allocated more space as needed. For better performance, set this size to a value large enough to prevent reallocations.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DISABLE_FIELD_CACHE, does not use double buffering. The other possible value is AFX_DAO_ENABLE_FIELD_CACHE. Uses double buffering, and you do not have to do extra work to mark fields dirty or Null. For performance and memory reasons, avoid this value unless your binary data is relatively small.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

Important It is recommended that you use DFX_Binary instead of this function. DFX_LongBinary is provided for compatibility with the MFC ODBC classes.

The DFX_LongBinary function transfers binary large object (BLOB) data using class CLongBinary between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_BYTES in DAO and type CLongBinary in the recordset.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_Currency, DFX_Long, DFX_Short, DFX_Single, DFX_Double, DFX_DateTime, DFX_Byte, CDaoFieldExchange::SetFieldType, CLongBinary


DFX_Short

void AFXAPI DFX_Short( CDaoFieldExchange* pFX, LPCTSTR szName, short& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type short, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_Short function transfers short integer data between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_I2 in DAO and type short in the recordset.

Note DFX_Short is equivalent to RFX_Int for the ODBC-based classes.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_Currency, DFX_Long, DFX_Single, DFX_Double, DFX_DateTime, DFX_Byte, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_Single

void AFXAPI DFX_Single( CDaoFieldExchange* pFX, LPCTSTR szName, float& value, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type float, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Recordset: Binding Records Dynamically in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_Single function transfers floating point data between the field data members of a CDaoRecordset object and the columns of a record on the data source. Data is mapped between type DAO_R4 in DAO and type float in the recordset.

Example

See DFX_Text.

See Also DFX_Text, DFX_Bool, DFX_Currency, DFX_Long, DFX_Short, DFX_Double, DFX_DateTime, DFX_Byte, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DFX_Text

void AFXAPI DFX_Text( CDaoFieldExchange* pFX, LPCTSTR szName, CString& value, int nPreAllocLength = AFX_DAO_TEXT_DEFAULT_SIZE, DWORD dwBindOptions = AFX_DAO_ENABLE_FIELD_CACHE );

Parameters

pFX

A pointer to an object of class CDaoFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CDaoFieldExchange object can specify, see the article DAO Record Field Exchange: How DFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type CString, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

nPreAllocSize

The framework preallocates this amount of memory. If your data is larger, the framework will allocated more space as needed. For better performance, set this size to a value large enough to prevent reallocations.

dwBindOptions

An option that lets you take advantage of MFC’s double buffering mechanism for detecting recordset fields that have changed. The default, AFX_DAO_ENABLE_FIELD_CACHE, uses double buffering. The other possible value is AFX_DAO_DISABLE_FIELD_CACHE. If you specify this value, MFC does no checking on this field. You must call SetFieldDirty and SetFieldNull yourself.

These options are explained further in the article DAO Record Field Exchange: Double Buffering Records in Visual C++ Programmer's Guide.

Note You can control whether data is double buffered by default by setting CDaoRecordset::m_bCheckCacheForDirtyFields.

Remarks

The DFX_Text function transfers CString data between the field data members of a CDaoRecordset object and columns of a record on the data source. Data is mapped between type DAO_CHAR in DAO (or, if the symbol _UNICODE is defined, DAO_WCHAR) and type CString in the recordset.

Example

This example shows several calls to DFX_Text. Notice also the two calls to CDaoFieldExchange::SetFieldType. ClassWizard normally writes the second call to SetFieldType and its associated DFX calls. You must write the first call and its DFX call. It is recommended that you put any parameter items before the “//{{AFX_FIELD_MAP” comment. You must put parameters outside the comments.

//Example for DFX_Text
void CSections::DoFieldExchange(CDaoFieldExchange* pFX)
{
    pFX->SetFieldType(CDaoFieldExchange::param);
    DFX_Text(pFX, "Name", m_strNameParam);
    //{{AFX_FIELD_MAP(CSections)
    pFX->SetFieldType(CDaoFieldExchange::outputColumn);
    DFX_Text(pFX, "CourseID", m_strCourseID);
    DFX_Text(pFX, "InstructorID", m_strInstructorID);
    DFX_Short(pFX, "LabFee", m_nRoomNo);
    DFX_Text(pFX, "LabFee", m_strSchedule);
    DFX_Short(pFX, "SectionNo", m_nSectionNo);
    DFX_Currency(pFX, "LabFee", m_currLabFee);
    //}}AFX_FIELD_MAP
}

See Also DFX_Bool, DFX_Long, DFX_Currency, DFX_Short, DFX_Single, DFX_Double, DFX_DateTime, DFX_Byte, DFX_Binary, DFX_LongBinary, CDaoFieldExchange::SetFieldType


DISP_DEFVALUE

DISP_DEFVALUE( theClass, pszName )

#include <afxdisp.h>

Parameters

theClass

Name of the class.

pszName

External name of the property that represents the “value” of the object.

Remarks

This macro makes an existing property the default value of an object. Using a default value can make programming your automation object simpler for Visual Basic applications.

The “default value” of your object is the property that is retrieved or set when a reference to an object does not specify a property or member function.

See Also Dispatch Maps, DECLARE_DISPATCH_MAP, DISP_PROPERTY_EX, DISP_FUNCTION, BEGIN_DISPATCH_MAP, END_DISPATCH_MAP


DISP_FUNCTION

DISP_FUNCTION( theClass, pszName, pfnMember, vtRetVal, vtsParams )

#include <afxdisp.h>

Parameters

theClass

Name of the class.

pszName

External name of the function.

pfnMember

Name of the member function.

vtRetVal

A value specifying the function’s return type.

vtsParams

A space-separated list of one or more constants specifying the function’s parameter list.

Remarks

The DISP_FUNCTION macro is used in a dispatch map to define an OLE automation function.

The vtRetVal argument is of type VARTYPE. Possible values for this argument are taken from the VARENUM enumeration. They are as follows:

Symbol | Return Type
VT_EMPTY | void
VT_I2 | short
VT_I4 | long
VT_R4 | float
VT_R8 | double
VT_CY | CY
VT_DATE | DATE
VT_BSTR | BSTR
VT_DISPATCH | LPDISPATCH
VT_ERROR | SCODE
VT_BOOL | BOOL
VT_VARIANT | VARIANT
VT_UNKNOWN | LPUNKNOWN

The vtsParams argument is a space-separated list of values from the VTS_ constants. One or more of these values separated by spaces (not commas) specifies the function’s parameter list. For example,

VTS_I2 VTS_PI2

specifies a list containing a short integer followed by a pointer to a short integer.

The VTS_ constants and their meanings are as follows:

Symbol | Parameter Type
VTS_I2 | short
VTS_I4 | long
VTS_R4 | float
VTS_R8 | double
VTS_CY | const CY or CY*
VTS_DATE | DATE
VTS_BSTR | LPCSTR
VTS_DISPATCH | LPDISPATCH
VTS_SCODE | SCODE
VTS_BOOL | BOOL
VTS_VARIANT | const VARIANT* or VARIANT&
VTS_UNKNOWN | LPUNKNOWN
VTS_PI2 | short*
VTS_PI4 | long*
VTS_PR4 | float*
VTS_PR8 | double*
VTS_PCY | CY*
VTS_PDATE | DATE*
VTS_PBSTR | BSTR*
VTS_PDISPATCH | LPDISPATCH*
VTS_PSCODE | SCODE*
VTS_PBOOL | BOOL*
VTS_PVARIANT | VARIANT*
VTS_PUNKNOWN | LPUNKNOWN*

See Also Dispatch Maps, DECLARE_DISPATCH_MAP, DISP_PROPERTY, DISP_PROPERTY_EX, BEGIN_DISPATCH_MAP, END_DISPATCH_MAP


DISP_PROPERTY

DISP_PROPERTY( theClass, pszName, memberName, vtPropType )

#include <afxdisp.h>

Parameters

theClass

Name of the class.

pszName

External name of the property.

memberName

Name of the member variable in which the property is stored.

vtPropType

A value specifying the property’s type.

Remarks

The DISP_PROPERTY macro is used in a dispatch map to define an OLE automation property.

The vtPropType argument is of type VARTYPE. Possible values for this argument are taken from the VARENUM enumeration:

Symbol | Property Type
VT_I2 | short
VT_I4 | long
VT_R4 | float
VT_R8 | double
VT_CY | CY
VT_DATE | DATE
VT_BSTR | CString
VT_DISPATCH | LPDISPATCH
VT_ERROR | SCODE
VT_BOOL | BOOL
VT_VARIANT | VARIANT
VT_UNKNOWN | LPUNKNOWN

When an external client changes the property, the value of the member variable specified by memberName changes; there is no notification of the change.

See Also Dispatch Maps, DECLARE_DISPATCH_MAP, DISP_PROPERTY_EX, DISP_FUNCTION, BEGIN_DISPATCH_MAP, END_DISPATCH_MAP


DISP_PROPERTY_EX

DISP_PROPERTY_EX( theClass, pszName, memberGet, memberSet, vtPropType )

#include <afxdisp.h>

Parameters

theClass

Name of the class.

pszName

External name of the property.

memberGet

Name of the member function used to get the property.

memberSet

Name of the member function used to set the property.

vtPropType

A value specifying the property’s type.

Remarks

The DISP_PROPERTY_EX macro is used in a dispatch map to define an OLE automation property and name the functions used to get and set the property’s value.

The memberGet and memberSet functions have signatures determined by the vtPropType argument. The memberGet function takes no arguments and returns a value of the type specified by vtPropType. The memberSet function takes an argument of the type specified by vtPropType and returns nothing.

The vtPropType argument is of type VARTYPE. Possible values for this argument are taken from the the VARENUM enumeration. For a list of these values, see the Remarks for the vtRetVal parameter in DISP_FUNCTION. Note that VT_EMPTY, listed in the DISP_FUNCTION remarks, is not permitted as a property data type.

See Also Dispatch Maps, DECLARE_DISPATCH_MAP, DISP_PROPERTY, DISP_FUNCTION, BEGIN_DISPATCH_MAP, END_DISPATCH_MAP


DISP_PROPERTY_NOTIFY

DISP_PROPERTY_NOTIFY( theClass, szExternalName, memberName, pfnAfterSet, vtPropType )

#include <afxdisp.h>

Parameters

theClass

Name of the class.

szExternalName

External name of the property.

memberName

Name of the member variable in which the property is stored.

pfnAfterSet

Name of the notification function for szExternalName.

vtPropType

A value specifying the property’s type.

Remarks

The DISP_PROPERTY_NOTIFY macro is used in a dispatch map to define an OLE automation property with notification. Unlike properties defined with DISP_PROPERTY, a property defined with DISP_PROPERTY_NOTIFY will automatically call the function specified by pfnAfterSet when the property is changed.

The vtPropType argument is of type VARTYPE. Possible values for this argument are taken from the VARENUM enumeration:

Symbol | Property Type
VT_I2 | short
VT_I4 | long
VT_R4 | float
VT_R8 | double
VT_CY | CY
VT_DATE | DATE
VT_BSTR | CString
VT_DISPATCH | LPDISPATCH
VT_ERROR | SCODE
VT_BOOL | BOOL
VT_VARIANT | VARIANT
VT_UNKNOWN | LPUNKNOWN

See Also Dispatch Maps, DISP_PROPERTY, DISP_FUNCTION


DISP_PROPERTY_PARAM

DISP_PROPERTY_NOTIFY( theClass, pszExternalName, pfnGet, pfnSet, vtPropType, vtsParams )

#include <afxdisp.h>

Parameters

theClass

Name of the class.

pszExternalName

External name of the property.

pfnGet

Name of the member function used to get the property.

pfnSet

Name of the member function used to set the property.

vtPropType

A value specifying the property’s type.

vtsParams

A string of space-separated VTS_ variant parameter types, one for each parameter.

Remarks

This macro defines a property accessed with separate Get and Set member functions. Unlike the DISP_PROPERTY_EX macro, this macro allows you to specify a parameter list for the property. This is useful for implementing properties which are indexed or parameterized.

For example, consider the following declaration of get and set member functions that allow the user to request a specific row and column when accessing the property:

afx_msg short GetArray(short row, short column);
afx_msg short SetArray(short row, short column, short nNewValue);

These correspond to the following DISP_PROPERTY_PARAM macro in the control dispatch map:

DISP_PROPERTY_PARAM(CMyCtrl, "Array", GetArray, SetArray, VT-I2, VTS_I2 VTS_I2)

As another example, consider the following get and set member functions:

LPDISPATCH CMyObject::GetItem(short index1, short index2, short index3);
void CMyObject::SetItem(short index1, short index2, short index3, LPDISPATCH newValue);

These correspond to the following DISP_PROPERTY_PARAM macro in the control dispatch map:

DISP_PROPERTY_PARAM(CMyObject, "item", GetItem, SetItem, VT_DISPATCH,     VTS_I2 VTS_I2 VTS_I2)

See Also Dispatch Maps, DISP_PROPERTY _EX


DumpElements

template< class TYPE >
void AFXAPI DumpElements( CDumpContext& dc, const TYPE* pElements, int nCount );

Parameters

dc

Dump context for dumping elements.

TYPE

Template parameter specifying the type of the elements.

pElements

Pointer to the elements to be dumped.

nCount

Number of elements to be dumped.

Remarks

Override this function to provide stream-oriented diagnostic output in text form for the elements of your collection. The CArray::Dump, CList::Dump, and CMap::Dump functions call this if the depth of the dump is greater than 0.

The default implementation does nothing. If the elements of your collection are derived from CObject, your override will typically iterate through the collection’s elements, calling Dump for each element in turn.

For information on diagnostics and on the Dump function, see MFC Debugging Support in Visual C++ Programmer’s Guide.

See Also CDumpContext::SetDepth, CObject::Dump, CArray, CList, CMap


DYNAMIC_DOWNCAST

DYNAMIC_DOWNCAST( class, pointer )

Parameters

class

The name of a class.

pointer

A pointer to be cast to a pointer to a object of type class.

Remarks

The DYNAMIC_DOWNCAST macro provides a handy way to cast a pointer to a pointer to a class object while checking to see if the cast is legal. The macro will cast the pointer parameter to a pointer to an object of the class parameter's type.

If the object referenced by the pointer is a "kind of" the identified class, the macro returns the appropriate pointer. If it isn't a legal cast the macro returns NULL.

See Also STATIC_DOWNCAST


END_CATCH

END_CATCH

Remarks

Marks the end of the last CATCH or AND_CATCH block.

For more information on the END_CATCH macro, see the article Exceptions in Visual C++ Programmer’s Guide.

See Also TRY, CATCH, AND_CATCH, THROW, THROW_LAST


END_CATCH_ALL

END_CATCH_ALL

Remarks

Marks the end of the last CATCH_ALL or AND_CATCH_ALL block.

See Also TRY, CATCH_ALL, AND_CATCH_ALL, THROW, THROW_LAST


END_CONNECTION_MAP

END_CONNECTION_MAP( )

Remarks

Use the END_CONNECTION_MAP macro to end the definition of your connection map.

See Also BEGIN_CONNECTION_MAP, DECLARE_CONNECTION_MAP


END_CONNECTION_PART

END_CONNECTION_PART( localClass )

Parameters

localClass

Specifies the name of the local class that implements the connection point.

Remarks

Use the END_CONNECTION_PART macro to end the declaration of your connection point.

See Also BEGIN_CONNECTION_PART, DECLARE_CONNECTION_MAP


END_DISPATCH_MAP

END_DISPATCH_MAP( )

#include <afxdisp.h>

Remarks

Use the END_DISPATCH_MAP macro to end definition of your dispatch map. It must be used in conjunction with BEGIN_DISPATCH_MAP.

See Also Dispatch Maps, DECLARE_DISPATCH_MAP, BEGIN_DISPATCH_MAP, DISP_FUNCTION, DISP_PROPERTY, DISP_PROPERTY_EX, DISP_DEFVALUE


END_EVENT_MAP

END_EVENT_MAP( )

Remarks

Use the END_EVENT_MAP macro to end the definition of your event map.

See Also DECLARE_EVENT_MAP, BEGIN_EVENT_MAP


END_EVENTSINK_MAP

END_EVENTSINK_MAP( )

Remarks

Use the END_EVENTSINK_MAP macro to end the definition of your event sink map.

See Also DECLARE_EVENTSINK_MAP, BEGIN_EVENTSINK_MAP


END_MESSAGE_MAP

END_MESSAGE_MAP( )

Remarks

Use the END_MESSAGE_MAP macro to end the definition of your message map.

For more information on message maps and the END_MESSAGE_MAP macro, see Message Handling and Mapping Topics in Visual C++ Programmer’s Guide.

See Also DECLARE_MESSAGE_MAP, BEGIN_MESSAGE_MAP, Message Map Function Categories


END_OLEFACTORY

END_OLEFACTORY( class_name )

Parameters

class_name

The name of the control class whose class factory this is.

Remarks

Use the END_OLEFACTORY macro to end the declaration of your control’s class factory.

See Also BEGIN_OLEFACTORY, DECLARE_OLECREATE_EX


END_PARSE_MAP

END_PARSE_MAP( theClass )

Parameters

theClass

Specifies the name of the class that owns this parse map.

Remarks

Use the END_PARSE_MAP macro to end the definition of your parse map. It must be used in conjunction with BEGIN_PARSE_MAP.

See ON_PARSE_COMMAND for a parse map example.

See Also BEGIN_PARSE_MAP, ON_PARSE_COMMAND, ON_PARSE_COMMAND_PARAMS, DEFAULT_PARSE_COMMAND, CHttpServer


END_PROPPAGEIDS

END_PROPPAGEIDS( class_name )

Parameters

class_name

The name of the control class that owns the property page.

Remarks

Use the END_PROPPAGEIDS macro to end the definition of your property page ID list.

See Also DECLARE_PROPPAGEIDS, BEGIN_PROPPAGEIDS


EVENT_CUSTOM

EVENT_CUSTOM( pszName, pfnFire, vtsParams )

Parameters

pszName

The name of the event.

pfnFire

The name of the event firing function.

vtsParams

A space-separated list of one or more constants specifying the function’s parameter list.

Remarks

Use the EVENT_CUSTOM macro to define an event-map entry for a custom event.

The vtsParams parameter is a space-separated list of values from the VTS_ constants. One or more of these values separated by spaces (not commas) specifies the function’s parameter list. For example:

VTS_COLOR VTS_FONT

specifies a list containing a short integer followed by a BOOL.

The VTS_ constants and their meanings are as follows:

Symbol | Parameter Type
VTS_I2 | short
VTS_I4 | long
VTS_R4 | float
VTS_R8 | double
VTS_COLOR | OLE_COLOR
VTS_CY | CURRENCY
VTS_DATE | DATE
VTS_BSTR | const char*
VTS_DISPATCH | LPDISPATCH
VTS_FONT | IFontDispatch*
VTS_HANDLE | HANDLE
VTS_SCODE | SCODE
VTS_BOOL | BOOL
VTS_VARIANT | const VARIANT*
VTS_PVARIANT | VARIANT*
VTS_UNKNOWN | LPUNKNOWN
VTS_OPTEXCLUSIVE | OLE_OPTEXCLUSIVE
VTS_PICTURE | IPictureDisp*
VTS_TRISTATE | OLE_TRISTATE
VTS_XPOS_PIXELS | OLE_XPOS_PIXELS
VTS_YPOS_PIXELS | OLE_YPOS_PIXELS
VTS_XSIZE_PIXELS | OLE_XSIZE_PIXELS
VTS_YSIZE_PIXELS | OLE_YSIZE_PIXELS
VTS_XPOS_HIMETRIC | OLE_XPOS_HIMETRIC
VTS_YPOS_HIMETRIC | OLE_YPOS_HIMETRIC
VTS_XSIZE_HIMETRIC | OLE_XSIZE_HIMETRIC
VTS_YSIZE_HIMETRIC | OLE_YSIZE_HIMETRIC

Note Additional variant constants have been defined for all variant types, with the exception of VTS_FONT and VTS_PICTURE, that provide a pointer to the variant data constant. These constants are named using the VTS_P constantname convention. For example, VTS_PCOLOR is a pointer to a VTS_COLOR constant.

See Also EVENT_CUSTOM_ID, DECLARE_EVENT_MAP


EVENT_CUSTOM_ID

EVENT_CUSTOM_ID( pszName, dispid, pfnFire, vtsParams )

Parameters

pszName

The name of the event.

dispid

The dispatch ID used by the control when firing the event.

pfnFire

The name of the event firing function.

vtsParams

A variable list of parameters passed to the control container when the event is fired.

Remarks

Use the EVENT_CUSTOM_ID macro to define an event firing function for a custom event belonging to the dispatch ID specified by dispid.

The vtsParams argument is a space-separated list of values from the VTS_ constants. One or more of these values separated by spaces (not commas) specifies the function’s parameter list. For example:

VTS_COLOR VTS_FONT

specifies a list containing a short integer followed by a BOOL.

For a list of the VTS_ constants, see EVENT_CUSTOM.

See Also EVENT_CUSTOM


HashKey

template< class ARG_KEY >
UINT AFXAPI HashKey( ARG_KEY key );

Return Value

The key’s hash value.

Parameters

ARG_KEY

Template parameter specifying the data type used to access map keys.

key

The key whose hash value is to be calculated.

Remarks

Calculates a hash value for the given key.

This function is called directly by CMap::RemoveKey and indirectly by CMap::Lookup and CMap::Operator [].

The default implementation creates a hash value by shifting key rightward by four positions. Override this function so that it returns hash values appropriate for your application.

See Also CMap


IMPLEMENT_DYNAMIC

IMPLEMENT_DYNAMIC( class_name, base_class_name )

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

base_class_name

The name of the base class (not enclosed in quotation marks).

Remarks

Generates the C++ code necessary for a dynamic CObject-derived class with run-time access to the class name and position within the hierarchy. Use the IMPLEMENT_DYNAMIC macro in a .CPP module, then link the resulting object code only once.

For more information, see CObject Class Topics in Visual C++ Programmer’s Guide.

See Also DECLARE_DYNAMIC, RUNTIME_CLASS, CObject::IsKindOf


IMPLEMENT_DYNCREATE

IMPLEMENT_DYNCREATE( class_name, base_class_name )

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

base_class_name

The actual name of the base class (not enclosed in quotation marks).

Remarks

Use the IMPLEMENT_DYNCREATE macro with the DECLARE_DYNCREATE macro to enable objects of CObject-derived classes to be created dynamically at run time. The framework uses this ability to create new objects dynamically, for example, when it reads an object from disk during serialization. Add the IMPLEMENT_DYNCREATE macro in the class implementation file. For more information, see CObject Class Topics in Visual C++ Programmer’s Guide.

If you use the DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE macros, you can then use the RUNTIME_CLASS macro and the CObject::IsKindOf member function to determine the class of your objects at run time.

If DECLARE_DYNCREATE is included in the class declaration, then IMPLEMENT_DYNCREATE must be included in the class implementation.

See Also DECLARE_DYNCREATE, RUNTIME_CLASS, CObject::IsKindOf


IMPLEMENT_OLECREATE

IMPLEMENT_OLECREATE( class_name, external_name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8 )

#include <afxdisp.h>

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

external_name

The object name exposed to other applications (enclosed in quotation marks).

l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8

Components of the class’s CLSID.

Remarks

This macro must appear in the implementation file for any class that uses DECLARE_OLECREATE.

The external name is the identifier exposed to other applications. Client applications use the external name to request an object of this class from an automation server.

The OLE class ID is a unique 128-bit identifier for the object. It consists of one long, two WORDs, and eight BYTEs, as represented by l, w1, w2, and b1 through b8 in the syntax description. ClassWizard and AppWizard create unique OLE class IDs for you as required.

See Also DECLARE_OLECREATE, CLSID Key.


IMPLEMENT_OLECREATE_EX

IMPLEMENT_OLECREATE_EX( class_name, external_name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8 )

Parameters

class_name

The name of the control property page class.

external_name

The object name exposed to applications.

l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8

Components of the class’s CLSID. For more information on these parameters, see the Remarks for IMPLEMENT_OLECREATE.

Remarks

Implements your control’s class factory and the GetClassID member function of your control class. This macro must appear in the implementation file for any control class that uses the DECLARE_OLECREATE_EX macro or the BEGIN_OLEFACTORY and END_OLEFACTORY macros. The external name is the identifier of the OLE control that is exposed to other applications. Containers use this name to request an object of this control class.

See Also DECLARE_OLECREATE_EX, BEGIN_OLEFACTORY, END_OLEFACTORY, IMPLEMENT_OLECREATE


IMPLEMENT_OLETYPELIB

IMPLEMENT_OLETYPELIB( class_name, tlid, wVerMajor, wVerMinor )

Parameters

class_name

The name of the control class related to the type library.

tlid

The ID number of the type library.

wVerMajor

The type library major version number.

wVerMinor

The type library minor version number.

Remarks

Implements the control’s GetTypeLib member function. This macro must appear in the implementation file for any control class that uses the DECLARE_OLETYPELIB macro.

See Also DECLARE_OLETYPELIB


IMPLEMENT_SERIAL

IMPLEMENT_SERIAL( class_name, base_class_name, wSchema )

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

base_class_name

The name of the base class (not enclosed in quotation marks).

wSchema

A UINT “version number” that will be encoded in the archive to enable a deserializing program to identify and handle data created by earlier program versions. The class schema number must not be –1.

Remarks

Generates the C++ code necessary for a dynamic CObject-derived class with run-time access to the class name and position within the hierarchy. Use the IMPLEMENT_SERIAL macro in a .CPP module; then link the resulting object code only once.

You can use the AFX_API macro to automatically export the CArchive extraction operator for classes that use the DECLARE_SERIAL and IMPLEMENT_SERIAL macros. Bracket the class declarations (located in the .H file) with the following code:

#undef AFX_API
#define AFX_API AFX_EXT_CLASS

<your class declarations here>

#undef AFX_API
#define AFX_API

For more information, see the CObject Class Topics in Visual C++ Programmer’s Guide.

See Also DECLARE_SERIAL, RUNTIME_CLASS, CObject::IsKindOf


ISAPIASSERT

ISAPIASSERT( booleanExpression )

Parameters

booleanExpression

Specifies an expression (including pointer values) that evaluates to nonzero or 0.

Remarks

Works exactly like the MFC macro ASSERT. Evaluates its argument. If the result is 0, the macro prints a diagnostic message and aborts the program. If the condition is nonzero, it does nothing.

The diagnostic message has the form

assertion failed in file <name> in line <num>

where name is the name of the source file, and num is the line number of the assertion that failed in the source file.

In the release version of your application, ISAPIASSERT does not evaluate the expression and thus will not interrupt the program. If the expression must be evaluated regardless of environment, use the ISAPIVERIFY macro in place of ISAPIASSERT. ISAPIASSERT is available only in the debug version of your application.

ISAPI applications do not have to use MFC. If MFC is not linked to your application, ISAPIASSERT provides the same ASSERT functionality. If your application is linked to the MFC, ISAPIASSERT simply calls MFC's ASSERT.

See Also ISAPITRACE, ISAPITRACE0, ISAPITRACE1, ISAPITRACE2, ISAPITRACE3, ISAPIVERIFY


ISAPITRACE

ISAPITRACE( exp )

Parameters

exp

Specifies a variable number of arguments that are used in exactly the same way that a variable number of arguments are used in the run-time function printf.

Remarks

Works exactly like the MFC macro TRACE, which itself provides functionality similar to the printf function by sending a formatted string to a dump device such as debug monitor. Like printf for C programs under MS-DOS, the ISAPITRACE macro is a convenient way to track the value of variables as your program executes. In the Debug environment, the ISAPITRACE macro output goes to the Debug window of Visual C++. In the Release environment, it does nothing.

ISAPI applications do not have to use MFC. If MFC is not linked to your application, ISAPITRACE provides the same TRACE functionality. If your application is linked to the MFC, ISAPITRACE simply calls MFC's TRACE.

See Also ISAPIASSERT, ISAPITRACE0, ISAPITRACE1, ISAPITRACE2, ISAPITRACE3, ISAPIVERIFY


ISAPITRACE0

ISAPITRACE0( exp )

Parameters

exp

A format string as used in the run-time function printf.

Remarks

ISAPITRACE0 is one variant of a group of trace macros that you can use for debug output. This group includes ISAPITRACE0, ISAPITRACE1, ISAPITRACE2, and ISAPITRACE3. The difference between these macros is the number of parameters taken. ISAPITRACE0 only takes a format string and can be used for simple text messages. ISAPITRACE1 takes a format string plus one argument — a variable to be dumped. Likewise, ISAPITRACE2 and ISAPITRACE3 take two and three parameters after the format string, respectively.

ISAPITRACE0 does nothing if you have compiled a release version of your application. As with ISAPITRACE, it only dumps data to the debug output device if you have compiled a debug version of your application.

ISAPITRACE0 works exactly like the MFC macro TRACE0. ISAPI applications do not have to use MFC. If MFC is not linked to your application, ISAPITRACE0 provides the same TRACE0 functionality. If your application is linked to the MFC, ISAPITRACE0 simply calls MFC's TRACE0.

See Also ISAPIASSERT, ISAPITRACE, ISAPITRACE1, ISAPITRACE2, ISAPITRACE3, ISAPIVERIFY


ISAPITRACE1

ISAPITRACE1( exp, param1 )

Parameters

exp

A format string as used in the run-time function printf.

param1

The name of the variable whose value should be dumped.

Remarks

Works exactly like the MFC macro TRACE1. See ISAPITRACE0 for a description of ISAPITRACE1.

ISAPI applications do not have to use MFC. If MFC is not linked to your application, ISAPITRACE1 provides the same TRACE1 functionality. If your application is linked to the MFC, ISAPITRACE1 simply calls MFC's TRACE1.

See Also ISAPIASSERT, ISAPITRACE, ISAPITRACE0, ISAPITRACE2, ISAPITRACE3, ISAPIVERIFY


ISAPITRACE2

ISAPITRACE2( exp, param1, param2 )

Parameters

exp

A format string as used in the run-time function printf.

param1, param2

The name of the variable whose value should be dumped.

Remarks

Works exactly like the MFC macro TRACE2. See ISAPITRACE0 for a description of ISAPITRACE2.

ISAPI applications do not have to use MFC. If MFC is not linked to your application, ISAPITRACE2 provides the same TRACE2 functionality. If your application is linked to the MFC, ISAPITRACE2 simply calls MFC's TRACE2.

See Also ISAPIASSERT, ISAPITRACE, ISAPITRACE0, ISAPITRACE1, ISAPITRACE3, ISAPIVERIFY


ISAPITRACE3

ISAPITRACE3( exp, param1, param2, param3 )

Parameters

exp

A format string as used in the run-time function printf.

param1, param2, param3

The name of the variable whose value should be dumped.

Remarks

Works exactly like the MFC macro TRACE3. See ISAPITRACE0 for a description of ISAPITRACE3.

ISAPI applications do not have to use MFC. If MFC is not linked to your application, ISAPITRACE3 provides the same TRACE3 functionality. If your application is linked to the MFC, ISAPITRACE3 simply calls MFC's TRACE3.

See Also ISAPIASSERT, ISAPITRACE, ISAPITRACE0, ISAPITRACE1, ISAPITRACE2, ISAPIVERIFY


ISAPIVERIFY

ISAPIVERIFY( booleanExpression )

Parameters

booleanExpression

Specifies an expression (including pointer values) that evaluates to nonzero or 0.

Remarks

Works exactly like the MFC macro VERIFY. In the debug version of your application, the ISAPIVERIFY macro evaluates its argument. If the result is 0, the macro prints a diagnostic message and halts the program. If the condition is nonzero, it does nothing.

The diagnostic message has the form

assertion failed in file <name> in line <num>

where name is the name of the source file and num is the line number of the assertion that failed in the source file.

In the release version of your application, ISAPIVERIFY evaluates the expression but does not print or interrupt the program. For example, if the expression is a function call, the call will be made.

ISAPI applications do not have to use MFC. If MFC is not linked to your application, ISAPIVERIFY provides the same VERIFY functionality. If your application is linked to the MFC, ISAPIVERIFY simply calls MFC's VERIFY.

See Also ISAPIASSERT, ISAPITRACE, ISAPITRACE0, ISAPITRACE1, ISAPITRACE2, ISAPITRACE3


METHOD_PROLOGUE

METHOD_PROLOGUE( theClass, localClass )

Parameters

theClass

Specifies the name of the class whose interface map is being implemented.

localClass

Specifies the name of the local class that implements the interface map.

Remarks

Use the METHOD_PROLOGUE macro to maintain the proper global state when calling methods of an exported interface.

Typically, member functions of interfaces implemented by CCmdTarget-derived objects already use this macro to provide automatic initialization of the pThis pointer. For example:

class CInnerUnknown : public IUnknown
   ...
   CInnerUnknown InnerUnknown;
   ...
// Inner IUnknown implementation

   STDMETHODIMP_(ULONG) CInnerUnknown::AddRef()
   {
   METHOD_PROLOGUE(CCmdTarget, InnerUnknown)
   return pThis->InternalAddRef();
   }

For additional information, see Technical Note 38 and "Managing the State Data of MFC Modules" in Creating New Documents, Windows, and Views, which is in Visual C++ Programmer’s Guide.


ON_COMMAND

ON_COMMAND( id, memberFxn )

Parameters

id

The command ID.

memberFxn

The name of the message-handler function to which the command is mapped.

Remarks

This macro is usually inserted in a message map by ClassWizard or manually. It indicates which function will handle a command message from a command user-interface object such as a menu item or toolbar button.

When a command-target object receives a Windows WM_COMMAND message with the specified ID, ON_COMMAND will call the member function memberFxn to handle the message.

Use ON_COMMAND to map a single command to a member function. Use ON_COMMAND_RANGE to map a range of command ids to one member function. Only one message-map entry can match a given command id. That is, you can’t map a command to more than one handler. For more information and examples, see Message Handling and Mapping Topics in Visual C++ Programmer’s Guide.

Example

// example for ON_COMMAND
BEGIN_MESSAGE_MAP( CMyDoc, CDocument )
    //{{AFX_MSG_MAP( CMyDoc )
    ON_COMMAND( ID_MYCMD, OnMyCommand )
    // ... More entries to handle additional commands
    //}}AFX_MSG_MAP
END_MESSAGE_MAP( )

See Also ON_UPDATE_COMMAND_UI


ON_COMMAND_RANGE

ON_COMMAND_RANGE( id1, id2, memberFxn )

Parameters

id1

Command ID at the beginning of a contiguous range of command IDs.

id2

Command ID at the end of a contiguous range of command IDs.

memberFxn

The name of the message-handler function to which the commands are mapped.

Remarks

Use this macro to map a contiguous range of command IDs to a single message handler function. The range of IDs starts with id1 and ends with id2.

Use ON_COMMAND_RANGE to map a range of command IDs to one member function. Use ON_COMMAND to map a single command to a member function. Only one message-map entry can match a given command ID. That is, you can’t map a command to more than one handler. For more information on mapping message ranges, see Handlers for Message-Map Ranges in Visual C++ Programmer’s Guide.

ClassWizard does not support message map ranges, so you must place the macro yourself. Be sure to put it outside the message map //{{AFX_MSG_MAP delimiters.

See Also ON_UPDATE_COMMAND_UI_RANGE, ON_CONTROL_RANGE, ON_COMMAND


ON_CONTROL

ON_CONTROL( wNotifyCode, id, memberFxn )

Parameters

wNotifyCode

The notification code of the control.

id

The command ID.

memberFxn

The name of the message-handler function to which the command is mapped.

Remarks

Indicates which function will handle a custom-control notification message. Control notification messages are those sent from a control to its parent window.

There should be exactly one ON_CONTROL macro statement in your message map for every control notification message that must be mapped to a message-handler function.

For more information and examples, see Message Handling and Mapping Topics in Visual C++ Programmer’s Guide.

See Also ON_MESSAGE, ON_REGISTERED_MESSAGE


ON_CONTROL_RANGE

ON_CONTROL_RANGE( wNotifyCode, id1, id2, memberFxn )

Parameters

wNotifyCode

The notification code to which your handler is responding.

id1

Command ID at the beginning of a contiguous range of control IDs.

id2

Command ID at the end of a contiguous range of control IDs.

memberFxn

The name of the message-handler function to which the controls are mapped.

Remarks

Use this macro to map a contiguous range of control IDs to a single message handler function for a specified Windows notification message, such as BN_CLICKED. The range of IDs starts with id1 and ends with id2. The handler is called for the specified notification coming from any of the mapped controls.

ClassWizard does not support message map ranges, so you must place the macro yourself. Be sure to put it outside the message map //{{AFX_MSG_MAP delimiters.

See Also ON_UPDATE_COMMAND_UI_RANGE, ON_COMMAND_RANGE


ON_EVENT

ON_EVENT( theClass, id, dispid, pfnHandler, vtsParams )

Parameters

theClass

The class to which this event sink map belongs.

id

The control ID of the OLE control.

dispid

The dispatch ID of the event fired by the control.

pfnHandler

Pointer to a member function that handles the event. This function should have a BOOL return type, and parameter types that match the event's parameters (see vtsParams). The function should return TRUE to indicate the event was handled; otherwise FALSE.

vtsParams

A sequence of VTS_ constants that specifies the types of the parameters for the event. These are the same constants that are used in dispatch map entries such as DISP_FUNCTION.

Remarks

Use the ON_EVENT macro to define an event handler function for an event fired by an OLE control.

The vtsParams argument is a space-separated list of values from the VTS_ constants. One or more of these values separated by spaces (not commas) specifies the function’s parameter list. For example:

VTS_I2 VTS_BOOL

specifies a list containing a short integer followed by a BOOL.

For a list of the VTS_ constants, see EVENT_CUSTOM.

See Also ON_EVENT_RANGE, ON_PROPNOTIFY, ON_PROPNOTIFY_RANGE


ON_EVENT_RANGE

ON_EVENT_RANGE( theClass, idFirst, idLast, dispid, pfnHandler, vtsParams )

Parameters

theClass

The class to which this event sink map belongs.

idFirst

The control ID of the first OLE control in the range.

idLast

The control ID of the last OLE control in the range.

dispid

The dispatch ID of the event fired by the control.

pfnHandler

Pointer to a member function that handles the event. This function should have a BOOL return type, a first parameter of type UINT (for the control ID), and additional parameter types that match the event’s parameters (see vtsParams). The function should return TRUE to indicate the event was handled; otherwise FALSE.

vtsParams

A sequence of VTS_ constants that specifies the types of the parameters for the event. The first constant should be of type VTS_I4, for the control ID. These are the same constants that are used in dispatch map entries such as DISP_FUNCTION.

Remarks

Use the ON_EVENT_RANGE macro to define an event handler function for an event fired by any OLE control having a control ID within a contiguous range of IDs.

The vtsParams argument is a space-separated list of values from the VTS_ constants. One or more of these values separated by spaces (not commas) specifies the function’s parameter list. For example:

VTS_I2 VTS_BOOL

specifies a list containing a short integer followed by a BOOL.

For a list of the VTS_ constants, see EVENT_CUSTOM.

See Also ON_EVENT, ON_PROPNOTIFY, ON_PROPNOTIFY_RANGE


ON_EVENT_REFLECT

ON_EVENT_REFLECT( theClass, dispid, pfnHandler, vtsParams )

Parameters

theClass

The class to which this event sink map belongs.

dispid

The dispatch ID of the event fired by the control.

pfnHandler

Pointer to a member function that handles the event. This function should have a BOOL return type and parameter types that match the event's parameters (see vtsParams). The function should return TRUE to indicate the event was handled; otherwise FALSE.

vtsParams

A sequence of VTS_ constants that specifies the types of the parameters for the event. These are the same constants that are used in dispatch map entries such as DISP_FUNCTION.

Remarks

The ON_EVENT_REFLECT macro, when used in the event sink map of an OLE control's wrapper class, receives events fired by the control before they are handled by the control's container.

The vtsParams argument is a space-separated list of values from the VTS_ constants.

One or more of these values separated by spaces (not commas) specifies the function's parameter list. For example:

VTS_I2 VTS_BOOL

specifies a list containing a short integer followed by a BOOL.

For a list of the VTS_ constants, see EVENT_CUSTOM.

See Also ON_EVENT, ON_PROPNOTIFY, ON_PROPNOTIFY_REFLECT


ON_MESSAGE

ON_MESSAGE( message, memberFxn )

Parameters

message

The message ID.

memberFxn

The name of the message-handler function to which the message is mapped.

Remarks

Indicates which function will handle a user-defined message. User-defined messages are usually defined in the range WM_USER to 0x7FFF. User-defined messages are any messages that are not standard Windows WM_MESSAGE messages. There should be exactly one ON_MESSAGE macro statement in your message map for every user-defined message that must be mapped to a message-handler function.

For more information and examples, see Message Handling and Mapping Topics in Visual C++ Programmer’s Guide.

Example

// example for ON_MESSAGE
#define WM_MYMESSAGE (WM_USER + 1)
BEGIN_MESSAGE_MAP( CMyWnd, CMyParentWndClass )
    //{{AFX_MSG_MAP( CMyWnd
    ON_MESSAGE( WM_MYMESSAGE, OnMyMessage )
    // ... Possibly more entries to handle additional messages
    //}}AFX_MSG_MAP
END_MESSAGE_MAP( )

See Also ON_UPDATE_COMMAND_UI, ON_CONTROL, ON_REGISTERED_MESSAGE, ON_COMMAND, User-Defined Handlers


ON_OLECMD

ON_OLECMD( pguid, olecmdid, id )

Parameters

pguid

Identifier of the command group to which the command belongs. Use NULL for the standard group.

olecmdid

The identifier of the OLE command.

id

The menu ID, toolbar ID, button ID, or other ID of the resource or object issuing the command.

Remarks

Routes commands through the command dispatch interface IOleCommandTarget. IOleCommandTarget allows a container to receive commands that originate in a DocObject’s user interface, and allows the container to send the same commands (such as New, Open, SaveAs, and Print on the File menu; and Copy, Paste, Undo, and so forth on the Edit menu) to a DocObject.

IOleCommandTarget is simpler than OLE Automation’s IDispatch. IOleCommandTarget relies entirely on a standard set of commands that rarely have arguments, and no type information is involved (type safety is diminished for command arguments as well). If you do need to dispatch commands with arguments, use COleServerDoc::OnExecOleCmd.

The IOleCommandTarget standard menu commands have been implemented by MFC in the following macros:

ON_OLECMD_CLEARSELECTION( )
Dispatches the Edit Clear command. Implemented as:
ON_OLECMD(NULL, OLECMDID_CLEARSELECTION, ID_EDIT_CLEAR)

ON_OLECMD_COPY( )
Dispatches the Edit Copy command. Implemented as:
ON_OLECMD(NULL, OLECMDID_COPY, ID_EDIT_COPY)

ON_OLECMD_CUT( )
Dispatches the Edit Cut command. Implemented as:
ON_OLECMD(NULL, OLECMDID_CUT, ID_EDIT_CUT)

ON_OLECMD_NEW( )
Dispatches the File New command. Implemented as:
ON_OLECMD(NULL, OLECMDID_NEW, ID_FILE_NEW)

ON_OLECMD_OPEN( )
Dispatches the File Open command. Implemented as:
ON_OLECMD(NULL, OLECMDID_OPEN, ID_FILE_OPEN)

ON_OLECMD_PAGESETUP( )
Dispatches the File Page Setup command. Implemented as:
ON_OLECMD(NULL, OLECMDID_PAGESETUP, ID_FILE_PAGE_SETUP)

ON_OLECMD_PASTE( )
Dispatches the Edit Paste command. Implemented as:
ON_OLECMD(NULL, OLECMDID_PASTE, ID_EDIT_PASTE)

ON_OLECMD_PASTESPECIAL( )
Dispatches the Edit Paste Special command. Implemented as:
ON_OLECMD(NULL, OLECMDID_PASTESPECIAL, ID_EDIT_PASTE_SPECIAL)

ON_OLECMD_PRINT( )
Dispatches the File Print command. Implemented as:
ON_OLECMD(NULL, OLECMDID_PRINT, ID_FILE_PRINT)

ON_OLECMD_PRINTPREVIEW( )
Dispatches the File Print Preview command. Implemented as:
ON_OLECMD(NULL, OLECMDID_PRINTPREVIEW, ID_FILE_PRINT_PREVIEW)

ON_OLECMD_REDO( )
Dispatches the Edit Redo command. Implemented as:
ON_OLECMD(NULL, OLECMDID_REDO, ID_EDIT_REDO)

ON_OLECMD_SAVE( )
Dispatches the File Save command. Implemented as:
ON_OLECMD(NULL, OLECMDID_SAVE, ID_FILE_SAVE)

ON_OLECMD_SAVE_AS( )
Dispatches the File Save As command. Implemented as:
ON_OLECMD(NULL, OLECMDID_SAVEAS, ID_FILE_SAVE_AS)

ON_OLECMD_SAVE_COPY_AS( )
Dispatches the File Save Copy As command. Implemented as:
ON_OLECMD(NULL, OLECMDID_SAVECOPYAS, ID_FILE_SAVE_COPY_AS)

ON_OLECMD_SELECTALL( )
Dispatches the Edit Select All command. Implemented as:
ON_OLECMD(NULL, OLECMDID_SELECTALL, ID_EDIT_SELECT_ALL)

ON_OLECMD_UNDO( )
Dispatches the Edit Undo command. Implemented as:
ON_OLECMD(NULL, OLECMDID_UNDO, ID_EDIT_UNDO)

See Also COleCmdUI, COleServerDoc::OnExecOleCmd


ON_OLEVERB

ON_OLEVERB( idsVerbName, memberFxn )

Parameters

idsVerbName

The string resource ID of the verb’s name.

memberFxn

The function called by the framework when the verb is invoked.

Remarks

This macro defines a message map entry that maps a custom verb to a specific member function of your control.

The resource editor can be used to create custom verb names that are added to your string table.

The function prototype for memberFxn is:

BOOL memberFxn( LPMSG lpMsg, HWND hWndParent, LPCRECT lpRect );

The values of the lpMsg, hWndParent, and lpRect parameters are taken from the corresponding parameters of the IOleObject::DoVerb member function.

See Also ON_STDOLEVERB


ON_PARSE_COMMAND

ON_PARSE_COMMAND( FnName, mapClass, Args )

Parameters

FnName

The name of the member function. Also the name of the command.

mapClass

The class name to map the function to.

Args

The arguments that map to the parameter’s FnName. See Remarks for a list of symbols.

Remarks

The ON_PARSE_COMMAND macro is used in a parse map to define a command to a CHttpServer object from a client.

The member function identified by FnName must take a pointer to the CHttpServerContext as its first parameter. FnName is of the type LPSTR, and is identified by the symbol ITS_LPSTR in the parse map; that is, FnName points to a string containing the member function in class mapClass.

The parameter Args can take one of the following values:

Symbol | Type or Comment
ITS_EMPTY | Args cannot be blank. Use ITS_EMPTY if you have no arguments.
ITS_PSTR | A pointer to a string.
ITS_RAW | The exact, raw data sent to the ISAPI extension. Do not use ITS_RAW with any other parameter type; to do so will cause an ASSERT. See Remarks for an example.
ITS_I2 | a short
ITS_I4 | a long
ITS_R4 | a float
ITS_R8 | a double

Examples

// The following  example Illustrates extracting
//  a string and a short sent to the server:

BEGIN_PARSE_MAP(CDerivedClass, CHttpServer)
   DEFAULT_PARSE_COMMAND(Myfunc, CDerivedClass)
   ON_PARSE_COMMAND(Myfunc, CDerivedClass, ITS_PSTR
    ITS_I2)
   ON_PARSE_COMMAND_PARAMS("string integer=42")
   ON_PARSE_COMMAND(Myfunc2, CDerivedClass, ITS_PSTR
    ITS_I2 ITS_PSTR)
   ON_PARSE_COMMAND_PARAMS("string integer
    string2='Default value'")
END_PARSE_MAP(CDerivedClass)

Note Use single quotes if you incorporate spaces into the default values for optional ITS_PSTRs.

void Myfunc(CHttpServerContext* pCtxt, LPTSTR pszName, int nNumber);
void Myfunc2(CHttpServerContext* pCtxt, LPTSTR pszName, int nNumber, LPTSTR pszTitle);

// The following  example Illustrates extracting
// raw data sent to the server:

BEGIN_PARSE_MAP(CDerivedClass, CHttpServer)
   DEFAULT_PARSE_COMMAND(Myfunc, CDerivedClass)
   ON_PARSE_COMMAND(Myfunc, CDerivedClass, ITS_RAW)
END_PARSE_MAP(CDerivedClass)

with the function prototype as follows:

void CDerivedClass::Myfunc(CHttpServerContext* pCtxt, void* pVoid, DWORD dwBytes);

In the second example above, the pVoid pointer points to the data sent to your extension. The dwBytes parameter has a count of bytes at pVoid. If dwBytes is zero, pVoid may not point to anything.

Note The handlers for a parse map command must take a pointer to a CHttpServerContext as the first parameter, and the parameters must be declared in the same order in which they're defined in ON_PARSE_COMMAND.

See Also BEGIN_PARSE_MAP, END_PARSE_MAP, ON_PARSE_COMMAND_PARAMS, DEFAULT_PARSE_COMMAND, CHttpServer


ON_PARSE_COMMAND_PARAMS

ON_PARSE_COMMAND_PARAMS( Params )

Parameters

Params

The parameters, mapped to the Args parameter and associated with the function identified by FnName, in the macro ON_PARSE_COMMAND immediately preceding ON_PARSE_COMMAND_PARAMS.

Remarks

The macro ON_PARSE_COMMAND_PARAMS identifies and specifies defaults for the parameters associated with the function that is mapped to a command to a CHttpServer object by a client. The macro ON_PARSE_COMMAND_PARAMS must immediately follow the ON_PARSE_COMMAND macro with which it is associated.

If a parameter is named, the client must supply the parameter name in the query. For example, if your parameters are as follows:

ON_PARSE_COMMAND_PARAMS("string int=42")

then the parameter string must be supplied by the client, or the query will fail.

If the parameter is optional, the client need not supply it, and the parse map will supply the default value. For example, if your parameters are as follows:

ON_PARSE_COMMAND_PARAMS("string=default int=42")

then neither parameter must be defined in the client’s query, and the parameter string is by default an empty string.

See ON_PARSE_COMMAND for a parse map example.

See Also BEGIN_PARSE_MAP, END_PARSE_MAP, ON_PARSE_COMMAND, DEFAULT_PARSE_COMMAND, CHttpServer


ON_PROPNOTIFY

ON_PROPNOTIFY( theClass, id, dispid, pfnRequest, pfnChanged )

Parameters

theClass

The class to which this event sink map belongs.

id

The control ID of the OLE control.

dispid

The dispatch ID of the property involved in the notification.

pfnRequest

Pointer to a member function that handles the OnRequestEdit notification for this property. This function should have a BOOL return type and a BOOL* parameter. This function should set the parameter to TRUE to allow the property to change and FALSE to disallow. The function should return TRUE to indicate the notification was handled; otherwise FALSE.

pfnChanged

Pointer to a member function that handles the OnChanged notification for this property. The function should have a BOOL return type and a UINT parameter. The function should return TRUE to indicate that notification was handled; otherwise FALSE.

Remarks

Use the ON_PROPNOTIFY macro to define an event sink map entry for handling property notifications from an OLE control.

The vtsParams argument is a space-separated list of values from the VTS_ constants. One or more of these values separated by spaces (not commas) specifies the function’s parameter list. For example:

VTS_I2 VTS_BOOL

specifies a list containing a short integer followed by a BOOL.

For a list of the VTS_ constants, see EVENT_CUSTOM.

See Also ON_EVENT_RANGE, ON_PROPNOTIFY_RANGE


ON_PROPNOTIFY_RANGE

ON_PROPNOTIFY_RANGE( theClass, idFirst, idLast, dispid, pfnRequest, pfnChanged )

Parameters

theClass

The class to which this event sink map belongs.

idFirst

The control ID of the first OLE control in the range.

idLast

The control ID of the last OLE control in the range.

dispid

The dispatch ID of the property involved in the notification.

pfnRequest

Pointer to a member function that handles the OnRequestEdit notification for this property. This function should have a BOOL return type and UINT and BOOL* parameters. The function should set the parameter to TRUE to allow the property to change and FALSE to disallow. The function should return TRUE to indicate that notification was handled; otherwise FALSE.

pfnChanged

Pointer to a member function that handles the OnChanged notification for this property. The function should have a BOOL return type and a UINT parameter. The function should return TRUE to indicate that notification was handled; otherwise FALSE.

Remarks

Use the ON_PROPNOTIFY_RANGE macro to define an event sink map entry for handling property notifications from any OLE control having a control ID within a contiguous range of IDs.

See Also ON_EVENT_RANGE, ON_PROPNOTIFY, ON_EVENT


ON_PROPNOTIFY_REFLECT

ON_PROPNOTIFY_REFLECT( theClass, dispid, pfnRequest, pfnChanged )

Parameters

theClass

The class to which this event sink map belongs.

dispid

The dispatch ID of the property involved in the notification.

pfnRequest

Pointer to a member function that handles the OnRequestEdit notification for this property. This function should have a BOOL return type and a BOOL* parameter. This function should set the parameter to TRUE to allow the property to change and FALSE to disallow. The function should return TRUE to indicate the notification was handled; otherwise FALSE.

pfnChanged

Pointer to a member function that handles the OnChanged notification for this property. The function should have a BOOL return type and no parameters. The function should return TRUE to indicate the notification was handled; otherwise FALSE.

Remarks

The ON_PROPNOTIFY_REFLECT macro, when used in the event sink map of an OLE control's wrapper class, receives property notifications sent by the control before they are handled by the control's container.

See Also ON_EVENT_REFLECT, ON_PROPNOTIFY


ON_REGISTERED_MESSAGE

ON_REGISTERED_MESSAGE( nMessageVariable, memberFxn )

Parameters

nMessageVariable

The registered window-message ID variable.

memberFxn

The name of the message-handler function to which the message is mapped.

Remarks

The Windows RegisterWindowMessage function is used to define a new window message that is guaranteed to be unique throughout the system. This macro indicates which function will handle the registered message.

For more information and examples, see Message Handling and Mapping Topics in Visual C++ Programmer’s Guide.

Example

// example for ON_REGISTERED_MESSAGE
const UINT    wm_Find = RegisterWindowMessage( FINDMSGSTRING )
BEGIN_MESSAGE_MAP( CMyWnd, CMyParentWndClass )
    //{{AFX_MSG_MAP( CMyWnd )
    ON_REGISTERED_MESSAGE( wm_Find, OnFind )
    // ... Possibly more entries to handle additional messages
    //}}AFX_MSG_MAP
END_MESSAGE_MAP( )

See Also ON_MESSAGE, ON_UPDATE_COMMAND_UI, ON_CONTROL, ON_COMMAND, ::RegisterWindowMessage, User-Defined Handlers


ON_REGISTERED_THREAD_MESSAGE

ON_REGISTERED_THREAD_MESSAGE( nMessageVariable, memberFxn )

Parameters

nMessageVariable

The registered window-message ID variable.

memberFxn

The name of the CWinThread-message-handler function to which the message is mapped.

Remarks

Indicates which function will handle the message registered by the Windows RegisterWindowMessage function. RegisterWindowMessage is used to define a new window message that is guaranteed to be unique throughout the system. ON_REGISTERED_THREAD_MESSAGE must be used instead of ON_REGISTERED_MESSAGE when you have a CWinThread class.

See Also ON_REGISTERED_MESSAGE, ON_THREAD_MESSAGE, ::RegisterWindowMessage, CWinThread


ON_STDOLEVERB

ON_STDOLEVERB( iVerb, memberFxn )

Parameters

iVerb

The standard verb index for the verb being overridden.

memberFxn

The function called by the framework when the verb is invoked.

Remarks

Use this macro to override the default behavior of a standard verb.

The standard verb index is of the form OLEIVERB_, followed by an action. OLEIVERB_SHOW, OLEIVERB_HIDE, and OLEIVERB_UIACTIVATE are some examples of standard verbs.

See ON_OLEVERB for a description of the function prototype to be used as the memberFxn parameter.

See Also ON_OLEVERB


ON_THREAD_MESSAGE

ON_THREAD_MESSAGE( message, memberFxn )

Parameters

message

The message ID.

memberFxn

The name of the CWinThread-message-handler function to which the message is mapped.

Remarks

Indicates which function will handle a user-defined message. ON_THREAD_MESSAGE must be used instead of ON_MESSAGE when you have a CWinThread class. User-defined messages are any messages that are not standard Windows WM_MESSAGE messages. There should be exactly one ON_THREAD_MESSAGE macro statement in your message map for every user-defined message that must be mapped to a message-handler function.

See Also ON_MESSAGE, ON_REGISTERED_THREAD_MESSAGE, CWinThread


ON_UPDATE_COMMAND_UI

ON_UPDATE_COMMAND_UI( id, memberFxn )

Parameters

id

The message ID.

memberFxn

The name of the message-handler function to which the message is mapped.

Remarks

This macro is usually inserted in a message map by ClassWizard to indicate which function will handle a user-interface update command message.

There should be exactly one ON_UPDATE_COMMAND_UI macro statement in your message map for every user-interface update command that must be mapped to a message-handler function.

For more information and examples, see Message Handling and Mapping Topics in Visual C++ Programmer’s Guide.

See Also ON_MESSAGE, ON_REGISTERED_MESSAGE, ON_CONTROL, ON_COMMAND, CCmdUI


ON_UPDATE_COMMAND_UI_RANGE

ON_UPDATE_COMMAND_UI_RANGE( id1, id2, memberFxn )

Parameters

id1

Command ID at the beginning of a contiguous range of command IDs.

id2

Command ID at the end of a contiguous range of command IDs.

memberFxn

The name of the update message-handler function to which the commands are mapped.

Remarks

Use this macro to map a contiguous range of command IDs to a single update message handler function. Update message handlers update the state of menu items and toolbar buttons associated with the command. The range of IDs starts with id1 and ends with id2.

ClassWizard does not support message map ranges, so you must place the macro yourself. Be sure to put it outside the message map //{{AFX_MSG_MAP delimiters.

See Also ON_COMMAND_RANGE, ON_CONTROL_RANGE


PROPPAGEID

PROPPAGEID( clsid )

Parameters

clsid

The unique class ID of a property page.

Remarks

Use this macro to add a property page for use by your OLE control. All PROPPAGEID macros must be placed between the BEGIN_PROPPAGEIDS and END_PROPPAGEIDS macros in your control’s implementation file.

See Also BEGIN_PROPPAGEIDS, END_PROPPAGEIDS


PX_Blob

BOOL PX_Blob( CPropExchange* pPX, LPCTSTR pszPropName, HGLOBAL& hBlob, HGLOBAL hBlobDefault = NULL );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

hBlob

Reference to the variable where the property is stored (typically a member variable of your class).

hBlobDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property that stores binary large object (BLOB) data. The property’s value will be read from or written to the variable referenced by hBlob, as appropriate. This variable should be initialized to NULL before initially calling PX_Blob for the first time (typically, this can be done in the control’s constructor). If hBlobDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s initialization or serialization process fails.

The handles hBlob and hBlobDefault refer to a block of memory which contains the following:

  • A DWORD which contains the length, in bytes, of the binary data that follows, followed immediately by

  • A block of memory containing the actual binary data.

Note that PX_Blob will allocate memory, using the Windows GlobalAlloc API, when loading BLOB-type properties. You are responsible for freeing this memory. Therefore, the destructor of your control should call GlobalFree on any BLOB-type property handles to free up any memory allocated to your control.

See Also COleControl::DoPropExchange


PX_Bool

BOOL PX_Bool( CPropExchange* pPX, LPCTSTR pszPropName, BOOL& bValue );

BOOL PX_Bool( CPropExchange* pPX, LPCTSTR pszPropName, BOOL& bValue, BOOL bDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

bValue

Reference to the variable where the property is stored (typically a member variable of your class).

bDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type BOOL. The property’s value will be read from or written to the variable referenced by bValue, as appropriate. If bDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_Color

BOOL PX_Color( CPropExchange* pPX, LPCTSTR pszPropName, OLE_COLOR& clrValue );

BOOL PX_Color( CPropExchange* pPX, LPCTSTR pszPropName, OLE_COLOR& clrValue, OLE_COLOR clrDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

clrValue

Reference to the variable where the property is stored (typically a member variable of your class).

clrDefault

Default value for the property, as defined by the control developer.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type OLE_COLOR. The property’s value will be read from or written to the variable referenced by clrValue, as appropriate. If clrDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_Currency

BOOL PX_Currency( CPropExchange* pPX, LPCTSTR pszPropName, CY& cyValue );

BOOL PX_Currency( CPropExchange* pPX, LPCTSTR pszPropName, CY& cyValue, CY cyDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

cyValue

Reference to the variable where the property is stored (typically a member variable of your class).

cyDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type currency. The property’s value will be read from or written to the variable referenced by cyValue, as appropriate. If cyDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_DataPath

BOOL PX_DataPath( CPropExchange* pPX, LPCTSTR pszPropName, CDataPathProperty& dataPathProperty );

BOOL PX_DataPath( CPropExchange* pPXe, CDataPathProperty& dataPathProperty );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

dataPathProperty

Reference to the variable where the property is stored (typically a member variable of your class).

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a data path property of type CDataPathProperty. Data path properties implement asynchronous control properties. The property’s value will be read from or written to the variable referenced by dataPathProperty, as appropriate.

See Also COleControl::DoPropExchange, CDataPathProperty


PX_Double

BOOL PX_Double( CPropExchange* pPX, LPCTSTR pszPropName, double& doubleValue );

BOOL PX_Double( CPropExchange* pPX, LPCTSTR pszPropName, double& doubleValue, double doubleDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

doubleValue

Reference to the variable where the property is stored (typically a member variable of your class).

doubleDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type double. The property’s value is read from or written to the variable referenced by doubleValue, as appropriate. If doubleDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange, PX_Float, PX_Short


PX_Float

BOOL PX_Float( CPropExchange* pPX, LPCTSTR pszPropName, float& floatValue );

BOOL PX_Float( CPropExchange* pPX, LPCTSTR pszPropName, float& floatValue, float floatDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

floatValue

Reference to the variable where the property is stored (typically a member variable of your class).

floatDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type float. The property’s value is read from or written to the variable referenced by floatValue, as appropriate. If floatDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange, PX_Double, PX_String


PX_Font

BOOL PX_Font( CPropExchange* pPX, LPCTSTR pszPropName, CFontHolder& font, const FONTDESC FAR* pFontDesc = NULL, LPFONTDISP pFontDispAmbient = NULL );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

font

A reference to a CFontHolder object that contains the font property.

pFontDesc

A pointer to a FONTDESC structure containing the values to use in initializing the default state of the font property, in the case where pFontDispAmbient is NULL.

pFontDispAmbient

A pointer to the IFontDisp interface of a font to use in initializing the default state of the font property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type font. The property’s value is read from or written to font, a CFontHolder reference, when appropriate. If pFontDesc and pFontDispAmbient are specified, they are used for initializing the property’s default value, when needed. These values are used if, for any reason, the control’s serialization process fails. Typically, you pass NULL for pFontDesc and the ambient value returned by COleControl::AmbientFont for pFontDispAmbient. Note that the font object returned by COleControl::AmbientFont must be released by a call to the IFontDisp::Release member function.

See Also COleControl::DoPropExchange, COleControl::AmbientFont


PX_IUnknown

BOOL PX_IUnknown( CPropExchange* pPX, LPCTSTR pszPropName, LPUNKNOWN& pUnk, REFIID iid, LPUNKNOWN pUnkDefault = NULL );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

pUnk

Reference to a variable containing the interface of the object that represents the value of the property.

iid

An interface ID indicating which interface of the property object is used by the control.

pUnkDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property represented by an object having an IUnknown-derived interface. The property’s value is read from or written to the variable referenced by pUnk, as appropriate. If pUnkDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_Long

BOOL PX_Long( CPropExchange* pPX, LPCTSTR pszPropName, long& lValue );

BOOL PX_Long( CPropExchange* pPX, LPCTSTR pszPropName, long& lValue, long lDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

lValue

Reference to the variable where the property is stored (typically a member variable of your class).

lDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type long. The property’s value is read from or written to the variable referenced by lValue, as appropriate. If lDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_Picture

BOOL PX_Picture( CPropExchange* pPX, LPCTSTR pszPropName, CPictureHolder& pict );

BOOL PX_Picture( CPropExchange* pPX, LPCTSTR pszPropName, CPictureHolder& pict, CPictureHolder& pictDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

pict

Reference to a CPictureHolder object where the property is stored (typically a member variable of your class).

pictDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a picture property of your control. The property’s value is read from or written to the variable referenced by pict, as appropriate. If pictDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_Short

BOOL PX_Short( CPropExchange* pPX, LPCTSTR pszPropName, short& sValue );

BOOL PX_Short( CPropExchange* pPX, LPCTSTR pszPropName, short& sValue, short sDefault);

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

sValue

Reference to the variable where the property is stored (typically a member variable of your class).

sDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type short. The property’s value is read from or written to the variable referenced by sValue, as appropriate. If sDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_String

BOOL PX_String( CPropExchange* pPX, LPCTSTR pszPropName, CString& strValue );

BOOL PX_String( CPropExchange* pPX, LPCTSTR pszPropName, CString& strValue, CString strDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

The name of the property being exchanged.

strValue

Reference to the variable where the property is stored (typically a member variable of your class).

strDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a character string property. The property’s value is read from or written to the variable referenced by strValue, as appropriate. If strDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange, CString


PX_ULong

BOOL PX_ULong( CPropExchange* pPX, LPCTSTR pszPropName, ULONG& ulValue );

BOOL PX_ULong( CPropExchange* pPX, LPCTSTR pszPropName, ULONG& ulValue, long ulDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

Name of the property being exchanged.

ulValue

Reference to the variable where the property is stored (typically a member variable of your class).

ulDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type ULONG. The property’s value is read from or written to the variable referenced by ulValue, as appropriate. If ulDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_UShort

BOOL PX_UShort( CPropExchange* pPX, LPCTSTR pszPropName, USHORT& usValue );

BOOL PX_UShort( CPropExchange* pPX, LPCTSTR pszPropName, USHORT& usValue, USHORT usDefault );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

pszPropName

Name of the property being exchanged.

usValue

Reference to the variable where the property is stored (typically a member variable of your class).

usDefault

Default value for the property.

Remarks

Call this function within your control’s DoPropExchange member function to serialize or initialize a property of type unsigned short. The property’s value is read from or written to the variable referenced by usValue, as appropriate. If usDefault is specified, it will be used as the property’s default value. This value is used if, for any reason, the control’s serialization process fails.

See Also COleControl::DoPropExchange


PX_VBXFontConvert

BOOL PX_VBXFontConvert( CPropExchange* pPX, CFontHolder& font );

Return Value

Nonzero if the exchange was successful; 0 if unsuccessful.

Parameters

pPX

Pointer to the CPropExchange object (typically passed as a parameter to DoPropExchange).

font

The font property of the OLE control that will contain the converted VBX font-related properties.

Remarks

Call this function within your control’s DoPropExchange member function to initialize a font property by converting a VBX control’s font-related properties.

This function should be used only by an OLE control that is designed as a direct replacement for a VBX control. When the Visual Basic development environment converts a form containing a VBX control to use the corresponding replacement OLE control, it will call the control’s IDataObject::SetData function, passing in a property set that contains the VBX control’s property data. This operation, in turn, causes the control’s DoPropExchange function to be invoked. DoPropExchange can call PX_VBXFontConvert to convert the VBX control’s font-related properties (for example, "FontName,” "FontSize,” and so on) into the corresponding components of the OLE control’s font property.

PX_VBXFontConvert should only be called when the control is actually being converted from a VBX form application. For example:

void CSampleCtrl::DoPropExchange(CPropExchange* pPX)
{
    ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
    COleControl::DoPropExchange(pPX);

    if (IsConvertingVBX())
        PX_VBXFontConvert(pPX, InternalGetFont());
}

See Also COleControl::DoPropExchange, COleControl::AmbientFont, PX_Font


RFX_Binary

void RFX_Binary( CFieldExchange* pFX, const char* szName, CByteArray& value, int nMaxLength = 255 );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type CByteArray, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

nMaxLength

The maximum allowed length of the string or array being transferred. The default value of nMaxLength is 255. Legal values are 1 to INT_MAX. The framework allocates this amount of space for the data. For best performance, pass a value large enough to accommodate the largest data item you expect.

Remarks

The RFX_Binary function transfers arrays of bytes between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_BINARY, SQL_VARBINARY, or SQL_LONGVARBINARY. Data in the data source of these types is mapped to and from type CByteArray in the recordset.

Example

See RFX_Text.

See Also RFX_Text, RFX_Bool, RFX_Long, RFX_Int, RFX_Single, RFX_Double, RFX_Date, RFX_Byte, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Binary_Bulk

void RFX_Binary_Bulk( CFieldExchange* pFX, LPCTSTR szName, BYTE** prgByteVals, long** prgLengths, int nMaxLength );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgByteVals

A pointer to an array of BYTE values. This array will store the data to be transferred from the data source to the recordset.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgByteVals. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

nMaxLength

The maximum allowed length of the values stored in the array pointed to by prgByteVals. To ensure that data will not be truncated, pass a value large enough to accommodate the largest data item you expect.

Remarks

The RFX_Binary_Bulk function transfers multiple rows of byte data from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column can have an ODBC type of SQL_BINARY, SQL_VARBINARY, or SQL_LONGVARBINARY. The recordset must define a field data member of type pointer to BYTE.

If you initialize prgByteVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

See RFX_Text_Bulk.

See Also RFX_Bool_Bulk, RFX_Byte_Bulk, RFX_Date_Bulk, RFX_Double_Bulk, RFX_Int_Bulk, RFX_Long_Bulk, RFX_Single_Bulk, RFX_Text_Bulk, CFieldExchange::SetFieldType


RFX_Bool

void RFX_Bool( CFieldExchange* pFX, const char* szName, BOOL& value );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type BOOL, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

Remarks

The RFX_BOOL function transfers Boolean data between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_BIT.

Example

See RFX_Text.

See Also RFX_Text, RFX_Long, RFX_Int, RFX_Single, RFX_Double, RFX_Date, RFX_Byte, RFX_Binary, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Bool_Bulk

void RFX_Bool_Bulk( CFieldExchange* pFX, LPCTSTR szName, BOOL** prgBoolVals, long** prgLengths );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgBoolVals

A pointer to an array of BOOL values. This array will store the data to be transferred from the data source to the recordset.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgBoolVals. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

Remarks

The RFX_Bool_Bulk function transfers multiple rows of Boolean data from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column must have an ODBC type of SQL_BIT. The recordset must define a field data member of type pointer to BOOL.

If you initialize prgBoolVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

See RFX_Text_Bulk.

See Also RFX_Binary_Bulk, RFX_Byte_Bulk, RFX_Date_Bulk, RFX_Double_Bulk, RFX_Int_Bulk, RFX_Long_Bulk, RFX_Single_Bulk, RFX_Text_Bulk, CFieldExchange::SetFieldType


RFX_Byte

void RFX_Byte( CFieldExchange* pFX, const char* szName, BYTE& value );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type BYTE, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

Remarks

The RFX_Byte function transfers single bytes between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_TINYINT.

Example

See RFX_Text.

See Also RFX_Text, RFX_Bool, RFX_Long, RFX_Int, RFX_Single, RFX_Double, RFX_Date, RFX_Binary, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Byte_Bulk

void RFX_Byte_Bulk( CFieldExchange* pFX, LPCTSTR szName, BYTE** prgByteVals, long** prgLengths );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgByteVals

A pointer to an array of BYTE values. This array will store the data to be transferred from the data source to the recordset.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgByteVals. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

Remarks

The RFX_Byte_Bulk function transfers multiple rows of single bytes from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column must have an ODBC type of SQL_TINYINT. The recordset must define a field data member of type pointer to BYTE.

If you initialize prgByteVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

See RFX_Text_Bulk.

See Also RFX_Binary_Bulk, RFX_Bool_Bulk, RFX_Date_Bulk, RFX_Double_Bulk, RFX_Int_Bulk, RFX_Long_Bulk, RFX_Single_Bulk, RFX_Text_Bulk, CFieldExchange::SetFieldType


RFX_Date

void RFX_Date( CFieldExchange* pFX, const char* szName, CTime& value );

void RFX_Date( CFieldExchange* pFX, const char* szName, TIMESTAMP_STRUCT& value );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. The two versions of the function take different data types for value. The first version of the function takes a reference to a CTime object. For a transfer from recordset to data source, this value is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member. The second version of the function takes a reference to a TIMESTAMP_STRUCT. You must set up this structure yourself prior to the call. Neither dialog data exchange (DDX) support nor ClassWizard support is available for this version. In your field map, place your call to the second version of RFX_Date outside the ClassWizard comment delimiters.

Remarks

The RFX_Date function transfers CTime or TIMESTAMP_STRUCT data between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_DATE, SQL_TIME, or SQL_TIMESTAMP.

The CTime version of the function imposes the overhead of some intermediate processing and has a somewhat limited range. If you find either of these factors too limiting, use the second version of the function. But note its lack of ClassWizard and DDX support and the requirement that you set up the structure yourself.

Example

See RFX_Text.

See Also RFX_Text, RFX_Bool, RFX_Long, RFX_Int, RFX_Single, RFX_Double, RFX_Byte, RFX_Binary, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Date_Bulk

void RFX_Date_Bulk( CFieldExchange* pFX, LPCTSTR szName, TIMESTAMP_STRUCT** prgTSVals, long** prgLengths );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgTSVals

A pointer to an array of TIMESTAMP_STRUCT values. This array will store the data to be transferred from the data source to the recordset. For more information about the TIMESTAMP_STRUCT data type, see the topic "C Data Types" in Appendix D of the ODBC SDK Programmer's Reference.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgTSVals. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

Remarks

The RFX_Date_Bulk function transfers multiple rows of TIMESTAMP_STRUCT data from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column can have an ODBC type of SQL_DATE, SQL_TIME, or SQL_TIMESTAMP. The recordset must define a field data member of type pointer to TIMESTAMP_STRUCT.

If you initialize prgTSVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

See RFX_Text_Bulk.

See Also RFX_Binary_Bulk, RFX_Bool_Bulk, RFX_Byte_Bulk, RFX_Double_Bulk, RFX_Int_Bulk, RFX_Long_Bulk, RFX_Single_Bulk, RFX_Text_Bulk, CFieldExchange::SetFieldType


RFX_Double

void RFX_Double( CFieldExchange* pFX, const char* szName, double& value );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type double, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

Remarks

The RFX_Double function transfers double float data between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_DOUBLE.

Example

See RFX_Text.

See Also RFX_Text, RFX_Bool, RFX_Long, RFX_Int, RFX_Single, RFX_Date, RFX_Byte, RFX_Binary, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Double_Bulk

void RFX_Double_Bulk( CFieldExchange* pFX, LPCTSTR szName, double** prgDblVals, long** prgLengths );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgDblVals

A pointer to an array of double values. This array will store the data to be transferred from the data source to the recordset.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgDblVals. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

Remarks

The RFX_Double_Bulk function transfers multiple rows of double-precision floating-point data from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column must have an ODBC type of SQL_DOUBLE. The recordset must define a field data member of type pointer to double.

If you initialize prgDblVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

See RFX_Text_Bulk.

See Also RFX_Binary_Bulk, RFX_Bool_Bulk, RFX_Byte_Bulk, RFX_Date_Bulk, RFX_Int_Bulk, RFX_Long_Bulk, RFX_Single_Bulk, RFX_Text_Bulk, CFieldExchange::SetFieldType


RFX_Int

void RFX_Int( CFieldExchange* pFX, const char* szName, int& value );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type int, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

Remarks

The RFX_Int function transfers integer data between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_SMALLINT.

Example

See RFX_Text.

See Also RFX_Text, RFX_Bool, RFX_Long, RFX_Single, RFX_Double, RFX_Date, RFX_Byte, RFX_Binary, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Int_Bulk

void RFX_Int_Bulk( CFieldExchange* pFX, LPCTSTR szName, int** prgIntVals, long** prgLengths );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgIntVals

A pointer to an array of integers. This array will store the data to be transferred from the data source to the recordset.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgIntVals. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

Remarks

The RFX_Int_Bulk function transfers multiple rows of integer data from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column must have an ODBC type of SQL_SMALLINT. The recordset must define a field data member of type pointer to int.

If you initialize prgIntVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

See RFX_Text_Bulk.

See Also RFX_Binary_Bulk, RFX_Bool_Bulk, RFX_Byte_Bulk, RFX_Date_Bulk, RFX_Double_Bulk, RFX_Long_Bulk, RFX_Single_Bulk, RFX_Text_Bulk, CFieldExchange::SetFieldType


RFX_Long

void RFX_Long( CFieldExchange* pFX, const char* szName, LONG&
value );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type long, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

Remarks

The RFX_Long function transfers long integer data between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_INTEGER.

Example

See RFX_Text.

See Also RFX_Text, RFX_Bool, RFX_Int, RFX_Single, RFX_Double, RFX_Date, RFX_Byte, RFX_Binary, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Long_Bulk

void RFX_Long_Bulk( CFieldExchange* pFX, LPCTSTR szName, long** prgLongVals, long** prgLengths );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgLongVals

A pointer to an array of long integers. This array will store the data to be transferred from the data source to the recordset.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgLongVals. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

Remarks

The RFX_Long_Bulk function transfers multiple rows of long integer data from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column must have an ODBC type of SQL_INTEGER. The recordset must define a field data member of type pointer to long.

If you initialize prgLongVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

See RFX_Text_Bulk.

See Also RFX_Binary_Bulk, RFX_Bool_Bulk, RFX_Byte_Bulk, RFX_Date_Bulk, RFX_Double_Bulk, RFX_Int_Bulk, RFX_Single_Bulk, RFX_Text_Bulk, CFieldExchange::SetFieldType


RFX_LongBinary

void RFX_LongBinary( CFieldExchange* pFX, const char* szName, CLongBinary& value );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type CLongBinary, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

Remarks

The RFX_LongBinary function transfers binary large object (BLOB) data using class CLongBinary between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_LONGVARBINARY or SQL_LONGVARCHAR.

Example

See RFX_Text.

See Also RFX_Text, RFX_Bool, RFX_Long, RFX_Int, RFX_Single, RFX_Double, RFX_Date, RFX_Byte, RFX_Binary, CFieldExchange::SetFieldType, CLongBinary


RFX_Single

void RFX_Single( CFieldExchange* pFX, const char* szName, float& value );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type float, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

Remarks

The RFX_Single function transfers floating-point data between the field data members of a CRecordset object and the columns of a record on the data source of ODBC type SQL_REAL.

Example

See RFX_Text.

See Also RFX_Text, RFX_Bool, RFX_Long, RFX_Int, RFX_Double, RFX_Date, RFX_Byte, RFX_Binary, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Single_Bulk

void RFX_Single_Bulk( CFieldExchange* pFX, LPCTSTR szName, float** prgFltVals, long** prgLengths );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgFltVals

A pointer to an array of float values. This array will store the data to be transferred from the data source to the recordset.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgFltVals. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

Remarks

The RFX_Single_Bulk function transfers multiple rows of floating-point data from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column must have an ODBC type of SQL_REAL. The recordset must define a field data member of type pointer to float.

If you initialize prgFltVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

See RFX_Text_Bulk.

See Also RFX_Binary_Bulk, RFX_Bool_Bulk, RFX_Byte_Bulk, RFX_Date_Bulk, RFX_Double_Bulk, RFX_Int_Bulk, RFX_Long_Bulk, RFX_Text_Bulk, CFieldExchange::SetFieldType


RFX_Text

void RFX_Text( CFieldExchange* pFX, const char* szName, CString& value, int nMaxLength = 255, int nColumnType = SQL_VARCHAR, short nScale = 0 );

Parameters

pFX

A pointer to an object of class CFieldExchange. This object contains information to define the context for each call of the function. For more information about the operations a CFieldExchange object can specify, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

value

The value stored in the indicated data member — the value to be transferred. For a transfer from recordset to data source, the value, of type CString, is taken from the specified data member. For a transfer from data source to recordset, the value is stored in the specified data member.

nMaxLength

The maximum allowed length of the string or array being transferred. The default value of nMaxLength is 255. Legal values are 1 to INT_MAX. The framework allocates this amount of space for the data. For best performance, pass a value large enough to accommodate the largest data item you expect.

nColumnType

Used mainly for parameters. An integer indicating the data type of the parameter. The type is an ODBC data type of the form SQL_XXX.

nScale

Specifies the scale for values of ODBC type SQL_DECIMAL or SQL_NUMERIC. nScale is only useful when setting parameter values. For more information, see the topic "Precision, Scale, Length, and Display Size" in Appendix D of the ODBC SDK Programmer's Reference.

Remarks

The RFX_Text function transfers CString data between the field data members of a CRecordset object and columns of a record on the data source of ODBC type SQL_LONGVARCHAR, SQL_CHAR, SQL_VARCHAR, SQL_DECIMAL, or SQL_NUMERIC. Data in the data source of all of these types is mapped to and from CString in the recordset.

Example

This example shows several calls to RFX_Text. Notice also the two calls to CFieldExchange::SetFieldType. ClassWizard normally writes the second call to SetFieldType and its associated RFX calls. You must write the first call and its RFX call. It is recommended that you put any parameter items before the “//{{AFX_FIELD_MAP” comment. You must put parameters outside the comments.

//Example for RFX_Text
void CSections::DoFieldExchange(CFieldExchange* pFX)
{
   pFX->SetFieldType(CFieldExchange::inputParam);
   RFX_Text(pFX, "Name", m_strNameParam);

   //{{AFX_FIELD_MAP(CSections)
   pFX->SetFieldType(CFieldExchange::outputColumn);
   RFX_Text(pFX, "CourseID", m_strCourseID);
   RFX_Text(pFX, "InstructorID", m_strInstructorID);
   RFX_Int(pFX, "RoomNo", m_nRoomNo);
   RFX_Text(pFX, "Schedule", m_strSchedule);
   RFX_Int(pFX, "SectionNo", m_nSectionNo);
   RFX_Single(pFX, "LabFee", m_flLabFee);
   //}}AFX_FIELD_MAP
}

See Also RFX_Bool, RFX_Long, RFX_Int, RFX_Single, RFX_Double, RFX_Date, RFX_Byte, RFX_Binary, RFX_LongBinary, CFieldExchange::SetFieldType


RFX_Text_Bulk

void RFX_Text_Bulk( CFieldExchange* pFX, LPCTSTR szName, LPSTR* prgStrVals, long** prgLengths, int nMaxLength );

Parameters

pFX

A pointer to a CFieldExchange object. This object contains information to define the context for each call of the function. For more information, see the article Record Field Exchange: How RFX Works in Visual C++ Programmer’s Guide.

szName

The name of a data column.

prgStrVals

A pointer to an array of LPSTR values. This array will store the data to be transferred from the data source to the recordset. Note that with the current version of ODBC, these values cannot be Unicode.

prgLengths

A pointer to an array of long integers. This array will store the length in bytes of each value in the array pointed to by prgStrVals. This length excludes the null termination character. Note that the value SQL_NULL_DATA will be stored if the corresponding data item contains a Null value. For more details, see the ODBC API function SQLBindCol in the ODBC SDK Programmer's Reference.

nMaxLength

The maximum allowed length of the values stored in the array pointed to by prgStrVals, including the null termination character. To ensure that data will not be truncated, pass a value large enough to accommodate the largest data item you expect.

Remarks

The RFX_Text_Bulk function transfers multiple rows of character data from a column of an ODBC data source to a corresponding array in a CRecordset-derived object. The data source column can have an ODBC type of SQL_LONGVARCHAR, SQL_CHAR, SQL_VARCHAR, SQL_DECIMAL, or SQL_NUMERIC. The recordset must define a field data member of type LPSTR.

If you initialize prgStrVals and prgLengths to NULL, then the arrays they point to will be allocated automatically, with sizes equal to the rowset size.

Note Bulk record field exchange only transfers data from the data source to the recordset object. In order to make your recordset updatable, you must use the ODBC API function SQLSetPos. For an example of how to do this, see the sample DBFETCH.

For more information, see the articles Recordset: Fetching Records in Bulk (ODBC) and Record Field Exchange (RFX) in Visual C++ Programmer’s Guide.

Example

ClassWizard does not support the Bulk RFX functions, so you must manually write calls in your DoBulkFieldExchange override. This example shows a call to RFX_Text_Bulk, as well as a call to RFX_Long_Bulk, for data transfer. These calls are preceded by a call to CFieldExchange::SetFieldType. Note that for parameters, you must call the RFX functions instead of the Bulk RFX functions.

void MultiRowSet::DoBulkFieldExchange( CFieldExchange* pFX )
{
   pFX->SetFieldType( CFieldExchange::outputColumn );
   RFX_Long_Bulk( pFX, _T( "[colRecID]" ),
                  &m_rgID, &m_rgIDLenghts );
   RFX_Text_Bulk( pFX, _T( "[colName]" ),
                  &m_rgName, &m_rgNameLengths, 30 );

   pFX->SetFieldType( CFieldExchange::inputParam );
   RFX_Text( pFX, "NameParam", m_strNameParam );
}

See Also RFX_Binary_Bulk, RFX_Bool_Bulk, RFX_Byte_Bulk, RFX_Date_Bulk, RFX_Double_Bulk, RFX_Int_Bulk, RFX_Long_Bulk, RFX_Single_Bulk, CFieldExchange::SetFieldType


RUNTIME_CLASS

RUNTIME_CLASS( class_name )

Parameters

class_name

The actual name of the class (not enclosed in quotation marks).

Remarks

Use this macro to get the run-time class structure from the name of a C++ class.

RUNTIME_CLASS returns a pointer to a CRuntimeClass structure for the class specified by class_name. Only CObject-derived classes declared with DECLARE_DYNAMIC, DECLARE_DYNCREATE, or DECLARE_SERIAL will return pointers to a CRuntimeClass structure.

For more information, see CObject Class Topics in Visual C++ Programmer’s Guide.

Example

// example for RUNTIME_CLASS
CRuntimeClass* prt = RUNTIME_CLASS( CAge );
ASSERT( lstrcmp( prt->m_lpszClassName, "CAge" )  == 0 );

See Also DECLARE_DYNAMIC, DECLARE_DYNCREATE, DECLARE_SERIAL, CObject::GetRuntimeClass, CRuntimeClass


SerializeElements

template< class TYPE >
void AFXAPI SerializeElements( CArchive& ar, TYPE* pElements, int nCount );

Parameters

TYPE

Template parameter specifying the type of the elements.

ar

An archive object to archive to or from.

pElements

Pointer to the elements being archived.

nCount

Number of elements being archived

Remarks

CArray, CList, and CMap call this function to serialize elements. The default implementation does a bit-wise read or write.

For information on implementing this and other helper functions, see the article Collections: How to Make a Type-Safe Collection in Visual C++ Programmer’s Guide.

See Also CArchive


STATIC_DOWNCAST

STATIC_DOWNCAST( class_name, pobject )

Parameters

class_name

The name of a class.

pobject

A pointer to be cast to a pointer to a object of type class_name.

Remarks

In builds of your application with the _DEBUG preprocessor symbol defined, this macro will cast a pointer to an object from one class to a pointer of a related type. The macro will ASSERT if the pointer is not NULL and points to an object that is not a "kind of" the target type.

In non-_DEBUG builds, the macro performs the cast without any checking.

The target type is specified by the class_name parameter, while the pobject parameter identifies the pointer. You might, for example, cast a pointer to CYourDocument called pYourDoc to a pointer to CDocument using this expression:

CDocument* pDoc = STATIC_DOWNCAST(CDocument, pYourDoc);

If pYourDoc does not point to a CDocument object, the macro will ASSERT.

See Also DYNAMIC_DOWNCAST


THIS_FILE

Remarks

This macro expands to the name of the file that is being compiled. The information is used by the ASSERT and VERIFY macros. AppWizard and ClassWizard place the macro in source code files they create.

See Also ASSERT, VERIFY


THROW

THROW( exception_object_pointer )

Parameters

exception_object_pointer

Points to an exception object derived from CException.

Remarks

Throws the specified exception. THROW interrupts program execution, passing control to the associated CATCH block in your program. If you have not provided the CATCH block, then control is passed to a Microsoft Foundation Class Library module that prints an error message and exits.

For more information, see the article Exceptions in Visual C++ Programmer’s Guide.

See Also THROW_LAST, TRY, CATCH, AND_CATCH, END_CATCH, CATCH_ALL, AND_CATCH_ALL, END_CATCH_ALL, AfxThrowArchiveException, AfxThrowFileException, AfxThrowMemoryException, AfxThrowNotSupportedException, AfxThrowResourceException, AfxThrowUserException


THROW_LAST

THROW_LAST( )

Remarks

Throws the exception back to the next outer CATCH block.

This macro allows you to throw a locally created exception. If you try to throw an exception that you have just caught, it will normally go out of scope and be deleted. With THROW_LAST, the exception is passed correctly to the next CATCH handler.

For more information, see the article Exceptions in Visual C++ Programmer’s Guide.

See Also THROW, TRY, CATCH, AND_CATCH, END_CATCH, CATCH_ALL, AND_CATCH_ALL, END_CATCH_ALL


TRACE

TRACE( exp )

Parameters

exp

Specifies a variable number of arguments that are used in exactly the same way that a variable number of arguments are used in the run-time function printf.

Remarks

Provides similar functionality to the printf function by sending a formatted string to a dump device such as a file or debug monitor. Like printf for C programs under MS-DOS, the TRACE macro is a convenient way to track the value of variables as your program executes. In the Debug environment, the TRACE macro output goes to afxDump. In the Release environment, it does nothing.

TRACE is limited to sending a total of 512 characters at a time. If you call TRACE with formatting commands, the total string length after the formatting commands have been expanded cannot be more than 512 characters, including the terminating NULL. Exceeding this limit causes an ASSERT.

Note This macro is available only in the debug version of MFC.

For more information, see MFC Debugging Support in Visual C++ Programmer’s Guide.

Example

// example for TRACE
int i = 1;
char sz[] = "one";
TRACE( "Integer = %d, String = %s\n", i, sz );
// Output: 'Integer = 1, String = one'

See Also TRACE0, TRACE1, TRACE2, TRACE3, AfxDump, afxTraceEnabled


TRACE0

TRACE0( exp )

Parameters

exp

A format string as used in the run-time function printf.

Remarks

TRACE0 is similar to TRACE, and is one variant of a group of trace macros that you can use for debug output. The group includes:

  • TRACE0 - Takes a format string (Only) and can be used for simple text messages which are dumped to afxDump

  • TRACE1 - Takes a format string plus one argument (one variable which is dumped to afxDump)

  • TRACE2 - Takes a format string plus two arguments (two variables which are dumped to afxDump)

  • TRACE3 - Takes a format string plus three arguments (three variables which are dumped to afxDump)

TRACE0 does nothing if you have compiled a release version of your application. As with TRACE, it only dumps data to afxDump if you have compiled a debug version of your application.

Note This macro is available only in the debug version of MFC.

Example

// example for TRACE0
TRACE0( "Start Dump of MyClass members:" );

See Also TRACE, TRACE1, TRACE2, TRACE3


TRACE1

TRACE1( exp, param1 )

Parameters

exp

A format string as used in the run-time function printf.

param1

The name of the variable whose value should be dumped.

Remarks

See TRACE0 for a description of the TRACE1 macro.

Example

// example for TRACE1
int i = 1;
TRACE1( "Integer = %d\n", i );
// Output: 'Integer = 1'


TRACE2

TRACE2( exp, param1, param2 )

Parameters

exp

A format string as used in the run-time function printf.

param1

The name of the variable whose value should be dumped.

param2

The name of the variable whose value should be dumped.

Remarks

See TRACE0 for a description of the TRACE2 macro.

Example

// example for TRACE2
int i = 1;
char sz[] = "one";
TRACE2( "Integer = %d, String = %s\n", i, sz );
// Output: 'Integer = 1, String = one'


TRACE3

TRACE3( exp, param1, param2, param3 )

Parameters

exp

A format string as used in the run-time function printf.

param1

The name of the variable whose value should be dumped.

param2

The name of the variable whose value should be dumped.

param3

The name of the variable whose value should be dumped.

Remarks

See TRACE0 for a description of the TRACE3 macro.


TRY

TRY

Remarks

Use this macro to set up a TRY block. A TRY block identifies a block of code that might throw exceptions. Those exceptions are handled in the following CATCH and AND_CATCH blocks. Recursion is allowed: exceptions may be passed to an outer TRY block, either by ignoring them or by using the THROW_LAST macro. End the TRY block with an END_CATCH or END_CATCH_ALL macro.

For more information, see the article Exceptions in Visual C++ Programmer’s Guide.

See Also CATCH, AND_CATCH, END_CATCH, CATCH_ALL, AND_CATCH_ALL, END_CATCH_ALL, THROW, THROW_LAST


VERIFY

VERIFY( booleanExpression )

Parameters

booleanExpression

Specifies an expression (including pointer values) that evaluates to nonzero or 0.

Remarks

In the debug version of MFC, the VERIFY macro evaluates its argument. If the result is 0, the macro prints a diagnostic message and halts the program. If the condition is nonzero, it does nothing.

The diagnostic message has the form

assertion failed in file <name> in line <num>

where name is the name of the source file and num is the line number of the assertion that failed in the source file.

In the release version of MFC, VERIFY evaluates the expression but does not print or interrupt the program. For example, if the expression is a function call, the call will be made.

See Also ASSERT


ClassWizard Comment Delimiters

In order for ClassWizard to distinguish between code entered by the user and code created by ClassWizard, several types of special delimiters are used. These delimiters are formatted to appear as comments in the code. Therefore they are never compiled or modified by anything except ClassWizard.

The following is a list of the ClassWizard comment delimiters. For more information, see the topics in this section.

Comment Delimiters

AFX_DATA

Marks the beginning and end of member variable declarations in a header file (.H) used for dialog data exchange (DDX).

AFX_DATA_INIT

Marks the beginning and end of dialog data exchange (DDX) member variable initializations in a dialog class’s constructor.

AFX_DATA_MAP

Marks the beginning and end of dialog data exchange (DDX) function calls in a dialog class’s DoDataExchange member function.

AFX_DISP

Marks the beginning and end of OLE Automation declarations in a class’s header (.H) file.

AFX_DISP_MAP

Marks the beginning and end of OLE Automation mapping in a class’s implementation (.CPP) file.

AFX_EVENT

Marks the beginning and end of OLE event declarations in a class’s header (.H) file.

AFX_EVENT_MAP

Marks the beginning and end of OLE events in a class’s implementation (.CPP) file.

AFX_FIELD

Marks the beginning and end of member variable declarations in a header file (.H) used for database record field exchange (RFX).

AFX_FIELD_INIT

Marks the beginning and end of record field exchange (RFX) member variable initializations in a recordset class’s constructor.

AFX_FIELD_MAP

Marks the beginning and end of record field exchange function calls in a recordset class’s DoFieldExchange member function.

AFX_MSG

Marks the beginning and end of ClassWizard entries in a header file (.H) related to message maps.

AFX_MSG_MAP

Marks the beginning and end of message map entries in a class’s message map (in the .CPP file).

AFX_VIRTUAL

Marks the beginning and end of virtual function override declarations in a class’s header (.H) file.


AFX_DATA

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_DATA is used to mark the beginning and end of member variable declarations in your header file (.H) used for dialog data exchange (DDX):

//{{AFX_DATA(classname)
...
//}}AFX_DATA

For more information, see AFX_DATA_MAP and AFX_DATA_INIT.


AFX_DATA_INIT

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_DATA_INIT is used to mark the beginning and end of dialog data exchange (DDX) member variable initializations in a dialog class’s constructor:

//{{AFX_DATA_INIT(classname)
...
//}}AFX_DATA_INIT

For more information, see AFX_DATA_MAP and AFX_DATA.


AFX_DATA_MAP

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_DATA_MAP is used to mark the beginning and end of dialog data exchange (DDX) function calls in a dialog class’s DoDataExchange member function:

//{{AFX_DATA_MAP(classname)
...
//}}AFX_DATA_MAP

For more information, see AFX_DATA_INIT and AFX_DATA.


AFX_DISP

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_DISP is used to mark the beginning and end of OLE Automation declarations in a class’s header (.H) file:

//{{AFX_DISP(classname)
...
//}}AFX_DISP

For more information, see AFX_DISP_MAP.


AFX_DISP_MAP

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_DISP_MAP is used to mark the beginning and end of OLE Automation mapping in a class’s implementation (.CPP) file:

//{{AFX_DISP_MAP(classname)
...
//}}AFX_DISP_MAP

For more information, see AFX_DISP.


AFX_EVENT

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_EVENT is used to mark the beginning and end of OLE event declarations in a class’s header (.H) file:

//{{AFX_EVENT(classname)
...
//}}AFX_EVENT

For more information, see AFX_EVENT_MAP.


AFX_EVENT_MAP

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_EVENT_MAP is used to mark the beginning and end of OLE events in a class’s implementation (.CPP) file:

//{{AFX_EVENT_MAP(classname)
...
//}}AFX_EVENT_MAP

For more information, see AFX_EVENT.


AFX_FIELD

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_FIELD is used to mark the beginning and end of member variable declarations in your header file (.H) used for database record field exchange (RFX):

//{{AFX_FIELD(classname)
...
//}}AFX_FIELD

For more information, see AFX_FIELD_MAP and AFX_FIELD_INIT.


AFX_FIELD_INIT

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_FIELD_INIT is used in MFC database applications to mark the beginning and end of record field exchange (RFX) member variable initializations in a recordset class’s constructor:

//{{AFX_DATA_FIELD(classname)
...
//}}AFX_DATA_FIELD

For more information, see AFX_FIELD_MAP and AFX_FIELD.


AFX_FIELD_MAP

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_FIELD_MAP is used in MFC database applications to mark the beginning and end of record field exchange function calls in a recordset class’s DoFieldExchange member function:

//{{AFX_FIELD_MAP(classname)
...
//}}AFX_FIELD_MAP

For more information, see AFX_FIELD_INIT and AFX_FIELD.


AFX_MSG

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_MSG is used to mark the beginning and end of ClassWizard entries in your header file (.H) related to message maps:

//{{AFX_MSG(classname)
...
//}}AFX_MSG

For more information, see AFX_MSG_MAP.


AFX_MSG_MAP

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_MSG_MAP is used to mark the beginning and end of message map entries in a class’s message map (in the .CPP file):

//{{AFX_MSG_MAP(classname)
...
//}}AFX_MSG_MAP

For more information, see AFX_MSG.


AFX_VIRTUAL

Remarks

ClassWizard and AppWizard insert specially formatted comment delimiters in your source code files to mark the places in your files that ClassWizard can write to. AFX_VIRTUAL is used to mark the beginning and end of virtual function override declarations in a class’s header (.H) file:

//{{AFX_VIRTUAL(classname)
...
//}}AFX_VIRTUAL

There is no corresponding ClassWizard section in the .CPP file.


Structures, Styles, Callbacks, and Message Maps

This section documents the structures, styles, and callback functions used by the Microsoft Foundation Class Library and the MFC message maps.


Structures Used by MFC

A description of structures that are called from various member functions follows this topic. For further information on individual structure usage, refer to the classes and member functions noted in the See Also list for each structure.


ABC Structure

The ABC structure has the following form:

typedef struct _ABC { /* abc */
    int     abcA;
    UINT    abcB;
    int     abcC;
} ABC;

The ABC structure contains the width of a character in a TrueType® font.

Members

abcA

Specifies the A spacing of the character. The A spacing is the distance to add to the current position before drawing the character glyph.

abcB

Specifies the B spacing of the character. The B spacing is the width of the drawn portion of the character glyph.

abcC

Specifies the C spacing of the character. The C spacing is the distance to add to the current position to provide white space to the right of the character glyph.

Comments

The total width of a character is the summation of the A, B, and C spaces. Either the A or the C space can be negative to indicate underhangs or overhangs.

See Also CDC::GetCharABCWidths


ABCFLOAT Structure

The ABCFLOAT structure has the following form:

typedef struct _ABCFLOAT { /* abcf */
    FLOAT   abcfA;
    FLOAT   abcfB;
    FLOAT   abcfC;
} ABCFLOAT;

The ABCFLOAT structure contains the A, B, and C widths of a font character.

Members

abcfA

Specifies the A spacing of the character. The A spacing is the distance to add to the current position before drawing the character glyph.

abcfB

Specifies the B spacing of the character. The B spacing is the width of the drawn portion of the character glyph.

abcfC

Specifies the C spacing of the character. The C spacing is the distance to add to the current position to provide white space to the right of the character glyph.

Comments

The A, B, and C widths are measured along the base line of the font. The character increment (total width) of a character is the sum of the A, B, and C spaces. Either the A or the C space can be negative to indicate underhangs or overhangs.

See Also CDC::Get CharABCWidths


AFX_EXTENSION_MODULE Structure

The AFX_EXTENSION_MODULE structure has the following form:

struct AFX_EXTENSION_MODULE
{
   BOOL bInitialized;
   HMODULE hModule;
   HMODULE hResource;
   CRuntimeClass* pFirstSharedClass;
   COleObjectFactory* pFirstSharedFactory;
};

The AFX_EXTENSION_MODULE is used during initialization of MFC extension DLLs to hold the state of extension DLL module.

Members

bInitialized

TRUE if the DLL module has been initialized with AfxInitExtensionModule.

hModule

Specifies the handle of the DLL module.

hResource

Specifies the handle of the DLL custom resource module.

pFirstSharedClass

A pointer to information (the CRuntimeClass structure) about the DLL module's first runtime class. Used to provide the start of the runtime class list.

pFirstSharedFactory

A pointer to the DLL module's first object factory (a COleObjectFactory object). Used to provide the start of the class factory list.

Comments

MFC extension DLLs need to do two things in their DllMain function:

  • Call AfxInitExtensionModule and check the return value.

  • Create a CDynLinkLibrary object if the DLL will be exporting CRuntimeClass objects or has its own custom resources.

The AFX_EXTENSION_MODULE structure is used to hold a copy of the extension DLL module state, including a copy of the runtime class objects that have been initialized by the extension DLL as part of normal static object construction executed before DllMain is entered. For example:

static AFX_EXTENSION_MODULE extensionDLL;
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
   // initialize this DLL's extension module
   VERIFY(AfxInitExtensionModule(extensionDLL, hInstance));

The module information stored in the AFX_EXTENSION_MODULE structure can be copied into the CDynLinkLibrary object. For example:

// CDynLinkLibrary class
IMPLEMENT_DYNAMIC(CDynLinkLibrary, CCmdTarget)
// Constructor
CDynLinkLibrary::CDynLinkLibrary(AFX_EXTENSION_MODULE& state, BOOL bSystem)
{
#ifndef _AFX_NO_OLE_SUPPORT
   m_factoryList.Construct(offsetof(COleObjectFactory, m_pNextFactory));
#endif
   m_classList.Construct(offsetof(CRuntimeClass, m_pNextClass));

   // copy info from AFX_EXTENSION_MODULE struct
   ASSERT(state.hModule != NULL);
   m_hModule = state.hModule;
   m_hResource = state.hResource;
   m_classList.m_pHead = state.pFirstSharedClass;
#ifndef _AFX_NO_OLE_SUPPORT
   m_factoryList.m_pHead = state.pFirstSharedFactory;
#endif
   m_bSystem = bSystem;

See Also AfxInitExtensionModule, AfxTermExtensionModule


BITMAP Structure

The BITMAP structure has the following form:

typedef struct tagBITMAP {  /* bm */
    int     bmType;
    int     bmWidth;
    int     bmHeight;
    int     bmWidthBytes;
    BYTE    bmPlanes;
    BYTE    bmBitsPixel;
    LPVOID  bmBits;
} BITMAP;

The BITMAP structure defines the height, width, color format, and bit values of a logical bitmap.

Members

bmType

Specifies the bitmap type. For logical bitmaps, this member must be 0.

bmWidth

Specifies the width of the bitmap in pixels. The width must be greater than 0.

bmHeight

Specifies the height of the bitmap in raster lines. The height must be greater than 0.

bmWidthBytes

Specifies the number of bytes in each raster line. This value must be an even number since the graphics device interface (GDI) assumes that the bit values of a bitmap form an array of integer (2-byte) values. In other words, bmWidthBytes * 8 must be the next multiple of 16 greater than or equal to the value obtained when the bmWidth member is multiplied by the bmBitsPixel member.

bmPlanes

Specifies the number of color planes in the bitmap.

bmBitsPixel

Specifies the number of adjacent color bits on each plane needed to define a pixel.

bmBits

Points to the location of the bit values for the bitmap. The bmBits member must be a long pointer to an array of 1-byte values.

Comments

The currently used bitmap formats are monochrome and color. The monochrome bitmap uses a 1-bit, 1-plane format. Each scan is a multiple of 16 bits.

Scans are organized as follows for a monochrome bitmap of height n:

Scan 0
Scan 1
.
.
.
Scan n-2
Scan n-1

The pixels on a monochrome device are either black or white. If the corresponding bit in the bitmap is 1, the pixel is turned on (white). If the corresponding bit in the bitmap is 0, the pixel is turned off (black).

All devices support bitmaps that have the RC_BITBLT bit set in the RASTERCAPS index of the CDC::GetDeviceCaps member function.

Each device has its own unique color format. In order to transfer a bitmap from one device to another, use the GetDIBits and SetDIBits Windows functions.

See Also CBitmap::CreateBitmapIndirect


BITMAPINFO Structure

The BITMAPINFO structure has the following form:

typedef struct tagBITMAPINFO {
    BITMAPINFOHEADER    bmiHeader;
    RGBQUAD             bmiColors[1];
} BITMAPINFO;

The BITMAPINFO structure defines the dimensions and color information for a Windows device-independent bitmap (DIB).

Members

bmiHeader

Specifies a BITMAPINFOHEADER structure that contains information about the dimensions and color format of a device-independent bitmap.

bmiColors

Specifies an array of RGBQUAD or DWORD data types that define the colors in the bitmap.

Comments

A device-independent bitmap consists of two distinct parts: a BITMAPINFO structure describing the dimensions and colors of the bitmap, and an array of bytes defining the pixels of the bitmap. The bits in the array are packed together, but each scan line must be padded with zeroes to end on a LONG boundary. If the height is positive, the origin of the bitmap is the lower-left corner. If the height is negative, the origin is the upper-left corner.

The biBitCount member of the BITMAPINFOHEADER structure determines the number of bits that define each pixel and the maximum number of colors in the bitmap. This member can be one of the following values:

  • The bitmap is monochrome, and the bmiColors member contains two entries. Each bit in the bitmap array represents a pixel. If the bit is clear, the pixel is displayed with the color of the first entry in the bmiColors table; if the bit is set, the pixel has the color of the second entry in the table.

  • The bitmap has a maximum of 16 colors, and the bmiColors member contains up to 16 entries. Each pixel in the bitmap is represented by a 4-bit index into the color table. For example, if the first byte in the bitmap is 0x1F, the byte represents two pixels. The first pixel contains the color in the second table entry, and the second pixel contains the color in the sixteenth table entry.

  • The bitmap has a maximum of 256 colors, and the bmiColors member contains up to 256 entries. In this case, each byte in the array represents a single pixel.

  • The bitmap has a maximum of 216 colors. The biCompression member of the BITMAPINFOHEADER must be BI_BITFIELDS. The bmiColors member contains 3 DWORD color masks which specify the red, green, and blue components, respectively, of each pixel. Bits set in the DWORD mask must be contiguous and should not overlap the bits of another mask. All the bits in the pixel do not have to be used. Each WORD in the array represents a single pixel.

  • The bitmap has a maximum of 224 colors, and the bmiColors member is NULL. Each 3-byte triplet in the bitmap array represents the relative intensities of blue, green, and red, respectively, of a pixel.

  • The bitmap has a maximum of 232 colors. The biCompression member of the BITMAPINFOHEADER must be BI_BITFIELDS. The bmiColors member contains three DWORD color masks which specify the red, green, and blue components, respectively, of each pixel. Bits set in the DWORD mask must be contiguous and should not overlap the bits of another mask. All the bits in the pixel do not have to be used. Each DWORD in the array represents a single pixel.

The biClrUsed member of the BITMAPINFOHEADER structure specifies the number of color indices in the color table that are actually used by the bitmap. If the biClrUsed member is set to zero, the bitmap uses the maximum number of colors corresponding to the value of the biBitCount member.

The colors in the bmiColors table should appear in order of importance. Alternatively, for functions that use DIBs, the bmiColors member can be an array of 16-bit unsigned integers that specify indices into the currently realized logical palette, instead of explicit RGB values. In this case, an application using the bitmap must call the Windows DIB functions ( CreateDIBitmap, CreateDIBPatternBrush, and CreateDIBSection) with the iUsage parameter set to DIB_PAL_COLORS.

If the bitmap is a packed bitmap (that is, a bitmap in which the bitmap array immediately follows the BITMAPINFO header and which is referenced by a single pointer), the biClrUsed member must be set to an even number when using the DIB_PAL_COLORS mode so the DIB bitmap array starts on a DWORD boundary.

Note The bmiColors member should not contain palette indices if the bitmap is to be stored in a file or transferred to another application. Unless the application has exclusive use and control of the bitmap, the bitmap color table should contain explicit RGB values.

See Also CBrush::CreateDIBPatternBrush


CDaoDatabaseInfo Structure

The CDaoDatabaseInfo structure has the following form:

struct CDaoDatabaseInfo
{
   CString m_strName;       // Primary
   BOOL m_bUpdatable;       // Primary
   BOOL m_bTransactions;    // Primary
   CString m_strVersion;    // Secondary
   long m_lCollatingOrder;  // Secondary
   short m_nQueryTimeout;   // Secondary
   CString m_strConnect;    // All
};

The CDaoDatabaseInfo structure contains information about a database object defined for data access objects (DAO). The database is a DAO object underlying an MFC object of class CDaoDatabase. The references to Primary, Secondary, and All above indicate how the information is returned by the CDaoWorkspace::GetDatabaseInfo member function.

Members

m_strName

Uniquely names the database object. To directly retrieve this property, call CDaoDatabase::GetName. For details, see the topic "Name Property" in DAO Help.

m_bUpdatable

Indicates whether changes can be made to the database. To directly retrieve this property, call CDaoDatabase::CanUpdate. For details, see the topic "Updatable Property" in DAO Help.

m_bTransactions

Indicates whether a data source supports transactions — the recording of a series of changes that can later be rolled back (canceled) or committed (saved). If a database is based on the Microsoft Jet database engine, the Transactions property is nonzero and you can use transactions. Other database engines may not support transactions. To directly retrieve this property, call CDaoDatabase::CanTransact. For details, see the topic "Transactions Property" in DAO Help.

m_strVersion

Indicates the version of the Microsoft Jet database engine. To retrieve the value of this property directly, call the database object’s GetVersion member function. For details, see the topic "Version Property" in DAO Help.

m_lCollatingOrder

Specifies the sequence of the sort order in text for string comparison or sorting. Possible values include:

  • dbSortGeneral Use the General (English, French, German, Portuguese, Italian, and Modern Spanish) sort order.

  • dbSortArabic Use the Arabic sort order.

  • dbSortCyrillic Use the Russian sort order.

  • dbSortCzech Use the Czech sort order.

  • dbSortDutch Use the Dutch sort order.

  • dbSortGreek Use the Greek sort order.

  • dbSortHebrew Use the Hebrew sort order.

  • dbSortHungarian Use the Hungarian sort order.

  • dbSortIcelandic Use the Icelandic sort order.

  • dbSortNorwdan Use the Norwegian or Danish sort order.

  • dbSortPDXIntl Use the Paradox International sort order.

  • dbSortPDXNor Use the Paradox Norwegian or Danish sort order.

  • dbSortPDXSwe Use the Paradox Swedish or Finnish sort order.

  • dbSortPolish Use the Polish sort order.

  • dbSortSpanish Use the Spanish sort order.

  • dbSortSwedFin Use the Swedish or Finnish sort order.

  • dbSortTurkish Use the Turkish sort order.

  • dbSortUndefined The sort order is undefined or unknown.

    For more information, see the topic "Customizing Windows Registry Settings for Data Access" in DAO Help.

m_nQueryTimeout

The number of seconds the Microsoft Jet database engine waits before a timeout error occurs when a query is run on an ODBC database. The default timeout value is 60 seconds. When QueryTimeout is set to 0, no timeout occurs; this can cause the program to hang. To retrieve the value of this property directly, call the database object’s GetQueryTimeout member function. For details, see the topic "QueryTimeout Property" in DAO Help.

m_strConnect

Provides information about the source of an open database. For information about connect strings, and for information about retrieving the value of this property directly, see the CDaoDatabase::GetConnect member function. For more information, see the topic "Connect Property" in DAO Help.

Comments

Information retrieved by the CDaoWorkspace::GetDatabaseInfo member function is stored in a CDaoDatabaseInfo structure. Call GetDatabaseInfo for the CDaoWorkspace object in whose Databases collection the database object is stored. CDaoDatabaseInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoDatabaseInfo object.

For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoWorkspace, CDaoDatabase, CDaoWorkspace::GetDatabaseCount


CDaoErrorInfo Structure

The CDaoErrorInfo structure has the following form:

struct CDaoErrorInfo
{
   long m_lErrorCode;
   CString m_strSource;
   CString m_strDescription;
   CString m_strHelpFile;
   long m_lHelpContext;
};

The CDaoErrorInfo structure contains information about an error object defined for data access objects (DAO). MFC does not encapsulate DAO error objects in a class. Instead, the CDaoException class supplies an interface for accessing the Errors collection contained in the DAO DBEngine object, the object that also contains all workspaces. When an MFC DAO operation throws a CDaoException object that you catch, MFC fills a CDaoErrorInfo structure and stores it in the exception object’s m_pErrorInfo member. (If you choose to call DAO directly, you must call the exception object’s GetErrorInfo member function yourself to fill m_pErrorInfo.)

For more information about handling DAO errors, see the article Exceptions: Database Exceptions in Visual C++ Programmer’s Guide. For related information, see the topic "Error Object" in DAO Help.

Members

m_lErrorCode

A numeric DAO error code. See the topic "Trappable Data Access Errors" in DAO Help.

m_strSource

The name of the object or application that originally generated the error. The Source property specifies a string expression representing the object that originally generated the error; the expression is usually the object’s class name. For details, see the topic "Source Property" in DAO Help.

m_strDescription

A descriptive string associated with an error. For details, see the topic "Description Property" in DAO Help.

m_strHelpFile

A fully qualified path to a Microsoft Windows Help file. For details, see the topic "HelpContext, HelpFile Properties" in DAO Help.

m_lHelpContext

A context ID for a topic in a Microsoft Windows Help file. For details, see the topic "HelpContext, HelpFile Properties" in DAO Help.

Comments

Information retrieved by the CDaoException::GetErrorInfo member function is stored in a CDaoErrorInfo structure. Examine the m_pErrorInfo data member from a CDaoException object that you catch in an exception handler, or call GetErrorInfo from a CDaoException object that you create explicitly in order to check errors that might have occurred during a direct call to the DAO interfaces. CDaoErrorInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoErrorInfo object.

For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoException


CDaoFieldInfo Structure

The CDaoFieldInfo structure has the following form:

struct CDaoFieldInfo
{
   CString m_strName;           // Primary
   short m_nType;               // Primary
   long m_lSize;                // Primary
   long m_lAttributes;          // Primary
   short m_nOrdinalPosition;    // Secondary
   BOOL m_bRequired;            // Secondary
   BOOL m_bAllowZeroLength;     // Secondary
   long m_lCollatingOrder;      // Secondary
   CString m_strForeignName;    // Secondary
   CString m_strSourceField;    // Secondary
   CString m_strSourceTable;    // Secondary
   CString m_strValidationRule; // All
   CString m_strValidationText; // All
   CString m_strDefaultValue;   // All
};

The CDaoFieldInfo structure contains information about a field object defined for data access objects (DAO). The references to Primary, Secondary, and All above indicate how the information is returned by the GetFieldInfo member function in classes CDaoTableDef, CDaoQueryDef, and CDaoRecordset.

Field objects are not represented by an MFC class. Instead, the DAO objects underlying MFC objects of the following classes contain collections of field objects: CDaoTableDef, CDaoRecordset, and CDaoQueryDef. These classes supply member functions to access some individual items of field information, or you can access them all at once with a CDaoFieldInfo object by calling the GetFieldInfo member function of the containing object.

Besides its use for examining object properties, you can also use CDaoFieldInfo to construct an input parameter for creating new fields in a tabledef. Simpler options are available for this task, but if you want finer control, you can use the version of CDaoTableDef::CreateField that takes a CDaoFieldInfo parameter.

Members

m_strName

Uniquely names the field object. For details, see the topic "Name Property" in DAO Help.

m_nType

A value that indicates the data type of the field. For details, see the topic "Type Property" in DAO Help. The value of this property can be one of the following:

  • dbBoolean Yes/No, same as TRUE/FALSE

  • dbByte Byte

  • dbInteger Short

  • dbLong Long

  • dbCurrency Currency; see MFC class COleCurrency

  • dbSingle Single

  • dbDouble Double

  • dbDate Date/Time; see MFC class COleDateTime

  • dbText Text; see MFC class CString

  • dbLongBinary Long Binary (OLE Object); you might want to use MFC class CByteArray instead of class CLongBinary as CByteArray is richer and easier to use.

  • dbMemo Memo; see MFC class CString

  • dbGUID A Globally Unique Identifier/Universally Unique Identifier used with remote procedure calls. For more information, see the topic "Type Property" in DAO Help.

    Note Do not use string data types for binary data. This causes your data to pass through the Unicode/ANSI translation layer, resulting in increased overhead and possibly unexpected translation.

m_lSize

A value that indicates the maximum size, in bytes, of a DAO field object that contains text or the fixed size of a field object that contains text or numeric values. For details, see the topic "Size Property" in DAO Help. Sizes can be one of the following values:

Type | Size (Bytes) | Description
dbBoolean | 1 byte | Yes/No (same as True/False)
dbByte | 1 | Byte
dbInteger | 2 | Integer
dbLong | 4 | Long
dbCurrency | 8 | Currency (COleCurrency)
dbSingle | 4 | Single
dbDouble | 8 | Double
dbDate | 8 | Date/Time (COleDateTime)
dbText | 1 - 255 | Text (CString)
dbLongBinary | 0 | Long Binary (OLE Object; CByteArray; use instead of CLongBinary)
dbMemo | 0 | Memo (CString)
dbGUID | 16 | A Globally Unique Identifier/Universally Unique Identifier used with remote procedure calls.

m_lAttributes

Specifies characteristics of a field object contained by a tabledef, recordset, querydef, or index object. The value returned can be a sum of these constants, created with the C++ bitwise-OR (|) operator:

  • dbFixedField The field size is fixed (default for Numeric fields).

  • dbVariableField The field size is variable (Text fields only).

  • dbAutoIncrField The field value for new records is automatically incremented to a unique long integer that cannot be changed. Only supported for Microsoft Jet database tables.

  • dbUpdatableField The field value can be changed.

  • dbDescending The field is sorted in descending (Z - A or 100 - 0) order (applies only to a field object in a Fields collection of an index object; in MFC, index objects are themselves contained in tabledef objects). If you omit this constant, the field is sorted in ascending (A - Z or 0 - 100) order (default).

    When checking the setting of this property, you can use the C++ bitwise-AND operator (&) to test for a specific attribute. When setting multiple attributes, you can combine them by combining the appropriate constants with the bitwise-OR (|) operator. For details, see the topic "Attributes Property" in DAO Help.

m_nOrdinalPosition

A value that specifies the numeric order in which you want a field represented by a DAO field object to be displayed relative to other fields. You can set this property with CDaoTableDef::CreateField. For details, see the topic "OrdinalPosition Property" in DAO Help.

m_bRequired

Indicates whether a DAO field object requires a non-Null value. If this property is TRUE, the field does not allow a Null value. If Required is set to FALSE, the field can contain Null values as well as values that meet the conditions specified by the AllowZeroLength and ValidationRule property settings. For details, see the topic "Required Property" in DAO Help. You can set this property for a tabledef with CDaoTableDef::CreateField.

m_bAllowZeroLength

Indicates whether an empty string ("") is a valid value of a DAO field object with a Text or Memo data type. If this property is TRUE, an empty string is a valid value. You can set this property to FALSE to ensure that you cannot use an empty string to set the value of a field. For details, see the topic "AllowZeroLength Property" in DAO Help. You can set this property for a tabledef with CDaoTableDef::CreateField.

m_lCollatingOrder

Specifies the sequence of the sort order in text for string comparison or sorting. For details, see the topic "Customizing Windows Registry Settings for Data Access" in DAO Help. For a list of the possible values returned, see the m_lCollatingOrder member of the CDaoDatabaseInfo structure. You can set this property for a tabledef with CDaoTableDef::CreateField.

m_strForeignName

A value that, in a relation, specifies the name of the DAO field object in a foreign table that corresponds to a field in a primary table. For details, see the topic "ForeignName Property" in DAO Help.

m_strSourceField

Indicates the name of the field that is the original source of the data for a DAO field object contained by a tabledef, recordset, or querydef object. This property indicates the original field name associated with a field object. For example, you could use this property to determine the original source of the data in a query field whose name is unrelated to the name of the field in the underlying table. For details, see the topic "SourceField, SourceTable Properties" in DAO Help. You can set this property for a tabledef with CDaoTableDef::CreateField.

m_strSourceTable

Indicates the name of the table that is the original source of the data for a DAO field object contained by a tabledef, recordset, or querydef object. This property indicates the original table name associated with a field object. For example, you could use this property to determine the original source of the data in a query field whose name is unrelated to the name of the field in the underlying table. For details, see the topic "SourceField, SourceTable Properties" in DAO Help. You can set this property for a tabledef with CDaoTableDef::CreateField.

m_strValidationRule

A value that validates the data in a field as it is changed or added to a table. For details, see the topic "ValidationRule Property" in DAO Help. You can set this property for a tabledef with CDaoTableDef::CreateField.

For related information about tabledefs, see the m_strValidationRule member of the CDaoTableDefInfo structure.

m_strValidationText

A value that specifies the text of the message that your application displays if the value of a DAO field object does not satisfy the validation rule specified by the ValidationRule property setting. For details, see the topic "ValidationText Property" in DAO Help. You can set this property for a tabledef with CDaoTableDef::CreateField.

m_strDefaultValue

The default value of a DAO field object. When a new record is created, the DefaultValue property setting is automatically entered as the value for the field. For details, see the topic "DefaultValue Property" in DAO Help. You can set this property for a tabledef with CDaoTableDef::CreateField.

Comments

Information retrieved by the GetFieldInfo member function (of the class that contains the field) is stored in a CDaoFieldInfo structure. Call the GetFieldInfo member function of the containing object in whose Fields collection the field object is stored. CDaoFieldInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoFieldInfo object.

For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoTableDef::GetFieldInfo, CDaoRecordset::GetFieldInfo, CDaoQueryDef::GetFieldInfo


CDaoIndexInfo Structure

The CDaoIndexInfo structure has the following form:

struct CDaoIndexInfo {
    CDaoIndexInfo( );                   // Constructor

    CString m_strName;                  // Primary
    CDaoIndexFieldInfo* m_pFieldInfos;  // Primary
    short m_nFields;                    // Primary
    BOOL m_bPrimary;                    // Secondary
    BOOL m_bUnique;                     // Secondary
    BOOL m_bClustered;                  // Secondary
    BOOL m_bIgnoreNulls;                // Secondary
    BOOL m_bRequired;                   // Secondary
    BOOL m_bForeign;                    // Secondary
    long m_lDistinctCount;              // All

    // Below the // Implementation comment:
    // Destructor, not otherwise documented
};

The CDaoIndexInfo structure contains information about an index object defined for data access objects (DAO). The references to Primary, Secondary, and All above indicate how the information is returned by the GetIndexInfo member function in classes CDaoTableDef and CDaoRecordset.

Index objects are not represented by an MFC class. Instead, DAO objects underlying MFC objects of class CDaoTableDef or CDaoRecordset contain a collection of index objects, called the Indexes collection. These classes supply member functions to access individual items of index information, or you can access them all at once with a CDaoIndexInfo object by calling the GetIndexInfo member function of the containing object.

CDaoIndexInfo has a constructor and a destructor in order to properly allocate and deallocate the index field information in m_pFieldInfos.

Members

m_strName

Uniquely names the field object. For details, see the topic "Name Property" in DAO Help.

m_pFieldInfos

A pointer to an array of CDaoIndexFieldInfo objects indicating which tabledef or recordset fields are key fields in an index. Each object identifies one field in the index. The default index ordering is ascending. An index object can have one or more fields representing index keys for each record. These can be ascending, descending, or a combination.

m_nFields

The number of fields stored in m_pFieldInfos.

m_bPrimary

If the Primary property is TRUE, the index object represents a primary index. A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order. Because the index field must be unique, the Unique property of the Index object is also set to TRUE in DAO. If the primary index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique. A primary index consists of a key for the table and usually contains the same fields as the primary key.

When you set a primary key for a table, the primary key is automatically defined as the primary index for the table. For more information, see the topics "Primary Property" and "Unique Property" in DAO Help.

Note There can be, at most, one primary index on a table.

m_bUnique

Indicates whether an index object represents a unique index for a table. If this property is TRUE, the index object represents an index that is unique. A unique index consists of one or more fields that logically arrange all records in a table in a unique, predefined order. If the index consists of one field, values in that field must be unique for the entire table. If the index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique.

If both the Unique and Primary properties of an index object are set to TRUE, the index is unique and primary: It uniquely identifies all records in the table in a predefined, logical order. If the Primary property is set to FALSE, the index is a secondary index. Secondary indexes (both key and nonkey) logically arrange records in a predefined order without serving as an identifier for records in the table.

For more information, see the topics "Primary Property" and "Unique Property" in DAO Help.

m_bClustered

Indicates whether an index object represents a clustered index for a table. If this property is TRUE, the index object represents a clustered index; otherwise, it does not. A clustered index consists of one or more nonkey fields that, taken together, arrange all records in a table in a predefined order. With a clustered index, the data in the table is literally stored in the order specified by the clustered index. A clustered index provides efficient access to records in a table. For more information, see the topic "Clustered Property" in DAO Help.

Note The Clustered property is ignored for databases that use the Microsoft Jet database engine because the Jet database engine does not support clustered indexes.

m_bIgnoreNulls

Indicates whether there are index entries for records that have Null values in their index fields. If this property is TRUE, fields with Null values do not have an index entry. To make searching for records using a field faster, you can define an index for the field. If you allow Null entries in an indexed field and expect many of the entries to be Null, you can set the IgnoreNulls property for the index object to TRUE to reduce the amount of storage space that the index uses. The IgnoreNulls property setting and the Required property setting together determine whether a record with a Null index value has an index entry, as the following table shows.

IgnoreNulls | Required | Null in index field
True | False | Null value allowed; no index entry added.
False | False | Null value allowed; index entry added.
True or False | True | Null value not allowed; no index entry added.

For more information, see the topic "IgnoreNulls Property" in DAO Help.

m_bRequired

Indicates whether a DAO index object requires a non-Null value.If this property is TRUE, the index object does not allow a Null value. For more information, see the topic "Required Property" in DAO Help.

Tip When you can set this property for either a DAO index object or a field object (contained by a tabledef, recordset, or querydef object), set it for the field object. The validity of the property setting for a field object is checked before that of an index object.

m_bForeign

Indicates whether an index object represents a foreign key in a table. If this property is TRUE, the index represents a foreign key in a table. A foreign key consists of one or more fields in a foreign table that uniquely identify a row in a primary table. The Microsoft Jet database engine creates an index object for the foreign table and sets the Foreign property when you create a relationship that enforces referential integrity. For more information, see the topic "Foreign Property" in DAO Help.

m_lDistinctCount

Indicates the number of unique values for the index object that are included in the associated table. Check the DistinctCount property to determine the number of unique values, or keys, in an index. Any key is counted only once, even though there may be multiple occurrences of that value if the index permits duplicate values. This information is useful in applications that attempt to optimize data access by evaluating index information. The number of unique values is also known as the cardinality of an index object. The DistinctCount property will not always reflect the actual number of keys at a particular time. For example, a change caused by a transaction rollback will not be reflected immediately in the DistinctCount property. For more information, see the topic "DistinctCount Property" in DAO Help.

Comments

Information retrieved by the GetIndexInfo member function of a tabledef object is stored in a CDaoIndexInfo structure. Call the GetIndexInfo member function of the containing tabledef object in whose Indexes collection the index object is stored. CDaoIndexInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoIndexInfo object.

For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoTableDef::GetIndexInfo


CDaoIndexFieldInfo Structure

The CDaoIndexFieldInfo structure has the following form:

struct CDaoIndexFieldInfo
{
   CString m_strName;          // Primary
   BOOL m_bDescending;         // Primary
};

The CDaoIndexFieldInfo structure contains information about an index field object defined for data access objects (DAO). An index object can have a number of fields, indicating which fields a tabledef (or a recordset based on a table) is indexed on. The references to Primary above indicate how the information is returned in the m_pFieldInfos member of a CDaoIndexInfo object obtained by calling the GetIndexInfo member function of class CDaoTableDef or CDaoRecordset.

Index objects and index field objects are not represented by an MFC class. Instead, the DAO objects underlying MFC objects of class CDaoTableDef or CDaoRecordset contain a collection of index objects, called the Indexes collection. Each index object, in turn, contains a collection of field objects. These classes supply member functions to access individual items of index information, or you can access them all at once with a CDaoIndexInfo object by calling the GetIndexInfo member function of the containing object. The CDaoIndexInfo object, then, has a data member, m_pFieldInfos, that points to an array of CDaoIndexFieldInfo objects.

Members

m_strName

Uniquely names the index field object. For details, see the topic "Name Property" in DAO Help.

m_bDescending

Indicates the index ordering defined by the index object. TRUE if the order is descending.

Comments

Call the GetIndexInfo member function of the containing tabledef or recordset object in whose Indexes collection is stored the index object you are interested in. Then access the m_pFieldInfos member of the CDaoIndexInfo object. The length of the m_pFieldInfos array is stored in m_nFields. CDaoIndexFieldInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoIndexFieldInfo object.

For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoTableDef::GetIndexInfo, CDaoRecordset::GetIndexInfo


CDaoParameterInfo Structure

The CDaoParameterInfo structure has the following form:

struct CDaoParameterInfo
{
   CString m_strName;       // Primary
   short m_nType;           // Primary
   ColeVariant m_varValue;  // Secondary
};

The CDaoParameterInfo structure contains information about a parameter object defined for data access objects (DAO). The references to Primary and Secondary above indicate how the information is returned by the GetParameterInfo member function in class CDaoQueryDef.

MFC does not encapsulate DAO parameter objects in a class. DAO querydef objects underlying MFC CDaoQueryDef objects store parameters in their Parameters collections. To access the parameter objects in a CDaoQueryDef object, call the querydef object’s GetParameterInfo member function for a particular parameter name or an index into the Parameters collection. You can use the CDaoQueryDef::GetParameterCount member function in conjunction with GetParameterInfo to loop through the Parameters collection.

Members

m_strName

Uniquely names the parameter object. For more information, see the topic "Name Property" in DAO Help.

m_nType

A value that indicates the data type of a parameter object. For a list of the possible values, see the m_nType member of the CDaoFieldInfo structure. For more information, see the topic "Type Property" in DAO Help.

m_varValue

The value of the parameter, stored in a COleVariant object.

Comments

Information retrieved by the CDaoQueryDef::GetParameterInfo member function is stored in a CDaoParameterInfo structure. Call GetParameterInfo for the querydef object in whose Parameters collection the parameter object is stored.

Note If you want to get or set only the value of a parameter, use the GetParamValue and SetParamValue member functions of class CDaoRecordset.

CDaoParameterInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoParameterInfo object. For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoQueryDef


CDaoQueryDefInfo Structure

The CDaoQueryDefInfo structure has the following form:

struct CDaoQueryDefInfo
{
   CString m_strName;               // Primary
   short m_nType;                   // Primary
   COleDateTime m_dateCreated;      // Secondary
   COleDateTime m_dateLastUpdated;  // Secondary
   BOOL m_bUpdatable;               // Secondary
   BOOL m_bReturnsRecords;          // Secondary
   CString m_strSQL;                // All
   CString m_strConnect;            // All
   short m_nODBCTimeout;            // All
};

The CDaoQueryDefInfo structure contains information about a querydef object defined for data access objects (DAO). The querydef is an object of class CDaoQueryDef. The references to Primary, Secondary, and All above indicate how the information is returned by the GetQueryDefInfo member function in class CDaoDatabase.

Members

m_strName

Uniquely names the querydef object. For more information, see the topic "Name Property" in DAO Help. Call CDaoQueryDef::GetName to retrieve this property directly.

m_nType

A value that indicates the operational type of a querydef object. The value can be one of the following:

  • dbQSelect Select — the query selects records.

  • dbQAction Action — the query moves or changes data but does not return records.

  • dbQCrosstab Crosstab — the query returns data in a spreadsheet-like format.

  • dbQDelete Delete — the query deletes a set of specified rows.

  • dbQUpdate Update — the query changes a set of records.

  • dbQAppend Append — the query adds new records to the end of a table or query.

  • dbQMakeTable Make-table — the query creates a new table from a recordset.

  • dbQDDL Data-definition — the query affects the structure of tables or their parts.

  • dbQSQLPassThrough Pass-through — the SQL statement is passed directly to the database backend, without intermediate processing.

  • dbQSetOperation Union — the query creates a snapshot-type recordset object containing data from all specified records in two or more tables with any duplicate records removed. To include the duplicates, add the keyword ALL in the querydef’s SQL statement.

  • dbQSPTBulk Used with dbQSQLPassThrough to specify a query that does not return records.

    Note To create an SQL pass-through query, you do not set the dbQSQLPassThrough constant. This is set automatically by the Microsoft Jet database engine when you create a querydef object and set the Connect property.

    For more information, see the topic "Type Property" in DAO Help.

m_dateCreated

The date and time the querydef was created. To directly retrieve the date the querydef was created, call the GetDateCreated member function of the CDaoTableDef object associated with the table. See Comments below for more information. Also see the topic "DateCreated, LastUpdated Properties" in DAO Help.

m_dateLastUpdated

The date and time of the most recent change made to the querydef. To directly retrieve the date the table was last updated, call the GetDateLastUpdated member function of the querydef. See Comments below for more information. And see the topic "DateCreated, LastUpdated Properties" in DAO Help.

m_bUpdatable

Indicates whether changes can be made to a querydef object. If this property is TRUE, the querydef is updatable; otherwise, it is not. Updatable means the querydef object’s query definition can be changed. The Updatable property of a querydef object is set to TRUE if the query definition can be updated, even if the resulting recordset is not updatable. To retrieve this property directly, call the querydef’s CanUpdate member function. For more information, see the topic "Updatable Property" in DAO Help.

m_bReturnsRecords

Indicates whether an SQL pass-through query to an external database returns records. If this property is TRUE, the query returns records. To directly retrieve this property, call CDaoQueryDef::GetReturnsRecords. Not all SQL pass-through queries to external databases return records. For example, an SQL UPDATE statement updates records without returning records, while an SQL SELECT statement does return records. For more information, see the topic "ReturnsRecords Property" in DAO Help.

m_strSQL

The SQL statement that defines the query executed by a querydef object. The SQL property contains the SQL statement that determines how records are selected, grouped, and ordered when you execute the query. You can use the query to select records to include in a dynaset- or snapshot-type recordset object. You can also define bulk queries to modify data without returning records. You can retrieve the value of this property directly by calling the querydef’s GetSQL member function. For more information, see the article DAO Queries in Visual C++ Programmer’s Guide and the topic "SQL Property" in DAO Help.

m_strConnect

Provides information about the source of a database used in a pass-through query. This information takes the form of a connect string. For more information about connect strings, and for information about retrieving the value of this property directly, see the CDaoDatabase::GetConnect member function.

m_nODBCTimeout

The number of seconds the Microsoft Jet database engine waits before a timeout error occurs when a query is run on an ODBC database. When you’re using an ODBC database, such as Microsoft SQL Server, there may be delays because of network traffic or heavy use of the ODBC server. Rather than waiting indefinitely, you can specify how long the Microsoft Jet engine waits before it produces an error. The default timeout value is 60 seconds. You can retrieve the value of this property directly by calling the querydef’s GetODBCTimeout member function. For more information, see the topic "ODBCTimeout Property" in DAO Help.

Comments

Information retrieved by the CDaoDatabase::GetQueryDefInfo member function is stored in a CDaoQueryDefInfo structure. Call GetQueryDefInfo for the database object in whose QueryDefs collection the querydef object is stored. CDaoQueryDefInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoQueryDefInfo object. Class CDaoDatabase also supplies member functions for directly accessing all of the properties returned in a CDaoQueryDefInfo object, so you will probably seldom need to call GetQueryDefInfo.

When you append a new field or parameter object to the Fields or Parameters collection of a querydef object, an exception is thrown if the underlying database does not support the data type specified for the new object.

The date and time settings are derived from the computer on which the querydef was created or last updated. In a multiuser environment, users should get these settings directly from the file server using the net time command to avoid discrepancies in the DateCreated and LastUpdated property settings. For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoQueryDef, CDaoDatabase


CDaoRelationInfo Structure

The CDaoRelationInfo structure has the following form:

struct CDaoRelationInfo
{
   CDaoRelationInfo( );             // Constructor

   CString m_strName;                      // Primary
   CString m_strTable;                     // Primary
   CString m_strForeignTable;              // Primary
   long m_lAttributes;                     // Secondary
   CDaoRelationFieldInfo* m_pFieldInfos;   // Secondary
   short m_nFields;                        // Secondary

   // Below the // Implementation comment:
   // Destructor, not otherwise documented
};

The CDaoRelationInfo structure contains information about a relation defined between fields of two tables in a CDaoDatabase object. The references to Primary and Secondary above indicate how the information is returned by the GetRelationInfo member function in class CDaoDatabase.

Relation objects are not represented by an MFC class. Instead, the DAO object underlying an MFC object of the CDaoDatabase class maintains a collection of relation objects: CDaoDatabase supplies member functions to access some individual items of relation information, or you can access them all at once with a CDaoRelationInfo object by calling the GetRelationInfo member function of the containing database object.

Members

m_strName

Uniquely names the relation object. For more information, see the topic "Name Property" in DAO Help.

m_strTable

Names the primary table in the relation.

m_strForeignTable

Names the foreign table in the relation. A foreign table is a table used to contain foreign keys. Generally, you use a foreign table to establish or enforce referential integrity. The foreign table is usually on the many side of a one-to-many relationship. Examples of foreign tables include tables containing codes for the American states or Canadian provinces or customer orders.

m_lAttributes

Contains information about the relation type. The value of this member can be any of the following:

  • dbRelationUnique Relationship is one-to-one.

  • dbRelationDontEnforce Relationship is not enforced (no referential integrity).

  • dbRelationInherited Relationship exists in a noncurrent database that contains the two attached tables.

  • dbRelationLeft The relationship is a left join. A left outer join includes all of the records from the first (left-hand) of two tables, even if there are no matching values for records in the second (right-hand) table.

  • dbRelationRight The relationship is a right join. A right outer join includes all of the records from the second (right-hand) of two tables, even if there are no matching values for records in the first (left-hand) table.

  • dbRelationUpdateCascade Updates will cascade.

  • dbRelationDeleteCascade Deletions will cascade.

m_pFieldInfos

A pointer to an array of CDaoRelationFieldInfo structures. The array contains one object for each field in the relation. The m_nFields data member gives a count of the array elements.

m_nFields

The number of CDaoRelationFieldInfo objects in the m_pFieldInfos data member.

Comments

Information retrieved by the CDaoDatabase::GetRelationInfo member function is stored in a CDaoRelationInfo structure. CDaoRelationInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoRelationInfo object. For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoRelationFieldInfo


CDaoRelationFieldInfo Structure

The CDaoRelationFieldInfo structure has the following form:

struct CDaoRelationFieldInfo
{
   CString m_strName;           // Primary
   CString m_strForeignName;    // Primary
};

The CDaoRelationFieldInfo structure contains information about a field in a relation defined for data access objects (DAO). A DAO relation object specifies the fields in a primary table and the fields in a foreign table that define the relation. The references to Primary in the structure definition above indicate how the information is returned in the m_pFieldInfos member of a CDaoRelationInfo object obtained by calling the GetRelationInfo member function of class CDaoDatabase.

Relation objects and relation field objects are not represented by an MFC class. Instead, the DAO objects underlying MFC objects of class CDaoDatabase contain a collection of relation objects, called the Relations collection. Each relation object, in turn, contains a collection of relation field objects. Each relation field object correlates a field in the primary table with a field in the foreign table. Taken together, the relation field objects define a group of fields in each table, which together define the relation. CDaoDatabase lets you access relation objects with a CDaoRelationInfo object by calling the GetRelationInfo member function. The CDaoRelationInfo object, then, has a data member, m_pFieldInfos, that points to an array of CDaoRelationFieldInfo objects.

Members

m_strName

The name of the field in the primary table of the relation.

m_strForeignName

The name of the field in the foreign table of the relation.

Comments

Call the GetRelationInfo member function of the containing CDaoDatabase object in whose Relations collection is stored the relation object you are interested in. Then access the m_pFieldInfos member of the CDaoRelationInfo object. CDaoRelationFieldInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoRelationFieldInfo object.

For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoRelationInfo


CDaoTableDefInfo Structure

The CDaoTableDefInfo structure has the following form:

struct CDaoTableDefInfo
{
   CString m_strName;               // Primary
   BOOL m_bUpdatable;               // Primary
   long m_lAttributes;              // Primary
   COleDateTime m_dateCreated;      // Secondary
   COleDateTime m_dateLastUpdated;  // Secondary
   CString m_strSrcTableName;       // Secondary
   CString m_strConnect;            // Secondary
   CString m_strValidationRule;     // All
   CString m_strValidationText;     // All
   long m_lRecordCount;             // All
};

The CDaoTableDefInfo structure contains information about a tabledef object defined for data access objects (DAO). The tabledef is an object of class CDaoTableDef. The references to Primary, Secondary, and All above indicate how the information is returned by the GetTableDefInfo member function in class CDaoDatabase.

Members

m_strName

Uniquely names the tabledef object. To retrieve the value of this property directly, call the tabledef object’s GetName member function. For more information, see the topic "Name Property" in DAO Help.

m_bUpdatable

Indicates whether changes can be made to the table. The quick way to determine whether a table is updatable is to open a CDaoTableDef object for the table and call the object’s CanUpdate member function. CanUpdate always returns nonzero (TRUE) for a newly created tabledef object and 0 (FALSE) for an attached tabledef object. A new tabledef object can be appended only to a database for which the current user has write permission. If the table contains only nonupdatable fields, CanUpdate returns 0. When one or more fields are updatable, CanUpdate returns nonzero. You can edit only the updatable fields. For more information, see the topic "Updatable Property" in DAO Help.

m_lAttributes

Specifies characteristics of the table represented by the tabledef object. To retrieve the current attributes of a tabledef, call its GetAttributes member function. The value returned can be a combination of these long constants (using the bitwise-OR (|) operator):

  • dbAttachExclusive For databases that use the Microsoft Jet database engine, indicates the table is an attached table opened for exclusive use.

  • dbAttachSavePWD For databases that use the Microsoft Jet database engine, indicates that the user ID and password for the attached table are saved with the connection information.

  • dbSystemObject Indicates the table is a system table provided by the Microsoft Jet database engine. (Read-only.)

  • dbHiddenObject Indicates the table is a hidden table provided by the Microsoft Jet database engine (for temporary use). (Read-only.)

  • dbAttachedTable Indicates the table is an attached table from a non-ODBC database, such as a Paradox database.

  • dbAttachedODBC Indicates the table is an attached table from an ODBC database, such as Microsoft SQL Server.

m_dateCreated

The date and time the table was created. To directly retrieve the date the table was created, call the GetDateCreated member function of the CDaoTableDef object associated with the table. See Comments below for more information. For related information, see the topic "DateCreated, LastUpdated Properties" in DAO Help.

m_dateLastUpdated

The date and time of the most recent change made to the design of the table. To directly retrieve the date the table was last updated, call the GetDateLastUpdated member function of the CDaoTableDef object associated with the table. See Comments below for more information. For related information, see the topic "DateCreated, LastUpdated Properties" in DAO Help.

m_strSrcTableName

Specifies the name of an attached table if any. To directly retrieve the source table name, call the GetSourceTableName member function of the CDaoTableDef object associated with the table.

m_strConnect

Provides information about the source of an open database. You can check this property by calling the GetConnect member function of your CDaoTableDef object. For more information about connect strings, see GetConnect.

m_strValidationRule

A value that validates the data in tabledef fields as they are changed or added to a table. Validation is supported only for databases that use the Microsoft Jet database engine. To directly retrieve the validation rule, call the GetValidationRule member function of the CDaoTableDef object associated with the table. For related information, see the topic "ValidationRule Property" in DAO Help.

m_strValidationText

A value that specifies the text of the message that your application should display if the validation rule specified by the ValidationRule property is not satisfied. For related information, see the topic "ValidationText Property" in DAO Help.

m_lRecordCount

The number of records accessed in a tabledef object. This property setting is read-only. To directly retrieve the record count, call the GetRecordCount member function of the CDaoTableDef object. The documentation for GetRecordCount describes the record count further. Note that retrieving this count can be a time-consuming operation if the table contains many records.

Comments

Information retrieved by the CDaoDatabase::GetTableDefInfo member function is stored in a CDaoTableDefInfo structure. Call the GetTableDefInfo member function of the CDaoDatabase object in whose TableDefs collection the tabledef object is stored. CDaoTableDefInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoTableDefInfo object.

The date and time settings are derived from the computer on which the base table was created or last updated. In a multiuser environment, users should get these settings directly from the file server to avoid discrepancies in the DateCreated and LastUpdated property settings.

For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoTableDef, CDaoDatabase, CDaoTableDef::CanUpdate, CDaoTableDef::GetAttributes, CDaoTableDef::GetDateCreated, CDaoTableDef::GetDateLastUpdated, CDaoTableDef::GetRecordCount, CDaoTableDef::GetSourceTableName, CDaoTableDef::GetValidationRule, CDaoTableDef::GetValidationText


CDaoWorkspaceInfo Structure

The CDaoWorkspaceInfo structure has the following form:

struct CDaoWorkspaceInfo
{
   CString m_strName;           // Primary
   CString m_strUserName;       // Secondary
   BOOL m_bIsolateODBCTrans;    // All
};

The CDaoWorkspaceInfo structure contains information about a workspace defined for data access objects (DAO) database access. The workspace is an object of class CDaoWorkspace. The references to Primary, Secondary, and All above indicate how the information is returned by the GetWorkspaceInfo member function in class CDaoWorkspace.

Members

m_strName

Uniquely names the workspace object. To retrieve the value of this property directly, call the querydef object’s GetName member function. For more information, see the topic "Name Property" in DAO Help.

m_strUserName

A value that represents the owner of a workspace object. For related information, see the topic "UserName Property" in DAO Help.

m_bIsolateODBCTrans

A value that indicates whether multiple transactions that involve the same ODBC database are isolated. For more information, see CDaoWorkspace::SetIsolateODBCTrans. For related information, see the topic "IsolateODBCTrans Property" in DAO Help.

Comments

Information retrieved by the CDaoWorkspace::GetWorkspaceInfo member function is stored in a CDaoWorkspaceInfo structure. CDaoWorkspaceInfo also defines a Dump member function in debug builds. You can use Dump to dump the contents of a CDaoWorkspaceInfo object. For information on using this and other MFC DAO Info structures, see the article DAO Collections: Obtaining Information About DAO Objects in Visual C++ Programmer's Guide.

See Also CDaoWorkspace


CODBCFieldInfo Structure

The CODBCFieldInfo structure has the following form:

struct CODBCFieldInfo
{
   CString m_strName;
   SWORD m_nSQLType;
   UDWORD m_nPrecision;
   SWORD m_nScale;
   SWORD m_nNullability;
};

The CODBCFieldInfo structure contains information about the fields in an ODBC data source. To retrieve this information, call CRecordset::GetODBCFieldInfo.

Members

m_strName

The name of the field.

m_nSQLType

The SQL data type of the field. This can be an ODBC SQL data type or a driver-specific SQL data type. For a list of valid ODBC SQL data types, see "SQL Data Types" in Appendix D of the ODBC SDK Programmer's Reference. For information about driver-specific SQL data types, see the driver's documentation.

m_nPrecision

The maximum precision of the field. For details, see "Precision, Scale, Length, and Display Size" in Appendix D of the ODBC SDK Programmer's Reference.

m_nScale

The scale of the field. For details, see "Precision, Scale, Length, and Display Size" in Appendix D of the ODBC SDK Programmer's Reference.

m_nNullability

Whether the field accepts a Null value. This can be one of two values: SQL_NULLABLE if the field accepts Null values, or SQL_NO_NULLS if the field does not accept Null values.

See Also CRecordset::GetODBCFieldInfo, CRecordset::GetFieldValue


COLORADJUSTMENT Structure

The COLORADJUSTMENT structure has the following form:

typedef struct  tagCOLORADJUSTMENT {    /* ca */
    WORD  caSize;
    WORD  caFlags;
    WORD  caIlluminantIndex;
    WORD  caRedGamma;
    WORD  caGreenGamma;
    WORD  caBlueGamma;
    WORD  caReferenceBlack;
    WORD  caReferenceWhite;
    SHORT caContrast;
    SHORT caBrightness;
    SHORT caColorfulness;
    SHORT caRedGreenTint;
} COLORADJUSTMENT;

The COLORADJUSTMENT structure defines the color adjustment values used by the Windows StretchBlt and StretchDIBits functions when the StretchBlt mode is HALFTONE.

Members

caSize

Specifies the size of the structure in bytes.

caFlags

Specifies how the output image should be prepared. This member can be set to NULL or any combination of the following values:

  • CA_NEGATIVE Specifies that the negative of the original image should be displayed.

  • CA_LOG_FILTER Specifies that a logarithmic function should be applied to the final density of the output colors. This will increase the color contrast when the luminance is low.

caIlluminantIndex

Specifies the luminance of the light source under which the image object is viewed. This member can be set to one of the following values:

  • ILLUMINANT_EQUAL_ENERGY

  • ILLUMINANT_A

  • ILLUMINANT_B

  • ILLUMINANT_C

  • ILLUMINANT_D50

  • ILLUMINANT_D55

  • ILLUMINANT_D65

  • ILLUMINANT_D75

  • ILLUMINANT_F2

  • ILLUMINANT_TURNGSTEN

  • ILLUMINANT_DAYLIGHT

  • ILLUMINANT_FLUORESCENT

  • ILLUMINANT_NTSC

caRedGamma

Specifies the n-th power gamma-correction value for the red primary of the source colors. The value must be in the range from 2,500 to 65,000. A value of 10,000 means no gamma-correction.

caGreenGamma

Specifies the n-th power gamma-correction value for the green primary of the source colors. The value must be in the range from 2,500 to 65,000. A value of 10,000 means no gamma-correction.

caBlueGamma

Specifies the n-th power gamma-correction value for the blue primary of the source colors. The value must be in the range from 2,500 to 65,000. A value of 10,000 means no gamma-correction.

caReferenceBlack

Specifies the black reference for the source colors. Any colors that are darker than this are treated as black. The value must be in the range from 0 to 4,000.

caReferenceWhite

Specifies the white reference for the source colors. Any colors that are lighter than this are treated as white. The value must be in the range from 6,000 to 10,000.

caContrast

Specifies the amount of contrast to be applied to the source object. The value must be in the range from -100 to 100. A value of 0 means no contrast adjustment.

caBrightness

Specifies the amount of brightness to be applied to the source object. The value must be in the range from -100 to 100. A value of 0 means no brightness adjustment.

caColorfulness

Specifies the amount of colorfulness to be applied to the source object. The value must be in the range from -100 to 100. A value of 0 means no colorfulness adjustment.

caRedGreenTint

Specifies the amount of red or green tint adjustment to be applied to the source object. The value must be in the range from -100 to 100. Positive numbers would adjust towards red and negative numbers adjust towards green. A 0 means no tint adjustment.

See Also CDC::GetColorAdjustment


COMPAREITEMSTRUCT Structure

The COMPAREITEMSTRUCT data structure has this form:

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

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

Members

CtlType

ODT_LISTBOX (which specifies an owner-draw list box) or ODT_COMBOBOX (which specifies an owner-draw combo box).

CtlID

The control ID for the list box or combo box.

hwndItem

The window handle of the control.

itemID1

The index of the first item in the list box or combo box being compared.

itemData1

Application-supplied data for the first item being compared. This value was passed in the call that added the item to the combo or list box.

itemID2

Index of the second item in the list box or combo box being compared.

itemData2

Application-supplied data for the second item being compared. This value was passed in the call that added the item to the combo or list box.

See Also CWnd::OnCompareItem


CREATESTRUCT Structure

The CREATESTRUCT structure has the following form:

typedef struct tagCREATESTRUCT {
   LPVOID    lpCreateParams;
   HANDLE    hInstance;
   HMENU     hMenu;
   HWND      hwndParent;
   int       cy;
   int       cx;
   int       y;
   int       x;
   LONG      style;
   LPCSTR    lpszName;
   LPCSTR    lpszClass;
   DWORD     dwExStyle;
} CREATESTRUCT;

The CREATESTRUCT structure defines the initialization parameters passed to the window procedure of an application.

Members

lpCreateParams

Points to data to be used to create the window.

hInstance

Identifies the module-instance handle of the module that owns the new window.

hMenu

Identifies the menu to be used by the new window. If a child window, contains the integer ID.

hwndParent

Identifies the window that owns the new window. This member is NULL if the new window is a top-level window.

cy

Specifies the height of the new window.

cx

Specifies the width of the new window.

y

Specifies the y-coordinate of the upper-left corner of the new window. Coordinates are relative to the parent window if the new window is a child window; otherwise coordinates are relative to the screen origin.

x

Specifies the x-coordinate of the upper-left corner of the new window. Coordinates are relative to the parent window if the new window is a child window; otherwise coordinates are relative to the screen origin.

style

Specifies the new window’s style.

lpszName

Points to a null-terminated string that specifies the new window’s name.

lpszClass

Points to a null-terminated string that specifies the new window’s Windows class name (a WNDCLASS structure; for more information, see the Win32 SDK documentation).

dwExStyle

Specifies the extended style for the new window.

See Also CWnd::OnCreate


DELETEITEMSTRUCT Structure

The DELETEITEMSTRUCT structure has the following form:

typedef struct tagDELETEITEMSTRUCT { /* ditms */
    UINT CtlType;
    UINT CtlID;
    UINT itemID;
    HWND hwndItem;
    UINT itemData;
} DELETEITEMSTRUCT;

The DELETEITEMSTRUCT structure describes a deleted owner-drawn list-box or combo-box item. When an item is removed from the list box or combo box or when the list box or combo box is destroyed, Windows sends the WM_DELETEITEM message to the owner for each deleted item. The lParam parameter of the message contains a pointer to this structure.

Members

CtlType

Specifies ODT_LISTBOX (an owner-drawn list box) or ODT_COMBOBOX (an owner-drawn combo box).

CtlID

Specifies the identifier of the list box or combo box.

itemID

Specifies index of the item in the list box or combo box being removed.

hwndItem

Identifies the control.

itemData

Specifies application-defined data for the item. This value is passed to the control in the lParam parameter of the message that adds the item to the list box or combo box.

See Also CWnd::OnDeleteItem


DEVMODE Structure

The DEVMODE structure has the following form:

typedef struct _devicemode {    /* dvmd */
    TCHAR  dmDeviceName[32];
    WORD   dmSpecVersion;
    WORD   dmDriverVersion;
    WORD   dmSize;
    WORD   dmDriverExtra;
    DWORD  dmFields;
    short  dmOrientation;
    short  dmPaperSize;
    short  dmPaperLength;
    short  dmPaperWidth;
    short  dmScale;
    short  dmCopies;
    short  dmDefaultSource;
    short  dmPrintQuality;
    short  dmColor;
    short  dmDuplex;
    short  dmYResolution;
    short  dmTTOption;
    short  dmCollate;
    TCHAR  dmFormName[32];
    WORD   dmUnusedPadding;
    USHORT dmBitsPerPel;
    DWORD  dmPelsWidth;
    DWORD  dmPelsHeight;
    DWORD  dmDisplayFlags;
    DWORD  dmDisplayFrequency;
} DEVMODE;

The DEVMODE data structure contains information about the device initialization and environment of a printer.

Members

dmDeviceName

Specifies the name of the device the driver supports; for example, PCL/HP LaserJet in the case of PCL/HP LaserJet®. This string is unique among device drivers.

dmSpecVersion

Specifies the version number of the initialization data specification on which the structure is based.

dmDriverVersion

Specifies the printer driver version number assigned by the printer driver developer.

dmSize

Specifies the size, in bytes, of the DEVMODE structure except the dmDriverData (device-specific) member. If an application manipulates only the driver-independent portion of the data, it can use this member to determine the length of the structure without having to account for different versions.

dmDriverExtra

Contains the number of bytes of private driver-data that follow this structure. If a device driver does not use device-specific information, set this member to zero.

dmFields

Specifies which of the remaining members in the DEVMODE structure have been initialized. Bit 0 (defined as DM_ORIENTATION) corresponds to dmOrientation; bit 1 (defined as DM_PAPERSIZE) specifies dmPaperSize, and so on. A printer driver supports only those members that are appropriate for the printer technology.

dmOrientation

Selects the orientation of the paper. This member can be either DMORIENT_PORTRAIT (1) or DMORIENT_LANDSCAPE (2).

dmPaperSize

Selects the size of the paper to print on. This member can be set to zero if the length and width of the paper are both set by the dmPaperLength and dmPaperWidth members. Otherwise, the dmPaperSize member can be set to one of the following predefined values:

  • DMPAPER_LETTER Letter, 8 1/2 by 11 inches

  • MPAPER_LEGAL Legal, 8 1/2 by 14 inches

  • DMPAPER_A4 A4 Sheet, 210 by 297 millimeters

  • DMPAPER_CSHEET C Sheet, 17 by 22 inches

  • DMPAPER_DSHEET D Sheet, 22 by 34 inches

  • DMPAPER_ESHEET E Sheet, 34 by 44 inches

  • DMPAPER_LETTERSMALL Letter Small, 8 1/2 by 11 inches

  • DMPAPER_TABLOID Tabloid, 11 by 17 inches

  • DMPAPER_LEDGER Ledger, 17 by 11 inches

  • DMPAPER_STATEMENT Statement, 5 1/2 by 8 1/2 inches

  • DMPAPER_EXECUTIVE Executive, 7 1/4 by 10 1/2 inches

  • DMPAPER_A3 A3 sheet, 297 by 420 millimeters

  • DMPAPER_A4SMALL A4 small sheet, 210 by 297 millimeters

  • DMPAPER_A5 A5 sheet, 148 by 210 millimeters

  • DMPAPER_B4 B4 sheet, 250 by 354 millimeters

  • DMPAPER_B5 B5 sheet, 182-by-257-millimeter paper

  • DMPAPER_FOLIO Folio, 8-1/2-by-13-inch paper

  • DMPAPER_QUARTO Quarto, 215-by-275-millimeter paper

  • DMPAPER_10X14 10-by-14-inch sheet

  • DMPAPER_11X17 11-by-17-inch sheet

  • DMPAPER_NOTE Note, 8 1/2 by 11 inches

  • DMPAPER_ENV_9 #9 Envelope, 3 7/8 by 8 7/8 inches

  • DMPAPER_ENV_10 #10 Envelope, 4 1/8 by 9 1/2 inches

  • DMPAPER_ENV_11 #11 Envelope, 4 1/2 by 10 3/8 inches

  • DMPAPER_ENV_12 #12 Envelope, 4 3/4 by 11 inches

  • DMPAPER_ENV_14 #14 Envelope, 5 by 11 1/2 inches

  • DMPAPER_ENV_DL DL Envelope, 110 by 220 millimeters

  • DMPAPER_ENV_C5 C5 Envelope, 162 by 229 millimeters

  • DMPAPER_ENV_C3 C3 Envelope, 324 by 458 millimeters

  • DMPAPER_ENV_C4 C4 Envelope, 229 by 324 millimeters

  • DMPAPER_ENV_C6 C6 Envelope, 114 by 162 millimeters

  • DMPAPER_ENV_C65 C65 Envelope, 114 by 229 millimeters

  • DMPAPER_ENV_B4 B4 Envelope, 250 by 353 millimeters

  • DMPAPER_ENV_B5 B5 Envelope, 176 by 250 millimeters

  • DMPAPER_ENV_B6 B6 Envelope, 176 by 125 millimeters

  • DMPAPER_ENV_ITALY Italy Envelope, 110 by 230 millimeters

  • DMPAPER_ENV_MONARCH Monarch Envelope, 3 7/8 by 7 1/2 inches

  • DMPAPER_ENV_PERSONAL 6 3/4 Envelope, 3 5/8 by 6 1/2 inches

  • DMPAPER_FANFOLD_US US Std Fanfold, 14 7/8 by 11 inches

  • DMPAPER_FANFOLD_STD_GERMAN German Std Fanfold, 8 1/2 by 12 inches

  • DMPA PER_FANFOLD_LGL_GERMAN German Legal Fanfold, 8 1/2 by 13 inches

dmPaperLength

Overrides the length of the paper specified by the dmPaperSize member, either for custom paper sizes or for devices such as dot-matrix printers, which can print on a page of arbitrary length. These values, along with all other values in this structure that specify a physical length, are in tenths of a millimeter.

dmPaperWidth

Overrides the width of the paper specified by the dmPaperSize member.

dmScale

Specifies the factor by which the printed output is to be scaled. The apparent page size is scaled from the physical page size by a factor of dmScale/100. For example, a letter-sized page with a dmScale value of 50 would contain as much data as a page of 17 by 22 inches because the output text and graphics would be half their original height and width.

dmCopies

Selects the number of copies printed if the device supports multiple-page copies.

dmDefaultSource

Reserved; must be zero.

dmPrintQuality

Specifies the printer resolution. There are four predefined device-independent values:

  • DMRES_HIGH

  • DMRES_MEDIUM

  • DMRES_LOW

  • DMRES_DRAFT

    If a positive value is given, it specifies the number of dots per inch (DPI) and is therefore device dependent.

dmColor

Switches between color and monochrome on color printers. Following are the possible values:

  • DMCOLOR_COLOR

  • DMCOLOR_MONOCHROME

dmDuplex

Selects duplex or double-sided printing for printers capable of duplex printing. Following are the possible values:

  • DMDUP_SIMPLEX

  • DMDUP_HORIZONTAL

  • DMDUP_VERTICAL

dmYResolution

Specifies the y-resolution, in dots per inch, of the printer. If the printer initializes this member, the dmPrintQuality member specifies the x-resolution, in dots per inch, of the printer.

dmTTOption

Specifies how TrueType® fonts should be printed. This member can be one of the following values:

  • DMTT_BITMAP Prints TrueType fonts as graphics. This is the default action for dot-matrix printers.

  • DMTT_DOWNLOAD Downloads TrueType fonts as soft fonts. This is the default action for Hewlett-Packard printers that use Printer Control Language (PCL).

  • DMTT_SUBDEV Substitute device fonts for TrueType fonts. This is the default action for PostScript® printers.

dmCollate

Specifies whether collation should be used when printing multiple copies. Using DMCOLLATE_FALSE provides faster, more efficient output, since the data is sent to a page printer just once, no matter how many copies are required. The printer is told to simply print the page again. This member can be be one of the following values:

  • DMCOLLATE_TRUE Collate when printing multiple copies.

  • DMCOLLATE_FALSE Do NOT collate when printing multiple copies.

dmFormName

Specifies the name of the form to use; for example, Letter or Legal. A complete set of names can be retrieved through the Windows EnumForms function.

dmUnusedPadding

Used to align the structure to a DWORD boundary. This should not be used or referenced. Its name and usage is reserved, and can change in future releases.

dmBitsPerPel

Specifies in bits per pixel the color resolution of the display device. For example: 4 bits for 16 colors, 8 bits for 256 colors, or 16 bits for 65,536 colors.

dmPelsWidth

Specifies the width, in pixels, of the visible device surface.

dmPelsHeight

Specifies the height, in pixels, of the visible device surface.

dmDisplayFlags

Specifies the device’s display mode. The following are valid flags:

  • DM_GRAYSCALE Specifies that the display is a non-color device. If this flag is not set, color is assumed.

  • DM_INTERLACED Specifies that the display mode is interlaced. If the flag is not set, non-interlaced is assumed.

dmDisplayFrequency

Specifies the frequency, in hertz (cycles per second), of the display device in a particular mode.

Comments

A device driver’s private data will follow the dmDisplayMode member. The number of bytes of private data is specified by the dmDriverExtra member.

See Also CDC::ResetDC, CPrintDialog::GetDevMode


DEVNAMES Structure

The DEVNAMES structure has the following form:

typedef struct tagDEVNAMES { /* dvnm */
    WORD wDriverOffset;
    WORD wDeviceOffset;
    WORD wOutputOffset;
    WORD wDefault;
    /* driver, device, and port-name strings follow wDefault */
} DEVNAMES;

The DEVNAMES structure contains strings that identify the driver, device, and output-port names for a printer. The PrintDlg function uses these strings to initialize members in the system-defined Print dialog box. When the user closes the dialog box, information about the selected printer is returned in this structure.

Members

wDriverOffset

(Input/Output) Specifies the offset to a null-terminated string that contains the filename (without the extension) of the device driver. On input, this string is used to determine the printer to display initially in the dialog box.

wDeviceOffset

(Input/Output) Specifies the offset to the null-terminated string (maximum of 32 bytes including the null) that contains the name of the device. This string must be identical to the dmDeviceName member of the DEVMODE structure.

wOutputOffset

(Input/Output) Specifies the offset to the null-terminated string that contains the DOS device name for the physical output medium (output port).

wDefault

Specifies whether the strings contained in the DEVNAMES structure identify the default printer. This string is used to verify that the default printer has not changed since the last print operation. On input, if the DN_DEFAULTPRN flag is set, the other values in the DEVNAMES structure are checked against the current default printer. If any of the strings do not match, a warning message is displayed informing the user that the document may need to be reformatted. On output, the wDefault member is changed only if the Print Setup dialog box was displayed and the user chose the OK button. The DN_DEFAULTPRN flag is set if the default printer was selected. If a specific printer is selected, the flag is not set. All other bits in this member are reserved for internal use by the Print Dialog box procedure.

See Also CPrintDialog::CreatePrinterDC


DRAWITEMSTRUCT Structure

The DRAWITEMSTRUCT structure has the following form:

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

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

Members

CtlType

The control type. The values for control types are as follows:

  • ODT_BUTTON Owner-drawn button

  • ODT_COMBOBOX Owner-drawn combo box

  • ODT_LISTBOX Owner-drawn list box

  • ODT_MENU Owner-drawn menu

  • ODT_LISTVIEW List view control

  • ODT_STATIC Owner-drawn static control

  • ODT_TAB Tab control

CtlID

The control ID for a combo box, list box, or button. This member is not used for a menu.

itemID

The menu-item ID for a menu or the index of the item in a list box or combo box. For an empty list box or combo box, this member is a negative value, which allows the application to draw only the focus rectangle at the coordinates specified by the rcItem member even though there are no items in the control. The user can thus be shown whether the list box or combo box has the input focus. The setting of the bits in the itemAction member determines whether the rectangle is to be drawn as though the list box or combo box has input focus.

itemAction

Defines the drawing action required. This will be one or more of the following bits:

  • ODA_DRAWENTIRE This bit is set when the entire control needs to be drawn.

  • ODA_FOCUS This bit is set when the control gains or loses input focus. The itemState member should be checked to determine whether the control has focus.

  • ODA_SELECT This bit is set when only the selection status has changed. The itemState member should be checked to determine the new selection state.

itemState

Specifies the visual state of the item after the current drawing action takes place. That is, if a menu item is to be dimmed, the state flag ODS_GRAYED will be set. The state flags are as follows:

  • ODS_CHECKED This bit is set if the menu item is to be checked. This bit is used only in a menu.

  • ODS_DISABLED This bit is set if the item is to be drawn as disabled.

  • ODS_FOCUS This bit is set if the item has input focus.

  • ODS_GRAYED This bit is set if the item is to be dimmed. This bit is used only in a menu.

  • ODS_SELECTED This bit is set if the item’s status is selected.

  • ODS_COMBOBOXEDIT The drawing takes place in the selection field (edit control) of an ownerdrawn combo box.

  • ODS_DEFAULT The item is the default item.

hwndItem

Specifies the window handle of the control for combo boxes, list boxes, and buttons. Specifies the handle of the menu (HMENU) that contains the item for menus.

hDC

Identifies a device context. This device context must be used when performing drawing operations on the control.

rcItem

A rectangle in the device context specified by the hDC member that defines the boundaries of the control to be drawn. Windows automatically clips anything the owner draws in the device context for combo boxes, list boxes, and buttons, but it does not clip menu items. When drawing menu items, the owner must not draw outside the boundaries of the rectangle defined by the rcItem member.

itemData

For a combo box or list box, this member contains the value that was passed to the list box by one of the following:

  • CComboBox::AddString

  • CComboBox::InsertString

  • CListBox::AddString

  • CListBox::InsertString

    For a menu, this member contains the value that was passed to the menu by one of the following:

  • CMenu::AppendMenu

  • CMenu::InsertMenu

  • CMenu::ModifyMenu

See Also CWnd::OnDrawItem


EXTENSION_CONTROL_BLOCK Structure

The EXTENSION_CONTROL_BLOCK structure has the following form:

typedef struct _EXTENSION_CONTROL_BLOCK {

    DWORD     cbSize;                              //IN
    DWORD     dwVersion                            //IN
    HCONN     ConnID;                              //IN
    DWORD     dwHttpStatusCode;                   //OUT
    CHAR      lpszLogData[HSE_LOG_BUFFER_LEN];    //OUT
    LPSTR     lpszMethod;                          //IN
    LPSTR     lpszQueryString;                     //IN
    LPSTR     lpszPathInfo;                        //IN
    LPSTR     lpszPathTranslated;                  //IN
    DWORD     cbTotalBytes;                        //IN
    DWORD     cbAvailable;                         //IN
    LPBYTE    lpbData;                             //IN
    LPSTR     lpszContentType;                     //IN

    BOOL ( WINAPI * GetServerVariable )
       ( HCONN       hConn,
        LPSTR       lpszVariableName,
        LPVOID      lpvBuffer,
        LPDWORD     lpdwSize );

    BOOL ( WINAPI * WriteClient )
       ( HCONN      ConnID,
       LPVOID     Buffer,
       LPDWORD    lpdwBytes,
       DWORD      dwReserved );

    BOOL ( WINAPI * ReadClient )
       ( HCONN      ConnID,
       LPVOID     lpvBuffer,
       LPDWORD    lpdwSize );

    BOOL ( WINAPI * ServerSupportFunction )
       ( HCONN      hConn,
       DWORD      dwHSERRequest,
       LPVOID     lpvBuffer,
       LPDWORD    lpdwSize,
       LPDWORD    lpdwDataType );

} EXTENSION_CONTROL_BLOCK, *LPEXTENSION_CONTROL_BLOCK;

The server communicates with the ISA via the EXTENSION_CONTROL_BLOCK.

The references to IN and OUT above indicates whether the member applies to messages to the extension (IN) or from the extension (OUT).

Members

The EXTENSION_CONTROL_BLOCK structure contains the following fields:

cbSize

The size of this structure.

dwVersion

The version information of HTTP_FILTER_REVISION. The HIWORD has the major version number and the LOWORD has the minor version number.

ConnID

A unique number assigned by the HTTP server. It must not be modified.

dwHttpStatusCode

The status of the current transaction when the request is completed. Can be one of the following:

  • HTTP_STATUS_BAD_REQUEST

  • HTTP_STATUS_AUTH_REQUIRED

  • HTTP_STATUS_FORBIDDEN

  • HTTP_STATUS_NOT_FOUND

  • HTTP_STATUS_SERVER_ERROR

  • HTTP_STATUS_NOT_IMPLEMENTED

lpszLogData

Buffer of size HSE_LOG_BUFFER_LEN. Contains a null-terminated log information string, specific to the ISA, of the current transaction. This log information will be entered in the HTTP server log. Maintaining a single log file with both HTTP server and ISA transactions is very useful for administration purposes.

lpszMethod

The method with which the request was made. This is equivalent to the CGI variable REQUEST_METHOD.

lpszQueryString

Null-terminated string containing the query information. This is equivalent to the CGI variable QUERY_STRING.

lpszPathInfo

Null-terminated string containing extra path information given by the client. This is equivalent to the CGI variable PATH_INFO.

lpszPathTranslated

Null-terminated string containing the translated path. This is equivalent to the CGI variable PATH_TRANSLATED.

cbTotalBytes

The total number of bytes to be received from the client. This is equivalent to the CGI variable CONTENT_LENGTH. If this value is 0xffffffff, then there are four gigabytes or more of available data. In this case, CHttpServerContext::ReadClient should be called until no more data is returned.

cbAvailable

The available number of bytes (out of a total of cbTotalBytes) in the buffer pointed to by lpbData. If cbTotalBytes is the same as cbAvailable the variable lpbData will point to a buffer which contains all the data sent by the client. Otherwise cbTotalBytes will contain the total number of bytes of data received. The ISA will then need to use the callback function CHttpServerContext::ReadClient to read the rest of the data (starting from an offset of cbAvailable).

lpbData

Points to a buffer of size cbAvailable that has the data sent by the client.

lpszContentType

Null-terminated string containing the content type of the data sent by the client. This is equivalent to the CGI variable CONTENT_TYPE.

GetServerVariable

This function copies information (including CGI variables) relating to an HTTP connection, or to the server itself, into a buffer. GetServerVariable takes the following parameters:

  • hConn A handle to a connection.

  • lpszVariableName Null-terminated string indicating which variable is being requested. Variable names are:
    Variable Name | Description
    ALL_HTTP | All HTTP headers that were not already parsed into one of the above variables. These variables are of the form HTTP_<header field name>.
    AUTH_PASS | This will retrieve the password corresponding to REMOTE_USER as supplied by the client. It will be a null-terminated string.
    AUTH_TYPE | Contains the type of authentication used. For example, if Basic authentication is used, the string will be "Basic". For Windows NT Challenge-response, it will be "NTLM". Other authentication schemes will have other strings. Because new authentication types can be added to Internet Server, it is not possible to list all possible strings. If the string is empty then no authentication is used.
    CONTENT_LENGTH | The number of bytes which the script can expect to receive from the client.
    CONTENT_TYPE | The content type of the information supplied in the body of a POST request.
    GATEWAY_INTERFACE | The revision of the CGI specification to which this server complies. The current version is CGI/1.1.
    HTTP_ACCEPT Special case HTTP header. Values of the Accept: fields are concatenated, separated by ", ". For example, if the following lines are part of the HTTP header:
    accept: */*; q=0.1
accept: text/html
accept: image/jpeg

    then the HTTP_ACCEPT variable will have a value of:

    */*; q=0.1, text/html, image/jpeg
    PATH_INFO | Additional path information, as given by the client. This comprises the trailing part of the URL after the script name but before the query string (if any).
    PATH_TRANSLATED | This is the value of PATH_INFO, but with any virtual path name expanded into a directory specification.
    QUERY_STRING | The information which follows the ? in the URL that referenced this script.
    REMOTE_ADDR | The IP address of the client.
    REMOTE_HOST | The hostname of the client.
    REMOTE_USER | This contains the username supplied by the client and authenticated by the server.
    REQUEST_METHOD | The HTTP request method.
    SCRIPT_NAME | The name of the script program being executed.
    SERVER_NAME | The server's hostname (or IP address) as it should appear in self-referencing URLs.
    SERVER_PORT | The TCP/IP port on which the request was received.
    SERVER_PROTOCOL | The name and version of the information retrieval protocol relating to this request. Normally HTTP/1.0.
    SERVER_SOFTWARE | The name and version of the web server under which the CGI program is running.

  • lpvBuffer Pointer to buffer to receive the requested information.

  • lpdwSize Pointer to DWORD indicating the number of bytes available in the buffer. On successful completion the DWORD contains the number of bytes transferred into the buffer (including the null terminating byte).

WriteClient

Sends information to the client from the indicated buffer. WriteClient takes the following parameters:

  • ConnID A unique connection number assigned by the HTTP server.

  • Buffer Pointer to the buffer where the data is to be written.

  • lpdwBytes Pointer to the data to be written.

  • dwReserved Reserved for future use.

ReadClient

Reads information from the body of the Web client's HTTP request into the buffer supplied by the caller. ReadClient takes the following parameters:

  • ConnID A unique connection number assigned by the HTTP server.

  • lpvBuffer Pointer to the buffer area to receive the requested information.

  • lpdwSize Pointer to DWORD indicating the number of bytes available in the buffer. On return *lpdwSize will contain the number of bytes actually transferred into the buffer.

ServerSupportFunction

Provide the ISAs with some general-purpose functions as well as functions that are specific to HTTP server implementation. ServerSupportFunction takes the following parameters:

  • hConn A handle to a connection.

  • dwHSERRequest An HTTP Server Extension value. See CHttpServerContext::ServerSupportFunction for a list of possible values and related parameters.

  • lpvBuffer When used with HSE_REQ_SEND_RESPONSE_HEADER, it points to a null-terminated optional status string (i.e., "401 Access Denied"). If this buffer is null, a default response of "200 Ok" will be sent by this function. When used with HSE_REQ_DONE_WITH_SESSION, it points to a DWORD indicating the status code of the request.

  • lpdwSize When used with HSE_REQ_SEND_RESPONSE_HEADER, it points to the size of the buffer lpdwDataType.

  • lpdwDataType A null-terminated string pointing to optional headers or data to be appended and sent with the header. If NULL, the header will be terminated by a “\r\n” pair.

Comments

A server identifies files with the extensions .EXE and .BAT as CGI (Common Gateway Interface) executables. In addition, a server will identify a file with a DLL extension as a script to execute.

When the server loads the DLL, it calls the DLL at the entry point CHttpServer::GetExtensionVersion to get the version number of the HTTP_FILTER_REVISION the ISA is based on and a short text description for server administrators. For every client request, the CHttpServer::HttpExtensionProc entry point is called. The extension receives the commonly-needed information such as the query string, path info, method name, and the translated path.

See Also CHttpServerContext::ReadClient, CHttpServer::GetExtensionVersion, CHttpServer::HttpExtensionProc


FILETIME Structure

The FILETIME structure has the following form:

typedef struct _FILETIME {
    DWORD dwLowDateTime;   /* low 32 bits  */
    DWORD dwHighDateTime;  /* high 32 bits */
} FILETIME, *PFILETIME, *LPFILETIME;

The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.

Members

dwLowDateTime

Specifies the low 32 bits of the file time.

dwHighDateTime

Specifies the high 32 bits of the file time.

See Also CTime::CTime


HSE_VERSION_INFO Structure

The HSE_VERSION_INFO structure has the following form:

typedef struct   _HSE_VERSION_INFO {

    DWORD  dwExtensionVersion;
    CHAR   lpszExtensionDesc[HSE_MAX_EXT_DLL_NAME_LEN];

} HSE_VERSION_INFO, *LPHSE_VERSION_INFO;

This structure is pointed to by the pVer parameter in the CHttpServer::GetExtensionVersion member function. It provides the ISA version number and a text description of the ISA.

Members

dwExtensionVersion

The version number of the ISA.

lpszExtensionDesc

The text description of the ISA. The default implementation provides placeholder text; override CHttpServer::GetExtensionVersion to provide your own description.

See Also CHttpServer::GetExtensionVersion


HTTP_FILTER_AUTHENT Structure

The HTTP_FILTER_AUTHENT structure has the following form:

typedef struct _HTTP_FILTER_AUTHENT{

CHAR*    pszUser;                           //IN/OUT
DWORD    cbUserBuff;                        //IN
CHAR*    pszPassword;                       //IN/OUT
DWORD    cbPasswordBuff;                    //IN
} HTTP_FILTER_AUTHENT, *PHTTP_FILTER_AUTHENT;

This structure is pointed to by the pvNotification in the CHttpFilter::HttpFilterProc when NotificationType is SF_NOTIFY_AUTHENTICATION, which indicates when the server is about to authenticate the client. This structure can be used to implement a different authentication scheme by overriding CHttpFilter::OnAuthentication.

The references to IN or IN/OUT above indicate whether the member applies to messages to the filter (IN) or both to and from the filter (IN/OUT).

Members

pszUser

Pointer to a string containing the username for this request. An empty string indicates an anonymous user.

cbUserBuff

Size of the buffer pointed to by pszUser. This is guaranteed to be at least SF_MAX_USERNAME.

pszPassword

Pointer to a string containing the password for this request.

cbPasswordBuff

Size of the buffer pointed to by pszPassword. This is guaranteed to be at least SF_MAX_PASSWORD.

See Also CHttpFilter::HttpFilterProc, CHttpFilter::OnAuthentication


HTTP_FILTER_CONTEXT Structure

The HTTP_FILTER_CONTEXT structure has the following form:

typedef struct _HTTP_FILTER_CONTEXT
{

DWORD    cbSize;                                  //IN
DWORD    Revision;                                //IN
PVOID    ServerContext;                           //IN
DWORD    ulReserved;                              //IN
BOOL     fIsSecurePort;                           //IN
PVOID    pFilterContext;                      //IN/OUT

BOOL    (WINAPI * GetServerVariable) (
    struct _HTTP_FILTER_CONTEXT *    pfc,
    LPSTR      lpszVariableName,
    LPVOID     lpvBuffer,
    LPDWORD    lpdwSize
    );

BOOL    (WINAPI * AddResponseHeaders) (
    struct _HTTP_FILTER_CONTEXT *    pfc,
    LPSTR    lpszHeaders,
    DWORD    dwReserved
    );

BOOL    (WINAPI * WriteClient)  (
    struct _HTTP_FILTER_CONTEXT *    pfc,
    LPVOID     Buffer,
    LPDWORD    lpdwBytes,
    DWORD      dwReserved
    );

VOID *     (WINAPI * AllocMem) (
    struct _HTTP_FILTER_CONTEXT *    pfc,
    DWORD      cbSize,
    DWORD      dwReserved
    );

BOOL    (WINAPI * ServerSupportFunction) (
    struct _HTTP_FILTER_CONTEXT *    pfc,
    enum SF_REQ_TYPE    sfReq,
    PVOID       pData,
    DWORD       ul1,
    DWORD       ul2
    );

} HTTP_FILTER_CONTEXT, *PHTTP_FILTER_CONTEXT;

The references to IN or IN/OUT above indicate whether the member applies to messages to the filter (IN) or both to and from the filter (IN/OUT).

Members

cbSize

Size of this structure, in bytes.

Revision

Revision level of this structure. Less than or equal to the version of the HTTP_FILTER_REVISION.

ServerContext

Reserved for server use.

ulReserved

Reserved for server use.

fIsSecurePort

TRUE indicates that this event is occurring over a secure port.

pFilterContext

A pointer to be used by the filter for any context information that the filter wants to associate with this request. Any memory associated with this request can be safely freed during the SF_NOTIFY_END_OF_NET_SESSION notification.

GetServerVariable

Pointer to a function to retrieve information about the server and this connection. See CHttpServerContext::GetServerVariable for details. GetServerVariable takes the following parameters:

  • pfc Pointer to a filter context passed to CHttpFilter::HttpFilterProc.

  • lpszVariableName Server variable to retrieve.

  • lpvBuffer Buffer to store value of variable.

  • lpdwSize Size of buffer lpvBuffer.

AddResponseHeaders

Pointer to a function that adds a header to the HTTP response. See the description of HSE_REQ_SEND_RESPONSE_HEADER at CHttpServerContext::ServerSupportFunction for details. AddResponseHeaders takes the following parameters:

  • pfc Pointer to a filter context passed to CHttpFilter::HttpFilterProc.

  • lpszHeaders Pointer string containing headers to add.

  • dwReserved Reserved for future use. Must be 0.

WriteClient

Pointer to a function that sends raw data back to the client. See CHttpFilterContext::WriteClient for details. WriteClient takes the following parameters:

  • pfc Pointer passed to CHttpFilter::HttpFilterProc.

  • Buffer Buffer containing data to send to the client.

  • lpdwBytes Size of the buffer pointed to by Buffer.

  • dwReserved Reserved for future use.

AllocMem

Pointer to a function used to allocate memory. Any memory allocated with this function will automatically be freed when the request is completed. AllocMem takes the following parameters:

  • pfc Pointer passed to CHttpFilter::HttpFilterProc.

  • cbSize Size of the buffer to allocate.

  • dwReserved Reserved for future use.

ServerSupportFunction

Pointer to a function used to extend the ISAPI filter APIs. Parameters, listed below, are specific to the ISA used.

  • pfc Pointer to a function used to extend the ISAPI filter APIs.

  • sfReq Server function notification. Possible values:

    SF_REQ_SEND_RESPONSE_HEADER Sends a complete HTTP server response header including the status, server version, message time and MIME version. Server extensions should append other information at the end, such as Content-type, Content-length, and so forth, followed by an extra '\r\n'.

    SF_REQ_ADD_HEADERS_ON_DENIAL If the server denies the HTTP request, add the specified headers to the server error response. This allows an authentication filter to advertise its services without filtering every request. Generally the headers will be WWW-Authenticate headers with custom authentication schemes, but no restriction is placed on what headers may be specified.

    SF_REQ_SET_NEXT_READ_SIZE Only used by raw data filters that return SF_STATUS_READ_NEXT.

  • pData Pointer to a string. Specific to the ISA. See the table under the Comments section for the appropriate values for each sfReq value.

  • ul1, ul2 Specific to the ISA. See the table under the Comments section for the appropriate values for each sfReq value.

Comments

Below are the corresponding possible values for the ServerSupportFunction parameters:

sfReq | pData | ul1, ul2
SF_REQ_SEND_RESPONSE_HEADER | Zero-terminated string pointing to optional status string (i.e., "401 Access Denied") or NULL for the default response of "200 OK". | Zero-terminated string pointing to optional data to be appended and set with the header. If NULL, the header will be terminated with an empty line.
SF_REQ_ADD_HEADERS_ON_DENIAL | Zero-terminated string pointing to one or more header lines with terminating '\r\n'. |
SF_REQ_SET_NEXT_READ_SIZE |  | Size in bytes for the next read.

See Also CHttpFilter::HttpFilterProc, CHttpFilter::OnLog, CHttpServerContext, CHttpServerContext::GetServerVariable, CHttpServerContext::ServerSupportFunction, CHttpServerContext::WriteClient


HTTP_FILTER_LOG Structure

The HTTP_FILTER_LOG structure has the following form:

typedef struct _HTTP_FILTER_LOG

{

const CHAR *    pszClientHostName;             //IN/OUT
const CHAR *    pszClientUserName;             //IN/OUT
const CHAR *    pszServerName;                 //IN/OUT
const CHAR *    pszOperation;                  //IN/OUT
const CHAR *    pszTarget;                     //IN/OUT
const CHAR *    pszParameters;                 //IN/OUT
DWORD        dwHttpStatus;                     //IN/OUT
DWORD        dwWin32Status;                    //IN/OUT

} HTTP_FILTER_LOG, *PHTTP_FILTER_LOG;

This structure is pointed to by the pvNotification in the CHttpFilter::HttpFilterProc when NotificationType is SF_NOTIFY_LOG, which indicates that the server is about to log information to the server log file. The strings cannot be changed but pointers can be replaced. If the string pointers are changed, the memory they point to must remain valid until the next notification.

The references to IN/OUT above indicate that the member applies to messages to (IN) and from (OUT) the filter.

Members

pszClientHostName

Client's host name.

pszClientUserName

Client's user name.

pszServerName

Name of the server the client connected to.

pszOperation

HTTP command.

pszTarget

Target of the HTTP command.

pszParameters

Parameters passed to the HTTP command.

dwHttpStatus

HTTP return status.

dwWin32Status

Win32 error code.

See Also CHttpFilter::HttpFilterProc, CHttpFilter::OnLog


HTTP_FILTER_PREPROC_HEADERS Structure

The HTTP_FILTER_PREPROC_HEADERS structure has the following form:

typedef struct _HTTP_FILTER_PREPROC_HEADERS

{
BOOL    (WINAPI * GetHeader) (
    struct _HTTP_FILTER_CONTEXT *    pfc,
    LPSTR    lpszName,
    LPVOID    lpvBuffer,
    LPDWORD    lpdwSize
    );
BOOL    (WINAPI * SetHeader) (
    struct _HTTP_FILTER_CONTEXT *    pfc,
    LPSTR    lpszName,
    LPSTR    lpszValue
    );
BOOL    (WINAPI * AddHeader) (
    struct _HTTP_FILTER_CONTEXT *    pfc,
    LPSTR    lpszName,
    LPSTR    lpszValue
    );
DWORD    dwReserved;

} HTTP_FILTER_PREPROC_HEADERS, *PHTTP_FILTER_PREPROC_HEADERS;

This structure is pointed to by the pvNotification in CHttpFilter::HttpFilterProc when NotificationType is SF_NOTIFY_PREPROC_HEADERS, which indicates when the server is about to process the client headers.

Members

GetHeader

Pointer to a function that retrieves the specified header value. Header names should include the trailing colon (“:”). The special values “method”, “url” and “version” can be used to retrieve the individual portions of the request line. GetHeader takes the following parameters:

  • pfc Filter context for this request from the pointer to the filter context passed to the CHttpFilter::HttpFilterProc.

  • lpszName The name of the header to retrieve.

  • lpvBuffer Pointer to a buffer of size lpdwSize where the value of the header will be stored.

  • lpdwSize Size of the buffer pointed to by lpvBuffer.

SetHeader

Pointer to a function used to change or delete the value of a header. SetHeader takes the following parameters:

  • pfc Filter context for this request from the pointer to the filter context passed to the CHttpFilter::HttpFilterProc.

  • lpszName Pointer to the name of the header to change or delete.

  • lpszValue Pointer to the string to change the header to, or a pointer to “\0” to delete the header.

AddHeader

Pointer to a function to add a header. AddHeader takes the following parameters:

  • pfc Filter context for this request from the pointer to the filter context passed to the CHttpFilter::HttpFilterProc.

  • lpszName Pointer to the name of the header to change or delete.

  • lpszValue Pointer to the string to change the header to, or a pointer to ”\0” to delete the header.

See Also CHttpFilter::HttpFilterProc, CHttpFilter::OnPreprocHeaders


HTTP_FILTER_RAW_DATA Structure

The HTTP_FILTER_RAW_DATA structure has the following form:

typedef struct _HTTP_FILTER_RAW_DATA
{
PVOID       pvInData;                              //IN
DWORD       cbInData;                              //IN
DWORD       cbInBuffer;                            //IN
DWORD       dwReserved;                            //IN
} HTTP_FILTER_RAW_DATA, *PHTTP_FILTER_RAW_DATA;

This structure is passed to the SF_NOTIFY_READ_RAW_DATA and SF_NOTIFY_SEND_RAW_DATA notification types for CHttpFilter::HttpFilterProc.

The references to IN above indicate that the message being processed is going to the filter.

Members

pvInData

Pointer to the data buffer (input or output).

cbInData

Amount of data in the buffer pointed to by pvInData.

cbInBuffer

Size of the buffer pointed to by pvInData.

dwReserved

Reserved for future use.

See Also CHttpFilter::HttpFilterProc, CHttpFilter::OnReadRawData, CHttpFilter::OnSendRawData


HTTP_FILTER_URL_MAP Structure

The HTTP_FILTER_URL_MAP structure has the following form:

typedef struct _HTTP_FILTER_URL_MAP

{
const CHAR *    pszURL;                           //IN
CHAR *          pszPhysicalPath;              //IN/OUT
DWORD           cbPathBuff;                       //IN
} HTTP_FILTER_URL_MAP, *PHTTP_FILTER_URL_MAP;

This structure is pointed to by the pvNotification in the CHttpFilter::HttpFilterProc when the NotificationType is SF_NOTIFY_URL_MAP, which indicates when the server is about to map the specified URL to a physical path. Filters can modify the physical path in place.

The references to IN or IN/OUT above indicate whether the member applies to messages to the filter (IN) or to and from the filter (IN/OUT).

Members

pszURL

Pointer to the URL that is being mapped to a physical path.

pszPhysicalPath

Pointer to the buffer where the physical path is stored.

cbPathBuff

Size of the buffer pointed to by pszPhysicalPath.

See Also CHttpFilter::HttpFilterProc, CHttpFilter::OnUrlMap


HTTP_FILTER_VERSION Structure

The HTTP_FILTER_VERSION structure has the following form:

typedef struct _HTTP_FILTER_VERSION

{
DWORD  dwServerFilterVersion;                      //IN
DWORD  dwFilterVersion;                           //OUT
CHAR   lpszFilterDesc[SF_MAX_FILTER_DESC_LEN+1];  //OUT
DWORD  dwFlags;                                   //OUT
} HTTP_FILTER_VERSION, *PHTTP_FILTER_VERSION;

This structure is passed to the application's CHttpFilter::HttpFilterProc entrypoint by the server to associate any context information with the HTTP request.

The references to IN or OUT above indicate whether the member applies to messages to the filter (IN) or from the filter (OUT).

Members

dwServerFilterVersion

Version of the header used by the filter. The version of the current header file is HTTP_FILTER_REVISION.

dwFilterVersion

Version of HTTP_FILTER_REVISION.

lpszFilterDesc

Location to store a short string description of the ISAPI filter application.

dwFlags

Combination of SF_NOTIFY_* flags to specify what events this application needs, and at what priority the filter is loaded. See CHttpFilter::GetFilterVersion and CHttpFilter::HttpFilterProc for lists of valid flags.

See Also CHttpFilter::HttpFilterProc, CHttpFilter::GetFilterVersion


LINGER Structure

The LINGER structure has the following form:

struct linger {
    u_short l_onoff;            // option on/off
    u_short l_linger;           // linger time
};

The LINGER structure is used for manipulating the SO_LINGER and SO_DONTLINGER options of CAsyncSocket::GetSockOpt.

Comments

Setting the SO_DONTLINGER option prevents blocking on member function Close while waiting for unsent data to be sent. Setting this option is equivalent to setting SO_LINGER with l_onoff set to 0.

See Also CAsyncSocket::GetSockOpt, CAsyncSocket::SetSockOpt


LOGBRUSH Structure

The LOGBRUSH structure has the following form:

typedef struct tag LOGBRUSH { /* lb */
   UINT     lbStyle;
   COLORREF lbColor;
   LONG     lbHatch;
} LOGBRUSH;

The LOGBRUSH structure defines the style, color, and pattern of a physical brush. It is used by the Windows CreateBrushIndirect and ExtCreatePen functions.

Members

lbStyle

Specifies the brush style. The lbStyle member must be one of the following styles:

  • BS_DIBPATTERN A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERN, the lbHatch member contains a handle to a packed DIB.

  • BS_DIBPATTERNPT A pattern brush defined by a device-independent bitmap (DIB) specification. If lbStyle is BS_DIBPATTERNPT, the lbHatch member contains a pointer to a packed DIB.

  • BS_HATCHED Hatched brush.

  • BS_HOLLOW Hollow brush.

  • BS_NULL Same as BS_HOLLOW.

  • BS_PATTERN Pattern brush defined by a memory bitmap.

  • BS_SOLID Solid brush.

lbColor

Specifies the color in which the brush is to be drawn. If lbStyle is the BS_HOLLOW or BS_PATTERN style, lbColor is ignored. If lbStyle is BS_DIBPATTERN or BS_DIBPATTERNBT, the low-order word of lbColor specifies whether the bmiColors members of the BITMAPINFO structure contain explicit red, green, blue (RGB) values or indices into the currently realized logical palette. The lbColor member must be one of the following values:

  • DIB_PAL_COLORS The color table consists of an array of 16-bit indices into the currently realized logical palette.

  • DIB_RGB_COLORS The color table contains literal RGB values.

lbHatch

Specifies a hatch style. The meaning depends on the brush style defined by lbStyle. If lbStyle is BS_DIBPATTERN, the lbHatch member contains a handle to a packed DIB. If lbStyle is BS_DIBPATTERNPT, the lbHatch member contains a pointer to a packed DIB. If lbStyle is BS_HATCHED, the lbHatch member specifies the orientation of the lines used to create the hatch. It can be one of the following values:

  • HS_BDIAGONAL A 45-degree upward, left-to-right hatch

  • HS_CROSS Horizontal and vertical crosshatch

  • HS_DIAGCROSS 45-degree crosshatch

  • HS_FDIAGONAL A 45-degree downward, left-to-right hatch

  • HS_HORIZONTAL Horizontal hatch

  • HS_VERTICAL Vertical hatch

    If lbStyle is BS_PATTERN, lbHatch is a handle to the bitmap that defines the pattern. If lbStyle is BS_SOLID or BS_HOLLOW, lbHatch is ignored.

Comments

Although lbColor controls the foreground color of a hatch brush, the CDC::SetBkMode and CDC::SetBkColor functions control the background color.

See Also CDC::GetCharABCWidths


LOGPEN Structure

The LOGPEN structure has the following form:

typedef struct tagLOGPEN {  /* lgpn */
    UINT     lopnStyle;
    POINT    lopnWidth;
    COLORREF lopnColor;
} LOGPEN;

The LOGPEN structure defines the style, width, and color of a pen, a drawing object used to draw lines and borders. The CPen::CreatePenIndirect function uses the LOGPEN structure.

Members

lopnStyle

Specifies the pen type. This member can be one of the following values:

  • PS_SOLID Creates a solid pen.

  • PS_DASH Creates a dashed pen. (Valid only when the pen width is 1.)

  • PS_DOT Creates a dotted pen. (Valid only when the pen width is 1.)

  • PS_DASHDOT Creates a pen with alternating dashes and dots. (Valid only when the pen width is 1.)

  • PS_DASHDOTDOT Creates a pen with alternating dashes and double dots. (Valid only when the pen width is 1.)

  • PS_NULL Creates a null pen.

  • PS_INSIDEFRAME Creates a pen that draws a line inside the frame of closed shapes produced by GDI output functions that specify a bounding rectangle (for example, the Ellipse, Rectangle, RoundRect, Pie, and Chord member functions). When this style is used with GDI output functions that do not specify a bounding rectangle (for example, the LineTo member function), the drawing area of the pen is not limited by a frame.

    If a pen has the PS_INSIDEFRAME style and a color that does not match a color in the logical color table, the pen is drawn with a dithered color. The PS_SOLID pen style cannot be used to create a pen with a dithered color. The PS_INSIDEFRAME style is identical to PS_SOLID if the pen width is less than or equal to 1.

    When the PS_INSIDEFRAME style is used with GDI objects produced by functions other than Ellipse, Rectangle, and RoundRect, the line may not be completely inside the specified frame.

lopnWidth

Specifies the pen width, in logical units. If the lopnWidth member is 0, the pen is 1 pixel wide on raster devices regardless of the current mapping mode.

lopnColor

Specifies the pen color.

Comments

The y value in the POINT structure for the lopnWidth member is not used.

See Also CPen::CreatePenIndirect


MEASUREITEMSTRUCT Structure

The MEASUREITEMSTRUCT data structure has the following form:

typedef struct tagMEASUREITEMSTRUCT {
    UINT   CtlType;
    UINT   CtlID;
    UINT   itemID;
    UINT   itemWidth;
    UINT   itemHeight;
    DWORD  itemData
} MEASUREITEMSTRUCT;

The MEASUREITEMSTRUCT structure informs Windows of the dimensions of an owner-drawn control or menu item. This allows Windows to process user interaction with the control correctly. Failure to fill out the proper members in the MEASUREITEMSTRUCT structure will cause improper operation of the control.

Members

CtlType

Contains the control type. The values for control types are as follows:

  • ODT_COMBOBOX Owner-draw combo box

  • ODT_LISTBOX Owner-draw list box

  • ODT_MENU Owner-draw menu

CtlID

Contains the control ID for a combo box, list box, or button. This member is not used for a menu.

itemID

Contains the menu-item ID for a menu or the list-box-item ID for a variable-height combo box or list box. This member is not used for a fixed-height combo box or list box, or for a button.

itemWidth

Specifies the width of a menu item. The owner of the owner-draw menu item must fill this member before it returns from the message.

itemHeight

Specifies the height of an individual item in a list box or a menu. Before it returns from the message, the owner of the owner-draw combo box, list box, or menu item must fill out this member. The maximum height of a list box item is 255.

itemData

For a combo box or list box, this member contains the value that was passed to the list box by one of the following:

  • CComboBox::AddString

  • CComboBox::InsertString

  • CListBox::AddString

  • CListBox::InsertString

    For a menu, this member contains the value that was passed to the menu by one of the following:

  • CMenu::AppendMenu

  • CMenu::InsertMenu

  • CMenu::ModifyMenu

See Also CWnd::OnMeasureItem


MINMAXINFO Structure

The MINMAXINFO structure has the following form:

typedef struct tagMINMAXINFO {
    POINT ptReserved;
    POINT ptMaxSize;
    POINT ptMaxPosition;
    POINT ptMinTrackSize;
    POINT ptMaxTrackSize;
} MINMAXINFO;

The MINMAXINFO structure contains information about a window's maximized size and position and its minimum and maximum tracking size.

Members

ptReserved

Reserved for internal use.

ptMaxSize

Specifies the maximized width (point.x) and the maximized height (point.y) of the window.

ptMaxPosition

Specifies the position of the left side of the maximized window (point.x) and the position of the top of the maximized window (point.y).

ptMinTrackSize

Specifies the minimum tracking width (point.x) and the minimum tracking height (point.y) of the window.

ptMaxTrackSize

Specifies the maximum tracking width (point.x) and the maximum tracking height (point.y) of the window.

See Also CWnd::OnGetMinMaxInfo


MSG Structure

The MSG structure has the following form:

typedef struct tagMSG {     // msg
    HWND   hwnd;
    UINT   message;
    WPARAM wParam;
    LPARAM lParam;
    DWORD  time;
    POINT  pt;
} MSG;

The MSG structure contains message information from a thread’s message queue.

Members

hwnd

Identifies the window whose window procedure receives the message.

message

Specifies the message number.

wParam

Specifies additional information about the message. The exact meaning depends on the value of the message member.

lParam

Specifies additional information about the message. The exact meaning depends on the value of the message member.

time

Specifies the time at which the message was posted.

pt

Specifies the cursor position, in screen coordinates, when the message was posted.


NCCALCSIZE_PARAMS Structure

The NCCALCSIZE_PARAMS structure has the following form:

typedef struct tagNCCALCSIZE_PARAMS {
    RECT           rgrc[3];
    PWINDOWPOS     lppos;
} NCCALCSIZE_PARAMS;

The NCCALCSIZE_PARAMS structure contains information that an application can use while processing the WM_NCCALCSIZE message to calculate the size, position, and valid contents of the client area of a window.

Members

rgrc

Specifies an array of rectangles. The first contains the new coordinates of a window that has been moved or resized. The second contains the coordinates of the window before it was moved or resized. The third contains the coordinates of the client area of a window before it was moved or resized. If the window is a child window, the coordinates are relative to the client area of the parent window. If the window is a top-level window, the coordinates are relative to the screen.

lppos

Points to a WINDOWPOS structure that contains the size and position values specified in the operation that caused the window to be moved or resized.

See Also CWnd::OnNcCalcSize


PAINTSTRUCT Structure

The PAINTSTRUCT structure has the following form:

typedef struct tagPAINTSTRUCT {
   HDC  hdc;
   BOOL fErase;
   RECT rcPaint;
   BOOL fRestore;
   BOOL fIncUpdate;
   BYTE rgbReserved[16];
} PAINTSTRUCT;

The PAINTSTRUCT structure contains information that can be used to paint the client area of a window.

Members

hdc

Identifies the display context to be used for painting.

fErase

Specifies whether the background needs to be redrawn. It is not 0 if the application should redraw the background. The application is responsible for drawing the background if a Windows window-class is created without a background brush (see the description of the hbrBackground member of the WNDCLASS structure in the Win32 SDK documentation).

rcPaint

Specifies the upper-left and lower-right corners of the rectangle in which the painting is requested.

fRestore

Reserved member. It is used internally by Windows.

fIncUpdate

Reserved member. It is used internally by Windows.

rgbReserved[16]

Reserved member. A reserved block of memory used internally by Windows.

See Also CPaintDC::m_ps


POINT Structure

The POINT data structure has the following form:

typedef struct tagPOINT {
   LONG x;
   LONG y;
} POINT;

The POINT structure defines the x- and y-coordinates of a point.

Members

x

Specifies the x-coordinate of a point.

y

Specifies the y-coordinate of a point.

See Also CPoint


RECT Structure

The RECT data structure has the following form:

typedef struct tagRECT {
   LONG left;
   LONG top;
   LONG right;
   LONG bottom;
} RECT;

The RECT structure defines the coordinates of the upper-left and lower-right corners of a rectangle.

Members

left

Specifies the x-coordinate of the upper-left corner of a rectangle.

top

Specifies the y-coordinate of the upper-left corner of a rectangle.

right

Specifies the x-coordinate of the lower-right corner of a rectangle.

bottom

Specifies the y-coordinate of the lower-right corner of a rectangle.

See Also CRect


RGNDATA Structure

The RGNDATA structure has the following form:

typedef struct _RGNDATA { /* rgnd */
    RGNDATAHEADER rdh;
    char          Buffer[1];
} RGNDATA;

The RGNDATA structure contains a header and an array of rectangles that compose a region. These rectangles, sorted top to bottom left to right, do not overlap.

Members

rdh

Specifies a RGNDATAHEADER structure. (For more information on this structure, see the Win32 SDK documentation.) The members of this structure specify the type of region (whether it is rectangular or trapezoidal), the number of rectangles that make up the region, the size of the buffer that contains the rectangle structures, and so on.

Buffer

Specifies an arbitrary-size buffer that contains the RECT structures that make up the region.

See Also CRgn::CreateFromData, CRgn::GetRegionData


SIZE Structure

The SIZE structure has the following form:

typedef struct tagSIZE {
    int cx;
    int cy;
} SIZE;

The SIZE structure specifies the width and height of a rectangle.

Members

cx

Specifies the x-extent when a function returns.

cy

Specifies the y-extent when a function returns.

Comments

The rectangle dimensions stored in this structure can correspond to viewport extents, window extents, text extents, bitmap dimensions, or the aspect-ratio filter for some extended functions.

See Also CSize


SOCKADDR Structure

The SOCKADDR structure has the following form:

struct sockaddr {
    unsigned short sa_family;
    char           sa_data[14];
};

The SOCKADDR structure is used to store an Internet Protocol (IP) address for a machine participating in a Windows Sockets communication.

Members

sa_family

Socket address family.

sa_data

Maximum size of all of the different socket address structures.

Comments

The Microsoft TCP/IP Sockets Developer’s Kit only supports the Internet address domains. To actually fill in values for each part of an address, you use the SOCKADDR_IN data structure, which is specifically for this address format. The SOCKADDR and the SOCKADDR_IN data structures are the same size. You simply cast to switch between the two structure types. For more information, see Windows Sockets Programming Considerations in the Win32 SDK documentation.

See Also SOCKADDR_IN, CAsyncSocket::Create, CSocket::Create


SOCKADDR_IN Structure

The SOCKADDR_IN structure has the following form:

struct sockaddr_in{
    short            sin_family;
    unsigned short      sin_port;
    struct   in_addr      sin_addr;
    char               sin_zero[8];
};

In the Internet address family, the SOCKADDR_IN structure is used by Windows Sockets to specify a local or remote endpoint address to which to connect a socket. This is the form of the SOCKADDR structure specific to the Internet address family and can be cast to SOCKADDR.

Members

sin_family

Address family (must be AF_INET).

sin_port

IP port.

sin_addr

IP address.

sin_zero

Padding to make structure the same size as SOCKADDR.

Comments

The IP address component of this structure is of type IN_ADDR. The IN_ADDR structure is defined in Windows Sockets header file WINSOCK.H as follows:

struct   in_addr {
    union   {
         struct{
             unsigned  char   s_b1,
                              s_b2,
                              s_b3,
                              s_b4;
        }  S_un_b;
             struct  {
             unsigned  short  s_w1,
                              s_w2;
              }  S_un_w;
               unsigned long  S_addr;
     } S_un;
};

For more information, see Windows Sockets Programming Considerations in the Win32 SDK documentation.

See Also SOCKADDR


SYSTEMTIME Structure

The SYSTEMTIME structure has the following form:

typedef struct _SYSTEMTIME {
    WORD wYear;
    WORD wMonth;
    WORD wDayOfWeek;
    WORD wDay;
    WORD wHour;
    WORD wMinute;
    WORD wSecond;
    WORD wMilliseconds;
} SYSTEMTIME;

The SYSTEMTIME structure represents a date and time using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.

Members

wYear

The current year.

wMonth

The current month; January is 1.

wDayOfWeek

The current day of the week; Sunday is 0, Monday is 1, and so on.

wDay

The current day of the month.

wHour

The current hour.

wMinute

The current minute.

wSecond

The current second.

wMilliseconds

The current millisecond.

See Also CTime::CTime


TEXTMETRIC Structure

The TEXTMETRIC structure has the following form:

typedef struct tagTEXTMETRIC {  /* tm */
    int  tmHeight;
    int  tmAscent;
    int  tmDescent;
    int  tmInternalLeading;
    int  tmExternalLeading;
    int  tmAveCharWidth;
    int  tmMaxCharWidth;
    int  tmWeight;
    BYTE tmItalic;
    BYTE tmUnderlined;
    BYTE tmStruckOut;
    BYTE tmFirstChar;
    BYTE tmLastChar;
    BYTE tmDefaultChar;
    BYTE tmBreakChar;
    BYTE tmPitchAndFamily;
    BYTE tmCharSet;
    int  tmOverhang;
    int  tmDigitizedAspectX;
    int  tmDigitizedAspectY;
} TEXTMETRIC;

The TEXTMETRIC structure contains basic information about a physical font. All sizes are given in logical units; that is, they depend on the current mapping mode of the display context.

For more complete information about this structure, see TEXTMETRIC in the Win32 SDK documentation.

See Also CDC::GetTextMetrics, TEXTMETRIC


WINDOWPLACEMENT Structure

The WINDOWPLACEMENT data structure has the following form:

typedef struct tagWINDOWPLACEMENT {     /* wndpl */
    UINT  length;
    UINT  flags;
    UINT  showCmd;
    POINT ptMinPosition;
    POINT ptMaxPosition;
    RECT  rcNormalPosition;
} WINDOWPLACEMENT;

The WINDOWPLACEMENT structure contains information about the placement of a window on the screen.

Members

length

Specifies the length, in bytes, of the structure.

flags

Specifies flags that control the position of the minimized window and the method by which the window is restored. This member can be one or both of the following flags:

  • WPF_SETMINPOSITION Specifies that the x- and y-positions of the minimized window can be specified. This flag must be specified if the coordinates are set in the ptMinPosition member.

  • WPF_RESTORETOMAXIMIZED Specifies that the restored window will be maximized, regardless of whether it was maximized before it was minimized. This setting is valid only the next time the window is restored. It does not change the default restoration behavior. This flag is valid only when the SW_SHOWMINIMIZED value is specified for the showCmd member.

showCmd

Specifies the current show state of the window. This member can 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 system’s list.

  • SW_RESTORE Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position (same as SW_SHOWNORMAL).

  • SW_SHOW Activates a window and displays it in its current size and position.

  • SW_SHOWMAXIMIZED Activates a window and displays it as a maximized window.

  • SW_SHOWMINIMIZED Activates a window and displays it as an icon.

  • SW_SHOWMINNOACTIVE Displays a window as an icon. The window that is currently active remains active.

  • SW_SHOWNA Displays a 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 a window. If the window is minimized or maximized, Windows restores it to its original size and position (same as SW_RESTORE).

ptMinPosition

Specifies the position of the window’s top-left corner when the window is minimized.

ptMaxPosition

Specifies the position of the window’s top-left corner when the window is maximized.

rcNormalPosition

Specifies the window’s coordinates when the window is in the normal (restored) position.

See Also CWnd::SetWindowPlacement


WINDOWPOS Structure

The WINDOWPOS data structure has the following form:

typedef struct tagWINDOWPOS { /* wp */
    HWND    hwnd;
    HWND    hwndInsertAfter;
    int     x;
    int     y;
    int     cx;
    int     cy;
    UINT    flags;
} WINDOWPOS;

The WINDOWPOS structure contains information about the size and position of a window.

Members

hwnd

Identifies the window.

hwndInsertAfter

Identifies the window behind which this window is placed.

x

Specifies the position of the left edge of the window.

y

Specifies the position of the right edge of the window.

cx

Specifies the window width, in pixels.

cy

Specifies the window height, in pixels.

flags

Specifies window-positioning options. This member can be one of the following values:

  • SWP_DRAWFRAME Draws a frame (defined in the class description for the window) around the window. The window receives a WM_NCCALCSIZE message.

  • SWP_FRAMECHANGED Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.

  • SWP_HIDEWINDOW Hides the window.

  • SWP_NOACTIVATE Does not activate the window.

  • SWP_NOCOPYBITS Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.

  • SWP_NOMOVE Retains current position (ignores the x and y members).

  • SWP_NOOWNERZORDER Does not change the owner window’s position in the Z-order.

  • SWP_NOSIZE Retains current size (ignores the cx and cy members).

  • SWP_NOREDRAW Does not redraw changes.

  • SWP_NOREPOSITION Same as SWP_NOOWNERZORDER.

  • SWP_NOSENDCHANGING Prevents the window from receiving the WM_WINDOWPOSCHANGING message.

  • SWP_NOZORDER Retains current ordering (ignores the hwndInsertAfter member).

  • SWP_SHOWWINDOW Displays the window.

See Also CWnd::OnWindowPosChanging


WSADATA Structure

The WSADATA structure has the following form:

struct WSAData {
    WORD             wVersion;
    WORD             wHighVersion;
    char             szDescription[WSADESCRIPTION_LEN+1];
    char             szSystemStatus[WSASYSSTATUS_LEN+1];
    unsigned short   iMaxSockets;
    unsigned short   iMaxUdpDg;
    char FAR *       lpVendorInfo;
};

The WSADATA structure is used to store Windows Sockets initialization information returned by a call to the AfxSocketInit global function.

Members

wVersion

The version of the Windows Sockets specification that the Windows Sockets DLL expects the caller to use.

wHighVersion

The highest version of the Windows Sockets specification that this DLL can support (also encoded as above). Normally this is the same as wVersion.

szDescription

A null-terminated ASCII string into which the Windows Sockets DLL copies a description of the Windows Sockets implementation, including vendor identification. The text (up to 256 characters in length) can contain any characters, but vendors are cautioned against including control and formatting characters: the most likely use that an application will put this to is to display it (possibly truncated) in a status message.

szSystemStatus

A null-terminated ASCII string into which the Windows Sockets DLL copies relevant status or configuration information. The Windows Sockets DLL should use this field only if the information might be useful to the user or support staff; it should not be considered as an extension of the szDescription field.

iMaxSockets

The maximum number of sockets which a single process can potentially open. A Windows Sockets implementation can provide a global pool of sockets for allocation to any process; alternatively it can allocate per-process resources for sockets. The number can well reflect the way in which the Windows Sockets DLL or the networking software was configured. Application writers can use this number as a crude indication of whether the Windows Sockets implementation is usable by the application. For example, an X Windows server might check iMaxSockets when first started: if it is less than 8, the application would display an error message instructing the user to reconfigure the networking software. (This is a situation in which the szSystemStatus text might be used.) Obviously there is no guarantee that a particular application can actually allocate iMaxSockets sockets, since there can be other Windows Sockets applications in use.

iMaxUdpDg

The size in bytes of the largest User Datagram Protocol (UDP) datagram that can be sent or received by a Windows Sockets application. If the implementation imposes no limit, iMaxUdpDg is zero. In many implementations of Berkeley sockets, there is an implicit limit of 8192 bytes on UDP datagrams (which are fragmented if necessary). A Windows Sockets implementation can impose a limit based, for instance, on the allocation of fragment reassembly buffers. The minimum value of iMaxUdpDg for a compliant Windows Sockets implementation is 512. Note that regardless of the value of iMaxUdpDg, it is inadvisable to attempt to send a broadcast datagram which is larger than the Maximum Transmission Unit (MTU) for the network. (The Windows Sockets API does not provide a mechanism to discover the MTU, but it must be no less than 512 bytes.)

lpVendorInfo

A far pointer to a vendor-specific data structure. The definition of this structure (if supplied) is beyond the scope of the Windows Sockets specification. For more information, see Windows Sockets Programming Considerations in the Win32 SDK documentation.

Note In MFC, the WSADATA structure is returned by the AfxSocketInit function, which you call in your InitInstance function. You can retrieve the structure and store it in your program if you need to use information from it later.

See Also AfxSocketInit


XFORM Structure

The XFORM structure has the following form:

typedef struct  tagXFORM {  /* xfrm */
    FLOAT eM11;
    FLOAT eM12;
    FLOAT eM21;
    FLOAT eM22;
    FLOAT eDx;
    FLOAT eDy;
} XFORM;

Comments

The XFORM structure specifies a world-space to page-space transformation. The eDx and eDy members specify the horizontal and vertical translation components, respectively. The following table shows how the other members are used, depending on the operation:

Operation | eM11 | eM12 | eM21 | eM22
Rotation | Cosine of rotation angle | Sine of rotation angle | Negative sine of rotation angle | Cosine of rotation angle
Scaling | Horizontal scaling component | Nothing | Nothing | Vertical scaling component
Shear | Nothing | Horizontal proportionality constant | Vertical proportionality constant | Nothing
Reflection | Horizontal reflection component | Nothing | Nothing | Vertical reflection component

See Also CRgn::CreateFromData


Styles Used by MFC

The styles described in the following topics are, in most cases, specified with the dwstyle parameter. For further information, refer to the member functions listed in the See Also list for each style.


Button Styles

  • BS_AUTOCHECKBOX Same as a check box, except that a check mark appears in the check box when the user selects the box; the check mark disappears the next time the user selects the box.

  • BS_AUTORADIOBUTTON Same as a radio button, except that when the user selects it, the button automatically highlights itself and removes the selection from any other radio buttons with the same style in the same group.

  • BS_AUTO3STATE Same as a three-state check box, except that the box changes its state when the user selects it.

  • BS_CHECKBOX Creates a small square that has text displayed to its right (unless this style is combined with the BS_LEFTTEXT style).

  • BS_DEFPUSHBUTTON Creates a button that has a heavy black border. The user can select this button by pressing the ENTER key. This style enables the user to quickly select the most likely option (the default option).

  • BS_GROUPBOX Creates a rectangle in which other buttons can be grouped. Any text associated with this style is displayed in the rectangle’s upper-left corner.

  • BS_LEFTTEXT When combined with a radio-button or check-box style, the text appears on the left side of the radio button or check box.

  • BS_OWNERDRAW Creates an owner-drawn button. The framework calls the DrawItem member function when a visual aspect of the button has changed. This style must be set when using the CBitmapButton class.

  • BS_PUSHBUTTON Creates a pushbutton that posts a WM_COMMAND message to the owner window when the user selects the button.

  • BS_RADIOBUTTON Creates a small circle that has text displayed to its right (unless this style is combined with the BS_LEFTTEXT style). Radio buttons are usually used in groups of related but mutually exclusive choices.

  • BS_3STATE Same as a check box, except that the box can be dimmed as well as checked. The dimmed state typically is used to show that a check box has been disabled.

See Also CButton::Create


Combo-Box Styles

  • CBS_AUTOHSCROLL Automatically scrolls the text in the edit control to the right when the user types a character at the end of the line. If this style is not set, only text that fits within the rectangular boundary is allowed.

  • CBS_DROPDOWN Similar to CBS_SIMPLE, except that the list box is not displayed unless the user selects an icon next to the edit control.

  • CBS_DROPDOWNLIST Similar to CBS_DROPDOWN, except that the edit control is replaced by a static-text item that displays the current selection in the list box.

  • CBS_HASSTRINGS An owner-draw combo box contains items consisting of strings. The combo box maintains the memory and pointers for the strings so the application can use the GetText member function to retrieve the text for a particular item.

  • CBS_OEMCONVERT Text entered in the combo-box edit control is converted from the ANSI character set to the OEM character set and then back to ANSI. This ensures proper character conversion when the application calls the AnsiToOem Windows function to convert an ANSI string in the combo box to OEM characters. This style is most useful for combo boxes that contain filenames and applies only to combo boxes created with the CBS_SIMPLE or CBS_DROPDOWN styles.

  • CBS_OWNERDRAWFIXED The owner of the list box is responsible for drawing its contents; the items in the list box are all the same height.

  • CBS_OWNERDRAWVARIABLE The owner of the list box is responsible for drawing its contents; the items in the list box are variable in height.

  • CBS_SIMPLE The list box is displayed at all times. The current selection in the list box is displayed in the edit control.

  • CBS_SORT Automatically sorts strings entered into the list box.

  • CBS_DISABLENOSCROLL The list box shows a disabled vertical scroll bar when the list box does not contain enough items to scroll. Without this style, the scroll bar is hidden when the list box does not contain enough items.

  • CBS_NOINTEGRALHEIGHT Specifies that the size of the combo box is exactly the size specified by the application when it created the combo box. Normally, Windows sizes a combo box so that the combo box does not display partial items.

See Also CComboBox::Create


Edit Styles

  • ES_AUTOHSCROLL Automatically scrolls text to the right by 10 characters when the user types a character at the end of the line. When the user presses the ENTER key, the control scrolls all text back to position 0.

  • ES_AUTOVSCROLL Automatically scrolls text up one page when the user presses ENTER on the last line.

  • ES_CENTER Centers text in a single-line or multiline edit control.

  • ES_LEFT Left-aligns text in a single-line or multiline edit control.

  • ES_LOWERCASE Converts all characters to lowercase as they are typed into the edit control.

  • ES_MULTILINE Designates a multiple-line edit control. (The default is single line.) If the ES_AUTOVSCROLL style is specified, the edit control shows as many lines as possible and scrolls vertically when the user presses the ENTER key. If ES_AUTOVSCROLL is not given, the edit control shows as many lines as possible and beeps if ENTER is pressed when no more lines can be displayed. If the ES_AUTOHSCROLL style is specified, the multiple-line edit control automatically scrolls horizontally when the caret goes past the right edge of the control. To start a new line, the user must press ENTER. If ES_AUTOHSCROLL is not given, the control automatically wraps words to the beginning of the next line when necessary; a new line is also started if ENTER is pressed. The position of the wordwrap is determined by the window size. If the window size changes, the wordwrap position changes and the text is redisplayed. Multiple-line edit controls can have scroll bars. An edit control with scroll bars processes its own scroll-bar messages. Edit controls without scroll bars scroll as described above and process any scroll messages sent by the parent window.

  • ES_NOHIDESEL Normally, an edit control hides the selection when the control loses the input focus and inverts the selection when the control receives the input focus. Specifying ES_NOHIDESEL deletes this default action.

  • ES_OEMCONVERT Text entered in the edit control is converted from the ANSI character set to the OEM character set and then back to ANSI. This ensures proper character conversion when the application calls the AnsiToOem Windows function to convert an ANSI string in the edit control to OEM characters. This style is most useful for edit controls that contain filenames.

  • ES_PASSWORD Displays all characters as an asterisk (*) as they are typed into the edit control. An application can use the SetPasswordChar member function to change the character that is displayed.

  • ES_RIGHT Right-aligns text in a single-line or multiline edit control.

  • ES_UPPERCASE Converts all characters to uppercase as they are typed into the edit control.

  • ES_READONLY Prevents the user from entering or editing text in the edit control.

  • ES_WANTRETURN Specifies that a carriage return be inserted when the user presses the ENTER key while entering text into a multiple-line edit control in a dialog box. Without this style, pressing the ENTER key has the same effect as pressing the dialog box’s default pushbutton. This style has no effect on a single-line edit control.

See Also CEdit::Create


Frame-Window Styles

  • FWS_ADDTOTITLE Specifies information to append to the end of a frame window title. For example, "Microsoft Draw - Drawing in Document1". You can specify the strings displayed in the Advanced Options dialog box in AppWizard. If you need to turn this option off, override the CWnd::PreCreateWindow member function.

  • FWS_PREFIXTITLE Shows the document name before the application name in a frame window title. For example, "Document - WordPad". You can specify the strings displayed in the Advanced Options dialog box in AppWizard. If you need to turn this option off, override the CWnd::PreCreateWindow member function.

  • FWS_SNAPTOBARS Controls sizing of the frame window that encloses a control bar when it is in a floating window rather than docked to a frame window. This style sizes the window to fit the control bar.


List-Box Styles

  • LBS_EXTENDEDSEL The user can select multiple items using the SHIFT key and the mouse or special key combinations.

  • LBS_HASSTRINGS Specifies an owner-draw list box that contains items consisting of strings. The list box maintains the memory and pointers for the strings so the application can use the GetText member function to retrieve the text for a particular item.

  • LBS_MULTICOLUMN Specifies a multicolumn list box that is scrolled horizontally. The SetColumnWidth member function sets the width of the columns.

  • LBS_MULTIPLESEL String selection is toggled each time the user clicks or double-clicks the string. Any number of strings can be selected.

  • LBS_NOINTEGRALHEIGHT The size of the list box is exactly the size specified by the application when it created the list box. Usually, Windows sizes a list box so that the list box does not display partial items.

  • LBS_NOREDRAW List-box display is not updated when changes are made. This style can be changed at any time by sending a WM_SETREDRAW message.

  • LBS_NOTIFY Parent window receives an input message whenever the user clicks or double-clicks a string.

  • LBS_OWNERDRAWFIXED The owner of the list box is responsible for drawing its contents; the items in the list box are the same height.

  • LBS_OWNERDRAWVARIABLE The owner of the list box is responsible for drawing its contents; the items in the list box are variable in height.

  • LBS_SORT Strings in the list box are sorted alphabetically.

  • LBS_STANDARD Strings in the list box are sorted alphabetically, and the parent window receives an input message whenever the user clicks or double-clicks a string. The list box contains borders on all sides.

  • LBS_USETABSTOPS Allows a list box to recognize and expand tab characters when drawing its strings. The default tab positions are 32 dialog units. (A dialog unit is a horizontal or vertical distance. One horizontal dialog unit is equal to one-fourth of the current dialog base width unit. The dialog base units are computed based on the height and width of the current system font. The GetDialogBaseUnits Windows function returns the current dialog base units in pixels.)

  • LBS_WANTKEYBOARDINPUT The owner of the list box receives WM_VKEYTOITEM or WM_CHARTOITEM messages whenever the user presses a key while the list box has input focus. This allows an application to perform special processing on the keyboard input.

  • LBS_DISABLENOSCROLL The list box shows a disabled vertical scroll bar when the list box does not contain enough items to scroll. Without this style, the scroll bar is hidden when the list box does not contain enough items.

See Also CListBox::Create


Message-Box Styles

Message_Box Types

  • MB_ABORTRETRYIGNORE The message box contains three pushbuttons: Abort, Retry, and Ignore.

  • MB_OK The message box contains one pushbutton: OK.

  • MB_OKCANCEL The message box contains two pushbuttons: OK and Cancel.

  • MB_RETRYCANCEL The message box contains two pushbuttons: Retry and Cancel.

  • MB_YESNO The message box contains two pushbuttons: Yes and No.

  • MB_YESNOCANCEL The message box contains three pushbuttons: Yes, No, and Cancel.

Message-Box Modality

  • MB_APPLMODAL The user must respond to the message box before continuing work in the current window. However, the user can move to the windows of other applications and work in those windows. The default is MB_APPLMODAL if neither MB_SYSTEMMODAL nor MB_TASKMODAL is specified.

  • MB_SYSTEMMODAL All applications are suspended until the user responds to the message box. System-modal message boxes are used to notify the user of serious, potentially damaging errors that require immediate attention and should be used sparingly.

  • MB_TASKMODAL Similar to MB_APPLMODAL, but not useful within a Microsoft Foundation class application. This flag is reserved for a calling application or library that does not have a window handle available.

Message-Box Icons

  • MB_ICONEXCLAMATION An exclamation-point icon appears in the message box.

  • MB_ICONINFORMATION An icon consisting of an “i” in a circle appears in the message box.

  • MB_ICONQUESTION A question-mark icon appears in the message box.

  • MB_ICONSTOP A stop-sign icon appears in the message box.

Message-Box Default Buttons

  • MB_DEFBUTTON1 The first button is the default. Note that the first button is always the default unless MB_DEFBUTTON2 or MB_DEFBUTTON3 is specified.

  • MB_DEFBUTTON2 The second button is the default.

  • MB_DEFBUTTON3 The third button is the default.

See Also AfxMessageBox


Scroll-Bar Styles

  • SBS_BOTTOMALIGN Used with the SBS_HORZ style. The bottom edge of the scroll bar is aligned with the bottom edge of the rectangle specified in the Create member function. The scroll bar has the default height for system scroll bars.

  • SBS_HORZ Designates a horizontal scroll bar. If neither the SBS_BOTTOMALIGN nor SBS_TOPALIGN style is specified, the scroll bar has the height, width, and position given in the Create member function.

  • SBS_LEFTALIGN Used with the SBS_VERT style. The left edge of the scroll bar is aligned with the left edge of the rectangle specified in the Create member function. The scroll bar has the default width for system scroll bars.

  • SBS_RIGHTALIGN Used with the SBS_VERT style. The right edge of the scroll bar is aligned with the right edge of the rectangle specified in the Create member function. The scroll bar has the default width for system scroll bars.

  • SBS_SIZEBOX Designates a size box. If neither the SBS_SIZEBOXBOTTOMRIGHTALIGN nor SBS_SIZEBOXTOPLEFTALIGN style is specified, the size box has the height, width, and position given in the Create member function.

  • SBS_SIZEBOXBOTTOMRIGHTALIGN Used with the SBS_SIZEBOX style. The lower-right corner of the size box is aligned with the lower-right corner of the rectangle specified in the Create member function. The size box has the default size for system size boxes.

  • SBS_SIZEBOXTOPLEFTALIGN Used with the SBS_SIZEBOX style. The upper-left corner of the size box is aligned with the upper-left corner of the rectangle specified in the Create member function. The size box has the default size for system size boxes.

  • SBS_TOPALIGN Used with the SBS_HORZ style. The top edge of the scroll bar is aligned with the top edge of the rectangle specified in the Create member function. The scroll bar has the default height for system scroll bars.

  • SBS_VERT Designates a vertical scroll bar. If neither the SBS_RIGHTALIGN nor SBS_LEFTALIGN style is specified, the scroll bar has the height, width, and position given in the Create member function.

See Also CScrollBar::Create


Static Styles

  • SS_BLACKFRAME Specifies a box with a frame drawn with the same color as window frames. The default is black.

  • SS_BLACKRECT Specifies a rectangle filled with the color used to draw window frames. The default is black.

  • SS_CENTER Designates a simple rectangle and displays the given text centered in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next centered line.

  • SS_GRAYFRAME Specifies a box with a frame drawn with the same color as the screen background (desktop). The default is gray.

  • SS_GRAYRECT Specifies a rectangle filled with the color used to fill the screen background. The default is gray.

  • SS_ICON Designates an icon displayed in the dialog box. The given text is the name of an icon (not a filename) defined elsewhere in the resource file. The nWidth and nHeight parameters are ignored; the icon automatically sizes itself.

  • SS_LEFT Designates a simple rectangle and displays the given text flush-left in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next flush-left line.

  • SS_LEFTNOWORDWRAP Designates a simple rectangle and displays the given text flush-left in the rectangle. Tabs are expanded, but words are not wrapped. Text that extends past the end of a line is clipped.

  • SS_NOPREFIX Unless this style is specified, Windows will interpret any ampersand (&) characters in the control’s text to be accelerator prefix characters. In this case, the ampersand (&) is removed and the next character in the string is underlined. If a static control is to contain text where this feature is not wanted, SS_NOPREFIX may be added. This static-control style may be included with any of the defined static controls. You can combine SS_NOPREFIX with other styles by using the bitwise OR operator. This is most often used when filenames or other strings that may contain an ampersand (&) need to be displayed in a static control in a dialog box.

  • SS_RIGHT Designates a simple rectangle and displays the given text flush-right in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next flush-right line.

  • SS_SIMPLE Designates a simple rectangle and displays a single line of text flush-left in the rectangle. The line of text cannot be shortened or altered in any way. (The control’s parent window or dialog box must not process the WM_CTLCOLOR message.)

  • SS_USERITEM Specifies a user-defined item.

  • SS_WHITEFRAME Specifies a box with a frame drawn with the same color as the window background. The default is white.

  • SS_WHITERECT Specifies a rectangle filled with the color used to fill the window background. The default is white.

See Also CStatic::Create


Window Styles

  • WS_BORDER Creates a window that has a border.

  • WS_CAPTION Creates a window that has a title bar (implies the WS_BORDER style). Cannot be used with the WS_DLGFRAME style.

  • WS_CHILD Creates a child window. Cannot be used with the WS_POPUP style.

  • WS_CLIPCHILDREN Excludes the area occupied by child windows when you draw within the parent window. Used when you create the parent window.

  • WS_CLIPSIBLINGS Clips child windows relative to each other; that is, when a particular child window receives a paint message, the WS_CLIPSIBLINGS style clips all other overlapped child windows out of the region of the child window to be updated. (If WS_CLIPSIBLINGS is not given and child windows overlap, when you draw within the client area of a child window, it is possible to draw within the client area of a neighboring child window.) For use with the WS_CHILD style only.

  • WS_DISABLED Creates a window that is initially disabled.

  • WS_DLGFRAME Creates a window with a double border but no title.

  • WS_GROUP Specifies the first control of a group of controls in which the user can move from one control to the next with the arrow keys. All controls defined with the WS_GROUP style FALSE after the first control belong to the same group. The next control with the WS_GROUP style starts the next group (that is, one group ends where the next begins).

  • WS_HSCROLL Creates a window that has a horizontal scroll bar.

  • WS_MAXIMIZE Creates a window of maximum size.

  • WS_MAXIMIZEBOX Creates a window that has a Maximize button.

  • WS_MINIMIZE Creates a window that is initially minimized. For use with the WS_OVERLAPPED style only.

  • WS_MINIMIZEBOX Creates a window that has a Minimize button.

  • WS_OVERLAPPED Creates an overlapped window. An overlapped window usually has a caption and a border.

  • WS_OVERLAPPEDWINDOW Creates an overlapped window with the WS_OVERLAPPED, WS_CAPTION, WS_SYSMENU, WS_THICKFRAME, WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles.

  • WS_POPUP Creates a pop-up window. Cannot be used with the WS_CHILD style.

  • WS_POPUPWINDOW Creates a pop-up window with the WS_BORDER, WS_POPUP, and WS_SYSMENU styles. The WS_CAPTION style must be combined with the WS_POPUPWINDOW style to make the Control menu visible.

  • WS_SYSMENU Creates a window that has a Control-menu box in its title bar. Used only for windows with title bars.

  • WS_TABSTOP Specifies one of any number of controls through which the user can move by using the TAB key. The TAB key moves the user to the next control specified by the WS_TABSTOP style.

  • WS_THICKFRAME Creates a window with a thick frame that can be used to size the window.

  • WS_VISIBLE Creates a window that is initially visible.

  • WS_VSCROLL Creates a window that has a vertical scroll bar.

See Also CWnd::Create, CWnd::CreateEx


Extended Window Styles

  • WS_EX_ACCEPTFILES Specifies that a window created with this style accepts drag-and-drop files.

  • WS_EX_CLIENTEDGE Specifies that a window has a 3D look — that is, a border with a sunken edge.

  • WS_EX_CONTEXTHELP Includes a question mark in the title bar of the window. When the user clicks the question mark, the cursor changes to a question mark with a pointer. If the user then clicks a child window, the child receives a WM_HELP message.

  • WS_EX_CONTROLPARENT Allows the user to navigate among the child windows of the window by using the TAB key.

  • WS_EX_DLGMODALFRAME Designates a window with a double border that may (optionally) be created with a title bar when you specify the WS_CAPTION style flag in the dwStyle parameter.

  • WS_EX_LEFT Gives window generic left-aligned properties. This is the default.

  • WS_EX_LEFTSCROLLBAR Places a vertical scroll bar to the left of the client area.

  • WS_EX_LTRREADING Displays the window text using left-to-right reading order properties. This is the default.

  • WS_EX_MDICHILD Creates an MDI child window.

  • WS_EX_NOPARENTNOTIFY Specifies that a child window created with this style will not send the WM_PARENTNOTIFY message to its parent window when the child window is created or destroyed.

  • WS_EX_OVERLAPPEDWINDOW Combines the WS_EX_CLIENTEDGE and WS_EX_WINDOWEDGE styles

  • WS_EX_PALETTEWINDOW Combines the WS_EX_WINDOWEDGE and WS_EX_TOPMOST styles.

  • WS_EX_RIGHT Gives a window generic right-aligned properties. This depends on the window class.

  • WS_EX_RIGHTSCROLLBAR Places a vertical scroll bar (if present) to the right of the client area. This is the default.

  • WS_EX_RTLREADING Displays the window text using right-to-left reading order properties.

  • WS_EX_STATICEDGE Creates a window with a three-dimensional border style intended to be used for items that do not accept user input.

  • WS_EX_TOOLWINDOW Creates a tool window, which is a window intended to be used as a floating toolbar. A tool window has a title bar that is shorter than a normal title bar, and the window title is drawn using a smaller font. A tool window does not appear in the task bar or in the window that appears when the user presses ALT+TAB.

  • WS_EX_TOPMOST Specifies that a window created with this style should be placed above all nontopmost windows and stay above them even when the window is deactivated. An application can use the SetWindowPos member function to add or remove this attribute.

  • WS_EX_TRANSPARENT Specifies that a window created with this style is to be transparent. That is, any windows that are beneath the window are not obscured by the window. A window created with this style receives WM_PAINT messages only after all sibling windows beneath it have been updated.

  • WS_EX_WINDOWEDGE Specifies that a window has a border with a raised edge.

See Also CWnd::CreateEx


Callback Functions Used by MFC

Three callback functions appear in the Microsoft Foundation Class Library. A description of callback functions that are passed to CDC::EnumObjects, CDC::GrayString, and CDC::SetAbortProc follows this topic. For the general usage of the callback functions, see the Remarks section of these member functions. Note that all callback functions must trap MFC exceptions before returning to Windows, since exceptions cannot be thrown across callback boundaries. For more information about exceptions, see the article Exceptions in Visual C++ Programmer’s Guide.


Callback Function for CDC::EnumObjects

int CALLBACK EXPORT ObjectFunc( LPSTR lpszLogObject, LPSTR* lpData );

Parameters

lpszLogObject

Points to a LOGPEN or LOGBRUSH data structure that contains information about the logical attributes of the object.

lpData

Points to the application-supplied data passed to the EnumObjects function.

Return Value

The callback function returns an int. The value of this return is user-defined. If the callback function returns 0, EnumObjects stops enumeration early.

Remarks

The ObjectFunc name is a placeholder for the application-supplied function name. The actual name must be exported.

See Also CDC::EnumObjects


Callback Function for CDC::GrayString

BOOL CALLBACK EXPORT OutputFunc( HDC hDC, LPARAM lpData, int nCount );

Return Value

The callback function’s return value must be TRUE to indicate success; otherwise it is FALSE.

Parameters

hDC

Identifies a memory device context with a bitmap of at least the width and height specified by nWidth and nHeight to GrayString.

lpData

Points to the character string to be drawn.

nCount

Specifies the number of characters to output.

Remarks

OutputFunc is a placeholder for the application-supplied callback function name. The callback function (OutputFunc) must draw an image relative to the coordinates (0,0) rather than (x, y).

See Also CDC::GrayString


Callback Function for CDC::SetAbortProc

BOOL CALLBACK EXPORT AbortFunc( HDC hPr, int code );

Return Value

The return value of the abort-handler function is nonzero if the print job is to continue, and 0 if it is canceled.

Parameters

hPr

Identifies the device context.

code

Specifies whether an error has occurred. It is 0 if no error has occurred. It is SP_OUTOFDISK if the Print Manager is currently out of disk space and more disk space will become available if the application waits. If code is SP_OUTOFDISK, the application does not have to abort the print job. If it does not, it must yield to the Print Manager by calling the PeekMessage or GetMessage Windows function.

Remarks

The name AbortFunc is a placeholder for the application-supplied function name. The actual name must be exported as described in the Remarks section of CDC::SetAbortProc.

See Also CDC::SetAbortProc


Message Maps

This section of the reference lists all message mapping macros and all CWnd message-map entries along with the corresponding member function prototypes:

Category | Description
WM_COMMAND Message Handler | Handles WM_COMMAND messages generated by user menu selections or menu access keys.
Child Window Notification Message Handlers | Handle notification messages from child windows.
WM_ Message Handlers | Handle WM_ messages, such as WM_PAINT.
User-Defined Message Handlers | Handle user-defined messages.

(For an explanation of the terminology and conventions used in this reference, see How to Use the Message Map Cross-Reference.)

Since Windows is a message-oriented operating system, a large portion of programming for the Windows environment involves message handling. Each time an event such as a keystroke or mouse click occurs, a message is sent to the application, which must then handle the event.

The Microsoft Foundation Class Library offers a programming model optimized for message-based programming. In this model, “message maps” are used to designate which functions will handle various messages for a particular class. Message maps contain one or more macros that specify which messages will be handled by which functions. For example, a message map containing an ON_COMMAND macro might look something like this:

BEGIN_MESSAGE_MAP( CMyDoc, CDocument )
    //{{AFX_MSG_MAP( CMyDoc )
    ON_COMMAND( ID_MYCMD, OnMyCommand )
    // ... More entries to handle additional commands
    //}}AFX_MSG_MAP
END_MESSAGE_MAP( )

The ON_COMMAND macro is used to handle command messages generated by menus, buttons, and accelerator keys. Macros are available to map the following:

Windows Messages

  • Control notifications

  • User-defined messages

Command Messages

  • Registered user-defined messages

  • User-interface update messages

Ranges of Messages

  • Commands

  • Update handler messages

  • Control notifications

Although message-map macros are important, you generally won’t have to use them directly. This is because ClassWizard automatically creates message-map entries in your source files when you use it to associate message-handling functions with messages. Any time you want to edit or add a message-map entry, you can use ClassWizard.

Note ClassWizard does not support message-map ranges. You must write these message-map entries yourself.

However, message maps are an important part of the Microsoft Foundation Class Library. You should understand what they do, and documentation is provided for them.


Message Map Macros

To support message maps, MFC supplies the following macros:

Message-Map Declaration and Demarcation Macros

DECLARE_MESSAGE_MAP | Declares that a message map will be used in a class to map messages to functions (must be used in the class declaration).
BEGIN_MESSAGE_MAP | Begins the definition of a message map (must be used in the class implementation).
END_MESSAGE_MAP | Ends the definition of a message map (must be used in the class implementation).

Message-Mapping Macros

ON_COMMAND | Indicates which function will handle a specified command message.
ON_CONTROL | Indicates which function will handle a specified control-notification message.
ON_MESSAGE | Indicates which function will handle a user-defined message.
ON_OLECMD | Indicates which function will handle a menu command from a DocObject or its container.
ON_REGISTERED_MESSAGE | Indicates which function will handle a registered user-defined message.
ON_REGISTERED_THREAD_MESSAGE | Indicates which function will handle a registered user-defined message when you have a CWinThread class.
ON_THREAD_MESSAGE | Indicates which function will handle a user-defined message when you have a CWinThread class.
ON_UPDATE_COMMAND_UI | Indicates which function will handle a specified user-interface update command message.

Message-Map Range Macros

ON_COMMAND_RANGE | Indicates which function will handle the range of command IDs specified in the first two parameters to the macro.
ON_UPDATE_COMMAND_UI_RANGE | Indicates which update handler will handle the range of command IDs specified in the first two parameters to the macro.
ON_CONTROL_RANGE | Indicates which function will handle notifications from the range of control IDs specified in the second and third parameters to the macro. The first parameter is a control-notification message, such as BN_CLICKED.

For more information on message maps, the message-map declaration and demarcation macros, and the message-mapping macros, see Message Maps and Message Handling and Mapping Topics. For more information about message-map ranges, see Handlers for Message-Map Ranges. For more information on how to use ClassWizard, see Using ClassWizard. Except for the topic Message Maps, these references are in the Visual C++ Programmer's Guide.


How to Use the Message-Map Cross-Reference

In entries labeled <memberFxn>, write your own member function for a derived CWnd class. Give your function any name you like. Other functions, such as OnActivate, are member functions of class CWnd. If called, they pass the message to the DefWindowProc Windows function. To process Windows notification messages, override the corresponding CWnd function in your derived class. Your function should call the overridden function in your base class to let the base class and Windows respond to the message.

In all cases, put the function prototype in the CWnd-derived class header, and code the message map entry as shown.

The following terms are used:

Term | Definition
id | Any user-defined menu item ID (WM_COMMAND messages) or control ID (child window notification messages).
“message” and “wNotifyCode” | Windows message IDs as defined in WINDOWS.H.
nMessageVariable | Name of a variable that contains the return value from the RegisterWindowMessage Windows function. It must be declared NEAR.


WM_COMMAND Message Handler

Map Entry | Function Prototype
ON_COMMAND(<id>, <memberFxn>) | afx_msg void memberFxn( );


Child Window Notification Message Handlers

There are five categories of child window notification messages:

Category | Description
Generic Control Handler | Handler for generic control notification codes.
User Button Handlers | Handlers for user button notification codes.
Combo Box Handlers | Handlers for combo box notification codes.
Edit Control Handlers | Handlers for edit control notification codes.
List Box Handlers | Handlers for list box notification codes.


Generic Control Handler

Map Entry | Function Prototype
ON_CONTROL( <wNotifyCode>, <id>, <memberFxn> ) | afx_msg void memberFxn( );


User Button Handlers

Map Entry | Function Prototype
ON_BN_CLICKED( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_BN_DISABLE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_BN_DOUBLECLICKED( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_BN_HILITE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_BN_PAINT( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_BN_UNHILITE( <id>, <memberFxn> ) | afx_msg void memberFxn( );


Combo Box Handlers

Map Entry | Function Prototype
ON_CBN_CLOSEUP( <id>, <memberFxn> ) | afx_msg void memberFxn( )
ON_CBN_DBLCLK( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_DROPDOWN( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_EDITCHANGE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_EDITUPDATE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_ERRSPACE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_KILLFOCUS( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_SELCHANGE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_SELENDCANCEL( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_SELENDOK( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_CBN_SETFOCUS( <id>, <memberFxn> ) | afx_msg void memberFxn( );


Edit Control Handlers

Map Entry | Function Prototype
ON_EN_CHANGE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_EN_ERRSPACE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_EN_HSCROLL( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_EN_KILLFOCUS( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_EN_MAXTEXT( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_EN_SETFOCUS( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_EN_UPDATE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_EN_VSCROLL( <id>, <memberFxn> ) | afx_msg void memberFxn( );


List Box Handlers

Map Entry | Function Prototype
ON_LBN_DBLCLK( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_LBN_ERRSPACE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_LBN_KILLFOCUS( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_LBN_SELCHANGE( <id>, <memberFxn> ) | afx_msg void memberFxn( );
ON_LBN_SETFOCUS( <id>, <memberFxn> ) | afx_msg void memberFxn( );


Handlers for WM_ Messages

Topic | Map Entries
A - C | ON_WM_ACTIVATE through ON_WM_CTLCOLOR
D - E | ON_WM_DEADCHAR through ON_WM_ERASEBKGND
F - K | ON_WM_FONTCHANGE through ON_WM_KILLFOCUS
L - M | ON_WM_LBUTTONDBLCLK through ON_WM_MOVING
N - O | ON_WM_NCACTIVATE through ON_WM_NCRBUTTONUP
P - R | ON_WM_PAINT through ON_WM_RENDERFORMAT
S | ON_WM_SETCURSOR through ON_WM_SYSKEYUP
T - Z | ON_WM_TIMECHANGE through ON_WM_WININICHANGE


WM_ Message Handlers: A - C

Map Entry | Function Prototype
ON_WM_ACTIVATE( ) | afx_msg void OnActivate( UINT, CWnd*, BOOL );
ON_WM_ACTIVATEAPP( ) | afx_msg void OnActivateApp( BOOL, HANDLE );
ON_WM_ASKCBFORMATNAME( ) | afx_msg void OnAskCbFormatName( UINT, LPSTR );
ON_WM_CANCELMODE( ) | afx_msg void OnCancelMode( );
ON_WM_CAPTURECHANGED( ) | afx_msg void OnCaptureChanged( CWnd* );
ON_WM_CHANGECBCHAIN( ) | afx_msg void OnChangeCbChain( HWND, HWND );
ON_WM_CHAR( ) | afx_msg void OnChar( UINT, UINT, UINT );
ON_WM_CHARTOITEM( ) | afx_msg int OnCharToItem( UINT, CWnd*, UINT );
ON_WM_CHILDACTIVATE( ) | afx_msg void OnChildActivate( );
ON_WM_CLOSE( ) | afx_msg void OnClose( );
ON_WM_COMPACTING( ) | afx_msg void OnCompacting( UINT );
ON_WM_COMPAREITEM( ) | afx_msg int OnCompareItem( LPCOMPAREITEMSTRUCT );
ON_WM_CONTEXTMENU( ) | afx_msg void OnContextMenu( CWnd*, CPoint );
ON_WM_COPYDATA( ) | afx_msg BOOL OnCopyData( CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct );
ON_WM_CREATE( ) | afx_msg int OnCreate( LPCREATESTRUCT );
ON_WM_CTLCOLOR( ) | afx_msg HBRUSH OnCtlColor( CDC*, CWnd*, UINT );


WM_ Message Handlers: D - E

Map Entry | Function Prototype
ON_WM_DEADCHAR( ) | afx_msg void OnDeadChar( UINT, UINT, UINT );
ON_WM_DELETEITEM( ) | afx_msg void OnDeleteItem( LPDELETEITEMSTRUCT );
ON_WM_DESTROY( ) | afx_msg void OnDestroy( );
ON_WM_DESTROYCLIPBOARD( ) | afx_msg void OnDestroyClipboard( );
ON_WM_DEVICECHANGE( ) | afx_msg void OnDeviceChange( UINT, DWORD );
ON_WM_DEVMODECHANGE( ) | afx_msg void OnDevModeChange( LPSTR );
ON_WM_DRAWCLIPBOARD( ) | afx_msg void OnDrawClipboard( );
ON_WM_DRAWITEM( ) | afx_msg void OnDrawItem( LPDRAWITEMSTRUCT );
ON_WM_DROPFILES( ) | afx_msg void OnDropFiles( HDROP );
ON_WM_ENABLE( ) | afx_msg void OnEnable( BOOL );
ON_WM_ENDSESSION( ) | afx_msg void OnEndSession( BOOL );
ON_WM_ENTERIDLE( ) | afx_msg void OnEnterIdle( UINT, CWnd* );
ON_WM_ERASEBKGND( ) | afx_msg BOOL OnEraseBkgnd( CDC * );


WM_ Message Handlers: F - K

Map Entry | Function Prototype
ON_WM_FONTCHANGE( ) | afx_msg void OnFontChange( );
ON_WM_GETDLGCODE( ) | afx_msg UINT OnGetDlgCode( );
ON_WM_GETMINMAXINFO( ) | afx_msg void OnGetMinMaxInfo( LPPOINT );
ON_WM_HELPINFO( ) | afx_msg BOOL OnHelpInfo( HELPINFO* );
ON_WM_HSCROLL( ) | afx_msg void OnHScroll( UINT, UINT, CWnd* );
ON_WM_HSCROLLCLIPBOARD( ) | afx_msg void OnHScrollClipboard CWnd*, UINT, UINT );
ON_WM_ICONERASEBKGND( ) | afx_msg void OnIconEraseBkgnd( CDC * );
ON_WM_INITMENU( ) | afx_msg void OnInitMenu( CMenu * );
ON_WM_INITMENUPOPUP( ) | afx_msg void OnInitMenuPopup( CMenu *, UINT, BOOL );
ON_WM_KEYDOWN( ) | afx_msg void OnKeyDown( UINT, UINT, UINT );
ON_WM_KEYUP( ) | afx_msg void OnKeyUp( UINT, UINT, UINT );
ON_WM_KILLFOCUS( ) | afx_msg void OnKillFocus( CWnd* );


WM_ Message Handlers: L - M

Map Entry | Function Prototype
ON_WM_LBUTTONDBLCLK( ) | afx_msg void OnLButtonDblClk( UINT, CPoint );
ON_WM_LBUTTONDOWN( ) | afx_msg void OnLButtonDown( UINT, CPoint );
ON_WM_LBUTTONUP( ) | afx_msg void OnLButtonUp( UINT, CPoint );
ON_WM_MBUTTONDBLCLK( ) | afx_msg void OnMButtonDblClk( UINT, CPoint );
ON_WM_MBUTTONDOWN( ) | afx_msg void OnMButtonDown( UINT, CPoint );
ON_WM_MBUTTONUP( ) | afx_msg void OnMButtonUp( UINT, CPoint );
ON_WM_MDIACTIVATE( ) | afx_msg void OnMDIActivate( BOOL, CWnd*, CWnd* );
ON_WM_MEASUREITEM( ) | afx_msg void OnMeasureItem( LPMEASUREITEMSTRUCT );
ON_WM_MENUCHAR( ) | afx_msg LONG OnMenuChar( UINT, UINT, CMenu * );
ON_WM_MENUSELECT( ) | afx_msg void OnMenuSelect( UINT, UINT, HMENU );
ON_WM_MOUSEACTIVATE( ) | afx_msg int OnMouseActivate( CWnd*, UINT, UINT );
ON_WM_MOUSEMOVE( ) | afx_msg void OnMouseMove( UINT, CPoint );
ON_WM_MOUSEWHEEL( ) | afx_msg BOOL OnMouseWheel( UINT, short, CPoint );
ON_WM_MOVE( ) | afx_msg void OnMove( int, int );
ON_WM_MOVING( ) | afx_msg void OnMoving( UINT, LPRECT );


WM_ Message Handlers: N - O

Map Entry | Function Prototype
ON_WM_NCACTIVATE( ) | afx_msg BOOL OnNcActivate( BOOL );
ON_WM_NCCALCSIZE( ) | afx_msg void OnNcCalcSize( BOOL, NCCALCSIZE_PARAMS FAR* );
ON_WM_NCCREATE( ) | afx_msg BOOL OnNcCreate( LPCREATESTRUCT );
ON_WM_NCDESTROY( ) | afx_msg void OnNcDestroy( );
ON_WM_NCHITTEST( ) | afx_msg UINT OnNcHitTest( CPoint );
ON_WM_NCLBUTTONDBLCLK( ) | afx_msg void OnNcLButtonDblClk( UINT, CPoint );
ON_WM_NCLBUTTONDOWN( ) | afx_msg void OnNcLButtonDown( UINT, CPoint );
ON_WM_NCLBUTTONUP( ) | afx_msg void OnNcLButtonUp( UINT, CPoint );
ON_WM_NCMBUTTONDBLCLK( ) | afx_msg void OnNcMButtonDblClk( UINT, CPoint );
ON_WM_NCMBUTTONDOWN( ) | afx_msg void OnNcMButtonDown( UINT, CPoint );
ON_WM_NCMBUTTONUP( ) | afx_msg void OnNcMButtonUp( UINT, CPoint );
ON_WM_NCMOUSEMOVE( ) | afx_msg void OnNcMouseMove( UINT, CPoint );
ON_WM_NCPAINT( ) | afx_msg void OnNcPaint( );
ON_WM_NCRBUTTONDBLCLK( ) | afx_msg void OnNcRButtonDblClk( UINT, CPoint );
ON_WM_NCRBUTTONDOWN( ) | afx_msg void OnNcRButtonDown( UINT, CPoint );
ON_WM_NCRBUTTONUP( ) | afx_msg void OnNcRButtonUp( UINT, CPoint );


WM_ Messages: P - R

Map Entry | Function Prototype
ON_WM_PAINT( ) | afx_msg void OnPaint( );
ON_WM_PAINTCLIPBOARD( ) | afx_msg void OnPaintClipboard( CWnd*, HANDLE );
ON_WM_PALETTECHANGED( ) | afx_msg void OnPaletteChanged( CWnd* );
ON_WM_PALETTEISCHANGING( ) | afx_msg void OnPaletteIsChanging( CWnd* );
ON_WM_PARENTNOTIFY( ) | afx_msg void OnParentNotify( UINT, LONG );
ON_WM_QUERYDRAGICON( ) | afx_msg HCURSOR OnQueryDragIcon( );
ON_WM_QUERYENDSESSION( ) | afx_msg BOOL OnQueryEndSession( );
ON_WM_QUERYNEWPALETTE( ) | afx_msg BOOL OnQueryNewPalette( );
ON_WM_QUERYOPEN( ) | afx_msg BOOL OnQueryOpen( );
ON_WM_RBUTTONDBLCLK( ) | afx_msg void OnRButtonDblClk( UINT, CPoint );
ON_WM_RBUTTONDOWN( ) | afx_msg void OnRButtonDown( UINT, CPoint );
ON_WM_RBUTTONUP( ) | afx_msg void OnRButtonUp( UINT, CPoint );
ON_WM_RENDERALLFORMATS( ) | afx_msg void OnRenderAllFormats( );
ON_WM_RENDERFORMAT( ) | afx_msg void OnRenderFormat( UINT );


WM_ Messages: S

Map Entry | Function Prototype
ON_WM_SETCURSOR( ) | afx_msg BOOL OnSetCursor( CWnd*, UINT, UINT );
ON_WM_SETFOCUS( ) | afx_msg void OnSetFocus( CWnd* );
ON_WM_SHOWWINDOW( ) | afx_msg void OnShowWindow( BOOL, UINT );
ON_WM_SIZE( ) | afx_msg void OnSize( UINT, int, int );
ON_WM_SIZECLIPBOARD( ) | afx_msg void OnSizeClipboard( CWnd*, HANDLE );
ON_WM_SIZING( ) | afx_msg void OnSizing( UINT, LPRECT );
ON_WM_SPOOLERSTATUS( ) | afx_msg void OnSpoolerStatus( UINT, UINT );
ON_WM_STYLECHANGED( ) | afx_msg void OnStyleChanged( int, LPSTYLESTRUCT );
ON_WM_STYLECHANGING( ) | afx_msg void OnStyleChanging( int, LPSTYLESTRUCT );
ON_WM_SYSCHAR( ) | afx_msg void OnSysChar( UINT, UINT, UINT );
ON_WM_SYSCOLORCHANGE( ) | afx_msg void OnSysColorChange( );
ON_WM_SYSCOMMAND( ) | afx_msg void OnSysCommand( UINT, LONG );
ON_WM_SYSDEADCHAR( ) | afx_msg void OnSysDeadChar( UINT, UINT, UINT );
ON_WM_SYSKEYDOWN( ) | afx_msg void OnSysKeyDown( UINT, UINT, UINT );
ON_WM_SYSKEYUP( ) | afx_msg void OnSysKeyUp( UINT, UINT, UINT );


WM_ Messages: T - Z

Map Entry | Function Prototype
ON_WM_TCARD( ) | afx_msg void OnTCard( UINT, DWORD );
ON_WM_TIMECHANGE( ) | afx_msg void OnTimeChange( );
ON_WM_TIMER( ) | afx_msg void OnTimer( UINT );
ON_WM_VKEYTOITEM( ) | afx_msg int OnVKeyToItem( UINT, CWnd*, UINT );
ON_WM_VSCROLL( ) | afx_msg void OnVScroll( UINT, UINT, CWnd* );
ON_WM_VSCROLLCLIPBOARD( ) | afx_msg void OnVScrollClipboard( CWnd*, UINT, UINT );
ON_WM_WINDOWPOSCHANGED( ) | afx_msg void OnWindowPosChanged( WINDOWPOS* lpwndpos );
ON_WM_WINDOWPOSCHANGING( ) | afx_msg void OnWindowPosChanging( WINDOWPOS* lpwndpos );
ON_WM_WININICHANGE( ) | afx_msg void OnWinIniChange( LPSTR );


User-Defined Handlers

Map Entry | Function Prototype
ON_MESSAGE( <message>, <memberFxn> ) | afx_msg LRESULT memberFxn(WPARAM, LPARAM);
ON_REGISTERED_MESSAGE( <nMessageVariable>, <memberFxn> ) | afx_msg LRESULT memberFxn(WPARAM, LPARAM);
ON_THREAD_MESSAGE( <message>, <memberFxn> ) | afx_msg void memberFxn( UINT, LONG );
ON_REGISTERED_THREAD_MESSAGE( <nMessageVariable>, <memberFxn> ) | afx_msg void memberFxn( UINT, LONG );


Obsolete MFC Functions

The following functions are not implemented in MFC version 4.x.

  • CDatabase::InWaitForDataSource

  • CDatabase::OnWaitForDataSource

  • CDatabase::SetSynchronousMode

  • CRecordset::OnWaitForDataSource

  • CTabCtrl::GetBkColor

  • CTabCtrl::SetBkColor

  • CWinApp::InitApplication

  • CWnd::GetSuperWndProcAddr


CDatabase::InWaitForDataSource

Remarks

In MFC 4.2, CDatabase::InWaitForDataSource became obsolete. The MFC ODBC classes now use only synchronous processing. To start an asychronous operation, you must directly call the ODBC API function SQLSetConnectOption. For more information, see the topic "Executing Functions Asynchronously" in the ODBC SDK Programmer's Guide.


CDatabase::OnWaitForDataSource

Remarks

In MFC 4.2, CDatabase::OnWaitForDataSource became obsolete. The MFC ODBC classes now use only synchronous processing. To start an asychronous operation, you must directly call the ODBC API function SQLSetConnectOption. For more information, see the topic "Executing Functions Asynchronously" in the ODBC SDK Programmer's Guide.


CDatabase::SetSynchronousMode

Remarks

In MFC 4.2, CDatabase::SetSynchronousMode became obsolete. The MFC ODBC classes now use only synchronous processing. To start an asychronous operation, you must directly call the ODBC API function SQLSetConnectOption. For more information, see the topic "Executing Functions Asynchronously" in the ODBC SDK Programmer's Guide.

Note Although SetSynchronousMode is obsolete, your code will still compile if you use this member function. SetSynchronousMode will simply generate a TRACE message that it is doing nothing.


CRecordset::OnWaitForDataSource

Remarks

In MFC 4.2, CRecordset::OnWaitForDataSource became obsolete. The MFC ODBC classes now use only synchronous processing. To start an asychronous operation, you must directly call the ODBC API function SQLSetConnectOption. For more information, see the topic "Executing Functions Asynchronously" in the ODBC SDK Programmer's Guide.


CTabCtrl::GetBkColor

Remarks

The GetBkColor and SetBkColor member functions are not valid for class CTabCtrl. These member functions are not implemented in MFC because the underlying Windows 95 TCM_SETCOLOR message was not implemented.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also COLORREF in the Win32 Programmer’s Reference


CTabCtrl::SetBkColor

Remarks

The SetBkColor and GetBkColor member functions are not valid for class CTabCtrl. These member functions are not implemented in MFC because the underlying Windows 95 TCM_SETCOLOR message was not implemented.

CTabCtrl Overview | Class Members | Hierarchy Chart

See Also COLORREF in the Win32 Programmer’s Reference


CWinApp::InitApplication

Remarks

The CWinApp::InitApplication member function is obsolete in MFC. An initialization that you would have done in InitApplication should be moved to InitInstance. If you override CWinApp::InitApplication, and you do not call the base class function, you will leak the CDocTemplate objects that were added through CWinApp::AddDocTemplate.

CWinApp Overview | Class Members | Hierarchy Chart

See Also CWinApp::InitInstance


CWnd::GetSuperWndProcAddr

Remarks

This function is obsolete. You will not need to override this function because the default implementation in CWnd now stores this pointer in all CWnd objects.


MFC Technical Notes

A technical note is a document written for programmers by programmers.

Each technical note describes a problem or feature that is beyond the scope of the printed MFC documentation. The technical notes supplied reflect requests for information from users, as well as specialized information that the MFC developers anticipate advanced users will want.

Technical notes have been organized by number and by category.


Technical Notes by Number

The technical notes below are listed numerically, with the most recently written technical note first. For a listing by category, see Technical Notes by Category.

Number | Title
71 | TN071: MFC IOleCommandTarget Implementation
70 | TN070: MFC Window Class Names
69 | Processing HTML Forms Using Internet Server Extension DLLs and Command Handlers
68 | Performing Transactions with the Microsoft Access 7 ODBC Driver
67 | Database Access from an ISAPI Server Extension
66 | Common MFC 3.x to 4.0 Porting Issues
65 | Dual-Interface Support for OLE Automation Servers
64 | Apartment-Model Threading in OLE Controls
63 | Debugging Internet Extension DLLs
62 | Message Reflection for Windows Controls
61 | ON_NOTIFY and WM_NOTIFY Messages
60 | Windows Common Controls
59 | Using MFC MBCS/Unicode Conversion Macros
58 | MFC Module State Implementation
57 | Localization of MFC Components
56 | Installation of MFC Components
55 | Migrating MFC ODBC Database Class Applications to MFC DAO Classes
54 | Calling DAO Directly While Using MFC DAO Classes
53 | Writing Custom DFX Routines for DAO Database Classes
52 | Writing Windows 95 Applications with MFC 3.1
51 | Using CTL3D Now and in the Future
50 | MFC/OLE Common Dialogs (MFCUIx32)
49 | MFC/OLE MBCS to Unicode Translation Layer (MFCANS32)
48 | Writing ODBC Setup and Administration Programs for MFC Database Applications
47 | Relaxing Database Transaction Requirements
46 | Commenting Conventions for the MFC Classes
45 | MFC/Database Support for Long Varchar/Varbinary
44 | MFC Support for DBCS
43 | RFX Routines
42 | ODBC Driver Developer Recommendations
41 | MFC/OLE1 Migration to MFC/OLE2
40 | MFC/OLE In-Place Resizing and Zooming
39 | MFC/OLE Automation Implementation
38 | MFC/OLE IUnknown Implementation
37 | Multithreaded MFC 2.1 Applications
36 | Using CFormView with AppWizard and ClassWizard
35 | Using Multiple Resource Files and Header Files with Visual C++
34 | Writing a Windows 3.0 Compatible MFC Application
33 | DLL Version of MFC
32 | MFC Exception Mechanism
31 | Control Bars
30 | Customizing Printing and Print Preview
29 | Splitter Windows
28 | Context-Sensitive Help Support
27 | Emulation Support for Visual Basic Custom Controls
26 | DDX and DDV Routines
25 | Document, View, and Frame Creation
24 | MFC-Defined Messages and Resources
23 | Standard MFC Resources
22 | Standard Commands Implementation
21 | Command and Message Routing
20 | ID Naming and Numbering Conventions
19 | Updating existing MFC Applications to MFC 3.0
18 | Migrating OLE Applications From MFC 1.0 to MFC 2.0
17 | Destroying Window Objects
16 | Using C++ Multiple Inheritance with MFC
15 | Windows for Pen
14 | Custom Controls
12 | Using Windows 3.1 Robustness Features
11 | Using MFC as Part of a DLL
8 | MFC OLE Support
7 | Debugging Trace Options
6 | Message Maps
4 | C++ Template Tool
3 | Mapping of Windows Handles to Objects
2 | Persistent Object Data Format
1 | Window Class Registration

Technical notes 1 to 17 are general topics that apply to MFC 1.0 and 2.0.

Technical notes 18 and 19 focus on migration of applications from MFC 1.0 to MFC 2.0.

Technical notes 20 to 36 are topics specific to MFC 2.0 (and higher)

Technical note 37 is specific to 32-bit versions of MFC.

Technical notes 38 to 48 are topics specific to MFC 2.5 (and higher)

Technical notes 49 to 52 are topics specific to MFC 3.0 (and higher)

Technical notes 53 to 71 are topics specific to MFC 4.0 (and higher)

Gaps in the Technical Note numbering are due to MFC 1.0 technical notes that are now obsolete. More complete information can now be found in the Visual C++ Programmer's Guide.


Technical Notes by Category

Technical notes are divided into the following categories. For a numerical listing of technical notes, see Technical Notes by Number.

MFC and Windows

TN001: Window Class Registration
TN003: Mapping of Windows Handles to Objects
TN012: Using MFC with Windows 3.1 Robustness Features
TN015: Windows for Pen
TN017: Destroying Window Objects
TN034: Writing a Windows 3.0 Compatible MFC Application
TN051: Using CTL3D Now and in the Future
TN052: Writing Windows 95 Applications with MFC3.1

MFC Architecture

TN002: Persistent Object Data Format
TN004: C++ Template Tool
TN006: Message Maps
TN016: Using C++ Multiple Inheritance with MFC
TN019: Updating Existing MFC Applications to MFC 3.0
TN021: Command and Message Routing
TN022: Standard Commands Implementation
TN025: Document, View, and Frame Creation
TN026: DDX and DDV Routines
TN029: Splitter Windows
TN030: Customizing Printing and Print Preview
TN031: Control Bars
TN032: MFC Exception Mechanism
TN037: Multithreaded MFC 2.1 Applications
TN044: MFC Support for DBCS
TN046: Commenting Conventions for the MFC Classes
TN058: MFC Module State Implementation
TN059: Using MFC MBCS/Unicode Conversion Macros
TN066: Common MFC 3.x to 4.0 Porting Issues

MFC Controls

TN014: Custom Controls
TN027: Emulation Support for Visual Basic Custom Controls
TN060: Windows Common Controls
TN061: ON_NOTIFY and WM_NOTIFY Messages
TN062: Message Reflection for Windows Controls

MFC Database

TN042: ODBC Driver Developer Recommendations
TN043: RFX Routines
TN045: MFC/Database Support for Long Varchar/Varbinary
TN047: Relaxing Database Transaction Requirements
TN048: Writing ODBC Setup and Administration Programs for MFC Database Applications
TN053: Custom DFX Routines for MFC DAO Classes
TN054: Calling DAO Directly While Using MFC DAO Classes
TN055: Migrating MFC ODBC Database Class Applications to MFC DAO Classes
TN068: Performing Transactions with the Microsoft Access 7 ODBC Driver

MFC Debugging

TN007: Debugging Trace Options

MFC DLLs

TN011: Using MFC as Part of a DLL
TN033: DLL Version of MFC
TN056: Installation of MFC Components
TN057: Localization of MFC Components

MFC OLE

TN008: MFC OLE Support
TN018: Migrating OLE Applications from MFC 1.0 to MFC 2.0
TN038: MFC/OLE IUnknown Implementation
TN039: MFC/OLE Automation Implementation
TN040: MFC/OLE In-Place Resizing and Zooming
TN041: MFC/OLE1 Migration to MFC/OLE2
TN049: MFC/OLE MBCS to Unicode Translation Layer (MFCANS32)
TN050: MFC/OLE Common Dialogs (MFCUIx32)
TN064: Apartment-Model Threading in OLE Controls
TN065: Dual-Interface Support for OLE Automation Servers
TN071: MFC IOleCommandTarget Implementation

MFC Resources

TN020: ID Naming and Numbering Conventions
TN023: Standard MFC Resources
TN024: MFC-Defined Messages and Resources
TN028: Context-Sensitive Help Support
TN035: Using Multiple Resource Files and Header Files with Visual C++
TN036: Using CFormView with AppWizard and ClassWizard
TN070: MFC Window Class Names

MFC Internet

TN063: Debugging Internet Extension DLLs
TN067: Database Access from an ISAPI Server Extension
TN069: Processing HTML Forms Using Internet Server Extension DLLs and Command Handlers


TN001: Window Class Registration

This note describes the MFC routines that register the special WNDCLASSes needed by Microsoft Windows. Specific WNDCLASS attributes used by MFC and Windows are discussed.

The Problem

The attributes of a CWnd object, like an HWND in Windows, are stored in two places: the window object and the WNDCLASS. A WNDCLASS is different than a C++ class. The name of the WNDCLASS is passed to general window creation functions such as CWnd::Create and CFrameWnd::Create in the lpszClassName parameter.

This WNDCLASS must be registered via one of four means:

  • Implicitly by MFC provided WNDCLASSes

  • Implicitly by subclassing a Windows control (or some other control)

  • Explicitly by calling the MFC AfxRegisterWndClass or AfxRegisterClass

  • Explicitly by calling the Windows routine RegisterClass

WNDCLASSes and MFC

The WNDCLASS structure consists of various fields that describe a window class. Following are the fields and how they are used in an MFC application.

Style | Style of window: see below
LpfnWndProc | window proc, must be AfxWndProc
CbClsExtra | not used (should be zero)
CbWndExtra | not used (should be zero)
HInstance | automatically filled with AfxGetInstanceHandle
HIcon | icon for frame windows, see below
HCursor | cursor for when mouse is over window, see below
HbrBackground | background color, see below
LpszMenuName | not used (should be NULL)
LpszClassName | class name, see below

Provided WNDCLASSes

In previous versions of MFC (prior to MFC 4.0), there were a number of predefined Window classes provided. These Window classes are no longer provided by default because of technical problems related to versioning (multiple versions of MFC loaded in one address space) as well as concerns relating to the fact that both MFC applications and OLE Controls may use the MFC DLLs.

The following reference is provided to help migrate code that uses these previously provided WNDCLASSes. Applications should use AfxRegisterWndClass (with the appropriate parameters) in place of these classes.

The following shows the classes and their attributes:

  • "AfxWnd" is used for all child windows created with CWnd::Create.
    • class style : CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW

    • no icon

    • arrow cursor

    • no background color
  • "AfxFrameOrView" is used for frame windows and views (including stand-alone CFrameWnds and CMDIChildWnds).
    • class style : CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;

    • icon AFX_IDI_STD_FRAME

    • arrow cursor

    • COLOR_WINDOW background color
  • "AfxMDIFrame" is used for the MDI frame window (that is, the parent) created with CMDIFrameWnd::Create.
    • class style : CS_DBLCLKS [ reduces flash during resizing ]

    • icon AFX_IDI_STD_MDIFRAME

    • arrow cursor

    • no background color
  • "AfxControlBar" is used for the standard control bar implementation.
    • class style : 0 [ reduces flash during resizing, no double clicks ]

    • no icon

    • arrow cursor

    • gray background color (COLOR_BTNFACE)

If the application provides a resource with the specified resource ID (for example, AFX_IDI_STD_FRAME) ID, MFC will use that resource. Otherwise the default resource is used. For the icon, the standard application icon is used, and for the cursor, the standard arrow cursor is used.

There are two icons that support MDI applications with single document types (one icon for the main application, the other icon for iconic document/MDIChild windows). For multiple document types with different icons, you must register additional WNDCLASSes or use the CFrameWnd::LoadFrame function.

CFrameWnd::LoadFrame will automatically register a WNDCLASS using the standard "AfxFrameOrView" attributes but using the icon ID you specify as the first parameter to LoadFrame.

The values for background color and cursor for the MDIFrameWnd are not used since the client area of the MDIFrameWnd is completely covered by the "MDICLIENT" window. Microsoft does not encourage subclassing the "MDICLIENT" window so use the standard colors and cursor types when possible.

Subclassing Controls

If you subclass or superclass a Windows control (for example, CButton) then your class automatically gets the WNDCLASS attributes provided in the Windows implementation of that control.

The AfxRegisterWndClass Function

MFC provides a helper routine for registering a window class. Given a set of attributes (window class style, cursor, background brush, and icon), a synthetic name is generated, and the resulting window class is registered. For example,

const char* AfxRegisterWndClass(UINT nClassStyle, HCURSOR hCursor,    HBRUSH hbrBackground, HICON hIcon);

This function returns a temporary string of the generated registered window class name. See the Class Library Reference for more details.

The string returned is a temporary pointer to a static string buffer which is valid until the next call to AfxRegisterWndClass. If you want to keep this string around, store it in a CString variable. For example,

CString strWndClass = AfxRegisterWndClass(CS_DBLCLK, ...);
...
CWnd* pWnd = new CWnd;
pWnd->Create(strWndClass, ...);
...

AfxRegisterWndClass will throw a CResourceException if the window class failed to register (either because of bad parameters, or out of Windows memory).

The RegisterClass and AfxRegisterClass Functions

If you want to do anything more sophisticated than what AfxRegisterWndClass provides, you may call the Windows API RegisterClass or the MFC function AfxRegisterClass. The CWnd, CFrameWnd and CMDIChildWnd Create functions take a lpszClassName string name for the window class as the first parameter. Any window class name can be used, regardless of how it was registered.

It is important to use AfxRegisterClass (or AfxRegisterWndClass) in a DLL on Win32. Win32 does not automatically unregister classes registered by a DLL, so this must be done explicitly when the DLL is terminated. By using AfxRegisterClass instead of RegisterClass this is done automatically for you. AfxRegisterClass maintains a list of unique classes registered by your DLL and will automatically unregister then when the DLL terminates. When using RegisterClass in a DLL, you must insure that all classes are unregistered when the DLL is terminated (in your DllMain function). Failure to do so may cause RegisterClass to fail unexpectedly when your DLL is used by another client application.


TN002: Persistent Object Data Format

This note describes the MFC routines that support persistent C++ objects and the format of the object data when it is stored in a file. This only applies to classes with the DECLARE_SERIAL and IMPLEMENT_SERIAL macros.

The Problem

The MFC implementation for persistent data relies on a compact binary format for saving the data for many objects in a single contiguous part of a file. This binary format provides the structure for how the data is stored, but it is the object's Serialize member function that provides the actual data saved by the object.

The MFC solves the structuring problem by using the class CArchive. A CArchive object provides a context for persistence that lasts from the time the archive is created until the CArchive::Close member function is called, either explicitly by the programmer or implicitly by the destructor when the scope containing the CArchive is exited.

This note describes the implementation of the CArchive members ReadObject and WriteObject. ReadObject and WriteObject are not called directly by instead are used by class-specific type-safe insertion and extraction operators generated automatically by the DECLARE_SERIAL and IMPLEMENT_SERIAL macros.

class CMyObject : public CObject
{
    DECLARE_SERIAL(CMyObject)
};

IMPLEMENT_SERIAL(CMyObj, CObject, 1)

// example usage (ar is a CArchive&)
CMyObject* pObj;
CArchive& ar;
ar << pObj;        // calls ar.WriteObject(pObj)
ar >> pObj;        // calls ar.ReadObject(RUNTIME_CLASS(CObj))

This note describes code located in the MFC source file ARCOBJ.CPP. The main CArchive implementation can be found in ARCCORE.CPP.

Saving Objects to the Store (CArchive::WriteObject)

The member function CArchive::WriteObject writes header data used to reconstruct the object. This data consists of two parts: the type of the object and the state of the object. This member function is also responsible for maintaining the identity of the object being written out, so that only a single copy is saved, regardless of the number of pointers to that object (including circular pointers).

Saving (inserting) and restoring (extracting) objects relies on several “manifest constants.” These are values that are stored in binary and provide important information to the archive (note the "w" prefix indicates 16-bit quantities):

Tag | Description
wNullTag | Used for NULL object pointers (0).
wNewClassTag | Indicates class description that follows is new to this archive context—(-1).
wOldClassTag | Indicates class of the object being read has been seen in this context (0x8000).

When storing objects, the archive maintains a CMapPtrToPtr (the m_pStoreMap) which is a mapping from a stored object to a 32-bit persistent identifier (PID). A PID is assigned to every unique object and every unique class name that is saved in the context of the archive. These PIDs are handed out sequentially starting at 1. It is important to note that these PIDs have no significance outside the scope of the archive and, in particular, are not to be confused with record number or other identity items.

Starting with MFC version 4.0 the CArchive class has been extended to support very large archives. In previous versions, a PID was a 16-bit quantity, limiting the archive to 0x7FFE (32766) objects. PIDs are now 32-bit, but they are written out as 16-bit unless they are larger than 0x7FFE. Large PIDs are written as 0x7FFF followed by the 32-bit PID. This technique maintains file backward compatibility.

When a request is made to save an object to an archive (usually through the global insertion operator), a check is made for a NULL CObject pointer; if the pointer is NULL, the wNullTag is inserted into the archive stream.

If we have a real object pointer that is capable of being serialized (the class is a DECLARE_SERIAL class), we then check the m_pStoreMap to see if the object has been saved already. If it has, we insert the 32-bit PID associated with that object.

If the object has not been saved before, there are two possibilities we must take into account: either both the object and the exact type (that is, class) of the object are new to this archive context, or the object is of an exact type already seen. To determine if the type has been seen we query the m_pStoreMap for a CRuntimeClass object that matches the CRuntimeClass object associated with the object we are saving. If we have seen this class before, WriteObject inserts a tag that is the bit-wise OR'ing of wOldClassTag and this index. If the CRuntimeClass is new to this archive context, then WriteObject assigns a new PID to that class and insert it into the archive, preceded by the wNewClassTag value.

The descriptor for this class is then inserted into the archive using the CRuntimeClass member function Store. CRuntimeClass::Store inserts the schema number of the class (see below) and the ASCII text name of the class. Note that the use of the ASCII text name does not guarantee uniqueness of the archive across applications, thus it is advisable to tag your data files to prevent corruption. Following the insertion of the class information, the archive places the object into the m_pStoreMap and then calls the Serialize member function to insert class-specific data into the archive. Placing the object into the m_pStoreMap before calling Serialize prevents multiple copies of the object from being saved to the store.

When returning to the initial caller (usually the root of the network of objects), it is important to Close the archive. If other CFile operations are going to be done, the CArchive member function Flush MUST be called. Failure to do so will result in a corrupt archive.

Note This implementation imposes a hard limit of 0x3FFFFFFE indices per archive context. This number represents the maximum number of unique objects and classes that can be saved in a single archive, but note that a single disk file can have an unlimited number of archive contexts.

Loading Objects from the Store (CArchive::ReadObject)

Loading (extracting) objects uses the CArchive::ReadObject member function and is the converse of WriteObject. As with WriteObject, ReadObject is not called directly by user code; user code should call the type-safe extraction operator which calls ReadObject with the expected CRuntimeClass. This insures the type integrity of the extract operation.

Since the WriteObject implementation assigned increasing PIDs, starting with 1 (0 is predefined as the NULL object), the ReadObject implementation can use an array to maintain the state of the archive context. When a PID is read from the store, if the PID is greater than the current upper bound of the m_pLoadArray, then ReadObject knows that a new object (or class description) follows.

Schema Numbers

The schema number, which is assigned to the class when the class' IMPLEMENT_SERIAL is encountered, is the "version" of the class implementation. The schema refers to the implementation of the class, not to the number of times a given object has been made persistent (usually referred to as the object version).

If you intend to maintain several different implementations of the same class over time, incrementing the schema as you revise your object's Serialize member function implementation will enable you to write code that can load objects stored using older versions of the implementation.

The CArchive::ReadObject member function will throw a CArchiveException when it encounters a schema number in the persistent store that differs from the schema number of the class description in memory. It is not easy to recover from this exception.

You can use VERSIONABLE_SCHEMA OR'd with your schema version to keep this exception from being thrown. By using VERSIONABLE_SCHEMA, your code can take the appropriate action in its Serialize function by checking the return value from CArchive::GetObjectSchema.

Calling Serialize Directly

There are many cases where the overhead of the general object archive scheme of WriteObject and ReadObject is not necessary or desired. This is the common case of serializing the data into a CDocument. In this case the Serialize member function of the CDocument is called directly, not with the extract or insert operators. The contents of the document may in turn use the more general object archive scheme.

Calling Serialize directly has the following advantages and disadvantages:

  • No extra bytes are added to the archive before or after the object is serialized. This not only makes the saved data smaller, but allows you to implement Serialize routines that can handle any file formats.

  • The MFC is tuned so the WriteObject and ReadObject implementations and related collections will not be linked into your application unless you need the more general object archive scheme for some other purpose.

  • Your code does not need to recover from old schema numbers. This makes your document serialization code responsible for encoding schema numbers, file format version numbers or whatever magic numbers desired at the start of your data files.

  • Any object that is serialized with a direct call to Serialize must not use CArchive::GetObjectSchema or must handle a return value of (UINT)-1 indicating that the version was unknown.

Because Serialize is called directly on your document, it is not usually possible for the sub-objects of the document to archive references to their parent document. These objects must be given a pointer to their container document explicitly or you must use CArchive::MapObject function to map the CDocument pointer to a PID before these back pointers are archived.

As noted above, you should encode the version and class information yourself when calling Serialize directly, allowing you to change the format later while still maintaining backward compatibility with older files. The CArchive::SerializeClassRef function can be called explicitly before directly serializing an object or before calling a base class.


TN003: Mapping of Windows Handles to Objects

This note describes the MFC routines that support mapping Windows object handles to C++ objects.

The Problem

Windows objects are normally represented by HANDLEs. The MFC classes wrap Windows object handles with C++ objects. The handle wrapping functions of the MFC class library provide a way to find the C++ object that is wrapping the Windows object with a particular handle. There are times when a Windows object does not have a C++ wrapper object, however, and at these times a temporary object is created to act as the C++ wrapper.

The Windows objects that use handle maps are:

  • HWND (CWnd and CWnd-derived classes)

  • HDC (CDC and CDC-derived classes)

  • HMENU (CMenu)

  • HPEN (CGdiObject)

  • HBRUSH (CGdiObject)

  • HFONT (CGdiObject)

  • HBITMAP (CGdiObject)

  • HPALETTE (CGdiObject)

  • HRGN (CGdiObject)

  • HIMAGELIST (CImageList)

  • SOCKET (CSocket)

Given a handle to any of these objects, you can find the MFC object that wraps the handle by calling the static member function FromHandle. For example, given an HWND called hWnd:

CWnd::FromHandle(hWnd)

will return a pointer to the CWnd that wraps the hWnd. If that hWnd does not have a specific wrapper object, then a temporary CWnd is created to wrap the hWnd. This makes it possible to get a valid C++ object from any handle.

Once you have a wrapper object, you can get to its handle through a public member variable. In the case of an CWnd, m_hWnd contains the HWND for that object.

Attaching Handles to MFC Objects

Given a newly created handle-wrapper object and a handle to a Windows object, you can associate the two by calling Attach. For example:

CWnd myWnd;
myWnd.Attach(hWnd);

This makes an entry in the permanent map associating myWnd and hWnd. Calling CWnd::FromHandle(hWnd) will now return a pointer to myWnd. When myWnd is deleted, the destructor will automatically destroy the hWnd by calling the Windows DestroyWindow function. If this is not desired, the hWnd must be detached from myWnd before the myWnd object is destroyed (normally when leaving the scope at which myWnd was defined). The Detach member function does this.

myWnd.Detach();

More About Temporary Objects

Temporary objects are created whenever FromHandle is given a handle that does not already have a wrapper object. These temporary objects are detached from their handle and deleted by the DeleteTempMap functions. The default OnIdle processing in CWinThread automatically calls DeleteTempMap for each class that supports temporary handle maps. This means that you cannot assume a pointer to a temporary object will be valid past the point of exit from the function where the pointer was obtained, as the temporary object will be deleted during the Windows message-loop idle time.

Wrapper Objects and Multiple Threads

Both temporary and permanent objects are maintained on a per-thread basis. That is, one thread cannot access another threads C++ wrapper objects, regardless of whether it is temporary or permanent. As stated above, temporary objects are deleted when the thread which that temporary object belongs enters OnIdle.

To pass these objects from one thread to another, always send them as their native HANDLE type. Passing a C++ wrapper object from one thread to another will often result in unexpected results.


TN004: C++ Template Tool

This note describes MFC template-class issues and the MFC TEMPLDEF template expansion tool.

The Problem

MFC uses template classes to implement the standard collection classes. Template classes are classes that can be expanded based on a type argument specified by the user. For the MFC standard collection classes, the classes in AFXCOLL.H and their implementations are already pre-expanded for you. To create your own collection classes for your own type, you can use AFXTEMPL.H which contains array, list, and map class templates using standard C++ template syntax. The TEMPLDEF tool is provided only for backward compatibility (in case you were using it to generate your own collection classes in previous versions).

The TEMPLDEF Tool

The TEMPLDEF tool is a template expander. TEMPLDEF uses a syntax similar to the ANSI language syntax. In order to use TEMPLDEF, you must build it first, much like any other sample. This sample is provided only for backward compatibility, since with this version of Visual C++, true C++ templates are fully supported as are the MFC template classes that use them (see CList, CArray, and CMap classes)

A good way to get started is by examining four .CTT template classes provided with MFC (found in MFC Programming Utilities sample TEMPLDEF subdirectory). The MKCOLL.BAT batch file gives examples of the command line syntax of the TEMPLDEF tool. The general form of the command line syntax is modeled after a C++ typedef of the equivalent template class. For example,

typedef CLinkedList<CMyObj> CMyLinkedList;

becomes

TEMPLDEF "CLinkedList<CMyObj> CMyLinkedList" LINKLIST.CTT MYLIST.H MYLIST.INL MYLIST.CPP

The MFC template classes are slightly more complicated than this example, taking a number of Boolean-constant template parameters that allow several slightly different variations of collections to be expanded. Please refer to the TEMPLDEF sample for more details on the TEMPLDEF program and the command line options for using the provided template classes.


TN006: Message Maps

This note describes the MFC message map facility.

The Problem

Microsoft Windows implements what are essentially virtual functions in window classes using its messaging facility. Due to the large number of messages involved, providing a separate virtual function for each Windows message results in a prohibitively large vtable.

Also, since the number of system-defined Windows messages changes over time, and since a specific application may want to define some Windows messages of its own, the message-map mechanism provides a level of indirection that prevents interface changes from breaking existing code.

Overview

MFC provides an alternative to the switch statement used in traditional Windows programs to handle messages sent to a window. A mapping from messages to member-functions may be defined so that when a message is to be handled by a window, the appropriate member function is called automatically. This message-map facility is designed to be similar to virtual functions but has additional benefits not possible with C++ virtual functions.

Defining a Message Map

The DECLARE_MESSAGE_MAP macro declares three members for a class.

  • A private array of AFX_MSGMAP_ENTRY entries called _messageEntries,

  • A protected AFX_MSGMAP structure called messageMap that points to the _messageEntries array

  • A protected virtual function called GetMessageMap that returns the address of messageMap.

This macro should be placed in the declaration of any class using message maps. By convention, it is at the end of the class declaration. For example:

class CMyWnd : public CMyParentWndClass
{
    // my stuff...

protected:
    //{{AFX_MSG(CMyWnd)
    afx_msg void OnPaint();
    //}}AFX_MSG

    DECLARE_MESSAGE_MAP()
};

This is the format generated by AppWizard and ClassWizard when they create new classes. The //{{ and //}} brackets are needed for ClassWizard.

The message map's table is defined with a set of macros that expand to message map entries. A table begins with a BEGIN_MESSAGE_MAP macro call, which defines the class that is handled by this message map and the parent class to which unhandled messages are passed. The table ends with the END_MESSAGE_MAP macro call.

Between these two macro calls is an entry for each message to be handled by this message map. Every standard Windows message has a macro of the form ON_WM_xxx (where xxx is the name of the message) that generates an entry for that message.

A standard function signature has been defined for unpacking the parameters of each Windows message and providing type safety. These signatures may be found in the file AFXWIN.H in the declaration of CWnd. Each one is marked with the word afx_msg for easy identification.

Note ClassWizard requires that you use the afx_msg keyword in your message map handler declarations.

These function signatures were derived using a simple convention. The name of the function always starts with "On". This is followed by the name of the Windows message with the WM_ removed and only the first letter of each word capitalized. The ordering of the parameters is wParam followed by LOWORD(lParam) then HIWORD(lParam). Unused parameters are not passed. Any handles that are wrapped by MFC classes are converted to pointers to the appropriate MFC objects. The following example shows how to handle the WM_PAINT message and cause the CMyWnd::OnPaint function to be called:

BEGIN_MESSAGE_MAP(CMyWnd, CMyParentWndClass)
    //{{AFX_MSG_MAP(CMyWnd)
    ON_WM_PAINT()
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

The message map table must be defined outside the scope of any function or class definition. It should not be placed within an extern "C" block.

Note ClassWizard will edit the message map entries that are found between the //{{ and //}} comment bracket.

User Defined Windows Messages

User-defined messages may be included in a message map by using the ON_MESSAGE macro. This macro accepts a message number and a member function of the form:

    // inside the class declaration
    afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);

For example:
    #define WM_MYMESSAGE (WM_USER + 100)

BEGIN_MESSAGE_MAP(CMyWnd, CMyParentWndClass)
    ON_MESSAGE(WM_MYMESSAGE, OnMyMessage)
END_MESSAGE_MAP()

In this example, we establish a handler for a custom message with a Windows message ID derived from the standard WM_USER base for user-defined messages. You might invoke this handler with code such as:

CWnd* pWnd = ...;
pWnd->SendMessage(WM_MYMESSAGE);

The range of user defined messages using this approach must be in the range WM_USER to 0x7fff.

Note ClassWizard does not support entering ON_MESSAGE handler routines from the ClassWizard user interface: you must manually enter them from the Visual C++ editor. Once entered, ClassWizard will parse these entries and allow you to browse them just like any other message-map entries.

Registered Windows Messages

The ::RegisterWindowMessage function is used to define a new window message that is guaranteed to be unique throughout the system. The macro ON_REGISTERED_MESSAGE is used to handle these messages. This macro accepts a the name of a near UINT variable that contains the registered windows message ID. For example

class CMyWnd : public CMyParentWndClass
{
public:
    CMyWnd();

    //{{AFX_MSG(CMyWnd)
    afx_msg LRESULT OnFind(WPARAM wParam, LPARAM lParam);
    //}}AFX_MSG

    DECLARE_MESSAGE_MAP()
};

static UINT NEAR WM_FIND = RegisterWindowMessage("COMMDLG_FIND");

BEGIN_MESSAGE_MAP(CMyWnd, CMyParentWndClass)
    //{{AFX_MSG_MAP(CMyWnd)
    ON_REGISTERED_MESSAGE(WM_FIND, OnFind)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

The registered Windows message ID variable (WM_FIND in the example above) must be a NEAR variable because of the way ON_REGISTERED_MESSAGE is implemented.

The range of user defined messages using this approach will be in the range 0xC000 to 0xFFFF.

Note ClassWizard does not support entering ON_REGISTERED_MESSAGE handler routines from the ClassWizard user interface, you must manually enter them from the text editor. Once entered, ClassWizard will parse these entries and allow you to browse them just like any other message-map entries.

Command Messages

Command messages from menus and accelerators are handled in message maps with the ON_COMMAND macro. This macro accepts a command ID as well as a member function. Only the specific WM_COMMAND message with a wParam equal to the specified command ID is handled by the member function specified in the message-map entry. Command handler member functions take no parameters and return void. The macro has the form:

ON_COMMAND(id, memberFxn)

Command update messages are routed through the same mechanism as ON_COMMAND handlers. The ON_UPDATE_COMMAND_UI macro is used instead. Command update handler member functions take a single parameter, a pointer to a CCmdUI object, and return void. The macro has the form

ON_UPDATE_COMMAND_UI(id, memberFxn)

An extended form of command message handlers is available for advanced uses. The ON_COMMAND_EX macro is used instead and provides a superset of the ON_COMMAND functionality. Extended command-handler member functions take a single parameter, a UINT containing the command ID, and return a BOOL. The BOOL return should be TRUE to indicate that the command has been handled, otherwise routing will continue to other command target objects.

Examples of the above forms:

  • Inside RESOURCE.H (usually generated by Visual C++)
    #define    ID_MYCMD      100
#define    ID_COMPLEX    101
  • Inside the class declaration
    afx_msg void OnMyCommand();
afx_msg void OnUpdateMyCommand(CCmdUI* pCmdUI);
afx_msg BOOL OnComplexCommand(UINT nID);
  • Inside the message map definition
    ON_COMMAND(ID_MYCMD, OnMyCommand)
ON_UPDATE_COMMAND_UI(ID_MYCMD, OnUpdateMyCommand)
ON_COMMAND_EX(ID_MYCMD, OnComplexCommand)
  • In the implementation file
    void CMyClass::OnMyCommand()
{
    // handle the command
}

void CMyClass::OnUpdateMyCommand(CCmdUI* pCmdUI)
{
    // set the UI state with pCmdUI
}

BOOL CMyClass::OnComplexCommand(UINT nID)
{
    // handle the command
    return TRUE;
}

Also available for advanced use is ON_COMMAND_RANGE and ON_COMMAND_RANGE_EX which allow you to handle a range of commands with a single command handler. See the product documentation for more information on these macros.

Note ClassWizard supports creating ON_COMMAND and ON_UPDATE_COMMAND_UI handlers, but it does not support creating ON_COMMAND_EX or ON_COMMAND_RANGE handlers. However, Class Wizard will parse and allow you to browse all three command handler variants.

Control Notification Messages

Messages that are sent from child controls to a window have an extra bit of information in their message map entry: the control's ID. The message handler specified in a message map entry is called only if (1) the control notification code (high word of lParam), such as BN_CLICKED, matches the notification code specified in the message-map entry and (2) control ID (wParam) matches the control ID specified in the message-map entry.

Custom control notification messages may use the ON_CONTROL macro to define a message map entry with a custom notification code. This macro has the form

ON_CONTROL(wNotificationCode, id, memberFxn)

For advanced usage ON_CONTROL_RANGE can be used to handle a specific control notification from a range of controls with the same handler.

ClassWizard does not support creating an ON_CONTROL or ON_CONTROL_RANGE handler in the user interface; you must manually enter them with the text editor. Once entered, ClassWizard will parse these entries and allow you to browse them just like any other message map entries.

The Windows Common Controls make use of the more powerful WM_NOTIFY for complex control notifications. This version of MFC has direct support for this new message with the ON_NOTIFY and ON_NOTIFY_RANGE macros. See the product documentation for more information on these macros.


TN007: Debugging Trace Options

To help debug windows programs, MFC provides a TRACE output mechanism. This will display, to a debugging output window or console, messages about the internal operation of the MFC library as well as warnings and errors if something goes wrong in your application.

Turning on TRACE output is strongly recommended, since it will sometimes give you advanced warning of problems that are about to occur or give more verbose reasons why problems do occur.

How to Turn on TRACE Output

By default TRACE message output is disabled. In order for trace output to be seen, you must perform the following steps:

  1. Compile your program with the _DEBUG symbol defined and link with a debug version of the MFC library. Debugging and trace options are only available in the _DEBUG version of the library.

  2. Enable the afxTraceEnabled flag. There are several ways to do this, but using the TRACER.EXE utility is highly recommended.

  3. Customize the afxTraceFlags to the level of detail you would like to see in trace messages. Use of the TRACER.EXE utility is highly recommended.

Where the Output Goes

When afxTraceEnabled is TRUE, then TRACE output (and default afxDump output) will go to the output window if present. When afxTraceEnable is FALSE, TRACE output and afxDump output will not be displayed.

If a debugger is present, then TRACE output will go to the debugger's output window. If no debugger is present, then TRACE output will not be seen.

Using TRACER.EXE

TRACER.EXE is a small MFC Programming Utilities sample program that allows you to set the options in AFX.INI. TRACER is installed in your BIN directory by the Visual C++ setup. The source code for TRACER is provided as well, so you can rebuild it and customize it as you wish.

A sample AFX.INI file is provided in the MFC\SRC subdirectory. This .INI file turns on diagnostic messages and uses the standard options. You should place this AFX.INI file in your Windows directory or run the TRACER.EXE program to create a new AFX.INI file and set options in it using a dialog box.

Any changes to AFX.INI will take effect in any debug MFC application launched after the changes are saved.

The global integer afxTraceFlags is used to turn on the built-in reporting features of the MFC and to store all flags. It can be set under program control or with the debugger. The global integer afxTraceFlags uses each bit to select a trace reporting option.

You can turn any bit on or off as desired. Try playing with them to get a flavor of the report information they generate. See the AFXWIN.H header for the numeric values of the different options.

// example under program control
afxTraceFlags = 4 + 8;        // windows message dumping

Ease of Reading

For ease of reading, certain frequent messages are not reported. These include:

Mouse move messages (non-client and client):

  • WM_NCHITTEST

  • WM_SETCURSOR

  • WM_ENTERIDLE

  • WM_CTLCOLOR

These messages are sent every time the mouse moves or during idle processing or other common dialog processing.


TN008: MFC OLE Support

This tech note, which previously discussed the MFC/OLE1 implementation and design, is now obsolete. MFC 1.0 and MFC 2.0 supported the original OLE 1.0 API. OLE 1.0 has been replaced by OLE 2.0 which is supported by MFC 2.5 (and higher). The following technical notes describe the MFC/OLE2 support included in this version of MFC:

  • Technical Note 38 MFC/OLE IUnknown Implementation

  • Technical Note 39 MFC/OLE Automation Implementation

  • Technical Note 40 MFC/OLE In-Place Resizing and Zooming

  • Technical Note 41 MFC/OLE1 Migration to MFC/OLE2


TN011: Using MFC as Part of a DLL

This note describes regular DLLs, which allow you to use the MFC library as part of a Windows dynamic-link library (DLL). It assumes you are familiar with Windows DLLs and how to build them. For information about MFC extension DLLs, which allow you to create extensions to the MFC library, see DLL Version of MFC.

DLL Interfaces

Regular DLLs assume interfaces between the application and the DLL are specified in normal C-like functions or explicitly exported classes. MFC class interfaces cannot be exported.

If both a DLL and an application want to use MFC, then both have a choice to either use the shared version of the MFC libraries or have a copy of the MFC library statically linked into them. In versions prior to Visual C++ 4.0, the MFC static link libraries were different for applications and DLLs. With the current version of MFC, the application and DLL may both use one of the standard versions of the MFC library. There is not a separate library for DLLs in this version (MFC makes the choice at runtime).

Regular DLLs have several advantages:

  • The application using the DLL does not have to use MFC or, for that matter, it does not have to be a Visual C++ application.

  • With regular DLLs that statically link to MFC, the size of the DLL depends only on those MFC and C runtime routines that are used and linked by the linker.

  • The file size of regular DLLs that dynamically link to MFC may be much smaller than regular DLLs that statically link to MFC, and the savings in memory from using the shared version of MFC can be significant. However, you must distribute the shared DLLs MFCx0.DLL and MSVCRTx0.DLL (or similar files) with your DLL.

  • There are no problems with classes changing underneath you. Your DLL design exports only those APIs you wish it to.

  • With regular DLLs that statically link to MFC, if both DLL and application use MFC, there are no problems with the application wanting a different version of MFC than the DLL (or vice versa). Since the MFC library is statically linked into each DLL or EXE, there is no question about which version you have.

API Limitations

Some MFC capabilities are not applicable to the DLL version, either because of technical limitations or because those services are usually provided by the application. These limitations are listed below:

  • CWinApp::Enable3dControls

  • CWinApp::SetDialogBkColor (color is ignored for message boxes)

Building Your DLL

When compiling regular DLLs that statically link to MFC, the symbols "_USRDLL" and "_WINDLL" must be defined. Your DLL code must also be compiled with the following compiler switches:

  • /D_WINDLL signifies the compilation is for a DLL

  • /D_USRDLL specifies you are building a regular DLL

When compiling regular DLLs that dynamically link to MFC, you must define the above symbols and use the above compiler switches. Additonally, the symbol "_AFXDLL” must be defined and your DLL code must be compiled with:

  • /D_AFXDLL specifies that you are building a regular DLL that dynamically links to MFC

The interfaces (APIs) between the application and the DLL must be explicitly exported. It is recommended that you define your interfaces to be low bandwidth, sticking to C interfaces where possible. More direct C interfaces are easier to maintain than more complex C++ classes.

Place your APIs in a separate header that can be included by both C and C++ files (that way you won't limit your DLL customers to C++ programmers). See the header TRACEAPI.H in the MFC Advanced Concepts sample DLLTRACE for an example. To export your functions, enter them in the EXPORTS section of your module definition file (.DEF) or include __declspec(dllexport) on your function definitions. Use __declspec(dllimport) to import these functions into the client executable.

You must add the AFX_MANAGE_STATE macro at the begining of all the exported functions in regular DLLs that dynamically link to MFC to set the current module state to the one for the DLL. This is done by adding the following line of code to the beginning of functions exported from the DLL:

AFX_MANAGE_STATE(AfxGetStaticModuleState( ))

WinMain -> DllMain

The MFC library defines the standard Win32 DllMain entry point that initializes your CWinApp derived object as in a normal MFC application. Place all DLL-specific initialization in the InitInstance member function as in a normal MFC application.

Note that the CWinApp::Run mechanism doesn't apply to a DLL, since the application owns the main message pump. If your DLL brings up modeless dialogs or has a main frame window of its own, your application's main message pump must call a DLL-exported routine that calls CWinApp::PreTranslateMessage.

See the DLLTRACE sample for use of this function.

The ExitInstance member function of your CWinApp derived class will be called from the MFC provided DllMain function before the DLL is unloaded.

What to Do to Link It All Together

With regular DLLs that statically link to MFC, you must link your DLL with this library (NAFXCWD.LIB or NAFXCW.LIB) along with the version of the C runtimes called 'LIBCMT.LIB'. These libraries are pre-built and may be installed by specifying them when you run Visual C++ setup.

Sample Code

Please see the MFC Advanced Concepts sample program DLLTRACE for a complete sample. This includes a simple DLL called 'TRACER.DLL' that implements the AFX Trace flags dialog (see Technical Note 7). It also has a simple HELLO application that calls the DLL to use the dialog.

Several interesting thing to note:

  • The compiler flags of the DLL and the application are very different.

  • The link lines and .DEF files for the DLL and the application are also very different.

  • The application using the DLL doesn't even have to be in C++.

  • The interface between the application and the DLL is a "C"-like API and are exported with TRACER.DEF.

The following extract from TRACEAPI.H illustrates what is needed for one API that is defined in a regular DLL that statically links to MFC:

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

struct TracerData
{
    BOOL    bEnabled;
    UINT    flags;
};

BOOL FAR PASCAL EXPORT PromptTraceFlags(TracerData FAR* lpData);

#ifdef __cplusplus
}
#endif

In this example, the declaration is enclosed in an 'extern "C" { }' block for C++ users. This has several advantages. First, it makes your DLL APIs usable by non-C++ client applications. Second, it reduces DLL overhead since C++ name mangling will not be applied to the exported name. Lastly, it makes it easier to explicitly add to a .DEF file (for exporting by ordinal) without having to worry about name mangling.

All API functions are "FAR PASCAL EXPORT". Although not stricly necessary for Win32 DLLs, these definitions have been kept for easy back-porting to 16-bit Windows. The FAR, PASCAL, and EXPORT macros all expand to nothing under Win32.

The structures used by the API are not derived from MFC classes and are defined completely in the API header. This reduces the complexity of the interface between the DLL and the application and, once again, makes the DLL usable by C programs as well.

Any data pointers used in the API are explicit FAR pointers. Again, FAR, is not really necessary for Win32, but is useful if you plan to compile the code for 16-bit Windows sometime in the future.


TN012: Using MFC with Windows 3.1 Robustness Features

Note This Technical Note was written for Windows 3.1. Windows NT implements most of these features. When running your application under Windows 3.1 (with the Win32s DLLs), these techniques can aid in debugging. Windows 95 also implements and extends the robustness features put in place during Windows 3.1. Running the debug version of Windows 95 is the best way to insure your application is running cleanly.

Windows 3.1 is a major improvement over Windows 3.0 in the area of robust application development. Windows 3.1 includes a number of new features that enhance the reliability of a Windows application. This technical note describes the use of these features within the MFC library.

These features include the debug kernel, STRICT type checking, diagnostics and memory management, and the WINDOWSX.H enhancements.

Windows 3.1 Debug Kernel

Note This section applies only to the Microsoft Visual C++ version 1.5.

Testing your MFC application with the debug system executables is probably the best thing you can do to make sure your applications are robust and reliable. The debugging versions of the system executables perform all sorts of useful error checking for you, informing you of any problems that arise with debug output messages.

The best way to use the debug system is with two machines: a machine for testing and debugging that has the debug system installed and a machine for development. One machine, your test machine, should always run with the debug kernel. The other machine, your development machine, should run with the non-debug kernel. The output from the debug kernel can be sent to the primary machine over a null modem line. If you have only a single machine, then you should be sure to run the debug kernel (there is a slight performance degradation). The output from the debug kernel can be routed to DBWIN, a tool included with the Microsoft Visual C++ version 1.5. In addition, the Visual C++ Output window will receive output when running under the debugger.

A useful trick for single-machine debugging is to place copies of the system and debug binaries and symbols in a separate directory and to have batch files that copy the appropriate files to your Windows System directory. This way you can exit Windows and switch back and forth quickly between debug and non-debug. The Visual C++ version 1.5 installation program will set this up, then you can switch between debug and non-debug version of Windows with the D2N.BAT and N2D.BAT batch files.

If you aren't running with a debugger or a debug terminal, you should run the DBWIN application so you can see the error and warning messages produced by the debug system. This application is included with the Visual C++ version 1.5.

Below are some common programming errors that appear frequently in shipped Windows applications. Many of these problems can cause random system UAEs and other problems under Windows 3.0. The debug system binaries will help you track down problems, such as:

  • Passing invalid parameters of all shapes and sizes.

  • Accessing nonexistent window words. In Windows 3.0, a SetWindowWord or SetWindowLong call past the end of the allocated window words (as defined with RegisterClass) would trash internal window manager data structures!

  • Using handles after they've been deleted or destroyed.

  • Using a device context (DC) after it has been released.

  • Deleting Graphics Device Interface (GDI) objects before they're deselected from a DC.

  • Forgetting to delete GDI bitmaps, brushes, pens, or other GDI or USER objects when an application terminates.

  • Writing past the end of an allocated memory block.

  • Reading or writing through a memory pointer after it has been freed.

  • Forgetting to export window procedures and other callbacks.

  • Forgetting to use MakeProcInstance with dialog procs and other callbacks. (The suggested technique is to make use of Microsoft C/C++ feature of marking these functions as EXPORT in their definition.)

  • Shipping an application without running it with the debugging KERNEL, USER, and GDI.

MFC Diagnostics

In addition, the Microsoft Foundation Classes ship with a set of robustness features that are compiled and linked only in the debug build of the library (those library variants ending with a 'D'). Use of these features in the applications you write and in the classes you design will greatly improve both the runtime and compile time error trapping of your application. These functions are outlined below, but all are documented in the Class Library Reference manual.

Every class derived from CObject in MFC implements a Dump member function, which permits you to view the state of an object in an ASCII format. This function can be called from the debugger or placed within #ifdef _DEBUG /#endif portions of your code. A helper function AfxDump is included in the debug library just for this purpose. It is called with a single parameter, a CObject*. You can call this function from the debugger to print out the argument. You should supply a Dump member for classes that you implement. As with AssertValid, you should first explicitly call your base class Dump member function. The output of Dump is routed to the standard MFC CDumpContext, afxDump, which by default goes to the debugger output window or to your debug terminal. You can also use the DBWIN program to view the output of afxDump. The source file MFC\SRC\DUMPINIT.CPP includes information on how to route afxDump to another destination.

TRACE, a macro that behaves much like printf, only routes output to the afxDump location. You should use TRACE statements to indicate tricky or exceptional places in your code. As with other robustness features, TRACE is only meaningful in the debug library, and has no effect in the retail build. The MFC library includes a number of built in TRACE statements for tracking the flow of messages. Please see Technical Note 7 for more information on debug trace.

ASSERT is a run-time check for the validity of a statement. You should use ASSERTs liberally throughout your program. Any place you have a comment to the effect:

// lpStr should be NULL at this point

you should replace that with a run-time assert:

ASSERT(lpStr == NULL);

The compiler cannot understand the comment, but it can evaluate the expression in the assertion macro. ASSERT statements have no effect in retails builds. If you need the information from ASSERT in the retail build, then use the VERIFY macro.

MFC also includes an extensive diagnostic memory allocator. You use the diagnostic memory allocator to check that you free all memory resources during certain program functions. The diagnostic allocator will track the source file and line number of an allocation, so if you use the CMemoryState::DumpAllObjectsSince API, you can locate any allocations that remain.

By default, MFC will dump all objects not freed by your program (if there are any) before your program exits. You can view this output by running your application under the debugger.

Windows 3.1 STRICT Type Checking

STRICT type checking is an option available with the WINDOWS.H header file. MFC uses these STRICT types by default, and you must use them if you are building an MFC application. MFC no longer supports building an application without the STRICT defintions.

Typesafe Linkage and STRICT

In C++ you are permitted to have many functions with the same name, as long as these functions have different formal parameter lists. In order to have unique link symbols, the C++ compiler will "decorate" these names using an algorithm that encodes information about a function such as the name, number, and type of formal parameters, calling convention, etc.

This newly generated name is used as the external link symbol for the function. This is known as typesafe linkage and is a big benefit of C++. This name decoration does not apply to functions within an extern "C" block, and that is why all APIs in WINDOWS.H are in such a block.

STRICT type checking in WINDOWS.H enhances type safety for Windows programs by using distinct types to represent all the different HANDLES in Windows. So for example, STRICT prevents you from mistakenly passing an HPEN to a routine expecting an HBITMAP.

Since the Windows APIs are all within extern "C" { } blocks, they are not decorated in the manner described above. STRICT changes the types of the various Windows typedefs to make them unique (specifically it uses different pointer types to represent HANDLEs, which cannot be freely converted without an explicit cast).

As you can see, if you have STRICT type checking enabled in one file, but not in another, the C++ compiler will generate different external link symbols for a single function. This will result in link-time errors. Therefore, it is recommended that you use STRICT type checking only for C modules (those that end in .C). Additionally, STRICT is a compile-time only option, so once you successfully compile your code, the benefits of STRICT are completely realized.

If you are mixing STRICT and non-STRICT code, you must be aware of linkage inconsistencies. In general, all MFC programming and all C++ should be done with STRICT. If you have legacy C code, then not using STRICT is acceptable.

Windows 3.1 WINDOWSX.H Header File

New with Windows 3.1 and Win32 is the WINDOWSX.H header file that supports various extensions to the C-coding style for Windows programmers using C. These macro APIs, message crackers, and control APIs are defined in the file WINDOWSX.H.

This syntax is primarily designed for C programmers. MFC supports the use of WINDOWSX.H, so if you have existing code that relies on these tensions, use this code unmodified in MFC. You will find, however, that MFC has comparable idioms for all of the features of WINDOWSX.H, and uses the C++ language to accomplish these tasks with more semantic and architectural safety.

To use WINDOWSX.H, be sure to #include it before you have included AFXWIN.H (or STDAFX.H if you are using the AppWizard structure).

The only caveat is that there are two WINDOWSX.H APIs that collide with the MFC C++ APIs. The two APIs SubclassWindow and CopyRgn are not available for use within MFC. You will need to recode these to use either the MFC API (and classes) or to call the Windows API directly. You can also code your own macro as long as it has a different name.


TN014: Custom Controls

This note describes the MFC Support for custom and self-drawing controls. Dynamic subclassing is also described. General advice on ownership of CWnd objects vs. HWNDs is presented.

The MFC sample application CTRLTEST illustrates many of these features. Please refer to the source code for the MFC General sample CTRLTEST and online help.

Owner-Draw Controls/Menus

Windows provides support for "owner draw" controls and menus. These are Windows messages sent to a parent window of a control or menu that allow you to customize the visual appearance and behavior of the control or menu.

MFC directly supports owner draw with the message map entries:

  • CWnd::OnDrawItem

  • CWnd::OnMeasureItem

  • CWnd::OnCompareItem

  • CWnd::OnDeleteItem

You can override these in your CWnd-derived class (usually a dialog or main frame window) to implement the owner-draw behavior.

This approach does not lead to reusable code. If you have two similar controls in two different dialogs, you must implement the custom control behavior in two places. The MFC-supported self-drawing control architecture solves this problem.

Self-Drawing Controls and Menus

MFC provides a default implementation (in CWnd and CMenu) for the standard owner-draw messages. This default implementation will decode the owner-draw parameters and delegate the owner-draw messages to the controls or menu. This is called "self-draw" since the drawing (/measuring/comparing) code is in the class of the control or menu, not in the owner window.

This allows you to build reusable control classes that display the control using "owner draw" semantics. The code for drawing the control, not the owner of the control, is in the control class. This is an object-oriented approach to custom control programming.

  • For self-draw buttons:
    CButton:DrawItem(LPDRAWITEMSTRUCT);
        // draw this button
  • For self-draw menus:
    CMenu:MeasureItem(LPMEASUREITEMSTRUCT);
        // measure the size of an item in this menu
CMenu:DrawItem(LPDRAWITEMSTRUCT);
        // draw an item in this menu
  • For self-draw list boxes:
    CListBox:MeasureItem(LPMEASUREITEMSTRUCT);
        // measure the size of an item in this list box
CListBox:DrawItem(LPDRAWITEMSTRUCT);
        // draw an item in this list box

CListBox:CompareItem(LPCOMPAREITEMSTRUCT);
        // compare two items in this list box if LBS_SORT
CListBox:DeleteItem(LPDELETEITEMSTRUCT);
        // delete an item from this list box
  • For self-draw combo boxes:
    CComboBox:MeasureItem(LPMEASUREITEMSTRUCT);
        // measure the size of an item in this combo box
CComboBox:DrawItem(LPDRAWITEMSTRUCT);
        // draw an item in this combo box

CComboBox:CompareItem(LPCOMPAREITEMSTRUCT);
        // compare two items in this combo box if CBS_SORT
CComboBox:DeleteItem(LPDELETEITEMSTRUCT);
        // delete an item from this combo box

For details on the owner-draw structures (DRAWITEMSTRUCT, MEASUREITEMSTRUCT, COMPAREITEMSTRUCT, and DELETEITEMSTRUCT) refer to the MFC documentation for CWnd::OnDrawItem, CWnd::OnMeasureItem, CWnd::OnCompareItem, and CWnd::OnDeleteItem respectively.

Using self-drawing controls and menus

For self-drawing menus, you must override both MeasureItem and DrawItem member functions.

For self-drawing list boxes and combo boxes, you must override MeasureItem and DrawItem. You must specify the OWNERDRAWVARIABLE style in the dialog template (LBS_OWNERDRAWVARIABLE and CBS_OWNERDRAWVARIABLE respectively). The OWNERDRAWFIXED style will not work with self-drawing items since the fixed item height is determined before self-drawing controls are attached to the list box. (The Win 3.1 member functions CListBox::SetItemHeight and CComboBox::SetItemHeight can be used to get around this limitation.)

In addition, note that switching to an OWNERDRAWVARIABLE style will affect the NOINTEGRALHEIGHT style. Because the control can not calculate an integral height with variable sized items, the default style of INTEGRALHEIGHT is ignored and the control is always NOINTEGRALHEIGHT. If your items are fixed height, you can prevent partial items from being drawn by specifying the control size to be an integral multiplier of the item size.

For self-drawing list boxes and combo boxes with the SORT style (LBS_SORT and CBS_SORT respectively), you must override the CompareItem member function.

For self-drawing list boxes and combo boxes, DeleteItem is not normally overridden. DeleteItem can be overridden if additional memory or other resources are stored with each list box or combo box item.

Examples of Self-Drawing Controls/Menus

The MFC General sample CTRLTEST provides samples of a self-draw menu (showing colors) and a self-draw list box (also showing colors).

The most typical example of a self-drawing button is a bitmap button (a button that shows one, two, or three bitmap images for the different states). This is provided in the MFC class CBitmapButton.

Dynamic Subclassing

Subclassing is the Windows term for replacing the WndProc of a window with a different WndProc and calling the old WndProc for default (superclass) functionality.

This should not be confused with C++ class derivation (C++ terminology uses the words "base" and "derived" while the Windows object model uses "super" and "sub"). C++ derivation with MFC and Windows subclassing are functionally very similar, except C++ does not support a feature similar to dynamic subclassing.

The CWnd class provides the connection between a C++ object (derived from CWnd) and a Windows window object (also known as an HWND).

There are three common ways these are related:

  • CWnd creates the HWND. The behavior can be modified in a derived class. "Class derivation" is done by creating a class derived from CWnd and created with calls to Create.

  • CWnd gets attached to an existing HWND. The behavior of the existing window is not modified. This is a case of "delegation" and is made possible by calling Attach to alias an existing HWND to a CWnd C++ object.

  • CWnd gets attached to an existing HWND and you can modify the behavior in a derived class. This is called "dynamic subclassing," since we are changing the behavior (and hence the class) of a Windows object at run time.

This last case is done with the member functions:

  • CWnd::SubclassWindow

  • CWnd::SubclassDlgItem.

Both routines attach a CWnd object to an existing Windows HWND. SubclassWindow takes the HWND directly, and SubclassDlgItem is a helper that takes a control ID and the parent window (usually a dialog). SubclassDlgItem is designed for attaching C++ objects to dialog controls created from a dialog template.

Please refer to the CTRLTEST example for several examples of when to use SubclassWindow and SubclassDlgItem.


TN015: Windows for Pen Computing

The MFC 2.0 product for Windows 3.1 supports the Windows for Pen Computing environment that is available as an add-on to Windows 3.1. MFC 4.0 and later versions do not support the Pen Computing add-on to Windows 3.1, but do support Pen Computing on Windows 95. Windows NT does not yet provide the Windows for Pen Computing environment.


TN016: Using C++ Multiple Inheritance with MFC

This note describes how to use Multiple Inheritance (MI) with the Microsoft Foundation Classes.

Why Multiple Inheritance?

There is an ongoing debate in the C++ and object-oriented communities over the value of MI. The Visual C++ compiler and development environment fully supports MI.

The MFC class library has been designed so that you do not need to understand MI to use MFC. MI is not used in any of the MFC classes. We have found that MI is not required to write a class library, nor is it required for writing serious applications. To use MI or not can be a personal decision, so we leave that decision to you.

So You Want to Use MI?

If you already understand how to use MI, understand the performance trade-offs, and want to use MFC, this technote will tell you what you must do. Some of the restrictions are general C++ restrictions, others are imposed by the MFC architecture.

The following describes some of the technical issues of how MI affect the use of common MFC idioms. At the end of this technical note a complete MFC application using MI is included which you can extract and compile.

CRuntimeClass

The persistence and dynamic object creation mechanisms of MFC use the CRuntimeClass data structure to uniquely identify classes. MFC associates one structure of this type with each dynamic and/or serializable class in the application. These structures are initialized at application startup time using a special static object of type AFX_CLASSINIT. You need not concern yourself with the implementation of this information, as it is likely to change between revisions of MFC.

The current implementation of CRuntimeClass does not support Multiple Inheritance runtime type information. This does not mean you cannot use MI in your MFC application, but if you do, you will have certain responsibilities when working with objects that have more than one base class.

The CObject::IsKindOf member function will not correctly determine the type of an object if it has multiple base classes. Therefore, you cannot use CObject as a virtual base class, and all calls to CObject member functions such as Serialize and operator new will need to have scope qualifiers so that C++ can disambiguate the appropriate function call. If you do find the need to use MI within MFC, then you should be sure to make the class containing the CObject base class the left-most class in the list of base classes.

For advice on the uses and abuses of MI, see Advanced C++ Programming Styles and Idioms by James O. Coplien (Addison Wesley, 1992).

CObject - The Root of all Classes

As you know, all significant classes derive directly or indirectly from class CObject. CObject does not have any member data, but does have some default functionality. When using MI, it will be common to inherit from two or more CObject-derived classes, for example, a CFrameWnd and a CObList:

class CListWnd : public CFrameWnd, public CObList
{
 ...
};
CListWnd myListWnd;

In this case CObject is included twice, which leads to two problems:

  • Any reference to CObject member functions must be disambiguated.
    myListWnd.Dump(afxDump);
    // compile time error, CFrameWnd::Dump or CObList::Dump ?
  • Static member functions, including 'operator new' and 'operator delete' must also be disambiguated.

Recommended Steps

When creating a new class with two or more CObject derived base classes, reimplement those CObject member that you expect people to use. Operators new and delete are mandatory, Dump is recommended. For example:

class CListWnd : public CFrameWnd, public CObList
{
public:
    void* operator new(size_t nSize)
        { return CFrameWnd::operator new(nSize); }
    void operator delete(void* p)
        { CFrameWnd::operator delete(p); }

    void Dump(CDumpContent& dc)
        { CFrameWnd::Dump(dc);
          CObList::Dump(dc); }
     ...
};

Virtual Inheritance of CObject ?

You may ask, "If you inherit CObject virtually, won't all of the ambiguity problems go away?".

Even in the efficient Microsoft Object Model, virtual inheritance is not as efficient as non-virtual inheritance (just as Multiple Inheritance is not as efficient as single inheritance in certain cases). Since there is no member data in CObject, virtual inheritance is not needed to prevent multiple copies of a base class's member data.

The real answer is no, virtual inheritance will not solve the ambiguity problems illustrated above. For example: the Dump virtual member function is still ambiguous (since CFrameWnd and CObList implement it differently).

Therefore we recommend following the steps above to provide disambiguation:

CObject::IsKindOf and Run-time Typing

The runtime typing mechanism supported by MFC in CObject uses the macros DECLARE_DYNAMIC, IMPLEMENT_DYNAMIC, DECLARE_DYNCREATE, IMPLEMENT_DYNCREATE, DECLARE_SERIAL and IMPLEMENT_SERIAL. These give the ability to do a run-time type check to allow for safe cast-downs.

These macros only support a single base class and will work in a limited way for multiply inherited classes. The base class you specify in IMPLEMENT_DYNAMIC or IMPLEMENT_SERIAL should be the first (or left-most) base class. For example,

class CListWnd : public CFrameWnd, public CObList
{
    DECLARE_DYNAMIC(CListWnd)
    ...
};
IMPLEMENT_DYNAMIC(CListWnd, CFrameWnd)

This will allow you to do type checking for the left-most base class only. The run-time type system will know nothing about additional bases (CObList in this case).

CWnd and Message Maps

In order for the MFC message map system to work correctly, there are two additional requirements:

  • There must be only one CWnd-derived base class.

  • The CWnd-derived base class must be the first (or left-most) base class.

In the example above, CFrameWnd is the first base class.

Some examples that will not work:

class CTwoWindows : public CFrameWnd, public CEdit
    { ... };
        // error : two copies of CWnd

class CListEdit : public CObList, public CEdit
    { ... };
        // error : CEdit (derived from CWnd) must be first

A Sample Program using MI

The following sample is a stand-alone application that consists of one class derived from CFrameWnd and CWinApp. This way of structuring an application is not a recommended, but this is an example of the smallest MFC application with one class.

You can cut the following program and copy it on top of HELLOAPP.CPP in the single-inheritance MFC General sample HELLOAPP. Then build the program as you would normally.

#include <afxwin.h>

class CHelloAppAndFrame : public CFrameWnd, public CWinApp
{
public:
    CHelloAppAndFrame()
        { }

    // Necessary evil for MI disambiguity
    void* operator new(size_t nSize)
        { return CFrameWnd::operator new(nSize); }
    void operator delete(void* p)
        { CFrameWnd::operator delete(p); }

// Implementation
    // CWinApp overrides
    virtual BOOL InitInstance();
    // CFrameWnd overrides
    virtual void PostNcDestroy();
    afx_msg void OnPaint();

    DECLARE_MESSAGE_MAP()

};

BEGIN_MESSAGE_MAP(CHelloAppAndFrame, CFrameWnd)
    ON_WM_PAINT()
END_MESSAGE_MAP()

// since the frame window is not allocated on the heap, we must
// override PostNCDestroy not to delete the frame object
void CHelloAppAndFrame::PostNcDestroy()
{
    // do nothing (do not call base class)
}

void CHelloAppAndFrame::OnPaint()
{
    CPaintDC dc(this);
    CRect rect;
    GetClientRect(rect);

    CString s = "Hello, Windows!";
    dc.SetTextAlign(TA_BASELINE | TA_CENTER);
    dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT));
    dc.SetBkMode(TRANSPARENT);
    dc.TextOut(rect.right / 2, rect.bottom / 2, s);
}

// Application initialization
BOOL CHelloAppAndFrame::InitInstance()
{
    // first create the main frame
    if (!CFrameWnd::Create(NULL, "Multiple Inheritance Sample",
        WS_OVERLAPPEDWINDOW, rectDefault))
        return FALSE;

    // the application object is also a frame window
    m_pMainWnd = this;
    ShowWindow(m_nCmdShow);
    return TRUE;
}

CHelloAppAndFrame theHelloAppAndFrame;


TN017: Destroying Window Objects

This note describes the use of the CWnd::PostNcDestroy member function. Use this function if you wish to do customized allocation of CWnd-derived objects.

This note also explains some of the reasons for the cardinal rule:

To destroy a C++ Windows object, use DestroyWindow not "delete".

This is important. If you follow the guidelines below, you will have few cleanup problems (such as forgetting to delete/free C++ memory, forgetting to free system resources like HWNDs, or freeing objects too many times).

The Problem

Windows objects (objects of classes derived from CWnd) represent both a C++ object (allocated in the application's heap) and an HWND (allocated in system resources by the window manager). Since there are several ways to destroy a window object, we must provide a set of rules that prevent system resource or application memory leaks and that prevent objects and Windows handles from being destroyed more than once.

This is more than a memory management problem. The presence of a Windows window has user-interface impact: a window drawn on the screen; once it is destroyed there is also an impact on system resources. Leaking C++ memory in your application address space is not as bad as leaking system resources.

Destroying Windows

The two permitted ways to destroy a Windows object are:

  • Calling CWnd::DestroyWindow or the Windows API ::DestroyWindow.

  • Explicit deletion with the delete operator.

The first case is by far the most common. This case applies even if DestroyWindow is not called directly by your code. The is the case when the user directly closes a frame window (the default WM_CLOSE behavior is to call DestroyWindow), and when a parent window is destroyed, Windows calls DestroyWindow for all the children.

The second case, the use of the delete operator on Windows objects, should be very rare and only in the cases outlined below.

Auto Cleanup with CWnd::PostNcDestroy

When destroying a Windows window, the last Windows message sent to the window is WM_NCDESTROY. The default CWnd handler for that message (CWnd::OnNcDestroy) will detach the HWND from the C++ object and call the virtual function PostNcDestroy. Some classes override this function to delete the C++ object.

The default implementation of CWnd::PostNcDestroy does nothing which is appropriate for window objects allocated on the stack frame or embedded in other objects. This is not appropriate for window objects that are designed to be allocated by themselves on the heap (not embedded in other C++ object).

Those classes that are designed to be allocated by themselves on the heap override the PostNcDestroy member function to perform a "delete this". This statement will free any C++ memory associated with the C++ object. Even though the default CWnd destructor calls DestroyWindow if m_hWnd is non-NULL, this does not lead to infinite recursion since the handle will be detached and NULL during the cleanup phase.

Note CWnd::PostNcDestroy is normally called after the Windows WM_NCDESTROY message is processed, as part of window destruction, and the HWND and the C++ window object are no longer attached. CWnd::PostNcDestroy will also be called in the implementation of most Create calls if failure occurs (see below for auto cleanup rules).

Auto Cleanup Classes

The following classes are not designed for auto-cleanup. They are normally embedded in other C++ object or on the stack:

  • All the standard Windows controls (CStatic, CEdit, CListBox, and so on).

  • Any child windows derived directly from CWnd (for example, custom controls)

  • Splitter windows (CSplitterWnd)

  • Default control bars (classes derived from CControlBar, see Technical Note 31 for enabling auto-delete for control bar objects)

  • Dialogs (CDialog) - designed for modal dialogs on the stack frame

  • All the standard dialogs except CFindReplaceDialog

  • The default dialogs created by ClassWizard

The following classes are designed for auto-cleanup. They are normally allocated by themselves on the heap:

  • Main frame windows (derived directly or indirectly from CFrameWnd)

  • View windows (derived directly or indirectly from CView)

If you wish to break any of these rules, you must override the PostNcDestroy member function in your derived class. To add auto-cleanup to your class, simply call your base class and then do a delete this. To remove auto-cleanup from your class, call CWnd::PostNcDestroy directly instead of the PostNcDestroy member in your direct base class.

The most common use of the above is to create a modeless dialog that can be allocated on the heap.

When to Call 'delete'

The recommended way to destroy a Windows object is to call DestroyWindow, either the C++ member function or the global ::DestroyWindow API.

Do not call the global ::DestroyWindow API to destroy an MDI Child window, use the virtual member function CWnd::DestroyWindow instead.

For C++ Window objects that don't perform auto-cleanup, using DestroyWindow instead of delete avoids problems of having to call DestroyWindow in the CWnd::~CWnd destructor where the VTBL is not pointing to the correctly derived class. This can lead to subtle bugs so the diagnostic (debug) version of MFC will warn you with

Warning: calling DestroyWindow in CWnd::~CWnd
   OnDestroy or PostNcDestroy in derived class will not be called

In the case of C++ Windows objects that do perform auto-cleanup, you must call DestroyWindow. If you use operator delete directly, the MFC diagnostic memory allocator will alert you that you are freeing memory twice (the first call to delete as well as the indirect call to "delete this" in the auto-cleanup implementation of PostNcDestroy).

After calling DestroyWindow on a non-auto-cleanup object, the C++ object will still be around, but m_hWnd will be NULL. After calling DestroyWindow on an auto-cleanup object, the C++ object will be gone, freed by the C++ delete operator in the auto-cleanup implementation of PostNcDestroy..


TN018: Migrating OLE Applications from MFC 1.0 to MFC 2.0

This technical note provided guidelines for migrating MFC version 1 applications that use MFC/OLE to MFC 2.0. This version of MFC does not support OLE 1.0. OLE 1.0 support has been replaced by OLE 2.0 support. For more information about migrating your MFC/OLE1 application to MFC/OLE2 see Technical Note 41.


TN019: Updating existing MFC Applications to MFC 3.0

This technical note primarily provides guidelines for migrating MFC 1.0 applications to the MFC 2.0 tools. Additional differences between MFC 2.0, 2.5, and 3.0 are presented in the first section, below.

MFC 4.0/3.0 API Changes

There are no known changes to the documented MFC APIs that would cause existing code to require changes. There are, of course, many additional features you may want to take advantage of. For more information on these features, see Visual C++ Programmer's Guide.

MFC 2.5 API Changes

MFC 2.5 added two major features to the class library: OLE 2.0 support, which replaced the OLE 1.0 support and ODBC support which provides database access. It is the intention of this technote to cover the API changes that may affect your existing code. For information about these new features, not covered in this technote, see Visual C++ Programmer's Guide.

CFrameWnd::RecalcLayout has an additional parameter, BOOL bNotify. This specifies whether or not to notify any OLE servers that they layout has changed. It is normally TRUE and therefore that is the default. This function is virtual, so if your program provides an override of this function you will need to add the extra parameter to your function as well.

There were other changes made to undocumented functions in the MFC 2.5 libraries to support OLE 2.0 as well as ODBC. If your program uses undocumented MFC APIs, you should review all such uses to make sure they are still valid.

Migrating MFC 1.0 Applications to MFC 2.0

IMPORTANT: To understand and evaluate the two approaches presented below, you must be familiar with MFC 2.0 concepts, such as the Document and View architecture, and the tools. We suggest you at least work through the MFC Tutorial sample SCRIBBLE in Tutorials before beginning any migration of existing code.

There are two basic approaches to migrating existing applications from MFC version 1, released with Microsoft C7, to MFC version 2.

Minimal Migration

Using the "Minimal Migration" method, you make only the minimum changes required, so that:

  • Your existing MFC 1.0 application compiles and links successfully with the MFC 2.0 libraries.

  • Your resources can be successfully edited using Visual C++.

  • Your message handler functions and dialog data are recognized by ClassWizard.

This is the easiest approach, but it does not take full advantage of the rich features in the MFC 2.0 library. Even if you chose the "Full Migration" method, you will need to understand and exercise techniques for minimal migration.

Full Migration

If you perform a "Full Migration", you can take full advantage of the MFC 2.0 library. Using the minimal migration method, you will be able to edit your application using Visual C++ and ClassWizard. By using the full migration method, you gain the following MFC 2.0 support:

  • Standard File menu and dialog user interfaces. You get features such as standard file open and save dialogs, file manager, drag-and-drop, most-recently-used File menu interface, and so on.

  • Printing. You supply the view code; the library takes care of getting the printer DC, putting up the abort dialog, running the print loop, and so on.

  • Print Preview. Usually, you will have to do no extra coding to have Print Preview functionality in your application.

  • Toolbars and status bars. They are now easy to add to your application using Visual C++ and MFC 2.0.

  • Splitter windows. If you structure your display code into view classes, then you'll be able to display them in splitter windows at very little additional cost.

  • OLE2 support. By utilizing the "Document/View" architecture your application can probably be OLE enabled without a significant amount of work.

The overall full migration method is basically to emulate developing an MFC 2.0 application from scratch, starting with AppWizard. The difference from developing an MFC 2.0 application from scratch, of course, is that you will borrow as much of the MFC 1.0 code you wrote as makes sense.

Minimal Migration

The following subsections present detailed guidelines for performing a minimal migration.

Conforming to Windows 3.1 STRICT typedefs

The default builds of the MFC 2.0 library adhere to the Windows 3.1 STRICT typedefs which are explained in the Windows 3.1 SDK. MFC 1.0 had STRICT turned off, but now MFC 2.0 has STRICT turned on by default. This follows MFC's commitment to track the industry standard Windows API and to foster development practices that make developing robust applications easier. Just as the STRICT typedefs were helpful to the developers of the MFC 2.0 classes to produce robust software, so will that be true for you in developing your application code.

When using STRICT type checking for the first time, many compilation errors will typically result. Modifying your MFC 1.0 application to conform to Windows 3.1 STRICT typedefs may very well represent the bulk of your minimal migration effort.

Once your application complies with STRICT, you may be able to compile an executable with no further changes. For example, the ABOUT2 and FILEVIEW MFC 1.0 samples compile with no additional changes. They were already STRICT compliant and did not used any changed MFC APIs.

MFC 2.0 API Changes

Beyond conforming to STRICT, most of the effort of doing a minimal migration is to identify and change your application code to conform to the relatively few MFC 2.0 API changes.

Out of over 1800 MFC 1.0 APIs, only 20 of the APIs that were changed result in compile-time errors. These changes require only trivial modifications to existing MFC 1.0 applications. The most extensive changes are the architectural restructuring of the OLE classes. These changes are covered in Technical Note 18.

To anticipate which changes you'll need to make, see the section "Alphabetical API Changes" at the end of this technote. It provides a useful, brief summary of which MFC 1.0 APIs were modified in MFC 2.0.

If you do not make all the changes necessary to deal with MFC 2.0 code, you will get various compilation and linking errors. These errors are almost always easy to diagnose. To aid your diagnosis, we provide some guidelines in the section "Compiler Errors" at the end of this technote.

The following MFC APIs have been removed in MFC 2.0. We recommend alternative APIs where appropriate. This list does not include changes to undocumented implementation APIs.

CDC::GetDCOrg

GetDCOrg is not available in Win32. For Windows 3.x only applications, just call the Windows API ::GetDCOrg directly.

CRuntimeClass::m_pszClassName

This member variable is now an LPSTR rather than the memory model-dependent (char*). It is named m_lpszClassName in MFC 2.0.

CMDIChildWnd::m_pMDIFrameWnd

In MFC 1.0, this member variable pointed to the class's MDIFrame parent. This member variable has been replaced with a member function CMDIChildWnd::GetMDIFrame. If you are using multiple document interface (MDI) in MFC 2.0, most uses CMDIChildWnd::m_pMDIFrameWnd (or GetMDIFrame) are no longer necessary since the default MDI support handles all of the standard MDI Windows menu commands.

CFrameWnd::GetChildFrame

Use CMDIFrameWnd::MDIGetActive for MDI frames instead.

The following API has been left in MFC 2.0 to support 1 compatibility but is obsolete. It will be removed from future versions of MFC.

CMDIFrameWnd::CreateClient

This functionality has been replaced by the more general OnCreateClient mechanism that supports view creation and the improved MFC 2.0 MDI support. The original CreateClient can still be used for MDI applications that manage their own MDI frame window's menu bar (by using CMDIFrame::MDISetMenu). The MFC 2.0 MDI support will automatically switch the MDI frame window's menu bar to the menu for the currently active MDI child window.

Other API-related Changes

Two MFC classes have been moved from the afxwin.h to the afxext.h header file:

  • CBitmapButton

  • CMetaFileDC

In your .cpp files that reference these classes add the following:

#include <afxext.h>

Many APIs have been changed so that they are stricter about the use of the 'const' modifier. These changes result in a more consistent use of the LPCSTR type name and the new LPCRECT type name. Note, there is no compile time issue with these changes, since any type can be promoted to a const version of that type when used as an argument. Like the STRICT change, this leads to more robust code when your code uses const data pointers.

The window Create functions listed below now have an additional parameter, but since the last parameter has a default value of NULL, existing code will work without modification. These functions are

  • CWnd::Create

  • CFrameWnd::Create

  • CMDIFrameWnd::Create

  • CMDIChildWnd::Create

The following functions were virtual in MFC 1.0 but are now nonvirtual in MFC 2.0:

  • CFile::GetStatus

  • CFrameWnd::GetParentFrame

If a derived class of your MFC 1.0 application overrides either of these functions, it is unlikely that the function in your derived class will be called in MFC 2.0. In addition, GetParentFrame was moved from CFrameWnd to CWnd to be a more generally useful API.

All static members of classes, as well as global operator/friend functions, now adhere to PASCAL calling conventions. All global functions are AFXAPI (PASCAL). Again, this is not a compile time issue but leads to faster and smaller generated code.

Many of the implementation-only classes and structures have been renamed to not use the 'C' prefix. For example, CExceptionContext has been renamed to AFX_EXCEPTION_CONTEXT. These classes are not documented and remain implementation details of the class library. It is unlikely that you have relied on these, and it is generally recommended that you do not rely on undocumented APIs of the class library since they are subject to change in future versions.

MFC 2.0 Default Behavior Changes

Dealing with MFC API changes is easy with the aid of errors reported by the compiler and linker. Not all library changes are revealed in the library header files, however. Some changes are revealed in run-time behavior of your application. These changes are generally not difficult to deal with, as long as you anticipate them. The following information is provided to help you anticipate such behavioral changes.

CDialog and CModalDialog have been merged into a single class. CModalDialog is now considered to be an obsolete class. However, for MFC 1.0 compatibility, all references to CModalDialog are still valid through a migration macro in afxwin.h:

#define CModalDialog CDialog

For many MFC 1.0 applications, this simple #define is sufficient. However, there are cases where this #define is not sufficient.

If you implemented a modeless dialog and relied on the default "do nothing" behavior for OnOK and OnCancel, then you must override these and the default behavior, since they now call EndDialog (for modal dialog processing).

CDialog::CreateIndirect still creates a modeless dialog. To create a modal dialog use CDialog::InitModalIndirect instead of the removed CModalDialog::CreateIndirect API.

Dialog box and message box background colors can now be globally set using the CWinApp::SetDialogBkColor API. The default parameter sets the color to light gray (not COLOR_BTNFACE) to produce gray backgrounds. You may specify other colors.

If SetDialogBkColor is not called in your CWinApp-derived InitInstance function, the default Window Background color (set in the Control Panel Color applet) is used.

In MFC 1.0, if a DLL contained a CWinApp object, it was necessary to provide a DllMain that included a call to AfxWinTerm. MFC 2.0 provides this DllMain, so any additional code included in the your DllMain should be migrated to the DLL's CWinApp::ExitInstance member function.

CMDIChildWnd::Create now correctly uses the dwStyle parameter. You must now specify a complete window style for the MDI child window. If you specify dwStyle = 0, you will now get an ASSERT failure in CMDIChildWnd::PreCreateWindow. To avoid this, you should specify the style WS_CHILD | WS_VISIBLE | WS_OVERLAPPEDWINDOW to be backward compatible with MFC 1.0.

MFC 2.0 supports setting different styles for MDI child windows, so you can remove some of the frame window controls, if desired.

Class CFrameWnd has a new data member, BOOL CFrameWnd::m_bAutoMenuEnable. It is set to TRUE by default. This causes menu items that don't have ON_UPDATE_COMMAND_UI or ON_COMMAND handlers to be automatically disabled. Menu items that have ON_COMMAND handlers, but no ON_UPDATE_COMMAND_UI handlers, will be automatically enabled.

This makes it easy to implement optional commands based on the current selection. Also, this greatly reduces the need for applications to write ON_UPDATE_COMMAND_UI handlers for enable/disable of menu items. For instance, an AppWizard-generated application will have Edit Cut/Copy/Paste disabled until the programmer implements handlers for them.

However, if your MFC 1.0 application is not updated to use ON_COMMAND and ON_UPDATE_COMMAND_UI handlers, then it must clear m_bAutoMenuEnable explicitly. Otherwise, menus that you disable will be re-enabled automatically.

Project (Build) Changes

You can continue to build your MFC 1.0 application using a standard makefile. By far the easiest way to migrate your project is to use the Visual C++ project facility to maintain your depedencies and other project options within the Visual C++ environment.

A common link error is unresolved externals to COMDLG32.DLL and SHELL32.DLL APIs. Be sure to link with COMDLG32.LIB and SHELL32.LIB.

You may be able to improve build times by placing #include <afxwin.h> in a precompiled header. By convention, MFC 2.0 applications specify "stdafx.h" as the precompiled header. Then module stdafx.cpp includes stdafx.h. This technique is illustrated by the code created by AppWizard, and by many of the MFC 2.0 samples.

Note It is important that you neither define nor undefine any of the _AFX_NO_XXX macros in stdafx.h. See the Knowledge Base article "PRB: Problems Occur When Defining _AFX_NO_XXX." You can find Knowledge Base articles on the MSDN Library CD, or at http://www.microsoft.com/kb/.

Visual C++ and ClassWizard Compatibility

Even for minimal migration, we recommend that you follow the steps below so that you can use Visual C++ and ClassWizard to edit your application resources and code.

  • For any module whose message map you want to edit with ClassWizard, add the following two comment lines in your .cpp file outside of any function implementations:
    //{{AFX_MSG_MAP(<class name>)
//}}AFX_MSG_MAP

    <class name> is the name of your class containing the message map.

    Similarly, add the following two comment lines inside of the corresponding class declaration in your .h file:

    //{{AFX_MSG(<class name>)
//}}AFX_MSG

    For an example of these declarations, look at the same comment lines in any application created by AppWizard. For an explanation of what these comment lines mean, see MFC: Using the MFC Source Files in Visual C++ Programmer's Guide.

  • Your project must have a makefile named <project>.mak and a resource file named <project>.rc, where <project> is the name of your project. Both of these files must be located in the project's root directory. The .MAK file may be an external makefile.

  • Run ClassWizard from within Visual C++. When ClassWizard discovers that a .CLW file does not exist, it asks you if you want to create one. Respond 'yes'. The .CLW file is essentially an index file that ClassWizard uses to identify modules that have such //{{AFX_MSG comment lines.

  • For any module whose virtual functions you want to edit with ClassWizard, add the following two comment lines inside your class declaration in your .h file:
    //{{AFX_VIRTUAL(<class name>)
//}}AFX_VIRTUAL

Full Migration

A full migration of your existing C or MFC 1.0 application to MFC 2.0 will offer you all the advantages of MFC 2.0. For most applications, a full migration is not difficult and is well worth the effort.

A successful full migration of an application to MFC 2.0 requires essentially the same understanding of MFC 2.0 as developing a new application from scratch. You should become familiar with the MFC 2.0 Class Library, Visual C++, AppWizard, and ClassWizard before you begin the full migration. You should understand what portions of your application code can be removed by deriving equivalent or improved functionality from the MFC 2.0 classes. Not only will using more of the library implementation make your source code smaller, but it will make these parts of your application better integrated with the rest of the MFC framework.

By fully migrating your application to MFC 2.0, you will be able to derive additional functionality from MFC at relatively little extra cost. For example, if your application did not have a splitter window user interface, but one would be useful to your users, then you will be able to quickly add this feature, having already ported your code to MFC 2.0's document/view architecture.

Although a full migration to MFC 2.0 may require a couple days effort for large applications, the process itself is fairly straightforward. The following general steps describe the process:

  1. Analyze how your existing application architecture factors into document, views, and frame windows.

    Do this before you start editing any code. Many programmers tend to intertwine document code with view code. Although doing so is not necessarily "bad," separation of document and view functionality is a design philosophy that the MFC framework endorses and supports particularly well. Even though MFC 1.0 did not have CDocument and CView classes, it also endorsed document/view separation. So will all future versions of the library.

    Study the MFC 2.0 samples that use the CDocument and CView classes, particularly the MFC Tutorial Sample SCRIBBLE. Then analyze your application to determine what the document is and what the view is. Determine whether your application has multiple document types or views.

    Even if your application does not lend itself to clear document/view separation, you will still be able to fully migrate to MFC 2.0 and take essentially complete advantage of the framework. You can "fake" document/view separation by implementing CDocument- and CView-derived classes, but your document or view class may delegate most of its work to the other class. Or, your view class might rely on your CFrameWnd- or CMDIChildWnd-derived class to implement the bulk of your application's user interface. In summary, you have almost complete freedom as to how to separate your document, view, and frame window classes.

    Your analysis also should determine whether your application needs multiple view classes and possibly multiple document classes. Even relatively simple applications sometimes need more than one view class. However, multiple views, such as in a splitter window, don't necessarily dictate that you have multiple CView-derived classes. For example, if each pane in the splitter window provides the same user interface as other panes in the splitter window, then they can share the same view class. In that case, each pane is simply a distinct object of the same view class. You'll probably want to design multiple view classes, if your application provides very distinct user interfaces in different windows.

  2. Analyze what AppWizard-supported framework features your application will need.

    AppWizard will create a skeleton MFC 2.0 application that supports various framework features that you select as options in AppWizard dialogs. Before you run AppWizard to create your skeleton application, you should first become familiar with the options AppWizard provides.

    Then, take a little time to decide which of AppWizard's options you'll want to select. Don't attempt to do this in a few minutes the first time you run AppWizard. For example, if your application does not already support OLE, this is a major decision that you'll want to consider. If you didn't chose AppWizard's OLE option to begin with, you'll still be able to modify your application code to use MFC's OLE features. But starting with the OLE option in AppWizard to begin with will save you time.

    Your analysis should determine whether your application is a single document interface (SDI) or multiple document interface (MDI) application. This particular determination should be obvious if you're familiar with these two distinct user interfaces in other Windows applications. AppWizard will create MDI applications by default since the MDI user interface is usually more functional to end users for it lets them open more than one document/file at a time. Fortunately, with the MFC 2.0 document/view architecture, supporting MDI requires no extra coding on your part.

  3. Generate a new application using AppWizard.

    Having done the above analysis, you're now ready to run AppWizard to create the skeleton code for your application.

    Having analyzed how your application separates into document, views, and frame windows, you should have a good idea what names to give to their corresponding classes and modules. You might want to assign somewhat generic names, such as the tutorial sample's CScribDoc and CScribView, and scribdoc.cpp and scribvw.cpp. However, if your application requires multiple view classes, you'll probably want to give the first AppWizard-created view class a more specialized name, such as CDataEntryView and CReportView. See the next step for additional information on creating multiple document and view classes.

    Having anticipated what additional AppWizard options you want, such as SDI or MDI, and OLE, you should now be able to select the AppWizard options and create the skeleton application in just a few minutes.

  4. Optionally, clone second view, document, and frame window classes.

    If your above analysis determines that your application should have multiple view, document, or frame window classes, then it's a good time to create the skeleton code for these classes right after you run AppWizard.

    You can create the skeleton code for your additional view, document, and frame window classes by cloning the ones created by AppWizard. That is, copy the .cpp and .h files, assigning a new module name for the second document or class. Then edit the skeleton code by changing class names. Another alternative is to use the ClassWizard's Add Class functionality to create a new class automatically in the files you specify using the names you specify. You will already be familiar with the ClassWizard's ability to create new classes if you have followed the SCRIBBLE tutorial.

    In either case, in your CWinApp-derived class's InitInstance function, you must register additional document template objects for any associations that you want to make between you multiple document, view, and frame window classes.

    This is also a quick step. You can postpone this step if you're not committed to implementing multiple documents, views, or frame window classes in your application.

  5. Migrate the relevant portions of your MFC 1.0 code into the classes created by AppWizard.

    This step represents the bulk of the work in migrating your MFC 1.0 application to MFC 2.0. You should do this incrementally. Migrate relatively small chunks of your application at a time. As you do this, you'll learn more details about what functionality the framework provides that will allow you to discard some of your old MFC 1.0 application code.

    As you migrate these chunks of code, keep in mind the guidelines presented under "Minimal Migration". Many of those guidelines apply to full migration. AppWizard will have already added the //{{AFX_MSG and //{{AFX_MSG_MAP comments to your command target classes (application, document, view, and frame window). It is not necessary for you manually add these as under the minimal migration approach. Although it is not required, we recommend that you move message-handling functions between the //{{AFX_MSG comments nested in the message maps. Also, move the declarations of these message-handling (afx_msg) functions between the //{{AFX_MSG comments in your header files. Doing so will allow you to use ClassWizard throughout the rest of your project's life cycle(s).

    These recommendations regarding //{{AFX_MSG comments also apply, perhaps to a lesser degree, to dialogs. If you don't anticipate many future changes to a given dialog class, then it might not be worth your effort to make that dialog ClassWizard-aware. That's fine. We recommend, of course, that you create all new dialog classes using ClassWizard's Add Class option.

    As you migrate an MFC 1.0 or Windows application, you may want to maintain compatibility with existing file formats. (The default MFC 2.0 document serialization mechanism may not be appropriate for your application.) To do direct CFile write and read calls, or to implement a non-file based document, you will want to override CDocument::OnOpenDocument and OnSaveDocument. The MFC General sample DIBLOOK provides an example of this technique. If your current application already serializes objects, then this will not be an issue.

Alphabetical API Changes

To understand the reasons for these changes, please refer to "Reason for Changes" below.

API / Variable | MFC 2.0 Change (Reason for Change)
CMetaFileDC::Close | Return type (2)
CWnd::Create | Extra default param added, CWnd* const (1, 3)
CFrameWnd::Create | Extra default param added, CWnd* const (1, 3)
CMDIChildWnd::Create | Extra default param added, CWnd* const (1, 3) dwStyle default is now: WS_CHILD | WS_VISIBLE | WS_OVERLAPPEDWINDOW
CWnd::CreateEx | Extra default param added, CWnd* const (1, 3)
CBitmap::CreateBitmap | Parameter types (4)
CDC::EnumObjects | Callback prototype (2)
CTime::Format | Const function (3)
CTimeSpan::Format | Const function (3)
CTime::FormatGmt | Const function (3)
CFile::GetStatus | Nonvirtual (5)
CDC::GrayString | Callback prototype and parameter type (2)
CBitmapButton::LoadBitmaps | Extra default parameter (1)
CWnd::OnActivateApp | Parameter type (2)
CWnd::OnCompareItem | Extra parameter (6)
CWnd::OnDeleteItem | Extra parameter (6)
CWnd::OnDrawItem | Extra parameter (6)
CWnd::OnDropFiles | Parameter type (2)
CWnd::OnGetMinMaxInfo | Parameter type (6)
CWnd::OnMeasureItem | Extra parameter (6)
CWnd::OnMenuChar | Return type (2)
CWnd::OnNcCalcSize | Extra parameter (6)
CWnd::OnPaintClipboard | Parameter type (2)
CWnd::OnParentNotify | Parameter type (2)
CWnd::OnSizeClipboard | Parameter type (2)
CWnd::OnSysCommand | Parameter type (2)
CWnd::OnWinIniChange | Parameter type (2)
CDC::PlayMetaFile | Parameter type (2)
CEdit::SetSel | Extra default parameter (6)
CEdit::SetTabStops | Parameter type (5)
CWnd::SetTimer | Callback prototype and parameter type (2)
CRuntimeClass::m_pszClassName | Renamed m_lpszClassName (5)

Deleted or Obsolete API | MFC 2.0 Change (Reason for Change)
CBitmapButton | Removed ctor with 3 params - use LoadBitmaps (1)
CMDIFrameWnd:: CreateClient | Use OnCreateClient (1)
GetChildFrame | Use MDIGetActive (1)
GetDCOrg | Use Windows API directly for 3.x (4)
m_pMDIFrameWnd | Now call GetParentFrame OR GetMDIFrame (1)

Reasons for Changes:

  • Improved functionality. The MFC 2.0 version of this API provides more or improved functionality over its MFC 1.0 counterpart.

  • STRICT conformance. The MFC 2.0 API was changed to conform with the STRICT Windows API.

  • Const correctness. The MFC 2.0 API was fixed to correctly apply the 'const' keyword to facilitate more robust programs.

  • Win32 portability. The MFC 2.0 API was changed to correctly reflect the Win32 API which facilitates easy porting of MFC applications to Win32.

  • Reduced memory usage. The MFC 2.0 API was changed to provide more efficient linkage and memory usage techniques which will result in smaller applications and reduced DGROUP usage.

  • Win 3.1 functionality. The MFC 2.0 API was changed to correctly reflect a Windows 3.1 API change. The API still remains compatible with Windows 3.0, but optional Windows 3.1 only parameters are now available.

Compiler Errors

Most changes to the MFC 2.0 APIs will generate one of a few compiler errors, or none at all if standard type conversions satisfy the compiler. The following compiler errors may be generated when compiling existing MFC 1.0 applications under MFC 2.0:

Number | Compiler Error Message
Compiler error C2039 | 'Identifier' : is not a member of ‘class-key.’
 | This error is caused when a member function or data member has been removed from a class, for example CFrameWnd's m_pMDIFrameWnd.
Compiler error C2501 | 'Identifier' : missing decl-specifiers.
 | This error is caused when you use an unknown class name. This is usually the case when the class no longer exists or has been moved to a different header file. For example if you get this error for CMetaFile and CBitmapButton then you must add #include "afxext.h" to the source files using those classes.
Compiler error C2248 | 'Member' cannot access 'specifier' member declared in class 'class.'
 | This error occurs if the access of a member has changed from MFC 1.0 to 2. For example, an undocumented API has been moved from public to protected member access. This should only occur in code that is using undocumented and unsupported APIs, which should be changed to use the appropriate MFC 2.0 functionality.
Compiler error C2642 | Cast to pointer to member must be from related pointer to member.
 | This error occurs when the message handler function prototype differs from the one in afxwin.h. For example, a line containing the ON_WM_ACTIVATEAPP macro will emit this error if the parameters and return type of your OnActivateApp message handler match the MFC 1.0 declaration.
Compiler error C2660 | 'Function' : function does not take 'number' parameters.
 | The number of parameters has changed from MFC 1.0 to MFC 2.0. For example, calling the CBitmapButton constructor with three parameters causes this error since this particular constructor has been removed and replaced by the LoadBitmaps member function.
Compiler error C2664 | 'Function' : cannot convert parameter 'number' from 'type1' to 'type2.'
 | The type of a parameter has changed, and standard conversions do not satisfy the compiler. CDC::EnumObjects is an example of this. In this case, the prototype of the callback function has changed.


TN020: ID Naming and Numbering Conventions

This note describes the ID naming and numbering conventions used by MFC 2.0 for resources, commands, strings, controls, and child windows.

The Problem

The MFC ID naming and numbering conventions are intended to meet the following requirements:

  • Provide a consistent ID-naming standard used across the MFC library and MFC applications that are supported by the Visual C++ resource editor. This allows the programmer to more readily interpret IDs as to their type and origin.

  • Emphasize the strong 1-to-1 relationship between certain types of IDs. This helps to clarify MFC's application framework architecture.

  • Conform to already widely used standards for naming IDs in Windows.

  • Partition the ID-numbering space, so as to avoid unintentional duplication of ID numbers among those assigned by the programmer, by MFC and Windows, and by Visual C++-edited resources.

Overview of ID Prefix Naming Convention

There are several categories or types of IDs in an application. The MFC ID-naming convention defines different prefixes for different resource types.

MFC uses the prefix "IDR_" to refer to a resource ID that applies to multiple resource types. For example, for a given frame window, the same "IDR_" value is used to refer to a menu, accelerator, string and icon resource all at once.

IDR_ | Multiple resource types (Used for Menus, Accelerators primarily).
IDD_ | For dialog template resources (for example, IDD_DIALOG1).
IDC_ | For Cursor resources.
IDI_ | For Icon resources.
IDB_ | For Bitmap resources.
IDS_ | For String resources.

Note that the IDS_ value for a string resource is the ID passed to LoadString. The actual implementation of string table resources groups together 16 strings into one segment.

Within a DIALOG resource, we follow the convention of:

IDOK,IDCANCEL | For standard push button IDs.
IDC_ | For other dialog controls.

The "IDC_" prefix is also used for cursors. This naming conflict is not usually a problem since a typical application will have few cursors and a large number of dialog controls.

Within a Menu resource, we follow the convention of:

IDM_ | For menu items not using the MFC command architecture.
ID_ | For menu item commands using the MFC command architecture.

Commands that follow the MFC command architecture must have an ON_COMMAND command handler and may have an ON_UPDATE_COMMAND_UI handler. If these command handlers follow the MFC command architecture, they will function correctly whether they are bound to a menu item, a toolbar button or a dialog bar button. The same ID_ is also used for a menu prompt string displayed on the program's message bar. Most of the menu items in your application should follow the MFC command convention. All of the standard command IDs (for example, ID_FILE_NEW) follow this convention.

MFC also uses "IDP_" as a specialized form of strings (that is, instead of "IDS_"). Strings with the "IDP_" prefix are "prompts," that is, strings used in message boxes. "IDP_" strings may contain "%1" and "%2" as place holders of strings determined by the program. "IDP_" strings usually have help topics, while "IDS_" strings do not. "IDP_" strings are always localized, while "IDS_" strings may or may not be localized.

The MFC library also uses the "IDW_" prefix as a specialized form of control IDs (that is, instead of "IDC_"). These IDs are assigned to child windows such as views and splitters by the framework classes. MFC implementation IDs are prefixed with "AFX_".

Overview of ID-Numbering Convention

The following lists the valid ranges for the IDs of the specific types. Some of the limits are technical implementation limits while others are just conventions to prevent your IDs from colliding with Windows predefined IDs or MFC default implementations.

We strongly recommend you do not defined IDs outside the recommended ranges. Even though the lower limit of many of these ranges is 1 (0 is not used), common convention starts practical use of IDs at 100 or 101.

Prefix | Resource Type | Valid Range
IDR_ | multiple | 1 -> 0x6FFF
IDD_ | dialog templates | 1 -> 0x6FFF
IDC_,IDI_,IDB_ | cursors, icons, bitmaps | 1 -> 0x6FFF
IDS_, IDP_ | general strings | 1 -> 0x7FFF
ID_ | commands | 0x8000 -> 0xDFFF
IDC_ | controls | 8 -> 0xDFFF

Reasons for these range limits:

  • By convention, the ID value of 0 is not used.

  • Windows implementation limitations restrict true resource IDs to be less than or equal to 0x7FFF.

  • MFC's internal framework implementations reserve several ranges: 0xE000->0xEFFF and 0x7000->0x7FFF.

  • Several Windows system commands use the range of 0xF000 -> 0xFFFF.

  • Control IDs of 1->7 are reserved by IDOK, IDCANCEL, and so on.

  • The range of 0x8000->0xFFFF for strings is reserved for menu prompts for commands.


TN021: Command and Message Routing

This note describes the command routing and dispatch architecture as well as advanced topics in general window message routing.

Please refer to Visual C++ Programmer's Guide for general details on the architectures described here, especially the distinction between Windows messages, control notifications, and commands. This note assumes you are very familiar with the issues described in the printed documentation and only addresses very advanced topics.

Command Routing and Dispatch MFC 1.0 Functionality Evolves to MFC 2.0 Architecture

Windows has the WM_COMMAND message that is overloaded to provide notifications of menu commands, accelerator keys and dialog-control notifications.

MFC 1.0 built on that a little by allowing a command handler (for example, "OnFileNew") in a CWnd derived class to get called in response to a specific WM_COMMAND. This is glued together with a data structure called the message map, and results in a very space-efficient command mechanism.

MFC 1.0 also provided additional functionality for separating control notifications from command messages. Commands are represented by a 16 bit ID, sometimes known as a Command ID. Commands normally start from a CFrameWnd (eg: a menu select or a translated accelerator) and get routed to a variety of other windows.

MFC 1.0 used command routing in a limited sense for the implementation of Multiple Document Interface (MDI). (An MDI frame window delegate commands to its active MDI Child window.)

This functionality has been generalized and extended in MFC 2.0 to allow commands to be handled by a wider range of objects (not just window objects). It provides a more formal and extensible architecture for routing messages and reuses the command target routing for not only handling of commands, but also for updating UI objects (like menu items and toolbar buttons) to reflect the current availability of a command.

Command IDs

See Visual C++ Programmer's Guide for an explanation of the command routing and binding process. Technical Note 20 contains information on ID naming.

We use the generic prefix "ID_" for command IDs. Command IDs are >= 0x8000. The message line or status bar will show the command description string if there is a STRINGTABLE resource with the same IDs as the command ID.

In the resources of your application, a command ID can appears in several places:

  • In one STRINGTABLE resource that has the same ID as the message-line prompt

  • In possibly many MENU resources that are attached to menu items that invoke the same command

  • (ADVANCED) in a dialog button for a GOSUB command

In the source code of your application, a command ID can appears in several places:

  • In your RESOURCE.H (or other main symbol header file) to define application-specific command IDs

  • PERHAPS In an ID array used to create a toolbar

  • In an ON_COMMAND macro

  • PERHAPS In an ON_UPDATE_COMMAND_UI macro

Currently, the only implementation in MFC that requires command IDs be >= 0x8000 is the implementation of GOSUB dialogs/commands.

GOSUB Commands, Using Command Architecture in Dialogs

The command architecture of routing and enabling commands works well with frame windows, menu items, toolbar buttons, dialog bar buttons, other control bars and other user-interface elements designed to update on demand and route commands or control IDs to a main command target (usually the main frame window). That main command target may route the command or control notifications to other command target objects as appropriate.

A dialog (modal or modeless) can benefit from some of the features of the command architecture if you assign the control ID of the dialog control to the appropriate command ID. Support for dialogs is not automatic, so you may have to write some additional code.

Note that for all these features to work properly, your command IDs should be >= 0x8000. Since many dialogs could get routed to the same frame, shared commands should be >= 0x8000, while the non-shared IDC’s in a specific dialog should be <= 0x7FFF.

You can place a normal button in a normal modal dialog with the IDC of the button set to the appropriate command ID. When the user selects the button, the owner of the dialog (usually the main frame window) gets the command just like any other command. This is called a GOSUB command since it usually is used to bring up another dialog (a GOSUB of the first dialog).

You can also call the function CWnd::UpdateDialogControls on your dialog and pass it the address of your main frame window. This function will enabled or disable your dialog controls based on whether they have command handlers in the frame. This function is called automatically for you for control bars in your application’s idle loop, but you must call it directly for normal dialogs that you wish to have this feature.

When ON_UPDATE_COMMAND_UI is Called

Maintaining the enabled/checked state of all a program's menu items all the time can be a computationally expensive problem. A common technique is to enable/check menu items only when the user selects the POPUP. The MFC 2.0 implementation of CFrameWnd handles the WM_INITMENUPOPUP message and uses the command routing architecture to determine the states of menus through ON_UPDATE_COMMAND_UI handlers.

CFrameWnd also handles the WM_ENTERIDLE message to describe the current menu item selected on the status bar (also known as the message line).

An application's menu structure, edited by Visual C++, is used to represent the potential commands available at WM_INITMENUPOPUP time. ON_UPDATE_COMMAND_UI handlers can modify the state or text of a menu, or for advanced uses (like the File MRU list or the OLE Verbs pop-up menu), actually modify the menu structure before the menu is drawn.

The same sort of ON_UPDATE_COMMAND_UI processing is done for toolbars (and other control bars) when the application enters its idle loop. See the Class Library Reference and Technical Note 31 for more information on control bars.

Nested Popup Menus

If you are using a nested menu structure, you will notice that the ON_UPDATE_COMMAND_UI handler for the first menu item in the popup is called in two different cases.

First it is called for the popup itself. This is necessary since popup menus do not have IDs and we use the ID of the first menu item of the popup to refer to the entire popup. In this case the m_pSubMenu member variable of the CCmdUI object will be non-NULL and will point to popup menu.

Second it is called just before the menu items in the popup are to be drawn. In this case the ID refers just to the first menu item and the m_pSubMenu member variable of the CCmdUI object will be NULL.

This allows you to enable the popup distinct from its menu items, but requires that you write some menu aware code. For example, in a nested menu with the following structure:

File>
    New>
        Sheet (ID_NEW_SHEET)
        Chart (ID_NEW_CHART)

The ID_NEW_SHEET and ID_NEW_CHART commands can be independently enabled or disabled. The "New" popup menu should be enabled if either of the two is enabled.

The command handler for ID_NEW_SHEET (the first command in the popup) would look something like:

void CMyApp::OnUpdateNewSheet(CCmdUI* pCmdUI)
{
    if (pCmdUI->m_pSubMenu != NULL)
    {
        // enable entire popup for "New" sheet and chart
        BOOL bEnable = m_bCanCreateSheet || m_bCanCreateChart;

        // CCmdUI::Enable is a no-op for this case, so we
        //   must do what it would have done.
        pCmdUI->m_pMenu->EnableMenuItem(pCmdUI->m_nIndex,
            MF_BYPOSITION |
                (bEnable ? MF_ENABLED : (MF_DISABLED | MF_GRAYED)));
        return;
    }
    // otherwise just the New Sheet command
    pCmdUI->Enable(m_bCanCreateSheet);
}

The command handler for ID_NEW_CHART would be a normal update command handler and look something like:

void CMyApp::OnUpdateNewChart(CCmdUI* pCmdUI)
{
    pCmdUI->Enable(m_bCanCreateChart);
}

ON_COMMAND and ON_BN_CLICKED

The message map macros for ON_COMMAND and ON_BN_CLICKED are the same. The MFC command and control notification routing mechanism only uses the command ID to decide where to route to. Control notifications with control notification code of zero (BN_CLICKED) are interpreted as commands.

Advanced note: In actual fact, all control notification messages go through the command handler chain. Therefore it is technically possible for you to write a control notification handler for say EN_CHANGE in your document class. This is not generally advisable since the practical applications of this feature are few, the feature is not supported by ClassWizard, and use of the feature can result in fragile code.

Disabling the Automatic Disabling of Button Controls

If you place a button control on a dialog bar, or in a dialog using where you are calling CWnd::UpdateDialogControls on your own, you will notice that buttons which do not have ON_COMMAND or ON_UPDATE_COMMAND_UI handlers will be automatically disabled for you by the framework. In some cases you will not need to have a handler, but you will want the button to remain enabled. The easiest way to achieve this is to add a dummy command handler (easy to do with ClassWizard) and do nothing in it.

Window Message Routing

The following describes some more advanced topics on the MFC classes and how Windows message routing and other topics impact them. The information here is only described briefly. Refer to the Class Library Reference for details about public APIs. Please refer to the MFC library source code for more information on implementation details.

Please refer to Technical Note 17 for details on Window cleanup, a very important topic for all CWnd-derived classes.

CWnd Issues

The implementation member function CWnd::OnChildNotify provides a powerful and extensible architecture for child windows (also known as controls) to hook or otherwise be informed of messages, commands, and control notifications that go to their parent (or "owner"). If the child window (/control) is a C++ CWnd object itself, the virtual function OnChildNotify is called first with the parameters from the original message (that is, a MSG structure). The child window can leave the message alone, eat it, or modify the message for the parent (rare).

The default CWnd implementation handles the following messages and uses the OnChildNotify hook to allow child windows (controls) to get first crack at the message:

  • WM_MEASUREITEM and WM_DRAWITEM (for self-draw)

  • WM_COMPAREITEM and WM_DELETEITEM (for self-draw)

  • WM_HSCROLL and WM_VSCROLL

  • WM_CTLCOLOR

  • WM_PARENTNOTIFY

You will notice the OnChildNotify hook is used for changing owner-draw messages into self-draw messages.

In addition to the OnChildNotify hook, scroll messages have further routing behavior. Please see below for more details on scroll bars and sources of WM_HSCROLL and WM_VSCROLL messages.

CFrameWnd Issues

The CFrameWnd class provides most of the command routing and user-interface updating implementation. This is primarily used for the main frame window of the application (CWinApp::m_pMainWnd) but applies to all frame windows.

The main frame window is the window with the menu bar and is the parent of the status bar or message line. Please refer to the above discussion on command routing and WM_INITMENUPOPUP.

The CFrameWnd class provides management of the active view. The following messages are routed through the active view:

  • All command messages (the active view gets first crack at them)

  • WM_HSCROLL and WM_VSCROLL messages from sibling scroll bars (see below)

  • WM_ACTIVATE (and WM_MDIACTIVATE for MDI) get turned into calls to the virtual function CView::OnActivateView

CMDIFrameWnd/CMDIChildWnd Issues

Both MDI frame window classes derive from CFrameWnd and therefore are both enabled for the same sort of command routing and user-interface updating provided in CFrameWnd. In a typical MDI application, only the main frame window (that is, the CMDIFrameWnd object) holds the menu bar and the status bar and therefore is the main source of the command routing implementation.

The general routing scheme is that the active MDI child window gets first crack at commands. The default PreTranslateMessage functions handle accelerator tables for both MDI child windows (first) and the MDI frame (second) as well as the standard MDI system-command accelerators normally handled by TranslateMDISysAccel (last).

Scroll Bar Issues

When handling scroll-message (WM_HSCROLL/OnHScroll and/or WM_VSCROLL/OnVScroll ), you should try to write the handler code so it does not rely on where the scroll bar message came from. This is not only a general Windows issue, since scroll messages can come from true scroll bar controls or from WS_HSCROLL/WS_VSCROLL scroll bars which are not scroll bar controls.

MFC extends that to allow for scroll bar controls to be either child or siblings of the window being scrolled (in fact the parent/child relationship between the scroll bar and window being scrolled can be anything). This is especially important for shared scroll bars with splitter windows. Please refer to Technical Note 29 for details on the implementation of CSplitterWnd including more information on shared scroll bar issues.

On a side note, there are two CWnd derived classes where the scroll bar styles specified at create time are trapped and not passed to Windows. When passed to a creation routine, WS_HSCROLL and WS_VSCROLL can be independently set, but after creation can not be changed. Of course, you should not directly test or set the WS_?SCROLL style bits of the window that they created.

For CMDIFrameWnd the scroll bar styles you pass in to Create or LoadFrame are used to create the MDICLIENT. If you wish to have a scrollable MDICLIENT area (like the Windows Program Manager) be sure to set both scroll bar styles (WS_HSCROLL | WS_VSCROLL) for the style used to create the CMDIFrameWnd.

For CSplitterWnd the scroll bar styles apply to the special shared scroll bars for the splitter regions. For static splitter windows, you will normally not set either scroll bar style. For dynamic splitter windows you will usually have the scroll bar style set for the direction you will split, That is, WS_HSCROLL if you can split rows, WS_VSCROLL if you can split columns.


TN022: Standard Commands Implementation

This note describes the standard command implementations provided by MFC 2.0. Please be sure to read Technical Note 21 first since that describes the mechanisms used to implement many of the standard commands.

This description assumes knowledge of the MFC architectures, APIs, and common programming practice. Documented as well as undocumented "implementation only" APIs are described. This is not a place to start to learn about the features of or how to program in MFC. Please refer to the Visual C++ Programmer's Guide for more general information and for details of documented APIs.

The Problem

MFC defines many standard command IDs in the header file AFXRES.H. Framework support for these commands varies. Understanding where and how the framework classes handle these commands will not only show you how the framework works internally but will provide useful information on how to customize the standard implementations and hopefully teach you a few techniques for implementing your own command handlers.

Contents of This Technical Note

Each command ID is described in two sections:

  • The title: the symbolic name of the command ID (for example, ID_FILE_SAVE) followed by the purpose of the command (for example, "saves the current document") separated by a colon.

  • One or more paragraphs describing which classes implement the command, and what the default implementation does

Most default command implementations are prewired in the framework's base class message map. There are some command implementations which require explicit wiring in your derived class. These are described under "Note". If you chose the right options in AppWizard, these default handlers will be connected for you in the generated skeleton application.

Naming Convention

Standard commands follow a simple naming convention that we recommend you use if possible. Most standard commands are located in standard places in an application's menu bar. The symbolic name of the command starts with "ID_" followed by the standard popup menu name, followed by the menu item name. The symbolic name is in upper case with underscore word-breaks. For commands that do not have standard menu item names, a logical command name is defined starting with "ID_" (for example, ID_NEXT_PANE).

We use the prefix "ID_" to indicate commands that are designed to be bound to menu items, toolbar buttons, or other command user-interface objects. Command handlers handling "ID_" commands should use the ON_COMMAND and ON_UPDATE_COMMAND_UI mechanisms of the MFC command architecture.

We recommend you use the standard "IDM_" prefix for menu items which do not follow the command architecture and need menu-specific code to enable and disable them. Of course the number of menu specific commands should be small since following the MFC command architecture not only makes command handlers more powerful (since they will work with toolbars) but makes the command handler code reusable.

ID Ranges

Please refer to Technical Note 20 for more details on the use of ID ranges in MFC.

MFC standard commands fall in the range 0xE000 to 0xEFFF. Please do not rely on the specific values of these IDs since they are subject to change in future versions of the library.

Your application should define its commands in the range 0x8000 to 0xDFFF.

Standard Command IDs

For each command ID, there is a standard message line prompt string that can be found in the file PROMPTS.RC. The string ID for that menu prompt must be the same as for the command ID.

  • ID_FILE_NEW: Creates a new/empty document.

    Note You must connect this to your CWinApp-derived class's message map to enable this functionality.

    CWinApp::OnFileNew implements this command differently depending on the number of document templates in the application. If there is only one CDocTemplate, CWinApp::OnFileNew will create a new document of that type, as well as the proper frame and view class.

    If there is more than one CDocTemplate, CWinApp::OnFileNew will prompt the user with a dialog (AFX_IDD_NEWTYPEDLG) letting them select which document type to use. The selected CDocTemplate is used to create the document.

    One common customization of ID_FILE_NEW is to provide a different and more graphical choice of document types. In this case you can implement your own CMyApp::OnFileNew and place it in your message map instead of CWinApp::OnFileNew. There is no need to call the base class implementation.

    Another common customization of ID_FILE_NEW is to provide a separate command for creating a document of each type. In this case you should define new command IDs, for example ID_FILE_NEW_CHART and ID_FILE_NEW_SHEET.

  • ID_FILE_OPEN: Opens an existing document.

    Note You must connect this to your CWinApp-derived class's message map to enable this functionality.

    CWinApp::OnFileOpen has a very simple implementation of calling CWinApp::DoPromptFileName followed by CWinApp::OpenDocumentFile with the file or path name of the file to open. The CWinApp implementation routine DoPromptFileName brings up the standard FileOpen dialog and fills it with the file extensions obtained from the current document templates.

    One common customization of ID_FILE_OPEN is to customize the FileOpen dialog or add additional file filters. The recommended way to customize this is to replace the default implementation with your own FileOpen dialog, and call CWinApp::OpenDocumentFile with the document's file or path name. There is no need to call the base class.

  • ID_FILE_CLOSE: Closes the currently open document.

    CDocument::OnFileClose calls CDocument::SaveModified to prompt the user to save the document if it has been modified and then calls OnCloseDocument. All the closing logic, including destroying the document, is done in the OnCloseDocument routine.

    Note ID_FILE_CLOSE acts differently from a WM_CLOSE message or an SC_CLOSE system command sent to the documents frame window. Closing a window will close the document only if that is the last frame window showing the document. Closing the document with ID_FILE_CLOSE will not only close the document but will close down all frame windows showing the document.

  • ID_FILE_SAVE: Saves the current document.

    The implementation uses a helper routine CDocument::DoSave which is used for both OnFileSave and OnFileSaveAs. If you save a document that has not been saved before (that is, it does not have a path name, as in the case of FileNew) or that was read from a read-only document, the OnFileSave logic will act like the ID_FILE_SAVE_AS command and ask the user to provide a new file name. The actual process of opening the file and doing the saving is done through the virtual function OnSaveDocument.

    There are two common reasons to customize ID_FILE_SAVE. For documents that do not save, simply remove the ID_FILE_SAVE menu items and toolbar buttons from your user interface. Also make sure that you never dirty your document (that is, never call CDocument::SetModifiedFlag) and the framework will never cause the document to be saved. For documents that save to someplace other than a disk file, define a new command for that operation.

    In the case of a COleServerDoc, ID_FILE_SAVE is used both for file save (for normal documents) and file update (for embedded documents).

    If your document data is stored in individual disk files, but you don't want to use the default CDocument serialize implementation, you should override CDocument::OnSaveDocument instead of OnFileSave.

  • ID_FILE_SAVE_AS: Saves the current document under a different file name.

    The CDocument::OnFileSaveAs implementation uses the same CDocument::DoSave helper routine as OnFileSave. The OnFileSaveAs command is handled just as ID_FILE_SAVE if the documents had no file name before the save. COleServerDoc::OnFileSaveAs implements the logic to save a normal document data file or to save a server document representing an OLE object embedded in some other application as a separate file.

    If you customize the logic of ID_FILE_SAVE, you will probably want to customize ID_FILE_SAVE_AS in a similar fashion or the operation of "Save As" may not apply to your document. You can remove the menu item from your menu bar if it is not needed.

  • ID_FILE_SAVE_COPY_AS: Saves a copy current document under a new name.

    The COleServerDoc::OnFileSaveCopyAs implementation is very similar to CDocument::OnFileSaveAs, except that the document object is not "attached" to the underlying file after the save. That is, if the in-memory document was "modified" before the save, it is still "modified". In addition, this command has no effect on the path name or title stored in the document.

  • ID_FILE_UPDATE: Notifies the container to save an embedded document.

    The COleServerDoc::OnUpdateDocument implementation simply notifiies the container that the embedding should be saved. The container then calls the appropriate OLE APIs in order to save the embedded object.

  • ID_FILE_PAGE_SETUP: Invokes an application-specific page setup/layout dialog.

    Currently there is no standard for this dialog, and the framework has no default implementation of this command.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_FILE_PRINT_SETUP: Invoke the standard Print Setup dialog.

    Note You must connect this to your CWinApp-derived class's message map to enable this functionality.

    This command invokes the standard print setup dialog that allows the user to customize the printer and print settings for at least this document or at most all the documents in this application. You must use the Control Panel to change the default printer settings for the entire system.

    CWinApp::OnFilePrintSetup has a very simple implementation creating a CPrintDialog object and calling the CWinApp::DoPrintDialog implementation function. This sets the application default printer setup.

    The common need for customizing this command is to allow for per-document printer settings, which should be stored with the document when saved. To do this you should add a message-map handler in your CDocument class that creates a CPrintDialog object, initializes it with the appropriate printer attributes (usually hDevMode and hDevNames), call the CPrintDialog::DoModal, and save the changed printer settings. For a robust implementation, you should look at the implementation of CWinApp::DoPrintDialog for detecting errors and CWinApp::UpdatePrinterSelection for dealing with sensible defaults and tracking system-wide printer changes.

  • ID_FILE_PRINT: Standard printing of the current document

    Note You must connect this to your CView-derived class's message map to enable this functionality.

    This command prints the current document, or more correctly, starts the printing process, which involves invoking the standard print dialog and running the print engine.

    CView::OnFilePrint implements this command and the main print loop. It calls the virtual CView::OnPreparePrinting to prompt of the user with the print dialog. It then prepares the output DC to go to the printer, brings up the printing progress dialog (AFX_IDD_PRINTDLG), and sends the StartDoc escape to the printer. CView::OnFilePrint also contains the main page-oriented print loop. For each page, it calls the virtual CView::OnPrepareDC followed by a StartPage escape and calling the virtual CView::OnPrint for that page. When complete, the virtual CView::OnEndPrinting is called, and the printing progress dialog is closed.

    The MFC printing architecture is designed to hook in many different ways for printing and print preview. You will normally find the various CView overridable functions adequate for any page-oriented printing tasks. Only in the case of an application that uses the printer for non-page oriented output, should you find the need to replace the ID_FILE_PRINT implementation.

  • ID_FILE_PRINT_PREVIEW: Enter print-preview mode for the current document.

    Note You must connect this to your CView-derived class's message map to enable this functionality.

    CView::OnFilePrintPreview starts the print preview mode by calling the documented helper function CView::DoPrintPreview. CView::DoPrintPreview is the main engine for the print preview loop, just as OnFilePrint is the main engine for the printing loop.

    The print preview operation can be customized in a variety of ways by passing different parameters to DoPrintPreview. Please refer to Technical Note 30, which discusses some of the details of print preview and how to customize it.

  • ID_FILE_MRU_FILE1...FILE16 : a range of command IDs for the File MRU list.

    CWinApp::OnUpdateRecentFileMenu is a update command UI handler that is one of the more advanced uses of the ON_UPDATE_COMMAND_UI mechanism. In your menu resource, you need only define a single menu item with ID ID_FILE_MRU_FILE1. That menu item remains initially disabled.

    As the MRU list grows, more menu items are added to the list. The standard CWinApp implementation defaults to the standard limit of the four most recently used files. You can change the default by calling CWinApp::LoadStdProfileSettings with a larger or smaller value. The MRU list is stored in the application's .INI file. The list is loaded in your application's InitInstance function if you call LoadStdProfileSettings, and is saved when your application exits. The MRU update command UI handler also will convert absolute paths to relative paths for display on the file menu.

    CWinApp::OnOpenRecentFile is the ON_COMMAND handler that performs the actual command. It simply gets the file name from the MRU list and calls CWinApp::OpenDocumentFile, which does all the work of opening the file and updating the MRU list.

    Customization of this command handler is not recommended.

  • ID_EDIT_CLEAR: Clears the current selection

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command using CEdit::Clear. The command is disabled if there is no current selection.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_CLEAR_ALL: Clears the entire document.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    If you choose to implement this command, we recommend you use this command ID. See the MFC Tutorial sample SCRIBBLE for an example implementation.

  • ID_EDIT_COPY: Copies the current selection to the Clipboard.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command, which copies the currently selected text to the Clipboard as CF_TEXT using CEdit::Copy. The command is disabled if there is no current selection.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_CUT: Cuts the current selection to the Clipboard.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command, which cuts the currently selected text to the Clipboard as CF_TEXT using CEdit::Cut. The command is disabled if there is no current selection.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_FIND: Begin the find operation, bring up the modeless find dialog.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command, which calls the implementation helper function OnEditFindReplace to use and store the previous find/replace settings in private implementation variables. The CFindReplaceDialog class is used to manage the modeless dialog for prompting the user.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_PASTE: Insert the current Clipboard contents.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command, which copies the current Clipboard data replacing the selected text using CEdit::Paste. The command is disabled if there is no CF_TEXT in the Clipboard.

    COleClientDoc just provides a update command UI handler for this command. If the Clipboard does not contain an embeddable OLE item/object, the command will be disabled. You are responsible for writing the handler for the actual command to do the actual pasting. If your OLE application can also paste other formats, you should provide your own update command UI handler in your view or document (that is, somewhere before COleClientDoc in the command target routing).

    If you choose to implement this command, we recommend you use this command ID.

    For replacing the standard OLE implementation, use COleClientItem::CanPaste.

  • ID_EDIT_PASTE_LINK: Insert a link from the current Clipboard contents.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    COleDocument just provides a update command UI handler for this command. If the Clipboard does not contain linkable OLE item/object, the command will be disabled. You are responsible for writing the handler for the actual command to do the actual pasting. If your OLE application can also paste other formats, you should provide your own update command UI handler in your view or document (that is, somewhere before COleDocument in the command target routing).

    If you choose to implement this command, we recommend you use this command ID.

    For replacing the standard OLE implementation, use COleClientItem::CanPasteLink.

  • ID_EDIT_PASTE_SPECIAL: Insert the current Clipboard contents with options.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class. MFC does not provide this dialog.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_REPEAT: Repeat the last operation.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command to repeat the last find operation. The private implementation variables for the last find are used. The command is disabled if a find can not be attempted.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_REPLACE: Begin the replace operation, bring up the modeless replace dialog.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command, which calls the implementation helper function OnEditFindReplace to use and store the previous find/replace settings in private implementation variables. The CFindReplaceDialog class is used to manage the modeless dialog that prompts the user.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_SELECT_ALL: Select the entire document.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command, which selects all the text in the document. The command is disabled if there is no text to select.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_UNDO: Undo the last operation.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    CEditView provides an implementation of this command, using CEdit::Undo. The command is disabled if CEdit::CanUndo returns FALSE.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_EDIT_REDO: Redo the last operation.

    Currently there is no standard implementation for this command. You must implement this for each CView-derived class.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_WINDOW_NEW: Open another window on the active document.

    CMDIFrameWnd::OnWindowNew implements this powerful feature by using the document template of the current document to create another frame containing another view of the current document.

    Like most multiple document interface (MDI) Window menu commands, the command is disabled if there is no active MDI child window.

    Customization of this command handler is not recommended. If you wish to provide a command that creates additional views or frame windows, you will probably be better off inventing your own command. You can clone the code from CMDIFrameWnd::OnWindowNew and modify it to the specific frame and view classes of your liking.

  • ID_WINDOW_ARRANGE: Arrange icons at the bottom of an MDI window.

    CMDIFrameWnd implements this standard MDI command in an implementation helper function OnMDIWindowCmd. This helper maps command IDs to MDI Windows messages and can therefore share a lot of code.

    Like most MDI Window menu commands, the command is disabled if there is no active MDI child window.

    Customization of this command handler is not recommended.

  • ID_WINDOW_CASCADE: Cascade windows so they overlap.

    CMDIFrameWnd implements this standard MDI command in an implementation helper function OnMDIWindowCmd. This helper maps command IDs to MDI Windows messages and can therefore share a lot of code.

    Like most MDI Window menu commands, the command is disabled if there is no active MDI child window.

    Customization of this command handler is not recommended.

  • ID_WINDOW_TILE_HORZ: Tile windows horizontally.

    This command is implemented in CMDIFrameWnd just like ID_WINDOW_CASCADE, except a different MDI Windows message is used for the operation.

    You should pick the default tile orientation for your application. You can do this by changing the ID for the Window "Tile" menu item to either ID_WINDOW_TILE_HORZ or ID_WINDOW_TILE_VERT.

  • ID_WINDOW_TILE_VERT: Tile windows vertically.

    This command is implemented in CMDIFrameWnd just like ID_WINDOW_CASCADE, except a different MDI Windows message is used for the operation.

    You should pick the default tile orientation for your application. You can do this by changing the ID for the Window "Tile" menu item to either ID_WINDOW_TILE_HORZ or ID_WINDOW_TILE_VERT.

  • ID_WINDOW_SPLIT: Keyboard interface to splitter.

    CView handles this command for the CSplitterWnd implementation. If the view is part of a splitter window, this command will delegate to the implementation function CSplitterWnd::DoKeyboardSplit. This will place the splitter in a mode that will allow keyboard users to split or unsplit a splitter window.

    This command is disabled if the view is not in a splitter.

    Customization of this command handler is not recommended.

  • ID_APP_ABOUT: Invoke the About dialog box.

    There is no standard implementation for an application's About box. The default AppWizard-created application will create a custom dialog class for your application and use it as your About box. AppWizard will also write the trivial command handler which handles this command and invokes the dialog.

    You will almost always implement this command.

  • ID_APP_EXIT: Exit the application.

    CWinApp::OnAppExit handles this command by sending a WM_CLOSE message to the application's main window. The standard shutting down of the application (prompting for dirty files and so on) is handled by the CFrameWnd implementation.

    Customization of this command handler is not recommended. Overriding CWinApp::SaveAllModified or the CFrameWnd closing logic is recommended.

    If you choose to implement this command, we recommend you use this command ID.

  • ID_HELP_INDEX: List Help topics from .HLP file.

    Note You must connect this to your CWinApp-derived class's message map to enable this functionality.

    CWinApp::OnHelpIndex handles this command by trivially calling CWinApp::WinHelp.

    Customization of this command handler is not recommended.

  • ID_HELP_USING: Display help on how to use Help.

    Note You must connect this to your CWinApp-derived class's message map to enable this functionality.

    CWinApp::OnHelpUsing handles this command by trivially calling CWinApp::WinHelp.

    Customization of this command handler is not recommended.

  • ID_CONTEXT_HELP: Enter SHIFT-F1 help mode.

    Note You must connect this to your CWinApp-derived class's message map to enable this functionality.

    CWinApp::OnContextHelp handles this command by setting the help mode cursor, entering a modal loop and waiting for the user to select a window to get help on. Please refer to Technical Note 28 for more details on the MFC Help implementation.

    Customization of this command handler is not recommended.

  • ID_HELP: Give help on the current context

    Note You must connect this to your CWinApp-derived class's message map to enable this functionality.

    CWinApp::OnHelp handles this command by getting the right help context for the current application context. This handles simple F1 help, help on message boxes and so on. Please refer to Technical Note 28 for more details on the MFC help implementation.

    Customization of this command handler is not recommended.

  • ID_DEFAULT_HELP: Display default help for context

    Note You must connect this to your CWinApp-derived class's message map to enable this functionality.

    This command is usually mapped to CWinApp::OnHelpIndex.

    A different command handler can be provided if a distinction between default Help and the Help index is desired.

  • ID_NEXT_PANE: Go to next pane

    CView handles this command for the CSplitterWnd implementation. If the view is part of a splitter window, this command will delegate to the implementation function CSplitterWnd::OnNextPaneCmd. This will move the active view to the next pane in the splitter.

    This command is disabled if the view is not in a splitter or there is no next pane to go to.

    Customization of this command handler is not recommended.

  • ID_PREV_PANE: Go to previous pane

    CView handles this command for the CSplitterWnd implementation. If the view is part of a splitter window, this command will delegate to the implementation function CSplitterWnd::OnNextPaneCmd. This will move the active view to the previous pane in the splitter.

    This command is disabled if the view is not in a splitter or there is no previous pane to go to.

    Customization of this command handler is not recommended.

  • ID_OLE_INSERT_NEW: Insert a new OLE object

    Currently there is no standard implementation for this command. You must implement this for your CView-derived class to insert a new OLE item/object at the current selection.

    All OLE client applications should implement this command. AppWizard, with the OLE option, will create a skeleton implementation of OnInsertObject in your view class which you will have to complete.

    See the MFC OLE sample OCLIENT example for a complete implementation of this command.

  • ID_OLE_EDIT_LINKS: Edit OLE links

    COleDocument handles this command by using the MFC-provided implementation of the standard OLE links dialog. The implementation of this dialog is accessed through the COleLinksDialog class. If the current document does not contain any links, the command is disabled.

    Customization of this command handler is not recommended.

  • ID_OLE_VERB_FIRST...LAST: An ID range for OLE verbs

    COleDocument uses this command ID range for the verbs supported by the currently selected OLE item/object. This must be a range since a given OLE item/object type can support zero or more custom verbs. In your application's menu, you should have one menu item with the ID of ID_OLE_VERB_FIRST. When the program is run, the menu will be updated with the appropriate menu verb description (or pop-up menu with many verbs). The management of the OLE menu is handled by AfxOleSetEditMenu, done in the update command UI handler for this command.

    There are no explicit command handlers for handling each of the command ID in this range. COleDocument::OnCmdMsg is overridden to trap all command IDs in this range, turn them into zero-based verb numbers, and launch the server for that verb (using COleClientItem::DoVerb).

    Customization or other use of this command ID range is not recommended.

  • ID_VIEW_TOOLBAR: Toggle the toolbar on and off

    CFrameWnd handles this command and the update-command UI handler to toggle the visible state of the toolbar. The toolbar must be a child window of the frame with child window ID of AFX_IDW_TOOLBAR. The command handler actually toggles the visibility of the toolbar window. CFrameWnd::RecalcLayout is used to redraw the frame window with the toolbar in its new state. The update-command UI handler checks the menu item when the toolbar is visible.

    Customization of this command handler is not recommended. If you wish to add additional toolbars, you will want to clone and modify the command handler and the update-command UI handler for this command.

  • ID_VIEW_STATUS_BAR: Toggle the status bar on and off

    This command is implemented in CFrameWnd just like ID_VIEW_TOOLBAR, except a different child window ID (AFX_IDW_STATUS_BAR) is used.

Update-Only Command Handlers

There are several standard command IDs that are used as indicators in status bars. These use the same update-command UI handling mechanism to display their current visual state during application idle time. Since they can't be selected by the user (that is, you can't push a status bar pane), then it makes no sense to have an ON_COMMAND handler for these command IDs.

  • ID_INDICATOR_CAPS : CAP lock indicator

  • ID_INDICATOR_NUM : NUM lock indicator

  • ID_INDICATOR_SCRL : SCRL lock indicator

  • ID_INDICATOR_KANA : KANA lock indicator (applicable only to Japanese systems)

All three of these are implemented in CFrameWnd::OnUpdateKeyIndicator, an implementation helper that uses the command ID to map to the appropriate Virtual Key. A common implementation enables or disables (for status panes disabled = no text) the CCmdUI object depending on whether the appropriate Virtual Key is currently locked.

Customization of this command handler is not recommended.

  • ID_INDICATOR_EXT : EXTended select indicator

  • ID_INDICATOR_OVR : OVeRstrike indicator

  • ID_INDICATOR_REC : RECording indicator

Currently there is no standard implementation for these indicators.

If you choose to implement these indicators, we recommend you use these indicator IDs and maintaining the ordering of the indicators in your status bar (that is, in this order: EXT, CAP, NUM, SCRL, OVR, REC).


TN023: Standard MFC Resources

This note describes the standard resources provided with and needed by the MFC library.

Standard Resources

MFC offers two categories of predefined resources that you can use in your application: clip-art resources and standard framework resources.

Clip-art resources are additional resources that the framework does not depend on, but which you might want to add to your application's user interface. The following clip-art resources are contained in the MFC General sample CLIPART:

  • COMMON.RC: a single file of resources containing
    • A large collection of icons that represent a variety of business and data-processing tasks

    • Several common cursors (see also AFXRES.RC)

    • A toolbar bitmap containing several toolbar buttons

    • The bitmap and icon resources used by COMMDLG.DLL
  • INDICATE.RC: contains string resources for the status-bar key-state indicators, such as "CAP" for Caps Lock.

  • PROMPTS.RC: contains menu-prompt string resources for each of the predefined commands, such as "Create a new document" for ID_FILE_NEW.

  • COMMDLG.RC: an Visual C++ compatible .RC file containing the standard COMMDLG dialog templates.

Standard framework resources are resources with AFX-defined IDs that the framework depends on for internal implementations. You will rarely need to change these AFX-defined resources. If you do, you should follow the procedure outlined below.

The following framework resources are contained in the MFC\INCLUDE directory:

  • AFXRES.RC: common resources used by the framework

  • AFXPRINT.RC: resources specific to printing

  • AFXOLECL.RC: resources specific to OLE client applications

  • AFXOLESV.RC: resources specific to full OLE server applications

Using Clip-Art Resources

To use a clip-art binary resource:

  1. Open your application's resource file in Visual C++.

  2. Open COMMON.RC, this contains all the binary clip-art resources. This may take some time as the COMMON.RC file is compiled.

  3. Press CTRL and drag to copy the resource(s) you want from COMMON.RC to your application's resource file.

  4. If you want, rename the resource from a string name to a symbol.

To use other clip-art resources, the steps are as above except you open the appropriate .RC file instead of COMMON.RC. Renaming the resource ID is not needed since the clip-art resources will already be assigned the appropriate symbols for you.

Note Be careful not to unintentionally move resources out of COMMON.RC permanently. You can avoid this by CTRL-dragging (copy) rather than straight dragging (move the resources). You can also avoid this by always responding with "No" when you're asked whether you want to save the changes to COMMON.RC.

The .RC resource files have a special TEXTINCLUDE resource in them that will prevent you from accidentally saving on top of the standard .RC files.

Customizing Standard Framework Resources

Standard framework resources are usually #include'd in your application's .RC file. AppWizard will generate a .RC file that includes the appropriate standard framework resources depending on which AppWizard options you choose. You can review, add, or remove which resources are #include'd by using Visual C++'s "Set Includes..." command in the Resource menu of Visual C++ and looking at the "Compile-Time Directives" edit item. For example:

#include "afxres.rc"
#include "afxprint.rc"

The most common case of customizing standard framework resources is adding or removing additional includes for printing, OLE Client, and OLE Server support.

In some rare case you may wish to customize the contents of the standard framework resources for your particular application, not just add and remove the entire file.

To customize the contents of a standard resource file, please follow these steps:

Open your application's resource file in Visual C++.

  1. Using the Resource Set Includes command, remove the #include for the standard .rc file you want to customize (for example, to customize the print-preview toolbar, remove the #include "afxprint.rc" line).

  2. Open the appropriate standard resources files in MFC\INCLUDE (for example, MFC\INCLUDE\AFXPRINT.RC)

  3. Copy all of the resources from the standard .rc file to your application resource file.

  4. This is an all or none proposition. Either you #include all of the resources from the .RC file in MFC\INCLUDE or you have a (customized) copy of these resources in your application resource file.

  5. Modify the copy of the standard resources in your application resource file.

  6. Note Be especially careful not to modify the resources directly in the standard .RC files.


TN024: MFC-Defined Messages and Resources

This note describes the internal Windows messages and resource formats used by MFC. This information explains the implementation of the framework, and will assist you in debugging your application. For the adventurous, even though all this information is officially unsupported, you may use some of this information for advanced implementations.

This note contains MFC private implementation details; all the contents are subject to change in the future. MFC private Windows messages have meaning in the scope of one application only but will change in the future to contain system-wide messages.

The range of MFC private Windows messages and resource types are in the reserved "system" range set aside by Microsoft Windows. Currently not all numbers in the ranges are used and, in the future, new numbers in the range may be used. The currently used numbers may be changed.

MFC private Windows messages are in the range 0x360->0x37F.

MFC private resource types are in the range 0xF0->0xFF.

MFC Private Windows Messages

These Windows messages are used in place of C++ virtual functions where relatively loose coupling is required between window objects and where a C++ virtual function would not be appropriate.

These private Windows messages and associated parameter structures are declared in the MFC private header 'AFXPRIV.H'. Be warned that any of your code that includes this header may be relying on undocumented behavior and will likely break in future versions of MFC.

In the rare case of needing to handle one of these messages, you should use the ON_MESSAGE message map macro and handle the message in the generic LRESULT/WPARAM/LPARAM format.

WM_QUERYAFXWNDPROC

This message is sent to a window that is being created. This is sent very early in the creation process as a method of determining if the WndProc is AfxWndProc. AfxWndProc returns 1.

wParam | Not used
lParam | Not used
returns | 1 if processed by AfxWndProc

WM_SIZEPARENT

This message is sent by a frame window to its immediate children during resizing (CFrameWnd::OnSize calls CFrameWnd::RecalcLayout which calls CWnd::RepositionBars) to reposition the control bars around the side of the frame. The AFX_SIZEPARENTPARAMS structure contains the current available client rectangle of the parent and a HDWP (which may be NULL) with which to call DeferWindowPos to minimize repainting.

wParam | Not used
lParam | Address of an AFX_SIZEPARENTPARAMS structure
returns | Not used (0)

Ignoring the message indicates that the window doesn't take part in the layout.

WM_SETMESSAGESTRING

This message is sent to a frame window to ask it to update the message line in the status bar. Either a string ID or a LPCSTR can be specified (but not both).

wParam | String ID (or zero)
lParam | LPCSTR for the string (or NULL)
returns | Not used (0)

WM_IDLEUPDATECMDUI

This message is sent in idle time to implement the idle-time update of update-command UI handlers. If the window (usually a control bar) handles the message, it creates a CCmdUI object (or an object of a derived class) and call CCmdUI::DoUpdate for each of the "items" in the window. This will in turn check for an ON_UPDATE_COMMAND_UI handler for the objects in the command-handler chain.

wParam | BOOL bDisableIfNoHandler
lParam | Not used (0)
returns | Not used (0)

bDisableIfNoHandler is non-zero to disable the UI object if there is neither an ON_UPDATE_COMMAND_UI nor an ON_COMMAND handler.

WM_EXITHELPMODE

This message is posted to a CFrameWnd that to exit context sensitive help mode. The receipt of this message terminates the modal loop started by CFrameWnd::OnContextHelp.

wParam | Not used (0)
lParam | Not used (0)
returns | Not used

WM_INITIALUPDATE

This message is sent by the document template to all descendants of a frame window when it is safe for them to do their initial update. It maps to a call to CView::OnInitialUpdate but can be used in other CWnd-derived classes for other one-shot updating.

wParam | Not used (0)
lParam | Not used (0)
returns | Not used (0)

WM_RECALCPARENT

This message is sent by a view to its parent window (obtained via GetParent) to force a layout recalculation (usually, the parent will call RecalcLayout). This is used in OLE server applications where it is necessary for the frame to grow in size as the view's total size grows.

If the parent window processes this message it should return TRUE and fill the RECT passed in lParam with the new size of the client area. This is used in CScrollView to properly handle scrollbars (place then on the outside of the window when they are added) when a server object is in-place activated.

wParam | Not used (0)
lParam | LPRECT rectClient, may be NULL
returns | TRUE if new client rectangle returned, FALSE otherwise

WM_SIZECHILD

This message is sent by COleResizeBar to its owner window (via GetOwner) when the user resizes the resize bar with the resize handles. COleIPFrameWnd responds to this message by attempting to reposition the frame window as the user has requested.

The new rectangle, given in client coordinates relative to the frame window which contains the resize bar, is pointed at by lParam.

wParam | Not used (0)
lParam | LPRECT rectNew
returns | Not used (0)

WM_DISABLEMODAL

This message is sent to all popup windows owned by a frame window that is being deactivated. The frame window uses the result to determine whether or not to disable the popup window.

You can use this to perform special processing in your popup window when the frame enters a modal state or to keep certain popup windows from getting disabled. Tooltips use this message to destroy themselves when the frame window goes into a modal state, for example.

wParam | Not used (0)
lParam | Not used (0)
returns | Non-zero to NOT disable the window, 0 indicates the window will be disabled

WM_FLOATSTATUS

This message is sent to all popup windows owned by a frame window when the frame is either activated or deactivated by another top-level frame window. This is used by the implementation of MFS_SYNCACTIVE in CMiniFrameWnd, to keep the activation of these popup windows in sync with the activation of the top level frame window.

wParam | Is one of the following values: FS_SHOW FS_HIDE FS_ACTIVATE FS_DEACTIVATE FS_ENABLE FS_DISABLE FS_SYNCACTIVE
lParam | Not used (0)

The return value should be non-zero if FS_SYNCACTIVE is set and the window syncronizes its activation with the parent frame. CMiniFrameWnd returns non-zero when the style is set to MFS_SYNCACTIVE.

For more information, see the implementation of CMiniFrameWnd.

WM_ACTIVATETOPLEVEL

This message is sent to a top-level window when a window in its "top-level group" is either activated or deactivated. A window is part of a top-level group if it is a top-level window (no parent or owner), or it is owned by such a window. This message is similar in use to WM_ACTIVATEAPP, but works in situations where windows belonging to different processes are mixed in a single window hierarchy (common in OLE applications).

WM_QUERY3DCONTROLS

This message is sent during window creation to determine if the window should be subclassed by CTL3D32.DLL. By default 3D controls are enabled for CControlBar, CDialog, CPropertySheet, and CFormView.

wParam | Not used (0)
lParam | Not used (0)
returns | Non-zero to subclass with CTL3D. The return value is used for the call to Ctl3dSubclassDlgEx.

WM_COMMANDHELP, WM_HELPHITTEST, WM_EXITHELPMODE

These messages are used in the implementation of context-sensitive Help. Please refer to Technical Note 28 for more information.

MFC Private Resource Formats

There is currently only one MFC private resource format defined, RT_DLGINIT.

RT_DLGINIT Resource Format

One MFC private resource format is used to store extra dialog initialization information. This includes the initial strings stored in a combo box. The format of this resource is not designed to be manually edited, but is handled by Visual C++.

Visual C++ and this RT_DLGINIT resource are not required to use the related features of MFC since there are API alternative to using the information in the resource. Using Visual C++ makes it much easier to write, maintain, and translate your application in the long run.

The basic structure of a RT_DLGINIT resource is as follows:

+---------------+                    \
| Control ID    |   UINT             |
+---------------+                    |
| Message #     |   UINT             |
+---------------+                    |
|length of data |   DWORD            |
+---------------+                    | Repeated
|   Data        |   Variable Length  |   for each control
|     ...      |   and Format       |   and message
+---------------+                    /
|     0         |   BYTE
+---------------+

A repeated section contains the control ID to send the message to, the Message # to send (a normal Windows message) and a variable length of data. The Windows message is sent in a form:

SendDlgItemMessage(<Control ID>, <Message #>, 0, &<Data>);

This is a very general format, allowing any Windows messages and data content. The Visual C++ resource editor and MFC only support a limited subset of Windows messages: CB_ADDSTRING for the initial list-choices for combo boxes (the data is a text string).


TN025: Document, View, and Frame Creation

This note describes the creation and ownership issues for WinApps, DocTemplates, Documents, Frames and Views. You can find most of this information, and other interesting creation and ownership issues, in Visual C++ Programmer's Guide.

WinApp

There is one CWinApp object in the system.

It is statically constructed and initialized by the framework's internal implementation of WinMain. You must derive from CWinApp to do anything useful (exception: extension DLLs should not have a CWinApp instance — initialization is done in DllMain instead).

The one CWinApp object owns a list of document templates (a CPtrList). There is one or more document template per application. DocTemplates are usually loaded from the resource file (that is, a string array) in CWinApp::InitInstance.

pTemplate = new CDocTemplate(IDR_MYDOCUMENT, ...);
AddDocTemplate(pTemplate);

The one CWinApp object owns all frame windows in the application. The main frame window for the application should be stored in CWinApp::m_pMainWnd; usually you set m_pMainWnd in the InitInstance implementation if you have not let AppWizard do it for you. For single document interface (SDI) this is one CFrameWnd that serves as the main application frame window as well as the only document frame window. For multiple document interface (MDI) this is an MDI-Frame (class CMDIFrameWnd) which serves as the main application frame window that contains all the child CFrameWnds. Each child window is of class CMDIChildWnd (derived from CFrameWnd) and serves as one of potentially many document frame windows.

DocTemplates

The CDocTemplate is the creator and manager of documents. It owns the documents which it creates. If your application uses the resource-based approach described below, it will not need to derive from CDocTemplate.

For an SDI application, the class CSingleDocTemplate keeps track of one open document. For an MDI application, the class CMultiDocTemplate keeps a list (a CPtrList) of all the currently open documents created from that template. CDocTemplate::AddDocument and CDocTemplate::RemoveDocument provide the virtual member functions for adding or removing a document from the template. CDocTemplate is a friend of CDocument so we can set the protected CDocument::m_pDocTemplate back pointer to point back to the doc template that created the document.

CWinApp handles the default OnFileOpen implementation, which will in turn query all the doc templates. The implementation includes looking for already open documents and deciding what format to open new documents in.

CDocTemplate manages the UI binding for documents and frames.

CDocTemplate keeps a count of the number of unnamed documents.

CDocument

A CDocument is owned by a CDocTemplate.

Documents have a list of currently open views (derived from CView) that are viewing the document (a CPtrList).

Documents do not create/destroy the views, but they are attached to each other after they are created. When a document is closed (that is, through File/Close), all attached views will be closed. When the last view on a document is closed (that is, Window/Close) the document will be closed.

The CDocument::AddView, RemoveView interface is used to maintain the view list. CDocument is a friend of CView so we can set the CView::m_pDocument back pointer.

CFrameWnd

A CFrameWnd (also known as a frame) plays the same role as in MFC 1.0, but now the CFrameWnd class is designed to be used in many cases without deriving a new class. The derived classes CMDIFrameWnd and CMDIChildWnd are also enhanced so many standard commands are already implemented.

The CFrameWnd is responsible for creating windows in the client area of the frame. Normally there is one main window filling the client area of the frame.

For an MDI-Frame window, the client area is filled with the MDICLIENT control which is in turn the parent of all the MDI-Child frame windows. For an SDI-Frame window or an MDI-Child frame window, the client area is usually filled with a CView-derived window object. In the case of CSplitterWnd, the client area of the view is filled with the CSplitterWnd window object, and the CView-derived window objects (one per split pane) are created as child windows of the CSplitterWnd.


TN026: DDX and DDV Routines

This note describes the dialog data exchange (DDX) and dialog data validation (DDV) architecture. It also describes how you write a DDX_ or DDV_ procedure and how you can extend ClassWizard to use your routines.

Overview of Dialog Data Exchange

All dialog data functions are done with C++ code. There are no special resources or magic macros. The heart of the mechanism is a virtual function that is overridden in every dialog class that does dialog data exchange and validation. It is always found in this form:

void CMyDialog::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);    // call base class

    //{{AFX_DATA_MAP(CMyDialog)
        <data_exchange_function_call>

    //}}AFX_DATA_MAP
}

The special format AFX comments allow ClassWizard to locate and edit the code within this function. Code that is not compatible with ClassWizard should be placed outside of the special format comments.

In the above example, <data_exchange_function_call> is in the form:

    DDX_Custom(pDX, nIDC, field);

and <data_validation_function_call> is optional and is in the form:

    DDV_Custom(pDX, field, ...);

More than one DDX_/DDV_ pair may be included in each DoDataExchange function.

See 'afxdd_.h' for a list of all the dialog data exchange routines and dialog data validation routines provided with MFC.

Dialog data is just that - member data in the CMyDialog class. It is not stored in a struct or anything special like that.

Notes

Although we call this “dialog data,” all features are available in any class derived from CWnd and are not limited to just dialogs.

Initial values of data are set in the standard C++ constructor, usually in a block with //{{AFX_DATA_INIT and //}}AFX_DATA_INIT comments.

CWnd::UpdateData is the operation that does the initialization and error handling around the call to DoDataExchange.

You can call CWnd::UpdateData at any time to perform data exchange and validation. By default UpdateData(TRUE) is called in the default CDialog::OnOK handler and UpdateData(FALSE) is called in the default CDialog::OnInitDialog.

The DDV_ routine should immediately follow the DDX_ routine for that field.

How Does It Work?

You do not need to understand the following in order to use dialog data. However, understanding how this works behind the scenes will help you write your own exchange or validation procedure.

The DoDataExchange member function is much like the Serialize member function - it is responsible for getting or setting data to/from an external form (in this case controls in a dialog) from/to member data in the class. The pDX parameter is the context for doing data exchange and is similar to the CArchive parameter to CObject::Serialize. The pDX (a CDataExchange object) has a direction flag much like CArchive has a direction flag:

  • if !m_bSaveAndValidate, then load the data state into the controls

  • if m_bSaveAndValidate, then set the data state from the controls

Validation only occurs when m_bSaveAndValidate is set. The value of m_bSaveAndValidate is determined by the BOOL parameter to CWnd::UpdateData.

There are three other interesting CDataExchange members:

  • m_pDlgWnd: The window (usually a dialog) that contains the controls. This is to prevent callers of the DDX_ and DDV_ global functions from having to pass 'this' to every DDX/DDV routine.

  • PrepareCtrl, and PrepareEditCtrl: Prepares a dialog control for data exchange. Stores that control's handle for setting the focus if a validation fails. PrepareCtrl is used for nonedit controls and PrepareEditCtrl is used for edit controls.

  • Fail: Called after bringing up a message box alerting the user to the input error. This routine will restore the focus to the last control (the last call to PrepareCtrl/PrepareEditCtrl) and throw an exception. This member function may be called from both DDX_ and DDV_ routines.

User Extensions

There are several ways to extend the default DDX/DDV mechanism. You can:

  • Add new data types.
    CTime
  • Add new exchange procedures (DDX_???).
    void PASCAL DDX_Time(CDataExchange* pDX, int nIDC, CTime& tm);
  • Add new validation procedures (DDV_???).
    void PASCAL DDV_TimeFuture(CDataExchange* pDX, CTime tm, BOOL bFuture);
// make sure time is in the future or past
  • Pass arbitrary expressions to the validation procedures.
    DDV_MinMax(pDX, age, 0, m_maxAge);

    Note Such arbitrary expressions cannot be edited by ClassWizard and therefore should be moved outside of the special format comments (//{{AFX_DATA_MAP(CMyClass)).

Have the DoDialogExchange member function include conditionals or any other valid C++ statements with intermixed exchange and validation function calls.

//{{AFX_DATA_MAP(CMyClass)
DDX_Check(pDX, IDC_SEX, m_bFemale);
DDX_Text(pDX, IDC_EDIT1, m_age);
//}}AFX_DATA_MAP
if (m_bFemale)
    DDV_MinMax(pDX, age, 0, m_maxFemaleAge);
else
    DDV_MinMax(pDX, age, 0, m_maxMaleAge);

Note As shown above, such code can not be edited by ClassWizard and should be used only outside of the special format comments.

ClassWizard Support

ClassWizard supports a subset of DDX/DDV customizations by allowing you to integrate your own DDX_ and DDV_ routines into the ClassWizard user interface. Doing this is only cost beneficial if you plan to reuse particular DDX and DDV routines time and time again in a project or in many projects.

To do this, special entries are made in DDX.CLW (previous versions of Visual C++ stored this information in APSTUDIO.INI) or in your project’s .CLW file. The special entries can be entered either in the [General Info] section of your project's .CLW file or in the [ExtraDDX] section of the DDX.CLW file in the \Program Files\Microsoft Visual Studio\Visual C++\bin directory. You may need to create the DDX.CLW file if it doesn’t already exist. If you plan to use the custom DDX_/DDV_ routines only in a certain project, add the entries to the [General Info] section of your project .CLW file instead. If you plan to use the routines on many projects, add the entries to the [ExtraDDX] section of DDX.CLW.

The general format of these special entries is:

ExtraDDXCount=n

; where n is the number of ExtraDDX? lines to follow

ExtraDDX?=<keys>;<vb-keys>; <prompt>; <type>; <initValue>; <DDX_Proc> [;<DDV_Proc>; <prompt1>; <arg1>; [<prompt2>; <fmt2>]]

; Where ? is a number 1-n indicating which DDX type in the list that is being defined.

Each field is delimited by a ';' character. The fields and their purpose are described below.

<keys>

= list of single characters indicating for which dialog controls this variable type is allowed.

E = edit

C = two-state check box

c = tri-state check box

R = first radio button in a group

L = non-sorted list box

l = sorted list box

M = combo box (with edit item)

N = non-sorted drop list

n = sorted drop list

1 = if the DDX insert should be added to head of list (default is add to tail) This is generally used for DDX routines that transfer the 'Control' property.

<vb-keys>

this field is used only in the 16-bit product for VBX controls (VBX controls are not supported in the 32-bit product)

<prompt> =

string to place in the Property combo box (no quotes)

<type> =

single identifier for type to emit in the header file. In our example above with DDX_Time, this would be set to CTime.

<vb-keys> =

not used in this version and should always be empty

<initValue> =

initial value - 0 or blank. If it is blank, then no initialization line will be written in the //{{AFX_DATA_INIT section of the implementation file. A blank entry should be used for C++ objects (such as CString, CTime, and so on) that have constructors that guarantee correct initialization.

<DDX_Proc> =

single identifier for the DDX_ procedure. The C++ function name must start with “DDX_,” but don't include “DDX_” in the <DDX_Proc> identifier. In the example above, the <DDX_Proc> identifier would be Time. When ClassWizard writes the function call to the implementation file in the {{AFX_DATA_MAP section, it appends this name to DDX_, thus arriving at DDX_Time.

<comment> =

comment to show in dialog for variable with this DDX. Place any text you would like here, usually provide something that describes the operation performed by the DDX/DDV pair.

<DDV_Proc>

The DDV portion of the entry is optional. Not all DDX routines have corresponding DDV routines. Often, it is more convenient to include the validation phase as an integral part of the transfer. This is often the case when your DDV routine doesn't require any parameters, since ClassWizard doesn't support DDV routines without any parameters.

= single identifier for the DDV_ procedure. The C++ function name must start with “DDV_” but don't include “DDX_” in the <DDX_Proc> identifier.

followed by 1 or 2 DDV args:

<promptX> =

string to place above the edit item (with & for accelerator)

<fmtX> =

format character for the arg type, one of

d = int

u = unsigned

D = long int (that is, long)

U = long unsigned (that is, DWORD)

f = float

F = double

s = string

An Example of Custom DDX

An example of custom DDX with validation can be found in the MFC Advanced Concepts sample CHKBOOK. See DDX_DollarsCents in DOLLCENT.CPP for an sample implementation of a custom DDX routine and CHKBOOK.CLW for the corresponding example ExtraDDXCount and ExtraDDX1 entries in the [General Info] section of CHKBOOK’s .CLW file.


TN027: Emulation Support for Visual Basic Custom Controls

Note VBX controls are not supported by this version of Visual C++.

The Visual C++ 1.0 (and 1.5) product for Windows 3.1 supports the use of VBX custom controls. This version of Visual C++ does not support VBX controls. This includes both the resource editor as well as runtime support in the MFC classes (CVBControl). The VBX API is inherently a 16-bit API packaged as 16-bit DLLs. 32-bit applications cannot directly call 16-bit DLLs, so calling a VBX from a 32-bit application is difficult at best.

Complicating the matter is the fact that the VBX API takes advantage of Intel segmentation to a great degree, using compiler extensions such as based pointers. This design (especially based pointers) does not mix well with the 32-bit flat address space of Win32 applications. If an application is dependent on VBX custom controls, it should be built as a 16-bit Windows application and run under the 16-bit emulation system in various Win32 operating systems.

OLE Controls (OCX) is a new custom control architecture for 32-bit systems. Building and using OLE Controls is fully supported in this version of Visual C++. See the product documentation for more information.


TN028: Context-Sensitive Help Support

This note describes the rules for assigning Help contexts IDs (that is, topic numbers) and other help issues in MFC 2.0. Context sensitive help support requires the help compiler which is available in Visual C++ Professional.

Types of Help Supported

There are two types of context-sensitive help implemented in Windows applications. The first, referred to as “F1 Help” involves launching WinHelp with the appropriate context based on the currently active object. The second is SHIFT+F1 mode. In this mode, the mouse cursor changes to the help cursor (a combination arrow + question mark), and the user proceeds to click on the object they'd like help on. At that point, WinHelp is launched giving help for the object on which the user clicked.

The Microsoft Foundation classes implement both of these forms of help. In addition, the framework supports two simple help commands, Help Index and Using Help.

Help Files

The Microsoft Foundation classes assume a single Help file. That Help file must have the same name and path as the application (.EXE -> .HLP).

This is a public CWinApp member variable named m_pszHelpFilePath that the user can change if desired.

Help Context Ranges

0x00000000 - 0x0000FFFF : user defined

0x00010000 - 0x0001FFFF : commands (menus/command buttons)

0x00010000 + ID_

(note: 0x18000-> 0x1FFFF is practical range since command IDs are >=0x8000)

0x00020000 - 0x0002FFFF : windows and dialogs

0x00020000 + IDR_

(note: 0x20000-> 0x27FFF is practical range since IDRs are <= 0x7FFF)

0x00030000 - 0x0003FFFF : error messages (based on error string ID)

0x00030000 + IDP_

0x00040000 - 0x0004FFFF : special purpose (non-client areas)

0x00040000 + HitTest area

0x00050000 - 0x0005FFFF : controls (those that are not commands)

0x00040000 + IDW_

These rules are hard-coded into the default implementation of the Microsoft Foundation classes. They can be overridden by providing different implementations of the various Help-related member functions.

Simple “Help” Commands

There are two simple Help commands that are implemented by the Microsoft Foundation classes:

  • ID_HELP_INDEX which is implemented by CWinApp::OnHelpIndex

  • ID_HELP_USING which is implemented by CWinApp::OnHelpUsing

These two commands simply show the Help index for the application and show the user help on using the WinHelp program, respectively.

Context-Sensitive Help (F1 Help)

This is the first form of context-sensitive Help (usually referred to as F1 Help). The user presses F1 to get help on the task at hand (the active window or menu item). No special “help mode” is involved.

The F1 key is usually translated to a command with an ID of ID_HELP by an accelerator placed into the main window's accelerator table. The ID_HELP command may also be generated by a button with an ID of ID_HELP on the main window or dialog box. Also, when a menu or a dialog box is active and the user presses F1, the keystroke is hard-coded to translate into an ID_HELP command.

However the ID_HELP command is generated, it is routed as a normal command until it reaches a command handler (for more information on the Microsoft Foundation classes command-routing architecture, refer to Technical Note 21.) If the application is Help enabled, the ID_HELP command will be handled by the CWinApp::OnHelp function. Since the default command routing is not adequate for determining the most specific context the command is instead always routed to the application object and then undergoes custom routing for Help.

CWinApp::OnHelp attempts to launch WinHelp in the following order:

  1. Checks for an active AfxMessageBox call with a Help ID. If a message box is currently active, WinHelp is launched with the context appropriate to that message box.

  2. If no message box is active, CWinApp::OnHelp sends a WM_COMMANDHELP (a message private to the Microsoft Foundation classes) to the active window. If that window does not respond by launching WinHelp, the same message is then sent to the parent of that window, until the message is processed or the current window is a top-level window (and therefore does not have a parent window).

  3. If the message remains unprocessed, then the default Help is invoked. This is done by sending a ID_DEFAULT_HELP command to the main window. This command is generally mapped to CWinApp::OnHelpIndex.

To globally override the ID base values (0x10000 for commands, 0x20000 for resources such as dialogs, and so on), the application should override CWinApp::WinHelp. This is in fact done in the implementation of the ClassWizard and AppWizard applications themselves, for example, since both share a single Help file.

To override this functionality and the way that a Help context is determined, an application should handle the WM_COMMANDHELP message (see below). You may wish to provide more specific Help routing than the framework provides, as it only goes as deep as the current MDI child window. Or you may wish to provide more specific help for a particular window or dialog -- perhaps based on the current internal state of that object or the active control within the dialog.

WM_COMMANDHELP

afx_msg LRESULT CWnd::OnCommandHelp(WPARAM, LPARAM lParam)

WM_COMMANDHELP is an MFC private Windows message that is received by the active window when Help is requested. When the window receives this message, it may call CWinApp::WinHelp with context that matches the window's internal state.

lParam

contains the currently available Help context. lParam is zero if no Help context has been determined yet. An implementation of OnCommandHelp can use the context ID in lParam to determine a “better” context or can just pass it to CWinApp::WinHelp.

wParam

is not used and will be zero.

If the OnCommandHelp function calls CWinApp::WinHelp, it should return TRUE. Returning TRUE stops the routing of this command to other classes (base classes) and to other windows.

Help Mode (Shift+F1 Help)

This is the second form of context-sensitive Help. Generally, this mode is entered by pressing SHIFT+F1 or via the menu/toolbar. It is implemented as a command (ID_CONTEXT_HELP). The message filter hook is not used to translate this command while a modal dialog box or menu is active, therefore this command is only available to the user when the application is executing the main message pump (CWinApp::Run).

After entering this mode, the Help mouse cursor is displayed over all areas of the application, even if the application would normally display it's own cursor for that area (such as the sizing border around the window). The user is able to use the mouse or keyboard to select a command. Instead of executing the command, Help on that command is displayed. Also the user can click a visible object on the screen, such as a button on the toolbar, and Help will be displayed for that object. This mode of Help is provided by CWinApp::OnContextHelp.

During the execution of this loop, all keyboard input is inactive, except for keys that access the menu. Also, command translation is still performed via PreTranslateMessage to allow the user to press an accelerator key and receive help on that command.

If there are particular translations or actions taking place in the PreTranslateMessage function that shouldn't take place during SHIFT+F1 Help mode, you should check the m_bHelpMode member of CWinApp before performing those operations. The CDialog implementation of PreTranslateMessage checks this before calling IsDialogMessage, for example. This disables “dialog navigation” keys on modeless dialogs during SHIFT+F1 mode. In addition, CWinApp::OnIdle is still called during this loop.

If the user chooses a command from the menu, it is handled as help on that command (through WM_COMMANDHELP, see below). If the user clicks a visible area of the applications window, a determination is made as to whether it is a nonclient click or a client click. OnContextHelp handles mapping of nonclient clicks to client clicks automatically. If it is a client click, it then sends a WM_HELPHITTEST to the window that was clicked. If that window returns a nonzero value, that value is used as the context for help. If it returns zero, OnContextHelp tries the parent window (and failing that, its parent, and so on). If a Help context cannot be determined, the default is to send a ID_DEFAULT_HELP command to the main window, which is then (usually) mapped to CWinApp::OnHelpIndex.

WM_HELPHITTEST

afx_msg LRESULT CWnd::OnHelpHitTest(WPARAM, LPARAM lParam)

WM_HELPHITTEST is an MFC private windows message, that is received by the active window clicked during SHIFT+F1 Help mode. When the Window receives this message, it returns a DWORD Help ID for use by WinHelp.

LOWORD(lParam)

contains the X-axis device coordinate where the mouse was clicked relative to the client area of the window.

HIWORD(lParam)

contains the Y-axis coordinate.

wParam

is not used and will be zero. If the return value is nonzero, WinHelp is called with that context. If the return value is zero, the parent window is queried for help.

In many cases, you can leverage hit-testing code you may already have. See the implementation of CToolBar::OnHelpHitTest for an example of handling the WM_HELPHITTEST message (the code leverages the hit-test code used on buttons and tooltips in CControlBar).

MFC AppWizard Support and MAKEHM

AppWizard creates the necessary files to build a Help file (.cnt and .hpj files). It also includes a number of prebuilt .RTF files that are accepted by the Microsoft Help Compiler. Many of the topics are complete, but some may need to be modified for your specific application.

Automatic creation of a “help mapping” file is supported by a utility called MAKEHM. The MAKEHM utility can translate an application's RESOURCE.H file to a Help mapping file. For example:

#define IDD_MY_DIALOG   2000
#define ID_MY_COMMAND   150

will be translated into:

HIDD_MY_DIALOG    0x207d0
HID_MY_COMMAND    0x10096

This format is compatible with the Help compiler's facility, which maps context IDs (the numbers on the right side) with topic names (the symbols on the left side).

The source code for MAKEHM is available in the MFC Programming Utilties sample MAKEHM.

Adding Help Support After Running AppWizard

The best way to add Help to your application is to check the “Context Sensitive Help” option in AppWizard's Options dialog before creating your application. That way AppWizard automatically adds the necessary message map entries to your CWinApp-derived class to support Help.

If you have already created your application without Help support and now wish to add it, see Visual C++ Programmer's Guide.

Help on Message Boxes

Help on Message Boxes (sometimes called alerts) is supported through the AfxMessageBox function, a wrapper for the MessageBox Windows API.

There are two versions of AfxMessageBox, one for use with a string ID and another for use with a pointer to string (LPCSTR):

int AFXAPI AfxMessageBox(LPCSTR lpszText, UINT nType, UINT nIDHelp);
int AFXAPI AfxMessageBox(UINT nIDPrompt, UINT nType, UINT nIDHelp);

In both cases, there is an optional Help ID.

In the first case, the default for nIDHelp is 0, which indicates no Help for this message box. If the user presses F1 while such as message box is active, the user will not receive Help (even if the application supports Help). If this is not desirable, a Help ID should be provided for nIDHelp.

In the second case, the default value for nIDHelp is -1, which indicates the Help ID is the same as nIDPrompt. Help will work only if the application is Help-enabled, of course). You should provide 0 for nIDHelp if you wish that the message box have no help support. Should you want the message to be Help enabled, but desire a different help ID than nIDPrompt, simply provide a positive value for nIDHelp different from that of nIDPrompt.


TN029: Splitter Windows

This note describes the MFC CSplitterWnd class, which is used to provide window splits and to manage the resizing of other Pane windows.

Note please be sure to read Technical Note 20 regarding use of IDs and valid ID ranges.

Splitter Styles

A CSplitterWnd supports two different styles of splitting windows.

In “static splitters,” the panes are created when the splitter window is created, and the order and number of panes never change. Splitter bars are used to resize the different panes, and the different panes are usually of different view classes. The Visual C++ graphics editor and the Windows File Manager are examples of programs that use this splitter style. Splitter boxes are not used by this style of splitter.

In “Dynamic splitters,” additional panes are created and destroyed as the user splits and un-splits new views. This splitter starts out with a single view, and splitter boxes are provided to initiate splitting. If the view is split in one direction, an additional view object is dynamically created to represent the new pane. If the view is split in two directions (possible with the keyboard interface), then three new views are created to represent the three new panes. When the split is active, the splitter box is drawn as a splitter bar between the panes. Additional view objects are destroyed when the user removes a split, but the original view (row 0, column 0) remains until the splitter window itself is destroyed. Microsoft Excel or Microsoft Word are examples of the dynamic splitter style.

When creating either kind of splitter window, you must specify the maximum number of rows and columns that the splitter will manage. For a static splitter, panes must be created to fill all the rows and columns. For a dynamic splitter, the first pane is automatically created when the CSplitterWnd is created.

The maximum number of panes you can specify for static splitters is 16 rows by 16 columns. The recommended configurations are:

  • 1 row x 2 columns : usually with dissimilar panes

  • 2 rows x 1 column : usually with dissimilar panes

  • 2 rows x 2 columns : usually with similar panes

The maximum number of panes you can specify for dynamic splitters is 2 rows by 2 columns. The recommended configurations are:

  • 1 row x 2 columns : for columnar data

  • 2 rows x 1 column : for textual or other data

  • 2 rows x 2 columns : for grid or table oriented data

Splitter Examples

Many of the MFC sample programs use splitter windows directly or indirectly. Step 4 of the MFC Tutorial SCRIBBLE adds a dynamic splitter window to split the CScribView into multiple panes. As shown in this step, adding a new splitter frame window is very easy with the Add Class feature of ClassWizard. This example is a dynamic splitter window by default.

The MFC General sample VIEWEX illustrates several uses of static splitters, including how to place a splitter in a splitter.

ClassWizard will also create a new multiple document interface (MDI) Child frame window class which contains a splitter window. Please refer to Splitter Windows in Visual C++ Programmer's Guide.

Terminology Used by Implementation

Terminology of the parts of a CSplitterWnd and related objects.

CSplitterWnd:

This is a window that provides pane-splitting controls and scroll bars that are shared between all panes on a row or column. Rows and columns are specified with zero-based numbers [that is, the first pane is row = 0 and column = 0]

Pane:

An application-specific window that is managed by a CSplitterWnd. A pane is usually a CView-derived object, but in fact can be any CWnd object that has the appropriate child window ID.

To do so, simply pass the RUNTIME_CLASS of your CWnd derived class as you would if you were using a CView derived class. Your class must use DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE -- the framework uses dynamic creation at runtime. Although there is a lot of code that is CView specific in CSplitterWnd, CObject::IsKindOf is always used before those actions are performed. Certainly, it is much easier to use CSplitterWnd with CView derived classes than CWnd derived classes.

Splitter Bar:

A control that is placed between rows and columns of panes. It may be used to adjust the sizes of rows or columns of Panes.

Splitter Box:

A small control at the top of the vertical scroll bars or to the left of the horizontal scroll bars in a dynamic CSplitterWnd. Used to create new rows or columns of panes.

Splitter Intersection:

The intersection of a vertical splitter bar and a horizontal splitter bar. May be dragged to adjust the size of a row and column of panes simultaneously.

Shared Scroll Bars

The CSplitterWnd class also supports shared scroll bars. These scroll bar controls are children of the CSplitterWnd and are shared with the different panes in the splitter.

For example, in a 1 row x 2 column window, you can specify WS_VSCROLL when creating the CSplitterWnd. A special scroll bar control will be created that is shared between the two panes.

[      ][      ][^]
[pane00][pane01][|]
[      ][      ][v]

When the user moves the scroll bar, WM_VSCROLL messages will be sent to both views. When the views set the scroll bar position, the shared scroll bar will be set.

Note that shared scroll bars are most useful with dynamic or static splits, splitting similar view objects. If you mix views of different types in a splitter, then you may have to write special code to coordinate their scroll positions. Any CView-derived class that uses the CWnd scroll bar APIs will delegate to the shared scroll bar if it exists. The CScrollView implementation is one such example of a CView class that supports shared scroll bars. Non-CView derived classes, classes that rely on noncontrol scroll bars, or classes that use standard Windows implementations (for example, CEditView) will not work with the shared scroll bar feature of CSplitterWnd.

Minimum Sizes

For each row there is a minimum row height, and similarly for each column there is a minimum column width. This minimum is used to decide if the pane is to small to be shown in complete detail.

For a static splitter window, the initial minimum row height and column width is 0. For a dynamic splitter window, the initial minimum row height and column width are set by the sizeMin parameter to the CSplitterWnd::Create function.

These minimum sizes can be changed with the SetRowInfo and SetColumnInfo APIs.

Actual vs. Ideal Sizes

The layout of the panes in the splitter window depends on the size of the containing frame (which in turn resizes the CSplitterWnd. CSplitterWnd repositions and resizes the panes so that they fit as ideally as possible).

The row height and column width sizes set by the user, or through the CSplitterWnd API, represent the ideal size. The actual size can be smaller than that ideal size (if there is not enough room to make that pane the ideal size) or larger than the ideal size (if that pane must be made larger to fill the left-over space on the right or bottom of the splitter window).

Protected Interface

The following describes some of the splitter window implementation overridables that can be used by advanced users of CSplitterWnd to customize the features and user interface of this class. These APIs are officially undocumented and are subject to change in future versions of MFC. Please refer to the implementation source code for more details on these implementation APIs.

Drawing the splitter bars, boxes and trackers:

enum ESplitType
    { splitBox, splitBar, splitIntersection, splitBorder };
virtual void OnDrawSplitter(CDC* pDC, ESplitType nType, const CRect& rect);
virtual void OnInvertTracker(const CRect& rect);

These virtual function can be overridden to provide alternate imagery for the various graphical components of a splitter window. The default imagery is similar to the splitter in Microsoft Works for Windows: only intersections of splitter bars are blended together. The imagery is also quite different when the framework detects Windows 4.0 -- in order to match the visuals in the shell on that (future) operating system.

Creating controls and views:

virtual BOOL CreateScrollBarCtrl(DWORD dwStyle, UINT nID);

This is called to create a shared scroll bar control. It can be overridden to include extra controls next to a scroll bar. The default behavior is to just create normal Windows scroll bar controls.

virtual void DeleteView(int row, int col);
virtual BOOL SplitRow(int cyBefore);
virtual BOOL SplitColumn(int cxBefore);
virtual void DeleteRow(int row);
virtual void DeleteColumn(int row);

These functions are called to implement the logic of the dynamic splitter window (that is, if the splitter window has the SPLS_DYNAMIC_SPLIT style). They can be customized, along with the virtual function CreateView, to implement more advanced dynamic splitters.

The following are high level commands that are used by the CView class to delegate to the CSplitterWnd implementation. They are virtual so that the standard CView implementation will not require the entire CSplitterWnd implementation to be linked in. For applications that use CView but not CSplitterWnd, the CSplitterWnd implementation will not be linked with the application.

virtual BOOL CanActivateNext(BOOL bPrev = FALSE);

Checks to see if the “Next Pane” or “Previous Pane” command is currently possible.

virtual void ActivateNext(BOOL bPrev = FALSE);

Performs the “Next Pane” or “Previous Pane” command.

virtual BOOL DoKeyboardSplit();

Performs the keyboard split command, usually “Window Split”.


TN030: Customizing Printing and Print Preview

This note describes the process of customizing printing and print preview and describes the purposes of the callback routines used in CView and the callback routines and member functions of CPreviewView.

The Problem

MFC provides a complete solution for most printing and print preview needs. In most cases, little additional code is required to have a view able to print and preview. However, there are ways to optimize printing that require significant effort on the part of the developer, and some applications need to add specific user interface elements to the print preview mode.

Efficient Printing

When an MFC application prints using the standard methods, Windows directs all Graphical Device Interface (GDI) output calls to an in-memory metafile. When EndPage is called, Windows plays the metafile once for each physical band that the printer requires to print one page. During this rendering, GDI frequently queries the Abort Procedure to determine if it should continue. Typically the abort procedure allows messages to be processed so that the user may abort the print job using a printing dialog.

Unfortunately, this can slow the printing process. If the printing in your application must be faster than can be achieved using the standard technique, you must implement manual banding.

Print Banding

In order to manually band, you must re implement the print loop such that OnPrint is called multiple times per page (once per band). The print loop is implemented in the OnFilePrint function in viewprnt.cpp. In your CView-derived class, you overload this function so that the message map entry for handling the print command calls your print function. Copy the OnFilePrint routine and change the print loop to implement banding. You will probably also want to pass the banding rectangle to your printing functions so that you can optimize drawing based on the section of the page being printed.

Second, you must frequently call QueryAbort while drawing the band. Otherwise, the Abort Procedure will not get called and the user will be unable to cancel the print job.

Print Preview: Electronic Paper with User Interface

Print Preview, in essence, tries to turn the display into an emulation of a printer. By default, the client area of the main window is used to display one or two pages fully within the window. The user is able to zoom in on an area of the page to see it in more detail. With additional support, the user may even be allowed to edit the document in preview mode.

Customizing Print Preview

This note only deals with one aspect of modifying print preview: Adding UI to preview mode. Other modifications are possible, but such changes are out of the scope of this discussion.

Briefly, the process of adding UI to the preview mode is to:

  1. Derive a view class from CPreviewView.

  2. Add command handlers for the UI aspects you desire.

  3. If you are adding visual aspects to the display, override OnDraw and perform your drawing after calling CPreviewView::OnDraw.

OnFilePrintPreview

This is the command handler for print preview. Its default implementation is:

void CView::OnFilePrintPreview()
{
    // In derived classes, implement special window handling here
    // Be sure to Unhook Frame Window close if hooked.

    // must not create this on the frame. Must outlive this function
    CPrintPreviewState* pState = new CPrintPreviewState;

    if (!DoPrintPreview(AFX_IDD_PREVIEW_TOOLBAR, this,
                RUNTIME_CLASS(CPreviewView), pState))
    {
        // In derived classes, reverse special window handling
        // here for Preview failure case

        TRACE0("Error: DoPrintPreview failed");
        AfxMessageBox(AFX_IDP_COMMAND_FAILURE);
        delete pState;      // preview failed to initialize,
                    // delete State now
    }
}

DoPrintPreview will hide the main pane of the application. Control Bars, such as the status bar, can be retained by specifying them in the pState->dwStates member (This is a bit mask and the bits for individual control bars are defined by AFX_CONTROLBAR_MASK( AFX_IDW_MYBAR)). The window pState->nIDMainPane is the window that will be automatically hidden and reshown. DoPrintPreview will then create a button bar for the standard Preview UI. If special window handling is needed, such as to hide or show other windows, that should be done before DoPrintPreview is called.

By default, when print preview finishes, it returns the control bars to their original states and the main pane to visible. If special handling is needed, it should be done in an override of EndPrintPreview. If DoPrintPreview fails, also provide special handling.

DoPrintPreview is called with:

  • The Resource ID of the dialog template for the preview toolbar.

  • A pointer to the view to perform the printing for the print preview

  • The run-time class of the Preview View class. This will be dynamically created in DoPrintPreview.

  • The CPrintPreviewState pointer. Note that the CPrintPreviewState structure (or the derived structure if the application needs more state preserved) must not be created on the frame. DoPrintPreview is modeless and this structure must survive until EndPrintPreview is called.

    Note If a separate view or view class is needed for printing support, a pointer to that object should be passed as the second parameter.

EndPrintPreview

This is called to terminate the print preview mode. It is often desirable to move to the page in the document that was last displayed in print preview. EndPrintPreview is the application's chance to do that. The pInfo->m_nCurPage member is the page that was last displayed (leftmost if two pages were displayed), and the pointer is a hint as to where on the page the user was interested. Since the structure of the application's view is unknown to the framework, the you must provide the code to move to the chosen point.

You should perform most actions before calling CView::EndPrintPreview. This call reverses the effects of DoPrintPreview and deletes pView, pDC, and pInfo.

// Any further cleanup should be done here.
CView::EndPrintPreview(pDC, pInfo, point, pView);

CWinApp::OnFilePrintSetup

This must be mapped for the Print Setup menu item. In most cases, it is not necessary to override the implementation.

Page Nomenclature

Another issue is that of page numbering and order. For simple word processor type applications, this is a straightforward issue. Most print preview systems assume that each printed page corresponds to one page in the document.

In trying to provide a generalized solution, there are several things to consider. Imagine a CAD system. The user has a drawing that covers several E-size sheets. On an E-size (or a smaller, scaled) plotter, page numbering would be as in the simple case. But on a laser printer, printing 16 A-size pages per sheet, what does print preview consider a “page”?

As the introductory paragraph states, Print Preview is acting like a printer. Therefore, the user will see what would come out of the particular printer that is selected. It is up to the view to determine what image is printed on each page.

The page description string in the CPrintInfo structure provides a means of displaying the page number to the user if it can be represented as one number per page (as in “Page 1” or “Pages 1-2”). This string is used by the default implementation of CPreviewView::OnDisplayPageNumber. If a different display is needed, one may override this virtual function to provide, for example, “Sheet1, Sections A, B”.


TN031: Control Bars

This note describes the control bar classes in MFC: the general CControlBar, CStatusBar, CToolBar, CDialogBar, and CDockBar.

CControlBar

A ControlBar is a CWnd-derived class that:

  • Is aligned to the top or bottom of a frame window.

  • May contain child items that are either HWND-based controls (for example, CDialogBar) or non-HWND based items (for example, CToolBar, CStatusBar).

Control bars support the additional styles:

  • CBRS_TOP (the default) pin the control bar to the top

  • CBRS_BOTTOM pin the control bar to the bottom

  • CBRS_NOALIGN don't reposition the control bar when the parent resizes

Classes derived from CControlBar provide more interesting implementations:

  • CStatusBar a status bar, items are status bar panes containing text

  • CToolBar a toolbar, items are bitmap buttons aligned in a row

  • CDialogBar a toolbar-like frame containing standard windows controls (created from a dialog template resource)

  • CDockBar a generalized docking area for other CControlBar derived objects. The specific member functions and variables available in this class are likely to change in future releases.

All control bar objects/windows will be child windows of some parent frame window. They are usually added as a sibling to the client area of the frame (for example, an MDI Client or view). The child window ID of a control bar is important. The default layout of control bar only works for control bars with IDs in the range of AFX_IDW_CONTROLBAR_FIRST to AFX_IDW_CONTROLBAR_LAST. Note that even though there is a range of 256 control bar IDs, the first 32 of these control bar IDs are special since they are directly supported by the print preview architecture.

The CControlBar class gives standard implementation for

  • Aligning the control bar to the top, bottom, or either side of the frame.

  • Allocating control item arrays.

  • Supporting the implementation of derived classes.

C++ control bar objects will usually be embedded as members of a CFrameWnd derived class, and will be cleaned up when the parent HWND and object are destroyed. If you need to allocate a control bar object on the heap, you can simply set the m_bAutoDestruct member to TRUE to make the control bar “delete this” when the HWND is destroyed.

Important If you create your own CControlBar-derived class, rather than using one of MFC's derived classes, such as CStatusBar, CToolBar, or CDialogBar, you will need to set the m_dwStyle data member. This can be done in the override of Create:

// CMyControlBar is derived from CControlBar
BOOL CMyControlBar::Create( CWnd* pParentWnd, DWORD dwStyle, UINT nID )
{
   m_dwStyle = dwStyle;

   .
   .
   .
}

Control Bar Layout Algorithm

The control bar layout algorithm is very simple. The frame window sends a message WM_SIZEPARENT to all children in the control bar range. Along with this message, a pointer to the parent's client rectangle is passed. This message is sent to children in Z-order. The control-bar children use this information to position themselves and to decrease the size of the parent's client area. The final rectangle that is left for the normal client area (less control bars) is used to position the main client window (usually an MDI client, view or splitter window).

See CWnd::RepositionBars and CFrameWnd::RecalcLayout for more details.

MFC private Windows messages, including WM_SIZEPARENT, are documented in Technical Note 24.

CStatusBar

A status bar is a control bar which has a row of text output panes. There are two common ways to use text output panes:

  • As a message line

    (for example, the standard menu help message line). These are usually accessed by a 0-based indexed

  • As status indicators

    (for example, the CAP, NUM and SCRL indicators). These are usually accessed by string/command ID.

The font for the status bar is 10 point “MS Sans Serif” (dictated by the Windows Interface Application Design Guide or the font mappers best match of a 10-point Swiss proportional font). On certain versions of Windows, such as the Japanese edition and Windows 4.0, the fonts selected are different.

The colors used in the status bar are also consistent with the recomendation of the Windows Interface Application Design Guide. These colors are not hard coded and are changed dynamically in response to user customization via the Control Panel.

Item | Windows COLOR value | Default RGB
Status bar background | COLOR_BTNFACE | RGB(192, 192, 192)
Status bar text | COLOR_BTNTEXT | RGB(000, 000, 000)
Status bar top/left edges | COLOR_BTNHIGHLIGHT | RGB(255, 255, 255)
Status bar bot/right edges | COLOR_BTNSHADOW | RGB(128, 128, 128)

CCmdUI Support for CStatusBar

The way indicators are usually updated is through the ON_UPDATE_COMMAND_UI mechanism. On idle time, the status bar will call the ON_UPDATE_COMMAND_UI handler with the string ID of the indicator pane.

The ON_UPDATE_COMMAND_UI handler can call:

  • Enable: to enable or disable the pane. A disabled pane looks exactly like an enabled pane but the text is invisible (that is, turns off the text indicator).

  • SetText: to change the text. Be careful if you use this since the pane will not automatically resize.

Please refer to class CStatusBar in the Class Library Reference for details about CStatusBar creation and customization APIs. Most customization of status bars should be done before the status bar is initially made visible.

The status bar supports only one stretchy pane, usually the first pane. The size of that pane is really a minimum size. If the status bar is bigger than the minimum size of all the panes, any extra width will be given to the stretchy pane. The default application with a status bar has right-aligned indicators for CAP, NUM and SCRL since the first pane is stretchy.

CToolBar

A toolbar is a control bar with a row of bitmap buttons that may include separators. Two styles of buttons are supported: pushbuttons and check box buttons. Radio group functionality can be built with check box buttons and ON_UPDATE_COMMAND_UI.

All the bitmap buttons in the toolbar are taken from one bitmap. This bitmap must contain one image or glyph for each button. Typically the order of the images/glyphs in the bitmap is the same order they will be drawn on the screen. (This can be changed using the customization APIs.)

Each button must be the same size. The default is the standard 24x22 pixels. Each image/glyph must be the same size and must be side-by-side in the bitmap. The default image/glyph size is 16x15 pixels. Therefore, for a toolbar with 10 buttons (using standard sizes), you need a bitmap that is 160 pixels wide and 15 pixels high.

Each button has one and only one image/glyph. The different button states and styles (for example, pressed, up, down, disabled, disabled down, indeterminate) are algorithmically generated from that one image/glyph. Any color bitmap or DIB can be used in theory. The algorithm for generating the different button states works best if the original image is shades of gray. Look at the standard toolbar buttons and the toolbar button clipart provided in MFC General sample CLIPART for examples.

The colors used in the toolbar are also consistent with the recommendation of the Windows Interface Application Design Guide. These colors are not hard coded and are changed dynamically in response to user customization via the Control Panel.

Item | Windows COLOR value | Default RGB
ToolBar background | COLOR_BTNFACE | RGB(192,192,192)
ToolBar buttons top/left edges | COLOR_BTNHIGHLIGHT | RGB(255,255,255)
ToolBar buttons bot/right edges | COLOR_BTNSHADOW | RGB(128,128,128)

In addition, the toolbar bitmap buttons are recolored as though they were standard Windows button controls. This recoloring occurs when the bitmap is loaded from the resource and in response to a change in system colors in response to user customization via the Control Panel. The following colors in a toolbar bitmap will be recolored automatically so they should be used with caution. If you do not wish to have a portion of your bitmap recolored, then use a color that closely approximates one of the mapped RGB values. The mapping is done based on exact RGB values.

RGB Value | Dynamically mapped COLOR value
RGB(000, 000, 000) | COLOR_BTNTEXT
RGB(128, 128, 128) | COLOR_BTNSHADOW
RGB(192, 192, 192) | COLOR_BTNFACE
RGB(255, 255, 255) | COLOR_BTNHIGHLIGHT

Please refer to class CToolBar the Class Library Reference for details about the CToolBar creation and customization APIs. Most customization of toolbars should be done before the toolbar is initially made visible.

The customization APIs can be used to adjust the button IDs, styles, spacer width and which image/glyph is used for what button. By default you do not need to use these APIs.

CCmdUI Support for CToolBar

The way toolbar buttons are always updated is through the ON_UPDATE_COMMAND_UI mechanism. On idle time, the toolbar will call the ON_UPDATE_COMMAND_UI handler with the command ID of that button. ON_UPDATE_COMMAND_UI is not called for separators, but it is called for pushbuttons and check box buttons.

The ON_UPDATE_COMMAND_UI handler can call:

  • Enable: to enable or disable the button. This works equally for pushbuttons and check box buttons.

  • SetCheck: to set the check state of a button. Calling this for a toolbar button will turn it into a check box button. SetCheck takes a parameter which can be 0 (not checked), 1 (checked) or 2 (indeterminate)

  • SetRadio: shorthand for SetCheck.

Check box buttons are “AUTO” check box buttons; that is, when the user presses them they will immediately change state. Checked is the down or depressed state. There is no built-in user interface way to change a button into the “indeterminate” state; that must be done through code.

The customization APIs will permit you to change the state of a given toolbar button, preferably you should change these states in the ON_UPDATE_COMMAND_UI handler for the command the toolbar button represents. Remember, the idle processing will change the state of toolbar buttons with the ON_UPDATE_COMMAND_UI handler, so any changes to these states made through SetButtonStyle may get lost after the next idle.

Toolbar buttons will send WM_COMMAND messages like normal buttons or menu items and are normally handled by an ON_COMMAND handler in the same class that provides the ON_UPDATE_COMMAND_UI handler.

There are four Toolbar button styles (TBBS_ values) used for display states:

  • TBBS_CHECKED: check box is currently checked (down)

  • TBBS_INDETERMINATE: check box is currently indeterminate

  • TBBS_DISABLED: button is currently disabled

  • TBBS_PRESSED: button is currently pressed

The six official Windows Interface Application Design Guide button styles are represented by the following TBBS values:

  • Up = 0

  • Mouse Down = TBBS_PRESSED (| any other style)

  • Disabled = TBBS_DISABLED

  • Down = TBBS_CHECKED

  • Down Disabled = TBBS_CHECKED | TBBS_DISABLED

  • Indeterminate = TBBS_INDETERMINATE

CDialogBar

A dialog bar is a control bar that contains standard Windows controls. It acts like a dialog in that it contains the controls and supports tabbing between them. It also acts like a dialog in that it uses a dialog template to represent the bar.

A CDialogBar is used for the print-preview toolbar, which contains standard pushbutton controls.

Using a CDialogBar is like using a CFormView. You must define a dialog template for the dialog bar and remove all the styles except WS_CHILD. Note that the dialog must not be visible.

The control notifications for a CDialogBar will be sent to the parent of the control bar (just like toolbar buttons).

CCmdUI Support for CDialogBar

Dialog bar buttons should be updated through the ON_UPDATE_COMMAND_UI handler mechanism. At idle time, the dialog bar will call the ON_UPDATE_COMMAND_UI handler with the command ID of all the buttons that have a ID >= 0x8000 (that is, in the range of command IDs).

The ON_UPDATE_COMMAND_UI handler can call:

  • Enable: to enable or disable the button.

  • SetText: to change the text of the button.

Customization can be done through standard window manager APIs.


TN032: MFC Exception Mechanism

Previous versions of Visual C++ did not support the standard C++ exception mechanism, and MFC provided macros TRY/CATCH/THROW which were used instead. This version of Visual C++ fully supports C++ exceptions. This note covered some of the advanced implementation details of the previous macros including how to automatically cleanup stack based objects. Because C++ exceptions support stack unwinding by default, this technical note is no longer necessary.

Please refer to Exceptions: Using MFC Macros and C++ Exceptions in Visual C++ Programmer's Guide for more information on the differences between the MFC macros and the new C++ keywords.


TN033: DLL Version of MFC

This note describes how you can use the MFCxx.DLL and MFCxxD.DLL (where x is the MFC version number) shared dynamic link libraries with MFC applications and extension DLLs. For more information about regular DLLs, see Using MFC as Part of a DLL.

This technical note covers three aspects of DLLs. The last two are for the more advanced users:

  • How you build an MFC Extension DLL

  • How you build an MFC application that uses the DLL version of MFC

  • How the MFC shared dynamic-link libraries are implemented

If you are interested in building a DLL using MFC that can be used with non-MFC applications (this is called a regular DLL), please refer to Technical Note 11.

Overview of MFCxx.DLL Support: Terminology and Files

Regular DLL: You use a regular DLL to build a stand-alone DLL using some of the MFC classes. Interfaces across the App/DLL boundary are “C” interfaces, and the client application does not have to be an MFC application.

This is the version of DLL support supported in MFC 1.0. It is described in Technical Note 11 and the MFC Advanced Concepts sample DLLTRACE.

Note As of Visual C++ version 4.0, the term USRDLL is obsolete and has been replaced by a regular DLL that statically links to MFC. You may also build a regular DLL that dynamically links to MFC.

MFC 3.0 (and above) supports regular DLLs with all the new functionality including the OLE and Database classes.

AFXDLL: This is also referred to as the shared version of the MFC libraries. This is the new DLL support added in MFC 2.0. The MFC library itself is in a number of DLLs (described below) and a client application or DLL dynamically links the DLLs that it requires. Interfaces across the application/DLL boundary are C++/MFC class interfaces. The client application MUST be an MFC application. This supports all MFC 3.0 functionality (excption: UNICODE is not supported for the database classes).

Note As of Visual C++ version 4.0, this type of DLL is referred to as an “Extension DLL.”

This note will use MFCxx.DLL to refer to the entire MFC DLL set, which includes:

  • Debug: MFCxxD.DLL (core), MFCOxxD.DLL (OLE), MFCDxxD.DLL (database), MFCNxxD.DLL (network), MFCSxxD.LIB (static)

  • Release: MFCxx.DLL (combined), MFCSxx.LIB (static)

  • Unicode Debug: MFCxxUD.DLL (core), MFCOxxUD.DLL (OLE), MFCDxxUD.DLL (database), MFCNxxUD.DLL (network), MFCSxxD.LIB (static)

  • Unicode Release: MFCxxU.DLL (combined), MFCSxxU.LIB (static)

Note The MFCSxx[U][D].LIB libraries are used in conjunction with the MFC shared DLLs. These libraries contain code that must be statically linked to the application or DLL.

An application links to the corresponding import libraries:

  • Debug: MFCxxD.LIB, MFCOxxD.LIB, MFCDxxD.LIB, MFCNxxD.LIB

  • Release: MFCxx.LIB

  • Unicode Debug: MFCxxUD.LIB, MFCOxxUD.LIB, MFCDxxUD.LIB, MFCNxxUD.LIB

  • Unicode Release: MFCxxU.LIB

An “MFC Extension DLL” is a DLL built upon MFCxx.DLL (and/or the other MFC shared DLLs). Here the MFC component architecture kicks in. If you derive a useful class from an MFC class, or build another MFC-like toolkit, you can place it in a DLL. That DLL uses MFCxx.DLL, as does the ultimate client application. This permits reusable leaf classes, reusable base classes, and reusable view/document classes.

Note It is not necessary to link with the MFCOxx[U]D, MFCDxx[U]D, or MFCNxx[U]D Debug libraries unless your application uses the MFC/OLE, database, or networking classes respectively.

Pros and Cons

Why should you use the shared version of MFC?

  • Using the shared library can result in smaller applications [a minimal application that uses most of the MFC library is less than 10K].

  • The shared version of MFC supports MFC Extension DLLs and regular DLLs.

  • Building an application that uses the shared MFC libraries is faster than building a statically linked MFC application because it is not necessary to link MFC itself. This is especially true in DEBUG builds where the linker must compact the debug information -- by linking with a DLL that already contains the debug information, there is less debug information to compact within your application.

Why should you not use the shared version of MFC:

  • Shipping an application that uses the shared library requires that you ship the MFCxx.DLL (and others) library with your program. MFCxx.DLL is freely redistributable like many DLLs, but you still must install the DLL in your SETUP program. In addition, you must ship the MSVCRTxx.DLL, which contains the C-runtime library which is used both by your program and the MFC DLLs themselves.

How to Write an MFC Extension DLL

An MFC Extension DLL is a DLL containing classes and functions written to embellish the functionality of the MFC classes. The OLE and database debug support DLLs (MFCOxxD.DLL and MFCDxxD.DLL) are examples of MFC extension DLLs in that they use MFCxxD.DLL. An MFC Extension DLL uses the shared MFC DLLs in the same way an application uses it, with a few additional considerations:

  • The build process is similar to building an application that uses the shared MFC libraries with a few additional compiler and linker options.

  • An MFC Extension DLL does not have a CWinApp derived class.

  • An MFC Extension DLL must provide a special DllMain. AppWizard supplies a DllMain function that you can modify.

  • An MFC Extension DLL will usually provide an initialization routine to create a CDynLinkLibrary if the extension DLL wishes to export CRuntimeClasses or resources to the application. A derived class of CDynLinkLibrary may be used if per-application data must be maintained by the extension DLL.

These considerations are described in more detail below. You should also refer to the MFC Advanced Concepts sample DLLHUSK since it illustrates:

  • Building an application using the shared libraries. (DLLHUSK.EXE is an MFC application that dynamically links to the MFC libraries as well as other DLLs.)

  • Building an MFC Extension DLL. (Note the special flags such as _AFXEXT that are used in building an extension DLL)

  • Two examples of MFC Extension DLLs. One shows the basic structure of an MFC Extension DLL with limited exports (TESTDLL1) and the other shows exporting an entire class interface (TESTDLL2).

Both the client application and any extension DLLs must use the same version of MFCxx.DLL. You should follow the convention of MFC DLL and provide both a debug and retail (/release) version of your extension DLL. This permits client programs to build both debug and retail versions of their applications and link them with the appropriate debug or retail version of all DLLs.

Note Due to C++ name mangling and export issue, the export list from an extension DLL may be different between the debug and retail versions of the same DLL and DLLs for different platforms. The retail MFCxx.DLL has about 2000 exported entry points; the debug MFCxxD.DLL has about 3000 exported entry points.

Quick Note on Memory Management

The section titled “Memory Management,” near the end of this technical note, describes the implementation of the MFCxx.DLL with the shared version of MFC. The information you need to know to implement just an extension DLL is described here.

MFCxx.DLL and all extension DLLs loaded into a client application's address space will use the same memory allocator, resource loading and other MFC “global” states as if they were in the same application. This is significant because the non-MFC DLL libraries and regular DLLs that statically link to MFC do the exact opposite and have each DLL allocating out of its own memory pool.

If an extension DLL allocates memory, then that memory can freely intermix with any other application-allocated object. Also, if an application that uses the shared MFC libraries crashes, the protection of the operating system will maintain the integrity of any other MFC application sharing the DLL.

Similarly other “global” MFC states, like the current executable file to load resources from, are also shared between the client application and all MFC extension DLLs as well as MFCxx.DLL itself.

Building an Extension DLL

You can use AppWizard to create an MFC extension DLL project, and it will automatically generate the appropriate compiler and linker settings. It was also generate a DllMain function that you can modify.

If you are converting an existing project to an MFC extension DLL, start with the standard rules for building an application using the shared version of MFC, then do the following:

  • Add /D_AFXEXT to the compiler flags. On the Project Settings dialog, select the C/C++ tab. Then select the Preprocessor category. Add _AFXEXT to the Preprocessor Definitions field, separating each of the items with commas.

  • Remove the /Gy compiler switch On the Project Setting dialog, select the C/C++ tab. Then select the C Language category. Ensure that the "Enable Function-Level Linking" checkbox is cleared. This will make it easier to export classes because the linker will not remove unreferenced functions. If the original project is used to build a Regular DLL statically linked to MFC, change the /MT[d] compiler option to /MD[d].

  • Build an export library with the /DLL option to LINK. This will be set when you create a new target, specifying Win32 Dynamic-Link Library as the target type.

Changing your Header Files

The goal of an extension DLL is usually to export some common functionality to one or more applications which can use that functionality. This boils down to exporting classes and global functions which are available for your client applications.

In order to do this you must insure that each of the member functions is marked as import or export as appropriate. This requires special declarations: __declspec(dllexport) and __declspec(dllimport). When your classes are used by the client applications, you want them to be declared as __declspec(dllimport). When the extension DLL itself is being built, they should be declared as __declspec(dllexport). In addition, the functions must be actually exported, so that the client programs bind to them at load time.

To export your entire class, use AFX_EXT_CLASS in the class definition. This macro is defined by the framework as __declspec(dllexport) when _AFXDLL and _AFXEXT is defined, but defined as __declspec(dllimport) when _AFXEXT is not defined. _AFXEXT as described above, is only defined when building your extension DLL. For example:

class AFX_EXT_CLASS CExampleExport : public CObject
{ ... class definition ... };

Not Exporting the Entire Class

Sometimes you may want to export just the individual necessary members of your class. For example, if you are exporting a CDialog-derived class, you might only need to export the constructor and the DoModal call. You can export these members using the DLL's .DEF file, but you can also use AFX_EXT_CLASS in much the same way on the individual members you need to export.

For example:

class CExampleDialog : public CDialog
{
public:
   AFX_EXT_CLASS CExampleDialog();
   AFX_EXT_CLASS int DoModal();
   // rest of class definition
   .
   .
   .
};

When you do this, you may run into an additional problem due to the fact that you are no longer exporting all members of the class. The problem is in the way that MFC macros work. Several of MFC's helper macros actually declare or define data members. Therefore, these data members will also need to be exported from your DLL.

For example, the DECLARE_DYNAMIC macro is defined as follows when building an extension DLL:

#define DECLARE_DYNAMIC(class_name) \
protected: \
   static CRuntimeClass* PASCAL _GetBaseClass(); \
   public: \
   static AFX_DATA CRuntimeClass class##class_name; \
   virtual CRuntimeClass* GetRuntimeClass() const; \

The line that begins "static AFX_DATA" is declaring a static object inside of your class. To export this class correctly and access the runtime information from a client .EXE, you need to export this static object. Because the static object is declared with the modifier AFX_DATA, you only need to define AFX_DATA to be __declspec(dllexport) when building your DLL and define it as __declspec(dllimport) when building your client executable.

As discussed above, AFX_EXT_CLASS is already defined in this way. So you just need to re-define AFX_DATA to be the same as AFX_EXT_CLASS around your class definition.

For example:

   #undef  AFX_DATA
   #define AFX_DATA AFX_EXT_CLASS
   class CExampleView : public CView
   {
     DECLARE_DYNAMIC()
     // ... class definition ...
   };
   #undef  AFX_DATA
   #define AFX_DATA

MFC always uses the AFX_DATA symbol on data items it defines within its macros, so this technique will work for all such scenarios. For example it will work for DECLARE_MESSAGE_MAP.

Note If you are exporting the entire class rather than selected members of the class, static data members are automatically exported.

You can use the same technique to automatically export the CArchive extraction operator for classes that use the DECLARE_SERIAL and IMPLEMENT_SERIAL macros. Export the archive operator by bracketing the class declarations (located in the .H file) with the following code:

#undef AFX_API
#define AFX_API AFX_EXT_CLASS

<your class declarations here>

#undef AFX_API
#define AFX_API

Limitations of _AFXEXT

You can use the _AFXEXT pre-processor symbol for your extension DLLs as long as you do not have multiple layers of extension DLLs. If you have extension DLLs which call or derive from classes in your own extension DLLs, which then derive from the MFC classes, you must use your own preprocessor symbol to avoid ambiguity.

The problem is that in Win32, you must explicitly declare any data as __declspec(dllexport) if it is to be exported from a DLL, and __declspec(dllimport) if it is to be imported from a DLL. When you define _AFXEXT, the MFC headers make sure that AFX_EXT_CLASS is defined correctly.

When you have multiple layers, one symbol such as AFX_EXT_CLASS is not sufficient, since an extension DLL may be exporting new classes as well as importing other classes from another extension DLL. In order to deal with this problem, use a special pre-processor symbol which indicates that you are building the DLL itself versus using the DLL. For example, imagine two extension DLLs, A.DLL, and B.DLL. They each export some classes in A.H and B.H, respectively. B.DLL uses the classes from A.DLL. The header files would look something like this:

// A.H
#ifdef A_IMPL
   #define CLASS_DECL_A   __declspec(dllexport)
#else
   #define CLASS_DECL_A   __declspec(dllimport)
#endif

class CLASS_DECL_A CExampleA : public CObject
{ ... class definition ... };

// B.H
#ifdef B_IMPL
   #define CLASS_DECL_B   __declspec(dllexport)
#else
   #define CLASS_DECL_B   __declspec(dllimport)
#endif

class CLASS_DECL_B CExampleB : public CExampleA
{ ... class definition .. };

When A.DLL is built, it is built with /D A_IMPL and when B.DLL is built, it is built with /D B_IMPL. By using separate symbols for each DLL, CExampleB is exported and CExampleA is imported when building B.DLL. CExampleA is exported when building A.DLL and imported when used by B.DLL (or some other client).

This type of layering cannot be done when using the built-in AFX_EXT_CLASS and _AFXEXT pre-processor symbols. The technique described above solves this problem in a manner not unlike the mechanism MFC itself uses when building its OLE, Database, and Network extension DLLs.

Not Exporting the Entire Class

Again you will have to take special care when you are not exporting an entire class. You have to ensure that the necessary data items created by the MFC macros are exported correctly. This can be done by re-defining AFX_DATA to your specific class' macro. This should be done any time you are not exporting the entire class.

For example:

// A.H
#ifdef A_IMPL
   #define CLASS_DECL_A  _declspec(dllexport)
#else
   #define CLASS_DECL_A  _declspec(dllimport)
   #endif

#undef  AFX_DATA
#define AFX_DATA CLASS_DECL_A

class CExampleA : public CObject
{
   DECLARE_DYNAMIC()
   CLASS_DECL_A int SomeFunction();
   //class definition
   .
   .
   .
};

#undef AFX_DATA
#define AFX_DATA

DllMain

The following is the exact code you should place in your main source file for your extension DLL. It should come after the standard includes. Note that when you use AppWizard to create starter files for an extension DLL, it supplies a DllMain for you.

#include "afxdllx.h"

static AFX_EXTENSION_MODULE extensionDLL;

extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
   if (dwReason == DLL_PROCESS_ATTACH)
   {
      // Extension DLL one-time initialization
      if (!AfxInitExtensionModule(
             extensionDLL, hInstance))
         return 0;

      // TODO: perform other initialization tasks here
   }
   else if (dwReason == DLL_PROCESS_DETACH)
   {
      // Extension DLL per-process termination
      AfxTermExtensionModule(extensionDLL);

          // TODO: perform other cleanup tasks here
   }
   return 1;   // ok
}

The call to AfxInitExtensionModule captures the modules runtime-classes (CRuntimeClass structures) as well as its object factories (COleObjectFactory objects) for use later when the CDynLinkLibrary object is created. The (optional) call to AfxTermExtensionModule allows MFC to cleanup the extension DLL when each process detaches (which happens when the process exits, or when the DLL is unloaded as a result of a FreeLibrary call) from the extension DLL. Since most extension DLLs are not dynamically loaded (usually, they are linked via their import libraries), the call to AfxTermExtensionModule is usually not necessary.

If your application loads and frees extension DLLs dynamically, be sure to call AfxTermExtensionModule as shown above. Also be sure to use AfxLoadLibrary and AfxFreeLibrary (instead of Win32 functions LoadLibrary and FreeLibrary) if your application uses multiple threads. Using AfxLoadLibrary and AfxFreeLibrary insures that the startup and shutdown code which executes when the extension DLL is loaded and unloaded does not corrupt the global MFC state.

The header file AFXDLLX.H contains special defintions for structures used in extension DLLs, such as the definition for AFX_EXTENSION_MODULE and CDynLinkLibrary.

The global extensionDLL must be declared as shown. Unlike the 16-bit version of MFC, you can allocate memory and call MFC functions during this time, since the MFCxx.DLL is fully initialized by the time your DllMain is called.

Sharing Resources and Classes

Simple MFC extension DLLs need only export a few low-bandwidth functions to the client application and nothing more. More user-interface intensive DLLs may want to export resources and C++ classes to the client application.

Exporting resources is done through a resource list. In each application is a singly linked list of CDynLinkLibrary objects. When looking for a resource, most of the standard MFC implementations that load resources look first at the current resource module (AfxGetResourceHandle) and if not found walk the list of CDynLinkLibrary objects attempting to load the requested resource.

Dynamic creation of C++ objects given a C++ class name is similar. The MFC object deserialization mechanism needs to have all of the CRuntimeClass objects registered so that it can reconstruct by dynamically creating C++ object of the required type based on what was stored earlier.

If you want the client application to use classes in your extension DLL that are DECLARE_SERIAL, then you will need to export your classes to be visible to the client application. This is also done by walking the CDynLinkLibrary list.

In the case of the MFC Advanced Concepts sample DLLHUSK, the list looks something like:

head ->   DLLHUSK.EXE   - or -   DLLHUSK.EXE
               |                      |
          TESTDLL2.DLL           TESTDLL2.DLL
               |                      |
          TESTDLL1.DLL           TESTDLL1.DLL
               |                      |
           MFCO42D.DLL                |
               |                      |
           MFCD42D.DLL                |
               |                      |
            MFC42D.DLL            MFC42.DLL

The MFCxx.DLL is usually last on the resource and class list. MFCxx.DLL includes all of the standard MFC resources, including prompt strings for all the standard command IDs. Placing it at the tail of the list allows DLLs and the client application itself to not have a their own copy of the standard MFC resources, but to rely on the shared resources in the MFCxx.DLL instead.

Merging the resources and class names of all DLLs into the client application's name space has the disadvantage that you have to be careful what IDs or names you pick. You can of course disable this feature by not exporting either your resources or a CDynLinkLibrary object to the client application. The DLLHUSK sample manages the shared resource name space by using multiple header files. See Technical Note 35 for more tips on using shared resource files.

Initializing the DLL

As mentioned above, you will usually want to create a CDynLinkLibrary object in order to export your resources and classes to the client application. You will need to provide an exported entry point to initialize the DLL. Minimally this is a void routine that takes no arguments and returns nothing, but it can be anything you like.

Each client application that wants to use your DLL must call this initialization routine, if you use this approach. You may also allocate this CDynLinkLibrary object in your DllMain just after calling AfxInitExtensionModule.

The initialization routine must create a CDynLinkLibrary object in the current application's heap, wired up to your extension DLL information. This can be done with the following:

extern "C" extern void WINAPI InitXxxDLL()
{
   new CDynLinkLibrary(extensionDLL);
}

The routine name, InitXxxDLL in this example, can be anything you want. It does not need to be extern “C”, but doing so makes the export list easier to maintain.

Note If you use your extension DLL from a regular DLL, you must export this initialization function. This function must be called from the regular DLL before using any extension DLL classes or resources.

Exporting Entries

The simple way to export your classes is to use __declspec(dllimport) and __declspec(dllexport) on each class and global function you wish to export. This makes it a lot easier, but is less efficient than naming each entry point (described below) since you have less control over what functions get exported and you cannot export the functions by ordinal. This is the method that both TESTDLL1 and TESTDLL2 use to export their entries.

A more efficient method (and the method used by MFCxx.DLL) is to export each entry by hand by naming each entry in the .DEF file. Since we are exporting selective exports from our DLL (that is, not everything), we must decide which particular interfaces we wish to export. This is difficult since you must specify the mangled names to the linker in the form of entries in the .DEF file. Don't export any C++ classes unless you really need to have a symbolic link for it.

If you have tried exporting C++ classes with a .DEF file before, you may want to develop a tool to generate this list automatically. This can be done using a two stage link process. Link your DLL once with no exports, and allow the linker to generate a .MAP file. The .MAP file can be used to generate a list of functions which should be exported, so with some munging, it can be used to generate your EXPORT entries for your .DEF file. The export list for MFCxx.DLL and the OLE and Database extension DLLs, several thousand in number, was generated with such a process (although it is not completely automatic and requires some hand tuning every once in a while).

CWinApp vs. CDynLinkLibrary

An MFC Extension DLL does not have a CWinApp-derived object of its own; instead it must work with the CWinApp-derived object of the client application. This means that the client application owns the main message pump, the idle loop and so on.

If your MFC Extension DLL needs to maintain extra data for each application, you can derive a new class from CDynLinkLibrary and create it in the InitXxxDLL routine describe above. When running, the DLL can check the current application's list of CDynLinkLibrary objects to find the one for that particular extension DLL.

Using Resources in Your DLL Implementation

As mentioned above, the default resource load will walk the list of CDynLinkLibrary objects looking for the first EXE or DLL which has the requested resource. All MFC APIs as well as all the internal code uses AfxFindResourceHandle to walk the resource list to find any resource, no matter where it may reside.

If you wish to only load resources from a specific place, use the APIs AfxGetResourceHandle and AfxSetResourceHandle to save the old handle and set the new handle. Be sure to restore the old resource handle before you return to the client application. The sample TESTDLL2 uses this approach for explicitly loading a menu.

Walking the list has the disadvantages that it is slightly slower and requires managing resource ID ranges. It has the advantage that a client application that links to several extension DLLs can use any DLL-provided resource without having to specify the DLL instance handle. AfxFindResourceHandle is an API used for walking the resource list to look for a given match. It takes the name and type of a resource and returns the resource handle where it was first found (or NULL).

Writing an Application That Uses the DLL Version

Application Requirements

An application that uses the shared version of MFC must follow a few simple rules:

  • It must have a CWinApp object and follow the standard rules for a message pump.

  • It must be compiled with a set of required compiler flags (see below).

  • It must link with the MFCxx import libraries. By setting the required compiler flags, the MFC headers determine at link time which library the application should link with.

  • To run the executable, MFCxx.DLL must be on the path or in the Windows system directory.

Building with the Development Environment

If you are using the internal makefile with most of the standard defaults, you can easily change the project to build the DLL version.

The following step assumes you have a correctly functioning MFC application linked with NAFXCWD.LIB (for debug) and NAFXCW.LIB (for retail) and you want to convert it to use the shared version of the MFC library. You are running the Visual C++ environment and have an internal project file.

  4. Select Settings from the Build menu. In the General page under Project Settings, set Microsoft Foundation Classes to Use MFC in a Shared DLL (MFCxx(d).dll).

Building with NMAKE

If you are using the external makefile feature of the Visual C++, or are using NMAKE directly, you will have to edit your makefile to support compiler and linker options

Required compiler flags:

/D_AFXDLL /MD

/D_AFXDLL

The standard MFC headers need this symbol to be defined:

/MD

The application must use the DLL version of the C-runtime library

All other compiler flags follow the MFC defaults (for example, _DEBUG for debug).

Edit the linker list of libraries. Change NAFXCWD.LIB to MFCxxD.LIB and change NAFXCW.LIB to MFCxx.LIB. Add MFCOxx[U]D.LIB, MFCDxx[U]D.LIB, and MFCNxx[U]D.LIB as appropriate (required for with use of the MFC/OLE, database, or networking classes). Replace LIBC.LIB with MSVCRT.LIB. As with any other MFC library it is important that MFCxxD.LIB is placed before any C-runtime libraries.

Optionally add /D_AFXDLL to both your retail and debug resource compiler options (the one that actually compiles the resources with /R). This makes your final executable smaller by sharing the resources that are present in the MFC DLLs.

A full rebuild is required after these changes are made.

Building the Samples

Most of the MFC sample programs can be built from Visual C++ or from a shared NMAKE-compatible MAKEFILE from the command line.

To convert any of these samples to use MFCxx.DLL, you can load the .MAK file into the Visual C++ and set the Project options as described above. If you are using the NMAKE build, you can specify “AFXDLL=1” on the NMAKE command line and that will build the sample using the shared MFC libraries.

The MFC Advanced Concepts sample DLLHUSK is built with the DLL version of MFC. This sample not only illustrates how to build an application linked with MFCxx.DLL, but it also illustrates other features of the MFC DLL packaging option such as MFC Extension DLLs described later in this technical note.

Packaging Notes

The retail version of the DLLs (MFCxx[U].DLL) are freely redistributable. The debug version of the DLLs are not freely redistributable and should be used only during the development of your application.

The debug DLLs are provided with debugging information. By using the Visual C++ debugger, you can trace execution of your application as well as the DLL. The Release DLLs (MFCxx[U].DLL) do not contain debugging information.

If you customize or rebuild the DLLs, then you should call them something other than “MFCxx” The MFC SRC file MFCDLL.MAK describes build options and contains the logic for renaming the DLL. This rule also applies to the MFC/OLE, database, and network DLLs which are built by MFCOLE.MAK, MFCDB.MAK, and MFCNET.MAK, respectively. Renaming the files is necessary, since these DLLs are potentially shared by many MFC applications. Having your custom version of the MFC DLLs replace those installed on the system may break another MFC application using the shared MFC DLLs.

Rebuilding the MFC DLLs is not recommended.

How the MFCxx.DLL Is Implemented

The following section describes how the MFC DLL (MFCxx.DLL and MFCxxD.DLL) is implemented. Understanding the details here are also not important if all you want to do is use the MFC DLL with your application. The details here are not essential for understanding how to write an MFC extension DLL, but understanding this implementation may help you write your own DLL.

Implementation Overview

The MFC DLL is really a special case of an MFC Extension DLL as described above. It has a very large number of exports for a large number of classes. There are a few additional things we do in the MFC DLL that make it even more special than a regular Extension DLL.

Win32 Does Most of the Work

The 16-bit version of MFC needed a number of special techniques including per-app data on the stack segment, special segments created by some 80x86 assembly code, per-process exception contexts, and other techniques. Win32 directly supports per-process data in a DLL, which is what you want most of the time. For the most part MFCxx.DLL is just NAFXCW.LIB packaged in a DLL. If you look at the MFC source code, you'll find very few #ifdef _AFXDLL, since there are very few special cases that need to be made. The special cases that are there are specifically to deal with Win32 on Windows 3.1 (otherwise known as Win32s). Win32s does not support per-process DLL data directly so the MFC DLL must use the thread-local storage (TLS) Win32 APIs to obtain process local data.

Impact on Library Sources, Additional Files

The impact of the _AFXDLL version on the normal MFC class library sources and headers is relatively minor. There is a special version file (AFXV_DLL.H) as well as an additional header file (AFXDLL_.H) included by the main AFXWIN.H header. The AFXDLL_.H header includes the CDynLinkLibrary class and other implementation details of both _AFXDLL applications and MFC Extension DLLs. The AFXDLLX.H header is provided for building MFC Extension DLLs (see above for details).

The regular sources to the MFC library in MFC SRC have some additional conditional code under the _AFXDLL #ifdef. An additional source file (DLLINIT.CPP) contains the extra DLL initialization code and other glue for the shared version of MFC.

In order to build the shared version of MFC, additional files are provided. (See below for details on how to build the DLL.)

  • A special makefile (MFCDLL.MAK) is used for building the DLLs. This makefile includes the standard MAKEFILE to get all the normal MFC library building rules.

  • Two .DEF files are used for exporting the MFC DLL entry points for debug (MFCxxD.DEF) and release (MFCxx.DEF) versions of the DLL.

  • An .RC file (MFCDLL.RC) contains all the standard MFC resources and a VERSIONINFO resource for the DLL.

  • A .CLW file (MFCDLL.CLW) is provided to allow browsing the MFC classes using ClassWizard. Note: this feature is not particular to the DLL version of MFC.

Building the MFC DLL

Rebuilding the MFC DLL is intentionally difficult, so you think twice (or three times) before doing it. If you understand the potential packaging problems and redistribution restrictions described below, and you still really need to rebuild the MFC DLL, you can.

The MFCDLL.MAK file will build the Debug DLL with CodeView info:

NMAKE /f mfcdll.mak DEBUG=1 LIBNAME=MYMFC

The MFCDLL.MAK file will build the Release DLL without CodeView info:

NMAKE /f mfcdll.mak DEBUG=0 LIBNAME=MYMFC

(similarly, you use MFCOLE.MAK, MFCDB.MAK, and MFCNET.MAK to build the MFCOxxD.DLL, MFCDxxD.DLL, and MFCNxxD.DLL -- the DLLs which contain the MFC/OLE, database, and network classes)

This will build a private version of the MFC DLL in your MFC SRC directory with the standard MFCxx.DLL and MFCxxD.DLL names. You will need to copy them to an appropriate place on your path to use the new DLLs. The MFCDLL.MAK makefile will also rebuild the import libraries (MFCxx.LIB and MFCxxD.LIB) and place them in the standard MFC LIB directory. This will replace the prebuilt MFCxx.LIB and MFCxxD.LIB libraries, so please be careful.

If you wish to redistribute a modified version of the MFC DLL library, please be sure to change the name of the DLL in the MFCDLL.MAK makefile and the two .DEF files. See the makefile MFCDLL.MAK for more info.

You may modify the library and redistribute a retail (/release) of your modified library only if you rename it to something other than MFCxx.DLL. You may not redistribute the debug version of either the pre-built or custom built debug DLL.

These redistribution restrictions are primarily to avoid a proliferation of nonstandard and potentially virus containing DLLs. Ideally you should not need to rebuild the DLLs and if you redistribute your application with the prebuilt MFCxx.DLL provided with the Visual C++ product, you will avoid a lot of problems for yourself and your users.

Memory Management

An application using MFCxx.DLL uses a common memory allocator provided by MSVCRTxx.DLL, the shared C-runtime DLL. Both the application, any extension DLLs, as well as the MFC DLLs themselves, use this shared memory allocator. By using a shared DLL for memory allocation, the MFC DLLs can allocate memory which is later freed by the application or vice-versa. Because both the application and the DLL must use the same allocator, you should not override the C++ global operator new or operator delete. The same rules apply to the rest of the C-runtime memory allocation routines (such as malloc, realloc, free, etc.).

Ordinals and class __declspec(dllexport) and DLL naming

We do not use the class __declspec(dllexport) functionality of the C++ compiler. Instead, a list of exports is included with the class library sources (MFCxx.DEF and MFCxxD.DEF). Only these select set of entry points (functions and data) are exported. Other symbols, such as MFC private implementation functions or classes, are not exported All exports are done by ordinal without a string name in the resident or non-resident name table.

Using class __declspec(dllexport) may be a viable alternative for building smaller DLLs, but in the case of a large DLL like MFC, the default exporting mechanism has efficiency and capacity limits.

What this all means is that we can package a large amount of functionality in the release MFCxx.DLL that is only around 800 KBytes without compromising much execution or loading speed. MFCxx.DLL would have been 100K larger had this technique not been used.This also makes it possible to add additional entry points at the end of the .DEF file to allow simple versioning without compromising the speed and size efficiency of exporting by ordinal. Major version revisions in the MFC class library will change the library name. That is, MFC30.DLL is the redistributable DLL containing version 3.0 of the MFC class library. An upgrade of this DLL, say, in a hypothetical MFC 3.1, the DLL would be named MFC31.DLL instead. Again, if you modify the MFC source code to produce a custom version of the MFC DLL, please use a different name (and preferably one without “MFC” in the name).


TN034: Writing a Windows 3.0 Compatible MFC Application

Note This Technical Note is not applicable to Windows NT.

The initial release of Windows NT contains the Windows 3.1 features. Therefore, the support for the older Windows 3.0 programming has been removed from the MFC provided with this version of Visual C++.


TN035: Using Multiple Resource Files and Header Files with Visual C++

This note describes how the Visual C++ resource editor supports multiple resource files and header files shared in a single project or shared across multiple projects and how you can take advantage of that support. This note answers these questions:

  • When might you want to split a project into multiple resource files and/or header files, and how you do it?

  • How do you share a common header .H file between two .RC files?

  • How do you divide project resources into multiple .RC files?

  • How do you (and the tools) manage build dependencies between .RC, .CPP, and .H files?

You should be aware that if you add an additional resource file to your project, ClassWizard will not recognize the resources in the added file.

This note is structured to answer the above questions as follows:

  • Overview of How Visual C++ Manages Resource Files and Header Files provides an overview of how the Resource Set Includes command in Visual C++ lets you use multiple resource files and header files in the same project.

  • Analysis of AppWizard-created .RC and .H Files looks at the multiple resource and header files that are used by an AppWizard-created application. These files serve as a good model for additional resource files and header files you might want to add to your project.

  • Including Additional Header Files describes where you might want to include multiple header files, and provides details how to do so.

  • Sharing a Header File Between Two .RC Files shows how you can share one header file between multiple .RC files in different projects, or perhaps in the same project.

  • Using Multiple Resource Files in the Same Project describes where you might want to break up your project into multiple .RC files, and provides details how to do so.

  • Enforcement of Non-Editable Visual C++ Files describes how you can make sure Visual C++ does not edit and unintentionally reformat a custom resource.

  • Managing Symbols Shared by Multiple Visual C++-Edited .RC Files describes how to share the same symbols across multiple .RC files and how to avoid assigning duplicate ID numeric values.

  • Managing Dependencies Between .RC, .CPP, and .H Files describes how Visual C++ and Visual C++ avoid unnecessary recompiling .CPP files that are dependent on resource symbol files.

  • How Visual C++ Manages Set Includes Information provides technical details about how Visual C++ keeps track of multiple (nested) .RC files and multiple header files that are #include'd by an .RC file.

Overview of How Visual C++ Manages Resource Files and Header Files

Visual C++ manages a single .RC resource file and a corresponding .H header file as a tightly coupled pair of files. When you edit and save resources in an .RC file, you indirectly edit and save symbols in the corresponding .H file. Although you can open and edit multiple .RC files at a time (using Visual C++'s MDI user interface) for any given .RC file you indirectly edit exactly one corresponding header file.

Symbol Header File

By default, Visual C++ always names the corresponding header file RESOURCE.H, regardless of the name of the resource file (e.g., MYAPP.RC). Using the File Set Includes command in Visual C++, you can change the name of this header file by updating the Symbol Header File file in the Set Includes dialog.

Read-Only Symbol Directives

Although Visual C++ only edits one header file for any given .RC file, Visual C++ supports references to symbols defined in additional read-only header files. Using the File Set Includes command in Visual C++, you can specify any number of additional read-only header files as Read-Only Symbol Directives. The "read-only" restriction means that when you add a new resource in the .RC file, you can use a symbol defined in the read-only header file; but if you delete the resource, the symbol still remains defined in the read-only header file. You cannot change the numeric value assigned to a read-only symbol.

Compile-Time Directives

Visual C++ also supports nesting of resource files, where one .RC file is #include'd within another. When you edit a given .RC file using Visual C++, any resources in the #include'd files are not visible. But when you compile the .RC file, the #include'd files are also compiled. Using the File Set Includes command in Visual C++, you can specify any number of #include'd .RC files as Compile-Time Directives.

Note what happens if you read into Visual C++ an .RC file that #include's another .RC file that is not specified as a Compile-Time Directive. This situation might arise when you bring to Visual C++ an .RC file that you had been previously maintaining manually with a text editor. When Visual C++ reads the #include'd .RC file, it merges the #include'd resources into the parent .RC file. When you save the parent .RC file, the #include statement, in effect, will be replaced by the #include'd resources. If you do not want this merge to happen, you should remove the #include statement from the parent .RC file prior to reading it into Visual C++; then using Visual C++, add back the same #include statement as a Compile-Time Directive.

Visual C++ saves in an .RC file the three kinds of above Set Includes information (Symbol Header File, Read-Only Symbol Directives, and Compile-Time Directives) in #include directives and in TEXTINCLUDE resources. The TEXTINCLUDE resources, an implementation detail that you do not normally need to deal with, are explained in How Visual C++ Manages Set Includes Information.

Analysis of AppWizard-Created .RC and .H Files

Examining the application code produced by AppWizard provides insight into how Visual C++'s manages multiple resource files and header files. The code excerpts examined below are from a MYAPP application produced by AppWizard using the default options.

An AppWizard-created application uses multiple resource files and multiple header files, as summarized in the diagram below:

   RESOURCE.H     AFXRES.H
          \       /
           \     /
          MYAPP.RC
              |
              |
        RES\MYAPP.RC2
        AFXRES.RC
        AFXPRINT.RC

You can view these multiple file relationships using the Visual C++ File/Set Includes command.

MYAPP.RC

The application resource file that you edit using Visual C++.

RESOURCE.H is the application-specific header file. It is always named RESOURCE.H by AppWizard, consistent with Visual C++'s default naming of the header file. The #include for this header file is the first statement in the resource file (MYAPP.RC):

//Microsoft Visual C++ generated resource script
//
#include "resource.h"

RES\MYAPP.RC2

Contains resources that will not be edited by Visual C++ but will be included in the final compiled .EXE file. AppWizard creates no such resources by default, since Visual C++ can edit all of the standard resources, including the version resource (a new feature in this release). An empty file is generated by AppWizard in case you wish to add your own custom formatted resources to this file.

If you use custom formatted resources, you can add them to RES\MYAPP.RC2 and edit them using the Visual C++ text editor.

AFXRES.RC and AFXPRINT.RC contain standard resources required by certain features of the framework. Like RES\MYAPP.RC2, these two framework-provided resource files are #include'd at the end of MYAPP.RC, and they are specified in the Compile-Time Directives of the Set Includes dialog box. Thus, you do not directly view or edit these framework resources while you edit MYAPP.RC in Visual C++, but they are compiled into the application's binary .RES file and final .EXE file. For more information on the standard framework resources, including procedures for modifying them, see Technical Note 23.

AFXRES.H defines standard symbols, such as ID_FILE_NEW, used by the framework and specifically used in AFXRES.RC. AFXRES.H also #include's WINRES.H, which contains a subset of WINDOWS.H that are needed by Visual C++ generated .RC files as well as AFXRES.RC. The symbols defined in AFXRES.H are available as you edit the application resource file (MYAPP.RC). For example, ID_FILE_NEW is used for the File New menu item in MYAPP.RC's menu resource. You cannot change or delete these framework-defined symbols.

Including Additional Header Files

The AppWizard-created application includes only two header files: RESOURCE.H and AFXRES.H. Only RESOURCE.H is application-specific. You may need to include additional read-only header files in the following cases:

The header file is provided by an external source, or you want to share the header file among multiple projects or multiple parts of the same project.

The header file has formatting and comments that you do not want Visual C++ to change or filter out when it saves the file. For example, maybe you want to preserve #define's that use symbolic arithmetic such as:

#define RED 0
#define BLUE 1
#define GREEN 2
#define ID_COLOR_BUTTON 1001
#define ID_RED_BUTTON (ID_COLOR_BUTTON + RED)
#define ID_BLUE_BUTTON (ID_COLOR_BUTTON + BLUE)
#define ID_GREEN_BUTTON (ID_COLOR_BUTTON + GREEN)

You can include additional read-only header files by using the File Set Includes command to specify the #include statement as a second Read-Only Symbol Directive, as in:

#include "afxres.h"
#include "second.h"

The new file relationship diagram now looks like this:

                   AFXRES.H
    RESOURCE.H     SECOND.H
          \       /
           \     /
          MYAPP.RC
              |
              |
        RES\MYAPP.RC2
        AFXRES.RC
        AFXPRINT.RC

Sharing a Header File Between Two .RC Files

You may want to share a header file between two .RC files that are in different projects, or possibly the same project. To do so, simply apply the Read-Only Directives technique described above to both .RC files. In the case where the two .RC files are for different applications (different projects), the result is illustrated in the following diagram:

     RESOURCE.H   AFXRES.H   RESOURCE.H
    (for MYAPP1)  SECOND.H   (for MYAPP2)
          \       /     \       /
           \     /       \     /
          MYAPP1.RC      MYAPP2.RC
           /    \        /     \
          /      \      /       \
RES\MYAPP1.RC2  AFXRES.RC     RES\MYAPP2.RC2
                AFXPRINT.RC

The case where the second header file is shared by two .RC files in the same application (project) is discussed below.

Using Multiple Resource Files in the Same Project

Visual C++ and the Resource Compiler support multiple .RC files in the same project through #include's of one .RC file within another. Multiple nesting is allowed. There are various reasons to split your project's resources into multiple .RC files:

  • It is easier to manage a large number of resources among multiple project team members if you split the resources into multiple .RC files. If you use a source control management package for checking out files and checking in changes, splitting the resources into multiple .RC files will give you finer control over managing changes to resources.

  • If you want to use preprocessor directives, such as #ifdef, #endif, and #define, for portions of your resources, you must isolate them in read-only resources that will be compiled by the Resource Compiler.

  • Component .RC files will load and save faster in Visual C++ than one composite .RC file.

  • If you want to maintain a resource with a text editor in a human-readable form, you should keep it in a .RC file separate from the one Visual C++ edits.

  • If you need to keep a user-defined resource in a binary or text form that is interpretable by another specialized data editor, then you should keep it in a separate .RC file so Visual C++ does not change the format to hexadecimal data. The .WAV (sound) file resources in the MFC Advanced Concepts sample SPEAKN are a good example.

You can #include a SECOND.RC in the Compile-Time Directives in the Set Includes dialog box:

#include "res\myapp.rc2"  // non-Visual C++ edited resources
#include "second.rc"  // THE SECOND .RC FILE

#include "afxres.rc"  // Standard components
#include "afxprint.rc"  // printing/print preview resources

The result is illustrated in the following diagram:

   RESOURCE.H     AFXRES.H
          \       /
           \     /
          MYAPP.RC
              |
              |
        RES\MYAPP.RC2
        SECOND.RC
        AFXRES.RC
        AFXPRINT.RC

Using Compile-Time Directives, you can organize your Visual C++-editable and non-editable resources into multiple .RC files, where the "master" MYAPP.RC does nothing but #include the other .RC files. If you are using a Visual C++ project .MAK file, then you should include the "master" .RC file in the project so that all the #include'd resources are compiled with your application.

Enforcement of Non-Editable Visual C++ Files

The AppWizard-created RES\MYAPP.RC2 file is an example of a file that contains resources that you do not want to accidentally read into Visual C++ and then write it back out with loss of formatting information. To protect against this, we place the following lines in the beginning of the RES\MYAPP.RC2 file:

#ifdef APSTUDIO_INVOKED
    #error this file is not editable by Visual C++
#endif //APSTUDIO_INVOKED

When Visual C++ compiles the .RC file, it defines APSTUDIO_INVOKED as well as RC_INVOKED. If the AppWizard-created file structure is corrupted and Visual C++ reads the #error line above, it reports a fatal error and abort the reading of the .RC file.

Managing Symbols Shared by Multiple Visual C++-Edited .RC Files

Two issues arise when you split up your resources into multiple .RC files that you want to edit separately in Visual C++:

  • You might want to share the same symbols across multiple .RC files.

  • You need to help Visual C++ avoid assigning the same ID numeric values to distinct resources (symbols).

The following diagram illustrates an organization of .RC and .H files that deals with the first issue:

              MYAPP.RC
             /         \
            /           \
MYSTRS.H   / MYSHARED.H  \  MYMENUS.H
     \    /    /      \   \    \
      \  /    /        \   \    \
   MYSTRS.RC           MYMENUS.RC

In this example, string resources are kept in one resource file, MYSTRS.RC, and menus are kept in another, MYMENUS.RC. Some symbols, such as for commands, may need to be shared between the two files. For example, a ID_TOOLS_SPELL may be the menu command ID for the Spell item in a Tools menu; and it may also be the string ID of the command prompt displayed by the framework in the application's main window status bar.

The ID_TOOLS_SPELL symbol is kept in the shared header file, MYSHARED.H. You maintain this shared header file manually with a text editor; Visual C++ does not directly edit it. In the two resource files MYSTRS.RC and MYMENUS.RC, you specify #include MYSHARED.H in the Read-Only Directives for MYAPP.RC, using the File Set Includes command, as described earlier.

It is most convenient to anticipate a symbol you will share before you attempt use it to identify any resource. Add the symbol to the shared header file and, if you have not already #include'd the shared header file in the Read-Only Directives for the .RC file, do so before using the symbol. If you did not anticipate sharing the symbol in this way, then you will have to manually (using a text editor) move the #define statement for the symbol from, say, MYMENUS.H to MYSHARED.H before using it in MYSTRS.RC.

When you manage symbols in multiple .RC files, you also must help Visual C++ avoid assigning the same ID numeric values to distinct resources (symbols). For any given .RC file, Visual C++ incrementally assigns IDs in each of four ID domains. Between editing sessions, Visual C++ keeps track of the last ID it assigned in each of the domains in the symbol header file for the .RC file. Here is what the APS_NEXT values are for an empty (new) .RC file:

#define _APS_NEXT_RESOURCE_VALUE  101
#define _APS_NEXT_COMMAND_VALUE   40001
#define _APS_NEXT_CONTROL_VALUE   1000
#define _APS_NEXT_SYMED_VALUE     101

_APS_NEXT_RESOURCE_VALUE is the next symbol value that will be used for a dialog resource, menu resource, and so on. The valid range for resource symbol values is 1 to 0x6FFF.

_APS_NEXT_COMMAND_VALUE is the next symbol value that will be used for a command identification. The valid range for command symbol values is 0x8000 to 0xDFFF.

_APS_NEXT_CONTROL_VALUE is the next symbol value that will be used for a dialog control. The valid range for dialog control symbol values is 8 to 0xDFFF.

_APS_NEXT_SYMED_VALUE is the next symbol value that will be issued when you manually assign a symbol value using the New command in the Symbol Browser.

Visual C++ starts with slightly higher values that the lowest legal value when creating a new .RC file. AppWizard will also initialize these values to something more appropriate for MFC applications. For more information about ID value ranges, see Technical Note 20.

Now every time you create a new resource file, even in the same project, Visual C++ defines the same _APS_NEXT_ values. This means that if you add, say, multiple dialogs in two different .RC files, it is highly likely that the same #define value will be assigned to different dialogs. For example, IDD_MY_DLG1 in the first .RC file might be assigned the same number, 101, as IDD_MY_DLG2 in a second .RC file.

To avoid this, you should reserve a separate numeric range for each of the four domains of IDs in the respective .RC files. Do this by manually updating the _APS_NEXT values in each of the .RC files before you start adding resources. For example, if the first .RC file uses the default _APS_NEXT values, then you might want to assign the following _APS_NEXT values to the second .RC file:

#define _APS_NEXT_RESOURCE_VALUE  2000
#define _APS_NEXT_COMMAND_VALUE   42000
#define _APS_NEXT_CONTROL_VALUE   2000
#define _APS_NEXT_SYMED_VALUE     2000

Of course, it is still possible that Visual C++ will assign so many IDs in the first .RC file that the numeric values start to overlap those reserved for the second .RC file. You should reserve sufficiently large ranges so that this does not happen.

Managing Dependencies Between .RC, .CPP, and .H Files

When Visual C++ saves an .RC file, it also saves symbol changes to the corresponding RESOURCE.H file. Any of your .CPP files that refer to resources in the .RC file must #include the RESOURCE.H file, usually from within your project's master header file. This leads to an undesirable side-effect due to the development environment's internal project management which scans source files for header dependencies. Every time you add a new symbol in Visual C++, all the .CPP file that #include RESOURCE.H would need to be recompiled.

Visual C++, circumvents the dependency on RESOURCE.H by including the following comment as the first line of the RESOURCE.H file:

//{{NO_DEPENDENCIES}}

The development environment interprets this comment by ignoring the changes to RESOURCE.H so that dependent .CPP files will not need to be recompiled.

Visual C++ always adds the //{{NO_DEPENDENCIES}} comment line to a .RC file when it saves the file. In some cases, circumventing of the build dependency on RESOURCE.H may lead to run-time errors undetected at link time. For example, if you use the Symbol Browser to change the numeric value assigned to a symbol for a resource, the resource will not be correctly found and loaded at application run-time if the .CPP file referring to the resource is not recompiled. In such cases, you should explicitly recompile any .CPP files that you know are affected by the symbol changes in RESOURCE.H or select Rebuild All. If you have the need to frequently change symbol values for a certain group of resources, you will probably find it more convenient and safer to break out these symbols into a separate read-only header file, as described in the above section Including Additional Header Files.

How Visual C++ Manages Set Includes Information

As discussed above, the File menu Set Includes command lets you specify three types of information:

  • Symbol Header File

  • Read-Only Symbol Directives

  • Compile-Time Directives

The following describes how Visual C++ maintains this information in a .RC file. You do not need this information to use Visual C++, but it may enhance your understanding so that you can more confidently use the Set Includes feature.

Each of the above three types of Set Includes information is stored in the .RC file in two forms: (1) as #include or other directives interpretable by the Resource Compiler, and (2) as special TEXTINCLUDE resources interpretable only by Visual C++.

The purpose of the TEXTINCLUDE resource is to safely store Set Include information in a form that is readily presentable in Visual C++'s Set Includes dialog box. TEXTINCLUDE is a resource type defined by Visual C++. Visual C++ recognizes three specific TEXTINCLUDE resources that have the resource identification numbers 1, 2 and 3:

TEXTINCLUDE resource i.d. | Type of Set Includes information
1 | Symbol Header File
2 | Read-Only Symbol Directives
3 | Compile-Time Directives

Each of the three types of Set Includes information is illustrated by the default MYAPP.RC and RESOURCE.H files created by AppWizard, as described below. The extra \0 and "" tokens between BEGIN and END blocks are required by the RC syntax to specify zero terminated strings and the double quote character respectively.

Symbol Header File

The form of the Symbol Header File information interpreted by the Resource Compiler is simply a #include statement:

#include "resource.h"

The corresponding TEXTINCLUDE resource is:

1 TEXTINCLUDE DISCARDABLE
BEGIN
   #resource.h\0"
END

Read-Only Symbol Directives

Read-Only Symbol Directives are included at the top of MYAPP.RC in the following form interpretable by the Resource Compiler:

#include "afxres.h"

The corresponding TEXTINCLUDE resource is:

2 TEXTINCLUDE DISCARDABLE
BEGIN
   "#include ""afxres.h""\r\n"
   "\0"
END

Compile-Time Directives

Compile-Time Directives are included at the end of MYAPP.RC in the following form interpretable by the Resource Compiler:

#ifndef APSTUDIO_INVOKED
///////////////////////
//
// From TEXTINCLUDE 3
//
#include "res\myapp.rc2"  // non-Visual C++ edited resources

#include "afxres.rc"  // Standard components
#include "afxprint.rc"  // printing/print preview resources
#endif  // not APSTUDIO_INVOKED

The #ifndef APSTUDIO_INVOKED directive instructs Visual C++ to skip over Compile-Time Directives.

The corresponding TEXTINCLUDE resource is:

3 TEXTINCLUDE DISCARDABLE
BEGIN
"#include ""res\myapp.rc2""  // non-Visual C++ edited resources\r\n"
"\r\n"
"#include ""afxres.rc""  // Standard components\r\n"
"#include ""afxprint.rc""  // printing/print preview resources\r\n"
"\0"
END


TN036: Using CFormView with AppWizard and ClassWizard

This technical note described how to modify an AppWizard generated application so that it used a CFormView instead of the default CView as its main view class. This is supported directly with this version of Visual C++.


TN037: Multithreaded MFC 2.1 Applications

This technical note originally described the limitations of multithreaded programs with MFC 2.1, originally provided with Visual C++ 1.0 for Windows NT. MFC 3.0 supports multithreading directly and is documented in Visual C++ Programmer's Guide. See that reference for more information.


TN038: MFC/OLE IUnknown Implementation

At the heart of OLE 2 is the "OLE Component Object Model", or COM. COM defines a standard for how cooperating objects communicate to one another. This includes the details of what an "object" looks like, including how methods are dispatched on an object. COM also defines a base class, from which all COM compatible classes are derived. This base class is IUnknown. Although the IUnknown interface is referred to as a C++ class, COM is not specific to any one language — it can be implemented in C, PASCAL, or any other language which can support the binary layout of a COM object.

OLE refers to all classes derived from IUnknown as "interfaces." This is an important distinction, since an "interface" such as IUnknown carries with it no implementation. It simply defines the protocol by which objects communicate, not the specifics of what those implementations do. This is reasonable for a system which allows for maximum flexibility. It is MFC's job to implement a default behavior for MFC/C++ programs.

To understand MFC's implementation of IUnknown you must first understand what this interface is. A simplified version of IUnknown is defined below:

class IUnknown
{
public:
    virtual HRESULT QueryInterface(REFIID iid, void** ppvObj) = 0;
    virtual ULONG AddRef() = 0;
    virtual ULONG Release() = 0;
};

Note Certain necessary calling convention details, such as __stdcall are left out for this illustration.

The AddRef and Release member functions control memory management of the object. COM uses a reference counting scheme to keep track of objects. An object is never referenced directly as you would in C++. Instead, COM objects are always referenced through a pointer. To release the object when the owner is done using it, the object's Release member is called (as opposed to using operator delete, as would be done for a traditional C++ object). The reference counting mechanism allows for multiple references to a single object to be managed. An implementation of AddRef and Release maintains a reference count on the object — the object is not deleted until its reference count reaches zero.

AddRef and Release are fairly straightforward from an implementation standpoint. Here is a trivial implementation:

ULONG CMyObj::AddRef()
{
    return ++m_dwRef;
}

ULONG CMyObj::Release()
{
    if (--m_dwRef == 0)
    {
        delete this;
        return 0;
    }
    return m_dwRef;
}

The QueryInterface member function is a little more interesting. As you can imagine, it isn't very interesting to have an object whose only member functions are AddRef and Release — it would be nice to tell the object to do more things than IUnknown provides. This is where QueryInterface is useful. It allows you to obtain a different "interface" on the same object. These interfaces are usually derived from IUnknown and add additional functionality by adding new member functions. COM interfaces never have member variables declared in the interface, and all member functions are declared as pure-virtual. For example,

class IPrintInterface : public IUnknown
{
public:
    virtual void PrintObject() = 0;
};

To get an IPrintInterface if you only have an IUnknown, call IUnknown::QueryInterface using the IID of the IPrintInterface. An IID is a 128-bit number that uniquely identifies the interface. There is an IID for each interface that either you or OLE define. If pUnk is a pointer to an IUnknown object, the code to retrieve an IPrintInterface from it might be:

IPrintInterface* pPrint = NULL;
if (pUnk->QueryInterface(IID_IPrintInterface,
    (void**)&pPrint) == NOERROR)
{
    pPrint->PrintObject();
    pPrint->Release();
        // release pointer obtained via QueryInterface
}

That seems fairly easy, but how would you implement an object supporting both the IPrintInterface and IUnknown interface? In this case it is simple since the IPrintInterface is derived directly from IUnknown — by implementing IPrintInterface, IUnknown is automatically supported. For example:

class CPrintObj : public CPrintInterface
{
    virtual HRESULT QueryInterface(REFIID iid, void** ppvObj);
    virtual ULONG AddRef();
    virtual ULONG Release();
    virtual void PrintObject();
};

The implementations of AddRef and Release would be exactly the same as those implemented above. CPrintObj::QueryInterface would look something like this:

HRESULT CPrintObj::QueryInterface(REFIID iid, void FAR* FAR* ppvObj)
{
    if (iid == IID_IUnknown || iid == IID_IPrintInterface)
    {
        *ppvObj = this;
        AddRef();
        return NOERROR;
    }
    return ResultFromScode(E_NOINTERFACE);
}

As you can see, if the interface identifier (IID) is recognized, a pointer is returned to your object; otherwise an error occurs. Also note that a successful QueryInterface results in an implied AddRef. Of course, you'd also have to implement CEditObj::Print. That is simple because the IPrintInterface was directly derived from the IUnknown interface. However if you wanted to support two different interfaces, both derived from IUnknown, consider the following:

class IEditInterface : public IUnkown
{
public:
    virtual void EditObject() = 0;
};

Although there are a number of different ways to implement a class supporting both IEditInterface and IPrintInterface, including using C++ multiple inheritance, this note will concentrate on the use of nested classes to implement this functionality.

class CEditPrintObj
{
public:
    CEditPrintObj();

    HRESULT QueryInterface(REFIID iid, void**);
    ULONG AddRef();
    ULONG Release();
    DWORD m_dwRef;

    class CPrintObj : public IPrintInterface
    {
    public:
        CEditPrintObj* m_pParent;
        virtual HRESULT QueryInterface(REFIID iid, void** ppvObj);
        virtual ULONG AddRef();
        virtual ULONG Release();
    } m_printObj;

    class CEditObj : public IEditInterface
    {
    public:
        CEditPrintObj* m_pParent;
        virtual ULONG QueryInterface(REFIID iid, void** ppvObj);
        virtual ULONG AddRef();
        virtual ULONG Release();
    } m_editObj;
};

The entire implementation is included below:

CEditPrintObj::CEditPrintObj()
{
    m_editObj.m_pParent = this;
    m_printObj.m_pParent = this;
}

ULONG CEditPrintObj::AddRef()
{
    return ++m_dwRef;
}

CEditPrintObj::Release()
{
    if (--m_dwRef == 0)
    {
        delete this;
        return 0;
    }
    return m_dwRef;
}

HRESULT CEditPrintObj::QueryInterface(REFIID iid, void** ppvObj)
{
    if (iid == IID_IUnknown || iid == IID_IPrintInterface)
    {
        *ppvObj = &m_printObj;
        AddRef();
        return NOERROR;
    }
    else if (iid == IID_IEditInterface)
    {
        *ppvObj = &m_editObj;
        AddRef();
        return NOERROR;
    }
    return ResultFromScode(E_NOINTERFACE);
}

ULONG CEditPrintObj::CEditObj::AddRef()
{
    return m_pParent->AddRef();
}

ULONG CEditPrintObj::CEditObj::Release()
{
    return m_pParent->Release();
}

HRESULT CEditPrintObj::CEditObj::QueryInterface(
    REFIID iid, void** ppvObj)
{
    return m_pParent->QueryInterface(iid, ppvObj);
}

ULONG CEditPrintObj::CPrintObj::AddRef()
{
    return m_pParent->AddRef();
}

ULONG CEditPrintObj::CPrintObj::Release()
{
    return m_pParent->Release();
}

HRESULT CEditPrintObj::CPrintObj::QueryInterface(
    REFIID iid, void** ppvObj)
{
    return m_pParent->QueryInterface(iid, ppvObj);
}

Notice that most of the IUnknown implementation is placed into the CEditPrintObj class rather than duplicating the code in CEditPrintObj::CEditObj and CEditPrintObj::CPrintObj. This reduces the amount of code and avoids bugs. The key point here is that from the IUnknown interface it is possible to call QueryInterface to retrieve any interface the object might support, and from each of those interfaces it is possible to do the same. This means that all QueryInterface functions available from each interface must behave exactly the same way. In order for these embedded objects to call the implementation in the "outer object", a back-pointer is used (m_pParent). The m_pParent pointer is initialized during the CEditPrintObj constructor. Then you would implement CEditPrintObj::CPrintObj::PrintObject and CEditPrintObj::CEditObj::EditObject as well. Quite a bit of code was added to add one feature — the ability to edit the object. Fortunately, it is quite uncommon for interfaces to have only a single member function (although it does happen) and in this case, EditObject and PrintObject would usually be combined into a single interface.

That's a lot of explanation and a lot of code for such a simple scenario. The MFC/OLE classes provide a simpler alternative. The MFC implementation uses a technique similar to the way Windows messages are wrapped with Message Maps. This facility is called Interface Maps and is discussed in the next section.

MFC Interface Maps

MFC/OLE includes an implementation of "Interface Maps" similar to MFC's "Message Maps" and "Dispatch Maps" in concept and execution. The core features of MFC's Interface Maps are as follows:

  • A standard implementation of IUnknown, built into the CCmdTarget class.

  • Maintenance of the reference count, modified by AddRef and Release

  • Data driven implementation of QueryInterface

In addition, interface maps support the following advanced features:

  • Support for creating aggregatable COM objects

  • Support for using aggregate objects in the implementation of a COM object

  • The implementation is hookable and extensible

For more information on aggregation, see the OLE Programmer's Reference.

MFC's interface map support is rooted in the CCmdTarget class. CCmdTarget "has-a" reference count as well as all the member functions associated with the IUnknown implementation (the reference count for example is in CCmdTarget). To create a class that supports OLE COM, you derive a class from CCmdTarget and use various macros as well as member functions of CCmdTarget to implement the desired interfaces. MFC's implementation uses nested classes to define each interface implementation much like the example above. This is made easier with a standard implementation of IUnknown as well as a number of macros that eliminate some of the repetitive code.

Interface Map Basics

To implement a class using MFC's interface maps follow these steps:

  1. Derive a class either directly or indirectly from CCmdTarget.

  2. Use the DECLARE_INTERFACE_MAP function in the derived class definition.

  3. For each interface you wish to support, use the BEGIN_INTERFACE_PART and END_INTERFACE_PART macros in the class definition.

  4. In the implementation file, use the BEGIN_INTERFACE_MAP and END_INTERFACE_MAP macros to define the class's interface map.

  5. For each IID supported, use the INTERFACE_PART macro between the BEGIN_INTERFACE_MAP and END_INTERFACE_MAP macros to map that IID to a specific "part" of your class.

  6. Implement each of the nested classes that represent the interfaces you support.

  7. Use the METHOD_PROLOGUE macro to access the parent, CCmdTarget-derived object.

  8. AddRef, Release, and QueryInterface can delegate to the CCmdTarget implementation of these functions (ExternalAddRef, ExternalRelease, and ExternalQueryInterface).

The CPrintEditObj example above could be implemented as follows:

class CPrintEditObj : public CCmdTarget
{
public:
    // member data and member functions for CPrintEditObj go here

// Interface Maps
protected:
    DECLARE_INTERFACE_MAP()

    BEGIN_INTERFACE_PART(EditObj, IEditInterface)
        STDMETHOD_(void, EditObject)();
    END_INTERFACE_PART(EditObj)

    BEGIN_INTERFACE_PART(PrintObj, IPrintInterface)
        STDMETHOD_(void, PrintObject)();
    END_INTERFACE_PART(PrintObj)
};

The above declaration creates a class derived from CCmdTarget. The DECLARE_INTERFACE_MAP macro tells the framework that this class will have a custom interface map. In addition, the BEGIN_INTERFACE_PART and END_INTERFACE_PART macros define nested classes, in this case with names CEditObj and CPrintObj (the X is used only to differentiate the nested classes from global classes which start with "C" and interface classes which start with "I"). Two nested members of these classes are created: m_CEditObj, and m_CPrintObj, respectively. The macros automatically declare the AddRef, Release, and QueryInterface functions; therefore you only declare the functions specific to this interface: EditObject and PrintObject (the OLE macro STDMETHOD is used such so that _stdcall and virtual keywords are provided as appropriate for the target platform).

To implement the interface map for this class:

BEGIN_INTERFACE_MAP(CPrintEditObj, CCmdTarget)
    INTERFACE_PART(CPrintEditObj, IID_IPrintInterface, PrintObj)
    INTERFACE_PART(CPrintEditObj, IID_IEditInterface, EditObj)
END_INTERFACE_MAP()

This connects the IID_IPrintInterface IID with m_CPrintObj and IID_IEditInterface with m_CEditObj respectively. The CCmdTarget implementation of QueryInterface (CCmdTarget::ExternalQueryInterface) uses this map to return pointers to m_CPrintObj and m_CEditObj when requested. It is not necessary to include an entry for IID_IUnknown; the framework will use the first interface in the map (in this case, m_CPrintObj) when IID_IUnknown is requested.

Even though the BEGIN_INTERFACE_PART macro automatically declared the AddRef, Release and QueryInterface functions for you, you still need to implement them:

ULONG FAR EXPORT CEditPrintObj::XEditObj::AddRef()
{
    METHOD_PROLOGUE(CEditPrintObj, EditObj)
    return pThis->ExternalAddRef();
}

ULONG FAR EXPORT CEditPrintObj::XEditObj::Release()
{
    METHOD_PROLOGUE(CEditPrintObj, EditObj)
    return pThis->ExternalRelease();
}

HRESULT FAR EXPORT CEditPrintObj::XEditObj::QueryInterface(
    REFIID iid, void FAR* FAR* ppvObj)
{
    METHOD_PROLOGUE(CEditPrintObj, EditObj)
    return (HRESULT)pThis->ExternalQueryInterface(&iid, ppvObj);
}

void FAR EXPORT CEditPrintObj::XEditObj::EditObject()
{
    METHOD_PROLOGUE(CEditPrintObj, EditObj)
    // code to "Edit" the object, whatever that means...
}

The implementation for CEditPrintObj::CPrintObj, would be similar to the above definitions for CEditPrintObj::CEditObj. Although it would be possible to create a macro that could be used to automatically generate these functions (as a matter of fact, earlier in the MFC/OLE development this was the case), it becomes difficult to set break points when a macro generates more than one line of code. For this reason, this code is expanded manually.

By using the framework implementation of message maps there are a number of things that weren't necessary to do:

  • Implement QueryInterface

  • Implement AddRef and Release

  • Declare either of these built-in methods on both of your interfaces

In addition, the framework uses message maps internally. This allows you to derive from a framework class, say COleServerDoc, that already supports certain interfaces and provides either replacements or additions to the interfaces provided by the framework. This is enabled by the fact that the framework fully supports inheriting an interface map from a base class — that is the reason why BEGIN_INTERFACE_MAP takes as its second parameter the name of the base class.

Note It is generally not possible to reuse the implementation of MFC's built-in implementations of the OLE interfaces by inheriting the embedded specialization of that interface from the MFC version. This is not possible because the use of the METHOD_PROLOGUE macro to get access to the containing CCmdTarget-derived object implies a fixed offset of the embedded object from the CCmdTarget-derived object. This means, for example, you cannot derive an embedded XMyAdviseSink from MFC's implementation in COleClientItem::XAdviseSink, because XAdviseSink relies on being at a specific offset from the top of the COleClientItem object.

You can, however, delegate to the MFC implementation for all of the functions that you want MFC's default behavior. This is done in the MFC implementation of IOleInPlaceFrame (XOleInPlaceFrame) in the COleFrameHook class (it delegates to m_xOleInPlaceUIWindow for many functions). This design was chosen to reduce the runtime size of objects which implement many interfaces; it eliminates the need for a back-pointer (such as the way m_pParent was used in the previous section).

Aggregation and Interface Maps

In addition to supporting stand-alone COM objects, MFC also supports aggregation. Aggregation itself is too complex a topic to discuss here; refer to the OLE Programmer's Reference for more information on aggregation. This note will simply describe the support for aggregation built into the framework and interface maps.

There are two ways to use aggregation: (1) using a COM object that supports aggregation, and (2) implementing an object that can be aggregated by another. These capabilities can be referred to as "using an aggregate object" and "making an object aggregatable". MFC supports both.

Using an Aggregate Object

To use an aggregate object, there needs to be some way to tie the aggregate into the QueryInterface mechanism. In other words, the aggregate object must behave as though it is a native part of your object. So how does this tie into MFC's interface map mechanism? In addition to the INTERFACE_PART macro, where a nested object is mapped to an IID, you can also declare an aggregate object as part of your CCmdTarget derived class. To do so, the INTERFACE_AGGREGATE macro is used. This allows you to specify a member variable (which must be a pointer to an IUnknown or derived class), which is to be integrated into the interface map mechanism. If the pointer is not NULL when CCmdTarget::ExternalQueryInterface is called, the framework will automatically call the aggregate object's QueryInterface member function, if the IID requested is not one of the native IIDs supported by the CCmdTarget object itself.

To use the INTERFACE_AGGREGATE macro, follow these steps:

  1. Declare a member variable (an IUnknown*) which will contain a pointer to the aggregate object.

  2. Include an INTERFACE_AGGREGATE macro in your interface map, which refers to the member variable by name.

  3. At some point (usually during CCmdTarget::OnCreateAggregates), initialize the member variable to something other than NULL.

For example,

class CAggrExample : public CCmdTarget
{
public:
    CAggrExample();

protected:
    LPUNKNOWN m_lpAggrInner;
    virtual BOOL OnCreateAggregates();

    DECLARE_INTERFACE_MAP()
    // "native" interface part macros may be used here
};

CAggrExample::CAggrExample()
{
    m_lpAggrInner = NULL;
}

BOOL CAggrExample::OnCreateAggregates()
{
    // wire up aggregate with correct controlling unknown
    m_lpAggrInner = CoCreateInstance(CLSID_Example,
        GetControllingUnknown(), CLSCTX_INPROC_SERVER,
        IID_IUnknown, (LPVOID*)&m_lpAggrInner);
    if (m_lpAggrInner == NULL)
        return FALSE;
    // optionally, create other aggregate objects here
    return TRUE;
}

BEGIN_INTERFACE_MAP(CAggrExample, CCmdTarget)
    // native "INTERFACE_PART" entries go here
    INTERFACE_AGGREGATE(CAggrExample, m_lpAggrInner)
END_INTERFACE_MAP()

The m_lpAggrInner is initialized in the constructor to NULL. The framework will ignore a NULL member variable in the default implementation of QueryInterface. OnCreateAggregates is a good place to actually create your aggregate objects. You'll have to call it explicitly if you are creating the object outside of the MFC implementation of COleObjectFactory. The reason for creating aggregates in CCmdTarget::OnCreateAggregates as well as the usage of CCmdTarget::GetControllingUnknown will become apparent when creating aggregatable objects is discussed.

This technique will give your object all of the interfaces that the aggregate object supports plus its native interfaces. If you only want a subset of the interfaces that the aggregate supports, you can override CCmdTarget::GetInterfaceHook. This allows you very low level hookability, similar to QueryInterface. Usually, you want all the interfaces that the aggregate supports.

Making an Object Implementation Aggregatable

For an object to be aggregatable, the implementation of AddRef, Release, and QueryInterface must delegate to a "controlling unknown." In other words, for it to be part of the object, it must delegate AddRef, Release, and QueryInterface to a different object, also derived from IUnknown. This "controlling unknown" is provided to the object when it is created, that is, it is provided to the implementation of COleObjectFactory. Implementing this carries a small amount of overhead, and in some cases is not desirable, so MFC makes this optional. To enable an object to be aggregatable, you call CCmdTarget::EnableAggregation from the object's constructor.

If the object also uses aggregates, you must also be sure to pass the correct "controlling unknown" to the aggregate objects. Usually this IUnknown pointer is passed to the object when the aggregate is created. For example, the pUnkOuter parameter is the "controlling unknown" for objects created with CoCreateInstance. The correct "controlling unknown" pointer can be retrieved by calling CCmdTarget::GetControllingUnknown. The value returned from that function, however, is not valid during the constructor. For this reason, it is suggested that you create your aggregates only in an override of CCmdTarget::OnCreateAggregates, where the return value from GetControllingUnknown is reliable, even if created from the COleObjectFactory implementation.

It is also important that the object manipulate the correct reference count when adding or releasing artificial reference counts. To ensure this is the case, always call ExternalAddRef and ExternalRelease instead of InternalRelease and InternalAddRef. It is rare to call InternalRelease or InternalAddRef on a class that supports aggregation.

Reference Material

Advanced usage of OLE, such as defining your own interfaces or overriding the framework's implementation of the OLE interfaces requires the use of the underlying interface map mechanism.

This section discusses each macro and the APIs which is used to implement these advanced features.

CCmdTarget::EnableAggregation — Function Description

void EnableAggregation();

Note Call this function in the constructor of the derived class if you wish to support OLE aggregation for objects of this type. This prepares a special IUnknown implementation that is required for aggregatable objects.

CCmdTarget::ExternalQueryInterface — Function Description

DWORD ExternalQueryInterface(const void FAR* lpIID, LPVOID FAR* ppvObj);

lpIID

A far pointer to an IID (the first argument to QueryInterface)

ppvObj

A pointer to an IUnknown* (second argument to QueryInterface)

Note Call this function in your implementation of IUnknown for each interface your class implements. This function provides the standard data-driven implementation of QueryInterface based on your object's interface map. It is necessary to cast the return value to an HRESULT. If the object is aggregated, this function will call the "controlling IUnknown" instead of using the local interface map.

CCmdTarget::ExternalAddRef — Function Description

DWORD ExternalAddRef();

Note Call this function in your implementation of IUnknown::AddRef for each interface your class implements. The return value is the new reference count on the CCmdTarget object. If the object is aggregated, this function will call the "controlling IUnknown" instead of manipulating the local reference count.

CCmdTarget::ExternalRelease — Function Description

DWORD ExternalRelease();

Note Call this function in your implementation of IUnknown::Release for each interface your class implements. The return value indicates the new reference count on the object. If the object is aggregated, this function will call the "controlling IUnknown" instead of manipulating the local reference count.

DECLARE_INTERFACE_MAP — Macro Description

DECLARE_INTERFACE_MAP

Note Use this macro in any class derived from CCmdTarget that will have an interface map. Used in much the same way as DECLARE_MESSAGE_MAP. This macro invocation should be placed in the class definition, usually in a header (.H) file. A class with DECLARE_INTERFACE_MAP must define the interface map in the implementation file (.CPP) with the BEGIN_INTERFACE_MAP and END_INTERFACE_MAP macros.

BEGIN_INTERFACE_PART and END_INTERFACE_PART — Macro Descriptions

BEGIN_INTERFACE_PART(localClass, iface);

END_INTERFACE_PART(localClass)

localClass

The name of the class that implements the interface

iface

The name of the interface that this class implements

Note For each interface that your class will implement, you need to have a BEGIN_INTERFACE_PART and END_INTERFACE_PART pair. These macros define a local class derived from the OLE interface that you define as well as an embedded member variable of that class. The AddRef, Release, and QueryInterface members are declared automatically. You must include the declarations for the other member functions that are part of the interface being implemented (those declarations are placed between the BEGIN_INTERFACE_PART and END_INTERFACE_PART macros).

The iface argument is the OLE interface that you wish to implement, such as IAdviseSink, or IPersistStorage (or your own custom interface).

The localClass argument is the name of the local class that will be defined. An 'X' will automatically be prepended to the name. This naming convention is used to avoid collisions with global classes of the same name. In addition, the name of the embedded member, the same as the localClass name except it is prefixed by 'm_x'.

For example:

BEGIN_INTERFACE_PART(MyAdviseSink, IAdviseSink)
   STDMETHOD_(void,OnDataChange)(LPFORMATETC, LPSTGMEDIUM);
   STDMETHOD_(void,OnViewChange)(DWORD, LONG);
   STDMETHOD_(void,OnRename)(LPMONIKER);
   STDMETHOD_(void,OnSave)();
   STDMETHOD_(void,OnClose)();
END_INTERFACE_PART(MyAdviseSink)

would define a local class called XMyAdviseSink derived from IAdviseSink, and a member of the class in which it is declared called m_xMyAdviseSink.Note:

Note The lines beginning with STDMETHOD_ are essentially copied from OLE2.H and modified slightly. Copying them from OLE2.H can reduce errors that are hard to resolve.

BEGIN_INTERFACE_MAP and END_INTERFACE_MAP — Macro Descriptions

BEGIN_INTERFACE_MAP(theClass, baseClass)

END_INTERFACE_MAP

theClass

The class in which the interface map is to be defined

baseClass

The class from which theClass derives from.

Remarks: The BEGIN_INTERFACE_MAP and END_INTERFACE_MAP macros are used in the implementation file to actually define the interface map. For each interface that is implemented there is one or more INTERFACE_PART macro invocations. For each aggregate that the class uses, there is one INTERFACE_AGGREGATE macro invocation.

INTERFACE_PART — Macro Description

INTERFACE_PART(theClass, iid, localClass)

theClass

The name of the class which contains the interface map.

iid

The IID which is to be mapped to the embedded class.

localClass

The name of the local class (less the 'X')

Note This macro is used between the BEGIN_INTERFACE_MAP macro and the END_INTERFACE_MAP macro for each interface your object will support. It allows you to map an IID to a member of the class indicated by theClass and localClass. The 'm_x' will be added to the localClass automatically. Note that more than one IID may be associated with a single member. This is very useful when you are implementing only a "most derived" interface and wish to provide all intermediate interfaces as well. A good example of this is the IOleInPlaceFrameWindow interface. Its hierarchy looks like this:

IUnknown
    IOleWindow
        IOleUIWindow
            IOleInPlaceFrameWindow

If an object implements IOleInPlaceFrameWindow, a client may QueryInterface on any of these interfaces: IOleUIWindow, IOleWindow, or IUnknown, besides the "most derived" interface IOleInPlaceFrameWindow (the one you are actually implementing). To handle this you can use more than one INTERFACE_PART macro to map each and every base interface to the IOleInPlaceFrameWindow interface:

in the class definition file:

BEGIN_INTERFACE_PART(CMyFrameWindow, IOleInPlaceFrameWindow)

in the class implementation file:

BEGIN_INTERFACE_MAP(CMyWnd, CFrameWnd)
    INTERFACE_PART(CMyWnd, IID_IOleWindow, MyFrameWindow)
    INTERFACE_PART(CMyWnd, IID_IOleUIWindow, MyFrameWindow)
    INTERFACE_PART(CMyWnd, IID_IOleInPlaceFrameWindow, MyFrameWindow)
END_INTERFACE_MAP

The framework takes care of IUnknown since it is always required.

INTERFACE_PART — Macro Description

INTERFACE_AGGREGATE(theClass, theAggr)

theClass

The name of the class which contains the interface map,

theAggr

The name of the member variable which is to be aggregated.

Note This macro is used to tell the framework that the class is using an aggregate object. It must appear between the BEGIN_INTERFACE_PART and END_INTERFACE_PART macros. An aggregate object is a separate object, derived from IUnknown. By using an aggregate and the INTERFACE_AGGREGATE macro, you can make all the interfaces that the aggregate supports appear to be directly supported by the object. The theAggr argument is simply the name of a member variable of your class which is derived from IUnknown (either directly or indirectly). All INTERFACE_AGGREGATE macros must follow the INTERFACE_PART macros when placed in an interface map.


TN039: MFC/OLE Automation Implementation

Overview of OLE IDispatch Interface

The IDispatch interface is the means by which applications expose methods and properties such that other applications such as Visual BASIC, or other languages, can make use of the application's features. The most important part of this interface is the IDispatch::Invoke function. MFC uses "dispatch maps" to implement IDispatch::Invoke. The dispatch map provides the MFC implementation information on the layout or "shape" of your CCmdTarget-derived classes, such that it can directly manipulate the properties of the object, or call member functions within your object to satisfy IDispatch::Invoke requests.

For the most part, ClassWizard and MFC cooperate to hide most of the details of OLE automation from the application programmer. The programmer concentrates on the actual functionality to expose in the application and doesn't have to worry about the underlying plumbing.

There are cases, however, where it is necessary to understand what MFC is doing behind the scenes. This note will address how the framework assigns DISPIDs to member functions and properties. Knowledge of the algorithm MFC uses for assigning DISPIDs is only necessary when you need to know the IDs, such as when you create a "type library" for your application's objects.

MFC DISPID assignment

Although the end-user of automation (a Visual Basic user, for example), sees the actual names of the automation enabled properties and methods in their code (e.g. obj.ShowWindow), the implementation of IDispatch::Invoke does not receive the actual names. For optimization reasons, it receives a DISPID, which is a 32-bit "magic cookie" that describes the method or property which is to be accessed. These DISPID values are returned from the IDispatch implementation through another method, called IDispatch::GetIDsOfNames. An automation client application will call GetIDsOfNames once for each member or property it intends to access, and cache them for later calls to IDispatch::Invoke. This way, the expensive string lookup is only done once per object use, instead of once per IDispatch::Invoke call.

MFC determines the DISPIDs for each method and property based on two things:

  • The distance from the top of the dispatch map (1 relative)

  • The distance of the dispatch map from the most derived class (0 relative)

The DISPID is divided into two parts. The LOWORD of the DISPID contains the first component, the distance from the top of the dispatch map. The HIWORD contains the distance from the most derived class. For example:

class CDispPoint : public CCmdTarget
{
public:
    short m_x, m_y;
    ...
    DECLARE_DISPATCH_MAP()
    ...
};

class CDisp3DPoint : public CDispPoint
{
public:
    short m_y;
    ...
    DECLARE_DISPATCH_MAP()
    ...
};

BEGIN_DISPATCH_MAP(CDispPoint, CCmdTarget)
    DISP_PROPERTY(CDispPoint, "x", m_x, VT_I2)
    DISP_PROPERTY(CDispPoint, "y", m_y, VT_I2)
END_DISPATCH_MAP()

BEGIN_DISPATCH_MAP(CDisp3DPoint, CDispPoint)
    DISP_PROPERTY(CDisp3DPoint, "z", m_z, VT_I2)
END_DISPATCH_MAP()

As you can see, there are two classes, both of which expose OLE automation interfaces. One of these classes is derived from the other and thus leverages the base class's functionality, including the OLE automation part ("x" and "y" properties in this case).

MFC will generate DISPIDs for class CDispPoint as follows:

property X    (DISPID)0x00000001
property Y    (DISPID)0x00000002

Since the properties are not in a base class, the HIWORD of the DISPID is always zero (the distance from the most derived class for CDispPoint is zero).

MFC will generate DISPIDs for class CDisp3DPoint as follows:

property Z    (DISPID)0x00000001
property X    (DISPID)0x00010001
property Y    (DISPID)0x00010002

The Z property is given a DISPID with a zero HIWORD since it is defined in the class which is exposing the properties, CDisp3DPoint. Since the X and Y properties are defined in a base class, the HIWORD of the DISPID is 1, since the class in which these properties are defined is at a distance of one derivation from the most derived class.

Note The LOWORD is always determined by the position in the map, even if there exist entries in the map with explicit DISPID (see next section for information on the _ID versions of the DISP_PROPERTY and DISP_FUNCTION macros).

Advanced MFC Dispatch Map Features

There are a number of additional features that ClassWizard does not support with this release of Visual C++. ClassWizard supports DISP_FUNCTION, DISP_PROPERTY, and DISP_PROPERTY_EX which define a method, member variable property, and get/set member function property, respectively. These capabilities are usually all that is needed to create most automation servers.

The following additional macros can be used when the ClassWizard supported macros are not adequate: DISP_PROPERTY_NOTIFY, and DISP_PROPERTY_PARAM.

DISP_PROPERTY_NOTIFY — Macro Description

DISP_PROPERTY_NOTIFY(theClass, pszName, memberName, pfnAfterSet, vtPropType)

theClass

Name of the class.

pszName

External name of the property.

memberName

Name of the member variable in which the property is stored.

pfnAfterSet

Name of member function to call when property is changed.

vtPropType

A value specifying the property's type.

Note This macro is much like DISP_PROPERTY, except that it accepts an additional argument. The additional argument, pfnAfterSet, should be a member function that returns nothing and takes no parameters, 'void OnPropertyNotify()'. It will be called after the member variable has been modified.

DISP_PROPERTY_PARAM — Macro Description

DISP_PROPERTY_PARAM(theClass, pszName, pfnGet, pfnSet, vtPropType, vtsParams)

theClass

Name of the class.

pszName

External name of the property.

memberGet

Name of the member function used to get the property.

memberSet

Name of the member function used to set the property.

vtPropType

A value specifying the property's type.

vtsParams

A string of space separated VTS_ for each parameter.

Note Much like the DISP_PROPERTY_EX macro, this macro defines a property accessed with separate Get and Set member functions. This macro, however, allows you to specify a parameter list for the property. This is useful for implementing properties which are indexed or parameterized in some other way. The parameters will always be placed first, followed by the new value for the property. For example:

DISP_PROPERTY_PARAM(CMyObject, "item", GetItem, SetItem, VT_DISPATCH,    VTS_I2 VTS_I2)

would correspond to get and set member functions:

LPDISPATCH CMyObject::GetItem(short row, short col)
void CMyObject::SetItem(short row, short col, LPDISPATCH newValue)

DISP_XXXX_ID — Macro Descriptions

DISP_FUNCTION_ID(theClass, pszName, dispid, pfnMember, vtRetVal, vtsParams)

DISP_PROPERTY_ID(theClass, pszName, dispid, memberName, vtPropType)

DISP_PROPERTY_NOTIFY_ID(theClass, pszName, dispid, memberName, pfnAfterSet, vtPropType)

DISP_PROPERTY_EX_ID(theClass, pszName, dispid, pfnGet, pfnSet, vtPropType)

DISP_PROPERTY_PARAM_ID(theClass, pszName, dispid, pfnGet, pfnSet, vtPropType, vtsParams)

theClass

Name of the class.

pszName

External name of the property.

dispid

The fixed DISPID for the property or method.

pfnGet

Name of the member function used to get the property.

pfnSet

Name of the member function used to set the property.

memberName

The name of the member variable to map to the property

vtPropType

A value specifying the property's type.

vtsParams

A string of space separated VTS_ for each parameter.

Note These macros allow you to specify a DISPID instead of letting MFC automatically assign one. These advanced macros have the same names except that ID is appended to the macro name (e.g. DISP_PROPERTY_ID) and the ID is determined by the parameter specified just after the pszName parameter. See AFXDISP.H for more information on these macros. The _ID entries must be placed at the end of the dispatch map. They will affect the automatic DISPID generation in the same way as a non-_ID version of the macro would (the DISPIDs are determined by position). For example:

BEGIN_DISPATCH_MAP(CDisp3DPoint, CCmdTarget)
    DISP_PROPERTY(CDisp3DPoint, "y", m_y, VT_I2)
    DISP_PROPERTY(CDisp3DPoint, "z", m_z, VT_I2)
    DISP_PROPERTY_ID(CDisp3DPoint, "x", 0x00020003, m_x, VT_I2)
END_DISPATCH_MAP()

MFC will generate DISPIDs for class CDisp3DPoint as follows:

property X    (DISPID)0x00020003
property Y    (DISPID)0x00000002
property Z     (DISPID)0x00000001

Specifying a fixed DISPID is useful to maintain backward compatibility to a previously existing dispatch interface, or to implement certain system defined methods or properties (usually indicated by a negative DISPID, such as the DISPID_NEWENUM collection).

Retrieving the IDispatch Interface for a COleClientItem

Many servers will support automation within their document objects, along with the OLE server functionality. In order to gain access to this automation interface, it is necessary to directly access the COleClientItem::m_lpObject member variable. The code below will retrieve the IDispatch interface for an object derived from COleClientItem. You can include the code below in your application if you find this functionality necessary:

LPDISPATCH CMyClientItem::GetIDispatch()
{
    ASSERT_VALID(this);
    ASSERT(m_lpObject != NULL);

    LPUNKNOWN lpUnk = m_lpObject;

    Run();    // must be running

    LPOLELINK lpOleLink = NULL;
    if (m_lpObject->QueryInterface(IID_IOleLink,
        (LPVOID FAR*)&lpOleLink) == NOERROR)
    {
        ASSERT(lpOleLink != NULL);
        lpUnk = NULL;
        if (lpOleLink->GetBoundSource(&lpUnk) != NOERROR)
        {
            TRACE0("Warning: Link is not connected!\n");
            lpOleLink->Release();
            return NULL;
        }
        ASSERT(lpUnk != NULL);
    }

    LPDISPATCH lpDispatch = NULL;
    if (lpUnk->QueryInterface(IID_IDispatch, &lpDispatch)
        != NOERROR)
    {
        TRACE0("Warning: does not support IDispatch!\n");
        return NULL;
    }

    ASSERT(lpDispatch != NULL);
    return lpDispatch;
}

The dispatch interface returned from this function could then be used directly or attached to a COleDispatchDriver for type-safe access. If you use it directly, make sure that you call its Release member when through with the pointer (the COleDispatchDriver destructor does this by default).


TN040: MFC/OLE In-Place Resizing and Zooming

This note will discuss the issues relating to in-place editing and how a server should accomplish correct zooming and in-place resizing. With in-place activation, the WYSIWYG concept is taken one step further in that containers and servers cooperate with each other, and in particular interpret the OLE specification in much the same way.

Because of the close interaction between a container and server supporting in-place activation there are a number of expectations from the end-user that should be maintained:

  • The presentation display (the metafile drawn in the COleServerItem::OnDraw override) should look exactly the same as when it is drawn for editing (except that editing tools are not visible).

  • When the container zooms, the server window should too!

  • Both the container and server should display objects for editing using the same metrics. This means using a mapping mode based on the number of logical pixels per inch — not physical pixels per inch, when rendering on the display device.

Note Because in-place activation only applies to items which are embedded (not linked), zooming only applies to embedded objects. You'll see APIs in both COleServerDoc and COleServerItem that are used for zooming. The reason for this dichotomy is that only functions which are valid for both linked and embedded items are in COleServerItem (this allows you to have a common implementation) and functions which are valid only for embedded objects are located in the COleServerDoc class (from the server's perspective, it is the document which is embedded).

Most of the burden is placed on the server implementor, in that the server must be aware of the container's zoom factor and modify its editing interface as appropriate. But how does the server determine the zoom factor that the container is using?

MFC Support for Zooming

The current zoom factor can be determined by calling COleServerDoc::GetZoomFactor. Calling this when the document is not in-place active will always result in a 100% zoom factor (or 1:1 ratio). Calling it while in-place active may return something other than 100%.

For an example of zooming correctly see the MFC OLE sample HIERSVR. Zooming in HIERSVR is complicated by the fact that it displays text — and text, in general, does not scale in a linear fashion (hints, typographic conventions, design widths and heights all complicate the matter). Still, HIERSVR is a reasonable reference for implementing zooming correctly, and so is the MFC Tutorial SCRIBBLE (step 7).

COleServerDoc::GetZoomFactor determines the zoom factor based on a number of different metrics available either from the container or from the implementation of your COleServerItem and COleServerDoc classes. In short, the current zoom factor is determined by the following formula:

Position Rectangle (PR) / Container Extent (CE)

The POSITION RECTANGLE is determined by the container. It is returned to the server during in-place activation when COleClientItem::OnGetItemPosition is called and is updated when the container calls the server's COleServerDoc::OnSetItemRects (with a call to COleClientItem::SetItemRects).

The CONTAINER EXTENT is slightly more complex to calculate. If the container has called COleServerItem::OnSetExtent (with a call to COleClientItem::SetExtent), then the CONTAINER EXTENT is this value converted to pixels based on the number of pixels per logical inch. If the container has not called SetExtent (which is usually the case), then the CONTAINER EXTENT is the size returned from COleServerItem::OnGetExtent. So, if the container has not called SetExtent, the framework assumes that if it did the container would have called it with 100% of the natural extent (the value returned from COleServerItem::GetExtent). Or stated another way, the framework assumes that the container is displaying 100% (no more, no less) of the item.

It is important to note that although COleServerItem::OnSetExtent and COleServerItem::OnGetExtent have similar names, they do not manipulate the same attribute of the item. OnSetExtent is called to let the server know how much of the object is visible in the container (regardless of the zoom factor) and OnGetExtent is called by the container to determine ideal size of the object.

By looking at each of the APIs involved here you can get a clearer picture:

COleServerItem::OnGetExtent

This function should return the "natural size" in HIMETRIC units of the item. The best way to think of the "natural size" is to define it as the size it might appear when printed. The size returned here is constant for a particular item contents (much like the metafile, which is constant for a particular item). This size does not change when zooming is applied to the item. It usually does not change when the container gives the item more or less space by calling OnSetExtent. An example of a change might be that of a simple text editor with no "margin" capability that wrapped text based on the last extent sent by the container. If a server does change, the server should probably set the OLEMISC_RECOMPOSEONRESIZE bit in the system registry (see the OLE SDK documentation for more information on this option).

COleServerItem::OnSetExtent

This function is called when the container shows "more or less" of the object. Most containers will not call this at all. The default implementation stores the last value received from the container in 'm_sizeExtent', which is used in COleServerDoc::GetZoomFactor when computing the CONTAINER EXTENT value described above.

COleServerDoc::OnSetItemRects

This function is called only when the document is in-place active. It is called when the container updates either the item's position or the clipping applied to the item. The POSITION RECTANGLE, as discussed above, provides the numerator for the zoom factor calculation. A server can request that the item position be changed by calling COleServerDoc::RequestPositionChange. The container may or may not respond to this request by calling OnSetItemRects (with a call to COleServerItem::SetItemRects).

COleServerDoc::OnDraw

It is important to realize that the metafile created by overriding of COleServerItem::OnDraw produces exactly the same metafile, regardless of the current zoom factor. The container will scale the metafile as appropriate. This is an important distinction between the view's OnDraw and the server item's OnDraw. The view handles zooming, the item just creates a zoomable metafile and leaves it up to the container to do the appropriate zooming.

The best way to insure that your server behaves correctly is to use the implementation of COleServerDoc::GetZoomFactor if your document is in-place active.

MFC Support for In-Place Resizing

MFC fully implements the in-place resizing interface as described in the OLE 2 specification. The user-interface is supported by the COleResizeBar class, a custom message WM_SIZECHILD, and special handling of this message in COleIPFrameWnd.

You may want to implement different handling of this message than what is provided by the framework. As described above, the framework leaves the results of in-place resizing up to the container — the server responds to the change in the zoom factor. If the container reacts by setting the both CONTAINER EXTENT and POSITION RECTANGLE during the processing of its COleClientItem::OnChangeItemPosition (called as a result of a call to COleServerDoc::RequestPositionChange) then the in-place resize will result in showing "more or less" of the item in the editing window. If the container reacts by just setting the POSITION RECTANGLE during the processing of COleClientItem::OnChangeItemPosition, the zoom factor will change and the item will be shown "zoomed in or out."

A server can control (to some degree) what happens during this negotiation. A spreadsheet, for example might elect to show more or fewer cells when the user resizes the window while editing the item in-place. A word-processor might elect to change the "page margins" so they are the same as the window and rewrap the text to the new margin. Servers implement this by changing the natural extent (the size returned from COleServerItem::OnGetExtent) when the resizing is done. This will cause both the POSITION RECTANGLE and the CONTAINER EXTENT to change by the same amount, resulting in the same zoom factor, but a bigger or smaller viewing area. In addition, more or less of the document will be visible in the metafile generated by OnDraw. In this case, the document itself is changing when the user resizes the item, instead of just the viewing area.

You can implement custom resizing and still leverage the user interface provided by COleResizeBar by overriding the WM_SIZECHILD message in your COleIPFrameWnd class. For more information on the specifics of WM_SIZECHILD, see Technical Note 24.


TN041: MFC/OLE1 Migration to MFC/OLE 2

General Issues Relating to Migration

One of the design goals for the OLE 2 classes in MFC 2.5 (and higher) was to retain much of the same architecture put in place in MFC 2.0 for OLE 1.0 support. As a result, many of the same OLE classes in MFC 2.0 still exist in this version of MFC (COleDocument, COleServerDoc, COleClientItem, COleServerItem). In addition, many of the APIs in these classes are exactly the same. However, OLE 2 is drastically different from OLE 1.0 so you can expect that some of the details have changed. If you are familiar with MFC 2.0's OLE1 support, you'll feel at home with MFC's 2.0 support.

If you are taking an existing MFC/OLE1 application and adding OLE 2 functionality to it, you should read this note first. This note covers some general issues you may encounter while porting your OLE1 functionality to MFC/OLE 2 and then discusses the problems uncovered while porting two applications included in MFC 2.0: the MFC OLE samples OCLIENT and HIERSVR.

MFC Document/View Architecture Is Important

If your application does not use MFC's Document/View architecture and you want to add OLE 2 support to your application, now is the time to move to Document/View. Many of the benefits of MFC's OLE 2 classes are only realized once your application is using the built-in architecture and components of MFC.

Implementing a server or container without using the MFC architecture is possible, but not recommended.

Use MFC Implementation Instead of Your Own

MFC "canned implementation" classes such as CToolBar, CStatusBar, and CScrollView have built-in special case code for OLE 2 support. So, if you can use these classes in your application you'll benefit from the effort put into them to make them OLE aware. Again, it is possible to "roll-your-own" classes here for these purposes, but it is not suggested. If you need to implement similar functionality, the MFC source code is an excellent reference for dealing with some of the finer points of OLE (especially when it comes to in-place activation).

Examine the MFC Sample Code

There are a number of MFC samples that include OLE functionality. Each of these applications implements OLE from a different angle:

HIERSVR - Meant mostly for use as a server application. It was included in MFC 2.0 as an MFC/OLE1 application and has been ported to MFC/OLE 2 and then extended such that it implements many OLE features available in OLE 2.

OCLIENT - This is a stand-alone container application, meant to demonstrate many of the OLE features from a container standpoint. It too was ported from MFC 2.0, and then extended to support many of the more advanced OLE features, such as custom clipboard formats and links to embedded items.

DRAWCLI - This application implements OLE container support much like OCLIENT does, except that it does so within the framework of an existing object-oriented drawing program. It shows you how you might implement OLE container support and integrate it into your existing application.

SUPERPAD - This application, as well as being a fine stand-alone application, is also an OLE server. The server support it implements is quite minimalist. Of particular interest is how it uses OLE clipboard services to copy data to the clipboard, but uses the functionality built into the Windows "edit" control to implement clipboard paste functionality. This shows an interesting mix of traditional Windows API usage as well as integration with the new OLE APIs.

For more information on the sample applications see the "MFC Sample Help".

Case Study: OCLIENT from MFC 2.0

As discussed above, OCLIENT was included in MFC 2.0 and implemented OLE with MFC/OLE1. The steps by which this application was initially converted to use the MFC/OLE 2 classes are described below. A number of features were added after the initial port was completed to better illustrate the MFC/OLE classes. These features will not be covered here; refer to the sample itself for more information on those advanced features.

Note The compiler errors and step-by-step process was created with Visual C++ 2.0. Specific error messages and locations may have changed with Visual C++ 4.0, but the conceptual information remains valid.

Getting It Up and Running

The approach taken to port the OCLIENT sample to MFC/OLE is to start by building it and fixing the obvious compiler errors that will result. If you take the OCLIENT sample from MFC 2.0 and compile it under this version of MFC, you'll find that there are not that many errors to resolve. The errors in the order in which they occurred are described below.

Compile and Fix Errors

\oclient\mainview.cpp(104) : error C2660: 'Draw' : function does not take 4 parameters

The first error concerns COleClientItem::Draw. In MFC/OLE1 it took more parameters than the MFC/OLE version takes. The extra parameters were often not necessary and usually NULL (as in this example). This version of MFC can automatically determine the values for the lpWBounds when the CDC that is being drawn to is a metafile DC. In addition, the pFormatDC parameter is no longer necessary since the framework will build one from the "attribute DC" of the pDC passed in. So to fix this problem, you simply remove the two extra NULL parameters to the Draw call.

\oclient\mainview.cpp(273) : error C2065: 'OLE_MAXNAMESIZE' : undeclared identifier
\oclient\mainview.cpp(273) : error C2057: expected constant expression
\oclient\mainview.cpp(280) : error C2664: 'CreateLinkFromClipboard' : cannot convert parameter 1 from 'char [1]' to 'enum ::tagOLERENDER '
\oclient\mainview.cpp(286) : error C2664: 'CreateFromClipboard' : cannot convert parameter 1 from 'char [1]' to 'enum ::tagOLERENDER '
\oclient\mainview.cpp(288) : error C2664: 'CreateStaticFromClipboard' : cannot convert parameter 1 from 'char [1]' to 'enum ::tagOLERENDER '

The errors above result from the fact that all of the COleClientItem::CreateXXXX functions in MFC/OLE1 required that a unique name be passed to represent the item. This was a requirement of the underlying OLE API. This is not necessary in MFC/OLE 2 since OLE 2 does not use DDE as the underlying communications mechanism (the name was used in DDE conversations). To fix this problem, you can remove the CreateNewName function as well as all references to it. It is easy to find out what each MFC/OLE function is expecting in this version simply by placing your cursor on the call and pressing F1.

Another area that is significantly different is OLE 2 clipboard handling. With OLE1, you used the Windows clipboard APIs interact with the clipboard. With OLE 2 this is done with a different mechanism. The MFC/OLE1 APIs assumed that the clipboard was open before copying a COleClientItem object to the clipboard. This is no longer necessary and will cause all MFC/OLE clipboard operations to fail. While you edit the code to remove dependencies on CreateNewName, you should also remove the code that opens and closes the Windows clipboard.

\oclient\mainview.cpp(332) : error C2065: 'AfxOleInsertDialog' : undeclared identifier
\oclient\mainview.cpp(332) : error C2064: term does not evaluate to a function
\oclient\mainview.cpp(344) : error C2057: expected constant expression
\oclient\mainview.cpp(347) : error C2039: 'CreateNewObject' : is not a member of 'CRectItem'

These errors result from the CMainView::OnInsertObject handler. Handling the "Insert New Object" command is another area where things have changed quite a bit. In this case, it is easiest to simply merge the original implementation with that provided by AppWizard for a new OLE Container application. In fact, this is a technique that you can apply to porting other applications. In MFC/OLE1, you displayed the "Insert Object" dialog by calling AfxOleInsertDialog function. In this version you construct a COleInsertObject dialog object and call DoModal. In addition, new OLE items are created with a CLSID instead of a classname string. The end result should look something like this

COleInsertDialog dlg;
if (dlg.DoModal() != IDOK)
    return;

BeginWaitCursor();

CRectItem* pItem = NULL;
TRY
{
    // First create the C++ object
    pItem = GetDocument()->CreateItem();
    ASSERT_VALID(pItem);

    // Initialize the item from the dialog data.
    if (!dlg.CreateItem(pItem))
        AfxThrowMemoryException();
           // any exception will do
    ASSERT_VALID(pItem);

    // run the object if appropriate
    if (dlg.GetSelectionType() ==
            COleInsertDialog::createNewItem)
        pItem->DoVerb(OLEIVERB_SHOW, this);

    // update right away
    pItem->UpdateLink();
    pItem->UpdateItemRectFromServer();

    // set selection to newly inserted item
    SetSelection(pItem);
    pItem->Invalidate();
}
CATCH (CException, e)
{
    // clean up item
    if (pItem != NULL)
        GetDocument()->DeleteItem(pItem);

    AfxMessageBox(IDP_FAILED_TO_CREATE);
}
END_CATCH

EndWaitCursor();

Note Insert New Object may be different for your application):

It is also necessary to include <afxodlgs.h> which contains the declaration for the COleInsertObject dialog class as well as the other standard dialogs provided by MFC.

\oclient\mainview.cpp(367) : error C2065: 'OLEVERB_PRIMARY' : undeclared identifier
\oclient\mainview.cpp(367) : error C2660: 'DoVerb' : function does not take 1 parameters

These errors are caused by the fact that some OLE1 constants have changed in OLE 2, even though in concept they are the same. In this case OLEVERB_PRIMARY has changed to OLEIVERB_PRIMARY. In both OLE1 and OLE 2, the primary verb is usually executed by a container when the user double-clicks on an item.

In addition, DoVerb now takes an extra parameter — a pointer to a view (CView*). This parameter is only used to implement "Visual Editing" (or in-place activation). For now you set that parameter to NULL, since you are not implementing this feature at this time.

To make sure that the framework never attempts to in-place activate, you should override COleClientItem::CanActivate as follows:

BOOL CRectItem::CanActivate()
{
    return FALSE;
}

\oclient\rectitem.cpp(53) : error C2065: 'GetBounds' : undeclared identifier
\oclient\rectitem.cpp(53) : error C2064: term does not evaluate to a function
\oclient\rectitem.cpp(84) : error C2065: 'SetBounds' : undeclared identifier
\oclient\rectitem.cpp(84) : error C2064: term does not evaluate to a function

In MFC/OLE1, COleClientItem::GetBounds and SetBounds were used to query and manipulate the extent of an item (the left and top members were always zero). In MFC/OLE 2 this is more directly supported by COleClientItem::GetExtent and SetExtent, which deal with a SIZE or CSize instead.

The code for your new SetItemRectToServer, and UpdateItemRectFromServer calls look like this:

BOOL CRectItem::UpdateItemRectFromServer()
{
   ASSERT(m_bTrackServerSize);
   CSize size;
   if (!GetExtent(&size))
      return FALSE;    // blank

   // map from HIMETRIC to screen coordinates
   {
      CClientDC screenDC(NULL);
      screenDC.SetMapMode(MM_HIMETRIC);
      screenDC.LPtoDP(&size);
   }
   // just set the item size
   if (m_rect.Size() != size)
   {
      // invalidate the old size/position
      Invalidate();
      m_rect.right = m_rect.left + size.cx;
      m_rect.bottom = m_rect.top + size.cy;
      // as well as the new size/position
      Invalidate();
   }
   return TRUE;
}

BOOL CRectItem::SetItemRectToServer()
{
   // set the official bounds for the embedded item
   CSize size = m_rect.Size();
   {
      CClientDC screenDC(NULL);
      screenDC.SetMapMode(MM_HIMETRIC);
      screenDC.DPtoLP(&size);
   }
   TRY
   {
      SetExtent(size);  // may do a wait
   }
   CATCH(CException, e)
   {
      return FALSE;  // links will not allow SetBounds
   }
   END_CATCH
   return TRUE;
}

\oclient\frame.cpp(50) : error C2039: 'InWaitForRelease' : is not a member of 'COleClientItem'
\oclient\frame.cpp(50) : error C2065: 'InWaitForRelease' : undeclared identifier
\oclient\frame.cpp(50) : error C2064: term does not evaluate to a function

In MFC/OLE1 synchronous API calls from a container to a server were simulated, since OLE1 was inherently asynchronous in many cases. It was necessary to check for an outstanding asynchronous call in progress before processing commands from the user. MFC/OLE1 provided the COleClientItem::InWaitForRelease function for doing so. In MFC/OLE 2 this is not necessary, so you can to remove the override of OnCommand in CMainFrame all together.

At this point OCLIENT will compile and link.

Other Necessary Changes

There are few things that aren't done that will keep OCLIENT from running, however. It is better to fix these problems now instead of later.

First of all it is necessary to initialize the OLE libraries. This is done by calling AfxOleInit from InitInstance:

if (!AfxOleInit())
{
  AfxMessageBox("Failed to initialize OLE libraries");
  return FALSE;
}

It is also a good idea to check for virtual functions for parameter list changes. One such function is COleClientItem::OnChange, overridden in every MFC/OLE container application. By looking at online help, you'll see that an extra 'DWORD dwParam' was added. The new CRectItem::OnChange looks as follows:

void
CRectItem::OnChange(OLE_NOTIFICATION wNotification, DWORD dwParam)
{
  if (m_bTrackServerSize &&
        !UpdateItemRectFromServer())
  {
    // Blank object
    if (wNotification == OLE_CLOSED)
    {
      // no data received for the object - destroy it
      ASSERT(!IsVisible());
      GetDocument()->DeleteItem(this);
      return;   // no update (item is gone now)
    }
  }
  if (wNotification != OLE_CLOSED)
      Dirty();
  Invalidate();  // any change will cause a redraw
}

In MFC/OLE1, container applications derived the document class from COleClientDoc. In MFC/OLE 2 this class has been removed and replaced by COleDocument (this new organization makes it easier to build container/server applications). There is a #define that maps COleClientDoc to COleDocument to simplify porting of MFC/OLE1 applications to MFC/OLE 2, such as OCLIENT. One of the features not supplied by COleDocument that was provided by COleClientDoc is the standard command message map entries. This is done so that server applications, which also use COleDocument (indirectly), do not carry with them the overhead of these command handlers unless they are a container/server application. So, you need to add the following entries to the CMainDoc message map:

ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdatePasteMenu)
ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE_LINK, OnUpdatePasteLinkMenu)
ON_UPDATE_COMMAND_UI(ID_OLE_EDIT_LINKS, OnUpdateEditLinksMenu)
ON_COMMAND(ID_OLE_EDIT_LINKS, COleDocument::OnEditLinks)
ON_UPDATE_COMMAND_UI(ID_OLE_VERB_FIRST, OnUpdateObjectVerbMenu)
ON_UPDATE_COMMAND_UI(ID_OLE_EDIT_CONVERT, OnUpdateObjectVerbMenu)
ON_COMMAND(ID_OLE_EDIT_CONVERT, OnEditConvert)

The implementation of all of these commands is in COleDocument, which is the base class for your document.

At this point, OCLIENT is a functional OLE container application. It is possible to insert items of any type (OLE1 or OLE 2). Since the necessary code to enable in-place activation is not implemented, items are edited in a separate window much like with OLE1. The next section discusses the necessary changes to enable in-place editing (sometimes called "Visual Editing").

Adding "Visual Editing"

One of the most interesting features of OLE is in-place activation (or "Visual Editing"). This feature allows the server application to take over portions of the container's user interface to provided a more seamless editing interface for the user. To implement in-place activation to OCLIENT, some special resources need to be added, as well as some additional code. These resources and the code are normally provided by AppWizard — in fact, much of the code here was borrowed directly from a fresh AppWizard application with "Container" support.

First of all, it is necessary to add a menu resource to be used when there is an item which is in-place active. You can create this extra menu resource in Visual C++ by copying the IDR_OCLITYPE resource and removing all but the File and Window popups. Two separator bars are inserted between the File and Window popups to indicate the separation of groups (it should look like: File | | Window). For more information on what these separators mean and how the server and container menus are merged see "Menus and Resources: Menu Merging" in OLE 2 Classes.

Once you have these menus created, you need to let the framework know about them. This is done by calling CDocTemplate::SetContainerInfo for the document template before you add it to the document template list in your InitInstance. The new code to register the document template looks like this:

CDocTemplate* pTemplate = new CMultiDocTemplate(
    IDR_OLECLITYPE,
    RUNTIME_CLASS(CMainDoc),
    RUNTIME_CLASS(CMDIChildWnd),    // standard MDI child frame
    RUNTIME_CLASS(CMainView));
pTemplate->SetContainerInfo(IDR_OLECLITYPE_INPLACE);
AddDocTemplate(pTemplate);

The IDR_OLECLITYPE_INPLACE resource is the special in-place resource created in Visual C++.

In order to enable in-place activation, there are some things that need to change in both the CView (CMainView) derived class as well as the COleClientItem derived class (CRectItem). All of these overrides are provided by AppWizard and most of the implementation will come directly from a default AppWizard application.

In the first step of this port, in-place activation was disabled entirely by overriding COleClientItem::CanActivate. This override should be removed to allow in-place activation. In addition, NULL was passed to all calls to DoVerb (there are two of them) because providing the view was only necessary for in-place activation. To fully implement in-place activation, it is necessary to pass the correct view in the DoVerb call. One of these calls is in CMainView::OnInsertObject:

pItem->DoVerb(OLEIVERB_SHOW, this);

Another is in CMainView::OnLButtonDblClk:

m_pSelection->DoVerb(OLEIVERB_PRIMARY, this);

It is necessary to override COleClientItem::OnGetItemPosition. This tells the server where to put its window relative to the container's window when the item is in-place activated. For OCLIENT, the implementation is trivial:

void CRectItem::OnGetItemPosition(CRect& rPosition)
{
    rPosition = m_rect;
}

Most servers also implement what is called "in-place resizing." This allows the server window to be sized and moved while the user is editing the item. The container must participate in this action, since moving or resizing the window usually affects the position and size within the container document itself. The implementation for OCLIENT synchronizes the internal rectangle maintained by m_rect with the new position and size.

BOOL CRectItem::OnChangeItemPosition(const CRect& rectPos)
{
    ASSERT_VALID(this);

    if (!COleClientItem::OnChangeItemPosition(rectPos))
        return FALSE;

    Invalidate();
    m_rect = rectPos;
    Invalidate();
    GetDocument()->SetModifiedFlag();

    return TRUE;
}

At this point, there is enough code to allow an item to be in-place activated and to deal with sizing and moving the item when it is active, but there is no code that will allow the user to exit the editing session. Although some servers will provide this functionality themselves by handling the escape key, it is suggested that containers provide two ways to deactivate an item: (1) by clicking outside the item, and (2) by hitting the escape key.

For the escape key add an accelerator with Visual C++ that maps the VK_ESCAPE key to a command, ID_CANCEL_EDIT is added to the resources. The handler for this command follows:

// The following command handler provides the standard
// keyboard user interface to cancel an in-place
// editing session.void CMainView::OnCancelEdit()
{
    // Close any in-place active item on this view.
    COleClientItem* pActiveItem =
        GetDocument()->GetInPlaceActiveItem(this);
    if (pActiveItem != NULL)
        pActiveItem->Close();
    ASSERT(GetDocument()->GetInPlaceActiveItem(this) == NULL);
}

To handle the case where the user clicks outside the item, you add the following code to the start of CMainView::SetSelection:

if (pNewSel != m_pSelection || pNewSel == NULL)
{
    COleClientItem* pActiveItem =
        GetDocument()->GetInPlaceActiveItem(this);
    if (pActiveItem != NULL && pActiveItem != pNewSel)
        pActiveItem->Close();
}

When an item is in-place active, it should have the focus. To make sure this is the case you handle OnSetFocus so that focus is always transfered to the active item when your view receives the focus:

// Special handling of OnSetFocus and OnSize are required
// when an object is being edited in-place.
void CMainView::OnSetFocus(CWnd* pOldWnd)
{
    COleClientItem* pActiveItem =
        GetDocument()->GetInPlaceActiveItem(this);
    if (pActiveItem != NULL &&
    pActiveItem->GetItemState() == COleClientItem::activeUIState)
    {
        // need to set focus to this item if it is same view
        CWnd* pWnd = pActiveItem->GetInPlaceWindow();
        if (pWnd != NULL)
        {
            pWnd->SetFocus();  // don't call the base class
            return;
        }
    }

    CView::OnSetFocus(pOldWnd);
}

When the view is resized, you need to notify the active item that the clipping rectangle has changed. To do this you provide a handler for OnSize:

void CMainView::OnSize(UINT nType, int cx, int cy)
{
    CView::OnSize(nType, cx, cy);
    COleClientItem* pActiveItem =
        GetDocument()->GetInPlaceActiveItem(this);
    if (pActiveItem != NULL)
        pActiveItem->SetItemRects();
}

Case Study: HIERSVR from MFC 2.0

HIERSVR was also included in MFC 2.0 and implemented OLE with MFC/OLE1. This note briefly describes the steps by which this application was initially converted to use the MFC/OLE 2 classes. A number of features were added after the initial port was completed to better illustrate the MFC/OLE 2 classes. These features will not be covered here; refer to the sample itself for more information on those advanced features.

Note The compiler errors and step-by-step process was created with Visual C++ 2.0. Specific error messages and locations may have changed with Visual C++ 4.0, but the conceptual information remains valid.

Getting It Up and Running

The approach taken to port the HIERSVR sample to MFC/OLE is to start by building it and fixing the obvious compiler errors that will result. If you take the HIERSVR sample from MFC 2.0 and compile it under this version of MFC, you'll find that there are not many errors to resolve (although there are more than with the OCLIENT sample). The errors in the order in which they usually occur are described below.

Compile and Fix Errors

\hiersvr\hiersvr.cpp(83) : error C2039: 'RunEmbedded' : is not a member of 'COleTemplateServer'

This first error points out a much larger problem with the InitInstance function for servers. The initialization required for an OLE server is probably one of the biggest changes you'll have to make to your MFC/OLE1 application to get it running. The best thing to do is look at what AppWizard creates for an OLE server and modify your code as appropriate. Here are some points to keep in mind:

It is necessary to initialize the OLE libraries by calling AfxOleInit

Call SetServerInfo on the document template object to set server resource handles and runtime class information that you can't set with the CDocTemplate constructor.

Don't show the main window of your application if /Embedding is present on the command line.

You'll need a GUID for your document. This is a unique identifier for your document's type (128 bits). AppWizard will create one for you — so if you use the technique described here of copying the new code from a new AppWizard generated server application, you can simply "steal" the GUID from that application. If not, you can use the GUIDGEN.EXE utility in the BIN directory.

It is necessary to "connect" your COleTemplateServer object to the document template by calling COleTemplateServer::ConnectTemplate.

Update the system registry when your application is run stand-alone. This way, if the user moves the .EXE for your application, running it from its new location will update the Windows system registration database to point to the new location.

After applying all of these changes based on what AppWizard creates for InitInstance, the InitInstance (and related GUID) for HIERSVR should read as follows:

// this is the GUID for HIERSVR documents
static const GUID BASED_CODE clsid =
    { 0xA0A16360L, 0xC19B, 0x101A, { 0x8C, 0xE5, 0x00, 0xDD, 0x01, 0x11, 0x3F, 0x12 } };

/////////////////////////////////////////////////////////////////////////////
// COLEServerApp initialization

BOOL COLEServerApp::InitInstance()
{
    // OLE 2 initialization
    if (!AfxOleInit())
    {
        AfxMessageBox("Initialization of the OLE failed!");
        return FALSE;
    }

    // Standard initialization
    LoadStdProfileSettings(); // Load standard INI file options

    // Register document templates
    CDocTemplate* pDocTemplate;
    pDocTemplate = new CMultiDocTemplate(IDR_HIERSVRTYPE,
        RUNTIME_CLASS(CServerDoc),
        RUNTIME_CLASS(CMDIChildWnd),
        RUNTIME_CLASS(CServerView));
    pDocTemplate->SetServerInfo(IDR_HIERSVRTYPE_SRVR_EMB);
    AddDocTemplate(pDocTemplate);

    // create main MDI Frame window
    CMainFrame* pMainFrame = new CMainFrame;
    if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
        return FALSE;
    m_pMainWnd = pMainFrame;

    SetDialogBkColor();   // gray look

    // enable file manager drag/drop and DDE Execute open
    m_pMainWnd->DragAcceptFiles();
    EnableShellOpen();

    m_server.ConnectTemplate(clsid, pDocTemplate, FALSE);
    COleTemplateServer::RegisterAll();

    // try to launch as an OLE server
    if (RunEmbedded())
    {
        // "short-circuit" initialization -- run as server!
        return TRUE;
    }
    m_server.UpdateRegistry();
    RegisterShellFileTypes();

    // not run as OLE server, so show the main window
    if (m_lpCmdLine[0] == '\0')
    {
        // create a new (empty) document
        OnFileNew();
    }
    else
    {
        // open an existing document
        OpenDocumentFile(m_lpCmdLine);
    }

    pMainFrame->ShowWindow(m_nCmdShow);
    pMainFrame->UpdateWindow();

    return TRUE;
}

You'll notice that the code above refers to a new resource ID, IDR_HIERSVRTYPE_SRVR_EMB. This is the menu resource to be used when a document that is embedded in another container is edited. In MFC/OLE1 the menu items specific to editing an embedded item were modified on the fly. Using an entirely different menu structure when editing an embedded item instead of editing a file-based document makes it much easier to provide different user interfaces for these two separate modes. As you'll see later, an entirely separate menu resource is used when editing an embedded object in-place.

To create this resource, load the resource script into Visual C++ and copy the existing IDR_HIERSVRTYPE menu resource. Rename the new resource to IDR_HIERSVRTYPE_SRVR_EMB (this is the same naming convention that AppWizard uses). Next change "File Save" to "File Update"; give it command ID ID_FILE_UPDATE. Also change "File Save As" to "File Save Copy As"; give it command ID ID_FILE_SAVE_COPY_AS. The framework provides the implementation of both of these commands.

\hiersvr\svritem.h(60) : error C2433: 'OLESTATUS' : 'virtual' not permitted on data declarations
\hiersvr\svritem.h(60) : error C2501: 'OLESTATUS' : missing decl-specifiers
\hiersvr\svritem.h(60) : error C2146: syntax error : missing ';' before identifier 'OnSetData'
\hiersvr\svritem.h(60) : error C2061: syntax error : identifier 'OLECLIPFORMAT'
\hiersvr\svritem.h(60) : error C2501: 'OnSetData' : missing decl-specifiers

There are a number of errors resulting from the override of OnSetData, since it is referring to the OLESTATUS type. OLESTATUS was the way OLE1 returned errors. This has changed to HRESULT in OLE 2, although MFC usually converts an HRESULT into a COleException containing the error. In this particular case, the override of OnSetData is no longer necessary, so the easiest thing to do is to remove it.

\hiersvr\svritem.cpp(30) : error C2660: 'COleServerItem::COleServerItem' : function does not take 1 parameters

The COleServerItem constructor takes an extra 'BOOL' parameter. This flag determines how memory management is done on the COleServerItem objects. By setting it to TRUE, the framework handles the memory management of these objects — deleting them when they are no longer necessary. HIERSVR uses CServerItem (derived from COleServerItem) objects as part of its native data, so you'll set this flag to FALSE. This lets HIERSVR determine when each server item is deleted.

\hiersvr\svritem.cpp(44) : error C2259: 'CServerItem' : illegal attempt to instantiate abstract class
\hiersvr\svritem.cpp(44) : error C2259: 'CServerItem' : illegal attempt to instantiate abstract class

As these errors imply, there are some 'pure-virtual' functions which have not been overridden in CServerItem. Most likely this is caused by the fact that OnDraw's parameter list has changed. To fix this error, change CServerItem::OnDraw as follows (as well as the declaration in svritem.h):

BOOL CServerItem::OnDraw(CDC* pDC, CSize& rSize)
{
    // request from OLE to draw node
    pDC->SetMapMode(MM_TEXT); // always in pixels
    return DoDraw(pDC, CPoint(0,0), FALSE);
}

The new parameter is 'rSize'. This allows you to fill in the size of the drawing, if convenient. This size must be in HIMETRIC. In this case, it is not convenient to fill this value in, so the framework calls OnGetExtent to retrieve the extent. For that to work, you'll have to implement OnGetExtent:

BOOL CServerItem::OnGetExtent(DVASPECT dwDrawAspect, CSize& rSize)
{
    if (dwDrawAspect != DVASPECT_CONTENT)
        return COleServerItem::OnGetExtent(dwDrawAspect, rSize);

    rSize = CalcNodeSize();
    return TRUE;
}

\hiersvr\svritem.cpp(104) : error C2065: 'm_rectBounds' : undeclared identifier
\hiersvr\svritem.cpp(104) : error C2228: left of '.SetRect' must have class/struct/union type
\hiersvr\svritem.cpp(106) : error C2664: 'void __pascal __far DPtoLP(struct ::tagPOINT __far *,int )__far const ' : cannot convert parameter 1 from 'int __far *' to 'struct ::tagPOINT __far *'

In the CServerItem::CalcNodeSize function the item size is converted to HIMETRIC and stored in m_rectBounds. The undocumented 'm_rectBounds' member of COleServerItem does not exist (it has been partially replaced by m_sizeExtent, but in OLE 2 this member has a slightly different usage than m_rectBounds did in OLE1). Instead of setting the HIMETRIC size into this member variable, you'll return it. This return value is used in OnGetExtent, implemented previously.

CSize CServerItem::CalcNodeSize()
{
    CClientDC dcScreen(NULL);

    m_sizeNode = dcScreen.GetTextExtent(m_strDescription,
      m_strDescription.GetLength());
    m_sizeNode += CSize(CX_INSET * 2, CY_INSET * 2);

    // set suggested HIMETRIC size
    CSize size(m_sizeNode.cx, m_sizeNode.cy);
    dcScreen.SetMapMode(MM_HIMETRIC);
    dcScreen.DPtoLP(&size);
    return size;
}

CServerItem also overrides COleServerItem::OnGetTextData. This function is obsolete in MFC/OLE and is replaced by a different mechanism. The MFC 3.0 version of the MFC OLE sample HIERSVR implements this functionality by overriding COleServerItem::OnRenderFileData. This functionality is not important for this basic port, so you can remove the OnGetTextData override.

There are many more errors in svritem.cpp that haven't been addressed. They are not "real" errors — just errors caused by previous errors.

\hiersvr\svrview.cpp(325) : error C2660: 'CopyToClipboard' : function does not take 2 parameters

COleServerItem::CopyToClipboard no longer supports the 'bIncludeNative' flag. The native data (the data written out by the server item's Serialize function) is always copied, so you remove the first parameter. In addition, CopyToClipboard will throw an exception when an error happens instead of returning FALSE. Change the code for CServerView::OnEditCopy as follows:

void CServerView::OnEditCopy()
{
    if (m_pSelectedNode == NULL)
        AfxThrowNotSupportedException();

    TRY
    {
        m_pSelectedNode->CopyToClipboard(TRUE);
    }
    CATCH_ALL(e)
    {
        AfxMessageBox("Copy to clipboard failed");
    }
    END_CATCH_ALL
}

Although there were more errors resulting from the compilation of the MFC 2.0 version of HIERSVR than there were for the same version of OCLIENT, there were actually fewer changes.

At this point HIERSVR will compile and link and function as an OLE server, but without the in-place editing feature, which will be implemented next.

Adding "Visual Editing"

To add "Visual Editing" (or in-place activation) to this server application, there are only a few things you must take care of:

  • You need a special menu resource to be used when the item is in-place active.

  • This application has a toolbar, so you'll need a toolbar with only a subset of the normal toolbar to match the menu commands available from the server (matches the menu resource mentioned above).

  • You need a new class derived from COleIPFrameWnd that provides the in-place user interface (much like CMainFrame, derived from CMDIFrameWnd, provides the MDI user interface).

  • You need to tell the framework about these special resources and classes.

The menu resource is easy to create. Run Visual C++, copy the menu resource IDR_HIERSVRTYPE to a menu resource called IDR_HIERSVRTYPE_SRVR_IP. Modify the menu so that only the Edit and Help menu popups are left. Add two separators to the menu in between the Edit and Help menus (it should look like: Edit | | Help). For more information on what these separators mean and how the server and container menus are merged, see "Menus and Resources: Menu Merging" in OLE 2 Classes.

The bitmap for the subset toolbar can be easily created by copying the one from a fresh AppWizard generated application with a "Server" option checked. This bitmap can then be imported into Visual C++. Be sure to give the bitmap an ID of IDR_HIERSVRTYPE_SRVR_IP.

The class derived from COleIPFrameWnd can be copied from an AppWizard generated application with server support as well. Copy both files, IPFRAME.CPP and IPFRAME.H and add them to the project. Make sure that the LoadBitmap call refers to IDR_HIERSVRTYPE_SRVR_IP, the bitmap created in the previous step.

Now that all the new resources and classes are created, add the necessary code so that the framework knows about these (and knows that this application now supports in-place editing). This is done by adding some more parameters to the SetServerInfo call in the InitInstance function:

pDocTemplate->SetServerInfo(IDR_HIERSVRTYPE_SRVR_EMB,
    IDR_HIERSVRTYPE_SRVR_IP, RUNTIME_CLASS(CInPlaceFrame));

It is now ready to run in-place in any container which also supports in-place activation. But, there is one minor bug still lurking in the code. HIERSVR supports a context menu, displayed when the user presses the right mouse button. This menu works when HIERSVR is fully open, but does not work when editing an embedding in-place. The reason can be pinned down to this single line of code in CServerView::OnRButtonDown:

pMenu->TrackPopupMenu(TPM_CENTERALIGN | TPM_RIGHTBUTTON,
    point.x, point.y, AfxGetApp()->m_pMainWnd);

Notice the reference to AfxGetApp()->m_pMainWnd. When the server is in-place activated, it has a main window and m_pMainWnd is set, but it is usually invisible. Furthermore, this window refers to the main window of the application, the MDI frame window that appears when the server is fully open or run stand-alone. It does not refer to the active frame window — which when in-place activated is a frame window derived from COleIPFrameWnd. To get the correct active window even when in-place editing, this version of MFC adds a new function, AfxGetMainWnd. Generally, you should use this function instead of AfxGetApp()->m_pMainWnd. This code needs to change as follows:

pMenu->TrackPopupMenu(TPM_CENTERALIGN | TPM_RIGHTBUTTON,
    point.x, point.y, AfxGetMainWnd());

Now you have an OLE server minimally enabled for functional in-place activation. But there are still many features available with MFC/OLE 2 that were not available in MFC/OLE1. See the HIERSVR sample for more ideas on features you might want to implement. Some of the features that HIERSVR implements are listed below:

  • Zooming, for true WYSISYG behavior with respect to the container.

  • Drag / drop and a custom clipboard format

  • Scrolling the container window as the selection is changed

The HIERSVR sample in MFC 3.0 also uses a slightly different design for its server items. This helps conserve memory and makes your links more flexible. With the 2.0 version of HIERSVR each node in the tree is-a COleServerItem. COleServerItem carries a bit more overhead than is strictly necessary for each of these nodes, but a COleServerItem is required for each active link. But for the most part, there are very few active links at any given time. To make this more efficient, the HIERSVR in this version of MFC separates the node from the COleServerItem. It has both a CServerNode and a CServerItem class. The CServerItem (derived from COleServerItem) is only created as necessary. Once the container (or containers) stop using that particular link to that particular node, the CServerItem object associated with the CServerNode is deleted. This design is more efficient and more flexible. Its flexibility comes in when dealing with multiple selection links. Neither of these two versions of HIERSVR support multiple selection, but it would be much easier to add (and to support links to such selections) with the MFC 3.0 version of HIERSVR, since the COleServerItem is separated from the native data.


TN042: ODBC Driver Developer Recommendations

This note describes guidelines for ODBC driver writers. It outlines general requirements and assumptions of ODBC functionality which the MFC Database classes make, and various expected semantic details. Required driver functionality to support the three CRecordset Open modes (forwardOnly, snapshot and dynaset) are described.

ODBC's Cursor Library

The MFC Database classes present functionality to the user which in many cases surpasses the functionality provided by most level 1 ODBC drivers. Fortunately, ODBC's Cursor Library will layer itself between the database classes and the driver, and will automatically provide much of this additional functionality.

For instance, most 1.0 drivers do not support backward scrolling. The Cursor Library can detect this, and will cache rows from the driver and present them as requested on FETCH_PREV calls in SQLExtendedFetch.

Another important example of cursor library dependence is positioned updates. Most 1.0 drivers also do not have positioned updates, but the cursor library will generate update statements which identify a target row on the data source based upon its current cached data values, or a cached timestamp value.

The class library never makes use of multiple rowsets. Therefore, the few SQLSetPos statements are always applied to row 1 of the rowset.

CDatabases

Each CDatabase allocates a single HDBC. (If CDatabase's ExecuteSQL function is used, an HSTMT is temporarily allocated.) So if multiple CDatabase's are required, multiple HDBCs per HENV must be supported.

The database classes require the cursor library. This is reflected in a SQLSetConnections call SQL_ODBC_CURSORS, SQL_CUR_USE_ODBC.

SQLDriverConnect, SQL_DRIVER_COMPLETE is used by CDatabase::Open to establish the connection to the data source.

The driver must support SQLGetInfo SQL_ODBC_API_CONFORMANCE >= SQL_OAC_LEVEL1, SQLGetInfo SQL_ODBC_SQL_CONFORMANCE >= SQL_OSC_MINIMUM.

In order for transactions to be supported for the CDatabase and its dependent recordsets, SQLGetInfo SQL_CURSOR_COMMIT_BEHAVIOR and SQL_CURSOR_ROLLBACK_BEHAVIOR must have SQL_CR_PRESERVE. Otherwise, attempts to perform transaction control will be ignored.

SQLGetInfo SQL_DATA_SOURCE_READ_ONLY must be supported. If it returns "Y", no update operations will be performed on the data source.

If the CDatabase is opened ReadOnly an attempt to set the data source readonly will be made with SQLSetConnectOption SQL_ACCESS_MODE, SQL_MODE_READ_ONLY.

If identifiers require quoting, this information should be returned from the driver with an SQLGetInfo SQL_IDENTIFIER_QUOTE_CHAR call.

For debugging purposes, SQLGetInfo SQL_DBMS_VER and SQL_DBMS_NAME are retrieved from the driver.

SQLSetStmtOption SQL_QUERY_TIMEOUT and SQL_ASYNC_ENABLE may be called on a CDatabase's HDBC.

SQLError may be called with any or all arguments NULL.

Of course, SQLAllocEnv, SQLAllocConnect, SQLDisconnect and SQLFreeConnect must be supported.

ExecuteSQL

In additional to allocating and freeing a temporary HSTMT, ExecuteSQL calls SQLExecDirect, SQLFetch, SQLNumResultCol and SQLMoreResults. SQLCancel may be called on the HSTMT.

GetDatabaseName

SQLGetInfo SQL_DATABASE_NAME will be called.

BeginTrans, CommitTrans, Rollback

SQLSetConnectOption SQL_AUTOCOMMIT and SQLTransact SQL_COMMIT, SQL_ROLLBACK and SQL_AUTOCOMMIT will be called if transaction requests are made.

CRecordsets

SQLAllocStmt, SQLPrepare, SQLExecute (For Open and Requery), SQLExecDirect (for update operations), SQLFreeStmt must be supported. SQLNumResultCols and SQLDescribeCol will be called on the results set at various times.

SQLSetParam is used extensively for binding parameter data and DATA_AT_EXEC functionality.

SQLBindCol is used extensively to register output Column data storage locations with ODBC.

Two SQLGetData calls are used to retrieve SQL_LONG_VARCHAR and SQL_LONG_VARBINARY data. The first call attempts to find the total length of the column value by calling SQLGetData with cbMaxValue of 0, but with a valid pcbValue. If pcbValue holds SQL_NO_TOTAL, an exception is thrown. Otherwise an HGLOBAL is allocated, and another SQLGetData call made to retrieve the entire result.

Updating

If pessimistic locking is requested, SQLGetInfo SQL_LOCK_TYPES will be queried. If SQL_LCK_EXCLUSIVE is not supported, an exception will be thrown.

Attempts to update a CRecordset (snapshot or dynaset) will cause a second HSTMT to be allocated. For drivers that don't support second HSTMT, the cursor library will simulate this functionality. Unfortunately, this may sometimes mean forcing the current query on the first HSTMT to completion before processing the second HSTMT's request.

SQLFreeStmt SQL_CLOSE and SQL_RESET_PARAMS and SQLGetCursorName will be called during update operations.

If there are CLongBinarys in the outputColumns, ODBC's DATA_AT_EXEC functionality must be supported. This includes returning SQL_NEED_DATA from SQLExecDirect, SQLParamData and SQLPutData.

SQLRowCount is called after executing to verify that only 1 record was updated by the SQLExecDirect.

ForwardOnly Cursors

Only SQLFetch is required for the Move operations. Note that forwardOnly cursors do not support updates.

Snapshot Cursors

Snapshot functionality requires SQLExtendedFetch support. As noted above, the ODBC cursor library will detect when a driver does not support SQLExtendedFetch, and provide the necessary support itself.

SQLGetInfo, SQL_SCROLL_OPTIONS must support SQL_SO_STATIC.

Dynaset Cursors

Below is the minimum support required to open a dynaset:

SQLGetInfo, SQL_ODBC_VER must return > "01".

SQLGetInfo, SQL_SCROLL_OPTIONS must support SQL_SO_KEYSET_DRIVEN.

SQLGetInfo, SQL_ROW_UPDATES must return "Y".

SQLGetInfo, SQL_POSITIONED_UPDATES must support SQL_PS_POSITIONED_DELETE and SQL_PS_POSITIONED_UPDATE.

In addition, if pessimistic locking is requested, a call to SQLSetPos with irow 1, fRefresh FALSE and fLock SQL_LCK_EXCLUSIVE will be made.


TN043: RFX Routines

This note describes the record field exchange (RFX) architecture. It also describes how you write an RFX_ procedure.

Overview of Record Field Exchange

All recordset field functions are done with C++ code. There are no special resources or magic macros. The heart of the mechanism is a virtual function that must be overridden in every derived recordset class. It is always found in this form:

void CMySet::DoFieldExchange(CFieldExchange* pFX)
{
  //{{AFX_FIELD_MAP(CMySet)
  <recordset exchange field type call>
  <recordset exchange function call>
  //}}AFX_FIELD_MAP
}

The special format AFX comments allow ClassWizard to locate and edit the code within this function. Code that is not compatible with ClassWizard should be placed outside of the special format comments.

In the above example, <recordset_exchange_field_type_call> is in the form:

pFX->SetFieldType(CFieldExchange::outputColumn);

and <recordset_exchange_function_call> is in the form:

RFX_Custom(pFX, "Col2", m_Col2);

Most RFX_ functions have three arguments as shown above, but some (e.g. RFX_Text and RFX_Binary) have additional optional arguments.

More than one RFX_ may be included in each DoDataExchange function.

See 'afxdb.h' for a list of all the recordset field exchange routines provided with MFC.

Recordset field calls are a way of registering memory locations (usually data members) to store field data for a CMySet class.

Notes

Recordset field functions are designed to work only with the CRecordset classes. They are not generally usable by any other MFC classes.

Initial values of data are set in the standard C++ constructor, usually in a block with //{{AFX_FIELD_INIT(CMylSet) and //}}AFX_FIELD_INIT comments.

Each RFX_ function must support various operations, ranging from returning the dirty status of the field to archiving the field in preparation for editing the field.

Each function which calls DoFieldExchange (for instance SetFieldNull, IsFieldDirty), does its own initialization around the call to DoFieldExchange.

How Does It Work?

You do not need to understand the following in order to use record field exchange. However, understanding how this works behind the scenes will help you write your own exchange procedure.

The DoFieldExchange member function is much like the Serialize member function - it is responsible for getting or setting data to/from an external form (in this case columns from the result of an ODBC query) from/to member data in the class. The pFX parameter is the context for doing data exchange and is similar to the CArchive parameter to CObject::Serialize. The pFX (a CFieldExchange object) has an operation indicator, which is similar to, but a generalization of the CArchive direction flag. An RFX function may have to support the following operations:

  • BindParam -- Indicate where ODBC should retrieve parameter data

  • BindFieldToColumn -- Indicate where ODBC must retrieve/deposit outputColumn data

  • Fixup -- Set CString/CByteArray lengths, set NULL status bit

  • MarkForAddNew -- Mark dirty if value has changed since AddNew call

  • MarkForUpdate -- Mark dirty if value has changed since Edit call

  • Name -- Append field names for fields marked dirty

  • NameValue -- Append "<column name>=?" for fields marked dirty

  • Value -- Append "?" followed by separator, like ',' or ' '

  • SetFieldDirty -- Set status bit dirty (i.e. changed) field

  • SetFieldNull -- Set status bit indicating null value for field

  • IsFieldDirty -- Return value of dirty status bit

  • IsFieldNull -- Return value of null status bit

  • IsFieldNullable -- Return TRUE if field can hold NULL values

  • StoreField -- Archive field value

  • LoadField -- Reload archived field value

  • GetFieldInfoValue -- Return general information on a field

  • GetFieldInfoOrdinal -- Return general information on a field

User Extensions

There are several ways to extend the default RFX mechanism. You can

  • Add new data types. For example:
    CBookmark
  • Add new exchange procedures (RFX_???).
    void AFXAPI RFX_Bigint(CFieldExchange* pFX, const char *szName,
    BIGINT& value);
  • Have the DoFieldExchange member function conditionally include additional RFX calls or any other valid C++ statements.
    while (posExtraFields != NULL)
{
    RFX_Text(pFX, m_listName.GetNext(posExtraFields),
        m_listValue.GetNext(posExtraValues));
}

Note Such code cannot be edited by ClassWizard and should be used only outside of the special format comments.

Writing a Custom RFX

To write your own Custom RFX function, it is suggested that you copy an existing RFX function and modify it to your own purposes. Selecting the right RFX to copy can make your job much easier. Some RFX functions have some unique properties that you should take into account when deciding which to copy.

RFX_Long and RFX_Int:

These are the simplest RFX functions. The data value doesn't need any special interpretation, and the data size is fixed.

RFX_Single and RFX_Double:

Like RFX_Long and RFX_Int above, these functions are simple and can make use of the default implementation extensively. They are stored in dbflt.cpp instead of dbrfx.cpp, however, to enable loading the runtime floating point library only when they are explicitly reference.

RFX_Text and RFX_Binary:

These two functions preallocate a static buffer to hold string/binary information, and must register these buffers with ODBC SQLBindCol instead of registering &value. Because of this, these two functions have lots of special-case code.

RFX_Date:

ODBC returns date and time information in their own TIMESTAMP_STRUCT data structure. This function dynamically allocates a TIMESTAMP_STRUCT as a "proxy" for sending and receiving date time data. Various operations must transfer the date and time information between the C++ CTime object and the TIMESTAMP_STRUCT proxy. Needless to say, this complicates this function considerably, but it is a good example of how to use a proxy for data transfer.

RFX_LongBinary:

This is the only class library RFX function that does not use column binding to receive and send data. This function ignores the BindFieldToColumn operation and instead, during the Fixup operation, allocates storage to hold the incoming SQL_LONGVARCHAR or SQL_LONGVARBINARY data, then performs an SQLGetData call to retrieve the value into the allocated storage. When preparing to send data values back to the data source (i.e. NameValue and Value operations), this function uses ODBC's DATA_AT_EXEC functionality. See Technical Note 45 for more information on working with SQL_LONGVARBINARY and SQL_LONGVARCHARs.

When writing your own RFX_ function, you will often be able to use CFieldExchange::Default to implement a given operation. Look at the implementation of Default for the operation in question. If it performs the operation you would be writing in your RFX_ function you can delegate to the CFieldExchange::Default. You can see examples of calling CFieldExchange::Default in dbrfx.cpp

It is important to call IsFieldType at the start of your RFX function, and return immediately if it returns FALSE. This mechanism keeps parameter operations from being performed on outputColumns, and vice versa (like calling BindParam on an outputColumn). In addition, IsFieldType automatically keeps track of the count of outputColumns (m_nFields) and params (m_nParams).


TN044: MFC Support for DBCS

This technical note described the support in MFC for "double-byte character sets" or DBCS.This information as well as information on MFC's support for UNICODE is now available in the Class Library Reference.


TN045: MFC/Database Support for Long Varchar/Varbinary

This note describes how to retrieve and send the ODBC SQL_LONGVARCHAR and SQL_LONGVARBINARY data types using the MFC database classes.

Overview of Long Varchar/Varbinary Support

The ODBC SQL_LONG_VARCHAR and SQL_LONGBINARY data types (referred to here as long data columns) can hold huge amounts of data. There are 3 ways you can handle this data:

  • Bind it to a CString/CByteArray,

  • Bind it to a CLongBinary, or

  • Don't bind it at all and retrieve and send the long data value manually, independent of the database classes. Each of the 3 methods has advantages and disadvantages.

Long data columns are not supported for parameters to a query. They are only supported for outputColumns.

Binding a Long Data Column to a CString/CByteArray

Advantages:

This approach is simple to understand, and you work with familiar classes. The framework provides CFormView support for CString with DDX_Text. You have lots of general string or collection functionality with the CString and CByteArray classes, and you can control the amount of memory allocated locally to hold the data value. The framework maintains an old copy of field data during Edit or AddNew function calls, and the framework can automatically detect changes to the data for you.

Note Since CString is designed for working on character data, and CByteArray for working on binary data, it is recommended that you put the character data (SQL_LONGVARCHAR) into CString, and the binary data (SQL_LONGVARBINARY) into CByteArray.

The RFX functions for CString and CByteArray have an additional argument which lets you override the default size of allocated memory to hold the retrieved value for the data column. Note the nMaxLength argument in the following function declarations:

void AFXAPI RFX_Text(CFieldExchange* pFX, const char *szName,
    CString& value, int nMaxLength = 255, int nColumnType =
    SQL_VARCHAR);

void AFXAPI RFX_Binary(CFieldExchange* pFX, const char *szName,
    CByteArray& value,int nMaxLength = 255);

If you retrieve a long data column into a CString or CByteArray, the maximum returned amount of data is, by default, 255 bytes. Anything beyond this is ignored. In this case, the framework will throw the exception AFX_SQL_ERROR_DATA_TRUNCATED. Fortunately, you can explicitly increase nMaxLength to greater values, up to MAXINT.

ClassWizard will bind a SQL_LONGVARCHAR to a CString, or a SQL_LONGVARBINARY to a CByteArray for you. If you want to allocate more than 255 bytes into which you retrieve your long data column, you can then supply an explicit value for nMaxLength.

When a long data column is bound to a CString or CByteArray, updating the field works just the same as when it is bound to a SQL_VARCHAR or SQL_VARBINARY. During Edit, the data value is cached away and later compared when Update is called to detect changes to the data value and set the Dirty and Null values for the column appropriately.

Binding a Long Data Column to a CLongBinary

If your long data column may contain more MAXINT bytes of data, you should probably consider retrieving it into a CLongBinary.

Advantages:

This retrieves an entire long data column - up to available memory.

Disadvantages:

The data is held in memory. This approach is also prohibitively expensive for very large amounts of data. You must call SetFieldDirty for the bound data member to ensure the field is included in an Update operation.

If you retrieve long data columns into a CLongBinary, the database classes will check the total size of the long data column, then allocate an HGLOBAL memory segment large enough to hold it the entire data value. The database classes then retrieve the entire data value into the allocated HGLOBAL.

If the data source cannot return the expected size of the long data column, the framework will throw the exception AFX_SQL_ERROR_SQL_NO_TOTAL. If the attempt to allocate the HGLOBAL fails, a standard memory exception is thrown.

ClassWizard will bind an SQL_LONGVARCHAR or SQL_LONGVARBINARY to a CLongBinary for you. Select CLongBinary as the Variable Type in the Add Member Variable dialog. ClassWizard will then add an RFX_LongBinary call to your DoFieldExchange call and increment the total number of bound fields.

To update long data column values, first make sure the allocated HGLOBAL is large enough to hold your new data by calling ::GlobalSize on the m_hData member of the CLongBinary. If it's too small, release the HGLOBAL and allocate one the appropriate size. Then set m_dwDataLength to reflect the new size.

Otherwise, if m_dwDataLength is larger than the size of the data you're replacing, you can either free and reallocate the HGLOBAL, or leave it allocated. Make sure to indicate the number of bytes actually used in m_dwDataLength.

How Updating a CLongBinary Works

It is not necessary to understand how updating a CLongBinary works, but it may be useful as an example on how to send long data values to a data source, if you choose this third method, described below.

Note In order for a CLongBinary field to be included in an update, you must explicitly call SetFieldDirty for the field. If you make any change to a field, including setting it Null, you must call SetFieldDirty.

When updating a CLongBinary field, the database classes use ODBC's DATA_AT_EXEC mechanism (see ODBC documentation on SQLSetPos's rgbValue argument). When the framework prepares the insert or update statement, instead of pointing to the HGLOBAL containing the data, the address of the CLongBinary is set as the value of the column instead, and the length indicator set to SQL_DATA_AT_EXEC. Later, when the update statement is sent to the data source, SQLExecDirect will return SQL_NEED_DATA. This alerts the framework that the value of the param for this column is actually the address of a CLongBinary. The framework calls SQLGetData once with a small buffer, expecting the driver to return the actual length of the data. If the driver returns the actual length of the binary large object (the BLOB), MFC reallocates as much space as necessary to fetch the BLOB. If the datasource returns SQL_NO_TOTAL, indicating that it can't determine the size of the BLOB, MFC will create smaller blocks. The default initial size is 64K, and subsequent blocks will be double the size; for example, the second will be 128K, the third is 256K, and so on. The initial size is configurable.

Not Binding: Retrieving/Sending Data Directly from ODBC with SQLGetData

With this method you completely bypass the database classes, and deal with the long data column yourself.

Advantages:

You can cache data to disk if necessary, or decide dynamically how much data to retrieve.

Disadvantages:

You don't get the framework's Edit or AddNew support, and you must write code yourself to perform basic functionality (Delete does work though, since it is not a column level operation).

In this case, the long data column must be in the select list of the recordset, but should not be bound to by the framework. One way to do this is to supply your own SQL statement via GetDefaultSQL or as the lpszSQL argument to CRecordset's Open function, and not bind the extra column with an RFX_ function call. ODBC requires that unbound fields appear to the right of bound fields, so add your unbound column(s) to the end of the select list.

Warning Since your long data column is not bound by the framework, changes to it will not be handled with CRecordset::Update calls. You must create and send the required SQL INSERT and UPDATE statements yourself.


TN046: Commenting Conventions for the MFC Classes

This technical note originally described the conventions used to comment the MFC classes.This information is now covered in MFC: Using the MFC Source Files in Visual C++ Programmer's Guide.


TN047: Relaxing Database Transaction Requirements

This tech note, which discussed the transaction requirements of the MFC ODBC database classes, is now obsolete. Prior to MFC 4.2, the database classes required that cursors be preserved on recordsets after a CommitTrans or Rollback operation. If the ODBC driver and DBMS did not support this level of cursor preservation, then the database classes did not enable transactions.

Beginning with MFC 4.2, the database classes have relaxed the restriction of requiring cursor preservation. Transactions will be enabled if the driver supports them. However, you must now check the effect of a CommitTrans or Rollback operation on open recordsets. See the member functions CDatabase::GetCursorCommitBehavior and CDatabase::GetCursorRollbackBehavior for more information.


TN048: Writing ODBC Setup and Administration Programs for MFC Database Applications

Applications using MFC database classes will need a setup program which installs ODBC components. They may also need an ODBC Administration program which will retrieve information about the available drivers, to specify default drivers and to configure data sources. This note describes the use of the ODBC Installer API to write these programs.

Writing an ODBC Setup Program

An MFC database application requires the ODBC Driver Manager (ODBC.DLL) and ODBC drivers to be able to get to data sources. Many ODBC drivers also require additional network and communication DLLs. Most ODBC drivers ship with a setup program that will install the required ODBC components. Application developers using MFC database classes can:

  • Rely on the driver-specific setup programs for installing ODBC components. This will require no further work on the developer's part—you can just redistribute the driver's setup program.

  • Alternatively, you can write your own setup program, which will install the driver manager and the driver.

The ODBC installer API can be used to write application-specific setup programs. The functions in the installer API are implemented by the ODBC installer DLL—ODBCINST.DLL on 16-bit Windows and ODBCCP32.DLL on Win32. An application can call SQLInstallODBC in the installer DLL, which will install the ODBC driver manager, ODBC drivers, and any required translators. It then records the installed drivers and translators in the ODBCINST.INI file (or the registry, on NT). SQLInstallODBC requires the full path to the ODBC.INF file, which contains the list of drivers to be installed and describes the files that comprise each driver. It also contains similar information about the driver manager and translators. ODBC.INF files are typically supplied by driver developers.

A program can also install individual ODBC components. To install the Driver Manager, a program first calls SQLInstallDriverManager in the installer DLL to get the target directory for the Driver Manager. This is usually the directory in which Windows DLLs reside. The program then uses the information in the [ODBC Driver Manager] section of the ODBC.INF file to copy the Driver Manager and related files from the installation disk to this directory. To install an individual driver, a program first calls SQLInstallDriver in the installer DLL to add the driver specification to the ODBCINST.INI file (or the registry, on NT). SQLInstallDriver returns the driver's target directory—usually the directory in which Windows DLLs reside. The program then uses the information in the driver's section of the ODBC.INF file to copy the driver DLL and related files from the installation disk to this directory.

For more information on ODBC.INF, ODBCINST.INI and using the installer API, see ODBC SDK Programmer's Reference, Chapter 19, Installing ODBC Software.

Writing an ODBC Administrator

An MFC database application can set up and configure ODBC data sources in one of two ways, as follows:

  • Use the ODBC Administrator (available as a program or as a Control Panel item).

  • Create your own program to configure data sources.

A program that configures data sources makes function calls to the installer DLL. The installer DLL calls a setup DLL to configure a data source. There is one setup DLL for each driver; it may be the driver DLL itself, or a separate DLL. The setup DLL prompts the user for information that the driver needs to connect to the data source and the default translator, if supported. It then calls the installer DLL and Windows APIs to record this information in the ODBC.INI file (or registry).

To display a dialog box with which a user can add, modify, and delete data sources, a program calls SQLManageDataSources in the installer DLL. This is the function that is invoked when the installer DLL is called from the Control Panel. To add, modify, or delete a data source, SQLManageDataSources calls ConfigDSN in the setup DLL for the driver associated with that data source. To directly add, modify, or delete data sources, a program calls SQLConfigDataSource in the installer DLL. The program passes the name of the data source and an option that specifies the action to take. SQLConfigDataSource calls ConfigDSN in the setup DLL and passes it the arguments from SQLConfigDataSource.

For more information, see ODBC SDK Programmer's Reference, Chapter 23, Setup DLL Function Reference, and Chapter 24, Installer DLL Function Reference.


TN049: MFC/OLE MBCS to Unicode Translation Layer (MFCANS32)

This note originally described how MFCANS32.DLL provides ANSI interfaces in the primarily Unicode world of 32-bit OLE.This DLL is no longer used by MFC.


TN050: MFC/OLE Common Dialogs (MFCUIx32)

This note originally covered some issues and the future of the OLE common dialogs provided and used by MFC. The OLE common dialogs are now provided as a component built-in to the system (OLEDLG.DLL) and are fully documented in the product documentation.


TN051: Using CTL3D Now and in the Future

This note covers issues specific to the use of CTL3D with MFC as well as what the future holds for CTL3D.

What is CTL3D?

CTL3D hooks into dialog creation and control creation and "subclasses" the standard windows controls to give them a more appealing 3D effect. This technique was first used by Microsoft Excel version 4.0. The Excel team shared the technology with the rest of the industry. Since then, the use of CTL3D has become a de facto standard and is commonly used by professional Windows applications. MFC 3.0 supports the use of this DLL directly.

The Future of CTL3D

There is no getting around it, however, CTL3D and the techniques it uses to accomplish this task are quite tricky (it does some things that you certainly wouldn’t want to do in your own applications). The idea of applications changing the standard look provided by the operating system leads to incompatibilities and user interface inconsistency (since not all applications have the same look). Future Windows operating systems such as Windows 95 will provide a much more pleasing 3D look by default. Eventually, this will make CTL3D unnecessary.

Applications are encouraged to use CTL3D only if the operating system does not provide 3D effects for the built-in controls. MFC 3.0 (and higher) does this by default. CWinApp::Enable3dControls is not operational on systems running Windows 95 (or any version of Windows which reports itself as version 4.0). Your application, even if not MFC-based, is encouraged to do the same thing.

For more information on Windows 95-specific issues, see Technical Note 52: Writing Windows 95 Applications with MFC 3.1.


TN052: Writing Windows 95 Applications with MFC 3.1

This note originally covered issues specific to writing applications for pre-release versions of Windows 95. MFC fully supports writing great Windows 95 applications. The issues and APIs specific to Windows 95 are fully covered in the product documentation.


TN053: Custom DFX Routines for DAO Database Classes

This technical note describes the DAO record field exchange (DFX) mechanism. To help understand what is happening in the DFX routines, the DFX_Text function will be explained in detail as an example. As an additional source of information to this technical note, you can simply examine the code for the other the individual DFX functions.You probably won’t need a custom DFX routine as often as you might need a custom RFX routine (used with ODBC database classes).

This technical note contains:

  • DFX Overview

  • Examples using DAO Record Field Exchange and Dynamic Binding

  • How DFX Works

  • What Your Custom DFX Routine Does

  • Details of DFX_Text

DFX Overview

The DAO record field exchange mechanism (DFX) is used to simplify the procedure of retrieving and updating data when using the CDaoRecordset class. The process is simplified through the use of data members of the CDaoRecordset class. By deriving from CDaoRecordset, you can add data members to the derived class representing each field in a table or query. This “static binding” mechanism is simple, but it may not be the data fetch/update method of choice for all applications. DFX retrieves every bound field each time the current record is changed. If you are developing a performance-sensitive application that does not require fetching every field when currency is changed, “dynamic binding” via CDaoRecordset::GetFieldValue and CDaoRecordset::SetFieldValue may be the data access method of choice.

Note DFX and dynamic binding are not mutually exclusive, so a hybrid use of static and dynamic binding can be used.

Example 1 - Use of DAO Record Field Exchange only

(assumes CDaoRecordset - derived class CMySet already open)

// Add a new record to the customers table
myset.AddNew();
myset.m_strCustID = _T("MSFT");
myset.m_strCustName = _T("Microsoft");
myset.Update();

Example 2 - Use of dynamic binding only

(assumes using CDaoRecordset class, rs, and it is already open)

// Add a new record to the customers table
COleVariant  varFieldValue1 ( _T("MSFT"), VT_BSTRT );
//Note: VT_BSTRT flags string type as ANSI, instead of UNICODE default
COleVariant  varFieldValue2  (_T("Microsoft"), VT_BSTRT );
rs.AddNew();
rs.SetFieldValue(_T("Customer_ID"), varFieldValue1);
rs.SetFieldValue(_T("Customer_Name"), varFieldValue2);
rs.Update();

Example 3 - Use of DAO Record Field Exchange and dynamic binding

(assumes browsing employee data with CDaoRecordset-derived class emp)

// Get the employee's data so that it can be displayed
emp.MoveNext();

// If user wants to see employee's photograph,
// fetch it
COleVariant varPhoto;
if (bSeePicture)
emp.GetFieldValue(_T("photo"), varPhoto);

// Display the data
PopUpEmployeeData(emp.m_strFirstName,
 emp.m_strLastName, varPhoto);

How DFX Works

The DFX mechanism works in a similar fashion to the record field exchange (RFX) mechanism utilized by the MFC ODBC classes. The priciples of DFX and RFX are the same but there are numerous internal differences. The design of the DFX functions was such that virtually all the code is shared by the individual DFX routines. At the highest level DFX only does a few things.

  • DFX constructs the SQL SELECT clause and SQL PARAMETERS clause if necessary.

  • DFX constructs the binding structure used by DAO’s GetRows function (more on this later).

  • DFX manages the data buffer used to detect dirty fields (if double-buffering is being used)

  • DFX manages the NULL and DIRTY status arrays and sets values if necessary on updates.

At the heart of the DFX mechanism is the CDaoRecordset derived class’s DoFieldExchange function. This function dispatches calls to the individual DFX functions of an appropriate operation type. Prior to calling DoFieldExchange the internal MFC functions set the operation type. The following list shows the various operation types and a brief description.

Operation | Description
AddToParameterList | Builds PARAMETERS clause
AddToSelectList | Builds SELECT clause
BindField | Sets up binding structure
BindParam | Sets parameter values
Fixup | Sets NULL status
AllocCache | Allocates cache for dirty check
StoreField | Saves current record to cache
LoadField | Restores cache to member values
FreeCache | Frees cache
SetFieldNull | Sets field status & value to NULL
MarkForAddNew | Marks fields dirty if not PSEUDO NULL
MarkForEdit | Marks fields dirty if don't match cache
SetDirtyField | Sets field values marked as dirty

In the next section, each operation will be explained in more detail for DFX_Text.

The most important feature to understand about the DAO record field exchange process is that it uses the GetRows function of the ICDaoRecordset object. The DAO GetRows function can work in several ways. This technical note will only briefly describe GetRows as it is outside of the scope of this technical note.

DAO GetRows can work in several ways.

  • It can fetch multiple records and multiple fields of data at one time. This allows for faster data access with the complication of dealing with a large data structure and the appropriate offsets to each field and for each record of data in the structure. MFC does not take advantage of this multiple record fetching mechanism.

  • Another way GetRows can work is to allow programmers to specify binding addresses for the retrieved data of each field for one record of data.

  • DAO will also “call back” into the caller for variable length columns in order to allow the caller to allocate memory. This second feature has the benefit of minimizing the number of copies of data as well as allowing direct storage of data into members of a class (the CDaoRecordset derived class). This second mechanism is the method MFC uses to bind to data members in CDaoRecordset derived classes.

What Your Custom DFX Routine Does

It is apparent from this discussion that the most important operation implemented in any DFX function must be the ability to set up the required data structures to successfully call GetRows. There are a number of other operations that a DFX function must support as well, but none as important nor complex as correctly preparing for the GetRows call.

The use of DFX is described in the online documentation. Essentially, there are 2 requirements. First, members must be added to the CDaoRecordset derived class for each bound field and parameter. Following this CDaoRecordset::DoFieldExchange should be overridden. Note that the data type of the member is important. It should match the data from the field in the database or at least be convertable to that type. For example a numeric field in database, such as a long integer, can always be converted to text and bound to a CString member, but a text field in a database may not necessarily be converted to a numeric representation, such as long integer and bound to a long integer member. DAO and the Microsoft Jet database engine are responsible for the conversion (rather than MFC).

Details of DFX_Text

As mentioned previously, probably the best way to explain how DFX works is to simply work through an example. For this purpose going through the internals of DFX_Text should work quite well to help provide at least a basic understanding of DFX.

AddToParameterList

This operation builds the SQL PARAMETERS clause (“Parameters <param name>, <param type> ... ;”) required by Jet. Each parameter is named and typed (as specified in the RFX call). See the function CDaoFieldExchange::AppendParamType function to see the names of the individual types. In the case of DFX_Text, the type used is text.

AddToSelectList

Builds the SQL SELECT clause. This is pretty straight forward as the column name specified by the DFX call is simply appended (“SELECT <column name>, ...”).

BindField

- By far the most complex of the operations. As mentioned previously this is where the DAO binding structure used by GetRows is set up. As you can see from the code in DFX_Text the types of information in the structure include the DAO type used (DAO_CHAR or DAO_WCHAR in the case of DFX_Text). Additionally, the type of binding used is also set up. In an earlier section GetRows was described only briefly, but it was sufficient to explain that the type of binding used by MFC is always direct address binding (DAOBINDING_DIRECT). In addition for variable length column binding (like DFX_Text) callback binding is used so that MFC can control the memory allocation and specify an address of the correct length. What this means is that MFC can always tell DAO “where” to put the data, thus allowing binding directly to member variables. The rest of the binding structure is filled in with things like the address of the memory allocation callback function and the type of column binding (binding by column name).

BindParam

This is a simple operation which calls SetParamValue with the parameter value specified in your parameter member.

Fixup

Fills in the NULL status for each field.

SetFieldNull

This operation only marks each field status as NULL and sets the member variable’s value to PSEUDO_NULL.

SetDirtyField

Calls SetFieldValue for each field marked dirty.

All of the remaining operations only deal with using the data cache. The data cache is an extra buffer of the data in the current record that is used to make certain things simpler. For instance “dirty” fields can be automatically detected. As described in the online documentation it can be turned off completely or at the field level. The implementation of the buffer utilizes a map. This map is used to match up dynamically allocated copies of the data with the address of the “bound” field (or CDaoRecordset derieved data member).

AllocCache

Dynamically allocates the cached field value and adds it to the map.

FreeCache

Deletes the cached field value and removes it from the map.

StoreField

Copies the current field value into the data cache.

LoadField

Copies the cached value into the field member.

MarkForAddNew

Checks if current field value is non-NULL and marks it dirty if necessary.

MarkForEdit

Compares current field value with data cache and marks dirty if necessary.

Tip Model your custom DFX routines on the existing DFX routines for standard data types.


TN054: Calling DAO Directly While Using MFC DAO Classes

When using the MFC DAO database classes, there may be situations where it is necessary to use DAO directly. Usually this will not be the case, but MFC has provided some helper mechanisms to facilitate making direct DAO calls simple when combining the use of the MFC classes with direct DAO calls. Making direct DAO calls to the methods of an MFC-managed DAO object should require only a few lines of code. If you need to create and use DAO objects that are not managed by MFC, you will have to do a little more work by actually calling Release on the object. This technical note explains when you might want to call DAO directly, what the MFC helpers can do to help you, and how to use the DAO OLE interfaces. Finally, this note provides some sample functions showing how to call DAO directly for DAO security features.

When to Make Direct DAO Calls

The most common situations for making direct DAO calls occur when collections need to be refreshed or when you are implementing features not wrapped by MFC. The most significant feature not exposed by MFC is security. If you want to implement security features, you will need to use the DAO User(s) and Group(s) objects directly. Besides security, there are only a few other DAO features not supported by MFC. These include recordset cloning and database replication features as well as a few late additions to DAO.

A Brief Overview of DAO and MFC’s Implementation

MFC’s wrapping of DAO makes using DAO easier by handling many of the details so you do not have to worry about the little things. This includes the initialization of OLE, the creation and management of the DAO objects (especially the collection objects), error checking, and providing a strongly-typed, simpler interface (no VARIANT or BSTR arguments). You can make direct DAO calls and still take advantage of these features. All your code must do is call Release for any objects created by direct DAO calls and not modify any of the interface pointers that MFC may rely on internally. For example, do not modify the m_pDAORecordset member of an open CDaoRecordset object unless you understand all the internal ramifications. You could, however, use the m_pDAORecordset interface to call DAO directly to get the Fields collection. In this case the m_pDAORecordset member would not be modified. You simply have to call Release on the Fields collection object when you are finished with the object.

Description of Helpers to Make DAO Calls Easier

The helpers provided to make calling DAO easier are the same helpers that are used internally in the MFC DAO Database classes. These helpers are used to check the return codes when making a direct DAO call, logging debug output, checking for expected errors, and throwing appropriate exceptions if necessary. There are two underlying helper functions and four macros that map to one of these two helpers. The best explanation would be to simply read the code. See DAO_CHECK, DAO_CHECK_ERROR, DAO_CHECK_MEM, and DAO_TRACE in AFXDAO.H to see the macros, and see AfxDaoCheck and AfxDaoTrace in DAOCORE.CPP.

Using the DAO OLE Interfaces

The OLE interfaces for each object in the DAO object hierarchy are defined in the header file DBDAOINT.H, which is found in the \Program Files\DevStudio\VC\include directory. These interfaces provide methods that allow you to manipulate the entire DAO hierarchy.

For many of the methods in the DAO interfaces, you will need to manipulate a BSTR object (a length-prefixed string used in OLE automation). The BSTR object typically is encapsulated within the VARIANT data type. The MFC class COleVariant itself inherits from the VARIANT data type. Depending on whether you build your project for ANSI or Unicode, the DAO interfaces will return ANSI or Unicode BSTRs. Two macros, V_BSTR and V_BSTRT, are useful for assuring that the DAO interface gets the BSTR of the expected type.

V_BSTR will extract the bstrVal member of a COleVariant. This macro is typically used when you need to pass the contents of a COleVariant to a method of a DAO interface. The following code fragment shows both the declarations and actual use for two methods of the DAO DAOUser interface that take advantage of the V_BSTR macro:

COleVariant varOldName;
COleVariant varNewName( _T("NewUser"), VT_BSTRT );

// Code to assign pUser to a valid value omitted
DAOUser *pUser = NULL;

// These method declarations were taken from DBDAOINT.H
// STDMETHOD(get_Name) (THIS_ BSTR FAR* pbstr) PURE;
// STDMETHOD(put_Name) (THIS_ BSTR bstr) PURE;

DAO_CHECK( pUser->get_Name( &V_BSTR ( &varOldName ) ));
DAO_CHECK( pUser->put_Name( V_BSTR ( &varNewName ) ));

Note that the VT_BSTRT argument specified in the COleVariant constructor above ensures that there will be an ANSI BSTR in the COleVariant if you build an ANSI version of your application and a Uunicode BSTR for a Unicode version of your application. This is what DAO expects.

The other macro, V_BSTRT, will extract either an ANSI or Unicode bstrVal member of COleVariant depending on the type of build (ANSI or Unicode). The following code demonstrates how to extract the BSTR value from a COleVariant into a CString:

COleVariant varName( _T( "MyName" ), VT_BSTRT );
CString str = V_BSTRT( &varName );

The V_BSTRT macro, along with other tricks to crack open other types stored within COleVariant, is demonstrated in the DAOVIEW sample included on the Visual C++ CD. Specifically, this translation is performed in the CCrack::strVARIANT method. This method, where possible, translates the value of a COleVariant into an instance of CString.

Simple Example of a Direct Call to DAO

Situations may arise when it is necessary to refresh the underlying DAO collection objects. Normally this should not be necessary, but it is a simple procedure if it is necessary. An example of when a collection might need to be refreshed is when operating in a multi-user environment with multiple users creating new tabledefs. In this case your tabledefs collection might become stale. To refresh the collection, you simply need to call the Refresh method of the particular collection object and check for errors:

DAO_CHECK( pMyDaoDatabase->
    m_pDAOTableDefs->Refresh( ) );

Note that currently all the DAO collection object interfaces are undocumented implementation details of the MFC DAO database classes.

Using DAO Directly for DAO Security Features

The MFC DAO database classes do not wrap DAO security features. You must call methods of DAO interfaces to use some DAO security features. The following function sets the system database and then changes the user’s password. This function calls three other functions, which are subsequently defined.

void ChangeUserPassword( )
{
   // Specify path to the Microsoft Access
   // system database
   CString strSystemDB =
     _T( "c:\\Program Files\\MSOffice\\access\\System.mdw" );

   // Set system database before MFC initilizes DAO
   // NOTE: An MFC module uses only one instance
   // of a DAO database engine object. If you have
   // called a DAO object in your application prior
   // to calling the function below, you must call
   // AfxDaoTerm to destroy the existing database
   // engine object. Otherwise, the database engine
   // object already in use will be reused, and setting
   // a system datbase will have no effect.
   //
   // If you have used a DAO object prior to calling
   // this function it is important that DAO be
   // terminated with AfxDaoTerm since an MFC
   // module only gets one copy of the database engine
   // and that engine will be reused if it hasn't been
   // terminated. In other words, if you do not call
   // AfxDaoTerm and there is currently a database
   // initialized, setting the system database will
   // have no affect.

   SetSystemDB( strSystemDB );

   // User name and password manually added
   // by using Microsoft Access
   CString strUserName = _T( "NewUser" );
   CString strOldPassword = _T( "Password" );
   CString strNewPassword = _T( "NewPassword" );

   // Set default user so that MFC will be able
   // to log in by default using the user name and
   // password from the system database
   SetDefaultUser( strUserName, strOldPassword );

   // Change the password. You should be able to
   // call this function from anywhere in your
   // MFC application
   ChangePassword( strUserName, strOldPassword,
                   strNewPassword );

   .
   .
   .

}

The next four examples demonstrate how to:

  • Set the system DAO database (.MDW file).

  • Set the default user and password.

  • Change the password of a user.

  • Change the password of an .MDB file.

Setting the System Database

Below is a sample function to set the system database that will be used by an application. This function must be called before any other DAO calls are made.

// Set the system database that the
// DAO database engine will use

void SetSystemDB( CString & strSystemMDB )
{
   COleVariant varSystemDB( strSystemMDB, VT_BSTRT );

   // Initialize DAO for MFC
   AfxDaoInit( );
   DAODBEngine* pDBEngine = AfxDaoGetEngine( );

   ASSERT( pDBEngine != NULL );

   // Call put_SystemDB method to set the
   // system database for DAO engine
   DAO_CHECK( pDBEngine->put_SystemDB( varSystemDB.bstrVal ) );
}

Setting the Default User and Password

To set the default user and password for a system database, use the following function:

void SetDefaultUser(CString & strUserName, CString & strPassword)
{
  COleVariant varUserName( strUserName, VT_BSTRT );
  COleVariant varPassword( strPassword, VT_BSTRT );

  DAODBEngine* pDBEngine = AfxDaoGetEngine( );
  ASSERT( pDBEngine != NULL );

  // Set default user:
  DAO_CHECK( pDBEngine->put_DefaultUser( varUserName.bstrVal ) );

  // Set default password:
  DAO_CHECK( pDBEngine->put_DefaultPassword( varPassword.bstrVal ) );
}

Changing a User’s Password

To change a user’s password, use the following function:

void ChangePassword( CString &strUserName,
                     CString &strOldPassword,
                     CString &strNewPassword )
{
   // Create (open) a workspace
   CDaoWorkspace wsp;
   CString strWspName = _T( "Temp Workspace" );

   wsp.Create( strWspName, strUserName,
               strOldPassword );
   wsp.Append( );

   // Determine how many objects there are
   // in the Users collection
   short nUserCount;
   short nCurrentUser;
   DAOUser *pUser  = NULL;
   DAOUsers *pUsers = NULL;

   // Side-effect is implicit OLE AddRef( )
   // on DAOUser object:
   DAO_CHECK( wsp.m_pDAOWorkspace->get_Users( &pUsers ) );

   // Side-effect is implicit OLE AddRef( )
   // on DAOUsers object
    DAO_CHECK( pUsers->get_Count( &nUserCount ) );

   // Traverse through the list of users
   // and change password for the userid
   // used to create/open the workspace
   for( nCurrentUser = 0; nCurrentUser < nUserCount;
        nCurrentUser++ )
   {
       COleVariant varIndex( nCurrentUser, VT_I2 );
       COleVariant varName;

       // Retrieve information for user nCurrentUser
       DAO_CHECK( pUsers->get_Item( varIndex, &pUser ) );

       // Retrieve name for user nCurrentUser
       DAO_CHECK( pUser->get_Name( &V_BSTR( &varName ) ) );

       CString strTemp = V_BSTRT( &varName );

       // If there is a match, change the password
       if( strTemp == strUserName )
       {
           COleVariant varOldPwd( strOldPassword,
                                  VT_BSTRT );
           COleVariant varNewPwd( strNewPassword,
                                  VT_BSTRT );

           DAO_CHECK( pUser->NewPassword( V_BSTR( &varOldPwd ),
                      V_BSTR( &varNewPwd ) ) );

           TRACE( "\t Password is changed\n" );
       }
   }

   // Clean up: decrement the usage count
   // on the OLE objects
   pUser->Release( );
   pUsers->Release( );

   wsp.Close( );
}

Changing the Password of an .MDB File

To change the password of an .MDB file, use the following function:

void SetDBPassword( LPCTSTR pDB, LPCTSTR pszOldPassword, LPCTSTR pszNewPassword )
{
   CDaoDatabase db;
   CString strConnect( _T( ";pwd=" ) );

   // the database must be opened as exclusive
   // to set a password
   db.Open( pDB, TRUE, FALSE,
            strConnect + pszOldPassword );

   COleVariant NewPassword( pszNewPassword, VT_BSTRT ),
               OldPassword( pszOldPassword, VT_BSTRT );

   DAO_CHECK( db.m_pDAODatabase->NewPassword( V_BSTR( &OldPassword ),
              V_BSTR( &NewPassword ) ) );

   db.Close();
}


TN055: Migrating MFC ODBC Database Class Applications to MFC DAO Classes

Overview

In many situations it may be desirable to migrate applications that use MFC’s ODBC database classes to MFC’s DAO database classes. This technical note will detail most of the differences between the MFC ODBC and DAO classes. With the differences in mind, it should not be overly difficult to migrate applications from the ODBC classes to the MFC classes if desired.

Why Migrate from ODBC to DAO?

There are a number of reasons why you might want to migrate applications from the ODBC Database Classes to the DAO Database Classes, but the decision is not necessarily simple or obvious. One thing to keep in mind is that the Microsoft Jet database engine that is used by DAO can read any ODBC data source for which you have an ODBC driver. It may be more efficient to use the ODBC Database Classes or call ODBC directly yourself, but the Microsoft Jet database engine can read ODBC data.

There are some simple cases that make the ODBC/DAO decision easy. For instance, when you only need access to data in a format that the Microsoft Jet engine can read directly (Access format, FoxPro format, Excel format, and so on) the obvious choice is to use the DAO Database Classes.

More complex cases arise when your data exists on a server or on a variety of different servers. In this case, the decision to use the ODBC Database classes or the DAO Database classes is a difficult one. If you want to do things like heterogeneous joins (join data from servers in multiple formats like SQL Server and Oracle), then the Microsoft Jet database engine will perform the join for you rather than forcing you to do the work necessary if you used the ODBC Database Classes or called ODBC directly. If you are using an ODBC driver that supports driver cursors, your best choice might be the ODBC Database classes.

The choice can be complicated, so you might want to write some sample code to test the performance of various methods given your special needs. This technical note assumes that you have made the decision to migrate from the ODBC Database Classes to the DAO Database classes.

Similarities Between ODBC Database Classes and MFC DAO Database Classes

The original design of the MFC ODBC classes was based on the DAO object model that has been in use in Microsoft Access and Microsoft Visual Basic. This means that there are many common features of the ODBC and DAO MFC classes, which will not all be listed in this section. In general, the programming models are the same.

To highlight a few similarities:

  • Both the ODBC and DAO classes have database objects that manage using the underlying database management system (DBMS).

  • Both have recordset objects representing a set of results returned from that DBMS.

  • The DAO database and recordset objects have members nearly identical to the ODBC classes.

  • With both sets of classes, the code to retrieve data is identical except for some object and member name changes. Changes will be required, but usually the process is a straightforward name change when switching from the ODBC classes to DAO classes.

For example in both models the procedure to retrieve data is to create and open a database object, create and open a recordset object, and navigate (move) though the data performing some operation.

Differences Between ODBC and DAO MFC Classes

The DAO classes include more objects and a richer set of methods, but this section will only detail the differences in similar classes and functionality.

Probably the most obvious differences between the classes are the name changes for similar classes and global functions. The following list shows the name changes of the objects, methods and global functions associated with the database classes:

Class or Function | Equivalent in MFC DAO Classes
CDatabase | CDaoDatabase
CDatabase::ExecuteSQL | CDaoDatabase::Execute
CRecordset | CDaoRecordset
CRecordset::GetDefaultConnect | CDaoRecordset::GetDefaultDBName
CFieldExchange | CDaoFieldExchange
RFX_Bool | DFX_Bool
RFX_Byte | DFX_Byte
RFX_Int | DFX_Short
RFX_Long | DFX_Long
 | DFX_Currency
RFX_Single | DFX_Single
RFX_Double | DFX_Double
RFX_Date * | DFX_Date (COleDateTime-based)
RFX_Text | DFX_Text
RFX_Binary | DFX_Binary
RFX_LongBinary | DFX_LongBinary

* The RFX_Date function is based on CTime and TIMESTAMP_STRUCT.

The major changes to functionality which may affect your application and require more than simple name changes are listed below.

  1. The constants and macros used to specify things like recordset open type and recordset open options have been changed.

    With the ODBC classes MFC needed to define these options via macros or enumerated types.

    With the DAO classes, DAO provides the definition of these options in a header file (DBDAOINT.H). Thus the recordset type is an enumerated member of CRecordset, but with DAO it is a constant instead. For example you would use snapshot when specifying the type of CRecordset in ODBC but DB_OPEN_SNAPSHOT when specifying the type of CDaoRecordset.

  2. The default recordset type for CRecordset is snapshot while the default recordset type for CDaoRecordset is dynaset (see the Note below for an additional issue about ODBC class snapshots).

  3. The ODBC CRecordset class has an option to create a forward-only recordset type. In the CDaoRecordset class, forward-only is not a recordset type, but rather a property (or option) of certain types of recordsets.

  4. An append-only recordset when opening a CRecordset object meant that the recordset’s data could be read and appended. With CDaoRecordset object, the append-only option means literally that the recordset’s data can only be appended (and not read).

  5. The ODBC classes’ transaction member functions are members of CDatabase and act at the database level. In the DAO classes, the transaction member functions are members of a higher level class (CDaoWorkspace) and thus may impact multiple CDaoDatabase objects sharing the same workspace (transaction space).

  6. The exception class has been changed. CDBExceptions are thrown in the ODBC classes and CDaoExceptions in the DAO classes.

  7. RFX_Date uses CTime and TIMESTAMP_STRUCT objects while DFX_Date uses COleDateTime. The COleDateTime is nearly identical to CTime, but is based on a 8-byte OLE DATE rather than a 4-byte time_t so it can hold a much bigger range of data.

Note DAO (CDaoRecordset) snapshots are read-only while ODBC (CRecordset) snapshots may be updatable depending on the driver and use of the ODBC cursor library. If you are using the cursor library, CRecordset snapshots are updatable. If you are using any of the Microsoft drivers from Desktop Driver Pack 3.0 without the ODBC cursor library, the CRecordset snapshots are read-only. If you are using another driver, check the driver’s documentation to see if snapshots (STATIC_CURSORS) are read-only.


TN056: Installation of MFC Components

This note describes the requirements for installation of any component that uses the MFC DLL(s), including CTL3D32.DLL. The components related to ODBC and DAO require special considerations and are not discussed here. Please refer to the documentation for those components for further information.

DLLs and Version Marks

The MFC DLL(s) are what is called a shared DLL. For the Win32 version of MFC, there is potentially only one MFC DLL that you need to install with your application: MFC4x.DLL or a later version. This single DLL contains all code necessary for core MFC, MFC/OLE, MFC/Database, and the MFC/Network classes (previous versions had each of these components broken out into separate DLLs).

For the Macintosh version of MFC, these are still separate DLLs: MFC4x.DLL, MFCO4x.DLL, and MFCD4x.DLL (or later versions). Even if your application does not use all of the MFC DLLs (perhaps you do not use the OLE or Database functionality of MFC, for example), you must install all of the MFC DLLs as a set. Anything else would result in mismatched components. This is important because there is no guarantee that a later version of MFC4x.DLL will work with version 4.x of MFCO4x.DLL.

Because these DLLs are shared components, they reside in the Windows “system” directory. That is, they should be installed into the directory indicated by the return value from GetSystemDirectory. Installing in this directory, like other shared system components, must be done carefully to avoid overwriting newer versions of the DLL that other applications previously installed may be relying upon. To retrieve the version information for the installed files, use the GetFileVersionInfo APIs provided by the Windows version API. You should only install a new DLL if its version information, give by the dwFileVersionMS and dwFileVersionLS fields of the VS_FIXEDFILEINFO structure are larger than the same version information of the already installed DLL.

Finally, if your application uses CTL3D32.DLL (if it calls CWinApp::Enable3dControls), you will need to install the correct version of CTL3D32.DLL into the system directory, again being careful to check that a newer version does not already exist. In addition, the version of CTL3D32.DLL that you install is different depending on the platform you are installing on. For Windows version 4.0 and greater, CTL3D32.DLL is not used under any circumstances, so it should not be installed (this includes Windows 95 and Windows NT 4.0). For Win32s, \WIN32S\REDIST\CTL3D32.DLL should be installed into the system directory. For Windows NT 3.xx, \MSDEV\CTL3D32.DLL should be installed into the system directory. Each of these DLLs is specific to the target platform, even though they have the same name. The Win32s version will refuse to run on Windows NT; the Windows NT version will refuse to run on Win32s.

Localization Considerations

If your application has chosen to localize its use of the MFC resources by installing MFC4xLOC.DLL or a later version, you will need to follow the instructions in this section. Like other shared DLLs, MFC4xLOC.DLL should only be installed if its version is newer than the version which is already installed. As a result installing this DLL is very similar to installing the other MFC DLL(s). There are a couple of exceptions.

First, you should never install MFC4xLOC.DLL on an English system. English resources are built into MFC4x.DLL and it is faster to load them from that DLL instead of searching (and loading) MFC4xLOC.DLL first.

Second, there are multiple versions of MFC4xLOC.DLL – one for each locale. Their names are based on the locale. For example MFC4xDEU.DLL is the German version of MFC4xLOC.DLL – it contains version information that identifies it as German locale; MFC4xESP.DLL, similarly, is the Spanish version of the DLL. If you install it, you must insure that 1) the locale for which it is intended matches the locale of the Windows system that is installed, and 2) that the locale is not different from the locale of the MFC4xLOC.DLL already installed (if it is installed). If these two conditions cannot be satisfied, then the DLL should not be overwritten. If the version mark on the existing MFC4xLOC.DLL is equal to or greater than the version mark in your distribution, then you’re product will work once installed. It may have mixed resources (some of one language, some of another), but it will work. If the version mark on the existing DLL is less than your distribution and the locale is mismatched, your product may not work once installed. You should warn the user of this mismatch and back out of your installation process. The user will have to resolve the conflict between this DLL and your product before continuing.

Important Obviously, this can add a lot of complexity to your installation as well as hassles for your end user if they use and install a mix of different localized applications (some applications localized to one language, and some to another). Because of this difficulty, it is highly recommended that you do not ship any version of MFC4xLOC.DLL. Instead, include the appropriate MFC implementation resources in your module itself and avoid this whole issue. See Technical Note 57 for more information on this subject.


TN057: Localization of MFC Components

This note describes some of the designs and procedures you can use to localize your component, be it an application or an OLE control, or a DLL which uses MFC.

Overview

There are really two issues to resolve when localizing a component which uses MFC. First of all, you must localize your own resources – strings, dialogs, and other resources that are specific to your component. Most components built using MFC also include and use a number of resources that are defined by MFC. You must provide localized MFC resources as well. Fortunately, several languages are already provided by MFC itself.

In addition, your component should be prepared to run in its target environment (European, or DBCS enabled environment). For the most part, this depends on your application treating characters with the high bit set correctly and handling strings with double byte characters. MFC is enabled, by default, for both of these environments, such that it is possible to have a single “world wide” binary that is used on all platforms with just different resources plugged in at setup time.

Localizing your Component’s Resources

Localizing your application or DLL should involve simply replacing the resources with resources that match the target language. For your own resources, this is relatively simple: edit the resources in the resource editor and build your application. If your code is written properly there will be no strings or text that you wish to localize hard-coded into your C++ source code – all localization can be done by simply modifying resources. In fact, you can implement your component such that all providing a localized version does not even involve a build of the original code. This is more complex, but is well worth it and is the mechanism chosen for MFC itself. It is also possible to localize an application by loading the EXE or DLL file into the resource editor and editing the resources directly. While this is possible, it is requires re-application of those changes each time you build a new version of your application.

One way to avoid that is to locate all resources in a separate DLL, sometimes called a satellite DLL. This DLL is then loaded dynamically at runtime and the resources are loaded from that DLL instead of from the main module with all your code. MFC directly supports this approach. Consider an application called MYAPP.EXE; it could have all of its resources located in a DLL called MYRES.DLL. In the application’s InitInstance it would perform the following to load that DLL and cause MFC to load resources from that location:

CMyApp::InitInstance()
{
// one of the first things in the init code
HINSTANCE hInst = LoadLibrary(“myres.dll”);
if (hInst != NULL)
AfxSetResourceHandle(hInst);

// other initialization code would follow
.
.
.
}

From then on, MFC will load resources from that DLL instead of from myapp.exe. All resources, however, must be present in that DLL – MFC will not search the application’s instance in search of a given resource. This technique applies equally well to regular DLLs as well as OLE Controls. Your setup program would copy the appropriate version of MYRES.DLL depending upon which resource locale the user would like.

It is relatively easy to create a resource only DLL. You create a DLL project, add your .RC file to it, and add the necessary resources. If you have an existing project that does not use this technique, you can copy the resources from that project. After adding the resource file to the project you are almost ready to build the project. The only thing you must do is set the linker options to include /NOENTRY. This tells the linker that the DLL has no entry point – since it has no code, it has no entry point.

Note The resource editor in Visual C++ 4.0 and later supports multiple languages per .RC file. This can make it very easy to manage your localization in a single project. The resources for each language is controlled by preprocessor directives generated by the resource editor.

Using the Provided MFC Localized Resources

Any MFC application that you build re-uses two things from MFC: code and resources. That is, MFC has various error messages, built-in dialogs, and other resources that are used by the MFC classes. In order to completely localize your application, you need to localize not only your application’s resources, but also the resources which come directly from MFC. MFC provides a number of different language resource files automatically, so that if the language you are targeting is one of the languages MFC already supports, you just need to make sure you use those localized resources.

As of this writing MFC supports: Chinese, German, Spanish, French, Italian, Japanese, and Korean. The files which contain these localized versions are in the MFC\INCLUDE\L.* (the ‘L’ stands for localized) directories. The German files are in MFC\INCLUDE\L.DEU, for example. In order to cause your application to use these RC files instead of the files located in MFC\INCLUDE, simply add a /IC:\PROGRAM FILES\DEVSTUDIO\VC\MFC\INCLUDE\L.DEU to your RC command line (this is just an example – you would need to substitute your locale of choice as well as the directory into which you installed Visual C++).

The above instructions will work if your application links statically with MFC. Most applications link dynamically (because that is the AppWizard default). In this scenario, not only the code is dynamically linked – so are the resources. As a result, you can localize your resources in your application, but the MFC implementation resources will still be loaded from the MFC4x.DLL (or a later version) or from MFC4xLOC.DLL if it exists. You can approach this from two different angles.

Feature Only in Professional and Enterprise Editions Static linking to MFC is supported only in Visual C++ Professional and Enterprise Editions. For more information, see Visual C++ Editions.

The more complex approach is to ship one of the localized MFC4xLOC.DLLs (such as MFC4xDEU, for German, MFC4xESP.DLL for Spanish, etc.), or a later version, and install the appropriate MFC4xLOC.DLL into the system directory when the user installs your application. This can be very complex for both the developer and the end user and as such is not recommended. See Technical Note 56 for more information on this technique and its caveats.

The simplest and safest approach is to include the localized MFC resources in your application or DLL itself (or its satellite DLL if you are using one). This avoids the problems of installing MFC4xLOC.DLL properly. To do so, you follow the same instructions for the static case given above (setting the RC command line properly to point to the localized resources), except that you must also remove the /D_AFXDLL define that was added by AppWizard. When /D_AFXDLL is defined, AFXRES.H (and the other MFC RC files) don’t actually define any resources (because they will be pulled from the MFC DLLs instead).


TN058: MFC Module State Implementation

This technical note describes the implementation of MFC “module state” constructs. An understanding of the module state implementation is critical for using the MFC shared DLLs from a DLL (or OLE in-process server).

Before reading this note, please refer to "Managing the State Data of MFC Modules" in Creating New Documents, Windows, and Views in the Visual C++ Programmer's Guide. This article contains important usage information and overview information on this subject.

Overview

There are three kinds of MFC state information: Module State, Process State, and Thread State. Sometimes these state types can be combined. For example, MFC’s handle maps are both module local and thread local. This allows two different modules to have different maps in each of their threads.

Process State and Thread State are similar. These data items are things that have traditionally been global variables, but have need to be specific to a given process or thread for proper Win32s support or for proper multithreading support. Which category a given data item fits in depends on that item and its desired semantics with regard to process and thread boundaries.

Module State is unique in that it can contain either truly global state or state that is process local or thread local. Also it can be switched quickly.

Module State Switching

Each thread contains a pointer to the “current” or “active” module state (not surprisingly, the pointer is part of MFC’s thread local state). This pointer is changed when the thread of execution passes a module boundary, such as an application calling into an OLE Control or DLL, or an OLE Control calling back into an application.

The current module state is switched by calling AfxSetModuleState. For the most part, you will never deal directly with the API. MFC, in many cases, will call it for you (at WinMain, OLE entry-points, AfxWndProc, etc.). This is done in any component you write by statically linking in a special WndProc, and a special WinMain (or DllMain) that knows which module state should be current. You can see this code by taking a look at DLLMODUL.CPP or APPMODUL.CPP in the MFC\SRC directory.

It is rare that you want to set the module state and then not set it back. Most of the time you want to “push” your own module state as the current one and then, after you are done, “pop” the original context back. This is done by the macro AFX_MANAGE_STATE and the special class AFX_MAINTAIN_STATE.

CCmdTarget has special features for supporting module state switching. In particular, a CCmdTarget is the root class used for OLE automation and OLE COM entry points. Like any other entry point exposed to the system, these entry points must set the correct module state. How does a given CCmdTarget know what the “correct” module state should be? The answer is that it “remembers” what the “current” module state is when it is constructed, such that it can set the current module state to that “remembered” value when it is later called. As a result, the module state that a given CCmdTarget object is associated with is the module state that was current when the object was constructed. Let’s take a simple example of loading an INPROC server, creating an object, and calling its methods.

  1. The DLL is loaded by OLE using LoadLibrary.

  2. RawDllMain is called first. It sets the module state to the known static module state for the DLL. For this reason RawDllMain is statically linked to the DLL.

  3. The constructor for the class factory associated with our object is called. COleObjectFactory is derived from CCmdTarget and as a result, it remembers in which module state it was instantiated. This is important — when the class factory is asked to create objects, it knows now what module state to make current.

  4. DllGetClassObject is called to obtain the class factory. MFC searches the class factory list associated with this module and returns it.

  5. COleObjectFactory::XClassFactory2::CreateInstance is called. Before creating the object and returning it, this function sets the module state to the module state that was current in step 3 (the one that was current when the COleObjectFactory was instantiated). This is done inside of METHOD_PROLOGUE.

  6. When the object is created, it too is a CCmdTarget derivative and in the same way COleObjectFactory remembered which module state was active, so does this new object. Now the object knows which module state to switch to whenever it is called.

  7. The client calls a function on the OLE COM object it received from its CoCreateInstance call. When the object is called it uses METHOD_PROLOGUE to switch the module state just like COleObjectFactory does.

As you can see, the module state is propagated from object to object as they are created. It is important to have the module state set appropriately. If it is not set, your DLL or COM object may interact poorly with an MFC application that is calling it, or may be unable to find its own resources, or may fail in other miserable ways.

Note that certain kinds of DLLs, specifically “MFC Extension” DLLs don’t switch the module state in their RawDllMain (actually, they usually don’t even have a RawDllMain). This is because they are intended to behave “as if” they were actually present in the application that uses them. They are very much a part of the application that is running and it is their intention to modify that application’s global state.

OLE Controls and other DLLs are very different. They do not want to modify the calling application’s state; the application that is calling them may not even be an MFC application and so there may be no state to modify. This is the reason that module state switching was invented.

For exported functions from a DLL, such as one that launches a dialog box in your DLL, you need to add the following code to the beginning of the function:

AFX_MANAGE_STATE(AfxGetStaticModuleState( ))

This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope.

Problems with resources in DLLs will occur if the AFX_MODULE_STATE macro is not used. By default, MFC uses the resource handle of the main application to load the resource template. This template is actually stored in the DLL. The root cause is that MFC's module state information has not been switched by the AFX_MODULE_STATE macro. The resource handle is recovered from MFC's module state. Not switching the module state causes the wrong resource handle to be used.

AFX_MODULE_STATE does not need to be put in every function in the DLL. For example, InitInstance can be called by the MFC code in the application without AFX_MODULE_STATE because MFC automatically shifts the module state before InitInstance and then switches it back after InitInstance returns. The same is true for all message map handlers. Regular DLLs actually have a special master window procedure that automatically switches the module state before routing any message.

Process Local Data

Process local data would not be of such great concern had it not been for the difficulty of the Win32s DLL model. In Win32s all DLLs share their global data, even when loaded by multiple applications. This is totally different from the “real” Win32 DLL data model, where each DLL gets a separate copy of its data space in each process that attaches to the DLL. To add to the complexity, data allocated on the heap in a Win32s DLL is in fact process specific (at least as far as ownership goes). Consider the following data and code:

static CString strGlobal; // at file scope

__declspec(dllexport)
void SetGlobalString(LPCTSTR lpsz)
{
   strGlobal = lpsz;
}

__declspec(dllexport)
void GetGlobalString(LPCTSTR lpsz, int cb)
{
   lstrcpyn(lpsz, strGlobal, cb);
}

Consider what happens if the above code is in located in a DLL and that DLL is loaded by two processes A and B (it could, in fact, be two instances of the same application). A calls SetGlobalString("Hello from A"). As a result, memory is allocated for the CString data in the context of process A. Keep in mind that the CString itself is global and is visible to both A and B. Now B calls GetGlobalString(sz, sizeof(sz)). B will be able to see the data that A set. This is because Win32s offers no protection between processes like Win32 does. So that is the first problem; in many cases it is not desirable to have one application affect global data that is considered to be owned by a different application.

But wait — there are more problems. Let’s say that A now exits. When A exits, the memory used by the 'strGlobal' string is made available for the system — that is, all memory allocated by process A is freed automatically by the operating system. It is not freed because the CString destructor is being called; it hasn’t been called yet. It is freed simply because the application which allocated it has left the scene. Now if B called GetGlobalString(sz, sizeof(sz)), it may not get valid data. Some other application may have used that memory for something else.

Clearly there is a problem here. MFC 3.x used a technique called thread-local storage (TLS). MFC 3.x would allocate a TLS index that under Win32s really acts as a process-local storage index, even though it isn’t called that and then would reference all data based on that TLS index. This is similar to the TLS index that was used to store thread-local data on Win32 (see below for more information on that subject). This caused every MFC DLL to utilize at least two TLS indices per process. When you account for loading many OLE Control DLLs (OCXs), you quickly run out of TLS indices (there are only 64 available). In addition, MFC had to place all this data in one place, in a single structure. It was not very extensible and was not ideal with regard to its use of TLS indices.

MFC 4.x addresses this with a set of class templates you can “wrap” around the data that should be process local. For example, the problem mentioned above could be fixed by writing:

struct CMyGlobalData : public CNoTrackObject
{
   CString strGlobal;
};
CProcessLocal<CMyGlobalData> globalData;

__declspec(dllexport)
void SetGlobalString(LPCTSTR lpsz)
{
   globalData->strGlobal = lpsz;
}

__declspec(dllexport)
void GetGlobalString(LPCTSTR lpsz, int cb)
{
   lstrcpyn(lpsz, globalData->strGlobal, cb);
}

MFC implements this in two steps. First, there is a layer on top of the Win32 Tls* APIs (TlsAlloc, TlsSetValue, TlsGetValue, etc.) which use only two TLS indexes per process, no matter how many DLLs you have. Second, the CProcessLocal template is provided to access this data. It overrides operator-> which is what allows the intuitive syntax you see above. All objects that are wrapped by CProcessLocal must be derived from CNoTrackObject. CNoTrackObject provides a lower-level allocator (LocalAlloc/LocalFree) and a virtual destructor such that MFC can automatically destroy the process local objects when the process is terminated. Such objects can have a custom destructor if additional cleanup is required. The above example doesn’t require one, since the compiler will generate a default destructor to destroy the embedded CString object.

There are other interesting advantages to this approach. Not only are all CProcessLocal objects destroyed automatically, they are not constructed until they are needed. CProcessLocal::operator-> will instantiate the associated object the first time it is called, and no sooner. In the example above, that means that the 'strGlobal' string will not be constructed until the first time SetGlobalString or GetGlobalString is called. In some instances, this can help decrease DLL startup time.

Thread Local Data

Similar to process local data, thread local data is used when the data must be local to a given thread. That is, you need a separate instance of the data for each thread that accesses that data. This can many times be used in lieu of extensive synchronization mechanisms. If the data does not need to be shared by multiple threads, such mechanisms can be expensive and unnecessary. Suppose we had a CString object (much like the sample above). We can make it thread local by wrapping it with a CThreadLocal template:

struct CMyThreadData : public CNoTrackObject
{
   CString strThread;
};
CThreadLocal<CMyThreadData> threadData;

void MakeRandomString()
{
   // a kind of card shuffle (not a great one)
   CString& str = threadData->strThread;
   str.Empty();
   while (str.GetLength() != 52)
   {
      TCHAR ch = rand() % 52 + 1;
      if (str.Find(ch) < 0)
         str += ch; // not found, add it
   }
}

If MakeRandomString was called from two different threads, each would “shuffle” the string in different ways without interfering with the other. This is because there is actually a strThread instance per thread instead of just one global instance.

Note how a reference is used to capture the CString address once instead of once per loop iteration. The loop code could have been written with threadData->strThread everywhere 'str' is used, but the code would be much slower in execution. It is best to cache a reference to the data when such references occur in loops.

The CThreadLocal class template uses the same mechanisms that CProcessLocal does and the same implementation techniques.


TN059: Using MFC MBCS/Unicode Conversion Macros

This note describes how to use the macros for MBCS/Unicode conversion which are defined in AFXPRIV.H. These macros are most useful if your application deals directly with the OLE API or for some reason, often needs to convert between Unicode and MBCS.

Overview

In MFC 3.x, a special DLL was used (MFCANS32.DLL) to automatically convert between Unicode and MBCS when OLE interfaces were called. This DLL was an almost transparent layer that allowed OLE applications to be written as if the OLE APIs and interfaces were MBCS, even though they are always Unicode (except on the Macintosh). While this layer was convenient and allowed applications to be quickly ported from Win16 to Win32 (MFC, Microsoft Word, Microsoft Excel, and VBA, are just some of the Microsoft applications that used this technology), it also had a sometimes significant performance hit. For this reason, MFC 4.x does not use this DLL and instead talks directly to the Unicode OLE interfaces. To do this, MFC needs to convert to Unicode to MBCS when making a call to an OLE interface, and often needs to convert to MBCS from Unicode when implementing an OLE interface. In order to handle this efficiently and easily, a number of macros were created to make this conversion easier.

One of the biggest hurdles of creating such a set of macros is memory allocation. Because the strings cannot be converted in place, new memory to hold the converted results must be allocated. This could have been done with code similar to the following:

// we want to convert an MBCS string in lpszA
int nLen = MultiByteToWideChar(CP_ACP, 0,lpszA, -1, NULL, NULL);
LPWSTR lpszW = new WCHAR[nLen];
MultiByteToWideChar(CP_ACP, 0,
lpszA, -1, lpszW, nLen);
// use it to call OLE here
pI->SomeFunctionThatNeedsUnicode(lpszW);
// free the string
delete[] lpszW;

This approach as a number of problems. The main problem is that it is a lot of code to write, test, and debug. Something that was a simple function call, is now much more complex. In addition, there is a significant runtime overhead in doing so. Memory has to be allocated on the heap and freed each time a conversion is done. Finally, the code above would need to have appropriate #ifdefs added for Unicode and Macintosh builds (which don’t require this conversion to take place).

The solution we came up with is to create some macros which 1) mask the difference between the various platforms, and 2) use an efficient memory allocation scheme, and 3) are easy to insert into the existing source code. Here is an example of one of the definitions:

#define A2W(lpa) (\
    ((LPCSTR)lpa == NULL) ? NULL : (\
           _convert = (strlen(lpa)+1),\
        AfxA2WHelper((LPWSTR) alloca(_convert*2),
lpa, _convert)\
    )\
)

Using this macro instead of the code above and things are much simpler:

// use it to call OLE here
USES_CONVERSION;
pI->SomeFunctionThatNeedsUnicode(T2OLE(lpszA));

There are extra calls where conversion is necessary, but using the macros is simple and effective.

The implementation of each macro uses the _alloca() function to allocate memory from the stack instead of the heap. Allocating memory from the stack is much faster than allocating memory on the heap, and the memory is automatically freed when the function is exited. In addition, the macros avoid calling MultiByteToWideChar (or WideCharToMultiByte) more than one time. This is done by allocating a little bit more memory than is necessary. We know that an MBC will convert into at most one WCHAR and that for each WCHAR we will have a maximum of two MBC bytes. By allocating a little more than necessary, but always enough to handle the conversion the second call second call to the conversion function is avoided. The call to the helper function AfxA2Whelper reduces the number of argument pushes that must be done in order to perform the conversion (this results in smaller code, than if it called MultiByteToWideChar directly).

In order to for the macros to have space to store the a temporary length, it is necessary to declare a local variable called _convert that does this in each function that uses the conversion macros. This is done by invoking the USES_CONVERSION macro as seen above in the example.

There are both generic conversion macros and OLE specific macros. These two different macro sets are discussed below. All of the macros reside in AFXPRIV.H.

Generic Conversion Macros

The generic conversion macros form the underlying mechanism. The macro example and implementation shown in the previous section, A2W, is one such “generic” macro. It has no relation to OLE specifically. The set of generic macros is listed below:

A2CW        (LPCSTR) -> (LPCWSTR)
A2W        (LPCSTR) -> (LPWSTR)
W2CA        (LPCWSTR) -> (LPCSTR)
W2A        (LPCWSTR) -> (LPSTR)

Besides doing text conversions, there are also macros and helper functions for converting TEXTMETRIC, DEVMODE, BSTR, and OLE allocated strings. These macros are beyond the scope of this discussion – refer to AFXPRIV.H for more information on those macros.

OLE Conversion Macros

The OLE conversion macros are designed specifically for handling functions which expect OLESTR characters. If you examine the OLE headers you will see many references to LPCOLESTR and OLECHAR. These types are used to refer to the type of characters used in OLE interfaces in a way that is not specific to the platform. OLECHAR maps to char in Win16 and Macintosh platforms and WCHAR in Win32.

In order to keep the number of #ifdef directives in the MFC code to a minimum we have a similar macro for each conversion that where OLE strings are involved. The following macros are the most commonly used:

T2COLE    (LPCTSTR) -> (LPCOLESTR)
T2OLE    (LPCTSTR) -> (LPOLESTR)
OLE2CT    (LPCOLESTR) -> (LPCTSTR)
OLE2T    (LPCOLESTR) -> (LPCSTR)

Again there are similar macros for doing TEXTMETRIC, DEVMODE, BSTR, and OLE allocated strings. Refer to AFXPRIV.H for more information.

Other Considerations

Don’t use the macros in a tight loop. For example, you do NOT want to write the following kind of code:

void BadIterateCode(LPCTSTR lpsz)
{
USES_CONVERSION;
for (int ii = 0; ii < 10000; ii++)
pI->SomeMethod(ii, T2COLE(lpsz));
}

The code above could result in allocating megabytes of memory on the stack depending on what the contents of the string lpsz is! It also takes time to convert the string for each iteration of the loop. Instead move such constant conversions out of the loop:

void MuchBetterIterateCode(LPCTSTR lpsz)
{
USES_CONVERSION;
LPCOLESTR lpszT = T2COLE(lpsz);
for (int ii = 0; ii < 10000; ii++)
pI->SomeMethod(ii, lpszT);
}

If the string is not constant, then encapsulate the method call into a function. This will allow the conversion buffer to be freed each time. For example:

void CallSomeMethod(int ii, LPCTSTR lpsz)
{
USES_CONVERSION;
pI->SomeMethod(ii, T2COLE(lpsz));
}

void MuchBetterIterateCode2(LPCTSTR* lpszArray)
{
for (int ii = 0; ii < 10000; ii++)
CallSomeMethod(ii, lpszArray[ii]);
}

Never return the result of one of the macros, unless the return value implies making a copy of the data before the return. For example, this code is bad:

LPTSTR BadConvert(ISomeInterface* pI)
{
USES_CONVERSION;
LPOLESTR lpsz = NULL;
pI->GetFileName(&lpsz);
LPTSTR lpszT = OLE2T(lpsz);
CoMemFree(lpsz);
return lpszT; // bad! returning alloca memory
}

The code above could be fixed by changing the return value to something which copies the value:

CString BetterConvert(ISomeInterface* pI)
{
USES_CONVERSION;
LPOLESTR lpsz = NULL;
pI->GetFileName(&lpsz);
LPTSTR lpszT = OLE2T(lpsz);
CoMemFree(lpsz);
return lpszT; // CString makes copy
}

The macros are easy to use and easy to insert into your code, but as you can tell from the caveats above, you need to be careful when using them.


TN060: The New Windows Common Controls

Technical Note 60, describing the new Windows common controls and how to use them, has been incorporated into the Visual C++ Programmer's Guide. See Control Topics.


TN061: ON_NOTIFY and WM_NOTIFY Messages

This technical note provides background information on the new WM_NOTIFY message and describes the recommended (and most common) way of handling WM_NOTIFY messages in your MFC application.

Notification Messages in Windows 3.x

In Windows 3.x, controls notify their parents of events such as mouse clicks, changes in content and selection, and control background painting by sending a message to the parent. Simple notifications are sent as special WM_COMMAND messages, with the notification code (such as BN_CLICKED) and control ID packed into wParam and the control’s handle in lParam. Note that since wParam and lParam are full, there is no way to pass any additional data — these messages can be only simple notification. For instance, in the BN_CLICKED notification, there’s no way to send information about the location of the mouse cursor when the button was clicked.

When controls in Windows 3.x need to send a notification message that includes additional data, they use a variety of special-purpose messages, including WM_CTLCOLOR, WM_VSCROLL, WM_HSCROLL, WM_DRAWITEM, WM_MEASUREITEM, WM_COMPAREITEM, WM_DELETEITEM, WM_CHARTOITEM, WM_VKEYTOITEM, and so on. These messages can be reflected back to the control that sent them. For more information, see TN062: Message Reflection for Windows Controls.

Notification Messages in Win32

For controls that existed in Windows 3.1, the Win32 API uses most of the notification messages that were used in Windows 3.x. However, Win32 also adds a number of sophisticated, complex controls to those supported in Windows 3.x. Frequently, these controls need to send additional data with their notification messages. Rather than adding a new WM_* message for each new notification that needs additional data, the designers of the Win32 API chose to add just one message, WM_NOTIFY, which can pass any amount of additional data in a standardized fashion.

WM_NOTIFY messages contain the ID of the control sending the message in wParam and a pointer to a structure in lParam. This structure is either an NMHDR structure or some larger structure that has an NMHDR structure as its first member. Note that since the NMHDR member is first, a pointer to this structure can be used as either a pointer to an NMHDR or as a pointer to the larger structure depending on how you cast it.

In most cases, the pointer will point to a larger structure and you’ll need to cast it when you use it. In only a few notifications, such as the common notifications (whose names start with NM_) and the tool tip control’s TTN_SHOW and TTN_POP notifications, is an NMHDR structure actually used.

The NMHDR structure or initial member contains the handle and ID of the control sending the message and the notification code (such as TTN_SHOW). The format of the NMHDR structure is shown below:

typedef struct tagNMHDR {
    HWND hwndFrom;
    UINT idFrom;
    UINT code;
} NMHDR;

For a TTN_SHOW message, the code member would be set to TTN_SHOW.

Most notifications pass a pointer to a larger structure that contains an NMHDR structure as its first member. For instance, consider the structure used by the list view control’s LVN_KEYDOWN notification message, which is sent when a key is pressed in a list view control. The pointer points to an LV_KEYDOWN structure, which is defined as shown below:

typedef struct tagLV_KEYDOWN {
    NMHDR hdr;
    WORD wVKey;
    UINT flags;
} LV_KEYDOWN;

Note that since the NMHDR member is first in this structure, the pointer you’re passed in the notification message can be cast to either a pointer to an NMHDR or a pointer to an LV_KEYDOWN.

Notifications Common to All New Windows Controls

Some notifications are common to all of the new Windows controls. These notifications pass a pointer to an NMHDR structure.

Notification code | Sent because
NM_CLICK | User clicked left mouse button in the control
NM_DBLCLK | User double-clicked left mouse button in the control
NM_RCLICK | User clicked right mouse button in the control
NM_RDBLCLK | User double-clicked right mouse button in the control
NM_RETURN | User pressed the ENTER key while control has input focus
NM_SETFOCUS | Control has been given input focus
NM_KILLFOCUS | Control has lost input focus
NM_OUTOFMEMORY | Control could not complete an operation because there was not enough memory available

ON_NOTIFY: Handling WM_NOTIFY Messages in MFC Applications

The function CWnd::OnNotify handles notification messages. Its default implementation checks the message map for notification handlers to call. In general, you do not override OnNotify. Instead, you provide a handler function and add a message-map entry for that handler to the message map of your owner window’s class.

ClassWizard, via either the ClassWizard property sheet or the WizardBar, can create the ON_NOTIFY message-map entry and provide you with a skeleton handler function. For more information on using ClassWizard to make this easier, see Mapping Messages to Functions in the Visual C++ Programmer's Guide.

The ON_NOTIFY message-map macro has the following syntax:

ON_NOTIFY( wNotifyCode, id, memberFxn )

where the italicized parameters are replaced with:

wNotifyCode

The code for the notification message to be handled, such as LVN_KEYDOWN.

id

The child identifier of the control for which the notification is sent.

memberFxn

The member function to be called when this notification is sent.

Your member function must be declared with the following prototype:

afx_msg void memberFxn( NMHDR * pNotifyStruct, LRESULT * result );

where the italicized parameters are:

pNotifyStruct

A pointer to the notification structure, as described in the section above.

result

A pointer to the result code you’ll set before you return.

Example

To specify that you want the member function OnKeydownList1 to handle LVN_KEYDOWN messages from the CListCtrl whose ID is IDC_LIST1, you would use ClassWizard to add the following to your message map:

ON_NOTIFY( LVN_KEYDOWN, IDC_LIST1, OnKeydownList1 )

In the example above, the function provided by ClassWizard is:

void CMessageReflectionDlg::OnKeydownList1(NMHDR* pNMHDR, LRESULT* pResult)
{
   LV_KEYDOWN* pLVKeyDow = (LV_KEYDOWN*)pNMHDR;
   // TODO: Add your control notification handler
   //       code here

   *pResult = 0;
}

Note that ClassWizard provides a pointer of the proper type automatically. You can access the notification structure through either pNMHDR or pLVKeyDow.

ON_NOTIFY_RANGE

If you need to process the same WM_NOTIFY message for a set of controls, you can use ON_NOTIFY_RANGE rather than ON_NOTIFY. For instance, you may have a set of buttons for which you want to perform the same action for a certain notification message.

When you use ON_NOTIFY_RANGE, you specify a contiguous range of child identifiers for which to handle the notification message by specifying the beginning and ending child identifiers of the range.

ClassWizard does not handle ON_NOTIFY_RANGE; to use it, you need to edit your message map yourself.

The message-map entry and function prototype for ON_NOTIFY_RANGE are as follows:

ON_NOTIFY_RANGE( wNotifyCode, id, idLast, memberFxn )

where the italicized parameters are replaced with:

wNotifyCode

The code for the notification message to be handled, such as LVN_KEYDOWN.

id

The first identifier in the contiguous range of identifiers.

idLast

The last identifier in the contiguous range of identifiers.

memberFxn

The member function to be called when this notification is sent.

Your member function must be declared with the following prototype:

afx_msg void memberFxn( UINT id, NMHDR * pNotifyStruct, LRESULT * result );

where the italicized parameters are:

id

The child identifier of the control that sent the notification.

pNotifyStruct

A pointer to the notification structure, as described above.

result

A pointer to the result code you’ll set before you return.

ON_NOTIFY_EX, ON_NOTIFY_EX_RANGE

If you want more than one object in the notification routing to handle a message, you can use ON_NOTIFY_EX (or ON_NOTIFY_EX_RANGE) rather than ON_NOTIFY (or ON_NOTIFY_RANGE). The only difference between the EX version and the regular version is that the member function called for the EX version returns a BOOL that indicates whether or not message processing should continue. Returning FALSE from this function allows you to process the same message in more than one object.

ClassWizard does not handle ON_NOTIFY_EX or ON_NOTIFY_EX_RANGE; if you want to use either of them, you need to edit your message map yourself.

The message-map entry and function prototype for ON_NOTIFY_EX and ON_NOTIFY_EX_RANGE are as follows. The meanings of the parameters are the same as for the non-EX versions.

ON_NOTIFY_EX( nCode, id, memberFxn )

ON_NOTIFY_EX_RANGE( wNotifyCode, id, idLast, memberFxn )

The prototype for both of the above is the same:

afx_msg BOOL memberFxn( UINT id, NMHDR * pNotifyStruct, LRESULT * result );

In both cases, id holds the child identifier of the control that sent the notification.

Your function must return TRUE if the notification message has been completely handled or FALSE if other objects in the command routing should have a chance to handle the message.


TN062: Message Reflection for Windows Controls

This technical note describes message reflection, a new feature in MFC 4.0. It also contains directions for creating a simple reusable control that uses message reflection.

This technical note does not discuss message reflection as it applies to ActiveX controls (formerly called OLE controls). Please see the article ActiveX Controls: Subclassing a Windows Control in Visual C++ Programmer's Guide.

What Is Message Reflection?

Windows controls frequently send notification messages to their parent windows. For instance, many controls send a control color notification message (WM_CTLCOLOR or one of its variants) to their parent to allow the parent to supply a brush for painting the background of the control.

In Windows and in MFC prior to version 4.0, the parent window, often a dialog box, is responsible for handling these messages. This means that the code for handling the message needs to be in the parent window’s class and that it has to be duplicated in every class that needs to handle that message. In the case above, every dialog box that wanted controls with custom backgrounds would have to handle the control color notification message. It would be much easier to reuse code if a control class could be written that would handle its own background color.

In MFC 4.0, the old mechanism still works—parent windows can handle notification messages. In addition, however, MFC 4.0 facilitates reuse by providing a feature called “message reflection” that allows these notification messages to be handled in either the child control window or the parent window, or in both. In the control background color example, you can now write a control class that sets its own background color by handling the reflected WM_CTLCOLOR message—all without relying on the parent. (Note that since message reflection is implemented by MFC, not by Windows, the parent window class must be derived from CWnd for message reflection to work.)

Older versions of MFC did something similar to message reflection by providing virtual functions for a few messages, such as messages for owner-drawn list boxes (WM_DRAWITEM, and so on). The new message reflection mechanism is generalized and consistent.

Message reflection is backward compatible with code written for versions of MFC previous to 4.0.

If you have supplied a handler for a specific message, or for a range of messages, in your parent window's class, it will override reflected message handlers for the same message provided you don't call the base class handler function in your own handler. For example, if you handle WM_CTLCOLOR in your dialog box class, your handling will override any reflected message handlers.

If, in your parent window class, you supply a handler for a specific WM_NOTIFY message or a range of WM_NOTIFY messages, your handler will be called only if the child control sending those messages does not have a reflected message handler through ON_NOTIFY_REFLECT(). If you use ON_NOTIFY_REFLECT_EX() in your message map, your message handler may or may not allow the parent window to handle the message. If the handler returns TRUE, the message will be handled by the parent as well, while a call that returns FALSE does not allow the parent to handle it. Note that the reflected message is handled before the notification message.

When a WM_NOTIFY message is sent, the control is offered the first chance to handle it. If any other reflected message is sent, the parent window has the first chance to handle it and the control will receive the reflected message. To do so, it will need a handler function and an appropriate entry in the control's class message map.

The message-map macro for reflected messages is slightly different than for regular notifications: it has _REFLECT appended to its usual name. For instance, to handle a WM_NOTIFY message in the parent, you use the macro ON_NOTIFY in the parent’s message map. To handle the reflected message in the child control, use the ON_NOTIFY_REFLECT macro in the child control’s message map. In some cases, the parameters are different, as well. Note that ClassWizard can usually add the message-map entries for you and provide skeleton function implementations with correct parameters.

See TN061: ON_NOTIFY and WM_NOTIFY Messages for information on the new WM_NOTIFY message.

Message-Map Entries and Handler Function Prototypes for Reflected Messages

To handle a reflected control notification message, use the message-map macros and function prototypes listed in the table below.

ClassWizard can usually add these message-map entries for you and provide skeleton function implementations. See Defining a Message Handler for a Reflected Message in the Visual C++ Programmer's Guide for information about how to define handlers for reflected messages.

To convert from the message name to the reflected macro name, prepend ON_ and append _REFLECT. For example, WM_CTLCOLOR becomes ON_WM_CTLCOLOR_REFLECT. (To see which messages can be reflected, do the opposite conversion on the macro entries in the table below.)

The three exceptions to the rule above are as follows:

  • The macro for WM_COMMAND notifications is ON_CONTROL_REFLECT.

  • The macro for WM_NOTIFY reflections is ON_NOTIFY_REFLECT.

  • The macro for ON_UPDATE_COMMAND_UI reflections is ON_UPDATE_COMMAND_UI_REFLECT.

In each of the above special cases, you must specify the name of the handler member function. In the other cases, you must use the standard name for your handler function.

The meanings of the parameters and return values of the functions are documented under either the function name or the function name with On prepended. For instance, CtlColor is documented in OnCtlColor. Several reflected message handlers need fewer parameters than the similar handlers in a parent window. Just match the names in the table below with the names of the formal parameters in the documentation.

Map entry | Function prototype
ON_CONTROL_REFLECT( wNotifyCode, memberFxn ) | afx_msg void memberFxn ( );
ON_NOTIFY_REFLECT( wNotifyCode, memberFxn ) | afx_msg void memberFxn ( NMHDR * pNotifyStruct, LRESULT* result );
ON_UPDATE_COMMAND_UI_REFLECT( memberFxn ) | afx_msg void memberFxn ( CCmdUI* pCmdUI );
ON_WM_CTLCOLOR_REFLECT( ) | afx_msg HBRUSH CtlColor ( CDC* pDC, UINT nCtlColor );
ON_WM_DRAWITEM_REFLECT( ) | afx_msg void DrawItem ( LPDRAWITEMSTRUCT lpDrawItemStruct );
ON_WM_MEASUREITEM_REFLECT( ) | afx_msg void MeasureItem ( LPMEASUREITEMSTRUCT lpMeasureItemStruct );
ON_WM_DELETEITEM_REFLECT( ) | afx_msg void DeleteItem ( LPDELETEITEMSTRUCT lpDeleteItemStruct );
ON_WM_COMPAREITEM_REFLECT( ) | afx_msg int CompareItem ( LPCOMPAREITEMSTRUCT lpCompareItemStruct );
ON_WM_CHARTOITEM_REFLECT( ) | afx_msg int CharToItem ( UINT nKey, UINT nIndex );
ON_WM_VKEYTOITEM_REFLECT( ) | afx_msg int VKeyToItem ( UINT nKey, UINT nIndex );
ON_WM_HSCROLL_REFLECT( ) | afx_msg void HScroll ( UINT nSBCode, UINT nPos );
ON_WM_VSCROLL_REFLECT( ) | afx_msg void VScroll ( UINT nSBCode, UINT nPos );
ON_WM_PARENTNOTIFY_REFLECT( ) | afx_msg void ParentNotify ( UINT message, LPARAM lParam );

The ON_NOTIFY_REFLECT and ON_CONTROL_REFLECT macros have variations that allow more than one object (such as the control and its parent) to handle a given message.

Map entry | Function prototype
ON_NOTIFY_REFLECT_EX( wNotifyCode, memberFxn ) | afx_msg BOOL memberFxn ( NMHDR * pNotifyStruct, LRESULT* result );
ON_CONTROL_REFLECT_EX( wNotifyCode, memberFxn ) | afx_msg BOOL memberFxn ( );

Handling Reflected Messages: An Example of a Reusable control

This simple example creates a reusable control called CYellowEdit. The control works the same as a regular edit control except that it displays black text on a yellow background. It would be easy to add member functions that would allow the CYellowEdit control to display different colors.

To try this example, do the following steps:

  1. Create a new dialog box in an existing application. For more information see dialog editor in the Visual C++ User’s Guide.

    You must have an application in which to develop the reusable control. If you don’t have an existing application to use, create a dialog-based application using AppWizard.

  2. With your project loaded into Visual C++, use ClassWizard to create a new class called CYellowEdit based on CEdit. Leave the “Add to Component Gallery” box checked.

  3. Add three member variables to your CYellowEdit class. The first two will be COLORREF variables to hold the text color and the background color. The third will be a CBrush object which will hold the brush for painting the background. The CBrush object allows you to create the brush once, merely referencing it after that, and to destroy the brush automatically when the CYellowEdit control is destroyed.

  4. Initialize the member variables by writing the constructor as follows:
    CYellowEdit::CYellowEdit()
{
m_clrText = RGB( 0, 0, 0 );
m_clrBkgnd = RGB( 255, 255, 0 );
m_brBkgnd.CreateSolidBrush( m_clrBkgnd );
}
  5. Using ClassWizard, add a handler for the reflected WM_CTLCOLOR message to your CYellowEdit class. Note that the equal sign in front of the message name in the list of messages you can handle indicates that the message is reflected. This is described in Defining a Message Handler for a Reflected Message in the Visual C++ Programmer's Guide.

    ClassWizard adds the following message-map macro and skeleton function for you:

    ON_WM_CTLCOLOR_REFLECT()

// Note: other code will be in between....

HBRUSH CYellowEdit::CtlColor(CDC* pDC, UINT nCtlColor)
{
// TODO: Change any attributes of the DC here

// TODO: Return a non-NULL brush if the
//    parent's handler should not be called
return NULL;
}
  6. Replace the body of the function with the following code. The code specifies the text color, the text background color, and the background color for rest of the control.
    pDC->SetTextColor( m_clrText );    // text
pDC->SetBkColor( m_clrBkgnd );    // text bkgnd
return m_brBkgnd;                // ctl bkgnd
  7. Create an edit control in your dialog box, then attach it to a member variable by double-clicking the edit control while holding a control key down. In the Add Member Variable dialog box, finish the variable name and choose “Control” for the category, then “CYellowEdit” for the variable type. Don’t forget to set the tab order in the dialog box. Also, be sure to include the header file for the CYellowEdit control in your dialog box’s header file.

  8. Build and run your application. The edit control will have a yellow background.

  9. You can now use Component Gallery to add your CYellowEdit control class to other projects.


TN063: Debugging Internet Extension DLLs

If you have written an Internet Server extension DLL, you might be interested in getting it running under the debugger so you can trace its execution, set breakpoints, or monitor variable values after the extension is called. Getting the Microsoft Internet Information Server (IIS) up and running with your DLL in the debugger is a little tricky. You will need to first find a quiet server where you can debug your DLL in a controlled setting. Once you’ve found such a resource, you can start debugging your DLL.

Because of differences between version 3.0 and 4.0 of IIS, it is important to know which version you will be using to debug your DLL.

  • Debugging Using Internet Information Server (3.0 and earlier)

  • Debugging Using Internet Information Server (4.0 and later)

Debugging Using Internet Information Server (3.0 and earlier)

Follow these steps to debug an Internet Server extension DLL using IIS 3.0:

  1. Stop the IIS publishing services by using the IIS Manager, or by stopping the services with the Services icon in the Windows NT Advanced Server Control Panel. Note that you must stop all three services even though you are only debugging extensions to the World Wide Web publishing service. To make things easier, you might want to make the services "Manually" started in Control Panel so you can avoid this step later in your development.

  2. Start Microsoft Visual C++, and click the Close Workspace command on the File menu to close any opened workspace.

  3. On the File menu, click Open Workspace to open the INETINFO.EXE program. This file is in the directory where you installed the Microsoft Internet Information Server.

  4. On the Project menu, click Settings, then click the Debug tab in the Project Settings dialog box.

  5. With General selected in the Category box, type the following in the Program Arguments text box:

    -e W3Svc

  6. Choose Additional DLLs from the Category drop-down list. Then, in the Local Names box, specify the complete path and name of your extension DLL or DLLs. Make sure the check box next to each is marked.

  7. Click OK to close the Project Settings dialog box.

  8. Make sure that the .PDB file for your DLL is in the same directory as the DLLs you plan to debug.

Debugging Tips

The IIS can be run as an interactive application, making debugging much easier. To do this you need to make a few changes to your system. For the user account that you are going to run the server under, you need to add a few privileges.

To add privileges, run User Manager. (If you're using Windows NT 3.51, run MUSRMGR.EXE. If you're using Windows NT 4.0, run USRMGR.EXE.) Click User Rights from the Policies menu. Select the Show Advanced User Rights check box. Then select Act as part of the operating system from the drop-down list on the right, and add the user account.

Repeat this process with Generate Security Audits (also in the drop-down list on the right). Make sure that all Internet Services (WWW, ftp, and gopher) are stopped and INETINFO.EXE is not running (use TLIST to check). Log off and log back on. You can then load the IIS with the command line:

INetInfo.Exe -e W3Svc

To load IIS under a debugger (for example, under WinDbg), use the following command line:

WinDbg INetInfo.Exe -e W3Svc

You are ready to go. In Visual C++, point to Debug on the Build menu and then click Go. This action starts the WWW publishing service, and the debugger will be aware of symbols in your DLL. You can ignore the warning that the file doesn’t have debugging information.

When you close Visual C++, save the workspace for INETINFO.EXE. That way, you can avoid reentering the settings for the debugging session. Just open the INETINFO.MDS workspace file when you are ready to start the debugger again.

Cached DLLs

You can adjust the registry setting at HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/W3SVC/Parameters/CacheExtensions to have the server reinitialize DLLs each time they are used. If this setting is 1, the server will keep DLLs loaded in memory as long as possible. This is the default setting for the server, since it helps the server achieve peak performance, and should only be changed if you are using the server for debugging. If you make the setting 0, the server will always reload extension DLLs each time they are used.

Forcing the server to reload your DLL is helpful when your DLL might be crashing or upsetting any per-instance data that it maintains. By forcing the server to reinitialize the DLL, you can get your DLL back into a predictable state with little effort. Be sure to test your DLL using the normal CacheExtensions setting, however, to make sure code in your DLL isn’t completely dependent on that initial state.

Debugging Using Internet Information Server (4.0 and later)

There are several ways to establish an environment for debugging your server components and Internet Server extension DLLs when using IIS 4.0 or later. If you are using a debugger capable of attaching to a Windows NT process, you can use this functionality to debug your component or extension. For example, if you are debugging with Visual C++, take the following steps:

  1. Start the iisadmin process. This can be done from the command line with the command net start iisadmin. You can also use the Services dialog box from the Control Panel to start the IIS Admin Service, which will start iisadmin.

  2. Start Visual C++. Point to Start Debug on the Build menu and click Attach to Process.

  3. Select the Show System Process check box.

  4. Select the inetinfo process from the list and click OK.

  5. Start the w3svc service. This can be done from the command line with the command net start w3svc. You can also use the Services dialog box in the Control Panel to start the World Wide Web Publishing Service.

If the debugger you are using cannot attach to a Windows NT process, take the following steps to establish an appropriate debugging environment:

  1. Open the Services dialog box in the Control Panel.

  2. Select the IIS Admin service and click the Startup button.

  3. Select the Allow Service to Interact with Desktop check box and click OK.

  4. Repeat steps 2 and 3 for all processes that run under the IIS Admin process, for example World Wide Web Publishing Service and FTP Publishing Service.

  5. Use the Registry Editor (REGEDIT) to add a subkey named Inetinfo.Exe to the HKEY_LOCAL_MACHINE/Software/Microsoft/WindowsNT/CurrentVersion/Image File Execution Options key.

  6. Add the following entry to this new key:

    Debugger = <DebuggerExeName> where DebuggerExeName is the full path to the debugger you are using.

When the World Wide Web Publishing Service is started, your debugger will also be launched. You can now set appropriate breakpoints in your Internet Server extension DLL.

You won't be able to set breakpoints in a component's source code until the component has been loaded into memory. To do this, start Internet Explorer and view the .ASP page containing the object. As soon as the page is loaded, you should be able to set breakpoints in your component. Click Refresh to view the page again, and trigger the breakpoints you selected. If the component cannot be loaded even once (for instance, if the fault occurs in component startup code), you need to load the component DLL prior to starting the debugging session. (See step 11 below.)

In some cases, you may not be able to use either of the two procedures outlined above. If you have difficulty using either of these strategies, there is a third approach, which has been described in previous releases of IIS. This third approach requires the establishing of Windows NT security privileges as well as making changes to the registry. It will also disable your ability to run IIS as a service. This approach should only be used if the previous two strategies have failed.

  1. Use the User Manager for Domains administration tool (USRMGR) to add the Log on as Service, Act as part of the operating system, and Generate security audits rights on the local computer to the Windows NT account you will use when debugging the Internet Server extension DLL.

  2. Use the Distributed COM Configuration utility (DCOMCNFG) to change the identity of the IIS Admin Service to the user account you will use for debugging.

  3. Use the Registry Editor (REGEDIT) to remove the LocalService keyword from all IISADMIN-related subkeys under HKEY_CLASSES_ROOT/AppID. This keyword may be found in the following subkeys:

    {61738644-F196-11D0-9953-00C04FD919C1} // IIS WAMREG admin Service

    {9F0BD3A0-EC01-11D0-A6A0-00A0C922E752} // IIS Admin Crypto Extension

    {A9E69610-B80D-11D0-B9B9-00A0C922E750} // IISADMIN Service

    The LocalService keyword may be found in additional subkeys of AppID.

  4. Add LocalServer32 subkeys to all IISADMIN-related subkeys under the CLSID node of the registry. This will include subkeys corresponding to all of the subkeys you removed in the previous step. Set the default value of these new keys to <path>\inetinfo.exe -e w3svc. (<path> is normally "c:\winnt\system32\inetsrv".)

  5. Stop the WWW and FTP services from the Microsoft Management Console, or from the Services dialog box in the Control Panel.

  6. Start Visual C++ and select the Debug tab in the Project Settings dialog box.

  7. Type the following path in the Executable for debug session field:

    C:\WINNT\System32\Inetsrv\Inetinfo.exe

  8. Type the following in the Program Arguments field:

    -e w3svc

  9. Select the Link tab in the Project Settings dialog box.

  10. Enter the name and path of the Internet Server extension DLL you are debugging in the Output file name field.

  11. Optionally, add your component DLL to the list of Additional DLLs that are loaded before the application starts. This will allow you to set breakpoints in component startup code.

  12. Click the Go button to start the debugging session.

Note After you have completed the debugging session, you must reverse steps 5 through 1 to restore the previous settings and allow IIS to run as a service.


TN064: Apartment-Model Threading in ActiveX Controls

This technical note explains how to enable apartment-model threading in an ActiveX control. Note that apartment-model threading is only supported in Visual C++ versions 4.2 or later.

What Is Apartment-Model Threading?

The apartment model is an approach to supporting embedded objects, such as ActiveX controls, within a multithreaded container application. Although the application may have multiple threads, each instance of an embedded object will be assigned to one “apartment,” which will execute on only one thread. In other words, all calls into an instance of a control will happen on the same thread.

However, different instances of the same type of control may be assigned to different apartments. So, if multiple instances of a control share any data in common (for example, static or global data), then access to this shared data will need to be protected by a synchronization object, such as a critical section.

For complete details on the apartment threading model, please see Processes and Threads in the OLE Programmer’s Reference.

Why Support Apartment-Model Threading?

Controls that support apartment-model threading can be used in multithreaded container applications that also support the apartment model. If you do not enable apartment-model threading, you will limit the potential set of containers in which your control could be used.

Enabling apartment-model threading is easy for most controls, particularly if they have little or no shared data.

Protecting Shared Data

If your control uses shared data, such as a static member variable, access to that data should be protected with a critical section to prevent more than one thread from modifying the data at the same time. To set up a critical section for this purpose, declare a static member variable of class CCriticalSection in your control’s class. Use the Lock and Unlock member functions of this critical section object wherever your code accesses the shared data.

Consider, for example, a control class that needs to maintain a string that is shared by all instances. This string can be maintained in a static member variable and protected by a critical section. The control’s class declaration would contain the following:

class CSampleCtrl : public COleControl
{
    ...
    static CString _strShared;
    static CCriticalSection _critSect;
};

The implementation for the class would include definitions for these variables:

int CString CSampleCtrl::_strShared;
CCriticalSection CSampleCtrl::_critSect;

Access to the _strShared static member can then be protected by the critical section:

void CSampleCtrl::SomeMethod()
{
    _critSect.Lock();
    if (_strShared.Empty())
        _strShared = "<text>";
    _critSect.Unlock();
    ...
}

Registering an Apartment-Model-Aware Control

Controls that support apartment-model threading should indicate this capability in the registry, by adding the named value “ThreadingModel” with a value of “Apartment” in their class ID registry entry under the class id\InprocServer32 key. To cause this key to be automatically registered for your control, pass the afxRegApartmentThreading flag in the sixth parameter to AfxOleRegisterControlClass:

BOOL CSampleCtrl::CSampleCtrlFactory::UpdateRegistry(BOOL bRegister)
{
    if (bRegister)
        return AfxOleRegisterControlClass(
            AfxGetInstanceHandle(),
            m_clsid,
            m_lpszProgID,
            IDS_SAMPLE,
            IDB_SAMPLE,
            afxRegApartmentThreading,
            _dwSampleOleMisc,
            _tlid,
            _wVerMajor,
            _wVerMinor);
    else
        return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}

If your control project was generated by ControlWizard in Visual C++ version 4.1 or later, this flag will already be present in your code. No changes are necessary to register the threading model.

If your project was generated by an earlier version of ControlWizard, your existing code will have a boolean value as the sixth parameter. If the existing parameter is TRUE, change it to afxRegInsertable | afxRegApartmentThreading. If the existing parameter is FALSE, change it to afxRegApartmentThreading.

If your control does not follow the rules for apartment-model threading, you must not pass afxRegApartmentThreading in this parameter.


TN065: Dual-Interface Support for OLE Automation Servers

This note discusses how to add dual-interface support to an MFC-based OLE Automation server application. The ACDUAL sample illustrates dual-interface support, and the example code in this note is taken from ACDUAL. The macros described in this note, such as DECLARE_DUAL_ERRORINFO, DUAL_ERRORINFO_PART, and IMPLEMENT_DUAL_ERRORINFO, are part of the ACDUAL sample and can be found in MFCDUAL.H.

Dual Interfaces

Although OLE Automation allows you to implement an IDispatch interface, a VTBL interface, or a dual interface (which encompasses both), Microsoft strongly recommends that you implement dual interfaces for all exposed OLE Automation objects. Dual interfaces have significant advantages over IDispatch-only or VTBL-only interfaces:

  • Binding can take place at compile time through the VTBL interface, or at run time through IDispatch.

  • OLE Automation controllers that can use the VTBL interface may benefit from improved performance.

  • Existing OLE Automation controllers that use the IDispatch interface will continue to work.

  • The VTBL interface is easier to call from C++.

  • Dual interfaces are required for compatibility with Visual Basic object support features.

Adding Dual-Interface Support to a CCmdTarget-Based Class

A dual interface is really just a custom interface derived from IDispatch. The most straightforward way to implement dual-interface support in a CCmdTarget-based class is to first implement the normal dispatch interface on your class using MFC and ClassWizard, then add the custom interface later. For the most part, your custom interface implementation will simply delegate back to the MFC IDispatch implementation.

First, modify the ODL file for your server to define dual interfaces for your objects. To define a dual interface, you must use an interface statement, instead of the DISPINTERFACE statement that the Visual C++ wizards generate. Rather than removing the existing DISPINTERFACE statement, add a new interface statement. By retaining the DISPINTERFACE form, you can continue to use ClassWizard to add properties and methods to your object, but you must add the equivalent properties and methods to your interface statement.

An interface statement for a dual interface must have the OLEAUTOMATION and DUAL attributes, and the interface must be derived from IDispatch. You can use the GUIDGEN sample to create a IID for the dual interface:

[ uuid(0BDD0E81-0DD7-11cf-BBA8-444553540000), // IID_IDualAClick
   oleautomation,
   dual
]
interface IDualAClick : IDispatch
  {
  };

Once you have the interface statement in place, start adding entries for the methods and properties. For dual interfaces, you need to rearrange the parameter lists so that your methods and property accessor functions in the dual interface return an HRESULT and pass their return values as parameters with the attributes [retval,out]. Remember that for properties, you will need to add both a read (propget) and write (propput) access function with the same id. For example:

[propput, id(1)] HRESULT text([in] BSTR newText);
[propget, id(1)] HRESULT text([out, retval] BSTR* retval);

After your methods and properties are defined, you need to add a reference to the interface statement in your coclass statement. For example:

[ uuid(4B115281-32F0-11cf-AC85-444553540000) ]
coclass Document
{
   dispinterface IAClick;
   [default] interface IDualAClick;
};

Once your ODL file has been updated, use MFC’s interface map mechanism to define an implementation class for the dual interface in your object class and make the corresponding entries in MFC’s QueryInterface mechanism. You need one entry in the INTERFACE_PART block for each entry in the interface statement of the ODL, plus the entries for a dispatch interface. Each ODL entry with the propput attribute needs a function named put_propertyname. Each entry with the propget attribute needs a function named get_propertyname.

To define an implementation class for your dual interface, add a DUAL_INTERFACE_PART block to your object class definition. For example:

BEGIN_DUAL_INTERFACE_PART(DualAClick, IDualAClick)
  STDMETHOD(put_text)(THIS_ BSTR newText);
  STDMETHOD(get_text)(THIS_ BSTR FAR* retval);
  STDMETHOD(put_x)(THIS_ short newX);
  STDMETHOD(get_x)(THIS_ short FAR* retval);
  STDMETHOD(put_y)(THIS_ short newY);
  STDMETHOD(get_y)(THIS_ short FAR* retval);
  STDMETHOD(put_Position)(THIS_ IDualAutoClickPoint FAR* newPosition);
  STDMETHOD(get_Position)(THIS_ IDualAutoClickPoint FAR* FAR* retval);
  STDMETHOD(RefreshWindow)(THIS);
  STDMETHOD(SetAllProps)(THIS_ short x, short y, BSTR text);
  STDMETHOD(ShowWindow)(THIS);
END_DUAL_INTERFACE_PART(DualAClick)

To connect the dual interface to MFC’s QueryInterface mechanism, add an INTERFACE_PART entry to the interface map:

BEGIN_INTERFACE_MAP(CAutoClickDoc, CDocument)
  INTERFACE_PART(CAutoClickDoc, DIID_IAClick, Dispatch)
  INTERFACE_PART(CAutoClickDoc, IID_IDualAClick, DualAClick)
END_INTERFACE_MAP()

Next, you need to fill in the implementation of the interface. For the most part, you will be able to delegate to the existing MFC IDispatch implementation. For example:

STDMETHODIMP_(ULONG) CAutoClickDoc::XDualAClick::AddRef()
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) CAutoClickDoc::XDualAClick::Release()
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   return pThis->ExternalRelease();
}
STDMETHODIMP CAutoClickDoc::XDualAClick::QueryInterface(
             REFIID iid, LPVOID* ppvObj)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP CAutoClickDoc::XDualAClick::GetTypeInfoCount(
            UINT FAR* pctinfo)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   LPDISPATCH lpDispatch = pThis->GetIDispatch(FALSE);
   ASSERT(lpDispatch != NULL);
   return lpDispatch->GetTypeInfoCount(pctinfo);
}
STDMETHODIMP CAutoClickDoc::XDualAClick::GetTypeInfo(
          UINT itinfo, LCID lcid, ITypeInfo FAR* FAR* pptinfo)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   LPDISPATCH lpDispatch = pThis->GetIDispatch(FALSE);
   ASSERT(lpDispatch != NULL);
   return lpDispatch->GetTypeInfo(itinfo, lcid, pptinfo);
}
STDMETHODIMP CAutoClickDoc::XDualAClick::GetIDsOfNames(
       REFIID riid, OLECHAR FAR* FAR* rgszNames, UINT cNames,
       LCID lcid, DISPID FAR* rgdispid)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   LPDISPATCH lpDispatch = pThis->GetIDispatch(FALSE);
   ASSERT(lpDispatch != NULL);
   return lpDispatch->GetIDsOfNames(riid, rgszNames, cNames,
                                    lcid, rgdispid);
}
STDMETHODIMP CAutoClickDoc::XDualAClick::Invoke(
    DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags,
    DISPPARAMS FAR* pdispparams, VARIANT FAR* pvarResult,
    EXCEPINFO FAR* pexcepinfo, UINT FAR* puArgErr)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   LPDISPATCH lpDispatch = pThis->GetIDispatch(FALSE);
   ASSERT(lpDispatch != NULL);
   return lpDispatch->Invoke(dispidMember, riid, lcid,
                             wFlags, pdispparams, pvarResult,
                             pexcepinfo, puArgErr);
}

For your object’s methods and property accessor functions, you need to fill in the implementation. Your method and property functions can generally delegate back to the methods generated using ClassWizard. However, if you set up properties to access variables directly, you need to write the code to get/put the value into the variable. For example:

STDMETHODIMP CAutoClickDoc::XDualAClick::put_text(BSTR newText)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   // MFC automatically converts from Unicode BSTR to
   // Ansi CString, if necessary...
   pThis->m_str = newText;
   return NOERROR;
}
STDMETHODIMP CAutoClickDoc::XDualAClick::get_text(BSTR* retval)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   // MFC automatically converts from Ansi CString to
   // Unicode BSTR, if necessary...
   pThis->m_str.SetSysString(retval);
   return NOERROR;
}

Passing Dual-Interface Pointers

Passing your dual-interface pointer isn’t straightforward, especially if you need to call CCmdTarget::FromIDispatch. FromIDispatch only works on MFC’s IDispatch pointers. One way to work around this is to query for the original IDispatch pointer set up by MFC and pass that pointer to functions that need it. For example:

STDMETHODIMP CAutoClickDoc::XDualAClick::put_Position(
      IDualAutoClickPoint FAR* newPosition)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   LPDISPATCH lpDisp = NULL;
   newPosition->QueryInterface(IID_IDispatch, (LPVOID*)&lpDisp);
   pThis->SetPosition(lpDisp);
   lpDisp->Release();
   return NOERROR;
}

Before passing a pointer back through the dual-interface method, you might need to convert it from the MFC IDispatch pointer to your dual-interface pointer. For example:

STDMETHODIMP CAutoClickDoc::XDualAClick::get_Position(
      IDualAutoClickPoint FAR* FAR* retval)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   LPDISPATCH lpDisp;
   lpDisp = pThis->GetPosition();
   lpDisp->QueryInterface(IID_IDualAutoClickPoint, (LPVOID*)retval);
   return NOERROR;
}

Registering the Application's Type Library

AppWizard does not generate code to register an OLE Automation server application’s type library with the system. While there are other ways to register the type library, it is convenient to have the application register the type library when it is updating its OLE type information, that is, whenever the application is run stand-alone.

To register the application’s type library whenever the application is run stand-alone:

  • Include AFXCTL.H in your standard includes header file, STDAFX.H, to access the definition of the AfxOleRegisterTypeLib function.

  • In your application’s InitInstance function, locate the call to COleObjectFactory::UpdateRegistryAll. Following this call, add a call to AfxOleRegisterTypeLib, specifying the LIBID corresponding to your type library, along with the name of your type library:
    // When a server application is launched stand-alone, it is a good idea
// to update the system registry in case it has been damaged.
m_server.UpdateRegistry(OAT_DISPATCH_OBJECT);
COleObjectFactory::UpdateRegistryAll();
// DUAL_SUPPORT_START
// Make sure the type library is registered or dual interface won't work.
AfxOleRegisterTypeLib(AfxGetInstanceHandle(), LIBID_ACDual, _T("AutoClik.TLB"));
// DUAL_SUPPORT_END

Modifying Project Build Settings to Accommodate Type Library Changes

To modify a project's build settings so that a header file containing UUID definitions is generated by MkTypLib whenever the type library is rebuilt:

  1. From the Build menu, click Settings, then select the ODL file from the file list for each configuration.

  2. Click the OLE Types tab and specify a filename in the Output header filename field. Use a filename that is not already used by your project, since MkTypLib will overwrite any existing file. Click OK to close the Build Settings dialog box.

To add the UUID definitions from the MkTypLib-generated header file to your project:

  1. Include the MkTypLib-generated header file in your standard includes header file, STDAFX.H.

  2. Create a new file, INITIIDS.CPP, and add it to your project. In this file, include your MkTypLib-generated header file after including OLE2.H and INITGUID.H:
    // initIIDs.c: defines IIDs for dual interfaces
// This must not be built with precompiled header.
  #include <ole2.h>
  #include <initguid.h>
  #include "acdual.h"
  3. From the Build menu, click Settings, then select INITIIDS.CPP from the file list for each configuration.

  4. Click the C++ tab, category “Precompiled Headers” and select the “Not using precompiled headers” radio button. Click OK to close the Build Settings dialog box.

Specifying the Correct Object Class Name in the Type Library

The wizards shipped with Visual C++ incorrectly use the implementation class name to specify the coclass in the server’s ODL file for OLE-createable classes. While this will work, the implementation class name is probably not the class name you want users of your object to use. To specify the correct name, open the ODL file, locate each coclass statement, and replace the implementation class name with the correct external name.

Note that when the coclass statement is changed, the variable names of CLSIDs in the MkTypLib-generated header file will change accordingly. You will need to update your code to use the new variable names.

Handling Exceptions and the Automation Error Interfaces

Your automation object’s methods and property accessor functions may throw exceptions. If so, you should handle them in your dual-interface implementation and pass information about the exception back to the controller through the OLE Automation error-handling interface, IErrorInfo. This interface provides for detailed, contextual error information through both IDispatch and VTBL interfaces. To indicate that an error handler is available, you should implement the ISupportErrorInfo interface.

To illustrate the error-handling mechanism, assume that the ClassWizard-generated functions used to implement the standard dispatch support throw exceptions. MFC’s implementation of IDispatch::Invoke typically catches these exceptions and converts them into an EXCEPTINFO structure that is returned through the Invoke call. However, when VTBL interface is used, you are responsible for catching the exceptions yourself. As an example of protecting your dual-interface methods:

STDMETHODIMP CAutoClickDoc::XDualAClick::put_text(BSTR newText)
{
   METHOD_PROLOGUE(CAutoClickDoc, DualAClick)
   TRY_DUAL(IID_IDualAClick)
   {
      // MFC automatically converts from Unicode BSTR to
      // Ansi CString, if necessary...
      pThis->m_str = newText;
      return NOERROR;
   }
   CATCH_ALL_DUAL
}

CATCH_ALL_DUAL takes care of returning the correct error code when an exception occurs. CATCH_ALL_DUAL converts an MFC exception into OLE Automation error-handling information using the ICreateErrorInfo interface. (An example CATCH_ALL_DUAL macro is in the file MFCDUAL.H in the ACDUAL sample. The function it calls to handle exceptions, DualHandleException, is in the file MFCDUAL.CPP.) CATCH_ALL_DUAL determines the error code to return based on the type of exception that occurred:

  • COleDispatchException – In this case, HRESULT is constructed using the following code:
    hr = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF,
                           (e->m_wCode + 0x200));

    This creates an HRESULT specific to the interface that caused the exception. The error code is offset by 0x200 to avoid any conflicts with system-defined HRESULTs for standard OLE interfaces.

  • CMemoryException – In this case, E_OUTOFMEMORY is returned.

  • Any other exception – In this case, E_UNEXPECTED is returned.

To indicate that the OLE Automation error handler is used, you should also implement the ISupportErrorInfo interface.

First, add code to your automation class definition to show it supports ISupportErrorInfo.

Second, add code to your automation class’s interface map to associate the ISupportErrorInfo implementation class with MFC’s QueryInterface mechanism. The INTERFACE_PART statement matches the class defined for ISupportErrorInfo.

Finally, implement the class defined to support ISupportErrorInfo.

(The ACDUAL sample contains three macros to help do these three steps, DECLARE_DUAL_ERRORINFO, DUAL_ERRORINFO_PART, and IMPLEMENT_DUAL_ERRORINFO, all contained in MFCDUAL.H.)

The following example implements a class defined to support ISupportErrorInfo. CAutoClickDoc is the name of your automation class and IID_IDualAClick is the IID for the interface that is the source of errors reported via the OLE Automation error object:

STDMETHODIMP_(ULONG) CAutoClickDoc::XSupportErrorInfo::AddRef()
{
   METHOD_PROLOGUE(CAutoClickDoc, SupportErrorInfo)
   return pThis->ExternalAddRef();
}
STDMETHODIMP_(ULONG) CAutoClickDoc::XSupportErrorInfo::Release()
{
   METHOD_PROLOGUE(CAutoClickDoc, SupportErrorInfo)
   return pThis->ExternalRelease();
}
STDMETHODIMP CAutoClickDoc::XSupportErrorInfo::QueryInterface(
   REFIID iid, LPVOID* ppvObj)
{
   METHOD_PROLOGUE(CAutoClickDoc, SupportErrorInfo)
   return pThis->ExternalQueryInterface(&iid, ppvObj);
}
STDMETHODIMP CAutoClickDoc::XSupportErrorInfo::InterfaceSupportsErrorInfo(
   REFIID iid)
{
   METHOD_PROLOGUE(CAutoClickDoc, SupportErrorInfo)
   return (iid == IID_IDualAClick) ? S_OK : S_FALSE;
}


TN066: Common MFC 3.x to 4.0 Porting Issues

This technical note described the most common problems that can occur when attempting to port an application written with MFC 3.x (the MFC included with Visual C++ 2.x) to MFC 4.0. This information is now available in the Visual C++ Programmer's Guide under Porting and Upgrading.


TN067: Database Access from an ISAPI Server Extension

ISAPI server extensions are DLLs. They work in the process space of the server. Concurrent requests made to an ISAPI extension are handled by separate threads. Therefore, the code in an ISAPI extension must be thread-safe.

Situation

Database access methods that use COM to handle initialization are not thread-safe. The specific problem lies in initializing the COM libraries in one thread and then using another thread to access the data. The current implementation of the Microsoft ODBC Desktop Drivers falls into this category. These drivers (dBase, Microsoft Visual FoxPro, Microsoft Access, Microsoft Excel, Paradox, and Text) that ship with Visual C++, use the Microsoft Jet 3.0 database engine, which is not thread-safe. Also, Data Access Objects (DAO) is a COM-based API, so it does not run reliably in the multithreaded environment of an ISAPI extension.

There may be other database access methods which are not thread-safe.

Resolution

To access a database from an ISAPI server extension, use an ODBC driver that has been designed and tested for multithreaded use. Microsoft's ODBC drivers for Microsoft SQL Server 6.x are an example.

The MFC ODBC database classes are thread-safe as of MFC 4.2. Be sure that any ODBC database driver you use with these classes is also thread-safe.

Applications that use the MFC ODBC database classes prior to version MFC 4.2 need to have the database code placed inside a critical section to ensure that only one thread accesses the MFC database code at a time. For more information, see class CCriticalSection.

Currently, the MFC DAO database classes are not thread-safe because they use the DAO COM-based objects.


TN068: Performing Transactions with the Microsoft Access 7 ODBC Driver

This note describes how to perform transactions when using the MFC ODBC database classes and the Microsoft Access 7.0 ODBC driver included in the Microsoft ODBC Desktop Driver Pack version 3.0.

Overview

If your database application performs transactions, you must be careful to call CDatabase::BeginTrans and CRecordset::Open in the correct sequence in your application. The Microsoft Access 7.0 driver uses the Microsoft Jet database engine, and Jet requires that your application not begin a transaction on any database that has an open cursor. For the MFC ODBC database classes, an open cursor equates to an open CRecordset object.

If you open a recordset before calling BeginTrans, you may not see any error messages. However, any recordset updates your application makes become permanent after calling CRecordset::Update, and the updates will not be rolled back by calling Rollback. To avoid this problem, you must call BeginTrans first and then open the recordset.

MFC checks the driver functionality for cursor commit and rollback behavior. Class CDatabase provides two member functions, GetCursorCommitBehavior and GetCursorRollbackBehavior, to determine the effect of any transaction on your open CRecordset object. For the Microsoft Access 7.0 ODBC driver, these member functions return SQL_CB_CLOSE because the Access driver does not support cursor preservation. Therefore, you must call CRecordset::Requery following a CommitTrans or Rollback operation.

When you need to perform multiple transactions one after another, you cannot call Requery after the first transaction and then start the next one. You must close the recordset before the next call to BeginTrans in order to satisfy Jet’s requirement. This technical note describes two methods of handling this situation:

  • Closing the recordset after each CommitTrans or Rollback operation.

  • Using the ODBC API function SQLFreeStmt.

Closing the Recordset after each CommitTrans or Rollback Operation

Before starting a transaction, make sure the recordset object is closed. After calling BeginTrans, call the recordset’s Open member function. Close the recordset immediately after calling CommitTrans or Rollback. Note that repeatedly opening and closing the recordset can slow an application’s performance.

Using SQLFreeStmt

You can also use the ODBC API function SQLFreeStmt to explicitly close the cursor after ending a transaction. To start another transaction, call BeginTrans followed by CRecordset::Requery. When calling SQLFreeStmt, you must specify the recordset’s HSTMT as the first parameter and SQL_CLOSE as the second parameter. This method is faster than closing and opening the recordset at the start of every transaction. The following code demonstrates how to implement this technique:

CMyDatabase db;
db.Open( "MYDATASOURCE" );
CMyRecordset rs( &db );

// start transaction 1 and
// open the recordset
db.BeginTrans( );
rs.Open( );

// manipulate data

// end transaction 1
db.CommitTrans( );  // or Rollback( )

// close the cursor
::SQLFreeStmt( rs.m_hstmt, SQL_CLOSE );

// start transaction 2
db.BeginTrans( );

// now get the result set
rs.Requery( );

// manipulate data

// end transaction 2
db.CommitTrans( );

rs.Close( );
db.Close( );

Another way to implement this technique is to write a new function, RequeryWithBeginTrans, which you can call to start the next transaction after you commit or rollback the first one. To write such a function, do the following steps:

  1. Copy the code for CRecordset::Requery( ) to the new function.

  2. Add the following line immediately after the call to SQLFreeStmt:
    m_pDatabase->BeginTrans( );

Now you can call this function between each pair of transactions:

// start transaction 1 and
// open the recordset
db.BeginTrans( );
rs.Open( );

// manipulate data

// end transaction 1
db.CommitTrans( );  // or Rollback( )

// close the cursor, start new transaction,
// and get the result set
rs.RequeryWithBeginTrans( );

// manipulate data

// end transaction 2
db.CommitTrans( );  // or Rollback( )

Note Do not use this technique if you need to change the recordset member variables m_strFilter or m_strSort between transactions. In that case, you should close the recordset after each CommitTrans or Rollback operation.


TN069: Processing HTML Forms Using Internet Server Extension DLLs and Command Handlers

Technical Note 69, describing how to use the new MfcISAPICommand parameter in HTML forms, can now be found in Processing HTML Forms Using Internet Server Extension DLLs and Command Handlers.


TN070: MFC Window Class Names

MFC windows use a dynamically created class name that reflects the features of the window. MFC generates class names dynamically for frame windows, views, and popup windows produced by the application. Dialog boxes and controls produced by an MFC application have the Windows-supplied name for the class of window in question.

You can replace the dynamically provided class name by registering your own window class and using it in an override of PreCreateWindow. Their MFC-supplied class names fit one of the two following forms:

Afx:%x:%x
Afx:%x:%x:%x:%x:%x

The hex digits that replace the %x characters are filled in from data from the WNDCLASS structure. MFC uses this technique so that multiple C++ classes requiring identical WNDCLASS structures can share the same registered window class. Unlike most simple Win32 applications, MFC applications have only one WNDPROC, so you can easily share WNDCLASS structures to save time and memory. The replaceable values for the %x characters shown above are as follows:

  • WNDCLASS.hInstance

  • WNDCLASS.style

  • WNDCLASS.hCursor

  • WNDCLASS.hbrBackground

  • WNDCLASS.hIcon

The first form (Afx:%x:%x) is used when hCursor, hbrBackground, and hIcon are all NULL.

Technical Notes by Number | Technical Notes by Category

See Also TN020: ID Naming and Numbering Conventions


TN071: MFC IOleCommandTarget Implementation

The IOleCommandTarget interface enables objects and their containers to dispatch commands to each other. For example, an object's toolbars may contain buttons for commands such as Print, Print Preview, Save, New, and Zoom. If such an object were embedded in a container that supports IOleCommandTarget, the object could enable its buttons and forward the commands to the container for processing when the user clicked them. If a container wanted the embedded object to print itself, it could make this request by sending a command through the IOleCommandTarget interface of the embedded object.

IOleCommandTarget is an Automation-like interface in that it is used by a client to invoke methods on a server. However, using IOleCommandTarget saves the overhead of making calls via Automation interfaces because programmers don't have to use the typically expensive Invoke method of IDispatch.

In MFC, the IOleCommandTarget interface is used by Active document servers to allow Active document containers to dispatch commands to the server. The Active document server class, CDocObjectServerItem, uses MFC interface maps (see TN038: MFC/OLE IUnknown Implementation) to implement the IOleCommandTarget interface.

IOleCommandTarget is also implemented in the COleFrameHook class. COleFrameHook is an undocumented MFC class that implements the frame window functionality of in-place editing containers. COleFrameHook also uses MFC interface maps to implement the IOleCommandTarget interface. COleFrameHook's implementation of IOleCommandTarget forwards OLE commands to COleDocObjectItem-derived Active document containers. This allows any MFC Active document container to receive messages from contained Active document servers.

MFC OLE Command Maps

MFC developers can take advantage of IOleCommandTarget by using MFC OLE command maps. OLE command maps are like message maps because they can be used to map OLE commands to member functions of the class that contains the command map. To make this work, place macros in the command map to specify the OLE command group of the command you want to handle, the OLE command, and the command ID of the WM_COMMAND message that will be sent when the OLE command is received. MFC also provides a number of predefined macros for standard OLE commands. For a list of the standard OLE commands that were originally designed for use with Microsoft Office applications, see the OLECMDID enumeration, which is defined in docobj.h.

When an OLE command is received by an MFC application that contains an OLE command map, MFC tries to find the command ID and command group for the requested command in the OLE command map of the application. If a match is found, a WM_COMMAND message is dispatched to the application containing the command map with the ID of the requested command. (See the description of ON_OLECMD below.) In this way, OLE commands dispatched to an application are turned into WM_COMMAND messages by MFC. The WM_COMMAND messages are then routed through the application's message maps using the MFC standard command routing architecture.

Unlike message maps, MFC OLE command maps are not supported by ClassWizard. MFC developers must add OLE command map support and OLE command map entries by hand. OLE command maps can be added to MFC Active document servers in any class that is in the WM_COMMAND message-routing chain at the time the Active document is in-place active in a container. These classes include the application's classes derived from CWinApp, CView, CDocument, and COleIPFrameWnd. In Active document containers, OLE command maps can only be added to the COleDocObjectItem-derived class. Also, in Active document containers, the WM_COMMAND messages will only be dispatched to the message map in the COleDocObjectItem-derived class.

OLE Command Map Macros

Use the following macros to add command map functionality to your class:

DECLARE_OLECMD_MAP ()

This macro goes in the class declaration (typically in the header file) of the class that contains the command map.

BEGIN_OLECMD_MAP(theClass, baseClass)

theClass

Name of the class that contains the command map.

baseClass

Name of the base class of the class that contains the command map.

This macro marks the beginning of the command map. Use this macro in the implementation file for the class that contains the command map.

END_OLECMD_MAP()

This macro marks the end of the command map. Use this macro in the implementation file for the class that contains the command map. This macro must always follow the BEGIN_OLECMD_MAP macro.

ON_OLECMD(pguid, olecmdid, id)

pguid

Pointer to the GUID of the OLE command's command group. This parameter is NULL for the standard OLE command group.

olecmdid

OLE command ID of the command to be invoked.

id

ID of the WM_COMMAND message to be sent to the application containing the command map when this OLE command is invoked.

Use the ON_OLECMD macro in the command map to add entries for the OLE commands you want to handle. When the OLE commands are received, they will be converted to the specified WM_COMMAND message and routed through the application's message map using the standard MFC command-routing architecture.

Example

The following example shows how to add OLE command-handling capability to an MFC Active document server to handle the OLECMDID_PRINT OLE command. This example assumes that you used AppWizard to generate an MFC application that is an Active document server.

  1. In your CView-derived class's header file, add the DECLARE_OLECMD_MAP macro to the class declaration.

    Note Use the CView-derived class because it is one of the classes in the Active document server that is in the WM_COMMAND message-routing chain.

    class CMyServerView : public CView
{
protected: // create from serialization only
CMyServerView();
DECLARE_DYNCREATE(CMyServerView)
DECLARE_OLECMD_MAP()
. . .
};
  2. In the implementation file for the CView-derived class, add the BEGIN_OLECMD_MAP and END_OLECMD_MAP macros:
    BEGIN_OLECMD_MAP(CMyServerView, CView)

END_OLECMD_MAP()
  3. To handle the standard OLE print command, add an ON_OLECMD macro to the command map specifying the OLE command ID for the standard print command and ID_FILE_PRINT for the WM_COMMAND ID. ID_FILE_PRINT is the standard print command ID used by AppWizard-generated MFC applications:
    BEGIN_OLECMD_MAP(CMyServerView, CView)
ON_OLECMD(NULL,OLECMDID_PRINT,ID_FILE_PRINT)
END_OLECMD_MAP()

Note that one of the standard OLE command macros, defined in afxdocob.h, could be used in place of the ON_OLECMD macro because OLECMDID_PRINT is a standard OLE command ID. The ON_OLECMD_PRINT macro will accomplish the same task as the ON_OLECMD macro shown above.

When a container application sends this server an OLECMDID_PRINT command through the server's IOleCommandTarget interface, the MFC printing command handler will be invoked in the server, causing the server to print the application. The Active document container's code to invoke the print command added in the steps above would look something like this:

void CContainerCntrItem::DoOleCmd()
{
   IOleCommandTarget *pCmd = NULL;
   HRESULT hr = E_FAIL;
   OLECMD ocm={OLECMDID_PRINT, 0};

   hr = m_lpObject->QueryInterface(IID_IOleCommandTarget,reinterpret_cast<void**>(&pCmd));
   if(FAILED(hr))
      return;

   hr = pCmd->QueryStatus(NULL, 1, &ocm, NULL);
   if(SUCCEEDED(hr) && (ocm.cmdf & OLECMDF_ENABLED))
   {
      //Command is available and enabled so call it
      COleVariant vIn;
      COleVariant vOut;
      hr = pCmd->Exec(NULL, OLECMDID_PRINT,
 OLECMDEXECOPT_DODEFAULT, &vIn, &vOut);
      ASSERT(SUCCEEDED(hr));
   }
   pCmd->Release();
}


Active Template Library (ATL) Reference

This reference material helps you understand and use ATL, a set of template-based C++ classes that simplify the programming of Component Object Model (COM) objects. To fully take advantage of ATL, a working familiarity with COM is highly recommended.
ATL Article Overview A short description of each of the ATL articles.
ATL Class Overview A listing of ATL classes sorted by category.
What else do you want to do?
Learn more about OLE
Learn more about ActiveX Controls
Look at some ATL Samples

Interesting home pages


What's New in ATL 2.1

This article provides a general list of features that have been added or changed since ATL 1.1:

  • Compiler Optimization

  • Objects and Controls

  • New and Renamed Classes

  • Connection Points

  • Critical Sections

  • CComBSTR Methods

  • CComVariant Methods

  • Registrar

  • Obsolete Topics

For more information about ATL, see the articles ATL Article Overview and ATL Class Overview.


Compiler Optimization

ATL 2.1 has been optimized for the Visual C++ 5.0 compiler. In particular, you should be aware that many ATL classes are declared with the ATL_NO_VTABLE macro:

class ATL_NO_VTABLE CComControl
{
   ...
};

ATL defines ATL_NO_VTABLE as follows:

#ifdef _ATL_DISABLE_NO_VTABLE
   #define ATL_NO_VTABLE
#else
   #define ATL_NO_VTABLE __declspec(novtable)
#endif

If _ATL_DISABLE_NO_VTABLE is not defined, the ATL_NO_VTABLE macro expands to declspec(novtable). When declspec(novtable) is used in a class declaration, it prevents the vtable pointer from being initialized in the class's constructor and destructor. The linker can thus eliminate the vtable and all the functions pointed to by the vtable, provided the most-derived class (usually CComObject, CComAggObject, or CComPolyObject) does not use declspec(novtable) and will thus initialize the vtable pointer correctly.

By default, the ATL Object Wizard will generate new classes with the ATL_NO_VTABLE macro. As previously described, the declspec(novtable) attribute should only be used with base classes that are not directly creatable. Further, it is unsafe to call virtual functions from the constructor of any object that uses declspec(novtable). You should move any such calls to the FinalConstruct method.

If you are unsure whether you should use the declspec(novtable) attribute, you can remove the ATL_NO_VTABLE macro from any class definition or you globally disable it by specifying #define _ATL_DISABLE_NO_VTABLE in stdafx.h, before all other ATL header files are included.


Objects and Controls

The ATL Object Wizard allows you to insert a variety of different objects and controls into your project, including:

  • Minimal COM objects

  • Full controls

  • Internet Explorer controls

  • Internet Explorer objects

  • Add-in objects

  • Dialog boxes

  • Property pages

  • Active Server components

  • Microsoft Transaction Server components

  • Component Registrar objects

For more information about these objects, see the article Creating an ATL Project. For step-by-step instructions on inserting a control and adding custom properties and events, see the ATL Tutorial.


New and Renamed Classes

Following is a list of all new and renamed classes since ATL 1.1. For an overview of all classes, see the article ATL Class Overview.


New Classes

ATL 2.1 includes 39 new classes, which can be categorized as follows:

IUnknown Implementation | UI Support
Class Factories | Persistence
Thread Pooling | Properties and Property Pages
Threading Models | Data Transfer
Connection Points | Object Safety
Controls | Running Objects
Windows Support | Site Information

IUnknown Implementation

  • CComObjectRootEx Manages reference counting for both aggregated and nonaggregated objects, and allows you to specify a threading model. CComObjectRoot, defined through a typedef statement, uses the default threading model of the server:
    typedef CComObjectRootEx<CComObjectThreadModel>

        CComObjectRoot;
  • CComPolyObject Implements IUnknown for aggregated and nonaggregated objects. Using CComPolyObject avoids having both CComAggObject and CComObject in your module. A single CComPolyObject object handles both aggregated and nonaggregated cases.

Class Factories

  • CComClassFactoryAutoThread Allows objects to be created in multiple apartments.

  • CComClassFactorySingleton Creates a single object.

Thread Pooling

  • CComAutoThreadModule Implements an EXE module, with support for multiple thread-pooled apartments.

  • CComApartment Manages an apartment in a thread-pooled EXE module.

  • CComSimpleThreadAllocator Manages thread selection for an EXE module.

Threading Models

  • CComMultiThreadModelNoCS Provides thread-safe methods for incrementing and decrementing a variable. Does not provide a critical section.

Connection Points

  • IPropertyNotifySinkCP Implements a connection point representing the IPropertyNotifySink interface.

  • CFirePropNotifyEvent Notifies a client's sink that an object's property has changed or is about to change.

Controls

  • CComControl Consists of helper functions and data members that are essential to ATL controls.

  • IOleControlImpl Provides methods necessary for controls.

  • IOleObjectImpl Provides the principal methods through which a container communicates with a control. Manages the activation and deactivation of in-place controls.

  • IQuickActivateImpl Combines initialization into a single call to help containers avoid delays when loading controls.

  • IPointerInactiveImpl Provides minimal mouse interaction for an otherwise inactive control.

Windows Support

  • CWindow Contains methods for manipulating a window. CWindow is the base class for CWindowImpl, CDialogImpl, and CContainedWindow.

  • CWindowImpl Implements a window based on a new window class. Also allows you to subclass or superclass the window.

  • CDialogImpl Implements a dialog box.

  • CContainedWindow Implements a window contained within another object. Allows you to subclass or superclass the window.

  • CWndClassInfo Manages the information of a new window class.

  • CDynamicChain Supports dynamic chaining of message maps.

  • CMessageMap Allows an object to expose its message maps to other objects.

UI Support

  • IOleObjectImpl Provides the principal methods through which a container communicates with a control. Manages the activation and deactivation of in-place controls.

  • IOleInPlaceObjectWindowlessImpl Manages the reactivation of in-place controls. Enables a windowless control to receive messages, as well as to participate in drag and drop operations.

  • IOleInPlaceActiveObjectImpl Assists communication between an in-place control and its container.

  • IViewObjectExImpl Enables a control to display itself directly and to notify the container of changes in its display. Provides support for flicker-free drawing, non-rectangular and transparent controls, and hit testing.

Persistence

  • IPersistStreamInitImpl Allows a client to load and save an object's persistent data to a stream.

  • IPersistStorageImpl Allows a client to load and save an object's persistent data to a storage.

  • IPersistPropertyBagImpl Allows a client to load and save an object's properties to a property bag.

Properties and Property Pages

  • IPropertyPageImpl Manages a particular property page within a property sheet.

  • IPropertyPage2Impl Similar to IPropertyPageImpl, but also allows a client to select a specific property in a property page.

  • IPerPropertyBrowsingImpl Accesses the information in an object's property pages.

  • ISpecifyPropertyPagesImpl Obtains the CLSIDs for the property pages supported by an object.

  • IPersistPropertyBagImpl Stores an object's properties in a client-supplied property bag.

  • CComDispatchDriver Retrieves or sets an object's properties through an IDispatch pointer.

  • CStockPropImpl Implements the stock properties supported by ATL.

Data Transfer

  • IDataObjectImpl Supports Uniform Data Transfer by using standard formats to retrieve and set data. Handles data change notifications by managing connections to advise sinks.

  • CBindStatusCallback Allows an asynchronous moniker to send and receive information about the asynchronous data transfer to and from your object.

Object Safety

  • IObjectSafetyImpl Allows an object to be marked as safe for initialization or safe for scripting.

Running Objects

  • IRunnableObjectImpl Determines if an object is running, forces it to run, or locks it into the running state.

Site Information

  • IObjectWithSiteImpl Retrieves and sets a pointer to an object's site. Used for objects that are not controls.

  • IOleObjectImpl Retrieves and sets a pointer to an object's site. Used for controls.


Renamed Classes

In addition to 39 new classes, 7 classes have been renamed. Through a #define statement, some of the old names remain compatible with ATL 2.1. However, it is recommended that you use the new names. For more information, see Obsolete ATL Topics.

Old name | New name
CcomConnectionPoint | IConnectionPointImpl (Not backward compatible. You must use the new name.)
CcomConnectionPointContainerImpl | IConnectionPointContainerImpl
CcomDualImpl | IDispatchImpl
CcomDynamicArrayCONNECTDATA | CComDynamicUnkArray (Not backward compatible. You must use the new name.)
CcomISupportErrorInfoImpl | ISupportErrorInfoImpl
CcomProvideClassInfo2Impl | IProvideClassInfo2Impl
CcomStaticArrayCONNECTDATA | CComUnkArray (Not backward compatible. You must use the new name.)

New Classes


Connection Points

As described in Obsolete ATL Topics, the following classes have been renamed.

Old name | New name
CComConnectionPointContainerImpl | IconnectionPointContainerImpl
CComConnectionPoint | IconnectionPointImpl
CComDynamicArrayCONNECTDATA | CcomDynamicUnkArray
CComStaticArrayCONNECTDATA | CcomUnkArray

For information about supporting connection points in ATL 2.1, see the article Connection Points.


Critical Sections

In ATL 2.1, you no longer need to pass a CComAutoCriticalSection or CComCriticalSection class member to any of the following macros:

  • COM_INTERFACE_ENTRY_AUTOAGGREGATE

  • COM_INTERFACE_ENTRY_AUTOAGGREGATE_BLIND

  • COM_INTERFACE_ENTRY_CACHED_TEAR_OFF


CComBSTR Methods

The following CComBSTR methods have been added since ATL 1.1:

Method | Description
Append | Appends a string to the CComBSTR object.
AppendBSTR | Appends a BSTR to the CComBSTR object.
Length | Returns the length of CComBSTR object's BSTR member.
ReadFromStream | Loads the CComBSTR object from a stream.
WriteToStream | Saves the CComBSTR object to a stream.
operator += | Appends another CcomBSTR object to your CComBSTR object.


CComVariant Methods

The following CComVariant methods have been added or changed since ATL 1.1:

Method | Description
Attach | Attaches a VARIANT to the CComVariant object.
CComVariant | The constructor takes additional parameter types.
ChangeType | Converts the CcomVariant object to a new type.
Clear | Clears the CcomVariant object.
Copy | Copies a VARIANT to the CcomVariant object.
Detach | Detaches the underlying VARIANT from the CComVariant object.
ReadFromStream | Loads the CComVariant object from a stream.
WriteToStream | Saves the CComVariant object to a stream.
operator = | Takes additional parameter types.


Registrar

The ATL 2.x Registry Component (Registrar) is provided in atl.dll. It no longer supports Automation or the 1.1 methods that operated on a single key. For more information about the Registrar, see The ATL Registry Component (Registrar).


Obsolete Topics

For information about all renamed and obsolete topics in ATL 2.1, see Obsolete ATL Topics.


What's New in ATL 3.0

This article lists features that are new or changed since ATL 2.1.

  • Features

  • Porting from ATL 2.1

  • Classes

  • Macros

For information about obsolete classes, methods, and macros in ATL 3.0, see Obsolete ATL Topics.

See Also

ATL Article Overview

ATL Class Overview

What's New for Visual C++ 6.0


New ATL Features

Add Message Handler for ATL

You can use ClassView or WizardBar to add message handlers for any ATL class that wraps a window. This is similar to adding a message handler to an MFC class. You can also access this command from the context menu in the resource editor (Events).

This feature supports creating both message handlers and event handlers.

This feature is only supported by ClassView and WizardBar, not ClassWizard; you cannot use ClassWizard to invoke this command for ATL classes or ATL dialog boxes.

For more information, see Adding a Message Handler.

ATL Composite Control

This control, based on a dialog template, can itself host multiple controls.

For more information, see Composite Control Fundamentals.

DHTML Control Added to the ATL Object Wizard

The ATL Object Wizard enables you to create a DHTML control; you can create the user interface for a control by having the wizard generate dynamic HTML. For example, the interface for a control could consist of three buttons on an HTML page.

For more information, see ATL Support for DHTML Controls.

ATL Support for Developing MMC Snap-in Tools

The ATL Object Wizard provides support for developing Microsoft Management Console (MMC) snap-ins. Your MMC snap-ins provide Windows NT system administrators with integrated tools, which you have designed for a specific task.

For more information, see MMC Snap-In Wizard.

Data Access Support in the ATL Object Wizard

There is a new category in the ATL Object Wizard called "Data Access." This new category contains two wizards: Consumer and Provider.

For more information, see Creating an OLE DB Consumer and Creating an OLE DB Template Provider.

ATL Support in MFC Projects

There is now greater interoperability between MFC- and ATL-based projects, including support for adding an ATL object to an MFC project. To add ATL support to your MFC project, click New ATL Object on the Insert menu. Click YES to confirm adding ATL support.

For more information, see Adding ATL Support to Your MFC Project

Implementing a Connection Point Is More Automated

To generate a connection point, right-click a class (in ClassView) that implements the BEGIN_COM_MAP macro and choose Implement Connection Point from the shortcut menu. In Visual C++ 5.0, you implemented connection points with the ATL Proxy Generator, which has been removed.

For more information, see Adding Connection Points to an Object.

Implement Interface Wizard

This new feature automates implementing an interface from a typelib. You select an interface from a type library, and the wizard adds stubbed-out functions for the interface and wires up the ATL-specific requirements.

For more information, see Adding a New Interface to an Existing Object or Control.


Porting from ATL 2.1

IObjectSafetyImpl

In ATL 2.1, the IObjectSafetyImpl class marked the control as being safe for scripting. For security reasons, this default has been removed, so you must explicitly specify your safety options using the second template parameters. You must now expose this class using COM_INTERFACE_ENTRY rather than COM_INTERFACE_ENTRY_IMPL.

_ATL_NO_UUIDOF

ATL 3.0 uses the compiler keyword __uuidof( class ) to obtain the corresponding IID for a given class. Because of changes in the COM_INTERFACE_ENTRY macros, now you simply include the header for the interface to use, instead of also linking to a library that defines the matching IIDs for that interface. This change can cause problems if the header was previously generated by an old version of MIDL, or if it was hand-coded and not marked appropriately.

If the declaration for the interface in the header has not been marked with an associated __declspec(uuid), then any attempt to use the __uuidof() keyword for that interface will fail. You can revert to the old style (ATL 2.x) COM_INTERFACE_ENTRY macros by defining _ATL_NO_UUIDOF in your build settings to work around any problems with this new behavior.

New _ATL_DEBUG_INTERFACES

In addition to _ATL_DEBUG_QI and _ATL_DEBUG_REFCOUNT, present in ATL 2.x, there is the new _ATL_DEBUG_INTERFACES, which will trace to the debug console any interface leaks that are detected when _Module.Term is called (when the server shuts down).

See Also

Debugging Tips for ATL Objects

Obsolete Macros

Macro | Comment
COM_INTERFACE_ENTRY_IMPL | Obsolete. Replace with COM_INTERFACE_ENTRY.
COM_INTERFACE_ENTRY_IMPL_IID | Obsolete. Replace with COM_INTERFACE_ENTRY_IID.
CHAIN_MSG_MAP_ALT_DYNAMIC | Obsolete and deleted.
BEGIN_PROPERTY_MAP | Obsolete. Use the new property map macro, BEGIN_PROP_MAP, as described in New Macros.
END_PROPERTY_MAP | Obsolete. Use the new property map macro, END_PROP_MAP, as described in New Macros.


Changes to Classes and Methods

Changes to ATL Classes

New Classes

The following classes are new since ATL 2.1:

Composite Control | CComCompositeControl
Connection Points | IDispEventImpl
MMC Snap-In Support | CSnapInItemImpl CSnapInPropertyPageImpl
Service Provider Support | IServiceProviderImpl
Windows Support | CAxDialogImpl CAxWindow CSimpleDialog CWinTraits CWinTraitsOR CDialogImplBase — see CDialogImpl

See Also

ATL Class Overview

Changes to IObjectSafetyImpl

See the IObjectSafetyImpl section in Porting from ATL 2.1.

Classes Moved to Another Header File

These classes were moved from Atlctl.h to Atlcom.h, to better group the functionality:

CComDispatchDriver

IDispEventImpl

IPersistPropertyBagImpl

IPersistStreamInitImpl

Changes to CComPtr and CComQIPtr

The following methods were added to CComPtr and CComQIPtr, for increased functionality. (The following links go to the CComPtr topics.)

  • operator ==

  • operator <

  • IsEqualObject

  • Attach

  • Detach

  • CopyTo

  • SetSite

  • Advise

  • CoCreateInstance

  • QueryInterface

The second template argument to CComQIPtr now defaults to __uuidof(T) where T is the first template argument. As a result, in most cases, you no longer must specify the second template parameter. The exception to this rule is for CComQIPtr objects that are of type IUnknown. They must still be declared using the two-template parameter syntax:

CComQIPtr<IUnknown, &IID_IUnknown> spUnk;

This limitation is minor, because it is unusual to use a CComQIPtr for holding an IUnknown.

Changes to CWindow

CWindow has the following new methods:

  • CWindow::SendMessage

  • CWindow::ResizeClient

  • CWindow::Create

Changes to CWindowImpl, CDialogImpl, and CContainedWindow

CWindowImpl, CDialogImpl, and CContainedWindow now do automatic unsubclassing when required.

These classes also have the following new template arguments:

  • Base class (the default is CWindow)

  • Style class (the default is CWinTraits)


New Maps, Map Entries, and DECLARE's

New Macros

New Map Type Macros

Property Maps | BEGIN_PROP_MAP END_PROP_MAP PROP_DATA_ENTRY
Category Maps | BEGIN_CATEGORY_MAP IMPLEMENTED_CATEGORY REQUIRED_CATEGORY END_CATEGORY_MAP
Service Maps | BEGIN_SERVICE_MAP SERVICE_ENTRY SERVICE_ENTRY_CHAIN END_SERVICE_MAP

Other Macros

Object map macro | OBJECT_ENTRY_NON_CREATEABLE
Message map macros REFLECT_NOTIFICATIONS

DEFAULT_REFLECTION_HANDLER

DECLARE_EMPTY_MSG_MAP
Window macro | DECLARE_WND_CLASS_EX
View macro | DECLARE_VIEW_STATUS
Debug macros _ASSERTE macro

_ATL_DEBUG_INTERFACES
Porting support macro | _ATL_NO_UUIDOF (See Porting from ATL 2.1 for details.)
COM interface entry macros COM_INTERFACE_ENTRY

COM_INTERFACE_ENTRY_IID

New Messages

WM_FORWARDMSG


ATL Article Overview

Porting from ATL 2.1

Articles in the Active Template Library (ATL) consist of the following:

Introduction to COM and ATL introduces the major concepts behind the Component Object Model (COM). This article also briefly explains what ATL is and when you should use it.

Creating an ATL Project contains information on the ATL COM AppWizard and ATL Object Wizard.

Fundamentals of ATL COM Objects discusses the relationship among various ATL classes and how those classes are implemented.

Composite Control Fundamentals provides step-by-step instructions for creating a composite control. A composite control is a type of ActiveX control that can contain other ActiveX controls or Windows controls.

ATL Support for DHTML Controls provides step-by-step instructions for creating a DHTML control.

MMC Snap-In Wizard discusses ATL support for Microsoft Management Console (MMC) Snap-In components.

ATL Window Classes describes how to create, superclass, and subclass windows in ATL.

Connection Points explains what connection points are and how ATL implements them.

Enumerators describes the implementation and creation of enumerators in ATL.

Debugging Tips for ATL Objects tells you how to use ATL's built-in support for debugging QueryInterface, AddRef, and Release calls.

ATL Services covers the series of events that occur when a service is implemented. It also talks about some of the concepts related to developing a service.

The ATL Registry Component (Registrar) discusses ATL scripting syntax and replaceable parameters. It also explains how to set up a static link to the Registrar.

See Also

ATL Class Overview

ATL Tutorial


ATL Class Overview

Classes in the Active Template Library (ATL) can be categorized as follows:

Class Factories | Object Safety
Class Information | Persistence
COM Modules | Properties and Property Pages
Composite Control | Registry Support
Connection Points | Running Objects
Controls: General Support | Service Provider Support
Data Transfer | Site Information
Data Types | Tear-Off Interfaces
Dual Interfaces | Thread Pooling
Error Information | Threading Models and Critical Sections
Interface Pointers | UI Support
IUnknown Implementation | Windows Support
MMC Snap-In |

See Also ATL Article Overview, Porting from ATL 2.1


Class Factories

The following classes implement or support a class factory:

  • CComClassFactory Provides a default class factory for object creation.

  • CComClassFactory2 Controls object creation through a license.

  • CComClassFactoryAutoThread Allows objects to be created in multiple thread-pooled apartments.

  • CComClassFactorySingleton Creates a single object.

  • CComCoClass Defines the class factory for the object.

ATL Class Overview

See Also Aggregation and Class Factory Macros


Class Information

The following class provides support for retrieving class information:

  • IProvideClassInfo2Impl Provides access to type information. Retrieves the outgoing IID for the object’s default event set.

ATL Class Overview


COM Modules

The following classes provide support for a COM module:

  • CComModule Implements a DLL or EXE module.

  • CComAutoThreadModule Implements an EXE module, with support for multiple thread-pooled apartments.

ATL Class Overview


Composite Control

The following class provides support for creating composite controls

  • CComCompositeControl ActiveX controls derived from CComCompositeControl are hosted by a standard dialog box. These types of controls are called composite controls because they are able to host other controls (native Windows controls and ActiveX controls).

ATL Class Overview

Related Articles Composite Control Fundamentals


Connection Points

The following classes provide support for connection points:

  • IConnectionPointContainerImpl Implements a connection point container.

  • IConnectionPointImpl Implements a connection point.

  • IPropertyNotifySinkCP Implements a connection point representing the IPropertyNotifySink interface.

  • CComDynamicUnkArray Manages unlimited connections between a connection point and its sinks.

  • CComUnkArray Manages a fixed number of connections between a connection point and its sinks.

  • CFirePropNotifyEvent Notifies a client’s sink that an object’s property has changed or is about to change.

  • IDispEventImpl Provides support for connection points for an ATL COM object. These connection points are mapped with an event sink map, which is provided by your COM object.

ATL Class Overview

Related Articles Connection Points

See Also Connection Point Macros and Global Functions


Controls: General Support

The following classes provide general support for ATL controls:

  • CComControl Consists of helper functions and data members that are essential to ATL controls.

  • IOleControlImpl Provides methods necessary for controls.

  • IOleObjectImpl Provides the principal methods through which a container communicates with a control. Manages the activation and deactivation of in-place controls.

  • IQuickActivateImpl Combines initialization into a single call to help containers avoid delays when loading controls.

  • IPointerInactiveImpl Provides minimal mouse interaction for an otherwise inactive control.

ATL Class Overview

Sample Programs

ATLFire | ATLTangram

Related Articles ATL Tutorial


Data Transfer

The following classes support various types of data transfer:

  • IDataObjectImpl Supports Uniform Data Transfer by using standard formats to retrieve and set data. Handles data change notifications by managing connections to advise sinks.

  • CBindStatusCallback Allows an asynchronous moniker to send and receive information about the asynchronous data transfer to and from your object.

ATL Class Overview


Data Types

The following classes wrap C++ data types:

  • CComBSTR Wraps the BSTR data type.

  • CComVariant Wraps the VARIANT data type.

ATL Class Overview


Dual Interfaces

The following class provides support for dual interfaces:

  • IDispatchImpl Implements the IDispatch portion of a dual interface.

ATL Class Overview


Error Information

The following class indicates how error information is handled:

  • ISupportErrorInfoImpl Determines whether the object supports the IErrorInfo interface. IErrorInfo allows error information to be propagated back to the client.

ATL Class Overview


Interface Pointers

The following classes manage a given interface pointer:

  • CComPtr Performs automatic reference counting.

  • CComQIPtr Similar to CComPtr, but also performs automatic querying of interfaces.

ATL Class Overview


IUnknown Implementation

The following classes implement IUnknown and related methods:

  • CComObjectRootEx Manages reference counting for both aggregated and nonaggregated objects. Allows you to specify a threading model.

  • CComObjectRoot Manages reference counting for both aggregated and nonaggregated objects. Uses the default threading model of the server.

  • CComAggObject Implements IUnknown for an aggregated object.

  • CComObject Implements IUnknown for a nonaggregated object.

  • CComPolyObject Implements IUnknown for aggregated and nonaggregated objects. Using CComPolyObject avoids having both CComAggObject and CComObject in your module. A single CComPolyObject object handles both aggregated and nonaggregated cases.

  • CComObjectNoLock Implements IUnknown for a nonaggregated object, without modifying the module lock count.

  • CComTearOffObject Implements IUnknown for a tear-off interface.

  • CComCachedTearOffObject Implements IUnknown for a “cached” tear-off interface.

  • CComContainedObject Implements IUnknown for the inner object of an aggregation or a tear-off interface.

  • CComObjectGlobal Manages a reference count on the module to ensure your object won’t be deleted.

  • CComObjectStack Creates a temporary COM object, using a skeletal implementation of IUnknown.

ATL Class Overview

Related Articles Fundamentals of ATL COM Objects

See Also Aggregation and Class Factory Macros, COM Map Macros and Global Functions


MMC Snap-In

The following classes provide support for developing Microsoft Management Console (MMC) snap-in components.

  • CSnapInItemImpl Implements a snap-in node object, such as adding menu items and toolbars, and forwarding commands for the snap-in node to the appropriate handler function.

  • CSnapInPropertyPageImpl Implements a snap-in property page object.

ATL Class Overview

Related Articles MMC Snap-In Wizard


Object Safety

The following class provides support for object safety:

  • IObjectSafetyImpl Allows an object to be marked as safe for initialization or safe for scripting.

ATL Class Overview

Related Articles ATL Tutorial


Persistence

The following classes implement object persistence:

  • IPersistStreamInitImpl Allows a client to load and save an object’s persistent data to a stream.

  • IPersistStorageImpl Allows a client to load and save an object’s persistent data to a storage.

  • IPersistPropertyBagImpl Allows a client to load and save an object’s properties to a property bag.

ATL Class Overview

Related Articles ATL Tutorial

See Also Property Map Macros


Properties and Property Pages

The following classes support properties and property pages:

  • IPropertyPageImpl Manages a particular property page within a property sheet.

  • IPropertyPage2Impl Similar to IPropertyPageImpl, but also allows a client to select a specific property in a property page.

  • IPerPropertyBrowsingImpl Accesses the information in an object’s property pages.

  • ISpecifyPropertyPagesImpl Obtains the CLSIDs for the property pages supported by an object.

  • IPersistPropertyBagImpl Stores an object’s properties in a client-supplied property bag.

  • CComDispatchDriver Retrieves or sets an object’s properties through an IDispatch pointer.

  • CStockPropImpl Implements the stock properties supported by ATL.

ATL Class Overview

Related Articles ATL Tutorial

See Also Property Map Macros, Stock Property Macros


Registry Support

The following class provides registry support:

  • CRegKey Contains methods for manipulating values in the system registry.

ATL Class Overview

Related Articles The ATL Registry Component (Registrar)

See Also Registry Macros


Running Objects

The following class provides support for running objects:

  • IRunnableObjectImpl Determines if an object is running, forces it to run, or locks it into the running state.

ATL Class Overview

Related Articles ATL Tutorial


Service Provider Support

The following class provides support for service providers:

  • IServiceProviderImpl Locates a service specified by its GUID and returns the interface pointer for the requested interface on the service.

ATL Class Overview


Site Information

The following classes allow an object to communicate with its site:

  • IObjectWithSiteImpl Retrieves and sets a pointer to an object’s site. Used for objects that are not controls.

  • IOleObjectImpl Retrieves and sets a pointer to an object’s site. Used for controls.

ATL Class Overview


Tear-Off Interfaces

The following classes provide support for tear-off interfaces:

  • CComTearOffObject Implements IUnknown for a tear-off interface.

  • CComCachedTearOffObject Implements IUnknown for a “cached” tear-off interface.

ATL Class Overview


Thread Pooling

The following classes support thread pooling:

  • CComAutoThreadModule Implements an EXE module, with support for multiple thread-pooled apartments.

  • CComApartment Manages an apartment in a thread-pooled EXE module.

  • CComSimpleThreadAllocator Manages thread selection for an EXE module.

ATL Class Overview


Threading Models and Critical Sections

The following classes define a threading model and critical section:

  • CComMultiThreadModel Provides thread-safe methods for incrementing and decrementing a variable. Provides a critical section.

  • CComMultiThreadModelNoCS Provides thread-safe methods for incrementing and decrementing a variable. Does not provide a critical section.

  • CComSingleThreadModel Provides methods for incrementing and decrementing a variable. Does not provide a critical section.

  • CComObjectThreadModel Determines the appropriate threading-model class for a single object class.

  • CComGlobalsThreadModel Determines the appropriate threading-model class for an object that is globally available.

  • CComAutoCriticalSection Contains methods for obtaining and releasing a critical section. The critical section is automatically initialized.

  • CComCriticalSection Contains methods for obtaining and releasing a critical section. The critical section must be explicitly initialized.

  • CComFakeCriticalSection Mirrors the methods in CComCriticalSection without providing a critical section. The methods in CComFakeCriticalSection do nothing.

ATL Class Overview


UI Support

The following classes provide general UI support:

  • IOleObjectImpl Provides the principal methods through which a container communicates with a control. Manages the activation and deactivation of in-place controls.

  • IOleInPlaceObjectWindowlessImpl Manages the reactivation of in-place controls. Enables a windowless control to receive messages, as well as to participate in drag and drop operations.

  • IOleInPlaceActiveObjectImpl Assists communication between an in-place control and its container.

  • IViewObjectExImpl Enables a control to display itself directly and to notify the container of changes in its display. Provides support for flicker-free drawing, non-rectangular and transparent controls, and hit testing.

ATL Class Overview

Related Articles ATL Tutorial


Windows Support

The following classes provide support for windows:

  • CWindow Contains methods for manipulating a window. CWindow is the base class for CWindowImpl, CDialogImpl, and CContainedWindow.

  • CWindowImpl Implements a window based on a new window class. Also allows you to subclass or superclass the window.

  • CDialogImpl Implements a dialog box.

  • CAxDialogImpl Implements a dialog box (modal or modeless) that hosts ActiveX controls.

  • CSimpleDialog Implements a dialog box (modal or modeless) with basic functionality.

  • CAxWindow Manipulates a window that hosts an ActiveX control.

  • CContainedWindow Implements a window contained within another object. Allows you to subclass or superclass the window.

  • CWndClassInfo Manages the information of a new window class.

  • CDynamicChain Supports dynamic chaining of message maps.

  • CMessageMap Allows an object to expose its message maps to other objects.

  • CWinTraits Provides a simple method of standardizing the traits of an ATL window object.

  • CWinTraitsOR Provides default values for window styles and extended styles used to create a window. These values are added, using the logical-OR operator, to values provided during the creation of a window.

ATL Class Overview

Related Articles ATL Window Classes, ATL Tutorial

See Also Message Map Macros, Window Class Macros


ATL Tutorial

With ATL, you can create efficient, flexible, lightweight controls. This tutorial leads you through the creation of a control and demonstrates some ATL fundamentals in the process.

The ATL control that you create in this seven-step tutorial draws a circle and a filled polygon inside the circle. You will add a control to your project, add a Sides property to indicate how many sides the polygon will have, and add drawing code to display your control when the property changes. Then, you will make your control respond to click events, add a property page to your control, and put your control on a Web page.

The tutorial is divided into seven steps. Do them in order because later steps depend on tasks you have completed in earlier steps.

  • Step 1: Creating the Project

  • Step 2: Adding a Control to Your Project

  • Step 3. Adding a Property to Your Control

  • Step 4: Changing Your Control's Drawing Code

  • Step 5: Adding an Event to Your Control

  • Step 6: Adding a Property Page to Your Control

  • Step 7: Putting Your Control on a Web Page

  • ATL References


Step 1: Creating the Project

First you will create the initial ATL project using the ATL COM AppWizard.

  1. In the Visual C++ environment, click New on the File menu, then choose the Projects tab.

  2. Select the ATL COM AppWizard.

  3. Type Polygon as the project name.

Your dialog box should look like this:

Click OK and the ATL COM AppWizard presents a dialog box offering several choices to configure the initial ATL project.

Because you are creating a control leave the Server Type as a DLL, since a control must be an in-process server. All the default options are fine, so click Finish. A dialog box appears that lists the main files that will be created. These files are listed below, along with a description of each file that the ATL COM AppWizard generates.

File | Description
Polygon.cpp | Contains the implementation of DllMain, DllCanUnloadNow, DllGetClassObject, DllRegisterServer and DllUnregisterServer. Also contains the object map, which is a list of the ATL objects in your project. This is initially blank, since you haven't created an object yet.
Polygon.def | The standard Windows module definition file for the DLL.
Polygon.dsw | The project workspace.
Polygon.dsp | The file that contains the project settings.
Polygon.idl | The interface definition language file, which describes the interfaces specific to your objects.
Polygon.rc | The resource file, which initially contains the version information and a string containing the project name.
Resource.h | The header file for the resource file.
Polygonps.mk | The make file that can be used to build a proxy/stub DLL. You will not need to use this.
Polygonps.def | The module definition file for the proxy/stub DLL.
StdAfx.cpp | The file that will #include the ATL implementation files.
StdAfx.h | The file that will #include the ATL header files.

To make the Polygon DLL useful, you need to add a control, using the ATL Object Wizard.

On to Step 2


Step 2: Adding a Control

To add an object to an ATL project, you use the ATL Object Wizard. Click New ATL Object on the Insert menu, and the ATL Object Wizard appears.

In the first ATL Object Wizard dialog box, select the category of object you want to add to your current ATL project. Some of the options you can select are a basic COM object, a control tailored to work in Internet Explorer, and a property page. In this tutorial, you will create a standard control, so set the category as Controls on the left, then on the right select Full Control. Finally, click Next.

A set of property pages is displayed that allows you to configure the control you are inserting into your project. Type "PolyCtl" as the short name. The other fields are automatically completed.

The Class field shows the C++ class name created to implement the control. The .H File and .CPP File fields show the files created to contain the definition of the C++ class. The CoClass is the name of the component class for this control, and Interface is the name of the interface on which your control will implement its custom methods and properties. The Type is a description for the control, and the ProgID is the readable name that can be used to look up the CLSID of the control.

Now enable support for rich error information and connection points for your control:

  1. Click on the Attributes tab.

  2. Click the Support ISupportErrorInfo check box.

  3. Click the Support Connection Points check box. This will create support for an outgoing interface in the IDL file.

You will color in the polygon when you draw it, so add a Fill Color stock property:

  1. Click on the Stock Properties tab.
    You see a list box with all the possible stock properties you can enter.

  2. Scroll down the list, then double-click Fill Color to move it to the Supported list.

You are finished selecting options for your control. Click OK.

When you created your control, several code changes and additions were made. The following files were created:

File | Description
PolyCtl.h | Contains most of the implementation of the C++ class CPolyCtl.
PolyCtl.cpp | Contains the remaining parts of CPolyCtl.
PolyCtl.rgs | A text file that contains the registry script used to register the control.
PolyCtl.htm | An HTML file that contains the source of a Web page that contains a reference to the newly created control, so that you can try it out in Internet Explorer immediately.

The Wizard also performed the following code changes:

  • A #include was added to the StdAfx.h and StdAfx.cpp files to include the ATL files necessary for controls.

  • The registry script PolyCtl.rgs was added to the project resource.

  • Polygon.idl was changed to include details of the new control.

  • The new control was added to the object map in Polygon.cpp.

The file PolyCtl.h is the most interesting because it contains the main code that implements your control.

You are now ready to build your control:

  1. On the Build menu click Build Polygon.dll.

  2. Once your control has finished building, click ActiveX Control Test Container on the Tools menu. The Test Container is launched.

  3. In Test Container, choose Insert New Control from the Edit menu. The Insert Control dialog box appears.

  4. From the list of available controls in the Insert Control dialog box, choose PolyCtl class.
    You should see a rectangle with the text "ATL 3.0 : PolyCtl" in the middle.

  5. Close Test Container.

Next, you will add a custom property to the control.


Step 3: Adding a Property to the Control

IPolyCtl is the interface that contains your custom methods and properties. The easiest way to add a property to this interface is to right-click it in ClassView and select Add Property.

The Add Property to Interface dialog box appears, allowing you to enter the details of the property you want to add:

  1. On the drop-down list of property types, select short.

  2. Type "Sides" as the Property Name. As you edit the Property Name field, the Implementation box shows the lines that will be added to your IDL file.

  3. Click OK to finish adding the property.

MIDL (the program that compiles .idl files) defines a Get method that retrieves the property and a Put method that sets the property. When MIDL compiles the file, it automatically defines those two methods in the interface by prepending put_ and get_ to the property name.

Along with adding the necessary lines to the .idl file, the Add Property to Interface dialog box also adds the Get and Put function prototypes to the class definition in PolyCtl.h and adds an empty implementation to PolyCtl.cpp.

To set and retrieve the property you need a place to store it. From FileView, open PolyCtl.h and add the following line at the end of the class definition after m_clrFillColor is defined:

     short m_nSides;

Now you can implement the Get and Put methods. The get_Sides and put_Sides function definitions have been added to PolyCtl.h. You need to add code in PolyCtl.cpp to match the following:

STDMETHODIMP CPolyCtl::get_Sides(short *pVal)
{
   *pVal = m_nSides;
   return S_OK;
}

STDMETHODIMP CPolyCtl::put_Sides(short newVal)
{
   if (newVal > 2 && newVal < 101)
   {
      m_nSides = newVal;
      return S_OK;
   }
   else
      return Error(_T("Shape must have between 3 and 100 sides"));
}

The get_Sides function simply returns the current value of the Sides property through the pVal pointer. In the put_Sides method, you make sure the user is setting the Sides property to an acceptable value. You need more than 2 sides, and since you will be storing an array of points for each side later on, 100 is a reasonable limit for a maximum value. If an invalid value is passed you use the ATL Error function to set the details in the IErrorInfo interface. This is useful if your container needs more information about the error than the returned HRESULT.

The last thing you need to do for the property is initialize m_nSides. Make a triangle the default shape by adding a line to the constructor in PolyCtl.h:

CPolyCtl()
{
   m_nSides = 3;
}

You now have a property called Sides. It's not much use until you do something with it, so next you will change the drawing code to use it.


Step 4: Changing the Drawing Code

In the drawing code you will use sin and cos functions to calculate the polygon points, so add include math.h at the top of PolyCtl.h:

#include <math.h>
#include "resource.h"       // main symbols

Note for Release builds only When the ATL COM AppWizard generates the default project, it defines the macro _ATL_MIN_CRT. This macro is defined so that you don't bring the C Run-Time Library into your code if you don't need it. The polygon control needs the C Run-Time Library start-up code to initialize the floating-point functions. Therefore, you need to remove the _ATL_MIN_CRT macro if you want to build a Release version. To remove the macro, click Settings on the Project menu. In the Settings For: drop-down list, choose Multiple Configurations. In the Select project configuration(s) to modify dialog box that appears, click the check boxes for all four Release versions, then click OK. On the C/C++ tab, choose the General category, then remove _ATL_MIN_CRT from the Preprocessor definitions edit box.

Once the polygon points are calculated, you store the points by adding an array of type POINT to the end of the class definition in PolyCtl.h:

   OLE_COLOR m_clrFillColor;
   short m_nSides;
   POINT m_arrPoint[100];

Now change the OnDraw function in PolyCtl.h to match the one below. Note that you remove the calls to the Rectangle and DrawText functions. You also explicitly get and select a black pen and white brush. You need to do this in case your control is running windowless. If you don't have your own window, you can't make assumptions about the device context you'll be drawing in.

The completed OnDraw looks like this:

HRESULT CPolyCtl::OnDraw(ATL_DRAWINFO& di)
{
   RECT& rc = *(RECT*)di.prcBounds;
   HDC hdc  = di.hdcDraw;

   COLORREF    colFore;
   HBRUSH      hOldBrush, hBrush;
   HPEN        hOldPen, hPen;

   // Translate m_colFore into a COLORREF type
   OleTranslateColor(m_clrFillColor, NULL, &colFore);

   // Create and select the colors to draw the circle
   hPen = (HPEN)GetStockObject(BLACK_PEN);
   hOldPen = (HPEN)SelectObject(hdc, hPen);
   hBrush = (HBRUSH)GetStockObject(WHITE_BRUSH);
   hOldBrush = (HBRUSH)SelectObject(hdc, hBrush);

   Ellipse(hdc, rc.left, rc.top, rc.right, rc.bottom);

   // Create and select the brush that will be used to fill the polygon
   hBrush    = CreateSolidBrush(colFore);
   SelectObject(hdc, hBrush);

   CalcPoints(rc);
   Polygon(hdc, &m_arrPoint[0], m_nSides);

   // Select back the old pen and brush and delete the brush we created
   SelectObject(hdc, hOldPen);
   SelectObject(hdc, hOldBrush);
   DeleteObject(hBrush);

   return S_OK;
}

You now need to add a function, called CalcPoints, that will calculate the coordinates of line intersections. These calculations will be based on the RECT variable that is passed into the function. First you should add the definition of CalcPoints to the public section for the IPolyCtl class in PolyCtl.h:

void    CalcPoints(const RECT& rc);

The public section of the IPolyCtl class should now look like this:

// IPolyCtl
public:
   STDMETHOD(get_Sides)(/*[out, retval]*/ short *newVal);
   STDMETHOD(put_Sides)(/*[in]*/ short newVal);
   void    CalcPoints(const RECT& rc);

Next, add the implementation of the CalcPoints function to the end of the PolyCtl.cpp file:

void CPolyCtl::CalcPoints(const RECT& rc)
{
   const double pi = 3.14159265358979;
   POINT   ptCenter;
   double  dblRadiusx = (rc.right - rc.left) / 2;
   double  dblRadiusy = (rc.bottom - rc.top) / 2;
   double  dblAngle = 3 * pi / 2;          // Start at the top
   double  dblDiff  = 2 * pi / m_nSides;   // Angle each side will make
   ptCenter.x = (rc.left + rc.right) / 2;
   ptCenter.y = (rc.top + rc.bottom) / 2;

   // Calculate the points for each side
   for (int i = 0; i < m_nSides; i++)
   {
      m_arrPoint[i].x = (long)(dblRadiusx * cos(dblAngle) + ptCenter.x + 0.5);
      m_arrPoint[i].y = (long)(dblRadiusy * sin(dblAngle) + ptCenter.y + 0.5);
      dblAngle += dblDiff;
   }
}

Now, initialize m_clrFillColor. Choose green as the default color and add this line to the CPolyCtl constructor in PolyCtl.h:

   m_clrFillColor = RGB(0, 0xFF, 0);

The constructor now looks like this:

CPolyCtl()
{
   m_nSides = 3;
   m_clrFillColor = RGB(0, 0xFF, 0);
}

Now rebuild the control and try it again. Open ActiveX Control Test Container and insert the control. You should see a green triangle within a circle. Try changing the number of sides by following the steps below. To modify properties on a dual interface from within Test Container, use Invoke Methods:

  1. In Test Container, click Invoke Methods on the Control menu.
    The Invoke Method dialog box is displayed.

  2. Click the PropPut version of the Sides property from the Method Name.

  3. Type 5 in the Parameter Value edit box, click Set Value and click Invoke.

Notice that the control doesn't change. What is wrong? Although you changed the number of sides internally by setting the m_nSides variable, you didn't cause the control to repaint. If you switch to another application and then switch back to Test Container you will find that the control is repainted and now has the correct number of sides.

To correct this problem, you need to add a call to the FireViewChange function, which is defined in IViewObjectExImpl, after you set the number of sides. If the control is running in its own window, FireViewChange will call the InvalidateRect API directly. If the control is running windowless, the InvalidateRect method will be called on the container's site interface. This forces the control to repaint itself.

The new put_Sides method is as follows:

STDMETHODIMP CPolyCtl::put_Sides(short newVal)
{
   if (newVal > 2 && newVal < 101)
   {
      m_nSides = newVal;
      FireViewChange();
      return S_OK;
   }
   else
      return Error(_T("Shape must have between 3 and 100 sides"));
}

After you've added FireViewChange, rebuild and try the control again. This time when you change the number of sides and click Invoke, you should see the control change immediately.

Next, you will add an event to the control.


Step 5: Adding an Event

Now you will add a ClickIn and a ClickOut event to your ATL control. You will fire the ClickIn event if the user clicks within the polygon and fire ClickOut if the user clicks outside.

When you created the full control in Step 2, you selected the Support Connection Points check box. This created the IPolyCtlEvents interface in your .idl file. Note that the interface name starts with an underscore. This is a convention to indicate that the interface is an internal interface. Thus, programs that allow you to browse COM objects can choose not to display the interface to the user. Also notice in the .idl file that Support Connection Points added a line to indicate that IPolyCtlEvents is the default source interface. The source attribute indicates that the control is the source of the notifications, so it will call this interface on the container.

Now you should add the ClickIn and ClickOut methods to the IPolyCtlEvents interface:

  1. Right click on IPolyCtlEvents in ClassView and selecting Add Method… from the popup menu.

  2. Select a Return Type of void.

  3. Type ClickIn in the Method Name box.

  4. Enter [in] long x, [in] long y in the Parameters box.

  5. Click OK.

Check the .idl file to see that the code was added as a method to the IPolyCtlEvents dispinterface. Then use the same procedure to define a ClickOut method with the same parameters and return type. The IPolyCtlEvents dispinterface in your .idl file should now look like this:

dispinterface _IPolyCtlEvents
{
   properties:
   methods:
   [id(1), helpstring("method ClickIn")] void ClickIn([in]long x, [in] long y);
   [id(2), helpstring("method ClickOut")] void ClickOut([in] long x, [in] long y);
};

The ClickIn and ClickOut methods that take the x and y coordinates of the clicked point as parameters.

Now generate your type library. To do this you can either rebuild your project or right-click the .idl file in FileView and click Compile Polygon.idl. This will create the Polygon.tlb file, which is your type library.

Next, implement a connection point interface and a connection point container interface for your control. (In COM, events are implemented through the mechanism of connection points. To receive events from a COM object, a container establishes an advisory connection to the connection point that the COM object implements. Since a COM object can have multiple connection points, the COM object also implements a connection point container interface. Through this interface, the container can determine which connection points are supported.) The interface that implements a connection point is called IConnectionPoint and the interface that implements a connection point container is called IConnectionPointContainer.

To help implement IConnectionPoint, use ClassView to access a connection point wizard. This wizard generates the IConnectionPoint interface by reading your type library and implementing a function for each event that can be fired.

To run the wizard, follow these steps:

  1. Go to ClassView (on the View menu, click Workspace to see ClassView).

  2. Right click on your control's implementation class, in this case CPolyCtl.

  3. In the shortcut menu, select Implement Connection Point….

  4. Select _PolyEvents from the Interfaces list then click OK and a proxy class for the connection point will be generated, in this case, CProxy_IPolyCtlEvents.

If you look at the generated PolygonCP.h file in FileView, you see it has a class called CProxy_PolyCtlEvents that derives from IConnectionPointImpl. PolygonCP.h also defines the two methods Fire_ClickIn and Fire_ClickOut, which take the two coordinate parameters. These are the methods you call when you want to fire an event from your control.

The wizard also added the CProxy_PolyEvents and IConnectionPointContainerImpl to your control's multiple inheritance list. The wizard also exposed IConnectionPointContainer for you by adding appropriate entries to the COM map.

You are finished implementing the code to support events. Now, add some code to fire the events at the appropriate moment. Remember, you are going to fire a ClickIn or ClickOut event when the user clicks the left mouse button in the control. To find out when the user clicks the button, first add a handler for the WM_LBUTTONDOWN message. In ClassView, right click on the CPolyCtl class and select Add Windows Message Handler... from the shortcut menu. Then select WM_LBUTTONDOWN from the list on the left and click the Add Handler button. Click OK.

Next, add new code to the OnLButtonDown function in PolyCtl.h (deleting any code placed by the wizard) so that OnLButtonDown now looks like this:

LRESULT CPolyCtl::OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   HRGN hRgn;
   WORD xPos = LOWORD(lParam);  // horizontal position of cursor
   WORD yPos = HIWORD(lParam);  // vertical position of cursor

   CalcPoints(m_rcPos);

   // Create a region from our list of points
   hRgn = CreatePolygonRgn(&m_arrPoint[0], m_nSides, WINDING);

   // If the clicked point is in our polygon then fire the ClickIn
   //  event otherwise we fire the ClickOut event
   if (PtInRegion(hRgn, xPos, yPos))
      Fire_ClickIn(xPos, yPos);
   else
      Fire_ClickOut(xPos, yPos);

   // Delete the region that we created
   DeleteObject(hRgn);
   return 0;
}

Since you have already calculated the points of the polygon in the OnDraw function, use them in OnLButtonDown to create a region. Then, use the PtInRegion API function to determine whether the clicked point is inside the polygon or not.

The uMsg parameter is the ID of the Windows message being handled. This allows you to have one function that handles a range of messages. The wParam and the lParam are the standard values for the message being handled. The parameter bHandled allows you to specify whether the function handled the message or not. By default, the value is set to TRUE to indicate that the function handled the message, but you can set it to FALSE. Doing so will cause ATL to continue looking for another message handler function to which to send the message.

Now try out your events. Build the control and start ActiveX Control Test Container again. This time, view the event log window. To route events to the output window, select Logging from the Options menu and select Log to output window. Now insert the control and try clicking in the window. Notice that ClickIn is fired if you click within the filled polygon and ClickOut is fired when you click outside of it.

Next you will add a property page.


Step 6: Adding a Property Page

Property pages are implemented as separate COM objects, which allow property pages to be shared if required. To add a property page to your control you can use the ATL Object Wizard.

Start the ATL Object Wizard and select Controls as the category on the left. Select Property Page on the right, then click Next.

You again get the dialog box allowing you to enter the name of the new object. Call the object PolyProp and enter that name in the Short Name edit box.

Notice that the Interface edit box is grayed out. This is because a property page doesn't need a custom interface.

Click on the Strings tab to set the title of the property page. The title of the property page is the string that appears in the tab for that page. Type &Polygon as the title. The Doc String is a description that a property frame uses to put in a status line or tool tip. Note that the standard property frame currently doesn't use this string, but you can set it anyway. You're not going to generate a Helpfile at the moment, so erase the entry in that text box. Click OK and the property page object will be created.

The following three files are created:

File | Description
PolyProp.h | Contains the C++ class CPolyProp, which implements the property page.
PolyProp.cpp | Includes the PolyProp.h file.
PolyProp.rgs | The registry script that registers the property page object.

The following code changes are also made:

  • The new property page is added to the object entry map in Polygon.cpp.

  • The PolyProp class is added to the Polygon.idl file.

  • The new registry script file PolyProp.rgs is added to the project resource.

  • A dialog box template is added to the project resource for the property page.

  • The property strings you specified are added to the resource string table.

Now add the fields that you want to appear on the property page. Notice that in Polygon.rc the dialog is empty except for a label that tells you to insert your controls here. Delete that label and add one that contains the text "Sides:". Next to the label add an edit box and give it an ID of IDC_SIDES.

Include Polygon.h at the top of the PolyProp.h file:

#include "Polygon.h"  // definition of IPolyCtl

Now enable the CPolyProp class to set the number of sides in your object when the Apply button is pressed. Change the Apply function in PolyProp.h as follows.

STDMETHOD(Apply)(void)
{
   USES_CONVERSION;
   ATLTRACE(_T("CPolyProp::Apply\n"));
   for (UINT i = 0; i < m_nObjects; i++)
   {
      CComQIPtr<IPolyCtl, &IID_IPolyCtl> pPoly(m_ppUnk[i]);
      short nSides = (short)GetDlgItemInt(IDC_SIDES);
      if FAILED(pPoly->put_Sides(nSides))
      {
         CComPtr<IErrorInfo> pError;
         CComBSTR         strError;
         GetErrorInfo(0, &pError);
         pError->GetDescription(&strError);
         MessageBox(OLE2T(strError), _T("Error"), MB_ICONEXCLAMATION);
         return E_FAIL;
      }
   }
   m_bDirty = FALSE;
   return S_OK;
}

A property page could have more than one client attached to it at a time, so the Apply function loops around and calls put_Sides on each client with the value retrieved from the edit box. You are using the CComQIPtr class, which performs the QueryInterface on each object to obtain the IPolyCtl interface from the IUnknown (stored in the m_ppUnk array).

The code now checks that setting the Sides property actually worked. If it fails, the code displays a message box displaying error details from the IErrorInfo interface. Typically, a container asks an object for the ISupportErrorInfo interface and calls InterfaceSupportsErrorInfo first, to determine whether the object supports setting error information. But since it's your control, you can forego that check.

CComPtr helps you by automatically handling the reference counting, so you don't need to call Release on the interface. CComBSTR helps you with BSTR processing, so you don't have to perform the final SysFreeString call. You also use one of the various string conversion classes, so you can convert the BSTR if necessary (this is why we add the USES_CONVERSION macro at the start of the function).

You also must set the property page's dirty flag to indicate that the Apply button should be enabled. This occurs when the user changes the value in the Sides edit box. Right-click the property page class (CPolyProp) in ClassView and then select Add Windows Message Handler... from the shortcut menu. Select IDC_SIDES from the object box and then add the EN_CHANGE message.

Now add the following code in Polyprop.h to the OnChangeSides function (deleting any code that the wizard put there):

LRESULT OnChangeSides(WORD wNotify, WORD wID, HWND hWnd, BOOL& bHandled)
{
   SetDirty(TRUE);
   return 0;
}

OnChangeSides will be called when a WM_COMMAND message is sent with the EN_CHANGE notification for the IDC_SIDES control. OnChangeSides then calls SetDirty and passes TRUE to indicate the property page is now dirty and the Apply button should be enabled.

Now, add the property page to your control. The ATL Object Wizard doesn't do this for you automatically, since there could be multiple controls in your project. Open PolyCtl.h and add this line to the property map:

   PROP_ENTRY("Sides", 1, CLSID_PolyProp)

The control's property map now looks like this:

BEGIN_PROP_MAP(CPolyCtl)
   PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4)
   PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4)
   PROP_ENTRY("FillColor", DISPID_FILLCOLOR, CLSID_StockColorPage)
   PROP_ENTRY("Sides", 1, CLSID_PolyProp)
   // Example entries
   // PROP_ENTRY("Property Description", dispid, clsid)
   // PROP_PAGE(CLSID_StockColorPage)
END_PROP_MAP()

You could have added a PROP_PAGE macro with the CLSID of your property page, but if you use the PROP_ENTRY macro as shown, the Sides property value is also saved when the control is saved. The three parameters to the macro are the property description, the DISPID of the property, and the CLSID of the property page that has the property on it. This is useful if, for example, you load the control into Visual Basic and set the number of Sides at design time. Since the number of Sides is saved, when you reload your Visual Basic project the number of Sides will be restored.

Now build that control and insert it into ActiveX Control Test Container. Then, in Test Container, on the Edit menu click PolyCtl Class Object. The property page appears; chose the Polygon tab.

The Apply button is initially disabled. Start typing a value in the Sides edit box and the Apply button will become enabled. After you have finished entering the value, click the Apply button. The control display changes and the Apply button is again disabled. Try entering an invalid value and you should see a message box containing the error description that you set from the put_Sides function.

Next you'll put your control on a Web page.


Step 7: Putting the Control on a Web Page

Your control is now finished. To see your control work in a real-world situation, put it on a Web page. When the ATL Object Wizard creates the initial control it also creates an HTML file that contains the control. You can open up the PolyCtl.htm file in Internet Explorer and you see your control on a Web page.

The control doesn't do anything yet, so change the Web page to respond to the events that you send. Open PolyCtl.htm in Visual C++ (if the file does not appear in FileView, select Open from the File menu to open the file) and add the lines in bold.

<HTML>
<HEAD>
<TITLE>ATL 3.0 test page for object PolyCtl</TITLE>
</HEAD>
<BODY>
<OBJECT ID="PolyCtl" <
 CLASSID="CLSID:4CBBC676-507F-11D0-B98B-000000000000">
>

</OBJECT>

<SCRIPT LANGUAGE="VBScript">

<!--

Sub PolyCtl_ClickIn(x, y)

   PolyCtl.Sides = PolyCtl.Sides + 1

End Sub

Sub PolyCtl_ClickOut(x, y)

   PolyCtl.Sides = PolyCtl.Sides - 1

End Sub

-->

</SCRIPT>

</BODY>

</HTML>

You have added some VBScript code that gets the Sides property from the control, and increases the number of sides by one if you click inside the control. If you click outside the control you reduce the number of sides by one.

Start up Internet Explorer and make sure your Security settings are set to Medium:

  1. Click Internet Options on the View menu.

  2. Select the Security tab and set the security to Medium, if necessary, then click OK.

Now open PolyCtl.htm in Internet Explorer. After you click on the control, a Security Alert dialog box informs you that Internet Explorer doesn't know if the control is safe to script.

What does this mean? Imagine if you had a control that, for example, displayed a file, but also had a Delete method that deleted a file. The control would be safe if you just viewed it on a page, but wouldn't be safe to script since someone could call the Delete method. This message is Internet Explorer's way of saying that it doesn't know if someone could do damage with this control, so it is asking the user.

You know your control is safe, so click Yes. Now click inside the polygon; the number of sides increases by one. Click outside the polygon to reduce the number of sides. If you try to reduce the number of sides below three, you will see the error message that you set.

The following figure shows the control running in Internet Explorer after you have clicked inside the polygon twice.

Since you know your control is always safe to script, it would be good to let Internet Explorer know, so that it doesn't need to show the Security Alert dialog box. You can do this through the IObjectSafety interface. ATL supplies an implementation of this interface in the class IObjectSafetyImpl.

To add the interface to your control, just add IObjectSafetyImpl to your list of inherited classes and add an entry for it in your COM map.

Add the following line to the end of the list of inherited classes in PolyCtl.h, remembering to add a comma to the previous line:

   public IObjectSafetyImpl<CPolyCtl, INTERFACESAFE_FOR_UNTRUSTED_CALLER>

Then add the following line to the COM map in PolyCtl.h:

   COM_INTERFACE_ENTRY(IObjectSafety)

Now build the control. Once the build has finished, open PolyCtl.htm in Internet Explorer again. This time the Web page should be displayed directly without the Safety Violation dialog box. Click inside and outside the polygon to confirm that the scripting is working.


ATL References

This tutorial has demonstrated some basic concepts about using ATL.

To view the available ATL documentation, see:

  • ATL Article Overview

  • ATL Class Overview

  • ATL Samples Index


Introduction to COM and ATL

This article provides a very brief introduction to COM and ATL. For more information on COM, see The Component Object Model in the Win32 SDK. For more information on ATL, see the ATL Article Overview and the ATL Class Overview.

  • Introduction to COM

  • Introduction to ATL


Introduction to COM

COM is the fundamental "object model" on which ActiveX Controls and OLE are built. COM allows an object to expose its functionality to other components and to host applications. It defines both how the object exposes itself and how this exposure works across processes and across networks. COM also defines the object's life cycle.

Fundamental to COM are these concepts:

  • Interfaces — the mechanism through which an object exposes its functionality.

  • IUnknown — the basic interface on which all others are based. It implements the reference counting and interface querying mechanisms running through COM.

  • Reference counting — the technique by which an object (or, strictly, an interface) decides when it is no longer being used and is therefore free to remove itself.

  • QueryInterface — the method used to query an object for a given interface.

  • Marshaling — the mechanism that enables objects to be used across thread, process, and network boundaries, allowing for location independence.

  • Aggregation — a way in which one object can make use of another.

See Also The Component Object Model in the Win32 SDK


Interfaces

An interface is the way in which an object exposes its functionality to the outside world. In COM, an interface is a table of pointers (like a C++ vtable) to functions implemented by the object. The table represents the interface, and the functions to which it points are the methods of that interface. An object can expose as many interfaces as it chooses.

Each interface is based on the fundamental COM interface, IUnknown. The methods of IUnknown allow navigation to other interfaces exposed by the object.

Also, each interface is given a unique interface ID (IID). This uniqueness makes it is easy to support interface versioning. A new version of an interface is simply a new interface, with a new IID.

Note IIDs for the standard COM, OLE, and COM interfaces are pre-defined.

Introduction to COM

See Also COM Objects and Interfaces in the Win32 SDK


IUnknown

IUnknown is the base interface of every other COM interface. IUnknown defines three methods: QueryInterface, AddRef, and Release. QueryInterface allows an interface user to ask the object for a pointer to another of its interfaces. AddRef and Release implement reference counting on the interface.

Introduction to COM

See Also IUnknown and Interface Inheritance in the Win32 SDK


Reference Counting

COM itself does not automatically try to remove an object from memory when it thinks the object is no longer being used. Instead, the object programmer must remove the unused object. The programmer determines whether an object can be removed based on a reference count.

COM uses the IUnknown methods, AddRef and Release, to manage the reference count of interfaces on an object. The general rules for calling these methods are:

  • Whenever a client receives an interface pointer, AddRef must be called on the interface.

  • Whenever the client has finished using the interface pointer, it must call Release.

In a simple implementation, each AddRef call increments and each Release call decrements a counter variable inside the object. When the count returns to zero, the interface no longer has any users and is free to remove itself from memory.

Reference counting can also be implemented so that each reference to the object (not to an individual interface) is counted. In this case, each AddRef and Release call delegates to a central implementation on the object, and Release frees the entire object when its reference count reaches zero.

Introduction to COM

See Also Managing Object Lifetimes through Reference Counting in the Win32 SDK


QueryInterface

Although there are mechanisms by which an object can express the functionality it provides statically (before it is instantiated), the fundamental COM mechanism is to use the IUnknown method called QueryInterface.

Every interface is derived from IUnknown, so every interface has an implementation of QueryInterface. Regardless of implementation, this method queries an object using the IID of the interface to which the caller wants a pointer. If the object supports that interface, QueryInterface retrieves a pointer to the interface, while also calling AddRef. Otherwise, it returns the E_NOINTERFACE error code.

Introduction to COM

See Also QueryInterface: Navigating in an Object in the Win32 SDK


Marshaling

The COM technique of marshaling allows interfaces exposed by an object in one process to be used in another process. In marshaling, COM provides code (or uses code provided by the interface implementor) both to pack a method's parameters into a format that can be moved across processes (as well as, across the wire to processes running on other machines) and to unpack those parameters at the other end. Likewise, COM must perform these same steps on the return from the call.

Note Marshaling is typically not necessary when an interface provided by an object is being used in the same process as the object. However, marshaling may be needed between threads.

Introduction to COM

See Also Marshaling Details in the Win32 SDK


Aggregation

There are times when an object's implementor would like to take advantage of the services offered by another, pre-built object. Furthermore, it would like this second object to appear as a natural part of the first. COM achieves both of these goals through containment and aggregation.

Aggregation means that the containing (outer) object creates the contained (inner) object as part of its creation process and the interfaces of the inner object are exposed by the outer. An object allows itself to be aggregatable or not. If it is, then it must follow certain rules for aggregation to work properly.

Primarily, all IUnknown method calls on the contained object must delegate to the containing object.

Introduction to COM

See Also Reusing Objects in the Win32 SDK


Introduction to ATL

ATL is the Active Template Library, a set of template-based C++ classes with which you can easily create small, fast Component Object Model (COM) objects. It has special support for key COM features including: stock implementations of IUnknown, IClassFactory, IClassFactory2 and IDispatch; dual interfaces; standard COM enumerator interfaces; connection points; tear-off interfaces; and ActiveX controls.

ATL code can be used to create single-threaded objects, apartment-model objects, free-threaded model objects, or both free-threaded and apartment-model objects.

Topics covered in this section include:

  • How a template library differs from a standard C++ library.

  • What you can and cannot do with ATL.

  • When to use ATL versus MFC.


Using a Template Library

A template is somewhat like a macro. As with a macro, invoking a template causes it to expand (with appropriate parameter substitution) to code you have written. However, a template goes further than this to allow the creation of new classes based on types that you pass as parameters. These new classes implement type-safe ways of performing the operation expressed in your template code.

Template libraries such as ATL differ from traditional C++ class libraries in that they are typically supplied only as source code (or as source code with a little, supporting run time) and are not inherently or necessarily hierarchical in nature. Rather than deriving from a class to get the functionality you desire, you instantiate a class from a template.

Introduction to ATL


The Scope of ATL

ATL allows you to easily create COM objects, Automation server, and ActiveX controls. ATL provides built-in support for many of the fundamental COM interfaces.

ATL is shipped as source code which you include in your application. ATL also makes a DLL available (atl.dll), which contains code that may be shared across components. However, this DLL is not necessary.

Introduction to ATL

See Also Creating an ATL Project


Choosing When to Use ATL

When developing components and applications, you can choose between two approaches — ATL and MFC (the Microsoft Foundation Class Library).

Using ATL

ATL is a fast, easy way to both create a COM component in C++ and maintain a small footprint. Use ATL to create a control if you don't need all of the built-in functionality that MFC automatically provides.

Using MFC

MFC allows you to create full applications, ActiveX controls, and active documents. If you have already created a control with MFC, you may want to continue development in MFC. When creating a new control, consider using ATL if you don't need all of MFC's built-in functionality.

Introduction to ATL


Creating an ATL Project

The easiest way to create an ATL project is to use the ATL COM AppWizard. You can then add objects or controls to your project using the ATL Object Wizard. Go through the ATL Tutorial to insert a control and add custom properties and events.

This article:

  • Describes how to use the ATL COM AppWizard.

  • Lists the files generated by the ATL COM AppWizard.

  • Describes how to add an object or a control with the ATL Object Wizard.

  • Describes how to add a new interface to an existing object or control.

  • Shows how to make an ATL object noncreatable.


Using the ATL COM AppWizard

To create a project using the ATL COM AppWizard

  1. Open Visual C++. Click New on the File menu and click the Projects tab.

  2. Choose ATL COM AppWizard as your application type.

  3. Enter a project name.

  4. Click OK.

The ATL COM AppWizard displays a dialog box showing options that apply to your ATL project:

  • Choose from one of three server types: Dynamic Link Library (DLL) for an in-process server, Executable (EXE) for a local out-of-process server, or Service (EXE), which is a Windows NT application that runs in the background when NT starts up.

  • Select the Allow merging of proxy/stub code check box as a convenience when marshaling interfaces is required. This option places the MIDL generated proxy and stub code in the same DLL as the server.

  • Select the Support MFC check box (available for DLL projects only) to use MFC functionality (such as CString) in your server.

  • Select the Support MTS check box to modify the project build settings to support the Microsoft Transaction Server. For more information on adding MTS support to your project, see MTS Support in ATL Projects.

Click Finish to generate the project. The AppWizard then displays information about the project that it is creating and then displays the newly created project in the Project Workspace.

Note When you build your project, you can choose a MinSize or MinDependency configuration. MinSize will generate a smaller component, since shared code will be used from Atl.dll. In this case, you must distribute Atl.dll with your component. MinDependency will generate a larger component, since all necessary code will be linked in with your component.

Note When building a Release version of a project, you can get the following link error:

LIBCMT.LIB(crt0.obj) : error LNK2001: unresolved external symbol _main

This error occurs if you are using CRT functions that require CRT startup code. The Release configurations define _ATL_MIN_CRT, which excludes CRT startup code from your EXE or DLL. To avoid this error, do one of the following:

  • Remove _ATL_MIN_CRT from the list of preprocessor defines to allow CRT startup code to be included. On the Project menu, click Settings. In the Settings For: drop-down list, choose Multiple Configurations. In the Select project configuration(s) to modify dialog box that appears, click the check boxes for all Release versions, and then click OK. On the C/C++ tab, choose the General category, then remove _ATL_MIN_CRT from the Preprocessor definitions edit box.

  • If possible, remove calls to CRT functions that require CRT startup code and use their Win32 equivalents. For example, use lstrcmp instead of strcmp. Known functions that require CRT startup code are some of the string and floating point functions.


MTS Support in ATL Projects

You can use the ATL COM AppWizard to easily add basic support for Microsoft Transaction Server (MTS).

Note MTS is designed for developing distributed, component-based applications and also provides a run-time infrastructure for deploying and managing these applications. For more information on MTS, see the Microsoft Transaction Server 2.0 section of the Platform SDK.

If you check the Support MTS check box on the first page of the ATL COM AppWizard, the wizard modifies the build script in the link step. Specifically, in addition to the standard list of libraries, the wizard adds the following MTS-specific libraries:

  • MTX.lib Import library for MTS APIs.

  • MTXGUID.lib Library containing GUIDs associated with MTX objects and interfaces.

In addition, the MTXEX.dll is delay-loaded on the host system when your application is launched.

See Also

Files Generated by the ATL COM AppWizard


Files Generated by the ATL COM AppWizard

Choose the FileView tab in the Project Workspace and expand by clicking + to see the files generated for your project:

Test.cpp | Contains the implementation of your DLL's exports for an in-process server and the implementation of WinMain for a local server. For a service, this additionally implements all the service management functions.
Test.def | Typically, contains a list of your DLL's exports. Generated only for an in-process server.
Test.idl | Includes the definitions for all your interfaces. As an Interface Definition Language (IDL) file, it will be processed by the MIDL compiler to generate the Test.tlb type library and marshaling code.
Test.rc | Contains the resource information for your project.
Resource.h | The header file for the resource file.
StdAfx.cpp | Includes the files StdAfx.h and Atlimpl.cpp.
StdAfx.h | Includes the ATL header files.


Adding Objects and Controls

You can use the ATL Object Wizard to add an object or a control to your ATL or MFC-based projects. For each COM object or control you add, the wizard generates CPP and H files, as well as an RGS file for script-based registry support.

If you are attempting to add a simple COM object to an MFC project, you will need to add ATL support to the existing project. For more information on this feature, see Adding ATL Support to Your MFC Project.

Note The ATL Object Wizard adds the object to the active project. If you wish to add the control to another project on the workspace, you must first make it the active project.

To add an object or a control using the ATL Object Wizard

  • With your project open, select New ATL Object from the Insert menu.

    -or-

  • From ClassView, click the right mouse button on the project-level folder, and select New ATL Object from the pop-up menu.

    The ATL Object Wizard opens.

Note If this is an MFC project to which you have not previously added an ATL object, you'll be prompted to specify whether you want ATL support added to your project. Clicking Yes opens the ATL Object Wizard.

The ATL Object Wizard displays the categories of objects on the left and the icons of the objects in each category on the right. Choose a category; the wizard displays the icons of the objects in that category.

ATL Objects

  • Simple Object adds a minimal COM object.

  • Add-in Object adds a COM object that extends the Visual C++ shell with your own toolbar button and event handling. This object offers the same functionality as the one added by the DevStudio Add-in Wizard on the Visual C++ File menu, New Projects tab.

  • Internet Explorer Object adds an object that supports the interfaces needed by Internet Explorer, but without support for a user interface.

  • Active Server Component adds an object that can be used by the Active Server Pages feature of Internet Information Server (IIS).

  • MMC SnapIn creates a framework for a Microsoft Management Console Snap-In object. See MMC Snap-In Wizard and Microsoft Management Console in the Platform SDK for more information.

  • MS Transaction Server Component includes the header files needed by the Microsoft Transaction Server and defines the object as nonaggregatable.

  • Component Registrar Object adds an object that implements the IComponentRegistrar interface. This object can be used to register any objects in your in-process server that declare the DECLARE_OBJECT_DESCRIPTION macro. Using this object you can register and/or unregister objects individually, unlike DllRegisterServer and DllUnregisterServer which register and unregister all objects in your server. You may also get a list of objects in the server and their descriptions with the IComponentRegistrar::GetComponents method.

ATL Controls

  • Full Control adds an object that supports the interfaces for all containers.

  • Lite Control adds an object that supports the interfaces needed by Internet Explorer, including support for a user interface.

  • Property Page adds an object that implements a property page.

  • Composite Control adds a control that can host many other controls.

  • HTML Control adds a control with DHTML functionality and displays an HTML web page in its user interface.

  • Lite Composite Control adds a composite control that can host other controls, but it supports only the interfaces needed by Internet Explorer.

  • Lite HTML Control adds a control with DHTML functionality and displays an HTML web page in its user interface, but it supports only the interfaces needed by Internet Explorer.

ATL Miscellaneous

  • Dialog adds an object that implements a dialog box.

Data Access

  • Provider adds code to support OLE DB provider templates.

  • Consumer adds code to support OLE DB consumer templates.

Double-click the control or object you want to insert. The ATL Object Wizard displays a dialog box showing options that apply to your object or control.

Note Depending on the type of object or control you select, some of the pages and options described below may not be available.

In the Names page, enter class and file names. By default, the name you enter for Short name becomes the root for all other names in this page. You can enter your own names rather than accept these defaults.

  • Class is the name of the class implementing your object.

  • CoClass is the name of the component class that contains a list of interfaces supported by the object.

  • Interface is the name of the interface you create for your object. This interface contains your custom methods. For Full Controls, Internet Explorer Controls, Simple Objects, Internet Explorer Objects, Add-in Objects, Active Server Components, and Microsoft Transaction Server Components, the wizard creates an interface with the name you specify. For Property Page objects, no custom interface is created, and the wizard assigns IUnknown as the object interface. Dialog objects do not create an interface.

  • Type is a description string for the object that goes into the registry.

  • ProgID is a name that containers can use instead of the CLSID of the object.

In the Attributes page, select a threading model, interface type, and aggregation support:

  • Choose Dual Interfaces if you want the object's interfaces to derive from IDispatch as well as support your custom functions (the vtable has custom interface functions plus late-binding IDispatch methods). This allows both COM clients and Automation controllers to access your object.

  • Choose Custom Interfaces to derive the object's interfaces from IUnknown (the vtable has custom interface functions and not IDispatch methods). A custom interface can be faster than a dual interface, especially across process boundaries.

  • Choose Only for aggregation if you want the object to be instantiated only if it is being aggregated.

  • Check the Support ISupportErrorInfo check box to have your object implement the ISupportErrorInfo interface for error reporting.

  • Check the Support Connection Points check box to add support for connection points to the object. The wizard will automatically derive the object's class from IConnectionPointContainerImpl.

  • Check the Free Threaded Marshaler check box to create a free-threaded marshaler object to efficiently marshal interface pointers between threads in the same process.

In the Miscellaneous page, choose the features for the object.

  • Choose Opaque to make your control completely opaque, so that none of the container shows behind the control boundaries. This helps the container draw the control more quickly. The entire control rectangle passes to your control class's OnDraw method. This option sets the VIEWSTATUS_OPAQUE bit in the VIEWSTATUS enumeration.

  • Choose Solid Background to make the control's background a solid color and not a pattern. This option is meaningful only if the Opaque is option is also selected. This option sets the VIEWSTATUS_SOLIDBKGND bit in the VIEWSTATUS enumeration.

  • Choose Invisible at runtime to make your control invisible at run time. You can use invisible controls to perform operations in the background, such as firing events at timed intervals.

  • Choose Acts like button to enable your control to act like a button, in particular to display itself as the default button based on the ambient property DisplayAsDefault.

  • Choose Acts like label to enable your control to replace the container's native label.

  • Choose Add control based on to superclass one of the standard window classes. The drop-down list contains window class names defined by Windows. When you choose one of these, the wizard adds a CContainedWindow member variable to your control's class. CContainedWindow::Create will superclass the window class you specify.

  • Choose Normalize DC to have your control create a normalized device context when it is called to draw itself. This standardizes the control's appearance, but is less efficient.

  • Choose Insertable to have your control appear in the Insert Object dialog box of applications such as Microsoft Word and Microsoft Excel. Your control can then be inserted by any application that supports embedded objects through the Insert Object dialog box.

  • Choose Windowed Only to force your control to be windowed, even in containers that support windowless objects. If you do not select this option, your control will automatically be windowless in containers that support windowless objects, and automatically be windowed in containers that do not support windowless objects.

In the Stock Properties page, select the stock properties you want the object to support, such as Caption or Border Color. You can select all the stock properties at once by clicking the >> button.

In the Strings page, enter names for the property page object.

  • Title is the text that appears on the property page's tab.

  • Doc String is a text string describing the page. The property frame could use the description in a status line or tool tip. The standard property frame currently does not use this string.

  • Helpfile is the name of the associated help file. The help file name should be the simple name without a path. When the user presses Help, the frame opens the help file in the directory named in the value of the HelpDir key in the property page registry entries under its CLSID.

In the Add-in page, choose features for the Add-in object.

  • Provide Toolbar creates a toolbar button the user can click to carry out a command added by your Add-in object.

  • Command Name is the name of the command added to Visual C++ by your Add-in object. This name appears in the list on the Add-ins and Macro Files tab of the Tools menu, Customize option.

  • Method Name is the name of the method that implements the command.

  • Toolbar Text is the text that you want to appear on the button you add to the toolbar to carry out your command.

  • Status bar Text is the text you want to appear on the status line when your command is executing.

  • Tooltips Text is the text you want to appear in the tooltip message for your toolbar button when the user's mouse hovers over the button.

  • Application Events allows your Add-in object to catch application events.

  • Debugger Events allows your Add-in object to catch debugger events.

In the ASP page, choose features for the Active Server component.

  • OnStartPage/OnEndPage, checked by default, adds the OnStartPage and OnEndPage methods to the object.

  • If OnStartPage/OnEndPage is checked, you can choose which Intrinsic Objects you want to have available as member pointers in the object's class. By default, each intrinsic object is checked.

In the MTX page, choose features for the Microsoft Transaction Server component. Dual and Custom choose the kind of interface implemented, and Support Connection Points adds support for connection points. These options are the same as the ones in the Attributes page for other kinds of objects. In addition, the MTX page has two unique options:

  • Support IObjectControl provides access to the three IObjectControl methods: Activate, CanBePooled, and Deactivate.

  • Can be pooled tells the Transaction Server run-time environment that your object should be returned to an instance pool after deactivation, rather than destroyed. This option cannot be selected unless the Support IObjectControl option is also selected.


Adding a New Interface to an Existing Object or Control

When you add an interface to your object or control, you create stubbed-out functions for each method in that interface. In your object or control, you can only add interfaces currently found in an existing type library. Also, the class in which you add the interface must implement the BEGIN_COM_MAP macro.

There are two ways to add a new interface to your control or object: manually and via ClassView.

To add a new interface manually

  1. Add the definition of your new interface to the IDL file.

  2. Derive your object or control from the interface.

  3. Create a new COM_INTERFACE_ENTRY for the interface.

  4. Implement methods on the interface.

To use ClassView to add an interface to an existing object or control

  1. Make sure that your workspace is visible by selecting Workspace from the View menu.

  2. In the Workspace, select the ClassView tab.

  3. Right-click on the class name of a control, for example, a full control or composite control, or any other control class that implements a BEGIN_COM_MAP macro in its header file. You will see a pop-up menu with the Implement Interface... option.

  4. Select the Implement Interface... option to display the Implement Interface dialog box.

  5. If there is a new interface in your project’s type library, you will see the interface displayed in the Interfaces list. You can also click AddTypelib... and select one or more type libraries from the Browse Type Libraries dialog box.

  6. Select interfaces from the available type libraries in the Implement Interface dialog box and click OK. This process adds a TLH file to your project directory for each object in which you selected one or more interfaces.


Making an ATL Object Noncreatable

You can change the attributes of an ATL-based COM object so that the automation client cannot directly create the object. In this case, the object would be returned via a method call on another object rather than created directly.

To make an object noncreatable

  1. Remove the OBJECT_ENTRY for the object from the ATL object map.

  2. Add the noncreatable attribute to the coclass. For example:
[
   uuid(A1992E3D-3CF0-11D0-826F-00A0C90F2851),
   helpstring(“MyObject”),
  noncreatable
]
coclass MyObject
{
   [default] interface IMyInterface;
}


Fundamentals of ATL COM Objects

The following illustration depicts the relationship among the various classes and interfaces used in defining an ATL COM object.

ATL Structure

ATL implements IUnknown in two phases:

  • CComObject, CComAggObject, or CComPolyObject implements the IUnknown methods.

  • CComObjectRoot or CComObjectRootEx manages the reference count and outer pointers of IUnknown.

Other aspects of your ATL COM object are handled by other classes:

  • CComCoClass defines the object's default class factory and aggregation model.

  • IDispatchImpl provides a default implementation of the IDispatch portion of any dual interfaces on the object.

For more information, see the following sections in this article:

  • Implementing CComObjectRootEx

  • Implementing CComObject, CComAggObject, and CComPolyObject

  • Supporting IDispatch and IErrorInfo

  • Supporting IDispEventImpl

  • Changing the Default Class Factory and Aggregation Model

  • Creating an Aggregate

For information about creating an ATL COM object, see the article Creating an ATL Project.


Implementing CComObjectRootEx

CComObjectRootEx is essential — all ATL objects must have one instance of CComObjectRootEx or CComObjectRoot in their inheritance. CComObjectRootEx provides the default QueryInterface mechanism based on COM map entries.

Through its COM map, an object's interfaces are exposed to a client when the client queries for an interface. The query is performed through CComObjectRootEx::InternalQueryInterface. InternalQueryInterface only handles interfaces in the COM map table.

You can enter interfaces into the COM map table with the COM_INTERFACE_ENTRY macro or one of its variants. For example, the following code from the BEEPER sample enters the interfaces IDispatch, IBeeper, and ISupportErrorInfo into the COM map table:

BEGIN_COM_MAP(CBeeper)
   COM_INTERFACE_ENTRY(IDispatch)
   COM_INTERFACE_ENTRY(IBeeper)
   COM_INTERFACE_ENTRY_TEAR_OFF(IID_ISupportErrorInfo, CBeeper2)
END_COM_MAP( )


Implementing CComObject, CComAggObject, and CComPolyObject

The template classes, CComObject, CComAggObject, and CComPolyObject are always the most derived classes in the inheritance chain. It is their responsibility to handle all the methods in IUnknown: QueryInterface, AddRef, and Release. In addition, CComAggObject and CComPolyObject (when used for aggregated objects) provide the special reference counting and QueryInterface semantics required for the inner unknown.

Whether CComObject, CComAggObject, or CComPolyObject is used depends on whether you declare the DECLARE_POLY_AGGREGATABLE macro and on whether your object is being aggregated:

  • If your class definition specifies the DECLARE_POLY_AGGREGATABLE macro, ATL creates an instance of CComPolyObject<CYourClass> when IClassFactory::CreateInstance is called. During creation, the value of the outer unknown is checked. If it is NULL, IUnknown is implemented for a non-aggregated object. If the outer unknown is not NULL, IUnknown is implemented for an aggregated object.

  • If you do not specify the DECLARE_POLY_AGGREGATABLE macro in your class definition and the object is not aggregated, ATL creates an instance of CComObject<CYourClass> when IClassFactory::CreateInstance is called.

  • If you do not specify the DECLARE_POLY_AGGREGATABLE macro in your class definition and the object is aggregated, ATL creates a CComAggObject<CYourClass> when IClassFactory::CreateInstance is called.

The advantage of using CComAggObject and CComObject is that the implementation of IUnknown is optimized for the kind of object being created. For instance, a nonaggregated object only needs a reference count, while an aggregated object needs both a reference count for the inner unknown and a pointer to the outer unknown.

The advantage of using CComPolyObject is that you avoid having both CComAggObject and CComObject in your module to handle the aggregated and nonaggregated cases. A single CComPolyObject object handles both cases. This means only one copy of the vtable and one copy of the functions exist in your module. If your vtable is large, this can substantially decrease your module size. However, if your vtable is small, using CComPolyObject can result in a slightly larger module size because it is not optimized for an aggregated or nonaggregated object, as are CComAggObject and CComObject.

The DECLARE_POLY_AGGREGATABLE macro is automatically added to your class definition by the ATL Object Wizard when you create a full control or Internet Explorer control. For more information about the wizard, see Creating an ATL Project.


Supporting IDispatch and IErrorInfo

You can use the template class IDispatchImpl to provide a default implementation of the IDispatch portion of any dual interfaces on your object.

If your object uses the IErrorInfo interface to report errors back to the client, then your object must support the ISupportErrorInfo interface. The template class ISupportErrorInfoImpl provides an easy way to implement this if you only have a single interface that generates errors on your object.


Supporting IDispEventImpl

The template class IDispEventImpl can be used to provide support for connection points in your ATL COM object. A connection point allows your COM object to handle events fired from external COM objects. These connection points are mapped with an event sink map, provided by your COM object.

To properly implement a connection point or points for your COM object, the following steps must be completed:

  • Import the type libraries for each external

  • Declare the IDispEventImpl interfaces

  • Declare an event sink map

  • Advise and unadvise the connection points

In this procedure, you will be modifying only the header file (.h) of your COM class.

Importing the Type Libraries

For each external object whose events you wish to handle, you must import the type library. This step defines the events that can be handled and provides information that is used when declaring the event sink map. The #import directive can be used to accomplish this. Add the necessary #import directive lines for each dispatch interface you will support to the header file (.h) of your COM class.

The following example imports the type library of an external COM server (MyServer):

#import "D:\MyServer.dll" raw_interfaces_only, no_namespace, named_guids

Note You must have a separate #import statement for each external dispatch interface you will support.

Declaring the IDispEventImpl Interfaces

Now that you have imported the type libraries of each dispatch interface, you need to declare separate IDispEventImpl interfaces for each external dispatch interface. Modify the declaration of your COM class by adding an IDispEventImpl interface declaration for each external object. For more information on the parameters, see IDispEventImpl.

The following lines of code declare two connection points, for the custom IExtEvents1 and IExtEvents2 interfaces, for the COM object implemented by class CMyObj:

public IDispEventImpl<0, CMyObj, &DIID__IExtEvents1,
    &LIBID_EXTEVENTS1Lib, 1, 0>,
public IDispEventImpl<1, CMyObj, &DIID__IExtEvents2,
    &LIBID_EXTEVENTS2Lib, 1, 0>

Declaring an Event Sink Map

In order for the event notifications to be handled by the proper function, your COM object must route each event to its correct handler. This is achieved by declaring an event sink map.

ATL provides several macros, BEGIN_SINK_MAP, END_SINK_MAP, and SINK_ENTRY, that make this mapping easier. The standard format is as follows:

BEGIN_SINK_MAP(comClass)
   SINK_ENTRY(id, dispid, func)
. . . //additional external event entries
END_SINK_MAP()

The following example declares an event sink map with two event handlers:

BEGIN_SINK_MAP(CMyObj)
   SINK_ENTRY(0, Events1, OnClick1)
   SINK_ENTRY(0, Events2, OnClick2)
END_SINK_MAP()

The implementation is nearly complete. The last step concerns the advising and unadvising of the external interfaces.

Advising and Unadvising the IDispEventImpl Interfaces

The final step is to implement a method that will advise (or unadvise) all connection points at the proper times. This advising must be done before communication between the external clients and your object can take place. Before your object becomes visible, each external dispatch interface supported by your object is queried for outgoing interfaces. A connection is established and a reference to the outgoing interface is used to handle events from the control. This procedure is referred to as "advising."

After your object is finished with the external interfaces, the outgoing interfaces should be notified that they are no longer used by your COM object. This process is referred to as "unadvising."

Because of the unique nature of COM objects, this procedure varies, in detail and execution, between implementations. These details are beyond the scope of this topic and are not addressed.


Changing the Default Class Factory and Aggregation Model

ATL uses CComCoClass to define the default class factory and aggregation model for your object. CComCoClass specifies the following two macros:

  • DECLARE_CLASSFACTORY Declares the class factory to be CComClassFactory.

  • DECLARE_AGGREGATABLE Declares that your object can be aggregated.

You can override either of these defaults by specifying another macro in your class definition. For example, to use CComClassFactory2 instead of CComClassFactory, specify the DECLARE_CLASSFACTORY2 macro:

class CMyClass : ...,
   public CComCoClass<CMyClass, &CLSID_CMyClass>
{
public:
   DECLARE_CLASSFACTORY2(CMyLicense)

   ...
};

Two other macros that define a class factory include DECLARE_CLASSFACTORY_AUTO_THREAD and DECLARE_CLASSFACTORY_SINGLETON.

ATL also uses the typedef mechanism to implement default behavior. For example, the DECLARE_AGGREGATABLE macro uses typedef to define a type called _CreatorClass, which is then reference throughout ATL. Note that in a derived class, a typedef using the same name as the base class's typedef results in ATL using your definition and overriding the default behavior.


Creating an Aggregate

To create an aggregate

  1. Add an IUnknown pointer to your class object and initialize it to NULL in the constructor.

  2. Override FinalConstruct to create the aggregate.

  3. Use the IUnknown pointer, defined in Step 1, as the second parameter for the COM_INTERFACE_ENTRY_AGGREGATE macros.

  4. Override FinalRelease to release the IUnknown pointer.

Note If you use and release an interface from the aggregate during FinalConstruct, you should add the DECLARE_PROTECT_FINAL_CONSTRUCT macro to the definition of your class object.


Composite Control Fundamentals

A composite control is a type of ActiveX control that can contain (similar to a dialog box) other ActiveX controls or Windows controls. Once the composite control is built, it can be inserted anywhere an ActiveX control can be hosted.

Visual C++ provides two tools, ATL COM AppWizard and ATL Object Wizard, that automate the process of creating and implementing a composite control project, similar to the result of running AppWizard to create an MFC application framework. Basically the development process consists of five steps:

  • Creating the ATL project (using ATL COM AppWizard)

  • Inserting a composite control (using ATL Object Wizard)

  • Modifying the ATL project

  • Adding functionality to the composite control

  • Building and testing the ATL project


Creating the ATL Project

The ATL COM AppWizard, provided by Visual C++, automates the creation of an ATL project. The following procedure details the necessary steps:

To create the ATL project

  1. From the File menu, click New.

  2. Click the Projects tab.

  3. Click the ATL COM AppWizard item.

  4. In the Project edit box, type the new name.

  5. In the Location edit box, type the location of the new project.

  6. Click OK to start the ATL COM AppWizard.

  7. In Step 1 of the ATL COM AppWizard, select Dynamic Link Library (DLL) from the Server Type group.

  8. Click Finish.

  9. Click OK to create the ATL project.

The newly created project is small and contains only a few of the necessary components needed for an ATL project. Currently, the project consists of:

  • .H and .CPP source files for the proxy initialization module.

  • .IDL source file, which is used to generate the type library and marshalling code.


Inserting a Composite Control

Another helpful wizard (ATL Object Wizard) provided by Visual C++ allows you to quickly insert an ATL object into your existing project. Access this wizard by choosing the New ATL Object option from the Insert menu or the ATL Object Wizard button from the ATL toolbar.

Once the ATL Object Wizard appears, choose the Controls option (in the left-hand pane) and then double-click the Composite Control item. At this point, you need to supply some information on the properties of the composite control you are inserting. For complete details on using the ATL Object Wizard, see Adding Objects and Controls.

  • The first page (Names) requests information related to the implementation class: short name, .H and .CPP files, and so on. Enter a value for the short name. All other entries are generated automatically, using the short name as the basis.

  • The second page (Attributes) presents default options related to the threading model interface and aggregation of the composite control. Accept the default options, or customize them, based on the needs of your composite control.

  • The final page (Stock Properties) provides a list of common control properties your composite control can support. Choose any necessary properties from the left-hand list.

Once you have made your selections, click OK. The ATL Object Wizard then creates the necessary parts which implement your composite control. These parts include:

  • A template for the dialog box that implements the composite control.

  • A custom resource, REGISTRY, that automatically registers the composite control when invoked.

  • A C++ class that implements the composite control.

  • A COM interface, exposed by the composite control.

  • An HTML test page containing the composite control.


Modifying the ATL Project

At this point, your composite control project implements the necessary objects for your composite control. The next step is to add any controls that the composite control will contain and handle any necessary events.

To add additional ActiveX or Windows controls, use the Dialog Editor. For more information on adding controls (and related tasks), see Overview: Dialog Editor in the Visual C++ User’s Guide.

To handle any necessary events, see Adding Functionality to the Composite Control.


Adding Functionality to the Composite Control

Once you have inserted any necessary controls into the composite control, the next step involves adding new functionality. This new functionality usually falls into two categories:

  • Supporting additional interfaces and customizing the behavior of your composite control with additional, specific features.

  • Handling events from the contained control (or controls).

For the purpose and scope of this article, the remaining portion of this section focuses solely on event handling.

Declaration of IDispEventImpl Interfaces for Contained Controls

For each contained control, that you want to handle events from, you must implement an event dispatch interface by deriving from the IDispEventImpl template class. This derivation is done in the declaration of your composite control and consists of two parameters:

  • ID of the control

  • Name of the composite control object

The following example code line, found in the base class declaration, declares an IDispEventImpl interface for a control (IDC_CIRCCTRL1), for the composite control class (CMyCompositeCtrl).

public IDispEventImpl<IDC_CIRCCTL1, CMyCompositeCtrl>

Declaration of the Event Sink Map

After declaring the dispatch event classes for each contained control, you need to add an event sink map to the composite control object. This map accomplishes two things:

  • Relates a control ID to a dispatch interface ID that the contained control uses for events

  • Maps handler functions to events from a contained control

The event sink map is implemented using several predefined macros:

BEGIN_SINK_MAP (CtrlName)

Declares the beginning of the event sink map for the CtrlName composite control.

SINK_ENTRY (CtrlID, DispIID, dispID, EventHandler)

Declares the handler function (EventHandler) for the specified event (dispID), of the dispatch interface DispIID, for the control identified by CtrlID.

END_SINK_MAP ()

Declares the end of the event sink map for the CtrlName composite control.

The following code example (located in the .CPP file of the composite control) declares an event sink map for the CMyCompositeCtrl object. It declares two event handlers for two contained controls (IDC_CIRCCTL1 and IDC_CIRCCTL2). The Click event for both controls is handled by the OnClick_CircCtrl1 and OnClick_CircCtrl2 functions.

BEGIN_SINK_MAP(CMyCompositeCtrl)
   SINK_ENTRY(IDC_CIRCCTL1, DISPID_CLICK, OnClick_CircCtrl1)
   SINK_ENTRY(IDC_CIRCCTL2, DISPID_CLICK, OnClick_CircCtrl2)
END_SINK_MAP()

Once you have declared the event sink map, proceed to implement the event handlers for the composite control.

Declaration and Implementation of Event Handlers

In the Declaration of the Event Sink Map step, you added a new map that declared two event handlers for the two contained Circ controls. It is now time to implement these handlers. The format is as follows:

retVal __stdcall EventHandler (args)
{
   //handle event firing appropriately
}

where retVal is the return value of the event handler, EventHandler is the name of the function handler, and args is an optional listing of arguments for the event. This name must match one of the event handlers declared in the composite control’s event sink map.

The following code example defines an event handler (the Click event) for the contained control identified by IDC_CIRCCTRL1:

void __stdcall OnClick_CircCtrl1( )
{
   MessageBox("Click event fired!", "CircCtl1", MB_OK);
}

Add event handlers for the remaining entries in the event sink map of your composite control.

Initiating and Terminating Contact with Contained Controls

Before the composite control becomes fully active, each contained control, whose events you are handling, is queried for outgoing interfaces, such as an event dispatch interface. If any interfaces are found, connections are established and a reference to the outgoing interface is used to handle events from the control. This procedure is referred to as “advising the control” and is automatically done by the composite control object, using the event sink map, upon initialization of the composite control.

After the user has dismissed the dialog box, all stored references to outgoing interfaces from contained controls are cleaned up. This is referred to as “unadvising the control” and is also done automatically by the composite control.


Building and Testing the ATL Project

As mentioned in Inserting a Composite Control, one of the initial components of the project is a default HTML page that hosts your new composite control. After you have completed modifying the composite control, choose the Build or Rebuild All option from the Build menu. Once the project successfully builds, load the HTML page, located in the root directory of your composite control project, into Internet Explorer and test the functionality of your control.

In addition to the Internet Explorer, you can test your composite control using the Test Container tool, or any other application that can host an ActiveX control.


ATL Support for DHTML Controls

Using ATL, you can create a control with Dynamic HTML (DHTML) capability. An ATL DHTML control:

  • Hosts the WebBrowser control.

  • Specifies the user interface (UI) of the DHTML control using HTML.

  • Accesses the WebBrowser object and its methods through its interface, IWebBrowser2.

  • Manages communication between C++ code and HTML.

A DHTML control is similar to any other ATL control, except the DHTML control includes an additional dispatch interface. See the figure in Identifying the Elements of the DHTML Control Project for an illustration of the interfaces provided in the default DHTML project.

You can view the ATL DHTML control in a web browser or other container, such as Test Container.

This article covers the following topics:

  • Identifying the Elements of the DHTML Control Project

  • Calling C++ Code from DHTML

  • Creating an ATL DHTML Control

  • Testing the ATL DHTML Control

  • Modifying the ATL DHTML Control

  • Testing the Altered ATL DHTML Control


Identifying the Elements of the DHTML Control Project

Most DHTML control code is exactly like that created for any ATL control. For a basic understanding of the generic code, work through the ATL tutorial, and read the sections Creating an ATL Project and Fundamentals of ATL COM Objects.

A DHTML control is similar to any ATL control, except:

  • In addition to the regular interfaces a control implements, it implements an additional interface that is used to communicate between the C++ code and the HTML user interface (UI). The HTML UI calls into C++ code using this interface.

  • It creates an HTML resource for the control UI.

  • It allows access to the DHTML object model through the member variable m_spBrowser, which is a smart pointer of type IWebBrowser2. Use this pointer to access any part of the DHTML object model.

Examining the elements of the DHTML control project

The following graphic illustrates the relationship between your DLL, the DHTML control, the web browser, and the HTML resource.

Note The names on this graphic are placeholders. The names of your HTML resource and the interfaces exposed on your control are based on the names you assign them in the ATL Object Wizard.

In this graphic, the elements are:

  • My DLL The DLL created using AppWizard.

  • DHTML Control (m_spBrowser) The DHTML control, created using the ATL Object Wizard. This control accesses the web browser object and its methods through the web browser object's interface, IWebBrowser2. The control itself exposes the following two interfaces, in addition to the other standard interfaces required for a control.
    • IDHCTL1 The interface exposed by the control for use only by the container.

    • IDHCTLUI1 The dispatch interface for communicating between the C++ code and the HTML user interface. The web browser uses the control's dispatch interface to display the control. You can call various methods of this dispatch interface from the control's user interface by invoking window.external, followed by the method name on this dispatch interface that you want to invoke. You would access window.external from a SCRIPT tag within the HTML that makes up the UI for this control. For more information about invoking external methods in the resource file, see Calling C++ Code from DHTML.
  • IDR_CTL1 The resource ID of the HTML resource. Its file name, in this case, is DHCTL1UI.htm. The DHTML control uses an HTML resource that contains standard HTML tags and external window dispatch commands that you can edit using the Text editor.

  • Web Browser The web browser displays the control's UI, based on the HTML in the HTML resource. A pointer to the web browser's IWebBrowser2 interface is available in the DHTML control to allow access to the DHTML object model.

  • The ATL Object Wizard generates a control with default code in both the HTML resource and the .cpp file. You can compile and run the control as it is generated by the wizard, and then view the control in either the web browser or Test Container. The picture below shows the default ATL DHTML control with three buttons displayed in Test Container:

See Creating an ATL DHTML Control to get started building a DHTML control.

ATL Support for DHTML Controls


Calling C++ Code from DHTML

A DHTML control can be hosted in a container, such as the Test Container or Internet Explorer. The container hosting the control communicates with the control using the normal control interfaces. DHTML uses the dispatch interface that ends with "UI" to communicate with your C++ code and your HTML resource. In Modifying the ATL DHTML Control, you can practice adding the methods to be called by these different interfaces.

To see an example of calling C++ code from DHTML, create a DHTML control using the ATL COM Object Wizard and examine the code in the header file and in the HTML file.

Declaring WebBrowser methods in the header file

To invoke C++ methods from the DHTML UI, you must add methods to your control's UI interface. For example, the header file created by the ATL Object Wizard contains the C++ method OnClick, which is a member of the UI interface of the wizard-generated control.

Examine OnClick in the control's .h file:

STDMETHOD(OnClick)(IDispatch* pdispBody, VARIANT varColor)

The first parameter, pdispBody, is a pointer to the body object's dispatch interface. The second parameter, varColor, identifies the color to apply to the control.

Calling C++ code in the HTML file

Once you have declared the WebBrowser methods in the header file, you can invoke the methods from the HTML file. Notice in the HTML file that the ATL Object Wizard inserts three Windows dispatch methods: three OnClick methods that dispatch messages to change the background color of the control.

Examine one of the methods in the HTML file:

<BUTTON onclick='window.external.OnClick(theBody, "red");'>Red</BUTTON>

In the HTML code above, the window external method, OnClick, is called as part of the button tag. The method has two parameters: theBody, which references the body of the HTML document, and "red", which indicates that the control's background color will be changed to red when the button is clicked. The Red following the tag is the button's label.

See Modifying the ATL DHTML Control for more information about providing your own methods. See Identifying the Elements of the DHTML Control Project for more information about the HTML file.

ATL Support for DHTML Controls


Creating an ATL DHTML Control

The ATL Object Wizard, provided by Visual C++, automates the process of creating a DHTML control. It generates the necessary resource files, including an HTML file containing sample code.

To create an ATL DHTML control

  1. Using AppWizard, create an ATL Project, as described elsewhere in the ATL documentation.

  2. From the ATL Object Wizard, in the right pane, click Control. In the left pane, click HTML Control. Click Next.

  3. In the ATL Object Wizard Properties dialog box, type the name of the control in the edit box labeled Short Name. This name becomes the root for all other names in this page. Click OK to accept the defaults.

You can now test the default control.

ATL Support for DHTML Controls


Testing the ATL DHTML Control

Once you have created your project, you can build and test the sample control. Before you do this, use ClassView and FileView to examine the project. The elements of your project are described in greater detail in Identifying the Elements of the DHTML Control Project.

To build and test the ATL DHTML control

  1. Build the project. From the Build menu, click Rebuild All.

  2. When the build is completed, from the Tools menu, click ActiveX Control Test Container to launch the Test Container application.

  3. In Test Container, from the Edit menu, click Insert New Control.

  4. In the Insert Control dialog box, select your control from the list box. Remember, its name is based on the short name you indicated in the ATL Object Wizard. Click OK.

  5. Examine the control. Note that it has a scroll bar. Use the control's handles to resize the control to activate the scrollbar.

  6. Test the control's buttons. The background color changes to the color indicated by the button.

  7. Close Test Container.

Next, try modifying the DHTML control.

ATL Support for DHTML Controls


Modifying the ATL DHTML Control

The ATL Object Wizard provides starter code so you can build and run the control, and so you can see how the methods are written in the project files and how the DHTML calls into the control's C++ code using the dispatch methods. You can add any dispatch method to the interface. Then, you can call the methods in the HTML resource.

To modify the ATL DHTML control

  1. In ClassView, expand the control project.

    Note that the interface that ends in "UI" has one method, OnClick. The interface that does not end in "UI" does not have any methods.

  2. Add a method called MethodInvoked to the interface that does not end in "UI."

    This method will be added to the interface that is used in the control container for container interaction, not to the interface used by DHTML to interact with the control. Only the container can invoke this method.

  3. Find the stubbed-out method in the .cpp file and add code to display a message box, for example:
    ::MessageBox(NULL, "I'm invoked", "Your Container Message", MB_OK);
  4. Add another method called HelloHTML, only this time, add it to the interface that ends in "UI." Find the stubbed-out HelloHTML method in the .cpp file and add code to display a message box, for example:
    ::MessageBox(NULL, "Here's your message", "HelloHTML", MB_OK);
  5. Add a third method, GoToURL, also to the interface ending in "UI." Implement this method by calling IWebBrowser2::Navigate, as follows:
    m_spBrowser->Navigate(CComBSTR("www.microsoft.com"), NULL, NULL, NULL, NULL);

    You can use the IWebBrowser2 methods because ATL provides a pointer to that interface for you in your .h file.

Next, modify the HTML resource to invoke the methods you created. You will add three buttons for invoking these methods.

To modify the HTML resource

  1. In FileView, double-click the .htm file to display the HTML resource.

    Examine the HTML, especially the calls to the external Windows dispatch methods. The HTML calls the project's OnClick method, and the parameters indicate the body of the control (theBody) and the color to assign ("red"). The text following the method call is the label that appears on the button.

  2. Add another OnClick method, only change the color. For example:
    <br>
<br>
<BUTTON onclick='window.external.OnClick(theBody, "white");'>Refresh</BUTTON>

    This method will create a button, labeled Refresh, that the user can click to return the control to the original, white background.

  3. Add the call to the HelloHTML method you created. For example:
    <br>
<br>
<BUTTON onclick='window.external.HelloHTML();'>HelloHTML</BUTTON>

    This method will create a button, labeled HelloHTML, that the user can click to display the HelloHTML message box.

  4. Finally, add the call to the GoToURL method you created. For example:
    <br>
<br>
<BUTTON onclick='window.external.GoToURL();'>WWW</BUTTON>

    This method will create a button, labeled WWW, that the user can click to display the Microsoft Web page in the control.

You can now build and test the modified DHTML control.

ATL Support for DHTML Controls


Testing the Modified ATL DHTML Control

Try out your new control to see how it works now.

  1. Rebuild the project and open it in Test Container. Resize the control to show all of the buttons you added. Before you try them, test the method that is not part of the UI.

  2. Highlight the control, so the border is activated.

  3. On the Control menu, click Invoke Methods.

    The only method on the list labeled Method Name is the method that the container can call: MethodInvoked. All other methods are controlled by the UI.

  4. Click Invoke to display the method's message box.

  5. Click OK and then, in the Invoke Methods dialog box, click Close.

  6. Examine the three buttons that you inserted by altering the HTML. Each button bears the label you identified in the previous topic: Refresh, HelloHTML, and WWW.

  7. Test the three new buttons to see how they work.

To learn more about the various elements and files that make up an ATL DHTML control, see Identifying the Elements of the DHTML Control Project.

ATL Support for DHTML Controls


MMC Snap-In Wizard

The Microsoft Management Console (MMC) Snap-In wizard is designed to easily create a framework for an MMC snap-in object, for use in an ATL project. The snap-in object is implemented with several ATL classes and macros.

This article discusses the following topics:

  • Overview of the MMC Snap-In Wizard

  • MMC Snap-In FAQ

This article is intended for developers who have prior experience developing snap-in objects and ATL projects. It is not intended as a tutorial but a supplement, regarding ATL support for MMC snap-ins, to the existing Platform SDK documentation. For more information, see Microsoft Management Console in the Platform SDK.


Overview of the MMC Snap-In Wizard

One of the objects provided by the ATL Object wizard is the MMC snap-in object. The Snap-In wizard is a simple two-page wizard that generates a framework for a snap-in object in an existing ATL project. The following topics are discussed:

  • Basic Structure of the Snap-In Wizard

  • Code Generated by the Snap-In Wizard

  • Differences Between a Snap-In and a Snap-In Extension

  • Effects of Options on the Generated Files


Basic Structure of the Snap-In Wizard

The Snap-In wizard consists of two pages. The first page allows the user to enter the common name of the snap-in object. From this string, the remaining names of the various objects and files are generated. It is recommended that you use the default naming convention.

The second page is more complex because there are a variety of optional elements that can be included in a snap-in object. The page is divided into three parts:

  • Extension SnapIn

    Determines if the new snap-in will be an extension of an existing snap-in and, if so, the name of the snap-in to be extended. Snap-in extensions can be of many types, from additional commands or buttons to a new node type. The extended snap-in must exist on the development machine. By default, the snap-in is not an extension.

  • Interfaces

    Determines the interfaces supported by the snap-in object. These interfaces include:

    • IComponentData

      Allows communication between the MMC console and items in the scope pane. Supported by default.

    • IComponent

      Allows communication between the MMC console and items in the result pane. Supported by default.

    • ISnapInAbout

      Enables the MMC console to get version and copyright information from the snap-in object. Supported by default.

    • IExtendContextMenu

      Allows extension (customization) of the snap-in context menu. Not supported by default.

    • IExtendPropertySheet

      Allows extension (customization) of the snap-in property sheet (or sheets). Not supported by default.

    • IExtendContextControlbar

      Allows extension (customization) of the snap-in control bar. Not supported by default.

  • Persistence

    Determines the type of persistence used by the snap-in object: storage, stream, or an initialized stream. By default, the snap-in uses storage persistence.

For more information on the effects of various options on the generated snap-in object, see Effects of Options on the Generated Files.


Code Generated by the Snap-In Wizard

Once you have determined the name and options for your snap-in object, the Snap-In wizard generates the necessary files and adds them to the existing ATL project.

Every generated snap-in object is implemented with three files. For this discussion, MySnapIn is the short name of the snap-in and the default options are accepted. The generated files are as follows:

  • MYSNAPIN.CPP

    Defines the GUIDs used by data members of the snap-in data class (CMySnapInData).

  • MYSNAPIN.H

    Contains the declarations for the five classes that implement the ATL snap-in object (in this case, MySnapIn):

    Class | Implements
    CMySnapInData | Data class of the snap-in
    CMySnapInComponent | Icomponent interface
    CMySnapIn | IcomponentData interface
    CMySnapInAbout | IsnapInAbout interface
    CMySnapInPage | Property page of the snap-in

  • MYSNAPIN.RGS

    Registers the snap-in object with the operating system upon the first usage.


Differences Between a Snap-In and a Snap-In Extension

By default, the Snap-In wizard generates a standard snap-in object. However, if you choose the Snap-In Extension option, the generated code will differ from the standard snap-in code. Specifically, the difference lies in the data class object of the snap-in extension (CMySnapInData). There are two main differences, both occurring in the header file of the generated data class.

  • The first difference is an additional method declaration, InitDataClass, in CMySnapInData. The InitDataClass method provides a safe method for initializing the m_pDataObject member of the extension data class (CMySnapInExtData). The default implementation caches a pointer to the snap-in object being extended, in the m_pDataObject member. In most cases, no further action is required.

    However, if the extended snap-in data object needs to be converted to the internal format (which the data represents) before being cached, this method provides a convenient access point to perform that conversion.

  • The second difference is an additional macro and map for the data class (CMySnapInExtData). The macro, found before the new map, creates a data member of type CMySnapInExtData in the extended snap-in object. After this macro, the extension node info map is declared. The declaration includes the BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP, END_EXTENSION_SNAPIN_NODEINFO_MAP, and EXTENSION_SNAPIN_NODEINFO_ENTRY macros. Each entry in the map specifies the CMySnapInExtData class.


Effects of Options on the Generated Files

MYSNAPIN.H and MYSNAPIN.RGS are the only files affected by the options on the second page.

MYSNAPIN.H

Each interface, from the IExtend* radio button group, that is checked adds a declaration of that specific interface to the CMySnapInComponent class. For instance, choosing the IExtendControlbar interface adds the following line to the member-wise initialization of the class:

public IExtendControlbarImpl<CMySnapInComponent>,

and the following line to CMySnapInComponent's COM map:

COM_INTERFACE_ENTRY(IExtendControlbar)

Similar modifications are made to CMySnapInComponent for the type of persistence chosen.

In addition to the modifications above, all methods of the persistence interface chosen are declared in MYSNAPIN.H. For instance, the following code is added if you choose IPersistStorage as the type of persistence:

STDMETHOD(GetClassID)(CLSID *pClassID)
{
    ATLTRACENOTIMPL(_T("CMySnapInComponent::GetClassID"));
}

//additional IPersistStorage methods
...

virtual HRESULT STDMETHODCALLTYPE HandsOffStorage()
{
    ATLTRACENOTIMPL(_T("CMySnapInComponent::HandsOffStorage"));
}

The modifications are similar for the CMySnapIn class.

If the ISnapInAbout interface is chosen, a separate class is declared (CMySnapInAbout), and the standard methods are declared.

MYSNAPIN.RGS

If the snap-in is a snap-in extension, the .RGS file generated by the wizard will differ slightly from the default. Specifically, two portions in the NoRemove MMC section will be modified to associate the snap-in extension object with the extended snap-in object.

For example, the following section sample is from a default snap-in object's .RGS file:

NoRemove MMC
    {
        NoRemove Snapins
        {
            ForceRemove {ACC4CCCD-8C61-11D1-B017-00C04FB99436} =
            s 'MySnapIn'
            {
                val NameString = s 'MySnapIn'
                val About = s '{ACC4CCCE-8C61-11D1-B017-00C04FB99436}'
                NodeTypes
                {
                    {ACC4CCCF-8C61-11D1-B017-00C04FB99436}
                }
                StandAlone
            }
        }
        NoRemove NodeTypes
        {
            ForceRemove {ACC4CCCF-8C61-11D1-B017-00C04FB99436}
            {
            }

        }
    }

However, for the snap-in extension, the NoRemove MMC section differs:

NoRemove MMC
    {
        NoRemove Snapins
        {
            ForceRemove {ACC4CCD5-8C61-11D1-B017-00C04FB99436} =
            s 'MySnapInDataExt1'
            {
                val NameString = s 'MySnapInDataExt1'
                val About = s '{ACC4CCD6-8C61-11D1-B017-00C04FB99436}'
            }
        }
        NoRemove NodeTypes
        {
            NoRemove {}
            {
                NoRemove Extensions
                {
                    NoRemove PropertySheet
                    {
                        val {ACC4CCD5-8C61-11D1-B017-00C04FB99436} =
                        s 'MySnapInDataExt1'
                    }
                    NoRemove ToolBar
                    {
                        val {ACC4CCD5-8C61-11D1-B017-00C04FB99436} =
                        s 'MySnapInDataExt1'
                    }
                }
            }

        }
    }


MMC Snap-In FAQ

The following questions are designed to assist developers in customizing and adding implementation support for the snap-in object.

  • How Do I Add a Toolbar Resource to the Snap-In Object?

  • How Do I Add Menu Items, Control Bar Buttons, and a Property Sheet to the Snap-In Object?

  • How Do I Enumerate the Child Items of the Snap-In Object?

  • How Do I Add Custom Item Types to the Snap-In Object?


How Do I Add a Toolbar Resource to the Snap-In Object?

By default, the MMC Snap-In wizard does not provide a toolbar resource for the snap-in template. The reason being that the ID of the toolbar resource is unknown at the time of creation. However, you can add a toolbar manually in a few steps.

  1. Create a toolbar resource for the snap-in project, using the Toolbar editor. Make sure that each toolbar button is 16 pixels wide by 16 pixels high.

  2. Locate the toolbar ID map of the snap-in object map of the data class of the snap-in object (located in the snapin_name.H file).

  3. Modify the map by adding an entry between BEGIN_SNAPINTOOLBARID_MAP and END_SNAPINTOOLBARID_MAP similar to the following:
    SNAPINTOOLBARID_ENTRY(IDR_TBARNAME)
  4. Save your changes to the project and rebuild.

Note Use additional SNAPINTOOLBARID_ENTRY macros to add additional toolbar resources to the snap-in module.


How Do I Add Menu Items, Control Bar Buttons, and a Property Sheet to the Snap-In Object?

There are several user interface (UI) components of the MMC snap-in object that can be customized. Some of these areas, such as toolbar buttons and menu items, affect components of the MMC application. The final component is a standard property sheet that displays the properties, of the snap-in object, that can be customized by the user. By default, the MMC Snap-In wizard does not generate any custom UI elements. However, there are placeholders throughout the snap-in object code that indicate where your custom UI elements can go.

Adding Custom Context Menu Items

One area you can customize is the context menu for the items of the snap-in object. Four menu items are available for customization: Top, New, Task, and View. The Snap-In wizard creates a menu resource with placeholders for the four slots.

Because the menu resource is known by the snap-in object, add any custom menu items needed under the appropriate slot and they automatically appear in the context menu of any snap-in item. The snap-in item knows which menu resource to use because the data object contains the following declaration:

SNAPINMENUID(IDR_MMCSNAP_MENU)

The Platform SDK provides an interface ( IExtendContextMenu) to customize the context menu of a snap-in item. In most cases, you don't need to call this interface directly, but if the snap-in is advanced, more information on this interface is available in the Platform SDK.

Adding Control Bar Buttons

If your snap-in object uses a custom toolbar, you can add any number of buttons to it once the toolbar resource has been created. You can then provide handlers for each button to handle custom tasks. For more information, see How Do I Add a Toolbar Resource to the Snap-In Object?.

The Platform SDK provides an interface ( IExtendControlbar) to customize the control bar of a snap-in. In most cases, you don't need to call this interface directly, but if the snap-in is advanced, more information on this interface is available in the Platform SDK.

Adding a Property Sheet

Each snap-in item can display a standard property sheet, accessible from the context menu when the user right-clicks the mouse.

By default, the MMC Snap-In wizard does not provide the implementation for this functionality. However, if you select the IExtendPropertySheet check box, the wizard creates a default property page class (CSnapNamePage, derived from CSnapInPropertyPageImpl) and a dialog resource (IDD_SnapName) for the property sheet.

To complete this feature, add controls that allow the user to modify the properties of the snap-in item.

To add additional pages to the property sheet, you need a new property page class, a new dialog resource, and additional code in the CreatePropertyPages method of your data class. In this example, the new class is called CMMCSnapPage2 and the dialog resource is IDD_MMCSNAP2.

Once you have the necessary classes and resources, add them to the CreatePropertyPages method to create and add the new property page to the sheet. For example, the following code adds a new page (pPage2), implemented with the new CMMCSnapPage2 class, to the snap-in object:

CMMCSnapPage2* pPage2 = new CMMCSnapPage2(_T("MMCSnap2"));
lpProvider->AddPage(pPage2->Create());

The Platform SDK provides an interface ( IExtendPropertySheet) to customize the property sheet of a snap-in. In most cases, you don't need to call this interface directly, but if the snap-in is advanced, more information on this interface is available in the Platform SDK.


How Do I Enumerate the Child Items of the Snap-In Object?

To properly display the contents of a snap-in object, you need to enumerate the child items of the object, if they exist. The best place for this modification is in the Notify method of the snap-in data class (in this discussion, CSnapNameData).

Note The snap-in data class is derived from CSnapInItemImpl.

By default, the ATL Object Wizard creates a handler for this notification. In this handler, you need to modify the existing switch statement to handle the MMCN_EXPAND and MMCN_SHOW notifications.

Handling the MMCN_EXPAND Notification

The MMCN_EXPAND notification is sent when the snap-in object folder needs to be expanded or contracted. In this case, you need only enumerate the scope pane items. This enumeration is done in the case statement for the MMCN_EXPAND notification.

To insert the scope pane items, first retrieve the IConsoleNameSpace interface for the snap-in object, and then call the InsertItem method. The following code demonstrates retrieval of the necessary interfaces:

CComQIPtr<IConsoleNameSpace,
&IID_IConsoleNameSpace> spConsoleNameSpace(pConsole);
// TODO : Enumerate scope pane items with a user-defined function

Handling the MMCN_SHOW Notification

The MMCN_SHOW notification is sent when an item is selected or de-selected for the first time. This enumeration is done in the case statement for the MMCN_SHOW notification. Unlike the MMCN_EXPAND notification, you must enumerate both the result pane items and scope pane items.

First, enumerate the scope items by retrieving the IConsoleNameSpace interface for the snap-in object, and then calling the InsertItem method. After you have enumerated the scope pane items, do the same for the result pane items by retrieving the IResultData interface and making a call to InsertItem.

CComQIPtr<IConsoleNameSpace,
&IID_IConsoleNameSpace> spConsoleNameSpace(pConsole);
// TODO : Enumerate scope pane items with a user-defined function
CComQIPtr<IResultData, &IID_IResultData> spResultData(pConsole);
// TODO : Enumerate the result pane items with a user-defined function


How Do I Add Custom Item Types to the Snap-In Object?

By default, the ATL Object Wizard creates a single data class, derived from CSnapInItemImpl, for the snap-in object.

In some cases, you need to implement one or more custom item types for a snap-in object. The simplest approach is to copy and modify a new class from the existing data class and make some additional modifications to the project. This procedure is accomplished in three steps:

  • Creating a Custom Item Data Class

  • Implementing the GUIDs for the Custom Data Class

  • Modifying the .RGS File of the Snap-In Project

Creating a Custom Item Data Class

The first step involves copying the declaration of the existing data class for the snap-in object and then modifying the results to create a separate class.

The data class declaration can be found at the beginning of the PROJNAME.H file of your snap-in project. Locate this class declaration, and copy and paste the result below the first declaration.

In the newly pasted declaration, replace any occurrences of the first class name with the name of the new second class. For instance, if your project data class is called CMySnapInData and you want to create a custom data item class called CMyCustomSnapInData, first copy and paste the declaration of the initial data class. Then search for any occurrences of CMySnapInData (in the pasted section) and replace it with CMyCustomSnapInData.

Implementing the GUIDs for the Custom Data Class

In addition to the class declaration, the data class has a GUID declaration and four static data members. The GUID and data members are defined at the end of the PROJNAME.CPP file. The following is an example declaration:

static const GUID CProjNameGUID_NODETYPE =
{ 0xb386c6b, 0x8633, 0x11d1, { 0xb0, 0x8, 0x0, 0xc0, 0x4f, 0xb9, 0x94, 0x36 } };
const GUID*  CProjNameData::m_NODETYPE = &CsdfdsfGUID_NODETYPE;
const TCHAR* CProjNameData::m_SZNODETYPE = _T("0B386C6B-8633-11D1-B008-00C04FB99436");
const TCHAR* CProjNameData::m_SZDISPLAY_NAME = _T("Csdfdsf");
const CLSID* CProjNameData::m_SNAPIN_CLASSID = &CLSID_sdfdsf;

Because these data members depend upon a GUID, you need to first generate a new GUID (using GUIDGEN) and then copy and paste the five declarations, of the initial data class, directly below. After you create a copy, modify it to use the newly created GUID. For example, using the preceding code sample and generating a new GUID, the result for the second data class would be as follows:

static const GUID CMyCustomSnapInGUID_NODETYPE =
    { 0x8dbeb252, 0x9201, 0x11d1, { 0xa8, 0xd6, 0x0, 0x60, 0x8, 0x93,
        0x8f, 0xb8 } };
const GUID*  CMyCustomSnapIn::m_NODETYPE = &CMySnapInGUID_NODETYPE;
const TCHAR* CMyCustomSnapIn::m_SZNODETYPE =
    _T("8DBEB252-9201-11D1-A8D6-006008938FB8");
const TCHAR* CMyCustomSnapIn::m_SZDISPLAY_NAME = _T("CMyCustomSnapIn");
const CLSID* CMyCustomSnapIn::m_SNAPIN_CLASSID = &CLSID_MyCustomSnapIn;

After these modifications are complete, there is one step left: modifying the registry file for the snap-in object.

Modifying the .RGS File of the Snap-In Project

The purpose of the .RGS file is to register the snap-in object and all its components. Because you have added a custom data item class, you need to modify the .RGS file to register this class too.

Note The GUID you generated in the previous step is used in this step.

There are two areas in the .RGS file you need to modify. Both can be found quickly by searching for the NodeTypes keyword.

The first occurrence is under the NoRemove Snapins section. In the nested NodeTypes section, add the new GUID immediately after the existing one, using the same GUID format as the existing one.

The second occurrence is in the NoRemove NodeTypes section. Copy the code found in this section, paste it in immediately after, and change the referenced GUID to the GUID of the custom class.

This completes the modifications of the snap-in project. After a successful compile, you will have a new custom item type.


ATL Window Classes

ATL contains several classes that allow you to use and implement windows. These classes, like other ATL classes, provide an efficient implementation that does not impose an overhead on your code.

  • CWindow allows you to attach a window handle to the CWindow object. You then call CWindow methods to manipulate the window.

  • CWindowImpl allows you to implement a new window and process messages with a message map. You can create a window based on a new Windows class, superclass an existing class, or subclass an existing window.

  • CDialogImpl allows you to implement a modal or a modeless dialog box and process messages with a message map.

  • CContainedWindow is a pre-built class that implements a window whose message map is contained in another class. Using CContainedWindow allows you to centralize message processing in one class.

  • CAxDialogImpl allows you to implement a dialog box (modal or modeless) that hosts ActiveX controls.

  • CSimpleDialog allows you to implement a dialog box (modal or modeless) with basic functionality.

  • CAxWindow allows you to implement a window that hosts an ActiveX control.

  • In addition to specific window classes, ATL provides several classes designed to make the implementation of an ATL window object easier. They are as follows:

  • CWndClassInfo manages the information of a new window class.

  • CWinTraits and CWinTraitsOR provide a simple method of standardizing the traits of an ATL window object.

This article explains how to use the ATL window classes. Topics covered include:

  • Using a window

  • Implementing a window

  • Implementing a dialog box

  • Using contained windows


Using a Window

Class CWindow allows you to use a window. Once you attach a window to a CWindow object, you can then call CWindow methods to manipulate the window. CWindow also contains an HWND operator to convert a CWindow object to an HWND. Thus you can pass a CWindow object to any function that requires a handle to a window. You can easily mix CWindow method calls and Win32 function calls, without creating any temporary objects.

Because CWindow has only one data member (a window handle), it does not impose an overhead on your code. In addition, many of the CWindow methods simply wrap corresponding Win32 API functions. By using CWindow, the HWND member is automatically passed to the Win32 function.

In addition to using CWindow directly, you can also derive from it to add data or code to your class. ATL itself derives three classes from CWindow: CWindowImpl, CDialogImpl, and CContainedWindow.


Implementing a Window

Class CWindowImpl allows you to implement a window and handle its messages. Message handing in ATL is based on a message map. This section explains:

  • How to add a message handler to a control.

  • What message maps are and how to use them.

  • How to implement a window with CWindowImpl.


Adding a Message Handler

You can use ClassView or the WizardBar to add a message handler (a member function that handles Windows messages) to a control, and map Windows messages to the message handler.

Adding a message handler in ATL is the similar to adding a message handler to an MFC class. See Adding a Message Handler in The Visual C++ Programmer's Guide for more information.

The following conditions apply only to adding an ATL message handler:

  • The message handlers follow the same naming convention as MFC.

  • The Add Windows Message Handler option is enabled only if there is a message map in the class definition. Otherwise, this option is disabled.

  • The new message map entries are added into the main message map. The wizard does not recognize alternate message maps and chaining.


Message Maps

A message map associates a handler function with a particular message, command, or notification. By using ATL's message map macros, you can specify a message map for a window. The window procedures in CWindowImpl, CDialogImpl, and CContainedWindow direct a window's messages to its message map.

The message handler functions accept an additional argument of type BOOL&. This argument indicates whether a message has been processed, and it is set to TRUE by default. A handler function can then set the argument to FALSE to indicate that it has not handled a message. In this case, ATL will continue to look for a handler function further in the message map. By setting this argument to FALSE, you can first perform some action in response to a message and then allow the default processing or another handler function to finish handling the message.

ATL also allows you to chain message maps, which directs the message handling to a message map defined in another class. For example, you can implement common message handling in a separate class to provide uniform behavior for all windows chaining to that class. You can chain to a base class or to a data member of your class.

ATL also supports dynamic chaining, which allows you to chain to another object's message map at run time. To implement dynamic chaining, you must derive your class from CDynamicChain. Then declare the CHAIN_MSG_MAP_DYNAMIC macro in your message map. CHAIN_MSG_MAP_DYNAMIC requires a unique number that identifies the object and the message map to which you are chaining. You must define this unique value through a call to CDynamicChain::SetChainEntry.

You can chain to any class that declares a message map, provided the class derives from CMessageMap. CMessageMap allows an object to expose its message maps to other objects. Note that CWindowImpl already derives from CMessageMap.

Finally, ATL supports alternate message maps, declared with the ALT_MSG_MAP macro. Each alternate message map is identified by a unique number, which you pass to ALT_MSG_MAP. Using alternate message maps, you can handle the messages of multiple windows in one map. Note that by default, CWindowImpl does not use alternate message maps. To add this support, override the WindowProc method in your CWindowImpl-derived class and call ProcessWindowMessage with the message map identifier.


Implementing a Window with CWindowImpl

To implement a window, derive a class from CWindowImpl. In your derived class, declare a message map and the message handler functions. You can now use your class in three different ways:

  • Creating a window based on a new Windows class

  • Superclassing an existing Windows class

  • Subclassing an existing window

Creating a window based on a new Windows class

CWindowImpl contains the DECLARE_WND_CLASS macro to declare Windows class information. This macro implements the GetWndClassInfo function, which uses CWndClassInfo to define the information of a new Windows class. When CWindowImpl::Create is called, this Windows class is registered and a new window is created.

Note CWindowImpl passes NULL to the DECLARE_WND_CLASS macro, which means ATL will generate a Windows class name. To specify your own name, pass a string to DECLARE_WND_CLASS in your CWindowImpl-derived class.

Following is an example of a class that implements a window based on a new Windows class:

class CMyWindow : public CWindowImpl<CMyWindow>, ...
{
public:
   // Optionally specify name of the new Windows class
   DECLARE_WND_CLASS("MyName")
              // If this macro is not specified in your
              // class, ATL will generate a class name
   ...

   BEGIN_MSG_MAP(CMyWindow)
      MESSAGE_HANDLER(WM_PAINT, OnPaint)
   END_MSG_MAP()

   LRESULT OnPaint(UINT nMsg, WPARAM wParam,
                   LPARAM lParam, BOOL& bHandled)
   {
      // Do some painting code
      return 0;
   }
};

To create a window, create an instance of CMyWindow and then call the Create method.

Note To override the default Windows class information, implement the GetWndClassInfo method in your derived class by setting the CWndClassInfo members to the appropriate values.

Superclassing an existing Windows class

The DECLARE_WND_SUPERCLASS macro allows you to create a window that superclasses an existing Windows class. Specify this macro in your CWindowImpl-derived class. Like any other ATL window, messages are handled by a message map.

When you use DECLARE_WND_SUPERCLASS, a new Windows class will be registered. This new class will be the same as the existing class you specify, but will replace the window procedure with CWindowImpl::WindowProc (or with your function that overrides this method).

Following is an example of a class that superclasses the standard Edit class:

class CMyEdit : public CWindowImpl<CMyEdit>, ...
{
public:
   // "Edit" is the name of the standard Windows class.
   // "MyEdit" is the name of the new Windows class
   // that will be based on the Edit class.
   DECLARE_WND_SUPERCLASS("Edit", "MyEdit")

   ...
   BEGIN_MSG_MAP(CMyEdit)
      MESSAGE_HANDLER(WM_CHAR, OnChar)
   END_MSG_MAP()

   LRESULT OnChar(UINT nMsg, WPARAM wParam,
                  LPARAM lParam, BOOL& bHandled)
   {
      // Do some character handling code
   }
};

To create the superclassed Edit window, create an instance of CMyEdit and then call the Create method.

For more information about superclassing, see Window Procedure Superclassing in the Win32 SDK.

Subclassing an existing window

To subclass an existing window, derive a class from CWindowImpl and declare a message map, as in the two previous cases. Note, however, that you do not specify any Windows class information, since you will subclass an already existing window.

Instead of calling Create, call SubclassWindow and pass it the handle to the existing window you want to subclass. Once the window is subclassed, it will use CWindowImpl::WindowProc (or your function that overrides this method) to direct messages to the message map. To detach a subclassed window from your object, call UnsubclassWindow. The window's original window procedure will then be restored.

For more information about subclassing, see Window Procedure Subclassing in the Win32 SDK.


Implementing a Dialog Box

There are two ways to add a dialog box to your ATL project: use the ATL Object Wizard or add it manually.

Adding a Dialog Box with the ATL Object Wizard

In the ATL Object Wizard (Insert menu, New ATL Object command), highlight the miscellaneous category in the left pane, then double-click the Dialog object in the right pane to add a dialog box to your ATL project. Fill in the ATL Object Wizard Properties dialog box as appropriate and click OK. The ATL Object Wizard adds a class derived from CAxDialogImpl to your project, and opens the resource editor with your dialog box template.

Note If your dialog box is derived from CAxDialogImpl , it can host both ActiveX and Windows controls. If you don’t want the overhead of ActiveX control support in your dialog box class, use CSimpleDialog or CDialogImpl instead.

Message and event handlers can be added to your dialog class from ClassView in the same way as to an MFC class. In ClassView, right-click the class and choose Add Windows Message Handler to open the New Windows Message and Event Handlers dialog box. For more information, see Adding a Message Handler.

To open the New Windows Message and Event Handlers dialog box from the dialog box template, right-click a control in the dialog box template and choose the Events command from the shortcut menu. In an ATL project, the dialog box class is highlighted in the Class or object to handle box; whereas, for an MFC project, the control is highlighted.

Adding a Dialog Box Manually

Implementing a dialog box is similar to implementing a window. You derive a class from either CAxDialogImpl, CDialogImpl, or CSimpleDialog and declare a message map to handle messages. However, you must also specify a dialog template resource ID in your derived class. Your class must have a data member called IDD to hold this value.

Note When you create a dialog box using the ATL Object Wizard, the wizard automatically adds the IDD member as an enum type.

CDialogImpl allows you to implement a modal or a modeless dialog box that hosts Windows controls. CAxDialogImpl allows you to implement a modal or a modeless dialog box that hosts both ActiveX and Windows controls.

To create a modal dialog box, create an instance of your CDialogImpl-derived (or CAxDialogImpl-derived) class and then call the DoModal method. To close a modal dialog box, call the EndDialog method from a message handler. To create a modeless dialog box, call the Create method instead of DoModal. To destroy a modeless dialog box, call DestroyWindow.

If your dialog box object contains ActiveX controls, and you are handling events from these controls, you will need to advise and unadvise all ActiveX control interfaces. This can be done by adding the following line of code to your InitDialog function:

AtlAdviseSinkMap(pMyDlg, TRUE);

To unadvise any ActiveX controls, add the following line of code to your EndDialog function (or the function invoked upon termination of your dialog box object):

AtlAdviseSinkMap(pMyDlg, FALSE);

Implement the dialog box's message handlers as you would the handlers in a CWindowImpl-derived class. If there is a message-specific return value, return it as an LRESULT. The returned LRESULT values are mapped by ATL for proper handling by the Windows dialog manager. For details, see the source code for CDialogImplBaseT::DialogProc in atlwin.h.

Example

The following class implements a dialog box:

class CMyDialog : public CDialogImpl<CMyDialog>, ...
{
public:
   enum { IDD = IDD_MYDIALOG };

   BEGIN_MSG_MAP(CMyDialog)
      MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
   END_MSG_MAP()

   LRESULT OnInitDialog(UINT uMsg, WPARAM wParam,
                        LPARAM lParam, BOOL& bHandled)
   {
      // Do some initialization code
      return 1;
   }
};


Using Contained Windows

ATL implements contained windows with CContainedWindow. A contained window represents a window that delegates its messages to a container object instead of handling them in its own class.

Note You do not need to derive a class from CContainedWindow in order to use contained windows.

With contained windows, you can either superclass an existing Windows class or subclass an existing window. To create a window that superclasses an existing Windows class, first specify the existing class name in the constructor for the CContainedWindow object. Then call CContainedWindow::Create. To subclass an existing window, you don't need to specify a Windows class name (pass NULL to the constructor). Simply call the CContainedWindow::SubclassWindow method with the handle to the window being subclassed.

You typically use contained windows as data members of a container class. The container does not need to be a window; however, it must derive from CMessageMap.

A contained window can use alternate message maps to handle its messages. If you have more than one contained window, you should declare several alternate message maps, each corresponding to a separate contained window.

Following is an example of a container class with two contained windows:

class CMyContainer : public CMessageMap, ...
{
public:
   CContainedWindow m_wndEdit;
   CContainedWindow m_wndList;

   CMyContainer() : m_wndEdit("Edit", this, 1),
                    m_wndList("List", this, 2)
   {
   }

   ...

   BEGIN_MSG_MAP(CMyContainer)
   ALT_MSG_MAP(1)
      // handlers for the Edit window go here
   ALT_MSG_MAP(2)
      // handlers for the List window go here
   END_MSG_MAP()

};

For more information about contained windows, see the SUBEDIT sample. For more information about superclassing and subclassing, see Window Procedure Superclassing and Window Procedure Subclassing in the Win32 SDK.


Connection Points

A connectable object is one that supports outgoing interfaces. An outgoing interface allows the object to communicate with a client. For each outgoing interface, the connectable object exposes a connection point. Each outgoing interface is implemented by a client on an object called a sink.

Each connection point supports the IConnectionPoint interface. The connectable object exposes its connection points to the client through the IConnectionPointContainer interface.

This article:

  • Briefly describes the ATL classes that support connection points.

  • Outlines the steps used to add connection points to an object.

  • Provides an example of declaring a connection point.


Connection Point Classes

ATL uses the following classes to support connection points:

  • IConnectionPointImpl implements a connection point. The IID of the outgoing interface it represents is passed as a template parameter.

  • IConnectionPointContainerImpl implements the connection point container and manages the list of IConnectionPointImpl objects.

  • IPropertyNotifySinkCP implements a connection point representing the IPropertyNotifySink interface.

  • CComDynamicUnkArray manages an arbitrary number of connections between the connection point and its sinks.

  • CComUnkArray manages a predefined number of connections as specified by the template parameter.

  • CFirePropNotifyEvent notifies a client's sink that an object's property has changed or is about to change.


Adding Connection Points to an Object

The ATL Tutorial demonstrates how to create a control with support for connection points, how to add events and then how to implement the connection point. IConnectionPointImpl discusses how ATL implements a connection point.

To implement a connection point, you have two choices:

  • Implement your own out-going event source (connection point).

  • Reuse a connection point interface defined in another type library.

In either case, the connection point wizard uses a type library to do its work.

Note Whenever you add a method to a dispinterface on which you have already implemented a connection point, you must recompile the .idl file and then follow the procedure to add a connection point to a control or object.

To add a connection point to a control or object

  1. Define a dispinterface in the library block of the .idl file. If you selected the Support Connection Points check box in the Attributes tab of the ATL Object Wizard, the dispinterface will already be created. If you did not check the Support Connection Points check box, you must manually add a dispinterface to the .idl file. The following is an example of a dispinterface. Outbound interfaces are not required to be dispatch interfaces but many scripting languages such as VBScript and JavaScript require this, so this example uses two dispinterfaces:
    library DProjLib
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");

[

uuid(57BC50F0-780B-11d1-8C44-0060083E866C),

helpstring("Buddy Events")

]

dispinterface DBuddyEvents

{

properties:

methods:

};

    Use either the uuidgen.exe or guidgen.exe utilities to generate a GUID.

  2. Add the dispinterface as the [default,source] interface in the coclass for the object. Again, if you selected the Support Connection Points check box in the Attributes tab of the ATL Object Wizard for this control, the wizard will create the [default,source] entry. To manually add this entry, add the line in bold:
    coclass Buddy
{
[default] interface IBuddy;
[default,source] dispinterface DBuddyEvents;
};

    See the .idl file in the Circ ATL sample for an example.

  3. Use ClassView to add methods and properties to the event interface.

  4. After the dispinterface is fully defined, compile the .idl file by right-clicking the .idl file in FileView and selecting the compile option. This will produce the type library.

  5. Right-click the class in ClassView and select Implement Connection Point.... A dialog box will display one or more type library tabs and each tab will display the interfaces for that type library. If you choose an interface and press OK, you will:
    • Generate a header file with an event proxy class that implements the code that will make the out-going calls for the event.

    • Add an entry to the connection point map.

    • Add a comment and #error (telling you to replace the NULL parameter with the address of the dispID) to the parameter list of IProvideClassInfo2Impl.

    If you have not built your type library, you will see a list of all the typelibs on your computer. You should only use one of these other typelibs to define your connection point if you want to implement the exact same outgoing interface found in another typelib. If you build a typelib with no default source interface in the coclass, the dialog box will display a warning message reporting no suitable (source) interface in the type library.

To implement a connection point taken from another object's type library

  1. In ClassView, right-click on a class that implements a BEGIN_COM_MAP macro, and select Implement connection point from the shortcut menu.

  2. In the Implement Connection Point dialog box, click Add Typelib....

  3. Select from one of the available type libraries. After you select the type library, you will see a list of the available interfaces in the type library.

  4. Choose one or more of the available interfaces and click OK.

  5. Edit the .idl file to either:
    • Copy the dispinterface from the idl file for the object whose event-source is being used.

    • Use the importlib instruction on that type library.

Here's an example from an .idl file that is using the connection point from the Circ control.

[
   uuid(38BBFD91-7575-11D1-8C3C-0060083E866C),
   version(1.0),
   helpstring("16190 1.0 Type Library")
]
library MY16190Lib
{
   importlib("stdole32.tlb");
   importlib("stdole2.tlb");
   importlib("D:\\ATL25\\samples\\circ\\circ.tlb");   //**** add this line

   [
      uuid(38BBFD9E-7575-11D1-8C3C-0060083E866C),
      helpstring("Atl16190Ctl Class")
   ]
   coclass Atl16190Ctl
   {
      [default] interface IAtl16190Ctl;
      [default,source] dispinterface _CircEvents;      //**** and this one
   };
};


Connection Point Example

This example shows an object that supports IPropertyNotifySink as an outgoing interface:

class CConnect :
   public CComObjectRootEx<CComObjectThreadModel>,
   public CComCoClass<CConnect, &CLSID_CConnect>,
   public IConnectionPointContainerImpl<CConnect>,
   public IConnectionPointImpl<CConnect,
             &IID_IPropertyNotifySink>
{
public:
   ...
   BEGIN_COM_MAP(CConnect)
      COM_INTERFACE_ENTRY_IMPL(IConnectionPointContainer)
   END_COM_MAP()

   BEGIN_CONNECTION_POINT_MAP(CConnect)
      CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink)
   END_CONNECTION_POINT_MAP()

   ...
};

Note When specifying IPropertyNotifySink as an outgoing interface, you can use class IPropertyNotifySinkCP instead of IConnectionPointImpl. For example:

class CConnect :
   public CComObjectRootEx<CComObjectThreadModel>,
   public CComCoClass<CConnect, &CLSID_CConnect>,
   public IConnectionPointContainerImpl<CConnect>,
   public IPropertyNotifySinkCP<CConnect>
{
   ...
};


Enumerators

Enumerators provide a consistent way to iterate through a collection of objects. For example, you can define a simple enumerator to access strings in a collection. A complex enumerator can access records from a database.

This article describes:

  • Implementing enumerators in ATL and COM.

  • Using CComEnum, _Copy, CComIEnum, and CComEnumImpl to create enumerators in ATL.

ATL does not define any standard objects for enumerators. However, it does provide you with the infrastructure for building them easily using the CComEnum and _Copy templates.

COM implements enumerators as separate objects that usually support a single interface, IEnum xxxx, where xxxx is the type that is being enumerated. Standard enumerator types defined by COM include: IEnumUnknown, IEnumMoniker, IEnumString, IEnumVARIANT, IEnumFORMATETC, IEnumSTATSTG, IEnumSTATDATA, and IEnumOLEVERB.


Using CComEnum, _Copy, CComIEnum, and CComEnumImpl to Create Enumerators in ATL

In ATL, CComEnum<Base, piid, T, Copy> defines an enumerator object that enumerates objects of type T. The parameter Base is the name of the interface that represents this enumerator (for example, IEnumVARIANT), and piid is a pointer to the IID of that interface. The parameter Copy is the name of a class used by CComEnum to implement copying the type and is typically used when cloning the enumerator.

A _Copy<class T> class performs deep copy semantics for the particular type T. ATL predefines certain copy classes for your convenience: _Copy<VARIANT>, _Copy<LPOLESTR>, _Copy<OLEVERB>, _Copy<CONNECTDATA>, and _CopyInterface<>. These can be used to quickly build many of the standard enumerators.

CComIEnum is a pure virtual class that defines an enumeration interface.

CComEnumImpl implements the methods on the enumeration interface: Next, Skip, Reset, and Clone. Generally, this class is only used internally by ATL during the implementation of CComIEnum.


Debugging Tips for ATL Objects

The debugging tips included in this article are:

  • Setting breakpoints using DebugBreak

  • Debugging QueryInterface calls

  • Debugging AddRef and Release calls

See Also Debugging Tips in "ATL Services"


Using DebugBreak

You can have your program call the DebugBreak Win32 function at the point in your code that you want debugging to start. Calling this function causes the program to display a dialog box as if it had crashed. Click Cancel to start the debugger and continue on in debug mode.


Enabling QueryInterface Debugging

ATL has built-in support for debugging QueryInterface calls. You enable this support using the following two-step process.

To enable QueryInterface debugging

  1. Run the FINDGUID program which comes with ATL and specify -insert as the command line parameter:

    findguid -insert

    This ensures all the common IIDs are in the interfaces section of your registry. You need to only do this once.

  2. Add the following line before including atlcom.h:

    #define _ATL_DEBUG_QI

Once you've enabled QueryInterface debugging, the debug output window of Visual C++ will display the name of each interface that is queried for on your object.


Enabling Reference Count Debugging

ATL has built-in support for tracing the reference count through AddRef and Release calls.

To enable reference count debugging

Add the following line before including atlbase.h:

#define _ATL_DEBUG_INTERFACES

With reference count debugging enabled, the debug output window of Visual C++ will display the current reference count for the interface along with the corresponding class name and interface name every time AddRef or Release is called.


ATL Services

To create your ATL COM object so that it runs in a service, simply select Service from the list of server options in the ATL COM AppWizard. The wizard will then create a CServiceModule class to implement the service.

The first four sections of this article discuss the actions that occur during execution of CServiceModule member functions. These topics appear in the same sequence as the functions are typically called. To improve your understanding of these topics, it is a good idea to use the source code generated by the ATL COM AppWizard as reference. These first four sections are:

  • CServiceModule::Start

  • CServiceModule::ServiceMain

  • CServiceModule::Run

  • CServiceModule::Handler

The last three sections of this article discuss concepts related to developing a service:

  • Registry Entries for ATL services

  • DCOMCNFG

  • Debugging Tips for ATL services

Note When the ATL COM object is built as a service, it will only be registered as a local server, and it will not appear in the Control Panel's list of services. This is because it is easier to debug the service as a local server than a service. To install it as a service, you must run the following at the command prompt:

YourEXE.exe /Service


CServiceModule::Start

The WinMain routine handles both registration and installation, as well as deregistration and uninstallation. When the service is run, WinMain calls CServiceModule::Start.

CServiceModule::Start sets up an array of SERVICE_TABLE_ENTRY structures that map each service to its startup function. This array is then passed to the Win32 API function, StartServiceCtrlDispatcher. In theory, one EXE could handle multiple services and the array could have multiple SERVICE_TABLE_ENTRY structures. Currently, however, an ATL-generated service supports only one service per EXE. Therefore, the array has a single entry that contains the service name and _ServiceName as the startup function. _ServiceName is a static member function of CServiceModule that calls the non-static member function, ServiceName.

Note Failure of StartServiceCtrlDispatcher to connect to the service control manager (SCM) probably means that the program is not running as a service. In this case, the program calls CServiceModule::Run directly so that the program can run as a local server. For more information about running the program as a local server, see Debugging Tips.


CServiceModule::ServiceMain

The SCM calls ServiceMain when you open the Services Control Panel application, select the service, and click Start.

After the SCM calls ServiceMain, a service must give the SCM a handler function. This function lets the SCM obtain the service's status and pass specific instructions (such as pausing or stopping). The SCM gets this function when the service passes _Handler to the Win32 API function, RegisterServiceCtrlHandler. (_Handler is a static member function that calls the non-static member function Handler.)

At startup, a service should also inform the SCM of its current status. It does this by passing SERVICE_START_PENDING to the Win32 API function, SetServiceStatus.

Now, CServiceModule::Run is called to perform the main work of the service. Run continues to execute until the service is stopped.


CServiceModule::Run

After being called, Run first stores the service's thread ID. The service will use this ID to close itself by sending a WM_QUIT message using the Win32 API function, PostThreadMessage.

Run then calls the Win32 API function, CoInitializeEx. By default, Run passes the COINIT_MULTITHREADED flag to the function. This flag indicates that the program is to be a free-threaded server.

Now you can specify security using CSecurityDescriptor. This class greatly simplifies the task of setting up and making changes to the discretionary access-control list (DACL) — a list of access-control entries (ACEs), where each ACE defines access to a Win32 object.

By default, the ATL COM AppWizard generates a call to the InitializeFromThreadToken member function of CSecurityDescriptor. This initializes the object's security descriptor to a null DACL, which means that any user has access to your object.

The easiest way to change user access is with the Deny and Allow member functions of CSecurityDescriptor. These functions add an ACE to the existing DACL. However, Deny always takes priority since Deny adds the ACE to the beginning of the DACL, while Allow adds it to the end. Both Deny and Allow pass the user name as the first parameter and the access rights (typically, COM_RIGHTS_EXECUTE) as the second.

Recall that the null DACL created by InitializeFromThreadToken grants all users access to the COM object. However, as soon as you call Allow to add an ACE, only that specified user will have access. The following code shows a call to Allow:

CSecurityDescriptor sd;
sd.InitializeFromThreadToken( );

if (bAllowOneUser)
{
   sd.Allow("MYDOMAIN\\myuser", COM_RIGHTS_EXECUTE);
}
CoInitializeSecurity(sd, -1, NULL, NULL,
                     RPC_C_AUTHN_LEVEL_PKT,
                     RPC_C_IMP_LEVEL_IMPERSONATE,
                     NULL, EOAC_NONE, NULL);

If the variable, bAllowOneUser, is TRUE, then only the one specified user has access because only that user's ACE is in the DACL. If bAllowOneUser is FALSE, then all users have access because the DACL is null.

If you do not want the service to specify its own security, remove the call to the Win32 API function, CoInitializeSecurity, and COM will then determine the security settings from the registry. A convenient way to configure registry settings is with the DCOMCNFG utility discussed later in this article.

Once security is specified, the object is registered with COM so that new clients can connect to the program. Finally, the program tells the SCM that it is running and the program enters a message loop. The program remains running until it posts a quit message upon service shutdown.

For more information about Windows NT security, see the MSDN article, "Windows NT Security in Theory and Practice."


CServiceModule::Handler

CServiceModule::Handler is the routine that the SCM calls to retrieve the status of the service and give it various instructions (such as stopping or pausing). The SCM passes an operation code to Handler to indicate what the service should do. A default ATL-generated service only handles the stop instruction. If the SCM passes the stop instruction, the service tells the SCM that the program is about to stop. The service then calls PostThreadMessage to post a quit message to itself. This terminates the message loop and the service will ultimately close.

To handle more instructions, you need to change the dwControlsAccepted data member initialized in the CServiceModule::Init function. This data member tells the SCM which buttons to enable when the service is selected in the Services Control Panel application.


Registry Entries

DCOM introduced the concept of Application IDs (AppIDs), which group configuration options for one or more DCOM objects into a centralized location in the registry. You specify an AppID by indicating its value in the AppID named value under the object's CLSID.

By default, an ATL-generated service uses its CLSID as the GUID for its AppID. Under HKEY_CLASSES_ROOT\AppID, you can specify DCOM-specific entries. Initially, two entries exist:

  • LocalService, with a value equal to the name of the service. If this value exists, it is used instead of the LocalServer32 key under the CLSID.

  • ServiceParameters, with a value equal to –Service. This value specifies parameters that will be passed to the service when it is started. Note that these parameters are passed to the service's ServiceMain function, not WinMain.

Any DCOM service also needs to create another key under HKEY_CLASSES_ROOT\AppID. This key is equal to the name of the EXE and acts as a cross-reference, as it contains an AppID value pointing back to the AppID entries.


DCOMCNFG

DCOMCNFG is a Windows NT 4.0 utility that allows you to configure various DCOM-specific settings in the registry. The DCOMCNFG window has three pages: Default Security, Default Properties, and Applications.

The Default Security Page

You can use the Default Security page to specify default permissions for objects on the system. The Default Security page has three sections: Access, Launch, and Configuration. To change a section's defaults, click on the corresponding Edit Default button. These Default Security settings are stored in the registry under HKEY_LOCAL_MACHINE\Software\Microsoft\OLE.

The Default Properties Page

On the Default Properties page, you must select the Enable Distributed COM on this Computer check box if you want clients on other machines to access COM objects running on this machine. Selecting this option sets the HKEY_LOCAL_MACHINE\Software\Microsoft\OLE\EnableDCOM value to Y.

The Applications Page

You change the settings for a particular object with the Applications page. Simply select the application from the list and click the Properties button. The Properties window has four pages:

  • The General page confirms the application you are working with.

  • The Location page allows you to specify where the application should run when a client calls CoCreateInstance on the relevant CLSID. If you select the Run Application on the Following Computer check box and enter a computer name, then a RemoteServerName value is added under the AppID for that application. Clearing the Run Application on this Computer check box renames the LocalService value to _LocalService and ,thereby, disables it.

  • The Security page is similar to the Default Security page found in the DCOMCNFG window, except that these settings apply only to the current application. Again, the settings are stored under the AppID for that object.

  • The Identify page identifies which user is used to run the application.


Debugging Tips

The following paragraphs outline some useful steps for debugging your service:

  • Using Task Manager

  • Displaying assertions

  • Running the program as a local server


Using Task Manager

One of the simplest ways to debug a service is through the use of the Task Manager in Windows NT 4.0. While the service is running, start the Task Manager and click on the Processes tab. Use the right mouse button to click on the name of the EXE and then click Debug. This launches Visual C++ attached to that running process. Now, click Break on the Debug menu to allow you to set breakpoints in your code. Click Run to run to your selected breakpoints.


Displaying Assertions

If the client connected to your service appears to hang, the service may have asserted and displayed a message box that you are not able to see. You can confirm this by using Visual C++'s debugger to debug your code (see Using Task Manager earlier in this section).

If you determine that your service is displaying a message box that you cannot see, you may want to set the Allow Service to Interact with Desktop option before using the service again. This option is a startup parameter that permits any message boxes displayed by the service to appear on the desktop. To set this option, open the Services Control Panel application, select the service, click Startup, and then select the Allow Service to Interact with Desktop option.


Running the Program as a Local Server

If running the program as a service is inconvenient, you can temporarily change the registry so that the program is run as a normal local server. Simply rename the LocalService value under your AppID to _LocalService and ensure the LocalServer32 key under your CLSID is set correctly. (Note that using DCOMCNFG to specify that your application should be run on a different computer renames your LocalServer32 key to _LocalServer32.) Running your program as a local server takes a few more seconds on startup because the call to StartServiceCtrlDispatcher in CServiceModule::Start takes a few seconds before it fails.


The ATL Registry Component (Registrar)

The ATL 2.x Registrar provides optimized access to the system registry through a custom interface. The Registrar is free-threaded and allows static linking of code for C++ clients.

Note The ATL 2.x Registrar, provided in atl.dll, does not support Automation or the 1.1 methods that operated on a single key.

This article covers the following topics related to the Registrar:

  • Creating Registrar Scripts, which includes:
    • Understanding Backus Nauer Form (BNF) Syntax

    • Understanding Parse Trees

    • Registry Scripting Examples

    • Using Replaceable Parameters (The Registrar's Preprocessor)

    • Invoking scripts
  • Setting Up a Static Link to the Registrar Code (C++ only)

Note All of the source code for the 2.x Registrar ships with ATL. You can find the source code in atl\src\atliface.h.


Creating Registrar Scripts

A registrar script provides data-driven, rather than API-driven, access to the system registry. Data-driven access is typically more efficient since it takes only one or two lines in a script to add a key to the registry.

The ATL Object Wizard automatically generates a registrar script for your COM server. You can find this script in the .rgs file associated with your object.

The ATL Registrar's Script Engine processes your registrar script at run time. ATL automatically invokes the Script Engine during server setup.


Understanding Backus Nauer Form (BNF) Syntax

The scripts used by the ATL Registrar follow BNF syntax and use the notation shown in the next table.

Convention/Symbol | What It Means
::= | Equivalent
| | OR
X+ | One or more Xs.
[X] | X is optional. Optional delimiters are denoted by [].
Any bold text | A string literal.
Any italicized text | How to construct the string literal.

As indicated in the preceding table, registrar scripts use string literals. These values are actual text that must appear in your script. The following table describes the string literals used in an ATL Registrar script.

String Literal | Description
ForceRemove | Completely remove the following key (if it exists) and then recreate it.
NoRemove | Do not remove the following key during Unregister.
val | The following <Key Name> is actually a named value.
Delete | Delete the following key during Register.
s | The following value is a string.
d | The following value is a DWORD.

BNF Syntax Examples

Here are a few syntax examples to help you understand how the notation and string literals work in an ATL Registrar script.

Syntax example 1

<registry expression> ::= <Add Key>

specifies that registry expression is equivalent to Add Key.

Syntax example 2

<registry expression> ::= <Add Key> | <Delete Key>

specifies that registry expression is equivalent to either Add Key or Delete Key.

Syntax example 3

<Key Name> ::= '<AlphaNumeric>+'

specifies that Key Name is equivalent to one or more AlphaNumerics.

Syntax example 4

<Add Key> ::= [ForceRemove | NoRemove | val]<Key Name>

specifies that Add Key is equivalent to Key Name, and that the string literals, ForceRemove, NoRemove, and val, are optional.

Syntax example 5

<AlphaNumeric> ::= any character not NULL, i.e. ASCII 0

specifies that AlphaNumeric is equivalent to any non-NULL character.


Understanding Parse Trees

Using BNF syntax, you define one or more parse trees in your script.

Each parse tree has the form:

<root key>{<registry expression>}+

where:

<root key> ::= HKEY_CLASSES_ROOT | HKEY_CURRENT_USER |
               HKEY_LOCAL_MACHINE | HKEY_USERS |
               HKEY_PERFORMANCE_DATA | HKEY_DYN_DATA |
               HKEY_CURRENT_CONFIG | HKCR | HKCU |
               HKLM | HKU | HKPD | HKDD | HKCC
<registry expression> ::= <Add Key> | <Delete Key>
<Add Key> ::= [ForceRemove | NoRemove | val]<Key Name>
              [<Key Value>][{< Add Key>}]
<Delete Key> ::= Delete<Key Name>
<Key Name> ::= '<AlphaNumeric>+'
<AlphaNumeric> ::= any character not NULL, i.e. ASCII 0
<Key Value> ::== <Key Type><Key Name>
<Key Type> ::= s | d
<Key Value> ::= '<AlphaNumeric>'

Note HKEY_CLASSES_ROOT and HKCR are equivalent; HKEY_CURRENT_USER and HKCU are equivalent; and so on.

A parse tree can add multiple keys and subkeys to the <root key>. In doing so, it keeps a subkey's handle open until the parser has completed parsing all its subkeys. This approach is more efficient than operating on a single key at a time, as seen in the following parse tree example:

HKEY_CLASSES_ROOT
{
   'MyVeryOwnKey'
   {
      'HasASubKey'
      {
         'PrettyCool?'
      }
   }
}

Here, the Registrar initially opens (creates) HKEY_CLASSES_ROOT\MyVeryOwnKey. It then sees that MyVeryOwnKey has a subkey. Rather than close the key to MyVeryOwnKey, the Registrar retains the handle and opens (creates) HasASubKey using this parent handle. (The system registry can be slower when no parent handle is open.) Thus, opening HKEY_CLASSES_ROOT\MyVeryOwnKey and then opening HasASubKey with MyVeryOwnKey as the parent is faster than opening MyVeryOwnKey, closing MyVeryOwnKey, and then opening MyVeryOwnKey\HasASubKey.


Registry Scripting Examples

The scripting examples in this article demonstrate how to add a key to the system registry; register the Registrar COM server; and specify multiple parse trees.

Add a Key to HKEY_CURRENT_USER

The following parse tree illustrates a simple script that adds a single key to the system registry. In particular, the script adds the key, MyVeryOwnKey, to HKEY_CURRENT_USER. It also assigns the default string value of HowGoesIt? to the new key:

HKEY_CURRENT_USER
{
   'MyVeryOwnKey' = s 'HowGoesIt?'
}

This script can easily be extended to define multiple subkeys as follows:

HKCU
{
   'MyVeryOwnKey' = s 'HowGoesIt?'
   {
      'HasASubkey'
      {
         'PrettyCool?' = d '55'
         val 'ANameValue' = s 'WithANamedValue'
      }
   }
}

Now, the script adds a subkey, HasASubkey, to MyVeryOwnKey. To this subkey, it adds both the PrettyCool? subkey (with a default DWORD value of 55) and the ANameValue named value (with a string value of WithANamedValue).

Register the Registrar COM Server

The following script registers the Registrar COM server itself.

HKCR
{
   ATL.Registrar = s 'ATL 2.0 Registrar Class'
   {
      CLSID = s '{44EC053A-400F-11D0-9DCD-00A0C90391D3}'
   }
   NoRemove CLSID
   {
      ForceRemove {44EC053A-400F-11D0-9DCD-00A0C90391D3} =
                   s 'ATL 2.0 Registrar Class'
      {
         ProgID = s 'ATL.Registrar'
         InprocServer32 = s '%MODULE%'
         {
            val ThreadingModel = s 'Apartment'
         }
      }
   }
}

At run time, this parse tree adds the ATL.Registrar key to HKEY_CLASSES_ROOT. To this new key, it then:

  • Specifies ATL Registrar 2.0 Class as the key's default string value.

  • Adds CLSID as a subkey.

  • Specifies {44EC053A-400F-11D0-9DCD-00A0C90391D3} for CLSID. (This value is the Registrar's CLSID for use with CoCreateInstance.)

Since CLSID is shared, it should not be removed in Unregister mode. The statement, NoRemove CLSID, does this by indicating that CLSID should be opened in Register mode and ignored in Unregister mode.

The ForceRemove statement provides a housekeeping function by removing a key and all its subkeys before recreating the key. This can be useful if the names of the subkeys have changed. In this scripting example, ForceRemove checks to see if {44EC053A-400F-11D0-9DCD-00A0C90391D3} already exists. If it does, ForceRemove:

  • Recursively deletes {44EC053A-400F-11D0-9DCD-00A0C90391D3} and all of its subkeys.

  • Recreates {44EC053A-400F-11D0-9DCD-00A0C90391D3}.

  • Adds ATL Registrar 2.0 Class as the default string value for {44EC053A-400F-11D0-9DCD-00A0C90391D3}.

The parse tree now adds two new subkeys to {44EC053A-400F-11D0-9DCD-00A0C90391D3}. The first key, ProgID, gets a default string value that is the ProgID. The second key, InprocServer32, gets a default string value, %MODULE%, that is a preprocessor value explained in the section, Using Replaceable Parameters (The Registrar's Preprocessor), of this article. InprocServer32 also gets a named value, ThreadingModel, with a string value of Apartment.

Specify Multiple Parse Trees

In order to specify more than one parse tree in a script, simply place one tree at the end of another. For example, the following script adds the key, MyVeryOwnKey, to the parse trees for both HKEY_CLASSES_ROOT and HKEY_CURRENT_USER:

HKCR
{
   'MyVeryOwnKey' = s 'HowGoesIt?'
}
HKEY_CURRENT_USER
{
   'MyVeryOwnKey' = s 'HowGoesIt?'
}

Note In a Registrar script, 4K is the maximum token size. (A token is any recognizable element in the syntax). In the previous scripting example, HKCR, HKEY_CURRENT_USER, 'MyVeryOwnKey', and 'HowGoesIt?' are all tokens.


Using Replaceable Parameters (The Registrar's Preprocessor)

Replaceable parameters allow a Registrar's client to specify run-time data. To do this, the Registrar maintains a replacement map into which it enters the values associated with the replaceable parameters in your script. The Registrar makes these entries at run time. The following section demonstrates these steps.

Using %MODULE%

The ATL Object Wizard automatically generates a script that uses %MODULE%. ATL uses this replaceable parameter for the actual location of your server's DLL or EXE.

Besides adding %MODULE% to the script, the ATL Object Wizard also adds the following line to the object's class declaration:

DECLARE_REGISTRY_RESOURCEID(IDR_MYCOMAPP)

This macro expands to:

static HRESULT WINAPI UpdateRegistry(BOOL bRegister)
{
   return _Module.UpdateRegistryFromResource(IDR_MYCOMAPP,
                                   bRegister);
}

where _Module refers to the global CComModule, which has the following method and #define statement:

UpdateRegistryFromResource(UINT nResID, BOOL bRegister,
       struct _ATL_REGMAP_ENTRY* pMapEntries = NULL);

#define UpdateRegistryFromResource
        UpdateRegistryFromResource

This method calls AtlModuleUpdateRegistryFromResource, which contains the following code:

ATLAPI AtlModuleUpdateRegistryFromResource(_ATL_MODULE*pM,
          LPCOLESTR lpszRes, BOOL bRegister,
          struct _ATL_REGMAP_ENTRY* pMapEntries,
          IRegistrar* pReg)
{
   USES_CONVERSION;
   ...
   CComPtr<IRegistrar> p;
   ...

   TCHAR szModule[_MAX_PATH];
   GetModuleFileName(pM->m_hInst, szModule, _MAX_PATH);
   p->AddReplacement(OLESTR("Module"), T2OLE(szModule));

   ...
}

Note You can find this code in atl\include\atlimpl.cpp.

CoCreateInstance acquires the pointer p, which points to the Registrar. Then, AddReplacement receives an LPCOLESTR containing the string "Module", as well as an LPCOLESTR containing the string acquired from the Win32 API function, GetModuleFileName. This code adds a replacement map entry for the Module variable that has a value associated with the result of GetModuleFileName. Now, when the preprocessor sees the %MODULE% in the script, it will replace it with the value from GetModuleFileName.

Concatenating run-time data with script data

Another use of the preprocessor is to concatenate run-time data with script data. For example, suppose we need an entry that contains a full path to a module with the string ", 1" appended at the end. First, define the following expansion:

'MyGoofyKey' = s '%MODULE%, 1'

Then, before calling one of the script processing methods, add a replacement to the map:

TCHAR szModule[_MAX_PATH]
GetModuleFileName(pM->m_hInst, szModule, _MAX_PATH);
p->AddReplacement(OLESTR("Module"), T2OLE(szModule));

During the parsing of the script, the Registrar expands '%MODULE%, 1' to c:\mycode\mydll.dll, 1.

Note In a Registrar script, 4K is the maximum token size. (A token is any recognizable element in the syntax.) This includes tokens that were created or expanded by the preprocessor.

Note To substitute replacement values at run time, remove the call to DECLARE_REGISTRY_RESOURCE or DECLARE_REGISTRY_RESOURCEID macro. Instead, replace it with your own UpdateRegistry member function that calls CComModule::UpdateRegistryFromResource, and pass your array of _ATL_REGMAP_ENTRY structures. Your array of _ATL_REGMAP_ENTRY must have at least one entry that is set to {NULL,NULL}, and this entry should always be the last entry. Otherwise, an access violation error will be generated when UpdateRegistryFromResrouce is called.


Invoking Scripts

The previous section, Using Replaceable Parameters (The Registrar's Preprocessor), discussed replacement maps and introduced two of the Registrar's methods, AddReplacement and ClearReplacements. The Registrar has eight other methods specific to scripting. All eight of these methods are described in the following table and invoke the Registrar on a particular script.

Method | Syntax/Description
ResourceRegister | HRESULT ResourceRegister( LPCOLESTR resFileName, UINT nID, LPCOLESTR szType ); Registers the script contained in a module's resource. resFileName indicates the UNC path to the module itself. nID and szType contain the resource's ID and type, respectively.
ResourceUnregister | HRESULT ResourceUnregister( LPCOLESTR resFileName, UINT nID, LPCOLESTR szType ); Unregisters the script contained in a module's resource. resFileName indicates the UNC path to the module itself. nID and szType contain the resource's ID and type, respectively.
ResourceRegisterSz | HRESULT ResourceRegisterSz( LPCOLESTR resFileName, LPCOLESTR szID, LPCOLESTR szType ); Registers the script contained in a module's resource. resFileName indicates the UNC path to the module itself. szID and szType contain the resource's string identifier and type, respectively.
ResourceUnregisterSz | HRESULT ResourceUnregisterSz( LPCOLESTR resFileName, LPCOLESTR szID, LPCOLESTR szType ); Unregisters the script contained in a module's resource. resFileName indicates the UNC path to the module itself. szID and szType contain the resource's string identifier and type, respectively.
FileRegister | HRESULT FileRegister( LPCOLESTR fileName ); Registers the script in a file. fileName is a UNC path to a file that contains (or is) a resource script.
FileUnregister | HRESULT FileUnregister( LPCOLESTR fileName ); Unregisters the script in a file. fileName is a UNC path to a file that contains (or is) a resource script.
StringRegister | HRESULT StringRegister( LPCOLESTR data ); Registers the script in a string. data contains the script itself.
StringUnregister | HRESULT StringUnregister( LPCOLESTR data ); Unregisters the script in a string. data contains the script itself.

ATL uses the first two methods shown in the table (ResourceRegister and ResourceUnregister) in atlimpl.cpp:

LPCOLESTR szType = OLESTR("REGISTRY");
GetModuleFileName(pM->m_hInstResource, szModule, _MAX_PATH);
LPOLESTR pszModule = T2OLE(szModule);

if (HIWORD(lpszRes)==0)
{
   if (bRegister)
     hRes = p->ResourceRegister(pszModule,
               ((UINT)LOWORD((DWORD)lpszRes)), szType);
   else
     hRes = p->ResourceUnregister(pszModule,
               ((UINT)LOWORD((DWORD)lpszRes)), szType);
}
else
{
   if (bRegister)
     hRes = p->ResourceRegisterSz(pszModule, lpszRes, szType);
   else
     hRes = p->ResourceUnregisterSz(pszModule, lpszRes, szType);
}

Note that szModule contains the value acquired from GetModuleFileName.

The next two methods shown in the table, ResourceRegisterSz and ResourceUnregisterSz, are similar to ResourceRegister and ResourceUnregister, but allow you to specify a string identifier.

The methods FileRegister and FileUnregister are useful if you do not want the script in a resource or if you want the script in its own file. The methods StringRegister and StringUnregister allow the .rgs file to be stored in a dynamically-allocated string.


Setting Up a Static Link to the Registrar Code (C++ only)

C++ clients can create a static link to the Registrar's code. Static linking of the Registrar's parser adds approximately 5K to a release build.

The simplest way to set up static linking assumes you have specified DECLARE_REGISTRY_RESOURCEID in your object's declaration. (This is the default specification used by the ATL.)

To create a static link using DECLARE_REGISTRY_RESOURCEID

  1. Open the Project Settings dialog box, select the C++ tab. In the Preprocessor Definitions text box, replace _ATL_DLL with _ATL_STATIC_REGISTRY.

  2. Recompile.

If the project has been created using the ATL AppWizard, you only need to select the Win32 Release MinDependency option, which has the correct preprocessor definitions for statically linking to the registrar code.


CAxDialogImpl

template <class T, class TBase = CWindow>
class ATL_NO_VTABLE CAxDialogImpl : public CDialogImplBaseT< TBase >

Parameters

T

Your class, derived from CAxDialogImpl.

TBase

The base window class for CDialogImplBaseT.

Implements a dialog box (modal or modeless) that hosts ActiveX controls.

CAxDialogImpl allows you to create a modal or modeless dialog box. CAxDialogImpl provides the dialog box procedure, which uses the default message map to direct messages to the appropriate handlers.

CAxDialogImpl derives from CDialogImplBaseT, which in turn derives from TBase (by default, CWindow) and CMessageMap.

Note Your class must define an IDD member that specifies the dialog template resource ID. For example, the ATL Object Wizard automatically adds the following line to your class:

enum { IDD = IDD_MYDIALOG };

where MyDialog is the Short name entered in the wizard’s Names page.

See Implementing a Dialog Box for more information.

#include <atlwin.h>

Class Members

See Also

CDialogImpl


CAxDialogImpl Class Members

Methods

DoModal | Creates a modal dialog box.
EndDialog | Destroys a modal dialog box.
Create | Creates a modeless dialog box.
DestroyWindow | Destroys a modeless dialog box.

CAxDialogImpl Overview


Methods


CAxDialogImpl::Create

HWND Create( HWND hWndParent, LPARAM dwInitParam = NULL );

HWND Create( HWND hWndParent, RECT&, LPARAM dwInitParam = NULL );

Return Value

The handle to the newly created dialog box.

Parameters

hWndParent

[in] The handle to the owner window.

dwInitParam

[in] Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

RECT&

This parameter is not used. This parameter is passed in by CComControl.

Remarks

Creates a modeless dialog box. This dialog box is automatically attached to the CAxDialogImpl object. To create a modal dialog box, call DoModal.

The second override is provided only so dialog boxes can be used with CComControl.

CAxDialogImpl Overview | Class Members

See Also

CAxDialogImpl::DestroyWindow, CAxDialogImpl::DoModal


CAxDialogImpl::DestroyWindow

BOOL DestroyWindow( );

Return Value

TRUE if the window is successfully destroyed; otherwise FALSE.

Remarks

Destroys the specified dialog box.

Note Do not call DestroyWindow to destroy a modal dialog box. Call EndDialog instead.

CAxDialogImpl Overview | Class Members

See Also

DestroyWindow in the Platform SDK


CAxDialogImpl::DoModal

int DoModal( HWND hWndParent = ::GetActiveWindow(), LPARAM dwInitParam = NULL );

Return Value

If successful, the value of the nRetCode parameter specified in the call to EndDialog; otherwise, -1.

Parameters

hWndParent

[in] The handle to the owner window. The default value is the return value of the GetActiveWindow Win32 function.

dwInitParam

[in] Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

Remarks

Creates a modal dialog box. This dialog box is automatically attached to the CAxDialogImpl object.

To create a modeless dialog box, call Create.

CAxDialogImpl Overview | Class Members

See Also

CAxDialogImpl::EndDialog, CAxDialogImpl::Create


CAxDialogImpl::EndDialog

BOOL EndDialog( int nRetCode );

Return Value

TRUE if the dialog box is destroyed; otherwise, FALSE.

Parameters

nRetCode

[in] The value to be returned by DoModal.

Remarks

Destroys a modal dialog box. EndDialog must be called through the dialog procedure. After the dialog box is destroyed, Windows uses the value of nRetCode as the return value for DoModal, which created the dialog box.

Note Do not call EndDialog to destroy a modeless dialog box. Call DestroyWindow instead.

CAxDialogImpl Overview | Class Members

See Also

CAxDialogImpl::DoModal


CAxWindow

class CAxWindow : public CWindow

This class provides methods for manipulating a window that hosts an ActiveX control. The hosting is provided by AxWin, which is wrapped by CAxWindow.

Class CAxWindow is implemented as a specialization of the CAxWindowT class. This specialization is declared as:

typedef CAxWindowT<CWindow> CAxWindow;

If you need to change the base class, you can use CAxWindowT and specify the new base class as a template argument.

#include <atlwin.h>

Class Members

See Also

CWindow, Composite Control Fundamentals


CAxWindow Class Members

Methods

CAxWindow | Constructs a CAxWindow object.
GetWndClassName | Retrieves the predefined class name of the CAxWindow object.
CreateControl | Creates an ActiveX control, initializes it, and hosts it in the CaxWindow window.
CreateControlEx | Creates an ActiveX control and retrieves an interface pointer (or pointers) from the control.
AttachControl | Attaches an existing ActiveX control to the CAxWindow object.
QueryHost | Retrieves the IUnknown pointer of the CAxWindow object.
QueryControl | Retrieves the IUnknown of the hosted ActiveX control.
SetExternalDispatch | Sets the external dispatch interface used by the CaxWindow object.
SetExternalUIHandler | Sets the external IDocHostUIHandler interface used by the CaxWindow object.

Operators

operator = Assigns an HWND to an existing CAxWindow object.

CAxWindow Overview

See Also

CWindow members


CAxWindow::AttachControl

HRESULT AttachControl( IUnknown* pControl, IUnknown** ppUnkContainer );

Return Value

A standard HRESULT value.

Parameters

pControl

[in] A pointer to the IUnknown of the control.

ppUnkContainer

[out] A pointer to the IUnknown of the host (the AxWin object).

Remarks

Creates a new host object if one isn’t already present and attaches the specified control to the host.

Note The control object being attached must be correctly initialized before calling AttachControl.

CAxWindow Overview | Class Members

See Also

AtlAxAttachControl


CAxWindow::CAxWindow

CAxWindow( HWND hWnd = NULL );

Parameters

hWnd

A handle to an existing window object.

Remarks

Constructs a CAxWindow object using an existing window object handle.


CAxWindow::CreateControl

HRESULT CreateControl( LPCOLESTR lpszName, IStream* pStream = NULL, IUnknown** ppUnkContainer = NULL );

HRESULT CreateControl( DWORD dwResID, IStream* pStream = NULL, IUnknown** ppUnkContainer = NULL );

Return Value

A standard HRESULT value.

Parameters

lpszName

A pointer to a string to create the control. Must be formatted in one of the following ways:

  • A ProgID such as "MSCAL.Calendar.7"

  • A CLSID such as "{8E27C92B-1264-101C-8A2F-040224009C02}"

  • A URL such as "http://www.microsoft.com"

  • A reference to an Active document such as "file://\\Documents\MyDoc.doc"

  • A fragment of HTML such as "MSHTML:<HTML><BODY>This is a line of text</BODY></HTML>"

    Note "MSHTML:" must precede the HTML fragment so that it is designated as being an MSHTML stream.

pStream

[in] A pointer to a stream that is used to initialize the properties of the control. Can be NULL.

ppUnkContainer

[out] The address of a pointer that will receive the IUnknown of the container. Can be NULL.

dwResID

The resource ID of an HTML resource. The WebBrowser control will be created and loaded with the specified resource.

Remarks

Creates an ActiveX control, initializes it, and hosts it in the specified window. If the second version of this function is used, an HTML control is created and bound to the resource identified by dwResID.

This method gives you the same result as calling CreateControlEx( lpszName, hWnd, pStream, NULL, NULL, NULL, NULL );.

CAxWindow Overview | Class Members

See Also

AtlAxCreateControl


CAxWindow::CreateControlEx

HRESULT CreateControlEx( LPCOLESTR lpszName, IStream* pStream = NULL, IUnknown** ppUnkContainer = NULL, IUnknown** ppUnkControl = NULL, REFIID iidSink = IID_NULL, IUnknown* punkSink = NULL );

HRESULT CreateControlEx( DWORD dwResID, IStream* pStream = NULL, IUnknown** ppUnkContainer = NULL, IUnknown** ppUnkControl = NULL, REFIID iidSink = IID_NULL, IUnknown* punkSink = NULL );

Return Value

A standard HRESULT value.

Parameters

lpszName

A pointer to a string to create the control. Must be formatted in one of the following ways:

  • A ProgID such as "MSCAL.Calendar.7"

  • A CLSID such as "{8E27C92B-1264-101C-8A2F-040224009C02}"

  • A URL such as "http://www.microsoft.com"

  • A reference to an Active document such as "file://\\Documents\MyDoc.doc"

  • A fragment of HTML such as "MSHTML:<HTML><BODY>This is a line of text</BODY></HTML>"

    Note "MSHTML:" must precede the HTML fragment so that it is designated as being an MSHTML stream.

pStream

[in] A pointer to a stream that is used to initialize the properties of the control. Can be NULL.

ppUnkContainer

[out] The address of a pointer that will receive the IUnknown of the container. Can be NULL.

ppUnkControl

[out] The address of a pointer that will receive the IUnknown of the control. Can be NULL.

dwResID

The resource ID of an HTML resource. The WebBrowser control will be created and loaded with the specified resource.

Remarks

Creates an ActiveX control, initializes it, and hosts it in the specified window. Use this function, instead of CreateControl, to retrieve interface pointers from the newly created control.

CAxWindow Overview | Class Members

See Also

AtlAxCreateControlEx


CAxWindow::GetWndClassName

static LPCTSTR GetWndClassName( );

Return Value

A pointer to a string containing the name of the window class, in this case, AtlAxWin.

Remarks

Call this function to retrieve the name of the window class.


CAxWindow::QueryControl

HRESULT QueryControl( REFIID iid, void** ppUnk );

template <class Q>
HRESULT QueryControl( Q** ppUnk );

Return Value

A standard HRESULT value.

Parameters

iid

[in] Specifies the IID of the control’s interface.

ppUnk

[out] A pointer to the IUnknown interface of the control. In the template version of this function, there is no need for a reference ID and the interface can be specified.

Q

[in] The interface that is being queried for.

Remarks

Call this function to retrieve the IUnknown interface of the hosted control.

CAxWindow Overview | Class Members

See Also

CAxWindow::QueryHost


CAxWindow::QueryHost

HRESULT QueryHost( REFIID iid, void** ppUnk );

template <class Q>
HRESULT QueryHost( Q** ppUnk );

Return Value

A standard HRESULT value.

Parameters

iid

[in] Specifies the IID of the control’s interface.

ppUnk

[out] A pointer to the IUnknown interface of the host. In the template version of this function, there is no need for a reference ID and the interface can be specified.

Q

[in] The interface that is being queried for.

Remarks

Call this function to return the IUnknown interface of the host. This allows access to the underlying functionality of the window-hosting code, implemented by AxWin.

CAxWindow Overview | Class Members

See Also

CAxWindow::QueryControl


CAxWindow::SetExternalDispatch

HRESULT SetExternalDispatch( IDispatch* pDisp );

Return Value

A standard HRESULT value.

Parameters

pDisp

[in] A pointer to an IDispatch interface.

Remarks

Call this function to set the external dispatch interface for the CAxWindow object.

CAxWindow Overview | Class Members

See Also

CAxWindow::SetExternalUIHandler


CAxWindow::SetExternalUIHandler

HRESULT SetExternalUIHandler( IDocHostUIHandlerDispatch* pUIHandler );

Return Value

A standard HRESULT value.

Parameters

pUIHandler

[in] A pointer to an IDocHostUIHandlerDispatch interface.

Remarks

Call this function to set the external IDocHostUIHandlerDispatch interface for the CAxWindow object.

This interface is used by controls that query the host’s site for the IDocHostUIHandlerDispatch interface. The WebBrowser control is one control that does this.

CAxWindow Overview | Class Members

See Also

CAxWindow::SetExternalDispatch


CAxWindow::operator =

CAxWindow< TBase >& operator=( HWND hWnd );

Remarks

Assigns a HWND to an existing CAxWindow object.


CBindStatusCallback

template< class T >
class CBindStatusCallback : public CComObjectRootEx<T::_ThreadModel::ThreadModelNoCS>, public IBindStatusCallbackImpl<T>

Parameters

T

Your class containing the function that will be called as the data is received.

The CBindStatusCallback class implements the IBindStatusCallback interface. IBindStatusCallback must be implemented by your application so it can receive notifications from an asynchronous data transfer. The asynchronous moniker provided by the system uses IBindStatusCallback methods to send and receive information about the asynchronous data transfer to and from your object.

Typically, the CBindStatusCallback object is associated with a specific bind operation. For example, in the ASYNC sample, when you set the URL property, it creates a CBindStatusCallback object in the call to Download:

STDMETHOD(put_URL)(BSTR strURL)
{
   ...
   m_bstrURL = strURL;
   CBindStatusCallback<CATLAsync>::Download(this,
             OnData, m_bstrURL, m_spClientSite, FALSE);
   return S_OK;
}

The asynchronous moniker uses the callback function OnData to call your application when it has data. The asynchronous moniker is provided by the system.

See the ActiveX SDK for a description of IBindStatusCallback.

#include <atlctl.h>

Class Members


CBindStatusCallback Class Members

IBindStatusCallback Methods

GetBindInfo | Called by the asynchronous moniker to request information on the type of bind to be created.
GetPriority | Called by the asynchronous moniker to get the priority of the bind operation. The ATL implementation returns E_NOTIMPL.
OnLowResource | Called when resources are low. The ATL implementation returns S_OK.
OnObjectAvailable | Called by the asynchronous moniker to pass an object interface pointer to your application. The ATL implementation returns S_OK.
OnProgress | Called to indicate the progress of a data downloading process. The ATL implementation returns S_OK.
OnStartBinding | Called when binding is started.
OnStopBinding | Called when the asynchronous data transfer is stopped.

Class Methods

CBindStatusCallback | Constructor.
Download | Starts the download process, creates a CBindStatusCallback object, and calls StartAsyncDownload.
OnDataAvailable | Called to provide data to your application as it becomes available. Reads the data, then calls the function passed to it to use the data.
StartAsyncDownload | Initializes the bytes available and bytes read to zero, creates a push-type stream object from a URL, and calls OnDataAvailable every time data is available.

Data Members

m_dwAvailableToRead | Number of bytes available to read.
m_dwTotalRead | Total number of bytes read.
m_pFunc | Pointer to the function called when data is available.
m_pT | Pointer to the object requesting the asynchronous data transfer.
m_spBindCtx | Pointer to the IBindCtx interface for the current bind operation.
m_spBinding | Pointer to the IBinding interface for the current bind operation. See the ActiveX SDK for a description of IBinding.
m_spMoniker | Pointer to the IMoniker interface for the URL to use.
m_spStream | Pointer to the IStream interface for the data transfer.

CBindStatusCallback Overview


CBindStatusCallback::CBindStatusCallback

CBindStatusCallback( );

Remarks

The constructor. Creates an object to receive notifications concerning the asynchronous data transfer. Typically, one object is created for each bind operation.

The constructor also initializes m_pT and m_pFunc to NULL.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload


CBindStatusCallback::Download

HRESULT Download( T* pT, ATL_PDATAAVAILABLE pFunc, BSTR bstrURL, IUnknown* pUnkContainer = NULL, BOOL bRelative = FALSE );

Return Value

One of the standard HRESULT values.

Parameters

pT

[in] A pointer to the object requesting the asynchronous data transfer. The CBindStatusCallback object is templatized on this object's class.

pFunc

[in] A pointer to the function that receives the data that is read. The function is a member of your object's class of type T. See StartAsyncDownload for syntax and an example.

bstrURL

[in] The URL to obtain data from. Can be any valid URL or file name. Cannot be NULL. For example:

CComBSTR mybstr =_T("http://somesite/data.htm")

pUnkContainer

[in] The IUnknown of the container. NULL by default.

bRelative

[in] A flag indicating whether the URL is relative or absolute. FALSE by default, meaning the URL is absolute.

Remarks

Creates a CBindStatusCallback object and calls StartAsyncDownload to start downloading data asynchronously from the specified URL. Every time data is available it is sent to the object through OnDataAvailable. OnDataAvailable reads the data and calls the function pointed to by pFunc (for example, to store the data or print it to the screen).

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload


CBindStatusCallback::GetBindInfo

HRESULT GetBindInfo( DWORD* pgrfBSCF, BINDINFO* pbindinfo );

Return Value

One of the standard HRESULT values.

Parameters

pgrfBSCF

[out] A pointer to BINDF enumeration values indicating how the bind operation should occur. By default, set with the following enumeration values:

BINDF_ASYNCHRONOUS Asynchronous download.

BINDF_ASYNCSTORAGE OnDataAvailable returns E_PENDING when data is not yet available rather than blocking until data is available.

BINDF_GETNEWESTVERSION The bind operation should retrieve the newest version of the data.

BINDF_NOWRITECACHE The bind operation should not store retrieved data in the disk cache.

pbindinfo

[in, out] A pointer to the BINDINFO structure giving more information about how the object wants binding to occur.

Remarks

Called to tell the moniker how to bind. The default implementation sets the binding to be asynchronous and to use the data-push model. In the data-push model, the moniker drives the asynchronous bind operation and continuously notifies the client whenever new data is available.

See IBindStatusCallback::GetBindInfo in the ActiveX SDK.


CBindStatusCallback::GetPriority

HRESULT GetPriority( LONG* pnPriority );

See IBindStatusCallback::GetPriority in the ActiveX SDK.

Remarks

Returns E_NOTIMPL.


CBindStatusCallback::OnDataAvailable

HRESULT OnDataAvailable( DWORD grfBSCF, DWORD dwSize, FORMATETC* pformatetc, STGMEDIUM* pstgmed );

Return Value

One of the standard HRESULT values.

Parameters

grfBSCF

[in] A BSCF enumeration value. One or more of the following: BSCF_FIRSTDATANOTIFICATION, BSCF_INTERMEDIARYDATANOTIFICATION, or BSCF_LASTDATANOTIFICATION.

dwSize

[in] The cumulative amount (in bytes) of data available since the beginning of the binding. Can be zero, indicating that the amount of data is not relevant or that no specific amount became available.

pformatetc

[in] Pointer to the FORMATETC structure that contains the format of the available data. If there is no format, can be CF_NULL.

pstgmed

[in] Pointer to the STGMEDIUM structure that holds the actual data now available.

Remarks

The system-supplied asynchronous moniker calls OnDataAvailable to provide data to the object as it becomes available.

OnDataAvailable reads the data, then calls a method of your object's class (for example, to store the data or print it to the screen). See CBindStatusCallback::StartAsyncDownload for details.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload


CBindStatusCallback::OnLowResource

HRESULT OnLowResource( DWORD dwReserved );

See IBindStatusCallback::OnLowResource in the ActiveX SDK.

Remarks

Returns S_OK.


CBindStatusCallback::OnObjectAvailable

HRESULT OnObjectAvailable( REFID riid, IUnknown* punk );

See IBindStatusCallback::OnObjectAvailable in the ActiveX SDK.

Remarks

Returns S_OK.


CBindStatusCallback::OnProgress

HRESULT OnProgress( ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTRONG szStatusText );

See IBindStatusCallback::OnProgress in the ActiveX SDK.

Remarks

Returns S_OK.


CBindStatusCallback::OnStartBinding

HRESULT OnStartBinding( DWORD dwReserved, IBinding* pBinding );

See IBindStatusCallback::OnStartBinding in the ActiveX SDK.

Remarks

Sets the data member m_spBinding to the IBinding pointer in pBinding.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::OnStopBinding


CBindStatusCallback::OnStopBinding

HRESULT OnStopBinding( HRESULT hresult, LPCWSTR szError );

See IBindStatusCallback::OnStopBinding in the ActiveX SDK.

Remarks

Releases the IBinding pointer in the data member m_spBinding. Called by the system-supplied asynchronous moniker to indicate the end of the bind operation.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::OnStartBinding


CBindStatusCallback::StartAsyncDownload

HRESULT StartAsyncDownload( T* pT, ATL_PDATAAVAILABLE pFunc, BSTR bstrURL, BOOL bRelative = FALSE );

Return Value

One of the standard HRESULT values.

Parameters

pT

[in] A pointer to the object requesting the asynchronous data transfer. The CBindStatusCallback object is templatized on this object's class.

pFunc

[in] A pointer to the function that receives the data being read. The function is a member of your object's class of type T. See Remarks for syntax and an example.

bstrURL

[in] The URL to obtain data from. Can be any valid URL or file name. Cannot be NULL. For example:

CComBSTR mybstr =_T("http://somesite/data.htm")

pUnkContainer

[in] The IUnknown of the container. NULL by default.

bRelative

[in] A flag indicating whether the URL is relative or absolute. FALSE by default, meaning the URL is absolute.

Remarks

Starts downloading data asynchronously from the specified URL. Every time data is available it is sent to the object through OnDataAvailable. OnDataAvailable reads the data and calls the function pointed to by pFunc (for example, to store the data or print it to the screen).

The function pointed to by pFunc is a member of your object's class and has the following syntax:

void Function_Name( CBindStatusCallback<T>* pbsc, BYTE* pBytes, DWORD dwSize );

In the following example (taken from the ASYNC sample), the function OnData writes the received data into a text box:

void OnData(CBindStatusCallback<CATLAsync>* pbsc,
            BYTE* pBytes, DWORD dwSize)
{
   m_bstrText.Append= (LPCSTR)pBytes;
   if (::IsWindow(m_EditCtrl.m_hWnd))
   {
      USES_CONVERSION;
      ::SendMessage(m_EditCtrl.m_hWnd, WM_SETTEXT, 0,
                    (LPARAM)OLE2CT((BSTR)m_bstrText));
   }
}

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::OnDataAvailable


CBindStatusCallback::m_dwAvailableToRead

DWORD m_dwAvailableToRead;

Remarks

Can be used to store the number of bytes available to be read. Initialized to zero in StartAsyncDownload.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload


CBindStatusCallback::m_dwTotalRead

DWORD m_dwTotalRead;

Remarks

The cumulative total of bytes read in the asynchronous data transfer. Incremented every time OnDataAvailable is called by the number of bytes actually read. Initialized to zero in StartAsyncDownload.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload, CBindStatusCallback::OnDataAvailable


CBindStatusCallback::m_pFunc

ATL_PDATAAVAILABLE m_pFunc;

Remarks

The function pointed to by m_pFunc is called by OnDataAvailable after it reads the available data (for example, to store the data or print it to the screen).

The function pointed to by m_pFunc is a member of your object's class and has the following syntax:

void Function_Name( CBindStatusCallback<T>* pbsc, BYTE* pBytes, DWORD dwSize );

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload, CBindStatusCallback::OnDataAvailable


CBindStatusCallback::m_pT

T* m_pT;

Remarks

A pointer to the object requesting the asynchronous data transfer. The CBindStatusCallback object is templatized on this object's class.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload


CBindStatusCallback::m_spBindCtx

CComPtr<IBindCtx> m_spBindCtx;

Remarks

A pointer to an IBindCtx interface that provides access to the bind context (an object that stores information about a particular moniker binding operation). Initialized in StartAsyncDownload.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload, CComPtr


CBindStatusCallback::m_spBinding

CComPtr<IBinding> m_spBinding;

Remarks

A pointer to the IBinding interface of the current bind operation. Initialized in OnStartBinding and released in OnStopBinding.

See the ActiveX SDK for a description of IBinding.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::OnStartBinding, CBindStatusCallback::OnStopBinding, CComPtr


CBindStatusCallback::m_spMoniker

CComPtr<IMoniker> m_spMoniker;

Remarks

A pointer to the IMoniker interface for the URL to use. Initialized in StartAsyncDownload.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::StartAsyncDownload, CComPtr


CBindStatusCallback::m_spStream

CComPtr<IStream> m_spStream;

Remarks

A pointer to the IStream interface of the current bind operation. Initialized in OnDataAvailable from the STGMEDIUM structure when the BCSF flag is BCSF_FIRSTDATANOTIFICATION and released when the BCSF flag is BCSF_LASTDATANOTIFICATION.

CBindStatusCallback Overview | Class Members

See Also CBindStatusCallback::OnDataAvailable, CComPtr


CComAggObject

template< class contained >
class CComAggObject : public IUnknown, public CComObjectRootEx< contained::_ThreadModel::ThreadModelNoCS >

Parameters

contained

Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interfaces you want to support on the object.

CComAggObject implements IUnknown for an aggregated object. CComAggObject has its own IUnknown, separate from the outer object's IUnknown, and maintains its own reference count.

CComAggObject uses CComContainedObject to delegate to the outer unknown.

For more information about aggregation, see the article Fundamentals of ATL COM Objects.

#include <atlcom.h>

Class Members

See Also CComObject, CComPolyObject, DECLARE_AGGREGATABLE, DECLARE_ONLY_AGGREGATABLE, DECLARE_NOT_AGGREGATABLE


CComAggObject Class Members

Class Methods

CcomAggObject | Constructor.
FinalConstruct | Performs final initialization of m_contained.
FinalRelease | Performs final destruction of m_contained.

IUnknown Methods

AddRef | Increments the reference count on the aggregated object.
QueryInterface | Retrieves a pointer to the requested interface.
Release | Decrements the reference count on the aggregated object.

Data Members

m_contained Delegates IUnknown calls to the outer unknown.

CComAggObject Overview


CComAggObject::AddRef

ULONG AddRef( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Increments the reference count on the aggregated object.

CComAggObject Overview | Class Members

See Also CComAggObject::Release


CComAggObject::CComAggObject

CComAggObject( void* pv );

Parameters

pv

[in] The outer unknown.

Remarks

The constructor. Initializes the CComContainedObject member, m_contained, and increments the module lock count.

The destructor decrements the module lock count.

CComAggObject Overview | Class Members

See Also CComAggObject::FinalConstruct, CComAggObject::FinalRelease


CComAggObject::FinalConstruct

HRESULT FinalConstruct( );

Return Value

A standard HRESULT value.

Remarks

Called during the final stages of object construction, this method performs any final initialization on the m_contained member.

CComAggObject Overview | Class Members

See Also CComObjectRootEx::FinalConstruct, CComAggObject::FinalRelease


CComAggObject::FinalRelease

void FinalRelease( );

Remarks

Called during object destruction, this method frees the m_contained member.

CComAggObject Overview | Class Members

See Also CComObjectRootEx::FinalRelease, CComAggObject::FinalConstruct


CComAggObject::QueryInterface

HRESULT QueryInterface( REFIID iid, void** ppvObject );

Return Value

A standard HRESULT value.

Parameters

iid

[in] The identifier of the interface being requested.

ppvObject

[out] A pointer to the interface pointer identified by iid. If the object does not support this interface, ppvObject is set to NULL.

Remarks

Retrieves a pointer to the requested interface. If the requested interface is IUnknown, QueryInterface returns a pointer to the aggregated object's own IUnknown and increments the reference count. Otherwise, this method queries for the interface through the CComContainedObject member, m_contained.


CComAggObject::Release

ULONG Release( );

Return Value

In debug builds, Release returns a value that may be useful for diagnostics or testing. In non-debug builds, Release always returns 0.

Remarks

Decrements the reference count on the aggregated object.

CComAggObject Overview | Class Members

See Also CComAggObject::AddRef


CComAggObject::m_contained

CComContainedObject< contained > m_contained;

Parameters

contained

[in] Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interfaces you want to support on the object.

Remarks

A CComContainedObject object derived from your class. All IUnknown calls through m_contained are delegated to the outer unknown.


CComApartment

class CComApartment

CComApartment is used by CComAutoThreadModule to manage an apartment in a thread-pooled EXE module. CComApartment provides methods for incrementing and decrementing the lock count on a thread.

#include <atlbase.h>

Class Members


CComApartment Class Members

Methods

Apartment | Marks the starting address of the thread.
GetLockCount | Returns the current lock count on the thread.
Lock | Increments the lock count on the thread.
Unlock | Decrements the lock count on the thread.

Data Members

m_dwThreadID | Contains the identifier of the thread.
m_hThread | Contains the handle to the thread.
m_nLockCnt | Contains the current lock count on the thread.

CComApartment Overview


CComApartment::Apartment

DWORD Apartment( );

Return Value

Always 0.

Remarks

The thread function marking the starting address of the thread. Automatically set during CComAutoThreadModule::Init.


CComApartment::GetLockCount

LONG GetLockCount( );

Return Value

The lock count on the thread.

Remarks

Returns the current lock count on the thread.

CComApartment Overview | Class Members

See Also CComApartment::Lock, CComApartment::Unlock, CComApartment::m_nLockCnt


CComApartment::Lock

LONG Lock( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Performs an atomic increment on the thread’s lock count. Called by CComAutoThreadModule::Lock.

The lock count on the thread is used for statistical purposes.

CComApartment Overview | Class Members

See Also CComApartment:Unlock, CComApartment::GetLockCount, CComApartment::m_nLockCnt


CComApartment::Unlock

LONG Unlock( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Performs an atomic decrement on the thread’s lock count. Called by CComAutoThreadModule::Unlock.

The lock count on the thread is used for statistical purposes.

CComApartment Overview | Class Members

See Also CComApartment::Lock, CComApartment::GetLockCount, CComApartment::m_nLockCnt


CComApartment::m_dwThreadID

DWORD m_dwThreadID;

Remarks

Contains the identifier of the thread.


CComApartment::m_hThread

HANDLE m_hThread;

Remarks

Contains the handle to the thread.


CComApartment::m_nLockCnt

LONG m_nLockCnt;

Remarks

Contains the current lock count on the thread.

CComApartment Overview | Class Members

See Also CComApartment::Lock, CComApartment::Unlock


CComAutoCriticalSection

class CComAutoCriticalSection

CComAutoCriticalSection provides methods for obtaining and releasing ownership of a critical section object. CComAutoCriticalSection is similar to class CComCriticalSection, except CComAutoCriticalSection automatically initializes critical section objects in the constructor.

Typically, you use CComAutoCriticalSection through the typedef name AutoCriticalSection. This name references CComAutoCriticalSection when CComMultiThreadModel is being used.

You should not use CComAutoCriticalSection in global objects or static class members if you want to eliminate the CRT startup code. In this case, use CComCriticalSection.

#include <atlbase.h>

Class Members

See Also CComFakeCriticalSection


CComAutoCriticalSection Class Members

Methods

CcomAutoCriticalSection | Constructor.
Lock | Obtains ownership of the critical section object.
Unlock | Releases ownership of the critical section object.

Data Members

m_sec A CRITICAL_SECTION object.

CComAutoCriticalSection Overview


CComAutoCriticalSection::CComAutoCriticalSection

void CComAutoCriticalSection( );

Remarks

The constructor. Calls the Win32 function InitializeCriticalSection, which initializes the critical section object contained in the m_sec data member.

The destructor calls DeleteCriticalSection, which releases all system resources used by the critical section object.


CComAutoCriticalSection::Lock

void Lock( );

Remarks

Calls the Win32 function EnterCriticalSection, which waits until the thread can take ownership of the critical section object contained in the m_sec data member. When the protected code has finished executing, the thread must call Unlock to release ownership of the critical section.


CComAutoCriticalSection::Unlock

void Unlock( );

Remarks

Calls the Win32 function LeaveCriticalSection, which releases ownership of the critical section object contained in the m_sec data member. To first obtain ownership, the thread must call the Lock method. Each call to Lock then requires a corresponding call to Unlock to release ownership of the critical section.


CComAutoCriticalSection::m_sec

CRITICAL_SECTION m_sec;

Remarks

Contains a critical section object that is used by all CComAutoCriticalSection methods.

CComCriticalSection Overview | Class Members

See Also CComAutoCriticalSection::CComAutoCriticalSection, CComAutoCriticalSection::Lock, CComAutoCriticalSection::Unlock


CComAutoThreadModule

template< class ThreadAllocator = CComSimpleThreadAllocator >
class CComAutoThreadModule : public CComModule

Parameters

ThreadAllocator

[in] The class managing thread selection. The default value is CComSimpleThreadAllocator.

CComAutoThreadModule derives from CComModule to implement a thread-pooled, apartment-model COM server for EXEs and Windows NT services. CComAutoThreadModule uses CComApartment to manage an apartment for each thread in the module.

Derive your module from CComAutoThreadModule when you want to create objects in multiple apartments. You must also include the DECLARE_CLASSFACTORY_AUTO_THREAD macro in your object’s class definition to specify CComClassFactoryAutoThread as the class factory.

By default, the ATL COM AppWizard will derive your module from CComModule. To use CComAutoThreadModule, modify the class definition. For example:

class CMyModule :
public CComAutoThreadModule<CComSimpleThreadAllocator>
{
public:
   LONG Unlock( )
   {
      LONG l = CComAutoThreadModule<ComSimpleThreadAllocator>::Unlock( );
      if (l == 0)
         PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
      return l;
   }

   DWORD dwThreadID;
};

For more information about the AppWizard, see the article Creating an ATL Project.

#include <atlbase.h>

Class Members


CComAutoThreadModule Class Members

Methods

CreateInstance | Selects a thread and then creates an object in the associated apartment.
GetDefaultThreads | Dynamically calculates the number of threads for the module based on the number of processors.
Init | Creates the module’s threads.
Lock | Increments the lock count on the module and on the current thread.
Unlock | Decrements the lock count on the module and on the current thread.

Data Members

dwThreadID | Contains the identifier of the current thread.
m_Allocator | Manages thread selection.
m_nThreads | Contains the number of threads in the module.
m_pApartments | Manages the module’s apartments.

CComAutoThreadModule Overview


CComAutoThreadModule::CreateInstance

HRESULT CreateInstance( void* pfnCreateInstance, REFIID riid, void** ppvObj );

Return Value

A standard HRESULT value.

Parameters

pfnCreateInstance

[in] A pointer to a creator function.

riid

[in] The IID of the requested interface.

ppvObj

[out] A pointer to the interface pointer identified by riid. If the object does not support this interface, ppvObj is set to NULL.

Remarks

Selects a thread and then creates an object in the associated apartment. Called by CComClassFactoryAutoThread::CreateInstance.


CComAutoThreadModule::GetDefaultThreads

static int GetDefaultThreads( );

Return Value

The number of threads to be created in the EXE module.

Remarks

This static method dynamically calculates the maximum number of threads for the EXE module, based on the number of processors. By default, this return value is passed to the Init method to create the threads.


CComAutoThreadModule::Init

void Init( _ATL_OBJMAP_ENTRY* p, HINSTANCE h, int nThreads = GetDefaultThreads( ) );

Parameters

p

[in] A pointer to an array of object map entries.

h

[in] The HINSTANCE passed to DLLMain or WinMain.

nThreads

[in] The number of threads to be created. By default, nThreads is the value returned by GetDefaultThreads.

Remarks

Initializes data members and creates the number of threads specified by nThreads.

CComAutoThreadModule Overview | Class Members

See Also CComAutoThreadModule::m_nThreads


CComAutoThreadModule::Lock

LONG Lock( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Performs an atomic increment on the lock count for the module and for the current thread. CComAutoThreadModule uses the module lock count to determine whether any clients are accessing the module. The lock count on the current thread is used for statistical purposes.

CComAutoThreadModule Overview | Class Members

See Also CComAutoThreadModule::Unlock, CComModule::m_nLockCnt, CComApartment::m_nLockCnt


CComAutoThreadModule::Unlock

LONG Unlock( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Performs an atomic decrement on the lock count for the module and for the current thread. CComAutoThreadModule uses the module lock count to determine whether any clients are accessing the module. The lock count on the current thread is used for statistical purposes.

When the module lock count reaches zero, the module can be unloaded.

CComAutoThreadModule Overview | Class Members

See Also CComAutoThreadModule::Lock, CComModule::m_nLockCnt, CComApartment::m_nLockCnt


CComAutoThreadModule::dwThreadID

DWORD dwThreadID;

Remarks

Contains the identifier of the current thread.


CComAutoThreadModule::m_Allocator

ThreadAllocator m_Allocator;

Remarks

The object managing thread selection. By default, the ThreadAllocator class template parameter is CComSimpleThreadAllocator.


CComAutoThreadModule::m_nThreads

int m_nThreads;

Remarks

Contains the number of threads in the EXE module. When Init is called, m_nThreads is set to the nThreads parameter value. Each thread’s associated apartment is managed by a CComApartment object.

CComAutoThreadModule Overview | Class Members

See Also CComAutoThreadModule::m_pApartments


CComAutoThreadModule::m_pApartments

CComApartment* m_pApartments;

Remarks

Points to an array of CComApartment objects, each of which manages an apartment in the module. The number of elements in the array is based on the m_nThreads member.


CComBSTR

class CComBSTR

The CComBSTR class is a wrapper for BSTRs, length-prefixed strings. The length is stored as an integer at the memory location preceding the data in the string.

A BSTR is null-terminated after the last counted character, but may also contain null characters embedded within the string. The string length is determined by the character count, not the first null character.

#include <atlbase.h>

Class Members


CComBSTR Class Members

Methods

Append | Appends a string to m_str.
AppendBSTR | Appends a BSTR to m_str.
Attach | Attaches a BSTR to the CComBSTR object.
CComBstr | Constructor.
Copy | Returns a copy of m_str.
Detach | Detaches m_str from the CComBSTR object.
Empty | Frees m_str.
Length | Returns the length of m_str.
LoadString | Loads a string resource.
ReadFromStream | Loads a BSTR object from a stream.
WriteToStream | Saves m_str to a stream.

Operators

operator BSTR | Converts a CcomBSTR object to a BSTR.
operator = | Assigns a value to m_str.
operator += | Appends a CcomBSTR to the object.
operator & | Returns the address of m_str.
operator ! | Returns TRUE or FALSE, depending on whether m_str is NULL.

Data Members

m_str Contains the BSTR associated with the CComBSTR object.

CComBSTR Overview


CComBSTR::Append

void Append( const CComBSTR& bstrSrc );

void Append( LPCOLESTR lpsz );

void Append( LPCSTR lpsz );

void Append( LPCOLESTR lpsz, int nLen );

Parameters

bstrSrc

[in] A CComBSTR object.

lpsz

[in] A character string. The Unicode version specifies an LPCOLESTR; the ANSI version specifies an LPCSTR.

nLen

[in] The number of characters from lpsz to append.

Remarks

Appends either lpsz or the BSTR member of bstrSrc to m_str.

CComBSTR Overview | Class Members

See Also CComBSTR::AppendBSTR, CComBSTR::operator +=


CComBSTR::AppendBSTR

void AppendBSTR( BSTR p );

Parameters

p

[in] A BSTR to append.

Remarks

Appends the specified BSTR to m_str.

CComBSTR Overview | Class Members

See Also CComBSTR::Append, CComBSTR::operator +=


CComBSTR::Attach

void Attach( BSTR src );

Parameters

src

[in] The BSTR to attach to the object.

Remarks

Attaches a BSTR to the CComBSTR object by setting the m_str member to src.

Note This method will assert if m_str is non-NULL.

CComBSTR Overview | Class Members

See Also CComBSTR::Detach, CComBSTR::operator =


CComBSTR::CComBSTR

CComBSTR( );

CComBSTR( int nSize );

CComBSTR( int nSize, LPCOLESTR sz );

CComBSTR( int nSize, LPCSTR sz );

CComBSTR( LPCOLESTR pSrc );

CComBSTR( LPCSTR pSrc );

CComBSTR( const CComBSTR& src );

Parameters

nSize

[in] The number of characters to copy from sz.

sz

[in] A string to copy. The Unicode version specifies an LPCOLESTR; the ANSI version specifies an LPCSTR. Only nSize characters will be copied. The default value is NULL.

pSrc

[in] A string to copy. The Unicode version specifies an LPCOLESTR; the ANSI version specifies an LPCSTR.

src

[in] A CComBSTR object.

Remarks

The default constructor sets the m_str member to NULL. The copy constructor sets m_str to a copy of the BSTR member of src.

The other four constructors set m_str to a copy of the specified string; however, if you pass a value for nSize, then only nSize characters will be copied, followed by a terminating null character.

The destructor frees the string pointed to by m_str.


CComBSTR::Copy

BSTR Copy( ) const;

Return Value

A copy of the m_str member.

Remarks

Allocates and returns a copy of m_str.

CComBSTR Overview | Class Members

See Also CComBSTR::operator =


CComBSTR::Detach

BSTR Detach( );

Return Value

The BSTR associated with the CComBSTR object.

Remarks

Detaches m_str from the CComBSTR object and sets m_str to NULL.

CComBSTR Overview | Class Members

See Also CComBSTR::Attach


CComBSTR::Empty

void Empty( );

Remarks

Frees the m_str member.


CComBSTR::Length

unsigned int Length( ) const;

Return Value

The length of the m_str member.

Remarks

Returns the number of characters in m_str, excluding the terminating null character.


CComBSTR::LoadString

bool LoadString( HINSTANCE hInst, UINT nID );

bool LoadString( UINT nID );

Return Value

Returns true if the string is successfully loaded. Otherwise, this function returns false.

Parameters

See LoadString in the Win32 SDK.

Remarks

Loads a string resource specified by HINSTANCE, and stores it in this object. The first function uses the hInst supplied by you. The second function uses the m_hInstResource member of CComModule.


CComBSTR::ReadFromStream

HRESULT ReadFromStream( IStream* pStream );

Return Value

A standard HRESULT value.

Parameters

pStream

[in] A pointer to the IStream interface on the stream containing the data.

Remarks

Sets the m_str member to the BSTR contained in the specified stream. ReadToStream requires a previous call to WriteToStream.


CComBSTR::WriteToStream

HRESULT WriteToStream( IStream* pStream );

Return Value

A standard HRESULT value.

Parameters

pStream

[in] A pointer to the IStream interface on a stream.

Remarks

Saves the m_str member to a stream.

CComBSTR Overview | Class Members

See Also CComBSTR::ReadFromStream


CComBSTR::operator BSTR

operator BSTR( ) const;

Remarks

Converts a CComBSTR object to a BSTR.


CComBSTR::operator =

CComBSTR& operator =( LPCOLESTR pSrc );

CComBSTR& operator =( LPCSTR pSrc );

CComBSTR& operator =( const CComBSTR& src );

Remarks

Sets the m_str member to a copy of pSrc or to a copy of the BSTR member of src. The pSrc parameter specifies either an LPCOLESTR for Unicode versions or LPCSTR for ANSI versions.

CComBSTR Overview | Class Members

See Also CComBSTR::Copy


CComBSTR::operator +=

CComBSTR& operator +=( const CComBSTR& bstrSrc );

Remarks

Appends the BSTR member of bstrSrc to m_str.

CComBSTR Overview | Class Members

See Also CComBSTR::Append, CComBSTR::AppendBSTR


CComBSTR::operator &

BSTR* operator &( );

Remarks

Returns the address of the BSTR stored in the m_str member.


CComBSTR::operator !

bool operator !( );

Remarks

Returns true if the m_str member is NULL; otherwise, false.


CComBSTR::m_str

BSTR m_str;

Remarks

Contains the BSTR associated with the CComBSTR object.


CComCachedTearOffObject

template <class contained>
class CComCachedTearOffObject : public IUnknown, public CComObjectRootEx< contained::_ThreadModel::ThreadModelNoCS >

Parameters

contained

Your tear-off class, derived from CComTearOffObjectBase and the interfaces you want your tear-off object to support.

CComCachedTearOffObject implements IUnknown for a tear-off interface. This class differs from CComTearOffObject in that CComCachedTearOffObject has its own IUnknown, separate from the owner object's IUnknown (the owner is the object for which the tear-off is being created). CComCachedTearOffObject maintains its own reference count on its IUnknown and deletes itself once its reference count is 0. Note, however, that querying for any of its tear-off interfaces increments the reference count of the owner object's IUnknown.

If the CComCachedTearOffObject object implementing the tear-off is already instantiated, and the tear-off interface is queried for again, the same CComCachedTearOffObject object is reused. In contrast, if a tear-off interface implemented by a CComTearOffObject is again queried for through the owner object, another CComTearOffObject will be instantiated.

The owner class must implement FinalRelease and call Release on the cached IUnknown for the CComCachedTearOffObject, which will decrement its reference count. This will cause CComCachedTearOffObject's FinalRelease to be called and delete the tear-off.

#include <atlcom.h>

Class Members

See Also CComTearOffObject, CComObjectRootEx


CComCachedTearOffObject Class Members

Methods

AddRef | Increments the reference count for a CComCachedTearOffObject object.
CcomCachedTearOffObject | Constructor.
FinalConstruct | Calls the m_contained::FinalConstruct (the tear-off class' method).
FinalRelease | Calls the m_contained::FinalRelease (the tear-off class' method).
QueryInterface | Returns a pointer to the IUnknown of the CComCachedTearOffObject object, or to the requested interface on your tear-off class (the class contained).
Release | Decrements the reference count for a CComCachedTearOffObject object and destroys it if the reference count is 0.

Data Members

m_contained A CComContainedObject object derived from your tear-off class (the class contained).

CComCachedTearOffObject Overview


CComCachedTearOffObject::AddRef

ULONG AddRef( );

Return Value

A value that may be useful for diagnostics and testing.

Remarks

Increments the reference count of the CComCachedTearOffObject object by 1.

CComCachedTearOffObject Overview | Class Members

See Also CComCachedTearOffObject::Release


CComCachedTearOffObject::CComCachedTearOffObject

CComCachedTearOffObject( void* pv );

Parameters

pv

[in] Pointer to the IUnknown of the CComCachedTearOffObject.

Remarks

The constructor. Initializes the CComContainedObject member, m_contained.

CComCachedTearOffObject Overview | Class Members

See Also CComTearOffObject


CComCachedTearOffObject::FinalConstruct

HRESULT FinalConstruct( );

Return Value

A standard HRESULT value.

Remarks

Calls m_contained::FinalConstruct to create m_contained, the CComContainedObject<contained> object used to access the interface implemented by your tear-off class.

CComCachedTearOffObject Overview | Class Members

See Also CComCachedTearOffObject::FinalRelease


CComCachedTearOffObject::FinalRelease

void FinalRelease( );

Remarks

Calls m_contained::FinalRelease to free m_contained, the CComContainedObject<contained> object.

CComCachedTearOffObject Overview | Class Members

See Also CComCachedTearOffObject::FinalConstruct


CComCachedTearOffObject::QueryInterface

HRESULT QueryInterface( REFIID iid , void** ppvObject );

Return Value

A standard HRESULT value.

Parameters

iid

[in] The GUID of the interface being requested.

ppvObject

[out] A pointer to the interface pointer identified by iid, or NULL if the interface is not found.

Remarks

Retrieves a pointer to the requested interface. If the requested interface is IUnknown, returns a pointer to the CComCachedTearOffObject's own IUnknown and increments the reference count. Otherwise, queries for the interface on your tear-off class using the InternalQueryInterface method inherited from CComObjectRootEx.

CComCachedTearOffObject Overview | Class Members

See Also CComCachedTearOffObject::AddRef, CComCachedTearOffObject::Release


CComCachedTearOffObject::Release

ULONG Release( );

Return Value

In non-debug builds, always returns 0. In debug builds, returns the a value that may be useful for diagnostics or testing.

Remarks

Decrements the reference count by 1 and, if the reference count is 0, deletes the CComCachedTearOffObject object.

CComCachedTearOffObject Overview | Class Members

See Also CComCachedTearOffObject::AddRef


CComCachedTearOffObject::m_contained

CComContainedObject<contained> m_contained;

Parameters

contained

[in] Your tear-off class, derived from CComTearOffObjectBase and the interfaces you want your tear-off object to support.

Remarks

A CComContainedObject object derived from your tear-off class. The methods m_contained inherits are used to access the tear-off interface in your tear-off class through the cached tear-off object's QueryInterface, FinalConstruct, and FinalRelease.

CComCachedTearOffObject Overview | Class Members

See Also CComTearOffObject


CComClassFactory

class CComClassFactory : public IClassFactory,
public CComObjectRootEx< CComGlobalsThreadModel >

CComClassFactory implements the IClassFactory interface, which contains methods for creating an object of a particular CLSID, as well as locking the class factory in memory to allow new objects to be created more quickly. IClassFactory must be implemented for every class that you register in the system registry and to which you assign a CLSID.

ATL objects normally acquire a class factory by deriving from CComCoClass. This class includes the macro DECLARE_CLASSFACTORY, which declares CComClassFactory as the default class factory. To override this default, specify one of the DECLARE_CLASSFACTORY XXX macros in your class definition. For example, the DECLARE_CLASSFACTORY_EX macro uses the specified class for the class factory:

class CMyClass : ..., public CComCoClass< ... >
{
public:
   DECLARE_CLASSFACTORY_EX(CMyClassFactory)

   ...
};

The above class definition specifies that CMyClassFactory will be used as the object's default class factory. CMyClassFactory must derive from CComClassFactory and override CreateInstance.

ATL provides three other macros that declare a class factory:

  • DECLARE_CLASSFACTORY2 Uses CComClassFactory2, which controls creation through a license.

  • DECLARE_CLASSFACTORY_AUTO_THREAD Uses CComClassFactoryAutoThread, which creates objects in multiple apartments.

  • DECLARE_CLASSFACTORY_SINGLETON Uses CComClassFactorySingleton, which constructs a single CComObjectGlobal object.

#include <atlcom.h>

Class Members

See Also CComObjectRootEx, CComGlobalsThreadModel


CComClassFactory Class Members

IClassFactory Methods

CreateInstance | Creates an object of the specified CLSID.
LockServer | Locks the class factory in memory.

CComClassFactory Overview


CComClassFactory::CreateInstance

HRESULT CreateInstance( LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj );

Return Value

A standard HRESULT value.

Parameters

pUnkOuter

[in] If the object is being created as part of an aggregate, then pUnkOuter must be the outer unknown. Otherwise, pUnkOuter must be NULL.

riid

[in] The IID of the requested interface. If pUnkOuter is non-NULL, riid must be IID_IUnknown.

ppvObj

[out] A pointer to the interface pointer identified by riid. If the object does not support this interface, ppvObj is set to NULL.

Remarks

Creates an object of the specified CLSID and retrieves an interface pointer to this object.

CComClassFactory Overview | Class Members

See Also CoCreateInstance, CoGetClassObject


CComClassFactory::LockServer

HRESULT LockServer( BOOL fLock );

Return Value

A standard HRESULT value.

Parameters

fLock

[in] If TRUE, the lock count is incremented; otherwise, the lock count is decremented.

Remarks

Increments and decrements the module lock count by calling _Module::Lock and _Module::Unlock, respectively. _Module refers to the global instance of CComModule or a class derived from it.

Calling LockServer allows a client to hold onto a class factory so that multiple objects can be created quickly.

CComClassFactory Overview | Class Members

See Also CComModule::Lock, CComModule::Unlock


CComClassFactory2

template< class license >
class CComClassFactory2 : public CComClassFactory2Base, license

Parameters

license

A class that implements the following static functions:

  • static BOOL VerifyLicenseKey( BSTR bstr );

  • static BOOL GetLicenseKey( DWORD dwReserved, BSTR* pBstr );

  • static BOOL IsLicenseValid( );

CComClassFactory2 implements the IClassFactory2 interface, which is an extension of IClassFactory. IClassFactory2 controls object creation through a license. A class factory executing on a licensed machine can provide a run-time license key. This license key allows an application to instantiate objects when a full machine license does not exist.

ATL objects normally acquire a class factory by deriving from CComCoClass. This class includes the macro DECLARE_CLASSFACTORY, which declares CComClassFactory as the default class factory. To use CComClassFactory2, specify the DECLARE_CLASSFACTORY2 macro in your object’s class definition. For example:

class CMyClass : ..., public CComCoClass< ... >
{
public:
   DECLARE_CLASSFACTORY2(CMyLicense)

   ...
};

CMyLicense, the template parameter to CComClassFactory2, must implement the static functions VerifyLicenseKey, GetLicenseKey, and IsLicenseValid. The following is an example of a simple license class:

class CMyLicense
{
protected:
   static BOOL VerifyLicenseKey(BSTR bstr)
   {
      USES_CONVERSION;
      return !lstrcmp(OLE2T(bstr), _T("My run-time license key"));
   }

   static BOOL GetLicenseKey(DWORD dwReserved, BSTR* pBstr)
   {
      USES_CONVERSION;
      *pBstr = SysAllocString( T2OLE(_T("My run-time license key")));
      return TRUE;
   }

   static BOOL IsLicenseValid() {  return TRUE; }
};

CComClassFactory2 derives from both CComClassFactory2Base and license. CComClassFactory2Base, in turn, derives from IClassFactory2 and CComObjectRootEx< CComGlobalsThreadModel >.

#include <atlcom.h>

Class Members

See Also CComClassFactoryAutoThread, CComClassFactorySingleton, CComObjectRootEx, CComGlobalsThreadModel


CComClassFactory2 Class Members

IClassFactory Methods

CreateInstance | Creates an object of the specified CLSID.
LockServer | Locks the class factory in memory.

IClassFactory2 Methods

CreateInstanceLic | Given a license key, creates an object of the specified CLSID.
GetLicInfo | Retrieves information describing the licensing capabilities of the class factory.
RequestLicKey | Creates and returns a license key.

CComClassFactory2 Overview


CComClassFactory2::CreateInstance

HRESULT CreateInstance( LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj );

Return Value

A standard HRESULT value.

Parameters

pUnkOuter

[in] If the object is being created as part of an aggregate, then pUnkOuter must be the outer unknown. Otherwise, pUnkOuter must be NULL.

riid

[in] The IID of the requested interface. If pUnkOuter is non-NULL, riid must be IID_IUnknown.

ppvObj

[out] A pointer to the interface pointer identified by riid. If the object does not support this interface, ppvObj is set to NULL.

Remarks

Creates an object of the specified CLSID and retrieves an interface pointer to this object. Requires the machine to be fully licensed. If a full machine license does not exist, call CreateInstanceLic.

CComClassFactory2 Overview | Class Members

See Also CoCreateInstance, CoGetClassObject


CComClassFactory2::CreateInstanceLic

HRESULT CreateInstanceLic( IUnknown* pUnkOuter, IUnknown* pUnkReserved, REFIID riid, BSTR bstrKey, void** ppvObject );

Return Value

A standard HRESULT value.

Parameters

pUnkOuter

[in] If the object is being created as part of an aggregate, then pUnkOuter must be the outer unknown. Otherwise, pUnkOuter must be NULL.

pUnkReserved

[in] Not used. Must be NULL.

riid

[in] The IID of the requested interface. If pUnkOuter is non-NULL, riid must be IID_IUnknown.

bstrKey

[in] The run-time license key previously obtained from a call to RequestLicKey. This key is required to create the object.

ppvObject

[out] A pointer to the interface pointer specified by riid. If the object does not support this interface, ppvObject is set to NULL.

Remarks

Similar to CreateInstance, except that CreateInstanceLic requires a license key. You can obtain a license key using RequestLicKey. In order to create an object on an unlicensed machine, you must call CreateInstanceLic.

CComClassFactory2 Overview | Class Members

See Also CoCreateInstance, CoGetClassObject


CComClassFactory2::GetLicInfo

HRESULT GetLicInfo( LICINFO* pLicInfo );

Return Value

A standard HRESULT value.

Parameters

pLicInfo

[out] Pointer to a LICINFO structure.

Remarks

Fills a LICINFO structure with information that describes the class factory's licensing capabilities. The fRuntimeKeyAvail member of this structure indicates whether, given a license key, the class factory allows objects to be created on an unlicensed machine. The fLicVerified member indicates whether a full machine license exists.

CComClassFactory2 Overview | Class Members

See Also CComClassFactory2::RequestLicKey, CComClassFactory2::CreateInstanceLic


CComClassFactory2::LockServer

HRESULT LockServer( BOOL fLock );

Return Value

A standard HRESULT value.

Parameters

fLock

[in] If TRUE, the lock count is incremented; otherwise, the lock count is decremented.

Remarks

Increments and decrements the module lock count by calling _Module::Lock and _Module::Unlock, respectively. _Module refers to the global instance of CComModule or a class derived from it.

Calling LockServer allows a client to hold onto a class factory so that multiple objects can be quickly created.

CComClassFactory2 Overview | Class Members

See Also CComModule::Lock, CComModule::Unlock


CComClassFactory2::RequestLicKey

HRESULT RequestLicKey( DWORD dwReserved, BSTR* pbstrKey );

Return Value

A standard HRESULT value.

Parameters

dwReserved

[in] Not used. Must be zero.

pbstrKey

[out] Pointer to the license key.

Remarks

Creates and returns a license key, provided that the fRuntimeKeyAvail member of the LICINFO structure is TRUE. A license key is required for calling CreateInstanceLic to create an object on an unlicensed machine. If fRuntimeKeyAvail is FALSE, then objects can only be created on a fully licensed machine.

Call GetLicInfo to retrieve the value of fRuntimeKeyAvail.


CComClassFactoryAutoThread

class CComClassFactoryAutoThread : public IClassFactory,
public CComObjectRootEx< CComGlobalsThreadModel >

CComClassFactoryAutoThread is similar to CComClassFactory, but allows objects to be created in multiple apartments. To take advantage of this support, derive your EXE module from CComAutoThreadModule.

ATL objects normally acquire a class factory by deriving from CComCoClass. This class includes the macro DECLARE_CLASSFACTORY, which declares CComClassFactory as the default class factory. To use CComClassFactoryAutoThread, specify the DECLARE_CLASSFACTORY_AUTO_THREAD macro in your object's class definition. For example:

class CMyClass : ..., public CComCoClass< ... >
{
public:
   DECLARE_CLASSFACTORY_AUTO_THREAD( )

   ...
};

#include <atlcom.h>

Class Members

See Also IClassFactory, CComClassFactory2, CComClassFactorySingleton, CComObjectRootEx, CComGlobalsThreadModel


CComClassFactoryAutoThread Class Members

IClassFactory Methods

CreateInstance | Creates an object of the specified CLSID.
LockServer | Locks the class factory in memory.

CComClassFactoryAutoThread Overview


CComClassFactoryAutoThread::CreateInstance

HRESULT CreateInstance( LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj );

Return Value

A standard HRESULT value.

Parameters

pUnkOuter

[in] If the object is being created as part of an aggregate, then pUnkOuter must be the outer unknown. Otherwise, pUnkOuter must be NULL.

riid

[in] The IID of the requested interface. If pUnkOuter is non-NULL, riid must be IID_IUnknown.

ppvObj

[out] A pointer to the interface pointer identified by riid. If the object does not support this interface, ppvObj is set to NULL.

Remarks

Creates an object of the specified CLSID and retrieves an interface pointer to this object. If your module derives from CComAutoThreadModule, CreateInstance first selects a thread to create the object in the associated apartment.

CComClassFactoryAutoThread Overview | Class Members

See Also CoCreateInstance, CoGetClassObject


CComClassFactoryAutoThread::LockServer

HRESULT LockServer( BOOL fLock );

Return Value

A standard HRESULT value.

Parameters

fLock

[in] If TRUE, the lock count is incremented; otherwise, the lock count is decremented.

Remarks

Increments and decrements the module lock count by calling _Module::Lock and _Module::Unlock, respectively. When using CComClassFactoryAutoThread, _Module typically refers to the global instance of CComAutoThreadModule.

Calling LockServer allows a client to hold onto a class factory so that multiple objects can be quickly created.

CComClassFactoryAutoThread Overview | Class Members

See Also CComAutoThreadModule::Lock, CComAutoThreadModule::Unlock


CComClassFactorySingleton

template< class T >
class CComClassFactorySingleton : public CComClassFactory

Parameters

T

Your class.

CComClassFactorySingleton derives from CComClassFactory and uses CComObjectGlobal to construct a single object. Each call to the CreateInstance method simply queries this object for an interface pointer.

ATL objects normally acquire a class factory by deriving from CComCoClass. This class includes the macro DECLARE_CLASSFACTORY, which declares CComClassFactory as the default class factory. To use CComClassFactorySingleton, specify the DECLARE_CLASSFACTORY_SINGLETON macro in your object’s class definition. For example:

class CMyClass : ..., public CComCoClass< ... >
{
public:
   DECLARE_CLASSFACTORY_SINGLETON(CMyClass)

   ...
};

#include <atlcom.h>

Class Members

See Also IClassFactory, CComClassFactory2, CComClassFactoryAutoThread, CComObjectRootEx, CComGlobalsThreadModel


CComClassFactorySingleton Class Members

IClassFactory Methods

CreateInstance Queries m_Obj for an interface pointer.

Data Members

m_Obj The CComObjectGlobal object constructed by CComClassFactorySingleton.

CComClassFactorySingleton Overview


CComClassFactorySingleton::CreateInstance

HRESULT CreateInstance( LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj );

Return Value

A standard HRESULT value.

Parameters

pUnkOuter

[in] If the object is being created as part of an aggregate, then pUnkOuter must be the outer unknown. Otherwise, pUnkOuter must be NULL.

riid

[in] The IID of the requested interface. If pUnkOuter is non-NULL, riid must be IID_IUnknown.

ppvObj

[out] A pointer to the interface pointer identified by riid. If the object does not support this interface, ppvObj is set to NULL.

Remarks

Calls QueryInterface through m_Obj to retrieve an interface pointer.

CComClassFactorySingleton Overview | Class Members

See Also CoCreateInstance, CoGetClassObject


CComClassFactorySingleton::m_Obj

CComObjectGlobal< T > m_Obj;

Remarks

The CComObjectGlobal object constructed by CComClassFactorySingleton, where T is the class template parameter. Each call to the CreateInstance method simply queries this object for an interface pointer.


CComCoClass

template< class T, const CLSID* pclsid >
class CComCoClass

Parameters

T

Your class, derived from CComCoClass.

pclsid

A pointer to the CLSID of the object.

CComCoClass provides methods for retrieving an object’s CLSID and setting error information. Any class object that can be created externally should be derived from CComCoClass.

CComCoClass also defines the default class factory and aggregation model for your object. CComCoClass uses the following two macros:

  • DECLARE_CLASSFACTORY Declares the class factory to be CComClassFactory.

  • DECLARE_AGGREGATABLE Declares that your object can be aggregated.

You can override either of these defaults by specifying another macro in your class definition. For example, to use CComClassFactory2 instead of CComClassFactory, specify the DECLARE_CLASSFACTORY2 macro:

class CMyClass : ...,
   public CComCoClass<CMyClass, &CLSID_CMyClass>
{
public:
   DECLARE_CLASSFACTORY2(CMyLicense)

   ...
};

#include <atlcom.h>

Class Members


CComCoClass Class Members

Methods

Error | Returns rich error information to the client.
GetObjectCLSID | Returns the object’s class identifier.
GetObjectDescription | Override to return the object’s description.

CComCoClass Overview


CComCoClass::Error

static HRESULT Error( LPCOLESTR lpszDesc, const IID& iid = GUID_NULL, HRESULT hRes = 0 );

static HRESULT Error( LPCOLESTR lpszDesc, DWORD dwHelpID, LPCOLESTR lpszHelpFile, const IID& iid = GUID_NULL, HRESULT hRes = 0 );

static HRESULT Error( LPCSTR lpszDesc, const IID& iid = GUID_NULL, HRESULT hRes = 0 );

static HRESULT Error( LPCSTR lpszDesc, DWORD dwHelpID, LPCSTR lpszHelpFile, const IID& iid = GUID_NULL, HRESULT hRes = 0 );

static HRESULT Error( UINT nID, const IID& iid = GUID_NULL, HRESULT hRes = 0, HINSTANCE hInst = _Module.GetResourceInstance( ) );

static HRESULT Error( UINT nID, DWORD dwHelpID, LPCOLESTR lpszHelpFile, const IID& iid = GUID_NULL, HRESULT hRes = 0, HINSTANCE hInst = _Module.GetResourceInstance( ) );

Return Value

A standard HRESULT value. For details, see Remarks.

Parameters

lpszDesc

[in] The string describing the error. The Unicode version of Error specifies that lpszDesc is of type LPCOLESTR; the ANSI version specifies a type of LPCSTR.

iid

[in] The IID of the interface defining the error or GUID_NULL (the default value) if the error is defined by the operating system.

hRes

[in] The HRESULT you want returned to the caller. The default value is 0. For more details about hRes, see Remarks.

nID

[in] The resource identifier where the error description string is stored. This value should lie between 0x0200 and 0xFFFF, inclusively. In debug builds, an ASSERT will result if nID does not index a valid string. In release builds, the error description string will be set to “Unknown Error.”

dwHelpID

[in] The help context identifier for the error.

lpszHelpFile

[in] The path and name of the help file describing the error.

hInst

[in] The handle to the resource. By default, this parameter is _Module::GetResourceInstance, where _Module is the global instance of CComModule or a class derived from it.

Remarks

This static method sets up the IErrorInfo interface to provide error information to the client. In order to call Error, your object must implement the ISupportErrorInfo interface.

If the hRes parameter is nonzero, then Error returns the value of hRes. If hRes is zero, then the first four versions of Error return DISP_E_EXCEPTION. The last two versions return the result of the macro MAKE_HRESULT( 1, FACILITY_ITF, nID ).

CComCoClass Overview | Class Members

See Also ISupportErrorInfoImpl, MAKE_HRESULT


CComCoClass::GetObjectCLSID

static const CLSID& GetObjectCLSID( );

Return Value

The object's class identifier.

Remarks

Provides a consistent way of retrieving the object's CLSID.


CComCoClass::GetObjectDescription

static LPCTSTR WINAPI GetObjectDescription( );

Return Value

The class object’s description.

Remarks

This static method retrieves the text description for your class object. The default implementation returns NULL. You can override this method with the DECLARE_OBJECT_DESCRIPTION macro. For example:

class CMyClass : public CComCoClass< ... >, ...
{
public:
   DECLARE_OBJECT_DESCRIPTION("Account Transfer Object 1.0")

   ...
};

GetObjectDescription is called by IComponentRegistrar::GetComponents. IComponentRegistrar is an Automation interface that allows you to register and unregister individual components in a DLL. When you create a Component Registrar object with the ATL Object Wizard, the wizard will automatically implement the IComponentRegistrar interface. IComponentRegistrar is typically used by Microsoft Transaction Server.

For more information about the ATL Object Wizard, see the article Creating an ATL Project.


CComCompositeControl

template < class Base >
class CComCompositeControl : public CComControl< Base, CAxDialogImpl< Base> >

Parameters

Base

Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interfaces you wish to support for your composite control.

Classes derived from class CComCompositeControl inherit the functionality of an ActiveX composite control. ActiveX controls derived from CComCompositeControl are hosted by a standard dialog box. These types of controls are called composite controls because they are able to host other controls (native Windows controls and ActiveX controls).

CComCompositeControl identifies the dialog resource to use in creating the composite control by looking for an enumerated data member in the child class. The member IDD of this child class is set to the resource ID of the dialog resource that will be used as the control's window. The following is an example of the data member that the class derived from CComCompositeControl should contain to identify the dialog resource to be used for the control's window:

enum { IDD = IDD_MYCOMPOSITE };

Note Composite controls are always windowed controls, although they can contain windowless controls.

A control implemented by a CComCompositeControl-derived class has default tabbing behavior built in. When the control receives focus by being tabbed to in a containing application, successively pressing the TAB key will cause the focus to be cycled through all of the composite control's contained controls, then out of the composite control and on to the next item in the tab order of the container. The tab order of the hosted controls is determined by the dialog resource and determines the order in which tabbing will occur.

#include <atlctl.h>

Class Members

See Also

CComControl, Composite Control Fundamentals


CComCompositeControl Class Members

Methods

AdviseSinkMap | Advises or unadvises all controls hosted by the composite control.
Create | Creates a CComCompositeControl object.
CalcExtent | Retrieves the size of the composite control.

CComCompositeControl Overview


CComCompositeControl::AdviseSinkMap

HRESULT AdviseSinkMap( bool bAdvise );

Return Value

S_OK

All controls in the map were connected or disconnected from their event source successfully.

E_FAIL

Not all controls in the control map could be connected or disconnected from their event source successfully.

E_POINTER

This error usually indicates a problem with the control map entries or the IDispEventImpl entries in the MI list.

CONNECT_E_ADVISELIMIT

The connection point has already reached its limit of connections and cannot accept any more.

CONNECT_E_CANNOTCONNECT

The sink does not support the interface required by this connection point.

CONNECT_E_NOCONNECTION

The cookie value does not represent a valid connection. This error usually indicates a problem with the control map entries or the IDispEventImpl entries in the MI list.

Parameters

bAdvise

[in] TRUE if all controls are to be unadvised; otherwise FALSE.

Remarks

Call this function to advise or unadvise all controls hosted by the composite control.

The base implementation of this function searches through the entries in the event sink map. It then advises or unadvises the connection points to the COM objects described by the event sink map's sink entries. This member function also relies on the fact that the derived class inherits from one instance of IDispEventImpl for every control in the sink map that is to be advised or unadvised.

CComCompositeControl Overview | Class Members

See Also

IDispEventImpl, BEGIN_SINK_MAP


CComCompositeControl::CalcExtent

BOOL CalcExtent( SIZE& size );

Return Value

TRUE if the control is hosted by a dialog box; otherwise FALSE.

Parameters

size

[out] A reference to a SIZE structure to be filled by this function.

Remarks

Call this function to calculate the size in HIMETRIC units of the dialog resource used to host the composite control. The size is returned in the size parameter.

CComCompositeControl Overview | Class Members

See Also

AtlPixelToHiMetric


CComCompositeControl::Create

HWND Create( HWND hWndParent, RECT& rcPos, LPARAM dwInitParam = NULL );

Return Value

A handle to the newly created composite control dialog box.

Parameters

hWndParent

[in] A handle to the parent window of the control.

rcPos

[in] The position rectangle of the composite control in client coordinates relative to hwndParent.

dwInitParam

[in] Any additional data to be passed to the control during control creation. The data passed as dwInitParam will show up as the LPARAM parameter of the WM_INITDIALOG message, which will be sent to the composite control when it gets created.

Remarks

This method is called to create the control window for the composite control. It is usually called during in-place activation of the control.

CComCompositeControl Overview | Class Members

See Also

AtlAxCreateDialog, WM_INITDIALOG


CComContainedObject

template< class Base >
class CComContainedObject : public Base

Parameters

Base

Your class, derived from CComObjectRoot or CComObjectRootEx.

ATL uses CComContainedObject in classes CComAggObject, CComPolyObject, and CComCachedTearOffObject. CComContainedObject implements IUnknown by delegating to the owner object's IUnknown. (The owner is either the outer object of an aggregation, or the object for which a tear-off interface is being created.) CComContainedObject calls CComObjectRootEx's OuterQueryInterface, OuterAddRef, and OuterRelease, all inherited through Base.

#include <atlcom.h>

Class Members


CComContainedObject Class Members

Class Methods

CComContainedObject | Constructor. Initializes the member pointer to the owner object's IUnknown.
GetControllingUnknown | Retrieves the owner object's Iunknown.

IUnknown Methods

AddRef | Increments the reference count on the owner object.
QueryInterface | Retrieves a pointer to the interface requested on the owner object.
Release | Decrements the reference count on the owner object.

CComContainedObject Overview


CComContainedObject::AddRef

ULONG AddRef( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Increments the reference count on the owner object.

CComContainedObject Overview | Class Members

See Also CComContainedObject::Release


CComContainedObject::CComContainedObject

CComContainedObject( void* pv );

Parameters

pv

[in] The owner object's IUnknown.

Remarks

The constructor. Sets the m_pOuterUnknown member pointer (inherited through the Base class) to pv.

CComContainedObject Overview | Class Members

See Also CComObjectRootEx::m_pOuterUnknown


CComContainedObject::GetControllingUnknown

IUnknown* GetControllingUnknown( );

Return Value

The owner object's IUnknown.

Remarks

Returns the m_pOuterUnknown member pointer (inherited through the Base class) which holds the owner object's IUnknown. This method may be virtual if Base has declared the DECLARE_GET_CONTROLLING_UNKNOWN macro.

CComContainedObject Overview | Class Members

See Also CComObjectRootEx::m_pOuterUnknown


CComContainedObject::QueryInterface

HRESULT QueryInterface( REFIID iid, void** ppvObject );

Return Value

A standard HRESULT value.

Parameters

iid

[in] The identifier of the interface being requested.

ppvObject

[out] A pointer to the interface pointer identified by iid. If the object does not support this interface, ppvObject is set to NULL.

Remarks

Retrieves a pointer to the interface requested on the owner object.


CComContainedObject::Release

ULONG Release( );

Return Value

In debug builds, Release returns a value that may be useful for diagnostics or testing. In non-debug builds, Release always returns 0.

Remarks

Decrements the reference count on the owner object.

CComContainedObject Overview | Class Members

See Also CComContainedObject::AddRef


CComControl

template < class T >
class CComControl : public CComControlBase, public CWindowImpl< T >

Parameters

T

The class implementing the control.

CComControl is a set of useful control helper functions and essential data members for ATL controls. When you create a full control or an Internet Explorer control using the ATL Object Wizard, the wizard will automatically derive your class from CComControl.

For more information about creating a control, see the ATL Tutorial. For more information about the ATL Object Wizard, see the article Creating an ATL Project.

For a demonstration of CComControl methods and data members, see the CIRC sample.

#include <atlctl.h>

Class Members

See Also CWindowImpl


CComControl Class Members

CComControl class members are divided into the following categories:

  • Methods

  • CComControlBase Methods

  • GetAmbient Property Methods

  • Data Members

  • Stock Property Data Members

Methods

CcomControl | Constructor.
ControlQueryInterface | Retrieves a pointer to the requested interface.
CreateControlWindow | Creates a window for the control.
FireOnChanged | Notifies the container's sink that a control property has changed.
FireOnRequestEdit | Notifies the container's sink that a control property is about to change.

CComControlBase Methods

CcomControlBase | Constructor. Stores the window handle. Initializes the control data and sets a default control size.
DoesVerbActivate | Checks that the iVerb parameter used by IOleObjectImpl::DoVerb activates the control.
DoesVerbUIActivate | Checks that the iVerb parameter used by IOleObjectImpl::DoVerb causes the control's user interface to activate.
DoVerbProperties | Tells the control to display its property sheet.
FireViewChange | Tells the control to discard any undo the state it is maintaining.
GetDirty | Retrieves the value of the flag indicating whether the control's properties have changed since it was last saved.
GetZoomInfo | Retrieves the zoom factor and stores it in the ATL_DRAWINFO structure.
InPlaceActivate | Determines that the control can be in-place activated, informs the container the control is going in-place active, and activates the control.
OnDraw | Draws your control.
OnDrawAdvanced | Normalizes the device context, then calls your control class's OnDraw method.
OnGetDlgCode | Called in response to a WM_GETDLGCODE message. Override to have the control process TAB keys and arrow keys.
OnKillFocus | Informs the container the control has lost focus.
OnPaint | Prepares the container for painting, gets information about the control size, and calls your control class's OnDraw method.
OnSetFocus | Informs the container the control has gained focus.
SendOnClose | Called by the server to notify the control's advise sinks the control has changed from the running to the loaded state.
SendOnDataChange | Called by the server to notify the control's advise sinks that data in the control has changed.
SendOnRename | Called by the server to notify the control's advise sinks the control has been renamed.
SendOnSave | Called by the server to notify the control's advise sinks the control has been saved.
SendOnViewChange | Notifies the control's advise sinks its view has changed.
SetControlFocus | Sets or removes keyboard focus to or from the control.
SetDirty | Sets the value of the flag indicating that the control's properties have changed since it was last saved.

GetAmbient Property Methods

GetAmbientAppearance | Gets the container's APPEARANCE property.
GetAmbientAutoClip | Gets the container's AUTOCLIP property.
GetAmbientBackColor | Gets the container's BACKCOLOR property.
GetAmbientDisplayAsDefault | Gets the container's DISPLAYASDEFAULT property.
GetAmbientDisplayName | Gets the container's DISPLAYNAME property.
GetAmbientFont | Gets the container's FONT properties.
GetAmbientForeColor | Gets the container's FORECOLOR property.
GetAmbientLocaleID | Gets the container's LOCALEID property.
GetAmbientMessageReflect | Gets the container's MESSAGEREFLECT property.
GetAmbientPalette | Gets the container's PALETTE property.
GetAmbientProperty | Retrieves the specified container property.
GetAmbientScaleUnits | Gets the container's SCALEUNITS property.
GetAmbientShowGrabHandles | Gets the container's SHOWGRABHANDLES property.
GetAmbientShowHatching | Gets the container's SHOWHATCHING property.
GetAmbientSupportsMnemonics | Gets the container's SUPPORTSMNEMONICS property.
GetAmbientTextAlign | Gets the container's TEXTALIGN property.
GetAmbientUIDead | Gets the container's UIDEAD property.
GetAmbientUserMode | Gets the container's USERMODE property.

Data Members

m_bAutoSize | Flag indicating the control cannot be any other size, and SetExtent should fail.
m_bDrawFromNatural | Flag indicating that GetData should use the control's actual size and not its current extent when drawing.
m_bDrawGetDataInHimetric | Flag indicating that GetData should use HIMETRIC units and not pixels when drawing.
m_bInPlaceActive | Flag indicating the control is in-place active.
m_bInPlaceSiteEx | Flag indicating the container supports OCX96 control features, such as windowless and flicker-free controls.
m_bNegotiatedWnd | Flag indicating whether or not the control has negotiated with the container about being windowless or windowed.
m_bRecomposeOnResize | Flag indicating the control wants to recompose its presentation when the container changes the control's display size.
m_bRequiresSave | Flag indicating the control has changed since it was last saved.
m_bResizeNatural | Flag indicating the control wants to resize its natural extent (its unscaled physical size) when the container changes the control's display size.
m_bUIActive | Flag indicating the control's user interface is active.
m_bUsingWindowRgn | Flag indicating the control is using the container-supplied window region.
m_bWasOnceWindowless | Flag indicating the control has been windowless, but may or may not be windowless now.
m_bWindowOnly | Flag indicating the control should be windowed even if the container supports windowless controls.
m_bWndless | Flag indicating the control is windowless.
m_hWndCD | A reference to the window handle associated with the control.
m_nFreezeEvents | A count of the number of times the container has refused to accept events (a freeze of events) without an intervening acceptance of events (a thaw of events).
m_phWndCD | A pointer to the window handle associated with the control.
m_rcPos | The RECT position of the control.
m_sizeExtent | The SIZE of the control on a particular display in HIMETRIC units (each logical unit is 0.01 millimeter). This size is scaled by the display.
m_sizeNatural | The fixed physical SIZE of the control in HIMETRIC units (each logical unit is 0.01 millimeter). This size is not scaled by the display.
m_spAdviseSink | A COM interface pointer of type IAdviseSink.
m_spAmbientDispatch | A CcomDispatchDriver object used to set and get properties through IDispatch.
m_spClientSite | A COM interface pointer of type IOleClientSite.
m_spDataAdviseHolder | A COM interface pointer of type IDataAdviseHolder.
m_spInPlaceSite | A pointer to the container's IOleInPlaceSite, IoleInPlaceSiteEX, or IOleInPlaceSiteWindowless COM interface.
m_spOleAdviseHolder | A COM interface pointer of type IOleAdviseHolder.

Stock Property Data Members

m_bAutoSize | Stores the AUTOSIZE stock property.
m_bBorderVisible | Stores the BORDERVISIBLE stock property.
m_bEnabled | Stores the ENABLED stock property.
m_bstrCaption | Stores the CAPTION stock property.
m_bstrText | Stores the TEXT stock property.
m_bTabStop | Stores the TABSTOP stock property.
m_bValid | Stores the VALID stock property.
m_clrBackColor | Stores the BACKCOLOR stock property.
m_clrBorderColor | Stores the BORDERCOLOR stock property.
m_clrFillColor | Stores the FILLCOLOR stock property.
m_clrForeColor | Stores the FORECOLOR stock property.
m_nAppearance | Stores the APPEARANCE stock property.
m_nBackStyle | Stores the BACKSTYLE stock property.
m_nBorderStyle | Stores the BORDERSTYLE stock property.
m_nBorderWidth | Stores the BORDERWIDTH stock property.
m_nDrawMode | Stores the DRAWMODE stock property.
m_nDrawStyle | Stores the DRAWSTYLE stock property.
m_nDrawWidth | Stores the DRAWWIDTH stock property.
m_nFillStyle | Stores the FILLSTYLE stock property.
m_nMousePointer | Stores the MOUSEPOINTER stock property.
m_nReadyState | Stores the READYSTATE stock property.
m_pFont | Stores the FONT stock property.
m_pMouseIcon | Stores the MOUSEICON stock property.
m_pPicture | Stores the PICTURE stock property.

CComControl Overview


CComControl::CComControl

CComControl( );

Remarks

The constructor. Calls the CComControlBase constructor, passing the m_hWnd data member inherited through CWindowImpl.

CComControl Overview | Class Members

See Also CComControl::CComControlBase, CWindow::m_hWnd


CComControl::CComControlBase

CComControlBase( HWND h );

Parameters

h [in] The handle to the window associated with the control.

Remarks

The constructor. Stores a pointer to the window handle in the data member m_phWndCD. Initializes the control size to 5080X5080 HIMETRIC units (2"X2") and initializes the CComControlBase data member values to NULL or FALSE.

CComControl Overview | Class Members

See Also CComControl::m_sizeExtent, CComControl::m_phWndCD


CComControl::ControlQueryInterface

virtual HRESULT ControlQueryInterface( const IID& iid, void** ppv );

Parameters

iid

[in] The GUID of the interface being requested.

ppv

[out] A pointer to the interface pointer identified by iid, or NULL if the interface is not found.

Remarks

Retrieves a pointer to the requested interface. Only handles interfaces in the COM map table.

CComControl Overview | Class Members

See Also CComObjectRootEx::InternalQueryInterface


CComControl::CreateControlWindow

virtual HWND CreateControlWindow( HWND hWndParent, RECT& rcPos );

Parameters

hWndParent

[in] Handle to the parent or owner window. A valid window handle must be supplied. The control window is confined to the area of its parent window.

rcPos

[in] The initial size and position of the window to be created.

Remarks

By default, creates a window for the control by calling CWindowImpl::Create. Override this method if you want to do something other than create a single window, for example, to create two windows, one of which becomes a toolbar for your control.

CComControl Overview | Class Members

See Also CWindowImpl::Create


CComControl::DoesVerbActivate

BOOL DoesVerbActivate( LONG iVerb );

Return Value

Returns TRUE if iVerb equals OLEIVERB_UIACTIVATE, OLEIVERB_PRIMARY, OLEIVERB_SHOW, or OLEIVERB_INPLACEACTIVATE; otherwise, returns FALSE.

Parameters

iVerb

[in] Value indicating the action to be performed by DoVerb.

Remarks

Checks that the iVerb parameter used by IOleObjectImpl::DoVerb either activates the control's user interface (iVerb equals OLEIVERB_UIACTIVATE), defines the action taken when the user double-clicks the control (iVerb equals OLEIVERB_PRIMARY), displays the control (iVerb equals OLEIVERB_SHOW), or activates the control (iVerb equals OLEIVERB_INPLACEACTIVATE). You can override this method to define your own activation verb.

CComControl Overview | Class Members

See Also IOleObjectImpl::DoVerb, CComControl::DoesVerbUIActivate


CComControl::DoesVerbUIActivate

BOOL DoesVerbUIActivate( LONG iVerb );

Return Value

Returns TRUE if iVerb equals OLEIVERB_UIACTIVATE or OLEIVERB_PRIMARY. Also returns TRUE if the control is not active and iVerb equals OLEIVERB_UIACTIVATE, OLEIVERB_PRIMARY, OLEIVERB_SHOW, or OLEIVERB_INPLACEACTIVATE. Otherwise, the method returns FALSE.

Parameters

iVerb

[in] Value indicating the action to be performed by DoVerb.

Remarks

Checks that the iVerb parameter used by IOleObjectImpl::DoVerb causes the control's user interface to activate and returns TRUE.

DoesVerbUIActivate also checks whether the control is in-place active. If it is not and the value of iVerb causes the control to go active, DoesVerbUIActivate returns TRUE. This handles older containers that must activate the control and its user interface together.

CComControl Overview | Class Members

See Also IOleObjectImpl::DoVerb, CComControl::DoesVerbActivate


CComControl::DoVerbProperties

HRESULT DoVerbProperties( LPCRECT prcPosRect, HWND hwndParent );

Return Value

One of the standard HRESULT values.

Parameters

prcPosRec

[in] Pointer to the rectangle the container wants the control to draw into.

hwndParent

[in] Handle of the window containing the control. Not used in the ATL implementation.

Remarks

Displays the control's property pages. By default, this is set as the action taken when the user double-clicks the control. You can change this to another action by overriding IOleObjectImpl::DoVerbPrimary.

CComControl Overview | Class Members

See Also IOleObjectImpl::DoVerbPrimary


CComControl::FireOnChanged

HRESULT FireOnChanged( DISPID dispID );

Return Value

One of the standard HRESULT values.

Parameters

dispID

[in] Identifier of the property that has changed.

Remarks

If your control class derives from IPropertyNotifySink, this method calls CFirePropNotifyEvent::FireOnChanged to notify all connected IPropertyNotifySink interfaces that the specified control property has changed. If your control class does not derive from IPropertyNotifySink, this method returns S_OK.

This function is safe to call even if your control doesn't support connection points.

CComControl Overview | Class Members

See Also CComControl::FireOnRequestEdit


CComControl::FireOnRequestEdit

HRESULT FireOnRequestEdit( DISPID dispID );

Return Value

One of the standard HRESULT values.

Parameters

dispID

[in] Identifier of the property about to change.

Remarks

If your control class derives from IPropertyNotifySink, this method calls CFirePropNotifyEvent::FireOnRequestEdit to notify all connected IPropertyNotifySink interfaces that the specified control property is about to change. If your control class does not derive from IPropertyNotifySink, this method returns S_OK.

This function is safe to call even if your control doesn't support connection points.

CComControl Overview | Class Members

See Also CComControl::FireOnChanged


CComControl::FireViewChange

HRESULT FireViewChange( );

Return Value

One of the standard HRESULT values.

Remarks

If the control is active (the control class data member m_bInPlaceActive is TRUE), notifies the container that you want to redraw the entire control. If the control is inactive, notifies the control's registered advise sinks (through the control class data member m_spAdviseSink) that the control's view has changed.


CComControl::GetAmbientAppearance

HRESULT GetAmbientAppearance( short& nAppearance);

Return Value

One of the standard HRESULT values.

Parameters

nAppearance

[out] The property DISPID_AMBIENT_APPEARANCE.

Remarks

Retrieves DISPID_AMBIENT_APPEARANCE, the current appearance setting for the control: 0 for flat and 1 for 3D.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientAutoClip

HRESULT GetAmbientAutoClip( BOOL& bAutoClip );

Return Value

One of the standard HRESULT values.

Parameters

bAutoClip

[out] The property DISPID_AMBIENT_AUTOCLIP.

Remarks

Retrieves DISPID_AMBIENT_AUTOCLIP, a flag indicating whether the container supports automatic clipping of the control display area.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientBackColor

HRESULT GetAmbientBackColor( OLE_COLOR& BackColor );

Return Value

One of the standard HRESULT values.

Parameters

BackColor

[out] The property DISPID_AMBIENT_BACKCOLOR.

Remarks

Retrieves DISPID_AMBIENT_BACKCOLOR, the ambient background color for all controls, defined by the container.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientDisplayAsDefault

HRESULT GetAmbientDisplayAsDefault( BOOL& bDisplayAsDefault );

Return Value

One of the standard HRESULT values.

Parameters

bDisplayAsDefault

[out] The property DISPID_AMBIENT_DISPLAYASDEFAULT.

Remarks

Retrieves DISPID_AMBIENT_DISPLAYASDEFAULT, a flag that is TRUE if the container has marked the control in this site to be a default button, and therefore a button control should draw itself with a thicker frame.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientDisplayName

HRESULT GetAmbientDisplayName( BSTR& bstrDisplayName );

Return Value

One of the standard HRESULT values.

Parameters

bstrDisplayName

[out] The property DISPID_AMBIENT_DISPLAYNAME.

Remarks

Retrieves DISPID_AMBIENT_DISPLAYNAME, the name the container has supplied to the control.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientFont

HRESULT GetAmbientFont( IFont** ppFont );

Return Value

One of the standard HRESULT values.

Parameters

ppFont

[out] The property DISPID_AMBIENT_FONT.

Remarks

Retrieves DISPID_AMBIENT_FONT, a pointer to the container's ambient IFont dispatch interface. If the property is NULL, the pointer is NULL. If the pointer is not NULL, the caller must release the pointer.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientForeColor

HRESULT GetAmbientForeColor( OLE_COLOR& ForeColor );

Return Value

One of the standard HRESULT values.

Parameters

ForeColor

[out] The property DISPID_AMBIENT_FORECOLOR.

Remarks

Retrieves DISPID_AMBIENT_FORECOLOR, the ambient foreground color for all controls, defined by the container.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientLocaleID

HRESULT GetAmbientLocaleID( LCID& lcid );

Return Value

One of the standard HRESULT values.

Parameters

lcid

[out] The property DISPID_AMBIENT_LOCALEID.

Remarks

Retrieves DISPID_AMBIENT_LOCALEID, the identifier of the language used by the container. The control can use this identifier to adapt its user interface to different languages.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientMessageReflect

HRESULT GetAmbientMessageReflect( BOOL& bMessageReflect );

Return Value

One of the standard HRESULT values.

Parameters

bMessageReflect

[out] The property DISPID_AMBIENT_MESSAGEREFLECT.

Remarks

Retrieves DISPID_AMBIENT_MESSAGEREFLECT, a flag indicating whether the container wants to receive window messages (such as WM_DRAWITEM) as events.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientPalette

HRESULT GetAmbientPalette( HPALETTE& hPalette );

Return Value

One of the standard HRESULT values.

Parameters

hPalette

[out] The property DISPID_AMBIENT_PALETTE.

Remarks

Retrieves DISPID_AMBIENT_PALETTE, used to access the container's HPALETTE.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientProperty

HRESULT GetAmbientProperty( DISPID dispid, VARIANT& var );

Return Value

One of the standard HRESULT values.

Parameters

dispid

[in] Identifier of the container property to be retrieved.

var

[in] Variable to receive the property.

Remarks

Retrieves the container property specified by id.

ATL has provided a set of helper functions to retrieve specific properties, for example, GetAmbientBackColor. These functions retrieve specific properties.

CComControl Overview | Class Members

See Also CComControl::m_spClientSite, GetAmbient Property Methods


CComControl::GetAmbientScaleUnits

HRESULT GetAmbientScaleUnits( BSTR& bstrScaleUnits );

Return Value

One of the standard HRESULT values.

Parameters

bstrScaleUnits

[out] The property DISPID_AMBIENT_SCALEUNITS.

Remarks

Retrieves DISPID_AMBIENT_SCALEUNITS, the container's ambient units (such as inches or centimeters) for labeling displays.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientShowGrabHandles

HRESULT GetAmbientShowGrabHandles( BOOL& bShowGrabHandles );

Return Value

One of the standard HRESULT values.

Parameters

bShowGrabHandles

[out] The property DISPID_AMBIENT_SHOWGRABHANDLES.

Remarks

Retrieves DISPID_AMBIENT_SHOWGRABHANDLES, a flag indicating whether the container allows the control to display grab handles for itself when active.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientShowHatching

HRESULT GetAmbientShowHatching( BOOL& bShowHatching );

Return Value

One of the standard HRESULT values.

Parameters

bShowHatching

[out] The property DISPID_AMBIENT_SHOWHATCHING.

Remarks

Retrieves DISPID_AMBIENT_SHOWHATCHING, a flag indicating whether the container allows the control to display itself with a hatched pattern when UI active.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientSupportsMnemonics

HRESULT GetAmbientSupportsMnemonics( BOOL& bSupportsMnemonics );

Return Value

One of the standard HRESULT values.

Parameters

bSupportsMnemonics

[out] The property DISPID_AMBIENT_SUPPORTSMNEMONICS.

Remarks

Retrieves DISPID_AMBIENT_SUPPORTSMNEMONICS, a flag indicating whether the container supports keyboard mnemonics.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientTextAlign

HRESULT GetAmbientTextAlign( short& nTextAlign );

Return Value

One of the standard HRESULT values.

Parameters

nTextAlign

[out] The property DISPID_AMBIENT_TEXTALIGN.

Remarks

Retrieves DISPID_AMBIENT_TEXTALIGN, the text alignment preferred by the container: 0 for general alignment (numbers right, text left), 1 for left alignment, 2 for center alignment, and 3 for right alignment.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientUIDead

HRESULT GetAmbientUIDead( BOOL& bUIDead );

Return Value

One of the standard HRESULT values.

Parameters

bUIDead

[out] The property DISPID_AMBIENT_UIDEAD.

Remarks

Retrieves DISPID_AMBIENT_UIDEAD, a flag indicating whether the container wants the control to respond to user-interface actions. If TRUE, the control should not respond. This flag applies regardless of the DISPID_AMBIENT_USERMODE flag.

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetAmbientUserMode

HRESULT GetAmbientUserMode( BOOL& bUserMode );

Return Value

One of the standard HRESULT values.

Parameters

bUserMode

[out] The property DISPID_AMBIENT_USERMODE.

Remarks

Retrieves DISPID_AMBIENT_USERMODE, a flag indicating whether the container is in run-mode (TRUE) or design-mode (FALSE).

CComControl Overview | Class Members

See Also GetAmbient Property Methods


CComControl::GetDirty

BOOL GetDirty( );

Return Value

Returns the value of data member m_bRequiresSave.

Remarks

Returns the value of data member m_bRequiresSave. This value is set in SetDirty.

CComControl Overview | Class Members

See Also CComControl::SetDirty


CComControl::GetZoomInfo

void GetZoomInfo( ATL_DRAWINFO& di );

Parameters

di

[out] The structure that will hold the zoom factor's numerator and denominator.

Remarks

Retrieves the x and y values of the numerator and denominator of the zoom factor for a control activated for in-place editing. The zoom factor is the proportion of the control's natural size to its current extent.

CComControl Overview | Class Members

See Also CComControl::m_sizeNatural, CComControl::m_sizeExtent


CComControl::InPlaceActivate

HRESULT InPlaceActivate( LONG iVerb, const RECT* prcPosRect = NULL );

Return Value

One of the standard HRESULT values.

Parameters

iVerb

[in] Value indicating the action to be performed by IOleObjectImpl::DoVerb.

prcPosRect

[in] Pointer to the position of the in-place control.

Remarks

Causes the control to transition from the inactive state to whatever state the verb in iVerb indicates. Before activation, this method checks that the control has a client site, checks how much of the control is visible, and gets the control's location in the parent window. After the control is activated, this method activates the control's user interface and tells the container to make the control visible.

This function also retrieves an IOleInPlaceSite, IOleInPlaceSiteEx, or IOleInPlaceSiteWindowless interface pointer for the control and stores it in the control class's data member m_spInPlaceSite. The control class data members m_bInPlaceSiteEx, m_bWndless, m_bWasOnceWindowless, and m_bNegotiatedWnd are set to TRUE as appropriate.

CComControl Overview | Class Members

See Also IOleInPlaceObjectWindowlessImpl::InPlaceDeactivate


CComControl::OnDraw

virtual HRESULT OnDraw( ATL_DRAWINFO& di );

Return Value

A standard HRESULT value.

Parameters

di

[in] A reference to the ATL_DRAWINFO structure that contains drawing information such as the draw aspect, the control bounds, and whether the drawing is optimized or not.

Remarks

Override this method to draw your control.

The default OnDraw deletes or restores the device context or does nothing, depending on flags set in OnDrawAdvanced.

An OnDraw method is automatically added to your control class when you create your control with the ATL Object Wizard. The wizard's default OnDraw draws a rectangle with the label "ATL 2.0".

CComControl Overview | Class Members

See Also CComControl::OnDrawAdvanced, IViewObjectExImpl::Draw


CComControl::OnDrawAdvanced

virtual HRESULT OnDrawAdvanced( ATL_DRAWINFO& di );

Return Value

A standard HRESULT value.

Parameters

di

[in] A reference to the ATL_DRAWINFO structure that contains drawing information such as the draw aspect, the control bounds, and whether the drawing is optimized or not.

Remarks

The default OnDrawAdvanced prepares a normalized device context for drawing, then calls your control class's OnDraw method. Override this method if you want to accept the device context passed by the container without normalizing it.

An OnDraw method is automatically added to your control class when you create your control with the ATL Object Wizard. The wizard's default OnDraw draws a rectangle with the label "ATL 2.0".

CComControl Overview | Class Members

See Also CComControl::OnDraw, IViewObjectExImpl::Draw


CComControl::OnGetDlgCode

LRESULT OnGetDlgCode( UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled );

Return Value

The result of message processing. 0 if successful.

Parameters

nMsg

[in] The window message identifier. Not used in the default ATL implementation.

wParam

[in] A 32-bit message parameter. Not used in the default ATL implementation.

lParam

[in] A 32-bit message parameter. Not used in the default ATL implementation.

bHandled

[in, out] Flag that indicates whether the window message was successfully handled. The default is TRUE.

Remarks

Called in response to a WM_GETDLGCODE window message. The message is sent to the dialog box associated with the control. Override this method to let the control process the input of arrow keys and TAB keys. The default ATL implementation simply returns 0.

CComControl Overview | Class Members

See Also WM_GETDLGCODE


CComControl::OnKillFocus

LRESULT OnKillFocus( UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled );

Return Value

Always returns 0.

Parameters

nMsg

[in] The window message identifier. Not used in the default ATL implementation.

wParam

[in] A 32-bit message parameter. Not used in the default ATL implementation.

lParam

[in] A 32-bit message parameter. Not used in the default ATL implementation.

bHandled

[in, out] Flag that indicates whether the window message was successfully handled. The default is TRUE.

Remarks

Checks that the control is in-place active and has a valid control site, then informs the container the control has lost focus.

CComControl Overview | Class Members

See Also CComControl::m_bInPlaceActive, CComControl::m_spClientSite


CComControl::OnPaint

LRESULT OnPaint( UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL& lResult );

Return Value

Returns zero.

Parameters

nMsg

[in] Specifies the message. Not used in the default ATL implementation.

wParam

[in] Additional message-specific information. Not used in the default ATL implementation.

lParam

[in] Additional message-specific information. Not used in the default ATL implementation.

lResult

[in, out] A boolean value. Not used in the default ATL implementation. See MESSAGE_HANDLER for more information.

Remarks

Prepares the container for painting, gets the control's client area, then calls the control class's OnDraw method.

An OnDraw method is automatically added to your control class when you create your control with the ATL Object Wizard. The wizard's default OnDraw draws a rectangle with the label "ATL 2.0".

CComControl Overview | Class Members

See Also BeginPaint, EndPaint, IViewObjectExImpl::Draw


CComControl::OnSetFocus

LRESULT OnSetFocus( UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled );

Return Value

Always returns 0.

Parameters

nMsg

[in] The window message identifier. Not used in the default ATL implementation.

wParam

[in] A 32-bit message parameter. Not used in the default ATL implementation.

lParam

[in] A 32-bit message parameter. Not used in the default ATL implementation.

bHandled

[in, out] Flag that indicates whether the window message was successfully handled. The default is TRUE.

Remarks

Checks that the control is in-place active and has a valid control site, then informs the container the control has gained focus.

CComControl Overview | Class Members

See Also CComControl::m_bInPlaceActive, CComControl::m_spClientSite


CComControl::SendOnClose

HRESULT SendOnClose( );

Return Value

One of the standard HRESULT values.

Remarks

Notifies all advisory sinks registered with the advise holder that the control has been closed.

CComControl Overview | Class Members

See Also CComControl::m_spOleAdviseHolder


CComControl::SendOnDataChange

HRESULT SendOnDataChange( DWORD advf = 0);

Return Value

One of the standard HRESULT values.

Parameters

advf

[in] Advise flags that specify how the call to IAdviseSink::OnDataChange is made. Values are from the ADVF enumeration.

Remarks

Notifies all advisory sinks registered with the advise holder that the control data has changed.

CComControl Overview | Class Members

See Also CComControl::m_spDataAdviseHolder


CComControl::SendOnRename

HRESULT SendOnRename( IMoniker* pmk );

Return Value

One of the standard HRESULT values.

Parameters

pmk

[in] Pointer to the new moniker of the control.

Remarks

Notifies all advisory sinks registered with the advise holder that the control has a new moniker.

CComControl Overview | Class Members

See Also CComControl::m_spOleAdviseHolder


CComControl::SendOnSave

HRESULT SendOnSave( );

Return Value

One of the standard HRESULT values.

Remarks

Notifies all advisory sinks registered with the advise holder that the control has been saved.

CComControl Overview | Class Members

See Also CComControl::m_spOleAdviseHolder


CComControl::SendOnViewChange

HRESULT SendOnViewChange( DWORD dwAspect, LONG lindex = -1 );

Return Value

One of the standard HRESULT values.

Parameters

dwAspect

[in] The aspect or view of the control.

lindex

[in] The portion of the view that has changed. Only -1 is valid.

Remarks

Notifies all registered advisory sinks that the control's view has changed.

CComControl Overview | Class Members

See Also CComControl::m_spAdviseSink


CComControl::SetControlFocus

BOOL SetControlFocus( BOOL bGrab );

Return Value

Returns TRUE if the control successfully receives focus; otherwise, FALSE.

Parameters

bGrab

[in] If TRUE, sets the keyboard focus to the calling control. If FALSE, removes the keyboard focus from the calling control, provided it has the focus.

Remarks

Sets or removes the keyboard focus to or from the control. For a windowed control, the Windows API function SetFocus is called. For a windowless control, IOleInPlaceSiteWindowless::SetFocus is called. Through this call, a windowless control obtains the keyboard focus and can respond to window messages.


CComControl::SetDirty

void SetDirty( BOOL bDirty );

Parameters

bDirty

[in] Value of the data member m_bRequiresSave.

Remarks

Sets the data member m_bRequiresSave to the value in bDirty. You should call SetDirty(TRUE) to flag that the control has changed since it was last saved. The value of m_bRequiresSave is retrieved with GetDirty.


CComControl::m_bAutoSize

unsigned m_bAutoSize:1;

Remarks

Flag indicating the control cannot be any other size. This flag is checked by IOleObjectImpl::SetExtent and, if TRUE, causes the function to return E_FAIL.

If you choose the AUTOSIZE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also IOleObjectImpl::SetExtent


CComControl::m_bBorderVisible

BOOL m_bBorderVisible;

Remarks

The data member in your control class that flags whether the control's border should be visible or not. If you choose the BORDERVISIBLE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_nBorderStyle, CComControl::m_clrBorderColor, CComControl::m_nBorderWidth


CComControl::m_bDrawFromNatural

unsigned m_bDrawFromNatural:1;

Remarks

Flag indicating that IDataObjectImpl::GetData should set the control size from m_sizeNatural rather than from m_sizeExtent.

CComControl Overview | Class Members

See Also IDataObjectImpl::GetData, CComControl::m_sizeNatural, CComControl::m_sizeExtent


CComControl::m_bDrawGetDataInHimetric

unsigned m_bDrawGetDataInHimetric:1;

Remarks

Flag indicating that IDataObjectImpl::GetData should use HIMETRIC units and not pixels when drawing. Each logical HIMETRIC unit is 0.01 millimeter.

CComControl Overview | Class Members

See Also IDataObjectImpl::GetData


CComControl::m_bEnabled

BOOL m_bEnabled;

Remarks

The data member in your control class that flags whether the control is enabled. The m_bInPlaceActive flag indicates the control is in-place active, while the m_bUIActive flag indicates the control's user interface (menus and toolbars) is also active.

If you choose the ENABLED option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.


CComControl::m_bInPlaceActive

unsigned m_bInPlaceActive:1;

Remarks

Flag indicating the control is in-place active. This means the control is visible and its window, if any, is visible, but its menus and toolbars may not be active. The m_bUIActive flag indicates the control's user interface, such as menus, is also active.

CComControl Overview | Class Members

See Also CComControl::m_bEnabled, CComControl::m_bUIActive


CComControl::m_bInPlaceSiteEx

unsigned m_bInPlaceSiteEx:1;

Remarks

Flag indicating the container supports the IOleInPlaceSiteEx interface and OCX96 control features, such as windowless and flicker-free controls.

The data member m_spInPlaceSite points to an IOleInPlaceSite, IOleInPlaceSiteEx, or IOleInPlaceSiteWindowless interface, depending on the value of the m_bWndless and m_bInPlaceSiteEx flags. (The data member m_bNegotiatedWnd must be TRUE for the m_spInPlaceSite pointer to be valid.)

If m_bWndless is FALSE and m_bInPlaceSiteEx is TRUE, m_spInPlaceSite is an IOleInPlaceSiteEx interface pointer. See m_spInPlaceSite for a table showing the relationship among these three data members.

CComControl Overview | Class Members

See Also CComControl::m_bWndless, CComControl::m_bNegotiatedWnd, CComControl::m_spInPlaceSite


CComControl::m_bNegotiatedWnd

unsigned m_bNegotiatedWnd:1;

Remarks

Flag indicating whether or not the control has negotiated with the container about support for OCX96 control features (such as flicker-free and windowless controls), and whether the control is windowed or windowless. The m_bNegotiatedWnd flag must be TRUE for the m_spInPlaceSite pointer to be valid.

CComControl Overview | Class Members

See Also CComControl::m_bWndless, CComControl::m_spInPlaceSite


CComControl::m_bRecomposeOnResize

unsigned m_bRecomposeOnResize:1;

Remarks

Flag indicating the control wants to recompose its presentation when the container changes the control's display size. This flag is checked by IOleObjectImpl::SetExtent and, if TRUE, SetExtent notifies the container of view changes. if this flag is set, the OLEMISC_RECOMPOSEONRESIZE bit in the OLEMISC enumeration should also be set.

CComControl Overview | Class Members

See Also IOleObjectImpl::SetExtent


CComControl::m_bRequiresSave

unsigned m_bRequiresSave:1;

Remarks

Flag indicating the control has changed since it was last saved. The value of m_bRequiresSave can be set with SetDirty and retrieved with GetDirty.

CComControl Overview | Class Members

See Also CComControl::SetDirty, CComControl::GetDirty


CComControl::m_bResizeNatural

unsigned m_bResizeNatural:1;

Remarks

Flag indicating the control wants to resize its natural extent (its unscaled physical size) when the container changes the control's display size. This flag is checked by IOleObjectImpl::SetExtent and, if TRUE, the size passed into SetExtent is assigned to m_sizeNatural.

The size passed into SetExtent is always assigned to m_sizeExtent, regardless of the value of m_bResizeNatural.

CComControl Overview | Class Members

See Also IOleObjectImpl::SetExtent, CComControl::m_sizeNatural, CComControl::m_sizeExtent


CComControl::m_bstrCaption

BSTR m_bstrCaption;

Remarks

The data member in your control class that holds text to be displayed with the control. If you choose the CAPTION option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_bstrText


CComControl::m_bstrText

BSTR m_bstrCaption;

Remarks

The data member in your control class that holds text to be displayed with the control. If you choose the TEXT option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_bstrCaption


CComControl::m_bTabStop

BOOL m_bTabStop;

Remarks

The data member in your control class that flags whether the control is a tab stop or not. If you choose the TABSTOP option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.


CComControl::m_bUIActive

unsigned m_bUIActive:1;

Remarks

Flag indicating the control's user interface, such as menus and toolbars, is active. The m_bInPlaceActive flag indicates that the control is active, but not that its user interface is active.

CComControl Overview | Class Members

See Also CComControl::m_bEnabled, CComControl::m_bInPlaceActive


CComControl::m_bUsingWindowRgn

unsigned m_bUsingWindowRgn:1;

Remarks

Flag indicating the control is using the container-supplied window region.


CComControl::m_bValid

BOOL m_bValid;

Remarks

The data member in your control class that flags whether the control is a valid or not. If you choose the VALID option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.


CComControl::m_bWasOnceWindowless

unsigned m_bWasOnceWindowless:1;

Remarks

Flag indicating the control has been windowless, but may or may not be windowless now.

CComControl Overview | Class Members

See Also CComControl::m_bWndless


CComControl::m_bWindowOnly

unsigned m_bWindowOnly:1;

Remarks

Flag indicating the control should be windowed, even if the container supports windowless controls.

CComControl Overview | Class Members

See Also CComControl::m_bWndless


CComControl::m_bWndless

unsigned m_bWndless:1;

Remarks

Flag indicating the control is windowless.

The data member m_spInPlaceSite points to an IOleInPlaceSite, IOleInPlaceSiteEx, or IOleInPlaceSiteWindowless interface, depending on the value of the m_bWndless and m_bInPlaceSiteEx flags. (The data member m_bNegotiatedWnd must be TRUE for the m_spInPlaceSite pointer to be valid.)

If m_bWndless is TRUE, m_spInPlaceSite is an IOleInPlaceSiteWindowless interface pointer. See m_spInPlaceSite for a table showing the complete relationship between these data members.

CComControl Overview | Class Members

See Also CComControl::m_spInPlaceSite, CComControl::m_bInPlaceSiteEx, CComControl::m_bNegotiatedWnd, CComControl::m_bWindowOnly, CComControl::m_bWasOnceWindowless


CComControl::m_clrBackColor

OLE_COLOR m_clrBackColor;

Remarks

The data member in your control class that holds the control's background color. If you choose the BACKCOLOR option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_clrBorderColor, CComControl::m_clrFillColor, CComControl::m_clrForeColor


CComControl::m_clrBorderColor

OLE_COLOR m_clrBorderColor;

Remarks

The data member in your control class that holds the control's border color. If you choose the BORDERCOLOR option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_clrBackColor, CComControl::m_clrFillColor, CComControl::m_clrForeColor


CComControl::m_clrFillColor

OLE_COLOR m_clrFillColor;

Remarks

The data member in your control class that holds the control's fill color. If you choose the FILLCOLOR option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_clrBackColor, CComControl::m_clrBorderColor, CComControl::m_clrForeColor


CComControl::m_clrForeColor

OLE_COLOR m_clrForeColor;

Remarks

The data member in your control class that holds the control's foreground color. If you choose the FORECOLOR option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_clrBackColor, CComControl::m_clrBorderColor, CComControl::m_clrFillColor


CComControl::m_hWndCD

HWND& m_hWndCD;

Remarks

Contains a reference to the window handle associated with the control. Part of a union with m_phWndCD.

CComControl Overview | Class Members

See Also CComControl::CComControl, CComControl::m_phWndCD


CComControl::m_nAppearance

long m_nAppearance;

Remarks

The data member in your control class that stores the paint style used by the control, for example, flat or 3D. If you choose the APPEARANCE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_nDrawMode


CComControl::m_nBackStyle

long m_nBackStyle;

Remarks

The data member in your control class that stores the control's background style, either transparent or opaque. If you choose the BACKSTYLE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_nFillStyle


CComControl::m_nBorderStyle

long m_nBorderStyle;

Remarks

The data member in your control class that stores the control's border style. If you choose the BORDERSTYLE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_bBorderVisible, CComControl::m_clrBorderColor, CComControl::m_nBorderWidth


CComControl::m_nBorderWidth

long m_nBorderWidth;

Remarks

The data member in your control class that stores the control's border width. If you choose the BORDERWIDTH option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_bBorderVisible, CComControl::m_clrBorderColor, CComControl::m_nBorderStyle


CComControl::m_nDrawMode

long m_nDrawMode;

Remarks

The data member in your control class that stores the appearance of output from the control's graphics methods, for example, XOR Pen or Invert Colors. If you choose the DRAWMODE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_nDrawWidth, CComControl::m_nDrawStyle


CComControl::m_nDrawStyle

long m_nDrawStyle;

Remarks

The data member in your control class that stores the line style used by the control's drawing methods, for example, solid, dashed, or dotted. If you choose the DRAWSTYLE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_nDrawWidth, CComControl::m_nDrawMode


CComControl::m_nDrawWidth

long m_nDrawWidth;

Remarks

The data member in your control class that stores the line width (in pixels) used by the control's drawing methods. If you choose the DRAWWIDTH option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_nDrawStyle, CComControl::m_nDrawMode


CComControl::m_nFillStyle

long m_nFillStyle;

Remarks

The data member in your control class that stores the control's fill style, for example, solid, transparent, or cross-hatched. If you choose the FILLSTYLE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_nBackStyle


CComControl::m_nFreezeEvents

short m_nFreezeEvents;

Remarks

A count of the number of times the container has frozen events (refused to accept events) without an intervening thaw of events (acceptance of events).

CComControl Overview | Class Members

See Also IOleControl::FreezeEvents


CComControl::m_nMousePointer

long m_nMousePointer;

Remarks

The data member in your control class that stores the type of mouse pointer displayed when the mouse is over the control, for example, arrow, cross, or hourglass. If you choose the MOUSEPOINTER option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_pMouseIcon


CComControl::m_nReadyState

long m_nReadyState;

Remarks

The data member in your control class that stores the control's readiness state, for example, loading or loaded. If you choose the READYSTATE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.


CComControl::m_pFont

IFontDisp* m_pFont;

Remarks

The data member in your control class that stores a pointer to IFontDisp font properties. If you choose the FONT option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.


CComControl::m_phWndCD

HWND* m_phWndCD;

Remarks

Contains a pointer to the window handle associated with the control. Initialized in the CComControl constructor. Part of a union with m_hWndCD.

CComControl Overview | Class Members

See Also CComControl::CComControl, CComControl::m_hWndCD


CComControl::m_pMouseIcon

IPictureDisp* m_pMouseIcon;

Remarks

The data member that stores a pointer to IPictureDisp picture properties of the graphic (icon, bitmap, or metafile) to be displayed when the mouse is over the control. The properties include the handle of the picture. If you choose the MOUSEICON option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_nMousePointer


CComControl::m_pPicture

IPictureDisp* m_pPicture;

Remarks

The data member that stores a pointer to IPictureDisp picture properties of a graphic (icon, bitmap, or metafile) to be displayed. The properties include the handle of the picture. If you choose the PICTURE option from the Stock Properties tab in the ATL Object Wizard, the wizard automatically creates this data member in your control class, creates put and get methods for the property, and supports IPropertyNotifySink to automatically notify the container when the property changes.

CComControl Overview | Class Members

See Also CComControl::m_pMouseIcon


CComControl::m_rcPos

RECT m_rcPos;

Remarks

The position in pixels of the control, expressed in the coordinates of the container.

CComControl Overview | Class Members

See Also CComControl::m_sizeExtent, CComControl::m_sizeNatural, RECT


CComControl::m_sizeExtent

SIZE m_sizeExtent;

Remarks

The extent of the control in HIMETRIC units (each unit is 0.01 millimeters) for a particular display. This size is scaled by the display. The control's physical size is specified in the m_sizeNatural data member and is fixed.

You can convert the size to pixels with the global function AtlHiMetricToPixel.

CComControl Overview | Class Members

See Also CComControl::m_sizeNatural, CComControl::m_rcPos, SIZE


CComControl::m_sizeNatural

SIZE m_sizeNatural;

Remarks

The physical size of the control in HIMETRIC units (each unit is 0.01 millimeters). This size is fixed, while the size in m_sizeExtent is scaled by the display.

You can convert the size to pixels with the global function AtlHiMetricToPixel.

CComControl Overview | Class Members

See Also CComControl::m_sizeExtent, CComControl::m_rcPos, SIZE


CComControl::m_spAdviseSink

CComPtr<IAdviseSink> m_spAdviseSink;

Remarks

A direct pointer to the advisory connection on the container (the container's IAdviseSink).

CComControl Overview | Class Members

See Also CComPtr


CComControl::m_spAmbientDispatch

CComDispatchDriver m_spAmbientDispatch;

Remarks

A CComDispatchDriver object that lets you retrieve and set an object's properties through an IDispatch pointer.

CComControl Overview | Class Members

See Also CComDispatchDriver


CComControl::m_spClientSite

CComPtr<IOleClientSite> m_spClientSite;

Remarks

A pointer to the control's client site within the container.

CComControl Overview | Class Members

See Also CComPtr, IOleClientSite


CComControl::m_spDataAdviseHolder

CComPtr<IDataAdviseHolder> m_spDataAdviseHolder;

Remarks

Provides a standard means to hold advisory connections between data objects and advise sinks. (A data object is a control that can transfer data and that implements IDataObject, whose methods specify the format and transfer medium of the data.)

The interface m_spDataAdviseHolder implements the IDataObject::DAdvise and IDataObject::DUnadvise methods to establish and delete advisory connections to the container. The control's container must implement an advise sink by supporting the IAdviseSink interface.

CComControl Overview | Class Members

See Also CComPtr


CComControl::m_spInPlaceSite

CComPtr<IOleInPlaceSiteWindowless> m_spInPlaceSite;

Remarks

A pointer to the container's IOleInPlaceSite, IOleInPlaceSiteEx, or IOleInPlaceSiteWindowless interface pointer.

The m_spInPlaceSite pointer is valid only if the m_bNegotiatedWnd flag is TRUE.

The following table shows how the m_spInPlaceSite pointer type depends on the m_bWndless and m_bInPlaceSiteEx data member flags:

m_spInPlaceSite Type | m_bWndless Value | m_bInPlaceSiteEx Value
IoleInPlaceSiteWindowless | TRUE | TRUE or FALSE
IoleInPlaceSiteEx | FALSE | TRUE
IoleInPlaceSite | FALSE | FALSE

CComControl Overview | Class Members

See Also CComPtr


CComControl::m_spOleAdviseHolder

CComPtr<IOleAdviseHolder> m_spOleAdviseHolder;

Remarks

Provides a standard implementation of a way to hold advisory connections. Implements the IOleObject::Advise and IOleObject::Unadvise methods to establish and delete advisory connections to the container. The control's container must implement an advise sink by supporting the IAdviseSink interface.

CComControl Overview | Class Members

See Also CComPtr


CComCriticalSection

class CComCriticalSection

CComCriticalSection provides methods for obtaining and releasing ownership of a critical section object. CComCriticalSection is similar to class CComAutoCriticalSection, except that you must explicitly initialize and release the critical section.

Typically, you use CComCriticalSection through the typedef name CriticalSection. This name references CComCriticalSection when CComMultiThreadModel is being used.

#include <atlbase.h>

Class Members

See Also CComFakeCriticalSection


CComCriticalSection Class Members

Methods

Init | Creates and initializes a critical section object.
Lock | Obtains ownership of the critical section object.
Term | Releases system resources used by the critical section object.
Unlock | Releases ownership of the critical section object.

Data Members

m_sec A CRITICAL_SECTION object.

CComCriticalSection Overview


CComCriticalSection::Init

void Init( );

Remarks

Calls the Win32 function InitializeCriticalSection, which initializes the critical section object contained in the m_sec data member.


CComCriticalSection::Lock

void Lock( );

Remarks

Calls the Win32 function EnterCriticalSection, which waits until the thread can take ownership of the critical section object contained in the m_sec data member. The critical section object must first be initialized with a call to the Init method. When the protected code has finished executing, the thread must call Unlock to release ownership of the critical section.


CComCriticalSection::Term

void Term( );

Remarks

Calls the Win32 function DeleteCriticalSection, which releases all resources used by the critical section object contained in the m_sec data member. Once Term has been called, the critical section can no longer be used for synchronization.


CComCriticalSection::Unlock

void Unlock( );

Remarks

Calls the Win32 function LeaveCriticalSection, which releases ownership of the critical section object contained in the m_sec data member. To first obtain ownership, the thread must call the Lock method. Each call to Lock requires a corresponding call to Unlock to release ownership of the critical section.


CComCriticalSection::m_sec

CRITICAL_SECTION m_sec;

Remarks

Contains a critical section object that is used by all CComCriticalSection methods.

CComCriticalSection Overview | Class Members

See Also CComCriticalSection::Lock, CComCriticalSection::Unlock, CComCriticalSection::Init, CComCriticalSection::Term


CComDispatchDriver

class CComDispatchDriver

CComDispatchDriver lets you retrieve or set an object's properties through an IDispatch pointer. For more information about adding properties to an object, see the ATL Tutorial.

#include <atlcom.h>

Class Members


CComDispatchDriver Class Members

Methods

CComDispatchDriver | Constructor. Initializes the data member p to NULL.
GetProperty | Gets the value of a property exposed by an object.
PutProperty | Sets the value of a property exposed by an object.
Release | Releases the Idispatch pointer and sets it to NULL.

Operators

operator IDispatch* | Converts a ComDispatchDriver object to an IDispatch pointer.
operator * | Returns the dereferenced value of the data member p.
operator & | Returns the address of data member p.
operator -> | Returns the data member p.
operator = | Sets the data member p to the specified IDispatch interface pointer.
operator ! | Checks whether the data member p is NULL or not.

Data Members

p Pointer to the Idispatch interface.

CComDispatchDriver Overview


CComDispatchDriver::CComDispatchDriver

CComDispatchDriver( );

CComDispatchDriver( IDispatch* lp );

CComDispatchDriver( IUnknown* lp );

Parameters

lp

[in] Pointer to an IDispatch or IUnknown interface.

Remarks

The constructor. If there is no lp parameter, the constructor initializes the data member p to NULL. If lp points to an IDispatch interface, the constructor sets p to that interface and calls AddRef. If lp points to an IUnknown interface, the constructor calls QueryInterface for the IDispatch interface and sets p to that interface.

The destructor calls Release on p, if necessary.


CComDispatchDriver::GetProperty

HRESULT GetProperty( DISPID dwDispID, VARIANT* var );

static HRESULT GetProperty( IDispatch* pDisp, DISPID dwDispID, VARIANT* var );

Return Value

One of the standard HRESULT values.

Parameters

dwDispID

[in] The DISPID of the property to be retrieved. The DISPID can be obtained from IDispatch::GetIDsOfNames.

var

[out] Pointer to where the property value is to be stored.

pDisp

[in] Pointer to the IDispatch interface.

Remarks

Gets the value of the property identified by dwDispID. If you supply pDisp, that IDispatch pointer is used. If you do not, the IDispatch pointer contained in the data member p is used.

The following example shows a call to the static version of GetProperty. This code is used to implement IPersistStreamInitImpl::Save.

CComPtr<IDispatch> pDispatch;
const IID* piidOld = NULL;
for(int i = 0; pMap[i].pclsidPropPage != NULL; i++)
               // pMap is a pointer to an array of
               // ATL_PROPMAP_ENTRY structures
{
   if (pMap[i].szDesc == NULL)
      continue;
   CComVariant var;
   if(pMap[i].piidDispatch != piidOld)
   {
      if(FAILED(ControlQueryInterface(*pMap[i].piidDispatch,
                                (void**)&pDispatch)))
      {
         ATLTRACE(_T("Failed to get a dispatch pointer
                  for property #%i\n"), i);
         hr = E_FAIL;
         break;
      }
      piidOld = pMap[i].piidDispatch;
   }
   if (FAILED(CComDispatchDriver::GetProperty(pDispatch,
                               pMap[i].dispid, &var)))
   {
      ATLTRACE(_T("Invoked failed on DISPID %x\n"),
               pMap[i].dispid);
      hr = E_FAIL;
      break;
   }
   HRESULT hr = var.WriteToStream(pStm);
   if (FAILED(hr))
      break;
}

CComDispatchDriver Overview | Class Members

See Also CComDispatchDriver::PutProperty


CComDispatchDriver::PutProperty

HRESULT PutProperty( DISPID dwDispID, VARIANT* var );

static HRESULT PutProperty( IDispatch* pDisp, DISPID dwDispID, VARIANT* var );

Return Value

One of the standard HRESULT values.

Parameters

dwDispID

[in] The DISPID of the property to be set. The DISPID can be obtained from IDispatch::GetIDsOfNames.

var

[in] Pointer to the property value to be set.

pDisp

[in] Pointer to the IDispatch interface.

Remarks

Sets the value of the property identified by dwDispID to the value in var. If you supply pDisp, that IDispatch pointer is used. If you do not, the IDispatch pointer contained in the data member p is used.

The following code illustrates PutProperty:

DISPID dwDispID;
VARIANT var;
HRESULT hRes;
OLECHAR *szMember = "ThisProperty";
VariantInit(&var)
...
hRes = pDisp->GetIDsOfNames(IID_NULL, szMember, 1, LOCALE_USER_DEFAULT, &dwDispID);
hRes = CComDispatchDriver::PutProperty(pDisp, dwDispID, &var);

CComDispatchDriver Overview | Class Members

See Also CComDispatchDriver::GetProperty


CComDispatchDriver::Release

void Release( );

Remarks

Checks whether data member p points to an IDispatch interface and, if it does, releases the interface and sets p to NULL.


CComDispatchDriver::operator IDispatch*

operator IDispatch*( ) ;

Remarks

Converts a CComDispatchDriver object to an IDispatch pointer by returning the data member p. Thus, if the CComDispatchDriver object is pDD, the following two statements are equivalent:

pMyDisp=(IDispatch*)(pDD)
pMyDisp= pDD.p


CComDispatchDriver::operator *

IDispatch& operator *( );

Remarks

Returns the dereferenced value of the IDispatch interface pointer stored in the data member p.

Note The operation will assert if p is NULL.


CComDispatchDriver::operator &

IDispatch** operator &( );

Remarks

Returns the address of the IDispatch interface pointer stored in the data member p. The operation will assert if p is non-NULL. This operator avoids memory leaks if you want to set p without releasing it first.


CComDispatchDriver::operator ->

IDispatch* operator ->( );

Remarks

Returns the IDispatch interface pointer stored in the data member p.

Note The operation will assert if p is NULL.


CComDispatchDriver::operator =

IDispatch* operator =( IDispatch* lp ) ;

IDispatch* operator =( IUnknown* lp ) ;

Remarks

Sets the data member p to an IDispatch interface pointer or to a pointer to an IDispatch interface obtained through an IUnknown pointer.

If p already points to an IDispatch interface, that interface is first released.

For example, if the CComDispatchDriver object is pDD and an IDispatch pointer is pMyDisp, pDD=pMyDisp sets pDD.p to pMyDisp. If an IUnknown pointer is pMyUnk, pDD=pMyUnk sets pDD.p to point to the IDispatch queried for on pMyUnk, that is:

pMyUnk->QueryInterface(IID_IDispatch, (void**)pDD.p);


CComDispatchDriver::operator !

BOOL operator !( );

Remarks

Returns TRUE if the data member p is NULL; otherwise, FALSE.


CComDispatchDriver::p

IDispatch* p;

Remarks

The pointer to the IDispatch interface. This data member can be set to an existing IDispatch interface with operator =.

CComDispatchDriver Overview | Class Members

See Also CComDispatchDriver::operator =


CComDynamicUnkArray

class CComDynamicUnkArray

CComDynamicUnkArray holds a dynamically allocated array of IUnknown pointers, each an interface on a connection point. CComDynamicUnkArray can be used as a parameter to the IConnectionPointImpl template class.

The CComDynamicUnkArray methods begin and end can be used to loop through all connection points (for example, when an event is fired).

See Adding Connection Points to an Object for details on automating creation of connection point proxies.

#include <atlcom.h>

Class Members

See Also CComUnkArray


CComDynamicUnkArray Class Members

Methods

begin | Returns a pointer to the first IUnknown pointer in the collection.
CComDynamicUnkArray | Constructor. Initializes the collection values to NULL and the collection size to zero.
end | Returns a pointer to one past the last IUnknown pointer in the collection.
GetAt | Retrieves the element at the specified index.
GetSize | Returns the length of an array.
clear | Empties the array.

CComDynamicUnkArray Overview


CComDynamicUnkArray::begin

IUnknown** begin( );

Return Value

A pointer to an IUnknown interface pointer.

Remarks

Returns a pointer to the beginning of the collection of IUnknown interface pointers.

The collection contains pointers to interfaces stored locally as IUnknown. You cast each IUnknown interface to the real interface type and then call through it. You do not need to query for the interface first.

Before using the IUnknown interface, you should check that it is not NULL.

CComDynamicUnkArray Overview | Class Members

See Also CComDynamicUnkArray::end, CComUnkArray::begin


CComDynamicUnkArray::clear

void clear( );

Remarks

Empties the array.


CComDynamicUnkArray::CComDynamicUnkArray

CComDynamicUnkArray( );

Remarks

The constructor. Sets the collection size to zero and initializes the values to NULL. The destructor frees the collection, if necessary.


CComDynamicUnkArray::end

IUnknown** end( );

Return Value

A pointer to an IUnknown interface pointer.

Remarks

Returns a pointer to one past the last IUnknown pointer in the collection.

CComDynamicUnkArray Overview | Class Members

See Also CComDynamicUnkArray::begin, CComUnkArray::end


CComDynamicUnkArray::GetAt

IUnknown* GetAt( int nIndex );

Return Value

A pointer to an IUnknown interface.

Parameters

nIndex

The index of the element to retrieve.

Remarks

Retrieves the element at the specified index.


CComDynamicUnkArray::GetSize

int GetSize( ) const;

Return Value

The length of the array.

Remarks

Returns the length of an array.


CComFakeCriticalSection

class CComFakeCriticalSection

CComFakeCriticalSection mirrors the methods found in CComCriticalSection. However, CComFakeCriticalSection does not provide a critical section; therefore, its methods do nothing.

Typically, you use CComFakeCriticalSection through a typedef name, either AutoCriticalSection or CriticalSection. When using CComSingleThreadModel or CComMultiThreadModelNoCS, both of these typedef names reference CComFakeCriticalSection. When using CComMultiThreadModel, they reference CComAutoCriticalSection and CComCriticalSection respectively.

#include <atlbase.h>

Class Members


CComFakeCriticalSection Class Members

Methods

Init | Does nothing.
Lock | Does nothing.
Term | Does nothing.
Unlock | Does nothing.

CComFakeCriticalSection Overview


CComFakeCriticalSection::Init

void Init( );

Remarks

Does nothing since there is no critical section.

CComFakeCriticalSection Overview | Class Members

See Also CComCriticalSection::Init


CComFakeCriticalSection::Lock

void Lock( );

Remarks

Does nothing since there is no critical section.

CComFakeCriticalSection Overview | Class Members

See Also CComCriticalSection::Lock


CComFakeCriticalSection::Term

void Term( );

Remarks

Does nothing since there is no critical section.

CComFakeCriticalSection Overview | Class Members

See Also CComCriticalSection::Term


CComFakeCriticalSection::Unlock

void Unlock( );

Remarks

Does nothing since there is no critical section.

CComFakeCriticalSection Overview | Class Members

See Also CComCriticalSection::Unlock


CComGlobalsThreadModel

#if defined( _ATL_SINGLE_THREADED )
 typedef CComSingleThreadModel CComGlobalsThreadModel;

#elif defined( _ATL_APARTMENT_THREADED )
 typedef CComMultiThreadModel CComGlobalsThreadModel;

#else
 typedef CComMultiThreadModel CComGlobalsThreadModel;

#endif

Depending on the threading model used by your application, the typedef name CComGlobalsThreadModel references either CComSingleThreadModel or CComMultiThreadModel. These classes provide additional typedef names to reference a critical section class.

Note CComGlobalsThreadModel does not reference class CComMultiThreadModelNoCS.

Using CComGlobalsThreadModel frees you from specifying a particular threading model class. Regardless of the threading model being used, the appropriate methods will be called.

In addition to CComGlobalsThreadModel, ATL provides the typedef name CComObjectThreadModel. The class referenced by each typedef depends on the threading model used, as shown in the following table:

 | Threading Model
typedef | Single | Apartment | Free
CcomObjectThreadModel | S | S | M
CcomGlobalsThreadModel | S | M | M

S=CComSingleThreadModel; M=CComMultiThreadModel

Use CComObjectThreadModel within a single object class. Use CComGlobalsThreadModel in an object that is globally available to your program, or when you wish to protect module resources across multiple threads.

#include <atlbase.h>

See Also CComObjectRootEx


CComModule

class CComModule : public _ATL_MODULE

CComModule implements a COM server module, allowing a client to access the module's components. CComModule supports both DLL (in-process) and EXE (local) modules.

A CComModule instance uses an object map to maintain a set of class object definitions. This object map is implemented as an array of _ATL_OBJMAP_ENTRY structures, and contains information for:

  • Entering and removing object descriptions in the system registry.

  • Instantiating objects through a class factory.

  • Establishing communication between a client and the root object in the component.

  • Performing lifetime management of class objects.

When you run the ATL COM AppWizard, the wizard automatically generates _Module, a global instance of CComModule or a class derived from it. For more information about the ATL COM AppWizard, see the article Creating an ATL Project.

In addition to CComModule, ATL provides CComAutoThreadModule, which implements an apartment-model module for EXEs and Windows NT services. Derive your module from CComAutoThreadModule when you want to create objects in multiple apartments.

#include <atlbase.h>

Class Members


CComModule Class Members

Methods

GetClassObject | Creates an object of a specified CLSID. For DLLs only.
GetLockCount | Returns the current lock count on the module.
GetModuleInstance | Returns m_hInst.
GetResourceInstance | Returns m_hInstResource.
GetTypeLibInstance | Returns m_hInstTypeLib.
Init | Initializes data members.
Lock | Increments the module lock count.
RegisterClassHelper | Enters an object's standard class registration in the system registry.
RegisterClassObjects | Registers the class factory in the Running Object Table. For EXEs only.
RegisterServer | Updates the system registry for each object in the object map.
RegisterTypeLib | Registers a type library.
RevokeClassObjects | Removes the class factory from the Running Object Table. For EXEs only.
Term | Releases data members.
Unlock | Decrements the module lock count.
UnregisterClassHelper | Removes an object's standard class registration from the system registry.
UnregisterServer | Unregisters each object in the object map.
UpdateRegistryClass | Registers or unregisters an object's standard class registration.
UpdateRegistryFromResourceD | Runs the script contained in a specified resource to register or unregister an object.
UpdateRegistryFromResourceS | Statically links to the ATL Registry Component. Runs the script contained in a specified resource to register or unregister an object.

Data Members

m_csObjMap | Ensures synchronized access to the object map information.
m_csTypeInfoHolder | Ensures synchronized access to the type library information.
m_csWindowCreate | Ensures synchronized access to window class information and static data used during window creation.
m_hHeap | Contains the handle to the heap managed by the module.
m_hInst | Contains the handle to the module instance.
m_hInstResource | By default, contains the handle to the module instance.
m_hInstTypeLib | By default, contains the handle to the module instance.
m_nLockCnt | Contains the current lock count on the module.
m_pObjMap | Points to the object map maintained by the module instance.

CComModule Overview


CComModule::GetClassObject

HRESULT GetClassObject( REFCLSID rclsid, REFIID riid, LPVOID* ppv );

Return Value

A standard HRESULT value.

Parameters

rclsid

[in] The CLSID of the object to be created.

riid

[in] The IID of the requested interface.

ppv

[out] A pointer to the interface pointer identified by riid. If the object does not support this interface, ppv is set to NULL.

Remarks

Creates an object of the specified CLSID and retrieves an interface pointer to this object.

Note GetClassObject is only available to DLLs.


CComModule::GetLockCount

LONG GetLockCount( );

Return Value

The lock count on the module.

Remarks

Returns the current lock count on the module. CComModule uses the lock count to determine whether any clients are accessing the module. When the lock count reaches zero, the module can be unloaded.

CComModule Overview | Class Members

See Also CComModule::Lock, CComModule::Unlock, CComModule::m_nLockCnt


CComModule::GetModuleInstance

HINSTANCE GetModuleInstance( );

Return Value

The HINSTANCE identifying this module.

Remarks

Returns the m_hInst data member.

CComModule Overview | Class Members

See Also CComModule::GetResourceInstance, CComModule::GetTypeLibInstance


CComModule::GetResourceInstance

HINSTANCE GetResourceInstance( );

Return Value

An HINSTANCE.

Remarks

Returns the m_hInstResource data member.

CComModule Overview | Class Members

See Also CComModule::GetModuleInstance, CComModule::GetTypeLibInstance


CComModule::GetTypeLibInstance

HINSTANCE GetTypeLibInstance( );

Return Value

An HINSTANCE.

Remarks

Returns the m_hInstTypeLib data member.

CComModule Overview | Class Members

See Also CComModule::GetModuleInstance, CComModule::GetResourceInstance


CComModule::Init

void Init( _ATL_OBJMAP_ENTRY* p, HINSTANCE h );

Parameters

p

[in] A pointer to an array of object map entries.

h

[in] The HINSTANCE passed to DLLMain or WinMain.

Remarks

Initializes all data members.

CComModule Overview | Class Members

See Also CComModule::Term


CComModule::Lock

LONG Lock( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Performs an atomic increment on the module's lock count. CComModule uses the lock count to determine whether any clients are accessing the module.

CComModule Overview | Class Members

See Also CComModule::Unlock, CComModule::GetLockCount, CComModule::m_nLockCnt


CComModule::RegisterClassHelper

HRESULT RegisterClassHelper( const CLSID& clsid, LPCTSTR lpszProgID, LPCTSTR lpszVerIndProgID, UINT nDescID, DWORD dwFlags );

Return Value

A standard HRESULT value.

Parameters

clsid

[in] The CLSID of the object to be registered.

lpszProgID

[in] The ProgID associated with the object.

lpszVerIndProgID

[in] The version-independent ProgID associated with the object.

nDescID

[in] The identifier of a string resource for the object's description.

dwFlags

[in] Specifies the threading model to enter in the registry. Possible values are THREADFLAGS_APARTMENT, THREADFLAGS_BOTH, or AUTPRXFLAG.

Remarks

Enters an object's standard class registration in the system registry. The UpdateRegistryClass method calls RegisterClassHelper.

CComModule Overview | Class Members

See Also CComModule::UnregisterClassHelper


CComModule::RegisterClassObjects

HRESULT RegisterClassObjects( DWORD dwClsContext, DWORD dwFlags );

Return Value

A standard HRESULT value.

Parameters

dwClsContext

[in] Specifies the context in which the class object is to be run. Possible values are CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, or CLSCTX_LOCAL_SERVER. For a description of these values, see CLSCTX in the Win32 SDK.

dwFlags

[in] Determines the connection types to the class object. Possible values are REGCLS_SINGLEUSE, REGCLS_MULTIPLEUSE, or REGCLS_MULTI_SEPARATE. For a description of these values, see REGCLS in the Win32 SDK.

Remarks

Registers the class factory in the Running Object Table.

Note RegisterClassObjects is only available to EXEs.

CComModule Overview | Class Members

See Also CComModule::RevokeClassObjects


CComModule::RegisterServer

HRESULT RegisterServer( BOOL bRegTypeLib = FALSE, const CLSID* pCLSID = NULL );

Return Value

A standard HRESULT value.

Parameters

bRegTypeLib

[in] Indicates whether the type library will be registered. The default value is FALSE.

pCLSID

[in] Points to the CLSID of the object to be registered. If NULL (the default value), all objects in the object map will be registered.

Remarks

Depending on the pCLSID parameter, updates the system registry for a single class object or for all objects in the object map. If bRegTypeLib is TRUE, the type library information will also be updated.

The BEGIN_OBJECT_MAP macro starts your object map definition.

RegisterServer will be called automatically by DLLRegisterServer for a DLL or by WinMain for an EXE run with the /RegServer command line option.

CComModule Overview | Class Members

See Also CComModule::UnregisterServer


CComModule::RegisterTypeLib

HRESULT RegisterTypeLib( );

HRESULT RegisterTypeLib( LPCTSTR lpszIndex );

Return Value

A standard HRESULT value.

Parameters

lpszIndex

[in] String in the format "\\N", where N is the integer index of the TYPELIB resource.

Remarks

Adds information about a type library to the system registry. If the module instance contains multiple type libraries, use the second version of this method to specify which type library should be used.


CComModule::RevokeClassObjects

HRESULT RevokeClassObjects( );

Return Value

A standard HRESULT value.

Remarks

Removes the class factory from the Running Object Table.

Note RevokeClassObjects is only available to EXEs.

CComModule Overview | Class Members

See Also CComModule::RegisterClassObjects


CComModule::Term

void Term( );

Remarks

Releases all data members.

CComModule Overview | Class Members

See Also CComModule::Init


CComModule::Unlock

LONG Unlock( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Performs an atomic decrement on the module's lock count. CComModule uses the lock count to determine whether any clients are accessing the module. When the lock count reaches zero, the module can be unloaded.

CComModule Overview | Class Members

See Also CComModule::Lock, CComModule::GetLockCount, CComModule::m_nLockCnt


CComModule::UnregisterClassHelper

HRESULT UnregisterClassHelper( const CLSID& clsid, LPCTSTR lpszProgID, LPCTSTR lpszVerIndProgID );

Return Value

A standard HRESULT value.

Parameters

clsid

[in] The CLSID of the object to be unregistered.

lpszProgID

[in] The ProgID associated with the object.

lpszVerIndProgID

[in] The version-independent ProgID associated with the object.

Remarks

Removes an object's standard class registration from the system registry. The UpdateRegistryClass method calls UnregisterClassHelper.

CComModule Overview | Class Members

See Also CComModule::RegisterClassHelper


CComModule::UnregisterServer

HRESULT UnregisterServer( const CLSID* pCLSID = NULL );

Return Value

A standard HRESULT value.

Parameters

pCLSID

[in] Points to the CLSID of the object to be unregistered. If NULL (the default value), all objects in the object map will be unregistered.

Remarks

Depending on the pCLSID parameter, unregisters either a single class object or all objects in the object map. The BEGIN_OBJECT_MAP macro starts your object map definition.

UnregisterServer will be called automatically by DLLUnregisterServer for a DLL or by WinMain for an EXE run with the /UnregServer command line option.

CComModule Overview | Class Members

See Also CComModule::RegisterServer


CComModule::UpdateRegistryClass

HRESULT UpdateRegistryClass( const CLSID& clsid, LPCTSTR lpszProgID, LPCTSTR lpszVerIndProgID, UINT nDescID, DWORD dwFlags, BOOL bRegister );

Return Value

A standard HRESULT value.

Parameters

clsid

[in] The CLSID of the object to be registered or unregistered.

lpszProgID

[in] The ProgID associated with the object.

lpszVerIndProgID

[in] The version-independent ProgID associated with the object.

nDescID

[in] The identifier of the string resource for the object's description.

dwFlags

[in] Specifies the threading model to enter in the registry. Possible values are THREADFLAGS_APARTMENT, THREADFLAGS_BOTH, or AUTPRXFLAG.

bRegister

[in] Indicates whether the object should be registered.

Remarks

If bRegister is TRUE, this method enters the object's standard class registration in the system registry. If bRegister is FALSE, it removes the object's registration.

Depending on the value of bRegister, UpdateRegistryClass calls either RegisterClassHelper or UnregisterClassHelper.

By specifying the DECLARE_REGISTRY macro, UpdateRegistryClass will be invoked automatically when your object map is processed.


CComModule::UpdateRegistryFromResourceD

HRESULT UpdateRegistryFromResourceD( LPCTSTR lpszRes, BOOL bRegister, struct _ATL_REGMAP_ENTRY* pMapEntries = NULL );

HRESULT UpdateRegistryFromResourceD( UINT nResID, BOOL bRegister, struct _ATL_REGMAP_ENTRY* pMapEntries = NULL );

Return Value

A standard HRESULT value.

Parameters

lpszRes

[in] A resource name.

nResID

[in] A resource ID.

bRegister

[in] Indicates whether the object should be registered.

pMapEntries

[in] A pointer to the replacement map storing values associated with the script's replaceable parameters. ATL automatically uses %MODULE%. To use additional replaceable parameters, see Remarks for details. Otherwise, use the NULL default value.

Remarks

Runs the script contained in the resource specified by lpszRes or nResID. If bRegister is TRUE, this method registers the object in the system registry; otherwise, it unregisters the object.

By specifying the DECLARE_REGISTRY_RESOURCE or DECLARE_REGISTRY_RESOURCEID macro, UpdateRegistryFromResourceD will be invoked automatically when your object map is processed.

Note To substitute replacement values at run time, do not specify the DECLARE_REGISTRY_RESOURCE or DECLARE_REGISTRY_RESOURCEID macro. Instead, create an array of _ATL_REGMAP_ENTRIES structures, where each entry contains a variable placeholder paired with a value to replace the placeholder at run time. Then call UpdateRegistryFromResourceD, passing the array for the pMapEntries parameter. This adds all the replacement values in the _ATL_REGMAP_ENTRIES structures to the Registrar's replacement map.

Note To statically link to the ATL Registry Component (Registrar), see UpdateRegistryFromResourceS.

For more information about replaceable parameters and scripting, see the article The ATL Registry Component (Registrar).

CComModule Overview | Class Members

See Also BEGIN_OBJECT_MAP


CComModule::UpdateRegistryFromResourceS

HRESULT UpdateRegistryFromResourceS( LPCTSTR lpszRes, BOOL bRegister, struct _ATL_REGMAP_ENTRY* pMapEntries = NULL );

HRESULT UpdateRegistryFromResourceS( UINT nResID, BOOL bRegister, struct _ATL_REGMAP_ENTRY* pMapEntries = NULL );

Return Value

A standard HRESULT value.

Parameters

lpszRes

[in] A resource name.

nResID

[in] A resource ID.

bRegister

[in] Indicates whether the resource script should be registered.

pMapEntries

[in] A pointer to the replacement map storing values associated with the script's replaceable parameters. ATL automatically uses %MODULE%. To use additional replaceable parameters, see Remarks for details. Otherwise, use the NULL default value.

Remarks

Similar to UpdateRegistryFromResourceD except UpdateRegistryFromResourceS creates a static link to the ATL Registry Component (Registrar).

UpdateRegistryFromResourceS will be invoked automatically when your object map is processed, provided you add #define _ATL_STATIC_REGISTRY to your stdafx.h.

Note To substitute replacement values at run time, do not specify the DECLARE_REGISTRY_RESOURCE or DECLARE_REGISTRY_RESOURCEID macro. Instead, create an array of _ATL_REGMAP_ENTRIES structures, where each entry contains a variable placeholder paired with a value to replace the placeholder at run time. Then call CComModule::UpdateRegistryFromResourceS, passing the array for the pMapEntries parameter. This adds all the replacement values in the _ATL_REGMAP_ENTRIES structures to the Registrar's replacement map.

For more information about replaceable parameters and scripting, see the article The ATL Registry Component (Registrar).

CComModule Overview | Class Members

See Also BEGIN_OBJECT_MAP


CComModule::m_csObjMap

CRITICAL_SECTION m_csObjMap;

Remarks

Ensures synchronized access to the object map.


CComModule::m_csTypeInfoHolder

CRITICAL_SECTION m_csTypeInfoHolder;

Remarks

Ensures synchronized access to the type library.


CComModule::m_csWindowCreate

CRITICAL_SECTION m_csWindowCreate;

Remarks

Ensures synchronized access to window class information and to static data used during window creation.


CComModule::m_hHeap

HANDLE m_hHeap;

Remarks

Contains the handle to the heap managed by the module.


CComModule::m_hInst

HINSTANCE m_hInst;

Remarks

Contains the handle to the module instance. The Init method sets m_hInst to the handle passed to DLLMain or WinMain.


CComModule::m_hInstResource

HINSTANCE m_hInstResource;

Remarks

By default, contains the handle to the module instance. The Init method sets m_hInstResource to the handle passed to DLLMain or WinMain. You can explicitly set m_hInstResource to the handle to a resource.

The GetResourceInstance method returns the handle stored in m_hInstResource.


CComModule::m_hInstTypeLib

HINSTANCE m_hInstTypeLib;

Remarks

By default, contains the handle to the module instance. The Init method sets m_hInstTypeLib to the handle passed to DLLMain or WinMain. You can explicitly set m_hInstTypeLib to the handle to a type library.

The GetTypeLibInstance method returns the handle stored in m_hInstTypeLib.


CComModule::m_nLockCnt

LONG m_nLockCnt;

Remarks

Contains the current lock count on the module. CComModule uses the lock count to determine whether any clients are accessing the module. When the lock count reached zero, the module can be unloaded.

CComModule Overview | Class Members

See Also CComModule::GetLockCount, CComModule::Lock, CComModule::Unlock


CComModule::m_pObjMap

_ATL_OBJMAP_ENTRY* m_pObjMap;

Remarks

Points to the object map maintained by the module instance.


CComMultiThreadModel

class CComMultiThreadModel

CComMultiThreadModel provides thread-safe methods for incrementing and decrementing the value of a variable. Typically, you use CComMultiThreadModel through one of two typedef names, either CComObjectThreadModel or CComGlobalsThreadModel. The class referenced by each typedef depends on the threading model used, as shown in the following table:

 | Threading Model
typedef | Single | Apartment | Free
CComObjectThreadModel | S | S | M
CComGlobalsThreadModel | S | M | M

S=CComSingleThreadModel; M=CComMultiThreadModel

CComMultiThreadModel itself defines three typedef names. AutoCriticalSection and CriticalSection reference classes that provide methods for obtaining and releasing ownership of a critical section. ThreadModelNoCS references class CComMultiThreadModelNoCS.

#include <atlbase.h>

Class Members

See Also CComSingleThreadModel, CComAutoCriticalSection, CComCriticalSection


CComMultiThreadModel Class Members

Methods

Decrement | Decrements the value of the specified variable in a thread-safe manner.
Increment | Increments the value of the specified variable in a thread-safe manner.

Typedefs

AutoCriticalSection | References class CComAutoCriticalSection.
CriticalSection | References class CComCriticalSection.
ThreadModelNoCS | References class CComMultiThreadModelNoCS.

CComMultiThreadModel Overview


CComMultiThreadModel::Decrement

static ULONG Decrement( LPLONG p );

Return Value

If the result of the decrement is 0, then Decrement returns 0. If the result of the decrement is nonzero, the return value is also nonzero but may not equal the result of the decrement.

Parameters

p

[in] Pointer to the variable to be decremented.

Remarks

This static method calls the Win32 function InterlockedDecrement, which decrements the value of the variable pointed to by p. InterlockedDecrement prevents more than one thread from simultaneously using this variable.

CComMultiThreadModel Overview | Class Members

See Also CComMultiThreadModel::Increment


CComMultiThreadModel::Increment

static ULONG Increment( LPLONG p );

Return Value

If the result of the increment is 0, then Increment returns 0. If the result of the increment is nonzero, the return value is also nonzero but may not equal the result of the increment.

Parameters

p

[in] Pointer to the variable to be incremented.

Remarks

This static method calls the Win32 function InterlockedIncrement, which increments the value of the variable pointed to by p. InterlockedIncrement prevents more than one thread from simultaneously using this variable.

CComMultiThreadModel Overview | Class Members

See Also CComMultiThreadModel::Decrement


Typedefs


CComMultiThreadModel::AutoCriticalSection

typedef CComAutoCriticalSection AutoCriticalSection;

Remarks

When using CComMultiThreadModel, the typedef name AutoCriticalSection references class CComAutoCriticalSection, which provides methods for obtaining and releasing ownership of a critical section object.

CComSingleThreadModel and CComMultiThreadModelNoCS also contain definitions for AutoCriticalSection. The following table shows the relationship between the threading model class and the critical section class reference by AutoCriticalSection:

Class defined in | Class referenced
CComMultiThreadModel | CComCriticalSection
CComSingleThreadModel | CComFakeCriticalSection
CComMultiThreadModelNoCS | CComFakeCriticalSection

In addition to AutoCriticalSection, you can use the typedef name CriticalSection. You should not specify AutoCriticalSection in global objects or static class members if you want to eliminate the CRT startup code.

Example

The following code is taken from CComObjectRootEx.

template< class ThreadModel >
class CComObjectRootEx : public CComObjectRootBase
{
public:
   typedef ThreadModel _ThreadModel;
   typedef _ThreadModel::AutoCriticalSection _CritSec;

   ULONG InternalAddRef( )
   {
      ...
      return _ThreadModel::Increment(&m_dwRef);
   }
   ...
   void Lock( ) { m_critsec.Lock( ); }
   ...

private:
   _CritSec m_critsec;

};

The following tables show the results of the InternalAddRef and Lock methods, depending on the ThreadModel template parameter and the threading model used by the application:

ThreadModel = CComObjectThreadModel

 | Single or Apartment | Free
InternalAddRef | The increment is not thread-safe. | The increment is thread-safe.
Lock | Does nothing; there is no critical section to lock. | The critical section is locked.

ThreadModel = CComObjectThreadModel::ThreadModelNoCS

 | Single or Apartment | Free
InternalAddRef | The increment is not thread-safe. | The increment is thread-safe.
Lock | Does nothing; there is no critical section to lock. | Does nothing; there is no critical section to lock.

CComMultiThreadModel Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel, CComMultiThreadModel::ThreadModelNoCS


CComMultiThreadModel::CriticalSection

typedef CComCriticalSection CriticalSection;

Remarks

When using CComMultiThreadModel, the typedef name CriticalSection references class CComCriticalSection, which provides methods for obtaining and releasing ownership of a critical section object.

CComSingleThreadModel and CComMultiThreadModelNoCS also contain definitions for CriticalSection. The following table shows the relationship between the threading model class and the critical section class referenced by CriticalSection:

Class defined in | Class referenced
CcomMultiThreadModel | CcomCriticalSection
CcomSingleThreadModel | CcomFakeCriticalSection
CcomMultiThreadModelNoCS | CcomFakeCriticalSection

In addition to CriticalSection, you can use the typedef name AutoCriticalSection. You should not specify AutoCriticalSection in global objects or static class members if you want to eliminate the CRT startup code.

Example

See AutoCriticalSection.

CComMultiThreadModel Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel, CComMultiThreadModel::ThreadModelNoCS


CComMultiThreadModel::ThreadModelNoCS

typedef CComMultiThreadModelNoCS ThreadModelNoCS;

Remarks

When using CComMultiThreadModel, the typedef name ThreadModelNoCS references class CComMultiThreadModelNoCS. CComMultiThreadModelNoCS provides thread-safe methods for incrementing and decrementing a variable; however, it does not provide a critical section.

CComSingleThreadModel and CComMultiThreadModelNoCS also contain definitions for ThreadModelNoCS. The following table shows the relationship between the threading model class and the class referenced by ThreadModelNoCS:

Class defined in | Class referenced
CComMultiThreadModel | CcomMultiThreadModelNoCS
CComSingleThreadModel | CcomSingleThreadModel
CComMultiThreadModelNoCS | CcomMultiThreadModelNoCS

Example

See AutoCriticalSection.

CComMultiThreadModel Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel


CComMultiThreadModelNoCS

class CComMultiThreadModelNoCS

CComMultiThreadModelNoCS is similar to CComMultiThreadModel in that it provides thread-safe methods for incrementing and decrementing a variable. However, when you reference a critical section class through CComMultiThreadModelNoCS, methods such as Lock and Unlock will do nothing.

Typically, you use CComMultiThreadModelNoCS through the ThreadModelNoCS typedef name. This typedef is defined in CComMultiThreadModelNoCS, CComMultiThreadModel, and CComSingleThreadModel.

Note The global typedef names CComObjectThreadModel and CComGlobalsThreadModel do not reference CComMultiThreadModelNoCS.

In addition to ThreadModelNoCS, CComMultiThreadModelNoCS defines AutoCriticalSection and CriticalSection. These latter two typedef names reference CComFakeCriticalSection, which provides empty methods associated with obtaining and releasing a critical section.

#include <atlbase.h>

Class Members


CComMultiThreadModelNoCS Class Members

Methods

Decrement | Decrements the value of the specified variable in a thread-safe manner.
Increment | Increments the value of the specified variable in a thread-safe manner.

Typedefs

AutoCriticalSection | References class CComFakeCriticalSection.
CriticalSection | References class CComFakeCriticalSection.
ThreadModelNoCS | References class CComMultiThreadModelNoCS.

CComMultiThreadModelNoCS Overview


CComMultiThreadModelNoCS::Decrement

static ULONG Decrement( LPLONG p );

Return Value

If the result of the decrement is 0, then Decrement returns 0. If the result of the decrement is nonzero, the return value is also nonzero but may not equal the result of the decrement.

Parameters

p

[in] Pointer to the variable to be decremented.

Remarks

This static method calls the Win32 function InterlockedDecrement, which decrements the value of the variable pointed to by p. InterlockedDecrement prevents more than one thread from simultaneously using this variable.

CComMultiThreadModelNoCS Overview | Class Members

See Also CComMultiThreadModelNoCS::Increment


CComMultiThreadModelNoCS::Increment

static ULONG Increment( LPLONG p );

Return Value

If the result of the increment is 0, then Increment returns 0. If the result of the increment is nonzero, the return value is also nonzero but may not equal the result of the increment.

Parameters

p

[in] Pointer to the variable to be incremented.

Remarks

This static method calls the Win32 function InterlockedIncrement, which increments the value of the variable pointed to by p. InterlockedIncrement prevents more than one thread from simultaneously using this variable.

CComMultiThreadModelNoCS Overview | Class Members

See Also CComMultiThreadModelNoCS::Decrement


CComMultiThreadModelNoCS::AutoCriticalSection

typedef CComFakeCriticalSection AutoCriticalSection;

Remarks

When using CComMultiThreadModelNoCS, the typedef name AutoCriticalSection references class CComFakeCriticalSection. Because CComFakeCriticalSection does not provide a critical section, its methods do nothing.

CComMultiThreadModel and CComSingleThreadModel also contain definitions for AutoCriticalSection. The following table shows the relationship between the threading model class and the critical section class referenced by AutoCriticalSection:

Class defined in | Class referenced
CComMultiThreadModelNoCS | CComFakeCriticalSection
CComMultiThreadModel | CComAutoCriticalSection
CComSingleThreadModel | CComFakeCriticalSection

In addition to AutoCriticalSection, you can use the typedef name CriticalSection. You should not specify AutoCriticalSection in global objects or static class members if you want to eliminate the CRT startup code.

Example

See CComMultiThreadModel::AutoCriticalSection.

CComMultiThreadModelNoCS Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel, CComMultiThreadModelNoCS::ThreadModelNoCS


CComMultiThreadModelNoCS::CriticalSection

typedef CComFakeCriticalSection CriticalSection;

Remarks

When using CComMultiThreadModelNoCS, the typedef name CriticalSection references class CComFakeCriticalSection. Because CComFakeCriticalSection does not provide a critical section, its methods do nothing.

CComMultiThreadModel and CComSingleThreadModel also contain definitions for CriticalSection. The following table shows the relationship between the threading model class and the critical section class referenced by CriticalSection:

Class defined in | Class referenced
CcomMultiThreadModelNoCS | CcomFakeCriticalSection
CcomMultiThreadModel | CcomCriticalSection
CComSingleThreadModel | CcomFakeCriticalSection

In addition to CriticalSection, you can use the typedef name AutoCriticalSection. You should not specify AutoCriticalSection in global objects or static class members if you want to eliminate the CRT startup code.

Example

See CComMultiThreadModel::AutoCriticalSection.

CComMultiThreadModelNoCS Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel, CComMultiThreadModelNoCS::ThreadModelNoCS


CComMultiThreadModelNoCS::ThreadModelNoCS

typedef CComMultiThreadModelNoCS ThreadModelNoCS;

Remarks

When using CComMultiThreadModelNoCS, the typedef name ThreadModelNoCS simply references CComMultiThreadModelNoCS.

CComMultiThreadModel and CComSingleThreadModel also contain definitions for ThreadModelNoCS. The following table shows the relationship between the threading model class and the class referenced by ThreadModelNoCS:

Class defined in | Class referenced
CcomMultiThreadModelNoCS | CComMultiThreadModelNoCS
CcomMultiThreadModel | CComMultiThreadModelNoCS
CcomSingleThreadModel | CComSingleThreadModel

Example

See CComMultiThreadModel::AutoCriticalSection.

Note that the definition of ThreadModelNoCS in CComMultiThreadModelNoCS provides symmetry with CComMultiThreadModel and CComSingleThreadModel. For example, suppose the sample code in CComMultiThreadModel::AutoCriticalSection declared the following typedef:

typedef ThreadModel::ThreadModelNoCS _ThreadModel;

Regardless of the class specified for ThreadModel (such as CComMultiThreadModelNoCS), _ThreadModel resolves accordingly.

CComMultiThreadModelNoCS Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel


CComObject

template< class Base >
class CComObject : public Base

Parameters

Base

Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interfaces you want to support on the object.

CComObject implements IUnknown for a nonaggregated object. However, calls to QueryInterface, AddRef, and Release are delegated to CComObjectRootEx.

For more information about using CComObject, see the article Fundamentals of ATL COM Objects.

#include <atlcom.h>

Class Members

See Also CComAggObject, CComPolyObject, DECLARE_AGGREGATABLE, DECLARE_NOT_AGGREGATABLE


CComObject Class Members

Methods

CComObject | Constructor.
CreateInstance | Creates a new CcomObject object.

IUnknown Methods

AddRef | Increments the reference count on the object.
QueryInterface | Retrieves a pointer to the requested interface.
Release | Decrements the reference count on the object.

CComObject Overview


CComObject::AddRef

ULONG AddRef( );

Return Value

This function returns the new incremented reference count on the object. This value may be useful for diagnostics or testing.

Remarks

Increments the reference count on the object.

CComObject Overview | Class Members

See Also CComObject::Release


CComObject::CComObject

CComObject( void* = NULL );

Parameters

void*

[in] This unnamed parameter is not used. It exists for symmetry with other CCom XXX Object XXX constructors.

Remarks

The constructor increments the module lock count. The destructor decrements it.


CComObject::CreateInstance

static HRESULT CreateInstance( CComObject< Base >** pp );

Return Value

A standard HRESULT value.

Parameters

pp

[out] A pointer to a CComObject<Base> pointer. If CreateInstance is unsuccessful, pp is set to NULL.

Remarks

This static method allows you to create a new CComObject<Base> object, without the overhead of CoCreateInstance.


CComObject::QueryInterface

HRESULT QueryInterface( REFIID iid, void** ppvObject );

Return Value

A standard HRESULT value.

Parameters

iid

[in] The identifier of the interface being requested.

ppvObject

[out] A pointer to the interface pointer identified by iid. If the object does not support this interface, ppvObject is set to NULL.

Remarks

Retrieves a pointer to the requested interface.


CComObject::Release

ULONG Release( );

Return Value

This function returns the new decremented reference count on the object. In debug builds, the return value may be useful for diagnostics or testing. In non-debug builds, Release always returns 0.

Remarks

Decrements the reference count on the object.

CComObject Overview | Class Members

See Also CComObject::AddRef


CComObjectGlobal

template< class Base >
class CComObjectGlobal : public Base

Parameters

Base

Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interface you want to support on the object.

CComObjectGlobal manages a reference count on the module containing your Base object. CComObjectGlobal ensures your object will not be deleted as long as the module is not released. Your object will only be removed when the reference count on the entire module goes to zero.

For example, using CComObjectGlobal, a class factory can hold a common global object that is shared by all its clients.

#include <atlcom.h>

Class Members

See Also CComObjectStack, CComAggObject, CComObject


CComObjectGlobal Class Members

Class Methods

CcomObjectGlobal Constructor.

IUnknown Methods

AddRef | Implements a global AddRef.
QueryInterface | Implements a global QueryInterface.
Release | Implements a global Release.

Data Members

m_hResFinalConstruct Contains the HRESULT returned during construction of the CComObjectGlobal object.

CComObjectGlobal Overview


CComObjectGlobal::AddRef

ULONG AddRef( );

Return Value

A value that may be useful for diagnostics and testing.

Remarks

Increments the reference count of the object by 1. By default, AddRef calls _Module::Lock, where _Module is the global instance of CComModule or a class derived from it.

CComObjectGlobal Overview | Class Members

See Also CComObjectGlobal::Release, CComModule::Lock


CComObjectGlobal::CComObjectGlobal

CComObjectGlobal( );

Remarks

The constructor. Calls FinalConstruct and then sets m_hResFinalConstruct to the HRESULT returned by FinalConstruct. If you have not derived your base class from CComObjectRoot, you must supply your own FinalConstruct method. The destructor calls FinalRelease.

CComObjectGlobal Overview | Class Members

See Also CComObjectRootEx::FinalConstruct


CComObjectGlobal::QueryInterface

HRESULT QueryInterface( REFIID iid, void** ppvObject ) ;

Return Value

A standard HRESULT value.

Parameters

iid

[in] The GUID of the interface being requested.

ppvObject

[out] A pointer to the interface pointer identified by iid, or NULL if the interface is not found.

Remarks

Retrieves a pointer to the requested interface pointer. QueryInterface only handles interfaces in the COM map table.

CComObjectGlobal Overview | Class Members

See Also CComObjectRootEx::InternalQueryInterface, BEGIN_COM_MAP


CComObjectGlobal::Release

ULONG Release( );

Return Value

In debug builds, Release returns a value that may be useful for diagnostics and testing. In non-debug builds, Release always returns 0.

Remarks

Decrements the reference count of the object by 1. By default, Release calls _Module::Unlock, where _Module is the global instance of CComModule or a class derived from it.

CComObjectGlobal Overview | Class Members

See Also CComObjectGlobal::AddRef, CComModule::Unlock


CComObjectGlobal::m_hResFinalConstruct

HRESULT m_hResFinalConstruct( );

Remarks

Contains the HRESULT from calling FinalConstruct during construction of the CComObjectGlobal object.

CComObjectGlobal Overview | Class Members

See Also CComObjectRootEx::FinalConstruct


CComObjectNoLock

template< class Base >
class CComObjectNoLock : public Base

Parameters

Base

Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interface you want to support on the object.

CComObjectNoLock is similar to CComObject in that it implements IUnknown for a nonaggregated object; however, CComObjectNoLock does not increment the module lock count in the constructor.

ATL uses CComObjectNoLock internally for class factories. In general, you will not use this class directly.

#include <atlcom.h>

Class Members


CComObjectNoLock Class Members

Class Methods

CcomObjectNoLock Constructor.

IUnknown Methods

AddRef | Increments the reference count on the object.
QueryInterface | Returns a pointer to the requested interface.
Release | Decrements the reference count on the object.

CComObjectNoLock Overview


CComObjectNoLock::AddRef

ULONG AddRef( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Increments the reference count on the object.

CComObjectNoLock Overview | Class Members

See Also CComObjectNoLock::Release


CComObjectNoLock::CComObjectNoLock

CComObjectNoLock( void* = NULL );

Parameters

void*

[in] This unnamed parameter is not used. It exists for symmetry with other CCom XXX Object XXX constructors.

Remarks

The constructor. Unlike CComObject, does not increment the module lock count.


CComObjectNoLock::QueryInterface

HRESULT QueryInterface( REFIID iid, void** ppvObject );

Return Value

A standard HRESULT value.

Parameters

iid

[in] The identifier of the interface being requested.

ppvObject

[out] A pointer to the interface pointer identified by iid. If the object does not support this interface, ppvObject is set to NULL.

Remarks

Retrieves a pointer to the requested interface.


CComObjectNoLock::Release

ULONG Release( );

Return Value

In debug builds, Release returns a value that may be useful for diagnostics or testing. In non-debug builds, Release always returns 0.

Remarks

Decrements the reference count on the object.

CComObjectNoLock Overview | Class Members

See Also CComObjectNoLock::AddRef


CComObjectRoot

typedef CComObjectRootEx<CComObjectThreadModel> CComObjectRoot;

CComObjectRoot is a typedef of CComObjectRootEx templatized on the default threading model of the server. Thus CComObjectThreadModel will reference either CComSingleThreadModel or CComMultiThreadModel.

CComObjectRootEx handles object reference count management for both nonaggregated and aggregated objects. It holds the object reference count if your object is not being aggregated, and holds the pointer to the outer unknown if your object is being aggregated. For aggregated objects, CComObjectRootEx methods can be used to handle the failure of the inner object to construct, and to protect the outer object from deletion when inner interfaces are released or the inner object is deleted.

#include <atlcom.h>

CComObjectRootEx Class Members

See Also CComObjectRootEx, CComAggObject, CComObject, CComPolyObject


CComObjectRootEx

template< class ThreadModel >
class CComObjectRootEx : public CComObjectRootBase

Parameters

ThreadModel

The class whose methods implement the desired threading model. You can explicitly choose the threading model by setting ThreadModel to CComSingleThreadModel, CComMultiThreadModel, or CComMultiThreadModelNoCS. You can accept the server's default thread model by setting ThreadModel to CComObjectThreadModel or CComGlobalsThreadModel.

CComObjectRootEx handles object reference count management for both nonaggregated and aggregated objects. It holds the object reference count if your object is not being aggregated, and holds the pointer to the outer unknown if your object is being aggregated. For aggregated objects, CComObjectRootEx methods can be used to handle the failure of the inner object to construct, and to protect the outer object from deletion when inner interfaces are released or the inner object is deleted.

A class that implements a COM server must inherit from CComObjectRootEx or CComObjectRoot.

If your class definition specifies the DECLARE_POLY_AGGREGATABLE macro, ATL creates an instance of CComPolyObject<CYourClass> when IClassFactory::CreateInstance is called. During creation, the value of the outer unknown is checked. If it is NULL, IUnknown is implemented for a nonaggregated object. If the outer unknown is not NULL, IUnknown is implemented for an aggregated object.

If your class does not specify the DECLARE_POLY_AGGREGATABLE macro, ATL creates an instance of CComObject<CYourClass> for aggregated objects or an instance of CComAggObject<CYourClass> for nonaggregated objects.

The advantage of using CComPolyObject is that you avoid having both CComAggObject and CComObject in your module to handle the aggregated and nonaggregated cases. A single CComPolyObject object handles both cases. Therefore, only one copy of the vtable and one copy of the functions exist in your module. If your vtable is large, this can substantially decrease your module size. However, if your vtable is small, using CComPolyObject can result in a slightly larger module size because it is not optimized for an aggregated or nonaggregated object, as are CComAggObject and CComObject.

The DECLARE_POLY_AGGREGATABLE macro is automatically added to your class definition by the ATL Object Wizard when you create a full control or Internet Explorer control.

If your object is aggregated, IUnknown is implemented by CComAggObject or CComPolyObject. These classes delegate QueryInterface, AddRef, and Release calls to CComObjectRootEx's OuterQueryInterface, OuterAddRef, and OuterRelease to forward to the outer unknown. Typically, you override CComObjectRootEx::FinalConstruct in your class to create any aggregated objects, and override CComObjectRootEx::FinalRelease to free any aggregated objects.

If your object is not aggregated, IUnknown is implemented by CComObject or CComPolyObject. In this case, calls to QueryInterface, AddRef, and Release are delegated to CComObjectRootEx's InternalQueryInterface, InternalAddRef, and InternalRelease to perform the actual operations.

#include <atlcom.h>

Class Members

See Also CComAggObject, CComObject, CComPolyObject


CComObjectRootEx Class Members

Methods

CcomObjectRootEx | Constructor.
InternalAddRef | Increments the reference count for a nonaggregated object.
InternalQueryInterface | Delegates to the IUnknown of a nonaggregated object.
InternalRelease | Decrements the reference count for a nonaggregated object.
Lock | If the thread model is multithreaded, obtains ownership of a critical section object.
Unlock | If the thread model is multithreaded, releases ownership of a critical section object.

CComObjectRootBase Methods

FinalConstruct | Override in your class to create any aggregated objects.
FinalRelease | Override in your class to release any aggregated objects.
OuterAddRef | Increments the reference count for an aggregated object.
OuterQueryInterface | Delegates to the outer IUnknown of an aggregated object.
OuterRelease | Decrements the reference count for an aggregated object.

Data Members

m_critsec | A CComAutoCriticalSection object or CComFakeCriticalSection object, depending on the thread model.
m_dwRef | With m_pOuterUnknown, part of a union. Used when the object is not aggregated to hold the reference count of AddRef and Release.
m_pOuterUnknown | With m_dwRef, part of a union. Used when the object is aggregated to hold a pointer to the outer unknown.

CComObjectRootEx Overview


CComObjectRootEx::CComObjectRootEx

CComObjectRootEx( );

Remarks

The constructor initializes the reference count to 0.


CComObjectRootEx::FinalConstruct

HRESULT FinalConstruct( );

Return Value

One of the standard HRESULT values.

Remarks

Typically, override this method in the class derived from CComObjectRootEx to create any aggregated objects. For example:

class CMyAggObject : public CComObjectRootEx< ... >
{
   DECLARE_GET_CONTROLLING_UNKNOWN
   HRESULT FinalConstruct( )
   {
      return CoCreateInstance(CLSID_SomeServer,
               GetControllingUnknown(), CLSCTX_ALL,
               IID_ISomeServer, &m_pSomeServer);
   }
   ...
};

If the construction fails, you can return an error. You can also use the macro DECLARE_PROTECT_FINAL_CONSTRUCT to protect your outer object from being deleted if (during creation) the internal aggregated object increments the reference count then decrements the count to 0.

By default, CComObjectRootEx::FinalConstruct simply returns S_OK.

Here is a typical way to create an aggregate:

  • Add an IUnknown pointer to your class object and initialize it to NULL in the constructor.

  • Override FinalConstruct to create the aggregate.

  • Use the IUnknown pointer you defined as the parameter to the COM_INTERFACE_ENTRY_AGGREGATE macro.

  • Override FinalRelease to release the IUnknown pointer.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::FinalRelease, DECLARE_GET_CONTROLLING_UNKNOWN


CComObjectRootEx::FinalRelease

void FinalRelease( );

Remarks

Typically, override this method in the class derived from CComObjectRootEx to free any aggregated objects before deletion.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::FinalConstruct


CComObjectRootEx::InternalAddRef

ULONG InternalAddRef( );

Return Value

A value that may be useful for diagnostics and testing.

Remarks

Increments the reference count of a nonaggregated object by 1. If the thread model is multithreaded, InterlockedIncrement is used to prevent more than one thread from changing the reference count at the same time.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::InternalRelease, InterlockedIncrement in the Win32 SDK


CComObjectRootEx::InternalQueryInterface

static HRESULT InternalQueryInterface( void* pThis, const _ATL_INTMAP_ENTRY* pEntries, REFIID iid, void** ppvObject );

Return Value

One of the standard HRESULT values.

Parameters

pThis

[in] A pointer to the object that contains the COM map of interfaces exposed to QueryInterface.

pEntries

[in] A pointer to the _ATL_INTMAP_ENTRY structure that accesses a map of available interfaces.

iid

[in] The GUID of the interface being requested.

ppvObject

[out] A pointer to the interface pointer specified in iid, or NULL if the interface is not found.

Remarks

Retrieves a pointer to the requested interface.

InternalQueryInterface only handles interfaces in the COM map table. If your object is aggregated, InternalQueryInterface does not delegate to the outer unknown. You can enter interfaces into the COM map table with the macro COM_INTERFACE_ENTRY or one of its variants.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::InternalAddRef, CComObjectRootEx::InternalRelease


CComObjectRootEx::InternalRelease

ULONG InternalRelease( );

Return Value

In non-debug builds, always returns 0. In debug builds, returns a value that may be useful for diagnostics or testing.

Remarks

Decrements the reference count of a nonaggregated object by 1. If the thread model is multithreaded, InterlockedDecrement is used to prevent more than one thread from changing the reference count at the same time.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::InternalAddRef, InterlockedDecrement in the Win32 SDK


CComObjectRootEx::Lock

void Lock( );

Remarks

If the thread model is multithreaded, this method calls the Win32 API function EnterCriticalSection, which waits until the thread can take ownership of the critical section object obtained through the m_critsec data member. When the protected code finishes executing, the thread must call Unlock to release ownership of the critical section.

If the thread model is single-threaded, this method does nothing.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::Unlock, CComObjectRootEx::m_critsec


CComObjectRootEx::OuterAddRef

ULONG OuterAddRef( );

Return Value

A value that may be useful for diagnostics and testing.

Remarks

Increments the reference count of the outer unknown of an aggregation.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::OuterRelease, CComObjectRootEx::OuterQueryInterface


CComObjectRootEx::OuterQueryInterface

HRESULT OuterQueryInterface( REFIID iid, void** ppvObject );

Return Value

One of the standard HRESULT values.

Parameters

iid

[in] The GUID of the interface being requested.

ppvObject

[out] A pointer to the interface pointer specified in iid, or NULL if the aggregation does not support the interface.

Remarks

Retrieves an indirect pointer to the requested interface.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::OuterAddRef, CComObjectRootEx::OuterRelease


CComObjectRootEx::OuterRelease

ULONG OuterRelease( );

Return Value

In non-debug builds, always returns 0. In debug builds, returns a value that may be useful for diagnostics or testing.

Remarks

Decrements the reference count of the outer unknown of an aggregation.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::OuterAddRef, CComObjectRootEx::OuterQueryInterface


CComObjectRootEx::Unlock

void Unlock( );

Remarks

If the thread model is multithreaded, this method calls the Win32 API function LeaveCriticalSection, which releases ownership of the critical section object obtained through the m_critsec data member. To obtain ownership, the thread must call Lock. Each call to Lock requires a corresponding call to Unlock to release ownership of the critical section.

If the thread model is single-threaded, this method does nothing.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::Lock, CComObjectRootEx::m_critsec


CComObjectRootEx::m_critsec

_CritSec m_critsec;

Remarks

A CComAutoCriticalSection or CComFakeCriticalSection object. The critical section class _CritSec is determined by the thread model: CComAutoCriticalSection if multithreaded, and CComFakeCriticalSection if single-threaded.

If the thread model is multithreaded, m_critsec is a CComAutoCriticalSection object and provides access to CComAutoCriticalSection's methods and a CRITICAL_SECTION object.

If the thread model is single-threaded, a critical section is not needed and m_critsec is a CComFakeCriticalSection object.

CComObjectRootEx Overview | Class Members

See Also CComObjectRootEx::Lock, CComObjectRootEx::Unlock


CComObjectRootEx::m_dwRef

long m_dwRef;

Remarks

Part of a union that accesses four bytes of memory.

union
{
   long m_dwRef;
   IUnknown* m_pOuterUnknown;
};

If the object is not aggregated, the reference count accessed by AddRef and Release is stored in m_dwRef. If the object is aggregated, the pointer to the outer unknown is stored in m_pOuterUnknown.


CComObjectRootEx::m_pOuterUnknown

IUnknown* m_pOuterUnknown;

Remarks

Part of a union that accesses four bytes of memory.

union
{
   long m_dwRef;
   IUnknown* m_pOuterUnknown;
};

If the object is aggregated, the pointer to the outer unknown is stored in m_pOuterUnknown. If the object is not aggregated, the reference count accessed by AddRef and Release is stored in m_dwRef.


CComObjectStack

template< class Base >
class CComObjectStack : public Base

Parameters

Base

Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interface you want to support on the object.

CComObjectStack is used to create a temporary COM object and provide the object a skeletal implementation of IUnknown. Typically, the object is used as a local variable within one function (that is, pushed onto the stack). Since the object is destroyed when the function finishes, reference counting is not performed to increase efficiency.

The following example shows how to create a COM object used inside a function:

void MyFunc( )
{
   CComObjectStack<CMyObject> Tempobj;
   ...
}

The temporary object Tempobj is pushed onto the stack and automatically disappears when the function finishes.

#include <atlcom.h>

Class Members

See Also CComAggObject, CComObject, CComObjectGlobal


CComObjectStack Class Members

Class Methods

CcomObjectStack Constructor.

IUnknown Methods

AddRef | Returns zero. In debug mode, calls _ASSERTE.
QueryInterface | Returns E_NOINTERFACE. In debug mode, calls _ASSERTE.
Release | Returns zero. In debug mode, calls _ASSERTE.

Data Members

m_hResFinalConstruct Contains the HRESULT returned during construction of the CComObjectStack object.

CComObjectStack Overview


CComObjectStack::AddRef

ULONG AddRef( );

Return Value

Returns zero.

Remarks

Returns zero. In debug mode, calls _ASSERTE.


CComObjectStack::CComObjectStack

CComObjectStack( );

Remarks

The constructor. Calls FinalConstruct and then sets m_hResFinalConstruct to the HRESULT returned by FinalConstruct. If you have not derived your base class from CComObjectRoot, you must supply your own FinalConstruct method. The destructor calls FinalRelease.

CComObjectStack Overview | Class Members

See Also CComObjectRootEx::FinalConstruct


CComObjectStack::QueryInterface

HRESULT QueryInterface( REFIID iid, void** ppvObject ) ;

Return Value

Returns E_NOINTERFACE.

Parameters

iid

[in] The IID of the interface being requested.

ppvObject

[out] A pointer to the interface pointer identified by iid, or NULL if the interface is not found.

Remarks

Returns E_NOINTERFACE. In debug mode, calls _ASSERTE.


CComObjectStack::Release

ULONG Release( );

Return Value

Returns zero.

Remarks

Returns zero. In debug mode, calls _ASSERTE.


CComObjectStack::m_hResFinalConstruct

HRESULT m_hResFinalConstruct( );

Remarks

Contains the HRESULT returned from calling FinalConstruct during construction of the CComObjectStack object.

CComObjectStack Overview | Class Members

See Also CComObjectRootEx::FinalConstruct


CComObjectThreadModel

#if defined( _ATL_SINGLE_THREADED )
 typedef CComSingleThreadModel CComObjectThreadModel;

#elif defined( _ATL_APARTMENT_THREADED )
 typedef CComSingleThreadModel CComObjectThreadModel;

#else
 typedef CComMultiThreadModel CComObjectThreadModel;

#endif

Depending on the threading model used by your application, the typedef name CComObjectThreadModel references either CComSingleThreadModel or CComMultiThreadModel. These classes provide additional typedef names to reference a critical section class.

Note CComObjectThreadModel does not reference class CComMultiThreadModelNoCS.

Using CComObjectThreadModel frees you from specifying a particular threading model class. Regardless of the threading model being used, the appropriate methods will be called.

In addition to CComObjectThreadModel, ATL provides the typedef name CComGlobalsThreadModel. The class referenced by each typedef depends on the threading model used, as shown in the following table:

 | Threading Model
typedef | Single | Apartment | Free
CcomObjectThreadModel | S | S | M
CcomGlobalsThreadModel | S | M | M

S=CComSingleThreadModel; M=CComMultiThreadModel

Use CComObjectThreadModel within a single object class. Use CComGlobalsThreadModel in an object that is either globally available to your program, or when you wish to protect module resources across multiple threads.

#include <atlbase.h>

See Also CComObjectRootEx


CComPolyObject

template< class contained >
class CComPolyObject : public IUnknown, public CComObjectRootEx< contained::_ThreadModel::ThreadModelNoCS >

Parameters

contained

Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interfaces you want to support on the object.

CComPolyObject implements IUnknown for an aggregated or nonaggregated object.

When an instance of CComPolyObject is created, the value of the outer unknown is checked. If it is NULL, IUnknown is implemented for a nonaggregated object. If the outer unknown is not NULL, IUnknown is implemented for an aggregated object.

The advantage of using CComPolyObject is that you avoid having both CComAggObject and CComObject in your module to handle the aggregated and nonaggregated cases. A single CComPolyObject object handles both cases. This means only one copy of the vtable and one copy of the functions exist in your module. If your vtable is large, this can substantially decrease your module size. However, if your vtable is small, using CComPolyObject can result in a slightly larger module size because it is not optimized for an aggregated or nonaggregated object, as are CComAggObject and CComObject.

If the DECLARE_POLY_AGGREGATABLE macro is specified in your object's class definition, CComPolyObject will be used to create your object. DECLARE_POLY_AGGREGATABLE will automatically be declared if you use the ATL Object Wizard to create a full control or Internet Explorer control.

If aggregated, the CComPolyObject object has its own IUnknown, separate from the outer object's IUnknown, and maintains its own reference count. CComPolyObject uses CComContainedObject to delegate to the outer unknown.

For more information about aggregation, see the article Fundamentals of ATL COM Objects.

#include <atlcom.h>

Class Members

See Also CComObjectRootEx, DECLARE_POLY_AGGREGATABLE


CComPolyObject Class Members

Class Methods

CcomPolyObject | Constructor.
FinalConstruct | Performs final initialization of m_contained.
FinalRelease | Performs final destruction of m_contained.

IUnknown Methods

AddRef | Increments the reference count on the object.
QueryInterface | Retrieves a pointer to the requested interface.
Release | Decrements the reference count on the object.

Data Members

m_contained Delegates Iunknown calls to the outer unknown if the object is aggregated or to the IUnknown of the object if the object is not aggregated.

CComPolyObject Overview


CComPolyObject::AddRef

ULONG AddRef( );

Return Value

A value that may be useful for diagnostics or testing.

Remarks

Increments the reference count on the object.

CComPolyObject Overview | Class Members

See Also CComPolyObject::Release


CComPolyObject::CComPolyObject

CComPolyObject( void* pv );

Parameters

pv

[in] A pointer to the outer unknown if the object is to be aggregated, or NULL if the object if the object is not aggregated.

Remarks

The constructor. Initializes the CComContainedObject data member, m_contained, and increments the module lock count.

The destructor decrements the module lock count.

CComPolyObject Overview | Class Members

See Also CComPolyObject::FinalConstruct, CComPolyObject::FinalRelease


CComPolyObject::FinalConstruct

HRESULT FinalConstruct( );

Return Value

A standard HRESULT value.

Remarks

Called during the final stages of object construction, this method performs any final initialization on the m_contained data member.

CComPolyObject Overview | Class Members

See Also CComObjectRootEx::FinalConstruct, CComPolyObject::FinalRelease


CComPolyObject::FinalRelease

void FinalRelease( );

Remarks

Called during object destruction, this method frees the m_contained data member.

CComPolyObject Overview | Class Members

See Also CComObjectRootEx::FinalRelease, CComPolyObject::FinalConstruct


CComPolyObject::QueryInterface

HRESULT QueryInterface( REFIID iid, void** ppvObject );

Return Value

A standard HRESULT value.

Parameters

iid

[in] The identifier of the interface being requested.

ppvObject

[out] A pointer to the interface pointer identified by iid. If the object does not support this interface, ppvObject is set to NULL.

Remarks

Retrieves a pointer to the requested interface.

For an aggregated object, if the requested interface is IUnknown, QueryInterface returns a pointer to the aggregated object's own IUnknown and increments the reference count. Otherwise, this method queries for the interface through the CComContainedObject data member, m_contained.


CComPolyObject::Release

ULONG Release( );

Return Value

In debug builds, Release returns a value that may be useful for diagnostics or testing. In nondebug builds, Release always returns 0.

Remarks

Decrements the reference count on the object.

CComPolyObject Overview | Class Members

See Also CComPolyObject::AddRef


CComPolyObject::m_contained

CComContainedObject< contained > m_contained;

Parameters

contained

[in] Your class, derived from CComObjectRoot or CComObjectRootEx, as well as from any other interfaces you want to support on the object.

Remarks

A CComContainedObject object derived from your class. IUnknown calls through m_contained are delegated to the outer unknown if the object is aggregated, or to the IUnknown of this object if the object is not aggregated.


CComPtr

template< class T >
class CComPtr

Parameters

T

A COM interface specifying the type of pointer to be stored.

ATL uses CComPtr and CComQIPtr to manage COM interface pointers. Both classes perform automatic reference counting through calls to AddRef and Release. Overloaded operators handle pointer operations. CComQIPtr additionally supports automatic querying of interfaces though QueryInterface.

The following code is from CFirePropNotifyEvent::FireOnRequestEdit:

static HRESULT FireOnRequestEdit(IUnknown* pUnk, DISPID dispID)
{
   CComQIPtr<IConnectionPointContainer,
            &IID_IConnectionPointContainer> pCPC(pUnk);
   if (!pCPC)
      return S_OK;

   CComPtr<IConnectionPoint> pCP;
   pCPC->FindConnectionPoint(IID_IPropertyNotifySink, &pCP);
   if (!pCP)
      return S_OK;

   ...
};

This example illustrates the following:

  • The constructor for the CComQIPtr object, pCPC, calls QueryInterface on pUnk to obtain the IConnectionPointContainer pointer. The retrieved pointer is stored in pCPC.

  • The function declares the CComPtr object, pCP, to hold an IConnectionPoint pointer.

  • IConnectionPointContainer::FindConnectionPoint is called through pCPC to retrieve an IConnectionPoint pointer via pCP.

#include <atlbase.h>

Class Members

See Also CComPtr::CComPtr, CComQIPtr::CComQIPtr


CComPtr Class Members

Methods

CComPtr | Constructor. Initializes the member pointer.
Detach | Detaches the member pointer.
Release | Decrements the reference count on the object pointed to by the member pointer.
IsEqualObject | Compares two objects for equivalence.
Attach | Attaches a pointer that already has its reference count incremented.
CopyTo | Copies the internal pointer to a target pointer and calls AddRef on the pointer if the copy is successful.
SetSite | Sets the site for the internal pointer.
Advise | Establishes a connection point with the object pointed to by the smart pointer.
CoCreateInstance | Creates an instance of an object in a type-safe manner.
QueryInterface | Calls QueryInterface on the internal pointer in a type-safe manner.

Operators

operator T* | Converts a CComPtr object to a T*.
operator * | Returns the dereferenced value of the member pointer.
operator & | Returns the address of the member pointer.
operator -> | Returns the member pointer.
operator = | Assigns a pointer to the member pointer.
operator ! | Returns TRUE or FALSE, depending on whether the member pointer is NULL.
operator < | Returns TRUE or FALSE, depending on whether the pointer is less than another pointer.
operator == | Compares two pointers for equivalence.

Data Members

p The managed COM interface pointer of type T*.

CComPtr Overview


CComPtr::Advise

HRESULT Advise( IUnknown* pUnk, const IID& iid, LPDWORD pdw );

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK

  • E_POINTER

  • CONNECT_E_ADVISELIMIT

  • CONNECT_E_CANNOTCONNECT

  • E_FAIL

See IConnectionPoint::Advise in the Platform SDK for a description of these return values.

Parameters

pUnk

[in] Pointer to the IUnknown interface of the sink object. This object sinks events from the event source of the object referred to by the smart pointer.

iid

[in] IID for the outgoing interface managed by the connection point.

pdw

[out] Returned token that uniquely identifies this connection.

Remarks

Establishes a connection point with the object pointed to by this smart pointer.


CComPtr::Attach

void Attach( T* p2 );

Parameters

p2

[in] A pointer.

Remarks

Attaches a pointer without incrementing its reference count. The pointer's reference count has had its reference count incremented by calling IUnknown::AddRef.


CComPtr::CComPtr

CComPtr( );

CComPtr( T* lp );

CComPtr ( const CComPtr< T >& lp );

Parameters

lp

[in] Used to initialize the interface pointer, p.

T

[in] A COM interface.

Remarks

The default constructor sets p to NULL. The copy constructor sets p to the member pointer of lp and calls AddRef through p. If you pass a pointer type derived from T, the constructor sets p to the T* parameter and calls AddRef.

The destructor calls Release through p.


CComPtr::CoCreateInstance

HRESULT CoCreateInstance( REFCLSID rclsid, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL );

HRESULT CoCreateInstance( LPCOLESTR szProgID, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL );

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK An instance of the specified object class was successfully created.

  • REGDB_E_CLASSNOTREG A specified class is not registered in the registration database. Also can indicate that the type of server you requested in the CLSCTX enumeration is not registered or the values for the server types in the registry are corrupt.

  • CLASS_E_NOAGGREGATION This class cannot be created as part of an aggregate.

See CoCreateInstance in the Platform SDK for a description of possible return values.

Parameters

rclsid

[in] CLSID associated with the data and code that will be used to create the object.

pUnkOuter

[in] If NULL, indicates that the object is not being created as part of an aggregate. If non-NULL, a pointer to the aggregate object's IUnknown interface (the controlling IUnknown).

dwClsContext

[in] Context in which the code that manages the newly created object will run.

szProgID

[in] ProgID associated with the data and code that will be used to create the object.

Remarks

Creates an instance of an object in a type-safe manner.


CComPtr::CopyTo

HRESULT CopyTo( T** ppT );

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK The pointer was copied successfully.

  • E_POINTER ppT is NULL.

Parameters

ppT

[in] Pointer to the target pointer.

Remarks

Copies the internal pointer to a target pointer. The pointer's reference count is incremented if successful. Returns an error if ppT is NULL.


CComPtr::Detach

T* Detach( );

Return Value

A pointer to the member to be detached.

Remarks

Returns the member pointer and detaches it from this CComPtr object by setting p to NULL. The pointer's reference count is not decremented.


CComPtr::IsEqualObject

bool IsEqualObject( IUnknown* pOther );

Return value

Returns TRUE if the two objects are equal; otherwise, FALSE.

Parameters

pOther

[in] Pointer to the other object.

Remarks

Compares the two objects for equivalence. This method performs IUnknown comparisons.


CComPtr::QueryInterface

template <class Q>
HRESULT QueryInterface( Q** pp ) const

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK The interface was retrieved successfully.

  • E_NOINTERFACE The object referred to by the pointer contained in this smart pointer does not implement the requested interface.

Parameters

Q

[in] Type of the interface.

pp

[out] Pointer to the resulting interface pointer.

Remarks

Calls QueryInterface on the internal pointer in a type-safe manner.


CComPtr::Release

void Release( );

Remarks

Calls IUnknown::Release through p and sets p to NULL.


CComPtr::SetSite

HRESULT SetSite( IUnknown* punkParent );

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK The site was set successfully.

  • E_POINTER The pointer contained by this smart pointer is NULL.

  • E_NOINTERFACE The pointer contained by this smart pointer does not implement IObjectWithSite.

Parameters

punkParent

[in] Pointer to the IUnknown interface pointer of the site managing this object.

Remarks

Sets the site for the internal pointer to punkParent. The internal pointer must point to an object that implements IObjectWithSite.


CComPtr::operator T*

operator T*( );

Remarks

Converts a CComPtr object to a T*.


CComPtr::operator *

T& operator *( );

Remarks

Returns the dereferenced value of the interface pointer, p.

Note The operation will assert if p is NULL.


CComPtr::operator &

T** operator &( );

Remarks

Returns the address of the interface pointer, p.

Note The operation will assert if p is non-NULL.


CComPtr::operator ->

T* operator ->( );

Remarks

Returns the interface pointer, p.

Note The operation will assert if p is NULL.


CComPtr::operator =

T* operator =( T* lp );

T* operator =( const CComPtr< T >& lp );

Remarks

When assigning a pointer type derived from T, the operator sets p to the given T*. When assigning a CComPtr, the operator sets p to the member pointer of lp.


CComPtr::operator !

bool operator !( );

Remarks

Returns true if p is NULL; otherwise, false.


CComPtr::operator <

bool operator <( T* pT ) const;

Return value

Returns true if the internal pointer is less than another pointer; otherwise, false.

Parameters

pT

[in] Pointer to be compared with the internal pointer.

Remarks

Checks if the internal pointer is less than another pointer.


CComPtr::operator ==

bool operator ==( T* pT ) const;

Return value

Returns true if the two pointers are equivalent; otherwise, false.

Parameters

pT

[in] Pointer to be compared with the internal pointer.

Remarks

Compares two pointers for equivalence.


CComPtr::p

T* p;

Remarks

Points to the specified COM interface.


CComQIPtr

template< class T, const IID* piid >
class CComQIPtr

Parameters

T

A COM interface specifying the type of pointer to be stored.

piid

A pointer to the IID of T.

ATL uses CComQIPtr and CComPtr to manage COM interface pointers. Both classes perform automatic reference counting through calls to AddRef and Release. Overloaded operators handle pointer operations. CComQIPtr additionally supports automatic querying of interfaces though QueryInterface.

For an example of using CComQIPtr and CComPtr, see the CComPtr class overview.

Note Do not use CComQIPtr<IUnknown, &IID_IUnknown>. Rather, use CComPtr<IUnknown>.

#include <atlbase.h>

Class Members

See Also CComPtr::CComPtr, CComQIPtr::CComQIPtr


CComQIPtr Class Members

Methods

CComQIPtr | Constructor. Initializes the member pointer.
Detach | Detaches the member pointer.
Release | Decrements the reference count on the object pointed to by the member pointer.
IsEqualObject | Compares two objects for equivalence.
Attach | Attaches a pointer that has previously had AddRef called.
CopyTo | Copies the internal pointer to a target pointer and calls AddRef on the pointer if the copy is successful.
SetSite | Sets the site for the internal pointer.
Advise | Establishes a connection point with the object pointed to by the smart pointer.
CoCreateInstance | Creates an instance in a type-safe manner.
QueryInterface | Queries an interface on the internal pointer in a type-safe manner.

Operators

operator T* | Converts a CComQIPtr object to a T*.
operator * | Returns the dereferenced value of the member pointer.
operator & | Returns the address of the member pointer.
operator -> | Returns the member pointer.
operator = | Assigns a pointer to the member pointer.
operator ! | Returns TRUE or FALSE, depending on whether the member pointer is NULL.
operator < | Returns TRUE or FALSE, depending on whether a pointer is less than another pointer.
operator == | Compares two pointers for equivalence.

Data Members

p The managed COM interface pointer of type T*.

CComQIPtr Overview


CComQIPtr::Advise

HRESULT Advise( IUnknown* pUnk, const IID& iid, LPDWORD pdw );

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK

  • E_POINTER

  • CONNECT_E_ADVISELIMIT

  • CONNECT_E_CANNOTCONNECT

  • E_FAIL

See IConnectionPoint::Advise in the Platform SDK for a description of these return values.

Parameters

pUnk

[in] Pointer to the IUnknown interface of the sink object. This object sinks events from the event source of the object referred to by the smart pointer.

iid

[in] IID for the outgoing interface managed by the connection point.

pdw

[out] Returned token that uniquely identifies this connection.

Remarks

Establishes a connection point with the object pointed to by this smart pointer.


CComQIPtr::Attach

void Attach( T* p2 );

Parameters

p2

[in] A pointer.

Remarks

Attaches a pointer without incrementing its reference count. The pointer’s reference count has had its reference count incremented by calling IUnknown::AddRef.


CComQIPtr::CComQIPtr

CComQIPtr( );

CComQIPtr( T* lp );

CComQIPtr( const CComQIPtr< T, piid >& lp );

CComQIPtr( IUnknown* lp );

Parameters

lp

[in] Used to initialize the interface pointer, p.

T

[in] A COM interface.

piid

[in] A pointer to the IID of T.

Remarks

The default constructor sets p to NULL. The copy constructor sets p to the member pointer of lp and calls AddRef through p.

If you pass a pointer type derived from T, the constructor sets p to the T* parameter and calls AddRef. If you pass a pointer type not derived from T, the constructor calls QueryInterface to set p to an interface pointer corresponding to piid.

The destructor calls Release through p.


CComQIPtr::CoCreateInstance

HRESULT CoCreateInstance( REFCLSID rclsid, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL );

HRESULT CoCreateInstance( LPCOLESTR szProgID, LPUNKNOWN pUnkOuter = NULL, DWORD dwClsContext = CLSCTX_ALL );

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK

  • REGDB_E_CLASSNOTREG

  • CLASS_E_NOAGGREGATION

See CoCreateInstance in the Platform SDK for a list of possible return values.

Parameters

rclsid

[in] CLSID associated with the data and code that will be used to create the object.

pUnkOuter

[in] If NULL, indicates that the object is not being created as part of an aggregate. If non-NULL, pointer to the aggregate object's IUnknown interface (the controlling IUnknown).

dwClsContext

[in] Context in which the code that manages the newly created object will run.

szProgID

[in] ProgID associated with the data and code that will be used to create the object.

Remarks

Creates an instance of an object in a type-safe manner.


CComQIPtr::CopyTo

HRESULT CopyTo( T** ppT );

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK The pointer was copied successfully.

  • E_POINTER ppT is NULL.

Parameters

ppT

[in] Pointer to the target pointer.

Remarks

Copies the internal pointer to a target pointer. The pointer's reference count is incremented if successful. Returns an error if ppT is NULL.


CComQIPtr::Detach

T* Detach( );

Return Value

A pointer to the member to be detached.

Remarks

Returns the member pointer and detaches it from this CComQIPtr object by setting p to NULL. The pointer’s reference count is not decremented.


CComQIPtr::IsEqualObject

bool IsEqualObject( IUnknown* pOther );

Return value

Returns TRUE if the two objects are equal; otherwise, FALSE.

Parameters

pOther

[in] Pointer to the other object.

Remarks

Compares the two objects for equivalence. This method performs IUnknown comparisons.


CComQIPtr::QueryInterface

template <class Q>
HRESULT QueryInterface( Q** pp ) const;

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK The interface was retrieved successfully.

  • E_NOINTERFACE The object referred to by the pointer contained in this smart pointer does not implement the requested interface

Parameters

Q

[in] Type of the interface.

pp

[out] Pointer to the resulting interface pointer.

Remarks

Calls QueryInterface on the internal pointer in a type-safe manner.


CComQIPtr::Release

void Release( );

Remarks

Calls IUnknown::Release through p and sets p to NULL.


CComQIPtr::SetSite

HRESULT SetSite( IUnknown* punkParent );

Return value

A standard HRESULT value. Can be one of the following values:

  • S_OK The site was set successfully.

  • E_POINTER The pointer contained by this smart pointer is NULL.

  • E_NOINTERFACE The pointer contained by this smart pointer does not implement IObjectWithSite.

Parameters

punkParent

[in] Pointer to the IUnknown interface pointer of the site managing this object.

Remarks

Sets the site for the internal pointer to punkParent. The internal pointer must point to an object that implements IObjectWithSite.


CComQIPtr::operator T*

operator T*( );

Remarks

Converts a CComQIPtr object to a T*.


CComQIPtr::operator *

T& operator *( );

Remarks

Returns the dereferenced value of the interface pointer, p.

Note The operation will assert if p is NULL.


CComQIPtr::operator &

T** operator &( );

Remarks

Returns the address of the interface pointer, p.

Note The operation will assert if p is non-NULL.


CComQIPtr::operator ->

T* operator ->( );

Remarks

Returns the interface pointer, p.

Note The operation will assert if p is NULL.


CComQIPtr::operator =

T* operator =( T* lp );

T* operator =( const CComQIPtr< T, piid >& lp );

T* operator =( IUnknown* lp );

Remarks

When assigning a pointer type derived from T, the operator sets p to the given T*. When assigning a CComQIPtr, the operator sets p to the member pointer of lp.

When assigning a pointer type not derived from T, the operator calls QueryInterface to set p to an interface pointer corresponding to piid. If QueryInterface fails, p is set to NULL.


CComQIPtr::operator !

bool operator !( );

Remarks

Returns true if p is NULL; otherwise, false.


CComQIPtr::operator <

bool operator <( T* pT ) const;

Return value

Returns true if the internal pointer is less than another pointer; otherwise, false.

Parameters

pT

[in] Pointer to be compared with the internal pointer.

Remarks

Checks if the internal pointer is less than another pointer.


CComQIPtr::operator ==

bool operator ==( T* pT ) const;

Return value

Returns true if the two pointers are equivalent; otherwise, false.

Parameters

pT

[in] Pointer to be compared with the internal pointer.

Remarks

Compares two pointers for equivalence.


CComQIPtr::p

T* p;

Remarks

Points to the specified COM interface.


CComSimpleThreadAllocator

class CComSimpleThreadAllocator

CComSimpleThreadAllocator manages thread selection for CComAutoThreadModule. CComSimpleThreadAllocator::GetThread simply cycles through each thread and returns the next one in the sequence.

#include <atlbase.h>

Class Members

See Also CComApartment


CComSimpleThreadAllocator Class Members

Methods

GetThread Selects a thread.

CComSimpleThreadAllocator Overview


CComSimpleThreadAllocator::GetThread

int GetThread( CComApartment* pApt, int nThreads );

Return Value

An integer between zero and nThreads – 1. Identifies one of the threads in the EXE module.

Parameters

pApt

[in] Not used in ATL's default implementation.

nThreads

[in] The maximum number of threads in the EXE module.

Remarks

Selects a thread by specifying the next thread in the sequence. You can override GetThread to provide a different method of selection or to make use of the pApt parameter.

GetThread is called by CComAutoThreadModule::CreateInstance.

CComSimpleThreadAllocator Overview | Class Members

See Also CComApartment


CComSingleThreadModel

class CComSingleThreadModel

CComSingleThreadModel provides methods for incrementing and decrementing the value of a variable. Unlike CComMultiThreadModel and CComMultiThreadModelNoCS, these methods are not thread-safe.

Typically, you use CComSingleThreadModel through one of two typedef names, either CComObjectThreadModel or CComGlobalsThreadModel. The class referenced by each typedef depends on the threading model used, as shown in the following table:

 | Threading Model
typedef | Single | Apartment | Free
CComObjectThreadModel | S | S | M
CComGlobalsThreadModel | S | M | M

S=CComSingleThreadModel; M=CComMultiThreadModel

CComSingleThreadModel itself defines three typedef names. ThreadModelNoCS references CComSingleThreadModel. AutoCriticalSection and CriticalSection reference class CComFakeCriticalSection, which provides empty methods associated with obtaining and releasing ownership of a critical section.

#include <atlbase.h>

Class Members


CComSingleThreadModel Class Members

Methods

Decrement | Decrements the value of the specified variable. This implementation is not thread-safe.
Increment | Increments the value of the specified variable. This implementation is not thread-safe.

Typedefs

AutoCriticalSection | References class CComFakeCriticalSection.
CriticalSection | References class CComFakeCriticalSection.
ThreadModelNoCS | References CcomSingleThreadModel.

CComSingleThreadModel Overview


CComSingleThreadModel::Decrement

static ULONG Decrement( LPLONG p );

Return Value

The result of the decrement.

Parameters

p

[in] Pointer to the variable to be decremented.

Remarks

This static method decrements the value of the variable pointed to by p.

CComSingleThreadModel Overview | Class Members

See Also CComSingleThreadModel::Increment


CComSingleThreadModel::Increment

static ULONG Increment( LPLONG p );

Return Value

The result of the increment.

Parameters

p

[in] Pointer to the variable to be incremented.

Remarks

This static method decrements the value of the variable pointed to by p.

CComSingleThreadModel Overview | Class Members

See Also CComSingleThreadModel::Decrement


CComSingleThreadModel::AutoCriticalSection

typedef CComFakeCriticalSection AutoCriticalSection;

Remarks

When using CComSingleThreadModel, the typedef name AutoCriticalSection references class CComFakeCriticalSection. Because CComFakeCriticalSection does not provide a critical section, its methods do nothing.

CComMultiThreadModel and CComMultiThreadModelNoCS also contain definitions for AutoCriticalSection. The following table shows the relationship between the threading model class and the critical section class referenced by AutoCriticalSection:

Class defined in | Class referenced
CcomSingleThreadModel | CComFakeCriticalSection
CcomMultiThreadModel | CComAutoCriticalSection
CcomMultiThreadModelNoCS | CComFakeCriticalSection

In addition to AutoCriticalSection, you can use the typedef name CriticalSection. You should not specify AutoCriticalSection in global objects or static class members if you want to eliminate the CRT startup code.

Example

See CComMultiThreadModel::AutoCriticalSection.

CComSingleThreadModel Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel, CComSingleThreadModel::ThreadModelNoCS


CComSingleThreadModel::CriticalSection

typedef CComFakeCriticalSection CriticalSection;

Remarks

When using CComSingleThreadModel, the typedef name CriticalSection references class CComFakeCriticalSection. Because CComFakeCriticalSection does not provide a critical section, its methods do nothing.

CComMultiThreadModel and CComMultiThreadModelNoCS also contain definitions for CriticalSection. The following table shows the relationship between the threading model class and the critical section class referenced by CriticalSection:

Class defined in | Class referenced
CcomSingleThreadModel | CcomFakeCriticalSection
CcomMultiThreadModel | CcomCriticalSection
CcomMultiThreadModelNoCS | CcomFakeCriticalSection

In addition to CriticalSection, you can use the typedef name AutoCriticalSection. You should not specify AutoCriticalSection in global objects or static class members if you want to eliminate the CRT startup code.

Example

See CComMultiThreadModel::AutoCriticalSection.

CComSingleThreadModel Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel, CComSingleThreadModel::ThreadModelNoCS


CComSingleThreadModel::ThreadModelNoCS

typedef CComSingleThreadModel ThreadModelNoCS;

Remarks

When using CComSingleThreadModel, the typedef name ThreadModelNoCS simply references CComSingleThreadModel.

CComMultiThreadModel and CComMultiThreadModelNoCS also contain definitions for ThreadModelNoCS. The following table shows the relationship between the threading model class and the class referenced by ThreadModelNoCS:

Class defined in | Class referenced
CcomSingleThreadModel | CcomSingleThreadModel
CcomMultiThreadModel | CcomMultiThreadModelNoCS
CcomMultiThreadModelNoCS | CcomMultiThreadModelNoCS

Example

See CComMultiThreadModel::AutoCriticalSection.

CComSingleThreadModel Overview | Class Members

See Also CComObjectThreadModel, CComGlobalsThreadModel


CComTearOffObject

template< class Base >
class CComTearOffObject : public Base

Parameters

Base

Your tear-off class, derived from CComTearOffObjectBase and the interfaces you want your tear-off object to support.

ATL implements its tear-off interfaces in two phases — the CComTearOffObjectBase methods handle the reference count and QueryInterface, while CComTearOffObject implements IUnknown.

CComTearOffObject implements a tear-off interface as a separate object that is instantiated only when that interface is queried for. The tear-off is deleted when its reference count becomes zero. Typically, you build a tear-off interface for an interface that is rarely used, since using a tear-off saves a vtable pointer in all the instances of your main object.

You should derive the class implementing the tear-off from CComTearOffObjectBase and from whichever interfaces you want your tear-off object to support. CComTearOffObjectBase is templatized on the owner class and the thread model. The owner class is the class of the object for which a tear-off is being implemented. If you do not specify a thread model, the default thread model is used.

You should create a COM map for your tear-off class. When ATL instantiates the tear-off, it will create CComTearOffObject<CYourTearOffClass> or CComCachedTearOffObject<CYourTearOffClass>.

For example, in the BEEPER sample, the CBeeper2 class is the tear-off class and the CBeeper class is the owner class:

class CBeeper2 : public ISupportErrorInfo,
                 public CComTearOffObjectBase<CBeeper>
{
public:
   CBeeper2() {}
   STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid)
   {
      return (InlineIsEqualGUID(IID_IBeeper,riid)) ?
              S_OK : S_FALSE;
   }

   BEGIN_COM_MAP(CBeeper2)
      COM_INTERFACE_ENTRY(ISupportErrorInfo)
   END_COM_MAP()
};

class CBeeper :
   public IDispatchImpl<IBeeper, &IID_IBeeper,
                        &LIBID_BeeperLib>,
   public CComObjectRoot,
   public CComCoClass<CBeeper, &CLSID_Beeper>
{
public:
   CBeeper();
   BEGIN_COM_MAP(CBeeper)
      COM_INTERFACE_ENTRY(IDispatch)
      COM_INTERFACE_ENTRY(IBeeper)
      COM_INTERFACE_ENTRY_TEAR_OFF(IID_ISupportErrorInfo,
                             CBeeper2)
   END_COM_MAP()
...
};

#include <atlcom.h>

Class Members

See Also CComCachedTearOffObject


CComTearOffObject Class Members

Methods

AddRef | Increments the reference count for a CcomTearOffObject object.
CcomTearOffObject | Constructor.
QueryInterface | Returns a pointer to the requested interface on either your tear-off class or the owner class.
Release | Decrements the reference count for a CcomTearOffObject object and destroys it.

CComTearOffObjectBase Methods

CComTearOffObjectBase Constructor.

CComTearOffObjectBase Data Members

m_pOwner A pointer to a CcomObject derived from the owner class.

CComTearOffObject Overview


CComTearOffObject::AddRef

ULONG AddRef( );

Return Value

A value that may be useful for diagnostics and testing.

Remarks

Increments the reference count of the CComTearOffObject object by 1.

CComTearOffObject Overview | Class Members

See Also CComTearOffObject::Release


CComTearOffObject::CComTearOffObject

CComTearOffObject( void* p );

Parameters

p

[in] Pointer that will be converted to a pointer to a CComObject<Owner> object.

Remarks

The constructor. Increments the owner's reference count by 1.

CComTearOffObject Overview | Class Members

See Also CComCachedTearOffObject::CComCachedTearOffObject


CComTearOffObject::CComTearOffObjectBase

CComTearOffObjectBase( );

Remarks

The constructor. Initializes the m_pOwner member to NULL.

CComTearOffObject Overview | Class Members

See Also CComCachedTearOffObject::CComCachedTearOffObject


CComTearOffObject::QueryInterface

HRESULT QueryInterface( REFIID iid , void** ppvObject );

Return Value

A standard HRESULT value.

Parameters

iid [in] The IID of the interface being requested.

ppvObject [out] A pointer to the interface pointer identified by iid, or NULL if the interface is not found.

Remarks

Retrieves a pointer to the requested interface. Queries first for interfaces on your tear-off class. If the interface is not there, queries for the interface on the owner object. If the requested interface is IUnknown, returns the IUnknown of the owner.

CComTearOffObject Overview | Class Members

See Also CComTearOffObject::AddRef, CComTearOffObject::Release


CComTearOffObject::Release

ULONG Release( );

Return Value

In non-debug builds, always returns 0. In debug builds, returns a value that may be useful for diagnostics or testing.

Remarks

Decrements the reference count by 1 and, if the reference count is 0, deletes the CComTearOffObject.

CComTearOffObject Overview | Class Members

See Also CComTearOffObject::AddRef


CComTearOffObject::m_pOwner

CComObject<Owner>* m_pOwner;

Parameters

Owner

[in] The class for which a tear-off is being implemented.

Remarks

A pointer to a CComObject object derived from Owner. The pointer is initialized to NULL during construction.

CComTearOffObject Overview | Class Members

See Also CComTearOffObject::CComTearOffObjectBase


CComUnkArray

template< unsigned int nMaxSize >
class CComUnkArray

Parameters

nMaxSize

The maximum number of IUnknown pointers that can be held in the static array.

CComUnkArray holds a fixed number of IUnknown pointers, each an interface on a connection point. CComUnkArray can be used as a parameter to the IConnectionPointImpl template class. CComUnkArray<1> is a template specialization of CComUnkArray that has been optimized for one connection point.

The CComUnkArray methods begin and end can be used to loop through all connection points (for example, when an event is fired).

See Adding Connection Points to an Object for details on automating creation of connection point proxies.

#include <atlcom.h>

Class Members

See Also CComDynamicUnkArray


CComUnkArray Class Members

Methods

begin | Returns a pointer to the first IUnknown pointer in the collection.
CComUnkArray | Constructor.
end | Returns a pointer to one past the last IUnknown pointer in the collection.

CComUnkArray Overview


CComUnkArray::begin

IUnknown** begin( );

Return Value

A pointer to an IUnknown interface pointer.

Remarks

Returns a pointer to beginning of the collection of IUnknown interface pointers.

The collection contains pointers to interfaces stored locally as IUnknown. You cast each IUnknown interface to the real interface type and then call through it. You do not need to query for the interface first.

Before using the IUnknown interface, you should check that it is not NULL.

CComUnkArray Overview | Class Members

See Also CComUnkArray::end, CComDynamicUnkArray::begin


CComUnkArray::CComUnkArray

CComUnkArray( );

Remarks

The constructor. Sets the collection to hold nMaxSize IUnknown pointers, and initializes the pointers to NULL.


CComUnkArray::end

IUnknown** end( );

Return Value

A pointer to an IUnknown interface pointer.

Remarks

Returns a pointer to one past the last IUnknown pointer in the collection.

The CComUnkArray methods begin and end can be used to loop through all connection points, for example, when an event is fired.

IUnknown** p = m_vec.begin();
while(p != m_vec.end())
{
   // Do something with *p
   p++;
}

CComUnkArray Overview | Class Members

See Also CComUnkArray::begin, CComDynamicUnkArray::end


CComVariant

class CComVariant : public tagVARIANT

CComVariant wraps the VARIANT type, which consists of a tagged union, as well as a member indicating the value type stored in the union. VARIANTs are typically used in Automation.

#include <atlbase.h>

Class Members


CComVariant Class Members

Methods

Attach | Attaches a VARIANT to the CcomVariant object.
CComVariant | Constructor.
ChangeType | Converts the CComVariant object to a new type.
Clear | Clears the CComVariant object.
Copy | Copies a VARIANT to the CcomVariant object.
Detach | Detaches the underlying VARIANT from the CComVariant object.
ReadFromStream | Loads a VARIANT from a stream.
WriteToStream | Saves the underlying VARIANT to a stream.

Operators

operator = | Assigns a value to the CcomVariant object.
operator == | Indicates whether the CcomVariant object equals the specified VARIANT.
operator != | Indicates whether the CcomVariant object does not equal the specified VARIANT.

CComVariant Overview


CComVariant::Attach

HRESULT Attach( VARIANT* pSrc );

Return Value

A standard HRESULT value.

Parameters

pSrc

[in] Points to the VARIANT to be attached to the object.

Remarks

Attaches the specified VARIANT to the CComVariant object. Attach sets the variant type of the object to VT_EMPTY.

CComVariant Overview | Class Members

See Also CComVariant::Detach


CComVariant::CComVariant

CComVariant( );
CComVariant( const CComVariant& varSrc );
CComVariant( const VARIANT& varSrc );
CComVariant( LPCOLESTR lpsz );
CComVariant( LPCSTR lpsz );
CComVariant( BSTR bstrSrc );
CComVariant( bool bSrc );
CComVariant( int nSrc );
CComVariant( BYTE nSrc );
CComVariant( short nSrc );
CComVariant( long nSrc, VARTYPE vtSrc = VT_I4 );
CComVariant( float fltSrc );
CComVariant( double dblSrc );
CComVariant( CY cySrc );
CComVariant( IDispatch* pSrc );
CComVariant( IUnknown* pSrc );

Parameters

varSrc

[in] The CComVariant or VARIANT used to initialize the CComVariant object.

lpsz

[in] The character string used to initialize the CComVariant object. The Unicode version specifies an LPCOLESTR; the ANSI version specifies an LPCSTR.

bstrSrc

[in] The BSTR used to initialize the CComVariant object.

bSrc

[in] The bool used to initialize the CComVariant object.

nSrc

[in] The int, BYTE, short, or long used to initialize the CComVariant object.

vtSrc

[in] The type for the CComVariant object. This parameter is available only when passing a long for nSrc. vtSrc can only be VT_I4 (the default value) or VT_ERROR; otherwise, the constructor will assert.

fltSrc

[in] The float used to initialize the CComVariant object.

dblSrc

[in] The double used to initialize the CComVariant object.

cySrc

[in] The CY used to initialize the CComVariant object.

pSrc

[in] The IDispatch or IUnknown pointer used to initialize the CComVariant object.

Remarks

Each constructor initializes the object by calling the VariantInit Win32 function. If you pass a parameter value, the constructor sets the object's value and type accordingly.

The destructor manages cleanup by calling CComVariant::Clear.


CComVariant::ChangeType

HRESULT ChangeType( VARTYPE vtNew, const VARIANT* pSrc = NULL );

Return Value

A standard HRESULT value.

Parameters

vtNew

[in] The new type for the CComVariant object.

pSrc

[in] A pointer to the VARIANT whose value will be converted to the new type. The default value is NULL, meaning the CComVariant object will be converted in place.

Remarks

Converts the CComVariant object to a new type. If you pass a value for pSrc, ChangeType will use this VARIANT as the source for the conversion. Otherwise, the CComVariant object will be the source.

CComVariant Overview | Class Members

See Also VariantChangeType


CComVariant::Clear

HRESULT Clear( );

Return Value

A standard HRESULT value.

Remarks

Clears the CComVariant object by calling the VariantClear API function.

The destructor automatically calls Clear.


CComVariant::Copy

HRESULT Copy( const VARIANT* pSrc );

Return Value

A standard HRESULT value.

Parameters

pSrc

[in] A pointer to the VARIANT to be copied

Remarks

Frees the CComVariant object and then assigns it a copy of the specified VARIANT.

CComVariant Overview | Class Members

See Also CComVariant::operator =, VariantCopy


CComVariant::Detach

HRESULT Detach( VARIANT* pSrc );

Return Value

A standard HRESULT value.

Parameters

pSrc

[out] Returns the underlying VARIANT value of the object.

Remarks

Detaches the underlying VARIANT from the CComVariant object and sets the object's type to VT_EMPTY.

CComVariant Overview | Class Members

See Also CComVariant::Attach


CComVariant::ReadFromStream

HRESULT ReadFromStream( IStream* pStream );

Return Value

A standard HRESULT value.

Parameters

pStream

[in] A pointer to the IStream interface on the stream containing the data.

Remarks

Sets the underlying VARIANT to the VARIANT contained in the specified stream. ReadToStream requires a previous call to WriteToStream.


CComVariant::WriteToStream

HRESULT WriteToStream( IStream* pStream );

Return Value

A standard HRESULT value.

Parameters

pStream

[in] A pointer to the IStream interface on a stream.

Remarks

Saves the underlying VARIANT to a stream.

CComVariant Overview | Class Members

See Also CComVariant::ReadFromStream


CComVariant::operator =

CComVariant& operator =( const CComVariant& varSrc );
CComVariant& operator =( const VARIANT& varSrc );
CComVariant& operator =( LPCOLESTR lpsz );
CComVariant& operator =( LPCSTR lpsz );
CComVariant& operator =( BSTR bstrSrc );
CComVariant& operator =( bool bSrc );
CComVariant& operator =( int nSrc );
CComVariant& operator =( BYTE nSrc );
CComVariant& operator =( short nSrc );
CComVariant& operator =( long nSrc );
CComVariant& operator =( float nSrc );
CComVariant& operator =( double nSrc );
CComVariant& operator =( CY cySrc );
CComVariant& operator =( IDispatch* pSrc );
CComVariant& operator =( IUnknown* pSrc );

Remarks

Assigns a value and corresponding type to the CComVariant object.

CComVariant Overview | Class Members

See Also CComVariant::Copy, VARIANT


CComVariant::operator ==

bool operator ==( const VARIANT& varSrc );

Remarks

Returns true if the value and type of varSrc are equal to the value and type, respectively, of the CComVariant object. Otherwise, false.

CComVariant Overview | Class Members

See Also CComVariant::operator !=, VARIANT


CComVariant::operator !=

bool operator !=( const VARIANT& varSrc );

Remarks

Returns true if either the value or type of varSrc is not equal to the value or type, respectively, of the CComVariant object. Otherwise, false.

CComVariant Overview | Class Members

See Also CComVariant::operator ==, VARIANT


CContainedWindow

template < class TBase = CWindow, class TWinTraits = CControlWinTraits >
class CContainedWindowT : public TBase

Parameters

TBase

The base class of your new class. The default base class is CWindow.

TWinTraits

A traits class that defines styles for your window. The default is CControlWinTraits.

Note CContainedWindow is a specialization of CContainedWindowT. If you want to change the base class or traits, use CContainedWindowT directly.

CContainedWindow implements a window contained within another object. CContainedWindow’s window procedure uses a message map in the containing object to direct messages to the appropriate handlers. When constructing a CContainedWindow object, you specify which message map should be used.

CContainedWindow allows you to create a new window by superclassing an existing window class. The Create method first registers a window class that is based on an existing class but uses CContainedWindow::WindowProc. Create then creates a window based on this new window class. Each instance of CContainedWindow can superclass a different window class.

CContainedWindow also supports window subclassing. The SubclassWindow method attaches an existing window to the CContainedWindow object and changes the window procedure to CContainedWindow::WindowProc. Each instance of CContainedWindow can subclass a different window.

Note For any given CContainedWindow object, call either Create or SubclassWindow. You should not invoke both methods on the same object.

When you use the Add control based on option in the ATL Object Wizard, the wizard will automatically add a CContainedWindow data member to the class implementing the control. The following example is taken from the SUBEDIT sample and shows how the contained window is declared:

class CAtlEdit : ...
{
public:
   // Declare a contained window data member
   CContainedWindow m_EditCtrl;

   // Initialize the contained window:
   // 1. Pass "EDIT" to specify that the contained
   //    window should be based on the standard
   //    Windows Edit box
   // 2. Pass 'this' pointer to specify that CAtlEdit
   //    contains the message map to be used for the
   //    contained window's message processing
   // 3. Pass the identifier of the message map. '1'
   //    identifies the alternate message map declared
   //    with ALT_MSG_MAP(1)
   CAtlEdit() : m_EditCtrl(_T("EDIT"), this, 1)
   {
      m_bWindowOnly = TRUE;
   }

   // Declare the default message map,
   // identified by '0'
   BEGIN_MSG_MAP(CAtlEdit)
      ...
      MESSAGE_HANDLER(WM_CREATE, OnCreate)
      ...
   // Declare an alternate message map,
   // identified by '1'
   ALT_MSG_MAP(1)
      MESSAGE_HANDLER(WM_CHAR, OnChar)
   END_MSG_MAP()

   // Define OnCreate handler
   // When the containing window receives a WM_CREATE
   // message, create the contained window by calling
   // CContainedWindow::Create
   LRESULT OnCreate(UINT uMsg, WPARAM wParam,
                    LPARAM lParam, BOOL& bHandled)
   {
      ...
      m_EditCtrl.Create(m_hWnd, rc, _T("hello"),
                        WS_CHILD | WS_VISIBLE |
                        ES_MULTILINE | ES_AUTOVSCROLL);
      return 0;
   }

   ...
};
For more information about | See
Creating controls | ATL Tutorial
Using windows in ATL | ATL Window Classes
ATL Object Wizard | Creating an ATL Project
Windows | Windows and subsequent topics in the Platform SDK
Subclassing | Window Procedure Subclassing in the Platform SDK
Superclassing | Window Procedure Superclassing in the Platform SDK

#include <atlwin.h>

Class Members

See Also

CWindow, CWindowImpl, CMessageMap, BEGIN_MSG_MAP, ALT_MSG_MAP


CContainedWindow Class Members

Methods

CContainedWindow | Constructor. Initializes data members to specify which message map will process the contained window’s messages.
Create | Creates a window.
DefWindowProc | Provides default message processing.
GetCurrentMessage | Returns the current message.
RegisterWndSuperclass | Registers the window class of the contained window.
SubclassWindow | Subclasses a window.
SwitchMessageMap | Changes which message map is used to process the contained window’s messages.
UnsubclassWindow | Restores a previously subclassed window.
WindowProc | Processes messages sent to the contained window.

Data Members

m_dwMsgMapID | Identifies which message map will process the contained window’s messages.
m_lpszClassName | Specifies the name of an existing window class on which a new window class will be based.
m_pfnSuperWindowProc | Points to the window class’s original window procedure.
m_pObject | Points to the containing object.

CContainedWindow Overview


CContainedWindow::CContainedWindow

CContainedWindow( LPTSTR lpszClassName, CMessageMap* pObject, DWORD dwMsgMapID = 0 );

CContainedWindow( CMessageMap* pObject, DWORD dwMsgMapID = 0 )

CContainedWindow( );

Parameters

lpszClassName

[in] The name of an existing window class on which the contained window will be based.

pObject

[in] A pointer to the containing object that declares the message map. This object’s class must derive from CMessageMap.

dwMsgMapID

[in] Identifies the message map that will process the contained window’s messages. The default value, 0, specifies the default message map declared with BEGIN_MSG_MAP. To use an alternate message map declared with ALT_MSG_MAP(msgMapID), pass msgMapID.

Remarks

The constructor initializes data members. If you want to create a new window through Create, you must pass the name of an existing window class for the lpszClassName parameter. For an example, see the CContainedWindow overview.

There are three constructors:

  • The constructor with three arguments is the one typically called.

  • The constructor with two arguments uses the class name from TBase::GetWndClassName.

  • The constructor with no arguments is used if you want to supply the arguments later. You must supply the window class name, message map object, and message map ID when you later call Create.

If you subclass an existing window through SubclassWindow, the lpszClassName value will not be used; therefore, you can pass NULL for this parameter.

CContainedWindow Overview | Class Members

See Also

CContainedWindow::m_lpszClassName, CContainedWindow::m_pObject, CContainedWindow::m_pfnSuperWindowProc, CContainedWindow::SwitchMessageMap


CContainedWindow::Create

HWND Create( HWND hWndParent, RECT& rcPos, LPCTSTR szWindowName = NULL, DWORD dwStyle = WS_CHILD | WS_VISIBLE, DWORD dwExStyle = 0, UINT nID = 0 );

Return Value

If successful, the handle to the newly created window; otherwise, NULL.

Parameters

hWndParent

[in] The handle to the parent or owner window.

rcPos

[in] A RECT structure specifying the position of the window.

szWindowName

[in] Specifies the name of the window. The default value is NULL.

dwStyle

[in] The style of the window. The default value is WS_CHILD | WS_VISIBLE. For a list of possible values, see CreateWindow in the Platform SDK.

dwExStyle

[in] The extended window style. The default value is 0, meaning no extended style. For a list of possible values, see CreateWindowEx in the Platform SDK.

nID

[in] For a child window, the window identifier. For a top-level window, an HWND casted to a UINT. The default value is 0.

Remarks

Calls RegisterWndSuperclass to register a window class that is based on an existing class but uses CContainedWindow::WindowProc. The existing window class name is saved in m_lpszClassName. Create then creates a window based on this new class. The newly created window is automatically attached to the CContainedWindow object.

Note Do not call Create if you have already called SubclassWindow.

CContainedWindow Overview | Class Members

See Also

CWindow::m_hWnd


CContainedWindow::DefWindowProc

LRESULT DefWindowProc( UINT uMsg, WPARAM wParam, LPARAM lParam );

Return Value

The result of the message processing.

Parameters

uMsg

[in] The message sent to the window.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

Remarks

Called by WindowProc to process messages not handled by the message map. By default, DefWindowProc calls the CallWindowProc Win32 function to send the message information to the window procedure specified in m_pfnSuperWindowProc.


CContainedWindow::GetCurrentMessage

const MSG* GetCurrentMessage( );

Return Value

The current message, packaged in the MSG structure.

Remarks

Returns the current message (m_pCurrentMsg).


CContainedWindow::RegisterWndSuperclass

ATOM RegisterWndSuperClass( );

Return Value

If successful, an atom that uniquely identifies the window class being registered; otherwise, 0.

Remarks

Called by Create to register the window class of the contained window. This window class is based on an existing class but uses CContainedWindow::WindowProc. The existing window class’s name and window procedure are saved in m_lpszClassName and m_pfnSuperWindowProc, respectively.

CContainedWindow Overview | Class Members

See Also

CContainedWindow::CContainedWindow


CContainedWindow::SubclassWindow

BOOL SubclassWindow( HWND hWnd );

Return Value

TRUE if the window is successfully subclassed; otherwise, FALSE.

Parameters

hWnd

[in] The handle to the window being subclassed.

Remarks

Subclasses the window identified by hWnd and attaches it to the CContainedWindow object. The subclassed window now uses CContainedWindow::WindowProc. The original window procedure is saved in m_pfnSuperWindowProc.

Note Do not call SubclassWindow if you have already called Create.

CContainedWindow Overview | Class Members

See Also

CContainedWindow::UnsubclassWindow


CContainedWindow::SwitchMessageMap

void SwitchMessageMap( DWORD dwMsgMapID );

Parameters

dwMsgMapID

[in] The message map identifier. To use the default message map declared with BEGIN_MSG_MAP, pass 0. To use an alternate message map declared with ALT_MSG_MAP(msgMapID), pass msgMapID.

Remarks

Changes which message map will be used to process the contained window’s messages. The message map must be defined in the containing object.

You initially specify the message map identifier in the constructor.

CContainedWindow Overview | Class Members

See Also

CContainedWindow::CContainedWindow, CContainedWindow::m_dwMsgMapID


CContainedWindow::UnsubclassWindow

HWND UnsubclassWindow( );

Return Value

The handle to the window previously subclassed.

Remarks

Detaches the subclassed window from the CContainedWindow object and restores the original window procedure, saved in m_pfnSuperWindowProc.

CContainedWindow Overview | Class Members

See Also

CContainedWindow::SubclassWindow


CContainedWindow::WindowProc

static LRESULT CALLBACK WindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );

Return Value

The result of the message processing.

Parameters

hWnd

[in] The handle to the window.

uMsg

[in] The message sent to the window.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

Remarks

This static method implements the window procedure. WindowProc directs messages to the message map identified by m_dwMsgMapID. If necessary, WindowProc calls DefWindowProc for additional message processing.

CContainedWindow Overview | Class Members

See Also

BEGIN_MSG_MAP, ALT_MSG_MAP


CContainedWindow::m_dwMsgMapID

DWORD m_dwMsgMapID;

Remarks

Holds the identifier of the message map currently being used for the contained window. This message map must be declared in the containing object.

The default message map, declared with BEGIN_MSG_MAP, is always identified by 0. An alternate message map, declared with ALT_MSG_MAP(msgMapID), is identified by msgMapID.

m_dwMsgMapID is first initialized by the constructor and can be changed by calling SwitchMessageMap. For an example, see the CContainedWindow overview.

CContainedWindow Overview | Class Members

See Also

CContainedWindow::m_pObject


CContainedWindow::m_lpszClassName

LPTSTR m_lpszClassName;

Remarks

Specifies the name of an existing window class. When you create a window, Create registers a new window class that is based on this existing class but uses CContainedWindow::WindowProc.

m_lpszClassName is initialized by the constructor. For an example, see the CContainedWindow overview.


CContainedWindow::m_pfnSuperWindowProc

WNDPROC m_pfnSuperWindowProc;

Remarks

If the contained window is subclassed, m_pfnSuperWindowProc points to the original window procedure of the window class. If the contained window is superclassed, meaning it is based on a window class that modifies an existing class, m_pfnSuperWindowProc points to the existing window class’s window procedure.

The DefWindowProc method sends message information to the window procedure saved in m_pfnSuperWindowProc.

CContainedWindow Overview | Class Members

See Also

CContainedWindow::Create, CContainedWindow::SubclassWindow


CContainedWindow::m_pObject

CMessageMap* m_pObject;

Remarks

Points to the object containing the CContainedWindow object. This container, whose class must derive from CMessageMap, declares the message map used by the contained window.

m_pObject is initialized by the constructor. For an example, see the CContainedWindow overview.

CContainedWindow Overview | Class Members

See Also

CContainedWindow::m_dwMsgMapID


CDialogImpl

template < class T, class TBase = CWindow >
class ATL_NO_VTABLE CDialogImpl : public CDialogImplBaseT< TBase >

Parameters

T

Your class, derived from CDialogImpl.

TBase

The base class of your new class. The default base class is CWindow.

CDialogImpl allows you to create a modal or modeless dialog box. CDialogImpl provides the dialog box procedure, which uses the default message map to direct messages to the appropriate handlers.

The base class destructor ~CWindowImplRoot ensures that the window is gone before destroying the object.

CDialogImpl derives from CDialogImplBaseT, which in turn derives from CWindowImplRoot.

Note Your class must define an IDD member that specifies the dialog template resource ID. For example, the ATL Object Wizard automatically adds the following line to your class:

enum { IDD = IDD_MYDIALOG };

where MyDialog is the Short name entered in the wizard’s Names page.

For more information about | See
Creating controls | ATL Tutorial
Using dialog boxes in ATL | ATL Window Classes
ATL Object Wizard | Creating an ATL Project
Dialog boxes | Dialog Boxes and subsequent topics in the Platform SDK

#include <atlwin.h>

Class Members

See Also

BEGIN_MSG_MAP


CDialogImpl Class Members

Methods

Create | Creates a modeless dialog box.
DestroyWindow | Destroys a modeless dialog box.
DoModal | Creates a modal dialog box.
EndDialog | Destroys a modal dialog box.

CDialogImplBaseT Methods

DialogProc | Processes messages sent to the dialog box.
GetDialogProc | Returns the current dialog box procedure.
OnFinalMessage | Called after receiving the last message, typically WM_NCDESTROY.
MapDialogRect | Maps the dialog-box units of the specified rectangle to screen units (pixels).
StartDialogProc | Called when the first message is received to process messages sent to the dialog box.

CDialogImpl Overview


CDialogImpl::Create

HWND Create( HWND hWndParent, LPARAM dwInitParam = NULL );

HWND Create( HWND hWndParent, RECT&, LPARAM dwInitParam = NULL );

Return Value

The handle to the newly created dialog box.

Parameters

hWndParent

[in] The handle to the owner window.

RECT& rect

[in] A RECT structure specifying the dialog's size and position.

dwInitParam

[in] Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

Remarks

Creates a modeless dialog box. This dialog box is automatically attached to the CDialogImpl object.

To create a modal dialog box, call DoModal.

The second override above is used only with CComControl.

CDialogImpl Overview | Class Members

See Also

CWindow::m_hWnd


CDialogImpl::DestroyWindow

BOOL DestroyWindow( );

Return Value

TRUE if the dialog box was successfully destroyed; otherwise FALSE.

Remarks

Destroys a modeless dialog box. Returns TRUE if the dialog box was successfully destroyed; otherwise FALSE.

CDialogImpl Overview | Class Members

See Also

CDialogImpl::Create


CDialogImpl::DialogProc

static LRESULT CALLBACK DialogProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );

Return Value

TRUE if the message is processed; otherwise, FALSE.

Parameters

hWnd

[in] The handle to the dialog box.

uMsg

[in] The message sent to the dialog box.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

Remarks

This static method implements the dialog box procedure. DialogProc uses the default message map to direct messages to the appropriate handlers.

You can override DialogProc to provide a different mechanism for handling messages.

CDialogImpl Overview | Class Members

See Also

BEGIN_MSG_MAP


CDialogImpl::DoModal

int DoModal( HWND hWndParent = ::GetActiveWindow( ) );

Return Value

If successful, the value of the nRetCode parameter specified in the call to EndDialog. Otherwise, -1.

Parameters

hWndParent

[in] The handle to the owner window. The default value is the return value of the GetActiveWindow Win32 function.

Remarks

Creates a modal dialog box. This dialog box is automatically attached to the CDialogImpl object.

To create a modeless dialog box, call Create.

CDialogImpl Overview | Class Members

See Also

CWindow::m_hWnd, CDialogImpl::EndDialog


CDialogImpl::EndDialog

BOOL EndDialog( int nRetCode );

Return Value

TRUE if the dialog box is destroyed; otherwise, FALSE.

Parameters

nRetCode

[in] The value to be returned by CDialogImpl::DoModal.

Remarks

Destroys a modal dialog box. EndDialog must be called through the dialog procedure. After the dialog box is destroyed, Windows uses the value of nRetCode as the return value for DoModal, which created the dialog box.

Note Do not call EndDialog to destroy a modeless dialog box. Call CWindow::DestroyWindow instead.

CDialogImpl Overview | Class Members

See Also

CDialogImpl::DialogProc


CDialogImpl::GetDialogProc

virtual WNDPROC GetDialogProc( );

Return Value

The current dialog box procedure.

Remarks

Returns DialogProc, the current dialog box procedure. Override this method to replace the dialog procedure with your own.

CDialogImpl Overview | Class Members

See Also

CDialogImpl::DialogProc, CDialogImpl::OnFinalMessage


CDialogImpl::MapDialogRect

BOOL MapDialogRect( LPRECT lpRect );

Return Value

Nonzero if the update succeeds; 0 if the update fails. To get extended error information, call GetLastError.

Parameters

lpRect

Points to a CRect object or RECT structure that is to receive the client coordinates of the update that encloses the update region.

Remarks

Converts (maps) the dialog-box units of the specified rectangle to screen units (pixels). The function replaces the coordinates in the specified RECT structure with the converted coordinates, which allows the structure to be used to create a dialog box or position a control within a dialog box.

CDialogImpl Overview | Class Members

See Also

MapDialogRect in the Platform SDK.


CDialogImpl::OnFinalMessage

virtual void OnFinalMessage( HWND hWnd );

Parameters

hWnd

[in] A handle to the window being destroyed.

Remarks

Called after receiving the last message (typically WM_NCDESTROY). Note that if you want to automatically delete your object upon the window destruction, you can call delete this; here.

CDialogImpl Overview | Class Members

See Also

CDialogImpl::GetDialogProc


CDialogImpl::StartDialogProc

static LRESULT CALLBACK StartDialogProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );

Return Value

The window procedure.

Parameters

hWnd

[in] The handle to the dialog box.

uMsg

[in] The message sent to the dialog box.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

Remarks

Called only once, when the first message is received, to process messages sent to the dialog box. After the initial call to StartDialogProc, DialogProc is set as a dialog procedure, and further calls go there.

CDialogImpl Overview | Class Members

See Also

DialogProc


CDynamicChain

class CDynamicChain

CDynamicChain manages a collection of message maps, enabling a Windows message to be directed, at run time, to another object’s message map.

To add support for dynamic chaining of message maps, do the following:

  • Derive your class from CDynamicChain. In the message map, specify the CHAIN_MSG_MAP_DYNAMIC macro to chain to another object’s default message map.

  • Derive every class you want to chain to from CMessageMap. CMessageMap allows an object to expose its message maps to other objects.

  • Call CDynamicChain::SetChainEntry to identify which object and which message map you want to chain to.

For example, suppose your class is defined as follows:

class CMyWindow : public CDynamicChain, ...
{
public:
   ...

   BEGIN_MSG_MAP(CMyWindow)
      MESSAGE_HANDLER(WM_PAINT, OnPaint)
      MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
      // dynamically chain to the default
      // message map in another object
      CHAIN_MSG_MAP_DYNAMIC(1313)
                // '1313' identifies the object
                // and the message map that will be
                // chained to. '1313' is defined
                // through the SetChainEntry method
   END_MSG_MAP()

   LRESULT OnPaint(UINT uMsg, WPARAM wParam,
                   LPARAM lParam, BOOL& bHandled)
   { ... }

   LRESULT OnSetFocus(UINT uMsg, WPARAM wParam,
                      LPARAM lParam, BOOL& bHandled)
   { ... }

};

The client then calls CMyWindow::SetChainEntry:

// myCtl is a CMyWindow object
myCtl.SetChainEntry(1313, &chainedObj);

where chainedObj is the chained object and is an instance of a class derived from CMessageMap. Now, if myCtl receives a message that is not handled by OnPaint or OnSetFocus, the window procedure directs the message to chainedObj’s default message map.

For more information about message map chaining, see Message Maps in the article “ATL Window Classes.”

#include <atlwin.h>

Class Members

See Also CWindowImpl


CDynamicChain Class Members

Methods

CallChain | Directs a Windows message to another object’s message map.
RemoveChainEntry | Removes a message map entry from the collection.
SetChainEntry | Adds a message map entry to the collection or modifies an existing entry.

CDynamicChain Overview


CDynamicChain::CallChain

BOOL CallChain( DWORD dwChainID, HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult );

Return Value

TRUE if the message is fully processed; otherwise, FALSE.

Parameters

dwChainID

[in] The unique identifier associated with the chained object and its message map.

hWnd

[in] The handle to the window receiving the message.

uMsg

[in] The message sent to the window.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

lResult

[out] The result of the message processing.

Remarks

Directs the Windows message to another object’s message map. In order for the window procedure to invoke CallChain, you must specify the CHAIN_MSG_MAP_DYNAMIC macro in your message map. For an example, see the CDynamicChain overview.

CallChain requires a previous call to SetChainEntry to associate the dwChainID value with an object and its message map.


CDynamicChain::RemoveChainEntry

BOOL RemoveChainEntry( DWORD dwChainID );

Return Value

TRUE if the message map is successfully removed from the collection. Otherwise, FALSE.

Parameters

dwChainID

[in] The unique identifier associated with the chained object and its message map. You originally define this value through a call to SetChainEntry.

Remarks

Removes the specified message map from the collection.


CDynamicChain::SetChainEntry

BOOL SetChainEntry( DWORD dwChainID, CMessageMap* pObject, DWORD dwMsgMapID = 0 );

Return Value

TRUE if the message map is successfully added to the collection. Otherwise, FALSE.

Parameters

dwChainID

[in] The unique identifier associated with the chained object and its message map.

pObject

[in] A pointer to the chained object declaring the message map. This object must derive from CMessageMap.

dwMsgMapID

[in] The identifier of the message map in the chained object. The default value is 0, which identifies the default message map declared with BEGIN_MSG_MAP. To specify an alternate message map declared with ALT_MSG_MAP(msgMapID), pass msgMapID.

Remarks

Adds the specified message map to the collection. If the dwChainID value already exists in the collection, its associated object and message map are replaced by pObject and dwMsgMapID, respectively. Otherwise, a new entry is added.

CDynamicChain Overview | Class Members

See Also CDynamicChain::CallChain, CDynamicChain::RemoveChainEntry, CHAIN_MSG_MAP_DYNAMIC


CFirePropNotifyEvent

class CFirePropNotifyEvent

CFirePropNotifyEvent has two methods that notify the container's sink that a control property has changed or is about to change.

If the class implementing your control is derived from IPropertyNotifySink, the CFirePropNotifyEvent methods are invoked when you call FireOnRequestEdit or FireOnChanged. If your control class is not derived from IPropertyNotifySink, calls to these functions return S_OK.

For more information about creating controls, see the ATL Tutorial.

#include <atlctl.h>

Class Members


CFirePropNotifyEvent Class Members

Methods

FireOnChanged | Notifies the container's sink that a control property has changed.
FireOnRequestEdit | Notifies the container's sink that a control property is about to change.

CFirePropNotifyEvent Overview


CFirePropNotifyEvent::FireOnChanged

HRESULT FireOnChanged( IUnknown* pUnk, DISPID dispID );

Return Value

One of the standard HRESULT values.

Parameters

pUnk

[in] Pointer to the IUnknown of the object sending the notification.

dispID

[in] Identifier of the property that has changed.

Remarks

Notifies all connected IPropertyNotifySink interfaces (on every connection point of the object) that the specified object property has changed. This function is safe to call even if your control doesn’t support connection points.

CFirePropNotifyEvent Overview | Class Members

See Also CFirePropNotifyEvent::FireOnRequestEdit, CComControl::FireOnChanged


CFirePropNotifyEvent::FireOnRequestEdit

HRESULT FireOnRequestEdit( IUnknown* pUnk, DISPID dispID );

Return Value

One of the standard HRESULT values.

Parameters

pUnk

[in] Pointer to the IUnknown of the object sending the notification.

dispID

[in] Identifier of the property about to change.

Remarks

Notifies all connected IPropertyNotifySink interfaces (on every connection point of the object) that the specified object property is about to change. This function is safe to call even if your control doesn’t support connection points.

CFirePropNotifyEvent Overview | Class Members

See Also CFirePropNotifyEvent::FireOnChanged, CComControl::FireOnRequestEdit


CMessageMap

class CMessageMap

CMessageMap is an abstract base class that allows an object’s message maps to be accessed by another object. In order for an object to expose its message maps, its class must derive from CMessageMap.

ATL uses CMessageMap to support contained windows and dynamic message map chaining. For example, any class containing a CContainedWindow object must derive from CMessageMap. The following code is taken from the SUBEDIT sample. Through CComControl, the CAtlEdit class automatically derives from CMessageMap.

class CAtlEdit : public CComControl<CAtlEdit>, ...
               // CComControl derives from CWindowImpl,
               // which derives from CMessageMap
{
public:
   // Declare a contained window data member
   CContainedWindow m_EditCtrl;

   // Initialize the contained window:
   // 1. Pass "EDIT" to specify that the contained
   //    window should be based on the standard
   //    Windows Edit box
   // 2. Pass 'this' pointer to specify that CAtlEdit
   //    contains the message map to be used for the
   //    contained window's message processing
   // 3. Pass the identifier of the message map. In
   //    this case, '1' identifies the message map
   //    declared with ALT_MSG_MAP(1)
   CAtlEdit() : m_EditCtrl(_T("EDIT"), this, 1)
   {
      m_bWindowOnly = TRUE;
   }

   // Declare the default message map
   BEGIN_MSG_MAP(CAtlEdit)
      MESSAGE_HANDLER(WM_PAINT, OnPaint)
      ...
   // Declare an alternate message map,
   // identified by '1'
   ALT_MSG_MAP(1)
      MESSAGE_HANDLER(WM_CHAR, OnChar)
   END_MSG_MAP()

   ...
};

Because the contained window, m_EditCtrl, will use a message map in the containing class, CAtlEdit derives from CMessageMap.

For more information about message maps, see Message Maps in the article “ATL Window Classes.”

#include <atlwin.h>

Class Members

See Also CDynamicChain, BEGIN_MSG_MAP, ALT_MSG_MAP


CMessageMap Class Members

Methods

ProcessWindowMessage Accesses a message map in the CMessageMap-derived class.

CMessageMap Overview


CMessageMap::ProcessWindowMessage

virtual BOOL ProcessWindowMessage( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult, DWORD dwMsgMapID ) = 0;

Return Value

TRUE if the message is fully handled; otherwise, FALSE.

Parameters

hWnd

[in] The handle to the window receiving the message.

uMsg

[in] The message sent to the window.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

lResult

[out] The result of the message processing.

dwMsgMapID

[in] The identifier of the message map that will process the message. The default message map, declared with BEGIN_MSG_MAP, is identified by 0. An alternate message map, declared with ALT_MSG_MAP(msgMapID), is identified by msgMapID.

Remarks

Accesses the message map identified by dwMsgMapID in a CMessageMap-derived class. Called by the window procedure of a CContainedWindow object or of an object that is dynamically chaining to the message map.

CMessageMap Overview | Class Members

See Also CHAIN_MSG_MAP_DYNAMIC


CSnapInPropertyPageImpl

CSnapInPropertyPageImpl : public CDialogImplBase

CSnapInPropertyPageImpl provides a basic implementation for a snap-in property page object. The basic features of a snap-in property page are implemented using several different interfaces and map types.

You derive from this class for the property pages of your snap-in object and implement specific notification and command handlers using predefined maps. To add custom functionality, see the MMC Snap-In FAQ.

#include <atlsnap.h>

Class Members


CSnapInPropertyPageImpl Class Members

Construction |
CSnapInPropertyPageImpl | Constructs a new CSnapInPropertyPageImpl object.
Create | Initializes a newly created CSnapInPropertyPageImpl object.

Operations |
CancelToClose | Changes the status of the OK and Cancel buttons.
SetModified | Call to activate or deactivate the Apply Now button.
QuerySiblings | Forwards the current message to all pages of the property sheet.

Overridables |
OnSetActive | Called by the framework when the current page becomes active.
OnKillActive | Called by the framework when the current page is no longer active.
OnApply | Called by the framework when the user clicks the Apply Now button is clicked while using a wizard-type property sheet.
OnReset | Called by the framework when the user clicks the Reset button is clicked while using a wizard-type property sheet.
OnQueryCancel | Called by the framework when the user clicks the Cancel button is clicked and before the cancel has taken place.
OnWizardBack | Called by the framework when the user clicks the Back button is clicked while using a wizard-type property sheet.
OnWizardNext | Called by the framework when the user clicks the Next button is clicked while using a wizard-type property sheet.
OnWizardFinish | Called by the framework when the user clicks the Finish button is clicked while using a wizard-type property sheet.
OnHelp | Called by the framework when the user clicks the Help button while using a wizard-type property sheet.

Data Members |
m_psp | The Windows PROPSHEETPAGE structure used by the CSnapInPropertyPageImpl object.


CSnapInPropertyPageImpl::CancelToClose

void CancelToClose( );

Remarks

Call this function after an unrecoverable change has been made to the data in a page of a modal property sheet. This function will change the OK button to Close and disable the Cancel button. This change alerts the user that a change is permanent and the modifications cannot be cancelled.

The CancelToClose member function does nothing in a modeless property sheet, because a modeless property sheet does not have a Cancel button by default.


CSnapInPropertyPageImpl::CSnapInPropertyPageImpl

CSnapInPropertyPageImpl( LPCTSTR lpszTitle = NULL );

Parameters

lpszTitle

[in] The title of the property page.

Remarks

Constructs a CSnapInPropertyPageImpl object. To initialize the underlying structure, call CSnapInPropertyPageImpl::Create.


CSnapInPropertyPageImpl::Create

HPROPSHEETPAGE Create( );

Return Value

A handle to a PROPSHEETPAGE structure containing the attributes of the newly created property sheet.

Remarks

Call this function to initialize the underlying structure of the property page. You should first call CSnapInPropertyPageImpl::CSnapInPropertyPageImpl before calling this function.


CSnapInPropertyPageImpl::OnApply

BOOL OnApply( );

Return Value

Nonzero if the changes are accepted; otherwise 0.

Remarks

This member function is called when the user clicks the OK or the Apply Now button.

Before OnApply can be called by the framework, you must have called SetModified and set its parameter to TRUE. This will activate the Apply Now button as soon as the user makes a change on the property page.

Override this member function to specify what action your program takes when the user clicks the Apply Now button. When overriding, the function should return TRUE to accept changes and FALSE to prevent changes from taking effect.

The default implementation of OnApply returns TRUE.


CSnapInPropertyPageImpl::OnHelp

void OnHelp( );

Remarks

This member function is called when the user clicks the Help button for the property page is pressed.

Override this member function to display help for the property page.


CSnapInPropertyPageImpl::OnKillActive

BOOL OnKillActive( );

Return Value

Nonzero if data was updated successfully; otherwise 0.

Remarks

This member function is called when the page is no longer the active page. Override this member function to perform special data validation tasks.


CSnapInPropertyPageImpl::OnQueryCancel

BOOL OnQueryCancel( );

Return Value

Nonzero to allow the cancel operation; otherwise 0.

Remarks

This member function is called when the user clicks the Cancel button and before the cancel action has taken place.

Override this member function to specify an action the program takes when the user clicks the Cancel button.

The default implementation of OnQueryCancel returns TRUE.


CSnapInPropertyPageImpl::OnReset

void OnReset( );

Remarks

This member function is called when the user clicks the Cancel button. When this function is called, changes to all property pages that were made by the user previously clicking the Apply Now button are discarded, and the property sheet retains focus.

Override this member function to specify what action the program takes when the user clicks the Cancel button.


CSnapInPropertyPageImpl::OnSetActive

BOOL OnSetActive( );

Return Value

Nonzero if the page was successfully set active; otherwise 0.

Remarks

This member function is called when the page is chosen by the user and becomes the active page. Override this member function to perform tasks when a page is activated. Your override of this member function should call the default version before any other processing is done.

The default implementation returns TRUE.


CSnapInPropertyPageImpl::OnWizardBack

BOOL OnWizardBack( );

Return Value

  • 0 to automatically advance to the previous page.

  • –1 to prevent the page from changing.

To jump to a page other than the next one, return the identifier of the dialog box to be displayed.

Remarks

This member function is called when the user clicks the Back button in a wizard.

Override this member function to specify some action the user must take when the Back button is pressed.


CSnapInPropertyPageImpl::OnWizardFinish

BOOL OnWizardFinish( );

Return Value

Nonzero if the property sheet is destroyed when the wizard finishes; otherwise zero.

Remarks

This member function is called when the user clicks the Finish button in a wizard.

Override this member function to specify some action the user must take when the Finish button is pressed.


CSnapInPropertyPageImpl::OnWizardNext

BOOL OnWizardNext( );

Return Value

  • 0 to automatically advance to the next page.

  • –1 to prevent the page from changing.

To jump to a page other than the next one, return the identifier of the dialog box to be displayed.

Remarks

This member function is called when the user clicks the Next button in a wizard.

Override this member function to specify some action the user must take when the Next button is clicked.


CSnapInPropertyPageImpl::QuerySiblings

LRESULT QuerySiblings( WPARAM wParam, LPARAM lParam );

Return Value

Nonzero if the message should not be forwarded to the next property page; otherwise zero.

Parameters

wParam

[in] Specifies additional message-dependent information.

lParam

[in] Specifies additional message-dependent information.

Remarks

Call this member function to forward a message to each page in the property sheet. If a page returns a nonzero value, the property sheet does not send the message to subsequent pages.


CSnapInPropertyPageImpl::SetModified

void SetModified( BOOL bChanged = TRUE );

Parameters

bChanged

[in] TRUE to indicate that the property page settings have been modified since the last time they were applied; FALSE to indicate that the property page settings have been applied, or should be ignored.

Remarks

Call this member function to enable or disable the Apply Now button, based on whether the settings in the property page should be applied to the appropriate external object.

The property sheet keeps track of which pages are “dirty,” that is, property pages for which you have called SetModified( TRUE ). The Apply Now button will always be enabled if you call SetModified( TRUE ) for one of the pages. The Apply Now button will be disabled when you call SetModified( FALSE ) for one of the pages, but only if none of the other pages is “dirty.”


CSnapInPropertyPageImpl::m_psp

PROPSHEETPAGE m_psp;

Remarks

m_psp is a structure whose members store the characteristics of PROPSHEETPAGE. Use this structure to initialize the appearance of a property page after it is constructed.

For more information on this structure, including a listing of its members, see PROPSHEETPAGE in the Windows SDK Programmer’s ReferencePlatform SDK.


CRegKey

class CRegKey

CRegKey provides methods for manipulating values in the system registry. The registry contains an installation-specific set of definitions for system components, such as software version numbers, logical-to-physical mappings of installed hardware, and COM objects.

CRegKey provides a programming interface to the system registry for a given machine. For example, to open a particular registry key, call CRegKey::Open. To retrieve or modify a data value, call CRegKey::QueryValue or CRegKey::SetValue, respectively. To close a key, call CRegKey::Close.

When you close a key, its registry data is written (flushed) to the hard disk. This process may take several seconds. If your application must explicitly write registry data to the hard disk, you can call the RegFlushKey Win32 function. However, RegFlushKey uses many system resources and should be called only when absolutely necessary.

#include <atlbase.h>

Class Members


CRegKey Class Members

Methods

Attach | Attaches a registry key handle to the CRegKey object.
Close | Releases m_hKey.
Create | Creates or opens the specified key.
CRegKey | Constructor.
DeleteSubKey | Deletes the specified key.
DeleteValue | Deletes a value field of the key identified by m_hKey.
Detach | Detaches m_hKey from the CregKey object.
Open | Opens the specified key.
QueryValue | Retrieves the data for a specified value field.
RecurseDeleteKey | Deletes the specified key and explicitly deletes all subkeys.
SetKeyValue | Stores data in a specified value field of a specified key.
SetValue | Stores data in a specified value field.

Operators

operator HKEY Converts a CRegKey object to an HKEY.

Data Members

m_hKey Contains a handle of the registry key associated with the CRegKey object.

CRegKey Overview


CRegKey::Attach

void Attach( HKEY hKey );

Parameters

hKey

[in] The handle of a registry key.

Remarks

Attaches an HKEY to the CRegKey object by setting the m_hKey member handle to hKey.

Note Attach will assert if m_hKey is non-NULL.

CRegKey Overview | Class Members

See Also CRegKey::Detach


CRegKey::Close

LONG Close( );

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Remarks

Releases the m_hKey member handle and sets it to NULL.

CRegKey Overview | Class Members

See Also CRegKey::Open


CRegKey::Create

LONG Create( HKEY hKeyParent, LPCTSTR lpszKeyName, LPTSTR lpszClass = REG_NONE, DWORD dwOptions = REG_OPTION_NON_VOLATILE, REGSAM samDesired = KEY_ALL_ACCESS, LPSECURITY_ATTRIBUTES lpSecAttr = NULL, LPDWORD lpdwDisposition = NULL );

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Parameters

hKeyParent

[in] The handle of an open key.

lpszKeyName

[in] Specifies the name of a key to be created or opened. This name must be a subkey of hKeyParent.

lpszClass

[in] Specifies the class of the key to be created or opened. The default value is REG_NONE.

dwOptions

[in] Options for the key. The default value is REG_OPTION_NON_VOLATILE. For a list of possible values and descriptions, see RegCreateKeyEx in the Win32 SDK.

samDesired

[in] The security access for the key. The default value is KEY_ALL_ACCESS. For a list of possible values and descriptions, see RegCreateKeyEx.

lpSecAttr

[in] A pointer to a SECURITY_ATTRIBUTES structure that indicates whether the handle of the key can be inherited by a child process. By default, this parameter is NULL (meaning the handle cannot be inherited).

lpdwDisposition

[out] If non-NULL, retrieves either REG_CREATED_NEW_KEY (if the key did not exist and was created) or REG_OPENED_EXISTING_KEY (if the key existed and was opened).

Remarks

Creates the specified key if it does not exist as a subkey of hKeyParent. Otherwise, Create opens the key.

Create sets the m_hKey member to the handle of this key.

CRegKey Overview | Class Members

See Also CRegKey::Open, CRegKey::Close


CRegKey::CRegKey

CRegKey( );

Remarks

The constructor. Sets the m_hKey member handle to NULL. The destructor releases m_hKey.


CRegKey::DeleteSubKey

LONG DeleteSubKey( LPCTSTR lpszSubKey );

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Parameters

lpszSubKey

[in] Specifies the name of the key to delete. This name must be a subkey of m_hKey.

Remarks

Removes the specified key from the registry. Under Windows 95, DeleteSubKey deletes the key and all its subkeys. Under Windows NT, DeleteSubKey can only delete a key that has no subkeys. If the key has subkeys, call RecurseDeleteKey instead.

CRegKey Overview | Class Members

See Also CRegKey::DeleteValue


CRegKey::DeleteValue

LONG DeleteValue( LPCTSTR lpszValue );

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Parameters

lpszValue

[in] Specifies the value field to remove.

Remarks

Removes a value field from m_hKey.

CRegKey Overview | Class Members

See Also CRegKey::DeleteSubKey


CRegKey::Detach

HKEY Detach( );

Return Value

The HKEY associated with the CRegKey object.

Remarks

Detaches the m_hKey member handle from the CRegKey object and sets m_hKey to NULL.

CRegKey Overview | Class Members

See Also CRegKey::Attach


CRegKey::Open

LONG Open( HKEY hKeyParent, LPCTSTR lpszKeyName, REGSAM samDesired = KEY_ALL_ACCESS );

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Parameters

hKeyParent

[in] The handle of an open key.

lpszKeyName

[in] Specifies the name of a key to be created or opened. This name must be a subkey of hKeyParent.

samDesired

[in] The security access for the key. The default value is KEY_ALL_ACCESS. For a list of possible values and descriptions, see RegCreateKeyEx in the Win32 SDK.

Remarks

Opens the specified key and sets m_hKey to the handle of this key. If the lpszKeyName parameter is NULL or points to an empty string, Open opens a new handle of the key identified by hKeyParent, but does not close any previously opened handle.

Unlike CRegKey::Create, Open will not create the specified key if it does not exist.

CRegKey Overview | Class Members

See Also CRegKey::Close


CRegKey::QueryValue

LONG QueryValue( DWORD& dwValue, LPCTSTR lpszValueName );

LONG QueryValue( LPTSTR szValue, LPCTSTR lpszValueName, DWORD* pdwCount )

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Parameters

dwValue

[out] The value field’s numerical data.

lpszValueName

[in] Specifies the value field to be queried.

szValue

[out] The value field’s string data.

pdwCount

[in, out] The size of the string data. Its value is initially set to the size of the szValue buffer.

Remarks

Retrieves the data for the specified value field of m_hKey. The first version of QueryValue allows you to retrieve numerical data. The second version allows you to retrieve string data.


CRegKey::RecurseDeleteKey

LONG RecurseDeleteKey( LPCTSTR lpszKey );

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Parameters

lpszKey

[in] Specifies the name of the key to delete. This name must be a subkey of m_hKey.

Remarks

Removes the specified key from the registry and explicitly removes any subkeys. If the key has subkeys, you must call this method under Windows NT in order to delete the key. Under Windows 95, you can call DeleteSubKey to remove the key and any subkeys.


CRegKey::SetKeyValue

LONG SetKeyValue( LPCTSTR lpszKeyName, LPCTSTR lpszValue, LPCTSTR lpszValueName = NULL );

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Parameters

lpszKeyName

[in] Specifies the name of the key to be created or opened. This name must be a subkey of m_hKey.

lpszValue

[in] Specifies the data to be stored. This parameter must be non-NULL.

lpszValueName

[in] Specifies the value field to be set. If a value field with this name does not already exist in the key, it is added.

Remarks

Creates or opens the lpszKeyName key and stores the lpszValue data in the lpszValueName value field.

CRegKey Overview | Class Members

See Also CRegKey::SetValue


CRegKey::SetValue

LONG SetValue( DWORD dwValue, LPCTSTR lpszValueName );

LONG SetValue( LPCTSTR lpszValue, LPCTSTR lpszValueName = NULL );

LONG SetValue( HKEY hKeyParent, LPCTSTR lpszKeyName, LPCTSTR lpszValue, LPCTSTR lpszValueName = NULL );

Return Value

If successful, returns ERROR_SUCCESS; otherwise, an error value.

Parameters

dwValue

[in] Specifies the data to be stored.

lpszValueName

[in] Specifies the value field to be set. If a value field with this name does not already exist in the key, it is added.

lpszValue

[in] Specifies the data to be stored. This parameter must be non-NULL.

hKeyParent

[in] The handle of an open key.

lpszKeyName

[in] Specifies the name of a key to be created or opened. This name must be a subkey of hKeyParent.

Remarks

Stores data in the specified value field of an open registry key. The first two versions of SetValue use m_hKey as the open key. The third version allows you to create or open a subkey of hKeyParent, and then set the value field of the subkey.

CRegKey Overview | Class Members

See Also CRegKey::SetKeyValue


CRegKey::operator HKEY

operator HKEY( ) const;

Remarks

Converts a CRegKey object to an HKEY.


CRegKey::m_hKey

HKEY m_hKey;

Remarks

Contains a handle of the registry key associated with the CRegKey object.


CSimpleDialog

template <WORD t_wDlgTemplateID, BOOL t_bCenter = TRUE>
class CSimpleDialog : public CDialogImplBase;

Parameters

t_wDlgTemplateID

The resource ID of the dialog template resource.

t_bCenter

TRUE if the dialog object is to be centered on the owner window; otherwise FALSE.

Implements a modal dialog box with basic functionality. CSimpleDialog provides support for Windows common controls only. To create and display a modal dialog box, create an instance of this class, providing the name of an existing resource template for the dialog box. The dialog box object closes when the user clicks on any control with a pre-defined value (such as IDOK or IDCANCEL).

CSimpleDialog allows you to create a modal or modeless dialog box. CSimpleDialog provides the dialog box procedure, which uses the default message map to direct messages to the appropriate handlers.

See Implementing a Dialog Box for more information.

#include <atlwin.h>

Class Members


CSimpleDialog Class Members

Methods |
DoModal | Creates a modal dialog box.

CSimpleDialog Overview


CSimpleDialog::DoModal

int DoModal( HWND hWndParent = ::GetActiveWindow() );

Return Value

If successful, the return value is the resource ID of the control that dismissed the dialog box.

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

Parameters

hWndParent

A handle to the parent of the dialog box. If no value is provided, the parent is set to the current active window.

Remarks

Invokes a modal dialog box and returns the dialog-box result when done. This method handles all interaction with the user while the dialog box is active. This is what makes the dialog box modal; that is, the user cannot interact with other windows until the dialog box is closed.


CSnapInItemImpl

template <class T, BOOL bIsExtension = FALSE>

class ATL_NO_VTABLE CSnapInItemImpl : public CSnapInItem

Parameters

T

Your class, derived from CSnapInItemImpl.

bIsExtension

TRUE if the object is a snap-in extension; otherwise FALSE.

CSnapInItemImpl provides a basic implementation for a snap-in node object, such as adding menu items and toolbars, and forwarding commands for the snap-in node to the appropriate handler function. These features are implemented using several different interfaces and map types. The default implementation handles notifications sent to the node object by determining the correct instance of the derived class and then forwarding the message to the correct instance.

You would derive from this class for each different node type in your snap-in object and implement specific notification and command handlers using predefined maps. To add custom functionality, see the MMC Snap-In FAQ.

#include <atlsnap.h>

Class Members


CSnapInItemImpl Class Members

Construction |
CSnapInItemImpl | Constructs a CSnapInItemImpl object.

Attributes |
AddMenuItems | Adds menu items to a context menu.
Command | Called by the console when a custom menu item is selected.
CreatePropertyPages | Adds pages to the property sheet of the snap-in.
FillData | Copies information on the snap-in object into a specified stream.
GetResultViewType | Determines the type of view used by the result pane.
GetScopePaneInfo | Retrieves the SCOPEDATAITEM structure of the snap-in.
GetResultPaneInfo | Retrieves the RESULTDATAITEM structure of the snap-in.
Notify | Called by the console to notify the snap-in of actions taken by the user.
SetMenuInsertionFlags | Modifies the menu insertion flags for a snap-in object.
SetToolbarButtonInfo | Sets the information of the specified toolbar button.
UpdateMenuState | Updates the state of a context menu item.
UpdateToolbarButton | Updates the state of the specified toolbar button.

Data Members |
m_bstrDisplayName | The name of the snap-in object.
m_scopeDataItem | The Windows SCOPEDATAITEM structure used by the CSnapInItemImpl object.
m_resultDataItem | The Windows RESULTDATAITEM structure used by the CsnapInItemImpl object.

CSnapInItemImpl Overview


CSnapInItemImpl::AddMenuItems

AddMenuItems( LPCONTEXTMENUCALLBACK piCallback, long *pInsertionAllowed, DATA_OBJECT_TYPES type );

Parameters

piCallback

[in] Pointer to the IContextMenuCallback that can add items to the context menu.

pInsertionAllowed

[in, out] Identifies MMC-defined, menu-item insertion points that can be used. This can be a combination of the following flags:

  • CCM_INSERTIONALLOWED_TOP Items can be inserted at the top of a context menu.

  • CCM_INSERTIONALLOWED_NEW Items can be inserted in the Create New submenu.

  • CCM_INSERTIONALLOWED_TASK Items can be inserted in the Task submenu.

  • CCM_INSERTIONALLOWED_VIEW Items can be inserted in the toolbar view menu or in the View submenu of the result pane context menu.

type

[in] Specifies the type of object. It can have one of the following values:

  • CCT_SCOPE Data object for scope pane context.

  • CCT_RESULT Data object for result pane context.

  • CCT_SNAPIN_MANAGER Data object for snap-in manager context.

  • CCT_UNINITIALIZED Data object has an invalid type.

Remarks

This method implements the Win32 function IExtendContextMenu::AddMenuItems.


CSnapInItemImpl::Command

Command( long lCommandID, DATA_OBJECT_TYPES type );

Parameters

lCommandID

[in] Specifies the command identifier of the menu item.

type

[in] Specifies the type of object. It can have one of the following values:

  • CCT_SCOPE Data object for scope pane context.

  • CCT_RESULT Data object for result pane context.

  • CCT_SNAPIN_MANAGER Data object for snap-in manager context.

  • CCT_UNINITIALIZED Data object has an invalid type.

Remarks

This method implements the Win32 function IExtendContextMenu::Command.


CSnapInItemImpl::CreatePropertyPages

CreatePropertyPages( LPPROPERTYSHEETCALLBACK lpProvider, long handle, IUnknown* pUnk, DATA_OBJECT_TYPES type );

Parameters

lpProvider

[in] Pointer to the IPropertySheetCallback interface.

handle

[in] Specifies the handle used to route the MMCN_PROPERTY_CHANGE notification message to the appropriate data class.

pUnk

[in] Pointer to the IExtendPropertySheet interface on the object that contains context information about the node.

type

[in] Specifies the type of object. It can have one of the following values:

  • CCT_SCOPE Data object for scope pane context.

  • CCT_RESULT Data object for result pane context.

  • CCT_SNAPIN_MANAGER Data object for snap-in manager context.

  • CCT_UNINITIALIZED Data object has an invalid type.

Remarks

This method implements the Win32 function IExtendPropertySheet::CreatePropertyPages.


CSnapInItemImpl::CSnapInItemImpl

CSnapInItemImpl( );

Remarks

Constructs a CSnapInItemImpl object.


CSnapInItemImpl::FillData

FillData( CLIPFORMAT cf, LPSTREAM pStream );

Parameters

cf

[in] The format (text, rich text, or rich text with OLE items) of the Clipboard.

pStream

[in] A pointer to the stream containing the object data.

Remarks

This function is called to retrieve information about the item.

To properly implement this function, copy the correct information into the stream (pStream), depending on the Clipboard format indicated by cf.


CSnapInItemImpl::GetResultViewType

GetResultViewType( LPOLESTR *ppViewType, long *pViewOptions );

Parameters

ppViewType

[out] Pointer to the address of the returned view type.

pViewOptions

[out] Pointer to the MMC_VIEW_OPTIONS enumeration, which provides the console with options specified by the owning snap-in. This value can be one of the following:

  • MMC_VIEW_OPTIONS_NOLISTVIEWS = 0x00000001 Tells the console to refrain from presenting standard list view choices in the View menu. Allows the snap-in to display its own custom views only in the result view pane. This is the only option flag defined at this time.

  • MMC_VIEW_OPTIONS_NONE = 0 Allows the default view options.

Remarks

Call this function to retrieve the type of view for the result pane of the snap-in object.


CSnapInItemImpl::GetScopePaneInfo

GetScopePaneInfo ( SCOPEDATAITEM *pScopeDataItem );

Parameters

pScopeDataItem

[out] A pointer to the SCOPEDATAITEM structure of the CSnapInItemImpl object.

Remarks

Call this function to retrieve the SCOPEDATAITEM structure of the snap-in.


CSnapInItemImpl::GetResultPaneInfo

GetResultPaneInfo ( RESULTDATAITEM *pResultDataItem );

Parameters

pResultDataItem

[out] A pointer to the RESULTDATAITEM structure of the CSnapInItemImpl object.

Remarks

Call this function to retrieve the RESULTDATAITEM structure of the snap-in.


CSnapInItemImpl::Notify

STDMETHOD(Notify)(MMC_NOTIFY_TYPE event, long arg, long param, IComponentData* pComponentData, IComponent* pComponent, DATA_OBJECT_TYPES type) = 0;

Parameters

event

[in] Identifies an action taken by a user. The following notifications are possible:

  • MMCN_ACTIVATE Sent when a window is being activated and deactivated.

  • MMCN_ADD_IMAGES Sent to add images to the result pane.

  • MMCN_BTN_CLICK Sent when the user clicks on one of the toolbar buttons.

  • MMCN_CLICK Sent when a user clicks a mouse button on a list view item.

  • MMCN_DBLCLICK Sent when a user double clicks a mouse button on a list view item.

  • MMCN_DELETE Sent to inform the snap-in that the object should be deleted.

  • MMCN_EXPAND Sent when a folder needs to be expanded or contracted.

  • MMCN_MINIMIZED Sent when a window is being minimized or maximized.

  • MMCN_PROPERTY_CHANGE Sent to notify a snap-in object that it’s view is about to change.

  • MMCN_REMOVE_CHILDREN Sent when the snap-in must delete the entire subtree it has added below the specified node.

  • MMCN_RENAME Sent the first time to query for a rename and the second time to do the rename.

  • MMCN_SELECT Sent when an item in the scope or result view pane is selected.

  • MMCN_SHOW Sent when a scope item is selected or deselected for the first time.

  • MMCN_VIEW_CHANGE Sent when the snap-in can update all views when a change occurs.

arg

[in] Depends on the notification type.

param

[in] Depends on the notification type.

pComponentData

[out] A pointer to the object implementing IComponentData. This parameter is NULL if the notification is not being forwarded from IComponentData::Notify.

pComponent

[out] A pointer to the object that implements IComponent. This parameter is NULL if the notification is not being forwarded from IComponent::Notify.

type

[in] Specifies the type of object. It can have one of the following values:

  • CCT_SCOPE Data object for scope pane context.

  • CCT_RESULT Data object for result pane context.

  • CCT_SNAPIN_MANAGER Data object for snap-in manager context.

  • CCT_UNINITIALIZED Data object has an invalid type.

Remarks

Called when the snap-in object is acted upon by the user.


CSnapInItemImpl::QueryPagesFor

QueryPagesFor(DATA_OBJECT_TYPES type);

Remarks

Called to see if the snap-in node supports property pages.


CSnapInItemImpl::SetMenuInsertionFlags

void SetMenuInsertionFlags( bool bBeforeInsertion, long* pInsertionAllowed );

Parameters

bBeforeInsertion

[in] Nonzero if the function should be called before items are added to the context menu; otherwise 0.

pInsertionAllowed

[in, out] Identifies MMC-defined, menu-item insertion points that can be used. This can be a combination of the following flags:

  • CCM_INSERTIONALLOWED_TOP Items can be inserted at the top of a context menu.

  • CCM_INSERTIONALLOWED_NEW Items can be inserted in the Create New submenu.

  • CCM_INSERTIONALLOWED_TASK Items can be inserted in the Task submenu.

  • CCM_INSERTIONALLOWED_VIEW Items can be inserted in the toolbar view menu or in the View submenu of the result pane context menu.

Remarks

Call this function to modify the menu insertion flags, specified by pInsertionAllowed, for the snap-in object.

If you are developing a primary snap-in, you can reset any of the insertion flags as a way of restricting the kind of menu items that a third-party extension can add. For example, the primary snap-in can clear the CCM_INSERTIONALLOWED_NEW flag to prevent extensions from adding their own Create New menu items.

You should not attempt to set bits in pInsertionAllowed that were originally cleared. Future versions of MMC may use bits not currently defined so you should not change bits that are currently not defined.


CSnapInItemImpl::SetToolbarButtonInfo

void SetToolbarButtonInfo( UINT id, BYTE *fsState, BYTE *fsType );

Parameters

id

[in] The ID of the toolbar button to be set.

fsState

[in] The state flags of the button. Can be one or more of the following:

  • TBSTATE_CHECKED The button has the TBSTYLE_CHECKED style and is being pressed.

  • TBSTATE_ENABLED The button accepts user input. A button that does not have this state does not accept user input and is grayed.

  • TBSTATE_HIDDEN The button is not visible and cannot receive user input.

  • TBSTATE_INDETERMINATE The button is grayed.

  • TBSTATE_PRESSED The button is being pressed.

  • TBSTATE_WRAP A line break follows the button. The button must also have the TBSTATE_ENABLED.

fsType

[in] The state flags of the button. Can be one or more of the following:

  • TBSTYLE_BUTTON Creates a standard push button.

  • TBSTYLE_CHECK Creates a button that toggles between the pressed and not-pressed states each time the user clicks it. The button has a different background color when it is in the pressed state.

  • TBSTYLE_CHECKGROUP Creates a check button that stays pressed until another button in the group is pressed.

  • TBSTYLE_GROUP Creates a button that stays pressed until another button in the group is pressed.

  • TBSTYLE_SEP Creates a separator, providing a small gap between button groups. A button that has this style does not receive user input.

Remarks

Call this function to modify any toolbar button styles, of the snap-in object, before the toolbar is created.


CSnapInItemImpl::UpdateMenuState

void UpdateMenuState( UINT id, LPTSTR pBuf, UINT *flags );

Parameters

id

[in] The ID of the menu item to be set.

pBuf

[in] A pointer to the string for the menu item to be updated.

flags

[in] Specifies the new state flags. This can be a combination of the following flags:

  • MF_POPUP Specifies that this is a submenu within the context menu. Menu items, insertion points, and further submenus may be added to this submenu using its lCommandID as their IInsertionPointID.

  • MF_BITMAP and MF_OWNERDRAW These flags are not permitted and will result in a return value of E_INVALIDARG.

  • MF_SEPARATOR Draws a horizontal dividing line. Only IContextMenuProvider is allowed to add menu items with MF_SEPARATOR set.

  • MF_CHECKED Places a check mark next to the menu item.

  • MF_DISABLED Disables the menu item so it cannot be selected, but the flag does not gray it.

  • MF_ENABLED Enables the menu item so it can be selected, restoring it from its grayed state.

  • MF_GRAYED Disables the menu item, graying it so it cannot be selected.

  • MF_MENUBARBREAK Functions the same as the MF_MENUBREAK flag for a menu bar. For a drop-down menu, submenu, or shortcut menu, the new column is separated from the old column by a vertical line.

  • MF_MENUBREAK Places the item on a new line (for a menu bar) or in a new column (for a drop-down menu, submenu, or shortcut menu) without separating columns.

  • MF_UNCHECKED Does not place a check mark next to the item (default).

    The following groups of flags cannot be used together:

  • MF_DISABLED, MF_ENABLED, and MF_GRAYED

  • MF_MENUBARBREAK and MF_MENUBREAK

  • MF_CHECKED and MF_UNCHECKED

Remarks

Call this function to modify a menu item before it is inserted into the context menu of the snap-in object.


CSnapInItemImpl::UpdateToolbarButton

BOOL UpdateToolbarButton( UINT id, BYTE fsState );

Parameters

id

Specifies the button ID of the toolbar button to be updated.

fsState

Specifies a toolbar button state. If this state is to be set, return TRUE. This can be a combination of the following flags:

  • ENABLED The button accepts user input. A button that does not have this state does not accept user input and is grayed.

  • CHECKED The button has the CHECKED style and is being pressed.

  • HIDDEN The button is not visible and cannot receive user input.

  • INDETERMINATE The button is grayed.

  • BUTTONPRESSED The button is being pressed.

Remarks

Call this function to modify a toolbar button, of the snap-in object, before it is displayed.


CSnapInItemImpl::m_bstrDisplayName

CComBSTR m_bstrDisplayName;

Remarks

Contains the string displayed for the node item.


CSnapInItemImpl::m_scopeDataItem

SCOPEDATAITEM m_scopeDataItem;

Remarks

The SCOPEDATAITEM structure of the snap-in data object.


CSnapInItemImpl::m_resultDataItem

RESULTDATAITEM m_resultDataItem;

Remarks

The RESULTDATAITEM structure of the snap-in data object.


CStockPropImpl

template < class T, class InterfaceName, const IID* piid, const GUID* plibid >
class CStockPropImpl : IDispatchImpl< InterfaceName, piid, plibid >

Parameters

T

The class implementing the control.

InterfaceName

A dual interface.

piid

A pointer to the IID of InterfaceName.

plibid

A pointer to the identifier of GUID of the type library section of InterfaceName.

CStockPropImpl implements every stock property you can choose from the Stock Properties tab in the ATL Object Wizard. The Object Wizard automatically creates a data member in your control class for each property, creates put and get methods for each property, and adds code to notify and synchronize with the container when any property changes.

The ATL Object Wizard can also be used to implement any or all of the stock properties in the same manner. For more information about adding stock properties to a control, see the ATL Tutorial. For more information about the ATL Object Wizard, see the article Creating an ATL Project.

CStockPropImpl implements put and get methods for the stock properties that are interface pointers, including FONT, MOUSEICON, and PICTURE. For all other stock properties, CStockPropImpl calls the macros IMPLEMENT_STOCKPROP, IMPLEMENT_BOOL_STOCKPROP , and IMPLEMENT_BSTR_STOCKPROP.

The following table lists the stock properties implemented and the data members created by CStockPropImpl. See the data members in CComControl for a description of each property, except HWND, whose data member is described in CWindow.

Stock Property | Data Member
APPEARANCE | m_nAppearance
AUTOSIZE | m_bAutoSize
BACKCOLOR | m_clrBackColor
BACKSTYLE | m_nBackStyle
BORDERCOLOR | m_clrBorderColor
BORDERSTYLE | m_nBorderStyle
BORDERVISIBLE | m_bBorderVisible
BORDERWIDTH | m_nBorderWidth
CAPTION | m_bstrCaption
DRAWMODE | m_nDrawMode
DRAWSTYLE | m_nDrawStyle
DRAWWIDTH | m_nDrawWidth
ENABLED | m_bEnabled
FILLCOLOR | m_clrFillColor
FILLSTYLE | m_nFillStyle
FONT | m_pFont
FORECOLOR | m_clrForeColor
HWND | m_hWnd
MOUSEICON | m_pMouseIcon
MOUSEPOINTER | m_nMousePointer
PICTURE | m_pPicture
READYSTATE | m_nReadyState
TABSTOP | m_bTabStop
TEXT | m_bstrText
VALID | m_bValid

#include <atlctl.h>


CWindow

class CWindow

CWindow provides the base functionality for manipulating a window in ATL. Many of the CWindow methods simply wrap one of the Win32 API functions. For example, compare the prototypes for CWindow::ShowWindow and ::ShowWindow:

CWindow method | Win32 function
BOOL ShowWindow( int nCmdShow ); | BOOL ShowWindow( HWND hWnd, int nCmdShow );

CWindow::ShowWindow calls the Win32 function ShowWindow by passing CWindow::m_hWnd as the first parameter. Every CWindow method that directly wraps a Win32 function passes the m_hWnd member; therefore, much of the CWindow documentation will refer you to the Win32 SDK documentation.

Note Not every window-related Win32 function is wrapped by CWindow, and not every CWindow method wraps a Win32 function.

CWindow::m_hWnd stores the HWND that identifies a window. An HWND is attached to your object when you:

  • Specify an HWND in CWindow’s constructor.

  • Call CWindow::Attach.

  • Use CWindow’s operator =.

  • Create or subclass a window using one of the following classes derived from CWindow:

    CWindowImpl Allows you to create a new window or subclass an existing window.

    CContainedWindow Implements a window contained within another object. You can create a new window or subclass an existing window.

    CDialogImpl Allows you to create a modal or modeless dialog box.

For more information about windows, see Windows and subsequent topics in the Win32 SDK. For more information about using windows in ATL, see the article ATL Window Classes.

#include <atlwin.h>

Class Members


CWindow Class Members

Alert Methods | Data Members
Attribute Methods | Icon Methods
Caret Methods | Menu Methods
Clipboard Methods | Message Methods
Construction, Destruction, and Initialization | Process and Thread Methods
Window Tree Access Methods | Scrolling Methods
Coordinate Mapping Methods | Timer Methods
Dialog Box Item Methods | Update and Painting Methods
Drag-Drop Methods | Window Access Methods
Font Methods | Window Size and Position Methods
Help Methods | Window State Methods

Hot Key Methods | Window Text Methods
Operators |

Alert Methods

FlashWindow | Flashes the window once.
MessageBox | Displays a message box.

Attribute Methods

GetExStyle | Retrieves the extended window styles.
GetStyle | Retrieves the window styles.
GetWindowLong | Retrieves a 32-bit value at a specified offset into the extra window memory.
GetWindowWord | Retrieves a 16-bit value at a specified offset into the extra window memory.
ModifyStyle | Modifies the window styles.
ModifyStyleEx | Modifies the extended window styles.
SetWindowLong | Sets a 32-bit value at a specified offset into the extra window memory.
SetWindowWord | Sets a 16-bit value at a specified offset into the extra window memory.

Caret Methods

CreateCaret | Creates a new shape for the system caret.
CreateGrayCaret | Creates a gray rectangle for the system caret.
CreateSolidCaret | Creates a solid rectangle for the system caret.
HideCaret | Hides the system caret.
ShowCaret | Displays the system caret.

Clipboard Methods

ChangeClipboardChain | Removes the window from the chain of Clipboard viewers.
OpenClipboard | Opens the Clipboard.
SetClipboardViewer | Adds the window to the Clipboard viewer chain.

Construction, Destruction, and Initialization

Create | Creates a window.
Attach | Attaches a window to the CWindow object.
CWindow | Constructor.
DestroyWindow | Destroys the window associated with the CWindow object.
Detach | Detaches the window from the CWindow object.

Coordinate Mapping Methods

ClientToScreen | Converts client coordinates to screen coordinates.
MapWindowPoints | Converts a set of points from the window’s coordinate space to the coordinate space of another window.
ScreenToClient | Converts screen coordinates to client coordinates.

Dialog Box Item Methods

CheckDlgButton | Changes the check state of the specified button.
CheckRadioButton | Checks the specified radio button.
DlgDirList | Fills a list box with the names of all files matching a specified path or filename.
DlgDirListComboBox | Fills a combo box with the names of all files matching a specified path or filename.
DlgDirSelect | Retrieves the current selection from a list box.
DlgDirSelectComboBox | Retrieves the current selection from a combo box.
GetDlgItemInt | Translates a control’s text to an integer.
GetDlgItemText | Retrieves a control’s text.
GetNextDlgGroupItem | Retrieves the previous or next control within a group of controls.
GetNextDlgTabItem | Retrieves the previous or next control having the WS_TABSTOP style.
GotoDlgCtrl | Sets the keyboard focus to a control in the dialog box.
IsDialogMessage | Determines whether a message is intended for the specified dialog box.
IsDlgButtonChecked | Determines the check state of the button.
NextDlgCtrl | Sets the keyboard focus to the next control in the dialog box.
PrevDlgCtrl | Sets the keyboard focus to the previous control in the dialog box.
SendDlgItemMessage | Sends a message to a control.
SetDlgItemInt | Changes a control’s text to the string representation of an integer value.
GetDlgControl | Retrieves the IUnknown of the specified control.
SetDlgItemText | Changes a control’s text.

Drag-Drop Methods

DragAcceptFiles Registers whether the window accepts dragged files.

Font Methods

GetFont | Retrieves the window’s current font.
SetFont | Changes the window’s current font.

Help Methods

GetWindowContextHelpId | Retrieves the window’s help context identifier.
SetWindowContextHelpId | Sets the window’s help context identifier.
WinHelp | Starts Windows Help.

Hot Key Methods

GetHotKey | Determines the hot key associated with the window.
SetHotKey | Associates a hot key with the window.

Icon Methods

GetIcon | Retrieves the window’s large or small icon.
SetIcon | Changes the window’s large or small icon.

Menu Methods

DrawMenuBar | Redraws the window’s menu bar.
GetMenu | Retrieves the window’s menu.
GetSystemMenu | Creates a copy of the system menu for modification.
HiliteMenuItem | Highlights or removes the highlight from a top-level menu item.
SetMenu | Changes the window’s current menu.

Message Methods

PostMessage | Places a message in the message queue associated with the thread that created the window. Returns without waiting for the thread to process the message.
SendMessage | Sends a message to the window and does not return until the window procedure has processed the message.
SendNotifyMessage | Sends a message to the window. If the window was created by the calling thread, SendNotifyMessage does not return until the window procedure has processed the message. Otherwise, it returns immediately.

Process and Thread Methods

GetWindowThreadID | Retrieves the identifier of the thread that created the specified window.
GetWindowProcessID | Retieves the identifier of the process that created the window.

Scrolling Methods

EnableScrollBar | Enables or disables the scroll bar arrows.
GetScrollInfo | Retrieves the parameters of a scroll bar.
GetScrollPos | Retrieves the position of the scroll box.
GetScrollRange | Retrieves the scroll bar range.
ScrollWindow | Scrolls the specified client area.
ScrollWindowEx | Scrolls the specified client area with additional features.
SetScrollInfo | Sets the parameters of a scroll bar.
SetScrollPos | Changes the position of the scroll box.
SetScrollRange | Changes the scroll bar range.
ShowScrollBar | Shows or hides a scroll bar.

Timer Methods

KillTimer | Destroys a timer event.
SetTimer | Creates a timer event.

Update and Painting Methods

BeginPaint | Prepares the window for painting.
EndPaint | Marks the end of painting.
GetDC | Retrieves a device context for the client area.
GetDCEx | Retrieves a device context for the client area and allows clipping options.
GetUpdateRect | Retrieves the coordinates of the smallest rectangle that completely encloses the update region.
GetUpdateRgn | Retrieves the update region and copies it into a specified region.
GetWindowDC | Retrieves a device context for the entire window.
Invalidate | Invalidates the entire client area.
InvalidateRect | Invalidates the client area within the specified rectangle.
InvalidateRgn | Invalidates the client area within the specified region.
IsWindowVisible | Determines the window’s visibility state.
LockWindowUpdate | Disables or enables drawing in the window.
Print | Requests that the window be drawn in a specified device context.
PrintClient | Requests that the window’s client area be drawn in a specified device context.
RedrawWindow | Updates a specified rectangle or region in the client area.
ReleaseDC | Releases a device context.
SetRedraw | Sets or clears the redraw flag.
ShowOwnedPopups | Shows or hides the pop-up windows owned by the window.
ShowWindow | Sets the window’s show state.
ShowWindowAsync | Sets the show state of a window created by a different thread.
UpdateWindow | Updates the client area.
ValidateRect | Validates the client area within the specified rectangle.
ValidateRgn | Validates the client area within the specified region.

Window Access Methods

ChildWindowFromPoint | Retrieves the child window containing the specified point.
ChildWindowFromPointEx | Retrieves a particular type of child window containing the specified point.
GetLastActivePopup | Retrieves the most recently active pop-up window.
GetParent | Retrieves the immediate parent window.
GetTopLevelParent | Retrieves the top-level parent or owner window.
GetTopLevelWindow | Retrieves the top-level owner window.
GetTopWindow | Retrieves the top-level child window.
GetWindow | Retrieves the specified window.
IsChild | Determines whether the specified window is a child window.
SetParent | Changes the parent window.

Window Size and Position Methods

ArrangeIconicWindows | Arranges all minimized child windows.
BringWindowToTop | Brings the window to the top of the Z order.
CenterWindow | Centers the window against a given window.
DeferWindowPos | Updates the specified multiple-window-position structure for the specified window.
GetClientRect | Retrieves the coordinates of the client area.
GetWindowPlacement | Retrieves the show state and positions.
GetWindowRect | Retrieves the window’s bounding dimensions.
GetWindowRgn | Obtains a copy of the window region of a window.
IsIconic | Determines whether the window is minimized.
IsZoomed | Determines whether the window is maximized.
MoveWindow | Changes the window’s size and position.
ResizeClient | Resizes the window.
SetWindowPlacement | Sets the show state and positions.
SetWindowPos | Sets the size, position, and Z order.
SetWindowRgn | Sets the window region of a window.

Window State Methods

EnableWindow | Enables or disables input.
IsWindow | Determines whether the specified window handle identifies an existing window.
IsWindowEnabled | Determines whether the window is enabled for input.
IsWindowUnicode | Determines whether the specified window is a native Unicode window.
SetActiveWindow | Activates the window.
SetCapture | Sends all subsequent mouse input to the window.
SetFocus | Sets the input focus to the window.

Window Text Methods

GetWindowText | Retrieves the window’s text.
GetWindowTextLength | Retrieves the length of the window’s text.
SetWindowText | Changes the window’s text.

Window Tree Access Methods

GetDescendantWindow | Retrieves the specified descendant window.
GetDlgCtrlID | Retrieves the window’s identifier (for child windows only).
GetDlgItem | Retrieves the specified child window.
SendMessageToDescendants | Sends a message to the specified descendant windows.
SetDlgCtrlID | Changes the window’s identifier.

Operators

operator HWND | Converts the CWindow object to an HWND.
operator = | Assigns an HWND to the CWindow object.

Data Members

m_hWnd The handle to the window associated with the CWindow object.

CWindow Overview


CWindow::ArrangeIconicWindows

UINT ArrangeIconicWindows( );

See ArrangeIconicWindows in the Win32 SDK.

Remarks

Arranges all minimized child windows.


CWindow::Attach

void Attach( HWND hWndNew );

Parameters

hWndNew

[in] The handle to a window.

Remarks

Attaches the window identified by hWndNew to the CWindow object.

CWindow Overview | Class Members

See Also CWindow::Detach


CWindow::BeginPaint

HDC BeginPaint( LPPAINTSTRUCT lpPaint );

See BeginPaint in the Win32 SDK.

Remarks

Prepares the window for painting.

CWindow Overview | Class Members

See Also CWindow::EndPaint


CWindow::BringWindowToTop

BOOL BringWindowToTop( );

See BringWindowToTop in the Win32 SDK.

Remarks

Brings the window to the top of the Z order.

CWindow Overview | Class Members

See Also CWindow::MoveWindow, CWindow::SetWindowPos


CWindow::CenterWindow

BOOL CenterWindow( HWND hWndCenter = NULL );

Return Value

TRUE if the window is successfully centered; otherwise, FALSE.

Parameters

hWndCenter

[in] The handle to the window against which to center. If this parameter is NULL (the default value), the method will set hWndCenter to the window’s parent window if it is a child window. Otherwise, it will set hWndCenter to the window’s owner window.

Remarks

Centers the window against a given window.

CWindow Overview | Class Members

See Also CWindow::MoveWindow, CWindow::SetWindowPos


CWindow::ChangeClipboardChain

BOOL ChangeClipboardChain( HWND hWndNewNext );

See ChangeClipboardChain in the Win32 SDK.

Remarks

Removes the window from the chain of Clipboard viewers.

CWindow Overview | Class Members

See Also CWindow::SetClipboardViewer


CWindow::CheckDlgButton

BOOL CheckDlgButton( int nIDButton, UINT nCheck );

See CheckDlgButton in the Win32 SDK.

Remarks

Changes the check state of the specified button.

CWindow Overview | Class Members

See Also CWindow::CheckRadioButton, CWindow::IsDlgButtonChecked


CWindow::CheckRadioButton

BOOL CheckRadioButton( int nIDFirstButton, int nIDLastButton, int nIDCheckButton );

See CheckRadioButton in the Win32 SDK.

Remarks

Checks the specified radio button.

CWindow Overview | Class Members

See Also CWindow::CheckDlgButton


CWindow::ChildWindowFromPoint

HWND ChildWindowFromPoint( POINT point ) const;

See ChildWindowFromPoint in the Win32 SDK.

Remarks

Retrieves the child window containing the specified point.

CWindow Overview | Class Members

See Also CWindow::ChildWindowFromPointEx, POINT


CWindow::ChildWindowFromPointEx

HWND ChildWindowFromPoint( POINT point, UINT uFlags ) const;

See ChildWindowFromPointEx in the Win32 SDK.

Remarks

Retrieves a particular type of child window containing the specified point.

CWindow Overview | Class Members

See Also CWindow::ChildWindowFromPoint, POINT


CWindow::ClientToScreen

BOOL ClientToScreen( LPPOINT lpPoint ) const;

BOOL ClientToScreen( LPRECT lpRect ) const;

See ClientToScreen in the Win32 SDK.

Remarks

Converts client coordinates to screen coordinates. The second version of this method allows you to convert the coordinates of a RECT structure.

CWindow Overview | Class Members

See Also CWindow::ScreenToClient, POINT


CWindow::Create

HWND Create( LPCTSTR lpstrWndClass, HWND hWndParent, RECT& rcPos, LPCTSTR szWindowName = NULL, DWORD dwStyle = 0, DWORD dwExStyle = 0, UINT nID = 0, LPVOID lpCreateParam = NULL )

HWND Create( LPCTSTR lpstrWndClass, HWND hWndParent, LPRECT lpRect = NULL, LPCTSTR szWindowName = NULL, DWORD dwStyle = 0, DWORD dwExStyle = 0, HMENU hMenu = NULL, LPVOID lpCreateParam = NULL )

Return Value

If successful, the handle to the newly created window, specified by m_hWnd. Otherwise, NULL.

Parameters

lpstrWndClass

[in] A pointer to the window’s class.

hWndParent

[in] The handle to the parent or owner window.

rcPos

[in] A RECT structure specifying the position of the window.

szWindowName

[in] Specifies the name of the window. The default value is NULL.

dwStyle

[in] The style of the window. The default value is 0, meaning no style is specified. For a list of possible values, see CreateWindow in the Platform SDK.

dwExStyle

[in] The extended window style. The default value is 0, meaning no extended style is specified. For a list of possible values, see CreateWindowEx in the Win32 SDK.

nID

[in] For a child window, the window identifier. For a top-level window, an HWND casted to a UINT. The default value is 0.

hMenu

A handle to the window’s menu.

lpCreateParam

A pointer to the window-creation data contained in a CREATESTRUCT structure.

Remarks

Creates a window. See CreateWindow in the Platform SDK for more information.

CWindow Overview | Class Members

See Also

CWindow::m_hWnd


CWindow::CreateCaret

BOOL CreateCaret( HBITMAP pBitmap );

See CreateCaret in the Win32 SDK.

Remarks

Creates a new shape for the system caret.

CWindow Overview | Class Members

See Also CWindow::CreateGrayCaret, CWindow::CreateSolidCaret


CWindow::CreateGrayCaret

BOOL CreateGrayCaret( int nWidth, int nHeight );

See CreateCaret in the Win32 SDK.

Remarks

Creates a gray rectangle for the system caret. Passes (HBITMAP) 1 for the bitmap handle parameter to the Win32 function.

CWindow Overview | Class Members

See Also CWindow::CreateCaret, CWindow::CreateSolidCaret


CWindow::CreateSolidCaret

BOOL CreateSolidCaret( int nWidth, int nHeight );

See CreateCaret in the Win32 SDK.

Remarks

Creates a solid rectangle for the system caret. Passes (HBITMAP) 0 for the bitmap handle parameter to the Win32 function.

CWindow Overview | Class Members

See Also CWindow::CreateCaret, CWindow::CreateGrayCaret


CWindow::CWindow

CWindow( HWND hWnd = NULL );

Parameters

hWnd

[in] The handle to a window.

Remarks

The constructor. Initializes the m_hWnd member to hWnd, which by default is NULL.

Note CWindow::CWindow does not create a window. Classes CWindowImpl, CContainedWindow, and CDialogImpl (all of which derive from CWindow) provide a method to create a window or dialog box, which is then assigned to CWindow::m_hWnd. You can also use the CreateWindow Win32 function.


CWindow::DeferWindowPos

HDWP DeferWindowPos( HDWP hWinPosInfo, HWND hWndInsertAfter, int x, int y, int cx, int cy, UINT uFlags );

See DeferWindowPos in the Win32 SDK.

Remarks

Updates the specified multiple-window-position structure for the specified window.


CWindow::DestroyWindow

BOOL DestroyWindow( );

See DestroyWindow in the Win32 SDK.

Remarks

Destroys the window associated with the CWindow object and sets m_hWnd to NULL. It does not destroy the CWindow object itself.


CWindow::Detach

HWND Detach( );

Return Value

The HWND associated with the CWindow object.

Remarks

Detaches m_hWnd from the CWindow object and sets m_hWnd to NULL.

CWindow Overview | Class Members

See Also CWindow::Attach


CWindow::DlgDirList

int DlgDirList( LPTSTR lpPathSpec, int nIDListBox, int nIDStaticPath, UINT nFileType );

See DlgDirList in the Win32 SDK.

Remarks

Fills a list box with the names of all files matching a specified path or filename.

CWindow Overview | Class Members

See Also CWindow::DlgDirListComboBox, CWindow::DlgDirSelect, CWindow::DlgDirSelectComboBox


CWindow::DlgDirListComboBox

int DlgDirListComboBox( LPTSTR lpPathSpec, int nIDComboBox, int nIDStaticPath, UINT nFileType );

See DlgDirListComboBox in the Win32 SDK.

Remarks

Fills a combo box with the names of all files matching a specified path or filename.

CWindow Overview | Class Members

See Also CWindow::DlgDirList, CWindow::DlgDirSelect, CWindow::DlgDirSelectComboBox


CWindow::DlgDirSelect

BOOL DlgDirSelect( LPTSTR lpString, int nCount, int nIDListBox );

See DlgDirSelectEx in the Win32 SDK.

Remarks

Retrieves the current selection from a list box.

CWindow Overview | Class Members

See Also CWindow::DlgDirSelectComboBox, CWindow::DlgDirList


CWindow::DlgDirSelectComboBox

BOOL DlgDirSelectComboBox( LPTSTR lpString, int nCount, int nIDComboBox );

See DlgDirSelectComboBoxEx in the Win32 SDK.

Remarks

Retrieves the current selection from a combo box.

CWindow Overview | Class Members

See Also CWindow::DlgDirSelect, CWindow::DlgDirListComboBox


CWindow::DragAcceptFiles

void DragAcceptFiles( BOOL bAccept = TRUE );

See DragAcceptFiles in the Win32 SDK.

Remarks

Registers whether the window accepts dragged files.


CWindow::DrawMenuBar

BOOL DrawMenuBar( );

See DrawMenuBar in the Win32 SDK.

Remarks

Redraws the window’s menu bar.

CWindow Overview | Class Members

See Also CWindow::GetMenu, CWindow::SetMenu


CWindow::EnableScrollBar

BOOL EnableScrollBar( UINT uSBFlags, UINT uArrowFlags = ESB_ENABLE_BOTH );

See EnableScrollBar in the Win32 SDK.

Remarks

Enables or disables the scroll bar arrows.

CWindow Overview | Class Members

See Also CWindow::ShowScrollBar


CWindow::EnableWindow

BOOL EnableWindow( BOOL bEnable = TRUE );

See EnableWindow in the Win32 SDK.

Remarks

Enables or disables input.

CWindow Overview | Class Members

See Also CWindow::IsWindowEnabled


CWindow::EndPaint

void EndPaint( LPPAINTSTRUCT lpPaint );

See EndPaint in the Win32 SDK.

Remarks

Marks the end of painting.

CWindow Overview | Class Members

See Also CWindow::BeginPaint


CWindow::FlashWindow

BOOL FlashWindow( BOOL bInvert );

See FlashWindow in the Win32 SDK.

Remarks

Flashes the window once.

CWindow Overview | Class Members

See Also CWindow::SetTimer


CWindow::GetClientRect

BOOL GetClientRect( LPRECT lpRect ) const;

See GetClientRect in the Win32 SDK.

Remarks

Retrieves the coordinates of the client area.

CWindow Overview | Class Members

See Also CWindow::GetWindowRect, RECT


CWindow::GetDC

HDC GetDC( );

See GetDC in the Win32 SDK.

Remarks

Retrieves a device context for the client area.

CWindow Overview | Class Members

See Also CWindow::GetDCEx, CWindow::GetWindowDC, CWindow::ReleaseDC


CWindow::GetDCEx

HDC GetDCEx( HRGN hRgnClip, DWORD flags );

See GetDCEx in the Win32 SDK.

Remarks

Retrieves a device context for the client area and allows clipping options.

CWindow Overview | Class Members

See Also CWindow::GetDC, CWindow::GetWindowDC, CWindow::ReleaseDC


CWindow::GetDescendantWindow

HWND GetDescendantWindow( int nID ) const;

Return Value

The handle to a descendant window.

Parameters

nID

[in] The identifier of the descendant window to be retrieved.

Remarks

Finds the descendant window specified by the given identifier. GetDescendantWindow searches the entire tree of child windows, not only the windows that are immediate children.

CWindow Overview | Class Members

See Also CWindow::GetDlgItem


CWindow::GetDlgControl

HRESULT GetDlgControl( int nID, IUnknown** ppUnkCtrl );

Parameters

nID

[in] The resource ID of the control being retreived

ppUnkCtrl

[out] A pointer to the IUnknown of the specified control.

Remarks

Call this function to retrieve the pointer to the IUnknown interface of a hosted control., specified by nID.


CWindow::GetDlgCtrlID

int GetDlgCtrlID( ) const;

See GetDlgCtrlID in the Win32 SDK.

Remarks

Retrieves the window’s identifier (for child windows only).

CWindow Overview | Class Members

See Also CWindow::SetDlgCtrlID


CWindow::GetDlgItem

HWND GetDlgItem( int nID ) const;

See GetDlgItem in the Win32 SDK.

Remarks

Retrieves the specified child window.

CWindow Overview | Class Members

See Also CWindow::GetDescendantWindow


CWindow::GetDlgItemInt

UINT GetDlgItemInt( int nID, BOOL* lpTrans = NULL, BOOL bSigned = TRUE ) const;

See GetDlgItemInt in the Win32 SDK.

Remarks

Translates a control’s text to an integer.

CWindow Overview | Class Members

See Also CWindow::SetDlgItemInt, CWindow::GetDlgItemText


CWindow::GetDlgItemText

UINT GetDlgItemText( int nID, LPTSTR lpStr, int nMaxCount ) const;

BOOL GetDlgItemText( int nID, BSTR& bstrText ) const;

See GetDlgItemText in the Win32 SDK.

Remarks

Retrieves a control’s text. The second version of this method allows you to copy the control’s text to a BSTR. This version returns TRUE if the text is successfully copied; otherwise, FALSE.

CWindow Overview | Class Members

See Also CWindow::SetDlgItemText, CWindow::GetDlgItem


CWindow::GetExStyle

DWORD GetExStyle( ) const;

Return Value

The window’s extended styles.

Remarks

Retrieves the extended window styles of the window.

To retrieve the regular window styles, call GetStyle.

CWindow Overview | Class Members

See Also CWindow::ModifyStyleEx


CWindow::GetFont

HFONT GetFont( ) const;

Return Value

A font handle.

Remarks

Retrieves the window’s current font by sending a WM_GETFONT message to the window.

CWindow Overview | Class Members

See Also CWindow::SetFont


CWindow::GetHotKey

DWORD GetHotKey( ) const;

Return Value

The virtual key code and modifiers for the hot key associated with the window. For a list of possible modifiers, see WM_GETHOTKEY in the Win32 SDK.

Remarks

Determines the hot key associated with the window by sending a WM_GETHOTKEY message.

CWindow Overview | Class Members

See Also CWindow::SetHotKey


CWindow::GetIcon

HICON GetIcon( BOOL bBigIcon = TRUE ) const;

Return Value

An icon handle.

Parameters

bBigIcon

[in] If TRUE (the default value) the method returns the large icon. Otherwise, it returns the small icon.

Remarks

Retrieves the handle to the window’s large or small icon. GetIcon sends a WM_GETICON message to the window.

CWindow Overview | Class Members

See Also CWindow::SetIcon


CWindow::GetLastActivePopup

HWND GetLastActivePopup( ) const;

See GetLastActivePopup in the Win32 SDK.

Remarks

Retrieves the most recently active pop-up window.


CWindow::GetMenu

HMENU GetMenu( ) const;

See GetMenu in the Win32 SDK.

Remarks

Retrieves the window’s menu.

CWindow Overview | Class Members

See Also CWindow::SetMenu


CWindow::GetNextDlgGroupItem

HWND GetNextDlgGroupItem( HWND hWndCtl, BOOL bPrevious = FALSE ) const;

See GetNextDlgGroupItem in the Win32 SDK.

Remarks

Retrieves the previous or next control within a group of controls.

CWindow Overview | Class Members

See Also CWindow::GetNextDlgTabItem


CWindow::GetNextDlgTabItem

HWND GetNextDlgTabItem( HWND hWndCtl, BOOL bPrevious = FALSE ) const;

See GetNextDlgTabItem in the Win32 SDK.

Remarks

Retrieves the previous or next control having the WS_TABSTOP style.

CWindow Overview | Class Members

See Also CWindow::GetNextDlgGroupItem


CWindow::GetParent

HWND GetParent( ) const;

See GetParent in the Win32 SDK.

Remarks

Retrieves the immediate parent window.

CWindow Overview | Class Members

See Also CWindow::SetParent


CWindow::GetScrollInfo

BOOL GetScrollInfo( int nBar, LPSCROLLINFO lpScrollInfo );

See GetScrollInfo in the Win32 SDK.

Remarks

Retrieves the parameters of a scroll bar.

CWindow Overview | Class Members

See Also CWindow::SetScrollInfo


CWindow::GetScrollPos

int GetScrollPos( int nBar ) const;

See GetScrollPos in the Win32 SDK.

Remarks

Retrieves the position of the scroll box.

CWindow Overview | Class Members

See Also CWindow::SetScrollPos


CWindow::GetScrollRange

BOOL GetScrollRange( int nBar, LPINT lpMinPos, LPINT lpMaxPos ) const;

See GetScrollRange in the Win32 SDK.

Remarks

Retrieves the scroll bar range.

CWindow Overview | Class Members

See Also CWindow::SetScrollRange


CWindow::GetStyle

DWORD GetStyle( ) const;

Return Value

The window’s styles.

Remarks

Retrieves the window styles of the window.

To retrieve the extended window styles, call GetExStyle.

CWindow Overview | Class Members

See Also CWindow::ModifyStyle


CWindow::GetSystemMenu

HMENU GetSystemMenu( BOOL bRevert ) const;

See GetSystemMenu in the Win32 SDK.

Remarks

Creates a copy of the system menu for modification.

CWindow Overview | Class Members

See Also CWindow::GetMenu


CWindow::GetTopLevelParent

HWND GetTopLevelParent( ) const;

Return Value

The handle to the top-level parent window.

Remarks

Retrieves the window’s top-level parent window.

CWindow Overview | Class Members

See Also CWindow::GetParent, CWindow::GetTopLevelWindow, CWindow::GetWindow


CWindow::GetTopLevelWindow

HWND GetTopLevelWindow( ) const;

Return Value

The handle to the top-level owner window.

Remarks

Retrieves the window’s top-level parent or owner window.

CWindow Overview | Class Members

See Also CWindow::GetTopLevelParent, CWindow::GetWindow


CWindow::GetTopWindow

HWND GetTopWindow( ) const;

See GetTopWindow in the Win32 SDK.

Remarks

Retrieves the top-level child window.

CWindow Overview | Class Members

See Also CWindow::GetWindow


CWindow::GetUpdateRect

BOOL GetUpdateRect( LPRECT lpRect, BOOL bErase = FALSE );

See GetUpdateRect in the Win32 SDK.

Remarks

Retrieves the coordinates of the smallest rectangle that completely encloses the update region.

CWindow Overview | Class Members

See Also CWindow::GetUpdateRgn, RECT


CWindow::GetUpdateRgn

int GetUpdateRgn( HRGN hRgn, BOOL bErase = FALSE );

See GetUpdateRgn in the Win32 SDK.

Remarks

Retrieves the update region and copies it into a specified region.

CWindow Overview | Class Members

See Also CWindow::GetUpdateRect


CWindow::GetWindow

HWND GetWindow( UINT nCmd ) const;

See GetWindow in the Win32 SDK.

Remarks

Retrieves the specified window.

CWindow Overview | Class Members

See Also CWindow::GetTopWindow, CWindow::GetTopLevelParent, CWindow::GetTopLevelWindow


CWindow::GetWindowContextHelpId

DWORD GetWindowContextHelpId( ) const;

See GetWindowContextHelpId in the Win32 SDK.

Remarks

Retrieves the window’s help context identifier.

CWindow Overview | Class Members

See Also CWindow::SetWindowContextHelpId


CWindow::GetWindowDC

HDC GetWindowDC( );

See GetWindowDC in the Win32 SDK.

Remarks

Retrieves a device context for the entire window.

CWindow Overview | Class Members

See Also CWindow::GetDC, CWindow::GetDCEx, CWindow::ReleaseDC


CWindow::GetWindowLong

LONG GetWindowLong( int nIndex ) const;

See GetWindowLong in the Win32 SDK.

Remarks

Retrieves a 32-bit value at a specified offset into the extra window memory.

CWindow Overview | Class Members

See Also CWindow::SetWindowLong, CWindow::GetWindowWord


CWindow::GetWindowPlacement

BOOL GetWindowPlacement( WINDOWPLACEMENT FAR* lpwndpl ) const;

See GetWindowPlacement in the Win32 SDK.

Remarks

Retrieves the show state and positions.

CWindow Overview | Class Members

See Also CWindow::SetWindowPlacement, WINDOWPLACEMENT


CWindow::GetWindowProcessID

DWORD GetWindowProcessID( );

See GetWindowThreadProcessID in the Win32 SDK.

Remarks

Retieves the identifier of the process that created the window.

CWindow Overview | Class Members

See Also CWindow::GetWindowThreadID


CWindow::GetWindowRect

BOOL GetWindowRect( LPRECT lpRect ) const;

See GetWindowRect in the Win32 SDK.

Remarks

Retrieves the window’s bounding dimensions.

CWindow Overview | Class Members

See Also CWindow::GetClientRect, RECT


CWindow::GetWindowRgn

int GetWindowRgn( HRGN hRgn );

See GetWindowRgn in the Win32 SDK.

Remarks

Obtains a copy of the window region of a window.

CWindow Overview | Class Members

See Also CWindow::SetWindowRgn


CWindow::GetWindowText

int GetWindowText( LPTSTR lpszStringBuf, int nMaxCount ) const;

BOOL GetWindowText( BSTR& bstrText );

See GetWindowText in the Win32 SDK.

Remarks

Retrieves the window’s text. The second version of this method allows you to store the text in a BSTR. If the text is successfully copied, the return value is TRUE; otherwise, the return value is FALSE.

CWindow Overview | Class Members

See Also CWindow::GetWindowTextLength, CWindow::SetWindowText


CWindow::GetWindowTextLength

int GetWindowTextLength( ) const;

See GetWindowTextLength in the Win32 SDK.

Remarks

Retrieves the length of the window’s text.

CWindow Overview | Class Members

See Also CWindow::GetWindowText


CWindow::GetWindowThreadID

DWORD GetWindowThreadID( );

See GetWindowThreadProcessID in the Win32 SDK.

Remarks

Retrieves the identifier of the thread that created the specified window.

CWindow Overview | Class Members

See Also CWindow::GetWindowProcessID


CWindow::GetWindowWord

WORD GetWindowWord( int nIndex ) const;

See GetWindowWord in the Win32 SDK.

Remarks

Retrieves a 16-bit value at a specified offset into the extra window memory.

CWindow Overview | Class Members

See Also CWindow::SetWindowWord, CWindow::GetWindowLong


CWindow::GotoDlgCtrl

void GotoDlgCtrl( HWND hWndCtrl ) const;

See WM_NEXTDLGCTL in the Win32 SDK.

Remarks

Sets the keyboard focus to a control in the dialog box.

CWindow Overview | Class Members

See Also CWindow::NextDlgCtrl, CWindow::PrevDlgCtrl,


CWindow::HideCaret

BOOL HideCaret( );

See HideCaret in the Win32 SDK.

Remarks

Hides the system caret.

CWindow Overview | Class Members

See Also CWindow::ShowCaret


CWindow::HiliteMenuItem

BOOL HiliteMenuItem( HMENU hMenu, UINT uHiliteItem, UINT uHilite );

See HiliteMenuItem in the Win32 SDK.

Remarks

Highlights or removes the highlight from a top-level menu item.


CWindow::Invalidate

BOOL Invalidate( BOOL bErase = TRUE );

See InvalidateRect in the Win32 SDK.

Remarks

Invalidates the entire client area. Passes NULL for the RECT parameter to the InvalidateRect Win32 function.

CWindow Overview | Class Members

See Also CWindow::InvalidateRect, CWindow::InvalidateRgn, CWindow::ValidateRect, CWindow::ValidateRgn


CWindow::InvalidateRect

BOOL InvalidateRect( LPCRECT lpRect, BOOL bErase = TRUE );

See InvalidateRect in the Win32 SDK.

Remarks

Invalidates the client area within the specified rectangle.

CWindow Overview | Class Members

See Also CWindow::Invalidate, CWindow::InvalidateRgn, CWindow::ValidateRect, RECT


CWindow::InvalidateRgn

void InvalidateRgn( HRGN hRgn, BOOL bErase = TRUE );

See InvalidateRgn in the Win32 SDK.

Remarks

Invalidates the client area within the specified region. Specifies a void return type, while the InvalidateRgn Win32 function always returns TRUE.

CWindow Overview | Class Members

See Also CWindow::Invalidate, CWindow::InvalidateRect, CWindow::ValidateRgn


CWindow::IsChild

BOOL IsChild( const HWND hWnd ) const;

See IsChild in the Win32 SDK.

Remarks

Determines whether the specified window is a child window.


CWindow::IsDialogMessage

BOOL IsDialogMessage( LPMSG lpMsg );

See IsDialogMessage in the Win32 SDK.

Remarks

Determines whether a message is intended for the specified dialog box.


CWindow::IsDlgButtonChecked

UINT IsDlgButtonChecked( int nIDButton ) const;

See IsDlgButtonChecked in the Win32 SDK.

Remarks

Determines the check state of the button.

CWindow Overview | Class Members

See Also CWindow::CheckDlgButton


CWindow::IsIconic

BOOL IsIconic( ) const;

See IsIconic in the Win32 SDK.

Remarks

Determines whether the window is minimized.

CWindow Overview | Class Members

See Also CWindow::IsZoomed


CWindow::IsWindow

BOOL IsWindow( );

See IsWindow in the Win32 SDK.

Remarks

Determines whether the specified window handle identifies an existing window.

CWindow Overview | Class Members

See Also CWindow::IsWindowEnabled, CWindow::IsWindowVisible, CWindow::IsWindowUnicode


CWindow::IsWindowEnabled

BOOL IsWindowEnabled( ) const;

See IsWindowEnabled in the Win32 SDK.

Remarks

Determines whether the window is enabled for input.

CWindow Overview | Class Members

See Also CWindow::EnableWindow, CWindow::IsWindowVisible, CWindow::IsWindowUnicode


CWindow::IsWindowVisible

BOOL IsWindowVisible( ) const;

See IsWindowVisible in the Win32 SDK.

Remarks

Determines the window’s visibility state.

CWindow Overview | Class Members

See Also CWindow::IsWindow, CWindow::IsWindowUnicode


CWindow::IsWindowUnicode

BOOL IsWindowUnicode( );

See IsWindowUnicode in the Win32 SDK.

Remarks

Determines whether the specified window is a native Unicode window.

CWindow Overview | Class Members

See Also CWindow::IsWindow, CWindow::IsWindowEnabled, CWindow::IsWindowVisible


CWindow::IsZoomed

BOOL IsZoomed( ) const;

See IsZoomed in the Win32 SDK.

Remarks

Determines whether the window is maximized.

CWindow Overview | Class Members

See Also CWindow::IsIconic


CWindow::KillTimer

BOOL KillTimer( UINT nIDEvent );

See KillTimer in the Win32 SDK.

Remarks

Destroys a timer event.

CWindow Overview | Class Members

See Also CWindow::SetTimer


CWindow::LockWindowUpdate

BOOL LockWindowUpdate( BOOL bLock = TRUE );

Return Value

TRUE if the window is successfully locked; otherwise, FALSE.

Parameters

bLock

[in] If TRUE (the default value), the window will be locked. Otherwise, it will be unlocked.

Remarks

Disables or enables drawing in the window by calling the LockWindowUpdate Win32 function. If bLock is TRUE, this method passes m_hWnd to the Win32 function; otherwise, it passes NULL.


CWindow::MapWindowPoints

int MapWindowPoints( HWND hWndTo, LPPOINT lpPoint, UINT nCount ) const;

int MapWindowPoints( HWND hWndTo, LPRECT lpRect ) const;

See MapWindowPoints in the Win32 SDK.

Remarks

Converts a set of points from the window’s coordinate space to the coordinate space of another window. The second version of this method allows you to convert the coordinates of a RECT structure.

CWindow Overview | Class Members

See Also POINT


CWindow::MessageBox

int MessageBox( LPCTSTR lpszText, LPCTSTR lpszCaption = NULL, UINT nType = MB_OK );

See MessageBox in the Win32 SDK.

Remarks

Displays a message box.


CWindow::ModifyStyle

BOOL ModifyStyle( DWORD dwRemove, DWORD dwAdd, UINT nFlags = 0 );

Return Value

TRUE if the window styles are modified; otherwise, FALSE.

Parameters

dwRemove

[in] Specifies the window styles to be removed during style modification.

dwAdd

[in] Specifies the window styles to be added during style modification.

nFlags

[in] Window-positioning flags. For a list of possible values, see the SetWindowPos function in the Win32 SDK.

Remarks

Modifies the window styles of the CWindow object. Styles to be added or removed can be combined by using the bitwise OR ( | ) operator. See the CreateWindow function in the Win32 SDK for information about the available window styles.

If nFlags is nonzero, ModifyStyle calls the Win32 function SetWindowPos, and redraws the window by combining nFlags with the following four flags:

  • SWP_NOSIZE Retains the current size.

  • SWP_NOMOVE Retains the current position.

  • SWP_NOZORDER Retains the current Z order.

  • SWP_NOACTIVATE Does not activate the window.

To modify a window’s extended styles, call ModifyStyleEx.

CWindow Overview | Class Members

See Also CWindow::GetStyle


CWindow::ModifyStyleEx

BOOL ModifyStyleEx( DWORD dwRemove, DWORD dwAdd, UINT nFlags = 0 );

Return Value

TRUE if the extended window styles are modified; otherwise, FALSE.

Parameters

dwRemove

[in] Specifies the extended styles to be removed during style modification.

dwAdd

[in] Specifies the extended styles to be added during style modification.

nFlags

[in] Window-positioning flags. For a list of possible values, see the SetWindowPos function in the Win32 SDK.

Remarks

Modifies the extended window styles of the CWindow object. Styles to be added or removed can be combined by using the bitwise OR ( | ) operator. See the CreateWindowEx function in the Win32 SDK for information about the available extended styles.

If nFlags is nonzero, ModifyStyleEx calls the Win32 function SetWindowPos, and redraws the window by combining nFlags with the following four flags:

  • SWP_NOSIZE Retains the current size.

  • SWP_NOMOVE Retains the current position.

  • SWP_NOZORDER Retains the current Z order.

  • SWP_NOACTIVATE Does not activate the window.

To modify windows using regular window styles, call ModifyStyle.

CWindow Overview | Class Members

See Also CWindow::GetExStyle


CWindow::MoveWindow

BOOL MoveWindow( int x, int y, int nWidth, int nHeight, BOOL bRepaint = TRUE );

BOOL MoveWindow( LPCRECT lpRect, BOOL bRepaint = TRUE );

See MoveWindow in the Win32 SDK.

Remarks

Changes the window’s size and position. The second version of this method uses a RECT structure to determine the window’s new position, width, and height.

CWindow Overview | Class Members

See Also CWindow::SetWindowPos


CWindow::NextDlgCtrl

void NextDlgCtrl( ) const;

See WM_NEXTDLGCTL in the Win32 SDK.

Remarks

Sets the keyboard focus to the next control in the dialog box.

CWindow Overview | Class Members

See Also CWindow::PrevDlgCtrl, CWindow::GotoDlgCtrl


CWindow::OpenClipboard

BOOL OpenClipboard( );

See OpenClipboard in the Win32 SDK.

Remarks

Opens the Clipboard.


CWindow::PostMessage

BOOL PostMessage( UINT message, WPARAM wParam = 0, LPARAM lParam = 0 );

See PostMessage in the Win32 SDK.

Remarks

Places a message in the message queue associated with the thread that created the window. Returns without waiting for the thread to process the message.

CWindow Overview | Class Members

See Also CWindow::SendMessage, CWindow::SendNotifyMessage


CWindow::PrevDlgCtrl

void PrevDlgCtrl( ) const;

See WM_NEXTDLGCTL in the Win32 SDK.

Remarks

Sets the keyboard focus to the previous control in the dialog box.

CWindow Overview | Class Members

See Also CWindow::NextDlgCtrl, CWindow::GotoDlgCtrl


CWindow::Print

void Print( HDC hDC, DWORD dwFlags ) const;

Parameters

hDC

[in] The handle to a device context.

dwFlags

[in] Specifies the drawing options. You can combine one or more of the following flags:

  • PRF_CHECKVISIBLE Draw the window only if it is visible.

  • PRF_CHILDREN Draw all visible child windows.

  • PRF_CLIENT Draw the client area of the window.

  • PRF_ERASEBKGND Erase the background before drawing the window.

  • PRF_NONCLIENT Draw the nonclient area of the window.

  • PRF_OWNED Draw all owned windows.

Remarks

Sends a WM_PRINT message to the window to request that it draw itself in the specified device context.

CWindow Overview | Class Members

See Also CWindow::PrintClient


CWindow::PrintClient

void PrintClient( HDC hDC, DWORD dwFlags ) const;

Parameters

hDC

[in] The handle to a device context.

dwFlags

[in] Specifies drawing options. You can combine one or more of the following flags:

  • PRF_CHECKVISIBLE Draw the window only if it is visible.

  • PRF_CHILDREN Draw all visible child windows.

  • PRF_CLIENT Draw the client area of the window.

  • PRF_ERASEBKGND Erase the background before drawing the window.

  • PRF_NONCLIENT Draw the nonclient area of the window.

  • PRF_OWNED Draw all owned windows.

Remarks

Sends a WM_PRINTCLIENT message to the window to request that it draw its client area in the specified device context.

CWindow Overview | Class Members

See Also CWindow::Print


CWindow::RedrawWindow

BOOL RedrawWindow( LPCRECT lpRectUpdate = NULL, HRGN hRgnUpdate = NULL, UINT flags = RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE );

See RedrawWindow in the Win32 SDK.

Remarks

Updates a specified rectangle or region in the client area.

CWindow Overview | Class Members

See Also CWindow::UpdateWindow, RECT


CWindow::ReleaseDC

int ReleaseDC( HDC hDC );

See ReleaseDC in the Win32 SDK.

Remarks

Releases a device context.

CWindow Overview | Class Members

See Also CWindow::GetDC, CWindow::GetDCEx, CWindow::GetWindowDC


CWindow::ResizeClient

BOOL ResizeClient( int nWidth, int nHeight, BOOL bRedraw = FALSE );

Parameters

nWidth

New width of the window in pixels.

nHeight

New height of the window in pixels.

bRedraw

A flag indicating whether to redraw changes. Default is FALSE, indicating the window does not redraw changes.

Remarks

Resizes the window to the specified client area size.

CWindow Overview | Class Members

See Also CWindow::SetWindowPos, ::SetWindowPos


CWindow::ScreenToClient

BOOL ScreenToClient( LPPOINT lpPoint ) const;

BOOL ScreenToClient( LPRECT lpRect ) const;

See ScreenToClient in the Win32 SDK.

Remarks

Converts screen coordinates to client coordinates. The second version of this method allows you to convert the coordinates of a RECT structure.

CWindow Overview | Class Members

See Also CWindow::ClientToScreen, POINT


CWindow::ScrollWindow

BOOL ScrollWindow( int xAmount, int yAmount, LPCRECT lpRect = NULL, LPCRECT lpClipRect = NULL );

See ScrollWindow in the Win32 SDK.

Remarks

Scrolls the specified client area.

CWindow Overview | Class Members

See Also CWindow::ScrollWindowEx, RECT


CWindow::ScrollWindowEx

int ScrollWindowEx( int dx, int dy, LPCRECT lpRectScroll, LPCRECT lpRectClip, HRGN hRgnUpdate, LPRECT lpRectUpdate, UINT flags );

See ScrollWindowEx in the Win32 SDK.

Remarks

Scrolls the specified client area with additional features.

CWindow Overview | Class Members

See Also CWindow::ScrollWindow, RECT


CWindow::SendDlgItemMessage

LRESULT SendDlgItemMessage( int nID, UINT message, WPARAM wParam = 0, LPARAM lParam = 0 );

See SendDlgItemMessage in the Win32 SDK.

Remarks

Sends a message to a control.

CWindow Overview | Class Members

See Also CWindow::SendMessage


CWindow::SendMessage

LRESULT SendMessage( UINT message, WPARAM wParam = 0, LPARAM lParam = 0 );

static LRESULT SendMessage( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )

See SendMessage in the Win32 SDK.

Remarks

Sends a message to the window and does not return until the window procedure has processed the message.

CWindow Overview | Class Members

See Also CWindow::PostMessage, CWindow::SendNotifyMessage, CWindow::SendMessageToDescendants


CWindow::SendMessageToDescendants

void SendMessageToDescendants( UINT message, WPARAM wParam = 0, LPARAM lParam = 0, BOOL bDeep = TRUE );

Parameters

message

[in] The message to be sent.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

bDeep

[in] If TRUE (the default value), the message will be sent to all descendant windows; otherwise, it will be sent only to the immediate child windows.

Remarks

Sends the specified message to all immediate children of the CWindow object. If bDeep is TRUE, the message is additionally sent to all other descendant windows.

CWindow Overview | Class Members

See Also CWindow::SendMessage, CWindow::SendNotifyMessage, CWindow::PostMessage


CWindow::SendNotifyMessage

BOOL SendNotifyMessage( UINT message, WPARAM wParam = 0, LPARAM lParam = 0 );

See SendNotifyMessage in the Win32 SDK.

Remarks

Sends a message to the window. If the window was created by the calling thread, SendNotifyMessage does not return until the window procedure has processed the message. Otherwise, it returns immediately.

CWindow Overview | Class Members

See Also CWindow::SendMessage, CWindow::SendMessageToDescendants, CWindow::PostMessage


CWindow::SetActiveWindow

HWND SetActiveWindow( );

See SetActiveWindow in the Win32 SDK.

Remarks

Activates the window.


CWindow::SetCapture

HWND SetCapture( );

See SetCapture in the Win32 SDK.

Remarks

Sends all subsequent mouse input to the window.


CWindow::SetClipboardViewer

HWND SetClipboardViewer( );

See SetClipboardViewer in the Win32 SDK.

Remarks

Adds the window to the Clipboard viewer chain.

CWindow Overview | Class Members

See Also CWindow::ChangeClipboardChain


CWindow::SetDlgCtrlID

int SetDlgCtrlID( int nID );

Return Value

If successful, the previous identifier of the window; otherwise 0.

Parameters

nID

[in] The new value to set for the window’s identifier.

Remarks

Sets the identifier of the window to the specified value.

CWindow Overview | Class Members

See Also CWindow::GetDlgCtrlID


CWindow::SetDlgItemInt

BOOL SetDlgItemInt( int nID, UINT nValue, BOOL bSigned = TRUE );

See SetDlgItemInt in the Win32 SDK.

Remarks

Changes a control’s text to the string representation of an integer value.

CWindow Overview | Class Members

See Also CWindow::GetDlgItemInt, CWindow::SetDlgItemText


CWindow::SetDlgItemText

BOOL SetDlgItemText( int nID, LPCTSTR lpszString );

See SetDlgItemText in the Win32 SDK.

Remarks

Changes a control’s text.

CWindow Overview | Class Members

See Also CWindow::GetDlgItemText, CWindow::SetDlgItemInt


CWindow::SetFocus

HWND SetFocus( );

See SetFocus in the Win32 SDK.

Remarks

Sets the input focus to the window.


CWindow::SetFont

void SetFont( HFONT hFont, BOOL bRedraw = TRUE );

Parameters

hFont

[in] The handle to the new font.

bRedraw

[in] If TRUE (the default value), the window is redrawn. Otherwise, it is not.

Remarks

Changes the window’s current font by sending a WM_SETFONT message to the window.

CWindow Overview | Class Members

See Also CWindow::GetFont


CWindow::SetHotKey

int SetHotKey( WORD wVirtualKeyCode, WORD wModifiers );

Return Value

For a list of possible return values, see WM_SETHOTKEY in the Win32 SDK.

Parameters

wVirtualKeyCode

[in] The virtual key code of the hot key.

wModifiers

[in] The modifiers of the hot key. For a list of possible values, see WM_SETHOTKEY in the Win32 SDK.

Remarks

Associates a hot key with the window by sending a WM_SETHOTKEY message.

CWindow Overview | Class Members

See Also CWindow::GetHotKey


CWindow::SetIcon

HICON SetIcon( HICON hIcon, BOOL bBigIcon = TRUE );

Return Value

The handle to the previous icon.

Parameters

hIcon

[in] The handle to a new icon.

bBigIcon

[in] If TRUE (the default value), the method sets a large icon. Otherwise, it sets a small icon.

Remarks

Sets the window’s large or small icon to the icon identified by hIcon. SetIcon sends a WM_SETICON message to the window.

CWindow Overview | Class Members

See Also CWindow::GetIcon


CWindow::SetMenu

BOOL SetMenu( HMENU hMenu );

See SetMenu in the Win32 SDK.

Remarks

Changes the window’s current menu.

CWindow Overview | Class Members

See Also CWindow::GetMenu


CWindow::SetParent

HWND SetParent( HWND hWndNewParent );

See SetParent in the Win32 SDK.

Remarks

Changes the parent window.

CWindow Overview | Class Members

See Also CWindow::GetParent


CWindow::SetRedraw

void SetRedraw( BOOL bRedraw = TRUE );

Parameters

bRedraw

[in] Specifies the state of the redraw flag. If TRUE (the default value), the redraw flag is set; if FALSE, the flag is cleared.

Remarks

Sets or clears the redraw flag by sending a WM_SETREDRAW message to the window. Call SetRedraw to allow changes to be redrawn or to prevent changes from being redrawn.


CWindow::SetScrollInfo

BOOL SetScrollInfo( int nBar, LPSCROLLINFO lpScrollInfo, BOOL bRedraw = TRUE );

See SetScrollInfo in the Win32 SDK.

Remarks

Sets the parameters of a scroll bar.

CWindow Overview | Class Members

See Also CWindow::GetScrollInfo


CWindow::SetScrollPos

int SetScrollPos( int nBar, int nPos, BOOL bRedraw = TRUE );

See SetScrollPos in the Win32 SDK.

Remarks

Changes the position of the scroll box.

CWindow Overview | Class Members

See Also CWindow::GetScrollPos


CWindow::SetScrollRange

BOOL SetScrollRange( int nBar, int nMinPos, int nMaxPos, BOOL bRedraw = TRUE );

See SetScrollRange in the Win32 SDK.

Remarks

Changes the scroll bar range.

CWindow Overview | Class Members

See Also CWindow::GetScrollRange


CWindow::SetTimer

UINT SetTimer( UINT nIDEvent, UINT nElapse )

See SetTimer in the Win32 SDK.

Remarks

Creates a timer event.

CWindow Overview | Class Members

See Also CWindow::KillTimer


CWindow::SetWindowContextHelpId

BOOL SetWindowContextHelpId( DWORD dwContextHelpId );

See SetWindowContextHelpId in the Win32 SDK.

Remarks

Sets the window’s help context identifier.

CWindow Overview | Class Members

See Also CWindow::GetWindowContextHelpId


CWindow::SetWindowLong

LONG SetWindowLong( int nIndex, LONG dwNewLong );

See SetWindowLong in the Win32 SDK.

Remarks

Sets a 32-bit value at a specified offset into the extra window memory.

CWindow Overview | Class Members

See Also CWindow::GetWindowLong, CWindow::SetWindowWord


CWindow::SetWindowPlacement

BOOL SetWindowPlacement( const WINDOWPLACEMENT FAR*lpwndpl );

See SetWindowPlacement in the Win32 SDK.

Remarks

Sets the show state and positions.

CWindow Overview | Class Members

See Also CWindow::GetWindowPlacement, WINDOWPLACEMENT


CWindow::SetWindowPos

BOOL SetWindowPos( HWND hWndInsertAfter, int x, int y, int cx, int cy, UINT nFlags );

BOOL SetWindowPos( HWND hWndInsertAfter, LPCRECT lpRect, UINT nFlags );

See SetWindowPos in the Win32 SDK.

Remarks

Sets the size, position, and Z order. The second version of this method uses a RECT structure to set the window’s new position, width, and height.

CWindow Overview | Class Members

See Also CWindow::BringWindowToTop, CWindow::MoveWindow, RECT


CWindow::SetWindowRgn

int SetWindowRgn( HRGN hRgn, BOOL bRedraw = FALSE );

See SetWindowRgn in the Win32 SDK.

Remarks

Sets the window region of a window.

CWindow Overview | Class Members

See Also CWindow::GetWindowRgn


CWindow::SetWindowText

BOOL SetWindowText( LPCTSTR lpszString );

See SetWindowText in the Win32 SDK.

Remarks

Changes the window’s text.

CWindow Overview | Class Members

See Also CWindow::GetWindowText


CWindow::SetWindowWord

WORD SetWindowLong( int nIndex, WORD wNewWord );

See SetWindowWord in the Win32 SDK.

Remarks

Sets a 16-bit value at a specified offset into the extra window memory.

CWindow Overview | Class Members

See Also CWindow::GetWindowWord, CWindow::SetWindowLong


CWindow::ShowCaret

BOOL ShowCaret( );

See ShowCaret in the Win32 SDK.

Remarks

Displays the system caret.

CWindow Overview | Class Members

See Also CWindow::HideCaret


CWindow::ShowOwnedPopups

BOOL ShowOwnedPopups( BOOL bShow = TRUE );

See ShowOwnedPopups in the Win32 SDK.

Remarks

Shows or hides the pop-up windows owned by the window.


CWindow::ShowScrollBar

BOOL ShowScrollBar( UINT nBar, BOOL bShow = TRUE );

See ShowScrollBar in the Win32 SDK.

Remarks

Shows or hides a scroll bar.


CWindow::ShowWindow

BOOL ShowWindow( int nCmdShow );

See ShowWindow in the Win32 SDK.

Remarks

Sets the window’s show state.


CWindow::ShowWindowAsync

BOOL ShowWindowAsync( int nCmdShow );

See ShowWindowAsync in the Win32 SDK.

Remarks

Sets the show state of a window created by a different thread.


CWindow::UpdateWindow

BOOL UpdateWindow( );

See UpdateWindow in the Win32 SDK.

Remarks

Updates the client area.

CWindow Overview | Class Members

See Also CWindow::RedrawWindow


CWindow::ValidateRect

BOOL ValidateRect( LPCRECT lpRect );

See ValidateRect in the Win32 SDK.

Remarks

Validates the client area within the specified rectangle.

CWindow Overview | Class Members

See Also CWindow::ValidateRgn, CWindow::InvalidateRect


CWindow::ValidateRgn

BOOL ValidateRgn( HRGN hRgn );

See ValidateRgn in the Win32 SDK.

Remarks

Validates the client area within the specified region.

CWindow Overview | Class Members

See Also CWindow::ValidateRect, CWindow::InvalidateRgn


CWindow::WinHelp

BOOL WinHelp( LPCTSTR lpszHelp, UINT nCmd = HELP_CONTEXT, DWORD dwData = 0 );

See WinHelp in the Win32 SDK.

Remarks

Starts Windows Help.


CWindow::operator HWND

operator HWND( ) const;

Remarks

Converts a CWindow object to an HWND.


CWindow::operator =

CWindow& operator =( HWND hWnd );

Remarks

Assigns an HWND to the CWindow object by setting the m_hWnd member to hWnd.


CWindow::m_hWnd

HWND m_hWnd;

Remarks

Contains a handle to the window associated with the CWindow object.

CWindow Overview | Class Members

See Also CWindow::CWindow


CWindowImpl

template < class T, class TBase = CWindow, class TWinTraits = CControlWinTraits >
class ATL_NO_VTABLE CWindowImpl : public CWindowImplBaseT< TBase, TWinTraits >

Parameters

T

Your class, derived from CWindowImpl.

TBase

The base class of your new class. The default base class is CWindow.

TWinTrait

A traits class that defines styles for your window. The default is CControlWinTraits.

CWindowImpl allows you to create a new window or subclass an existing window. CWindowImpl’s window procedure uses a message map to direct messages to the appropriate handlers.

CWindowImpl::Create creates a new window based on the window class information managed by CWndClassInfo. CWindowImpl contains the DECLARE_WND_CLASS macro, which means CWndClassInfo will register a new window class. If you want to superclass an existing window class, derive your class from CWindowImpl and include the DECLARE_WND_SUPERCLASS macro. In this case, CWndClassInfo will register a window class that is based on an existing class but uses CWindowImpl::WindowProc. For example:

class CMyWindow : CComControl<CMyWindow>, ...
                // CComControl derives from CWindowImpl
{
public:
   // 1. The NULL parameter means ATL will generate a
   //    name for the superclass
   // 2. The "EDIT" parameter means the superclass is
   //    based on the standard Windows Edit box
   DECLARE_WND_SUPERCLASS(NULL, "EDIT")
   ...
};

Note Because CWndClassInfo manages the information for a single window class, each window created through an instance of CWindowImpl will be based on the same window class.

CWindowImpl also supports window subclassing. The SubclassWindow method attaches an existing window to the CWindowImpl object and changes the window procedure to CWindowImpl::WindowProc. Each instance of CWindowImpl can subclass a different window.

Note For any given CWindowImpl object, call either Create or SubclassWindow. You should not invoke both methods on the same object.

In addition to CWindowImpl, ATL provides CContainedWindow to create a window contained within another object.

The base class destructor (~CWindowImplRoot) ensures that the window is gone before the object is destroyed.

CWindowImpl derives from CWindowImplBaseT, which derives from CWindowImplRoot, which in turn derives from TBase and CMessageMap.

For more information about | See
Creating controls | ATL Tutorial
Using windows in ATL | ATL Window Classes
ATL Object Wizard | Creating an ATL Project
Windows | Windows and subsequent topics in the Platform SDK
Subclassing | Window Procedure Subclassing in the Platform SDK
Superclassing | Window Procedure Superclassing in the Platform SDK

#include <atlwin.h>

Class Members

See Also

BEGIN_MSG_MAP, CComControl


CWindowImpl Class Members

Methods

Create Creates a window.

CWindowImplBaseT Methods

DefWindowProc | Provides default message processing.
GetWndClassInfo | Returns a static instance of CWndClassInfo, which manages the window class information.
SubclassWindow | Subclasses a window.
UnsubclassWindow | Restores a previously subclassed window.
WindowProc | Processes messages sent to the window.
GetWindowProc | Returns the current window procedure.
GetCurrentMessage | Returns the current message.
OnFinalMessage | Called after receiving the last message (typically WM_NCDESTROY).

Data Members

m_pfnSuperWindowProc Points to the window class’s original window procedure.

CWindowImpl Overview


CWindowImpl::Create

HWND Create( HWND hWndParent, RECT& rcPos, LPCTSTR szWindowName = NULL, DWORD dwStyle = WS_CHILD | WS_VISIBLE, DWORD dwExStyle = 0, UINT nID = 0 );

Return Value

If successful, the handle to the newly created window. Otherwise, NULL.

Parameters

hWndParent

[in] The handle to the parent or owner window.

rcPos

[in] A RECT structure specifying the position of the window.

szWindowName

[in] Specifies the name of the window. The default value is NULL.

dwStyle

[in] The style of the window. The default value is WS_CHILD | WS_VISIBLE. For a list of possible values, see CreateWindow in the Platform SDK.

dwExStyle

[in] The extended window style. The default value is 0, meaning no extended style. For a list of possible values, see CreateWindowEx in the Platform SDK.

nID

[in] For a child window, the window identifier. For a top-level window, an HWND cast to a UINT. The default value is 0.

Remarks

Creates a window based on a new window class. Create first registers the window class if it has not yet been registered. The newly created window is automatically attached to the CWindowImpl object.

To use a window class that is based on an existing window class, derive your class from CWindowImpl and include the DECLARE_WND_SUPERCLASS macro. The existing window class’s window procedure is saved in m_pfnSuperWindowProc. For more information, see the CWindowImpl overview.

Note Do not call Create if you have already called SubclassWindow.

CWindowImpl Overview | Class Members

See Also

CWindowImpl::GetWndClassInfo, CWndClassInfo::Register, CWindow::m_hWnd


CWindowImpl::DefWindowProc

LRESULT DefWindowProc( UINT uMsg, WPARAM wParam, LPARAM lParam );

LRESULT DefWindowProc( );

Return Value

The result of the message processing.

Parameters

uMsg

[in] The message sent to the window.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

Remarks

Called by WindowProc to process messages not handled by the message map. By default, DefWindowProc calls the CallWindowProc Win32 function to send the message information to the window procedure specified in m_pfnSuperWindowProc.

The function with no parameters automatically retrieves the needed parameters from the current message.


CWindowImpl::GetCurrentMessage

const MSG* GetCurrentMessage( );

Return Value

The current message.

Remarks

Returns the current message, packaged in the MSG structure.

CWindowImpl Overview | Class Members

See Also

CWindowImpl::OnFinalMessage, CWindowImpl::UnsubclassWindow, CWindowImpl::WindowProc


CWindowImpl::GetWindowProc

virtual WNDPROC GetWindowProc( );

Return Value

The current window procedure.

Remarks

Returns WindowProc, the current window procedure. Override this method to replace the window procedure with your own.

CWindowImpl Overview | Class Members

See Also

CWindowImpl::OnFinalMessage, CWindowImpl::UnsubclassWindow, CWindowImpl::WindowProc


CWindowImpl::GetWndClassInfo

static CWndClassInfo& GetWndClassInfo( );

Return Value

A static instance of CWndClassInfo.

Remarks

Called by Create to access the window class information. By default, CWindowImpl obtains this method through the DECLARE_WND_CLASS macro, which specifies a new window class.

To superclass an existing window class, derive your class from CWindowImpl and include the DECLARE_WND_SUPERCLASS macro to override GetWndClassInfo. For more information, see the CWindowImpl overview.

Besides using the DECLARE_WND_CLASS and DECLARE_WND_SUPERCLASS macros, you can override GetWndClassInfo with your own implementation.


CWindowImpl::OnFinalMessage

virtual void OnFinalMessage( HWND hWnd );

Parameters

hWnd

[in] A handle to the window being destroyed.

Remarks

Called after receiving the last message (typically WM_NCDESTROY). The default implementation of OnFinalMessage does nothing, but you can override this function to handle cleanup before destroying a window. If you want to automatically delete your object upon the window destruction, you can call delete this; in this function.

CWindowImpl Overview | Class Members

See Also

CWindowImpl::GetWindowProc, CWindowImpl::UnsubclassWindow


CWindowImpl::SubclassWindow

BOOL SubclassWindow( HWND hWnd );

Return Value

TRUE if the window is successfully subclassed; otherwise, FALSE.

Parameters

hWnd

[in] The handle to the window being subclassed.

Remarks

Subclasses the window identified by hWnd and attaches it to the CWindowImpl object. The subclassed window now uses CWindowImpl::WindowProc. The original window procedure is saved in m_pfnSuperWindowProc.

Note Do not call SubclassWindow if you have already called Create.

CWindowImpl Overview | Class Members

See Also

CWindowImpl::UnsubclassWindow


CWindowImpl::UnsubclassWindow

HWND UnsubclassWindow( );

Return Value

The handle to the window previously subclassed.

Remarks

Detaches the subclassed window from the CWindowImpl object and restores the original window procedure, saved in m_pfnSuperWindowProc.

CWindowImpl Overview | Class Members

See Also

CWindowImpl::SubclassWindow


CWindowImpl::WindowProc

static LRESULT CALLBACK WindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );

Return Value

The result of the message processing.

Parameters

hWnd

[in] The handle to the window.

uMsg

[in] The message sent to the window.

wParam

[in] Additional message-specific information.

lParam

[in] Additional message-specific information.

Remarks

This static method implements the window procedure. WindowProc uses the default message map (declared with BEGIN_MSG_MAP) to direct messages to the appropriate handlers. If necessary, WindowProc calls DefWindowProc for additional message processing. If the final message is not handled, WindowProc does the following:

  • Performs unsubclassing if the window was unsubclassed

  • Clears m_hWnd

  • Calls OnFinalMessage before the window is destroyed

You can override WindowProc to provide a different mechanism for handling messages.


CWindowImpl::m_pfnSuperWindowProc

WNDPROC m_pfnSuperWindowProc;

Remarks

Depending on the window, points to one of the following window procedures:

Type of window | Window procedure
A window based on a new window class, specified through the DECLARE_WND_CLASS macro. | The DefWindowProc Win32 function.
A window based on a window class that modifies an existing class, specified through the DECLARE_WND_SUPERCLASS macro. | The existing window class’s window procedure.
A subclassed window. | The subclassed window’s original window procedure.

CWindowImpl::DefWindowProc sends message information to the window procedure saved in m_pfnSuperWindowProc.

CWindowImpl Overview | Class Members

See Also

CWindowImpl::Create, CWindowImpl::SubclassWindow


CWinTraits

template <DWORD t_dwStyle = 0, DWORD t_dwExStyle = 0>
class CWinTraits

Parameters

t_dwStyle

Default window styles.

t_dwExStyle

Default extended window styles.

Remarks

This class provides a simple method of standardizing the traits of an ATL window object. You are able to specify both the standard and extended styles for the ATL window object.

The CWinTraits class can be used, as a template parameter for creating ATL window classes, to specify the styles for the window object.

The class makes use of three predefined types of ATL window styles:

CControlWinTraits

Designed for a standard control window. The following standard styles are used: WS_CHILD, WS_VISIBLE, WS_CLIPCHILDREN, and WS_CLIPSIBLINGS. There are no extended styles.

CFrameWinTraits

Designed for a standard frame window. The standard styles used include: WS_OVERLAPPEDWINDOW, WS_CLIPCHILDREN, and WS_CLIPSIBLINGS. The extended styles used include: WS_EX_APPWINDOW and WS_EX_WINDOWEDGE.

CMDIChildWinTraits

Designed for a standard MDI child window. The standard styles used include: WS_OVERLAPPEDWINDOW, WS_CHILD, WS_VISIBLE, WS_CLIPCHILDREN, and WS_CLIPSIBLINGS. The extended styles used include: WS_EX_MDICHILD.

In addition to CWinTraits, CWinTraitsOR provides the same functionality plus the ability to combine styles using the bitwise OR operator.

#include <atlwin.h>

Class Members


CWinTraits Class Members

Methods

GetWndStyle | Retrieves the current standard styles for the CWinTraits object.
GetWndExStyle | Retrieves the current extended styles for the CWinTraits object.

CWinTraits Overview


CWinTraits::GetWndStyle

static DWORD GetWndStyle( DWORD dwStyle );

Return Value

Th standard window styles of the object.

Parameters

dwStyle

Standard styles used for creation of a window. If dwStyle is 0, default style values (t_dwStyle) are returned. If dwStyle is nonzero, dwStyle is returned.

Remarks

Call this function to retrieve the standard styles of the CWinTraits object.

CWinTraits Overview | Class Members

See Also

CWinTraits::GetWndExStyle


CWinTraits::GetWndExStyle

static DWORD GetWndExStyle( DWORD dwExStyle );

Return Value

The extended window styles of the object.

Parameters

dwExStyle

Extended styles used for creation of a window. If dwExStyle is 0, default style values (t_dwExStyle) are returned. If dwExStyle is nonzero, dwExStyle is returned.

Remarks

Call this function to retrieve the extended styles of the CWinTraits object.

CWinTraits Overview | Class Members

See Also

CWinTraits::GetWndStyle


CWinTraitsOR

template < DWORD t_dwStyle = 0, DWORD t_dwExStyle = 0, class TWinTraits = CControlWinTraits >
class CWinTraitsOR

Parameters

t_dwStyle

Default window styles.

t_dwExStyle

Default extended window styles.

CWinTraitsOR provides default values for window styles and extended styles used to create a window. These values will be added (using the logical OR operator) to values provided during the creation of a window.

In addition to CWinTraitsOR, CWinTraits provides the same functionality without the ability to combine styles.

#include <atlwin.h>

Class Members


CWinTraitsOR Class Members

Methods

GetWndStyle | Retrieves the current standard styles for the CWinTraitsOR object.
GetWndExStyle | Retrieves the current extended styles for the CWinTraitsOR object.

CWinTraitsOR Overview


CWinTraitsOR::GetWndStyle

static DWORD GetWndStyle( DWORD dwStyle );

Return Value

A combination of styles that are passed in dwStyle and the default ones specified by t_dwStyle, using the logical OR operator.

Parameters

dwStyle

Styles used for creation of a window.

Remarks

Call this function to retrieve a combination (using the logical OR operator) of the standard styles of the CWinTraits object and the default styles specified by t_dwStyle.

CWinTraitsOR Overview | Class Members

See Also

CWinTraitsOR::GetWndStyle


CWinTraitsOR::GetWndExStyle

static DWORD GetWndExStyle( DWORD dwExStyle )

Return Value

A combination of extended styles that are passed in dwExStyle and default ones specified by t_dwExStyle, using the logical OR operator

Parameters

dwExStyle

Extended styles used for creation of a window.

Remarks

Call this function to retrieve a combination (using the logical OR operator) of the extended styles of the CWinTraits object and the default styles specified by t_dwStyle.

CWinTraitsOR Overview | Class Members

See Also

CWinTraitsOR::GetWndExStyle


CWndClassInfo

class CWndClassInfo

CWndClassInfo manages the information of a window class. You typically use CWndClassInfo through one of three macros, DECLARE_WND_CLASS, DECLARE_WND_CLASS_EX, or DECLARE_WND_SUPERCLASS, as described in the following table:

Macro | Description
DECLARE_WND_CLASS | CWndClassInfo registers information for a new window class.
DECLARE_WND_CLASS_EX | CWndClassInfo registers information for a new window class, including the class parameters.
DECLARE_WND_SUPERCLASS | CWndClassInfo registers information for a window class that is based on an existing class but uses a different window procedure. This technique is called superclassing.

By default, CWindowImpl includes the DECLARE_WND_CLASS macro to create a window based on a new window class. DECLARE_WND_CLASS provides default styles and background color for the control. If you want to specify the style and background color yourself, derive your class from CWindowImpl and include the DECLARE_WND_CLASS_EX macro in your class definition.

If you want to create a window based on an existing window class, derive your class from CWindowImpl and include the DECLARE_WND_SUPERCLASS macro in your class definition. For example:

class CMyWindow : CComControl<CMyWindow>, ...
                // CComControl derives from CWindowImpl
{
public:
   // 1. The NULL parameter means ATL will generate a
   //    name for the superclass
   // 2. The "EDIT" parameter means the superclass is
   //    based on the standard Windows Edit box
   DECLARE_WND_SUPERCLASS(NULL, "EDIT")
   ...
};

For more information about window classes and superclassing, see Window Classes and Window Procedure Superclassing in the Win32 SDK.

For more information about using windows in ATL, see the article ATL Window Classes.

#include <atlwin.h>

Class Members

See Also CComControl


CWndClassInfo Class Members

Methods

Register Registers the window class.

Data Members

m_atom | Uniquely identifies the registered window class.
m_bSystemCursor | Specifies whether the cursor resource refers to a system cursor or to a cursor contained in a module resource.
m_lpszCursorID | Specifies the name of the cursor resource.
m_lpszOrigName | Contains the name of an existing window class.
m_szAutoName | Holds an ATL-generated name of the window class.
m_wc | Maintains window class information in a WNDCLASSEX structure.
pWndProc | Points to the window procedure of an existing window class.

CWndClassInfo Overview


CWndClassInfo::Register

ATOM Register( WNDPROC* pProc );

Return Value

If successful, an atom that uniquely identifies the window class being registered. Otherwise, 0.

Parameters

pProc

[out] Specifies the original window procedure of an existing window class.

Remarks

Called by CWindowImpl::Create to register the window class if it has not yet been registered.

If you have specified the DECLARE_WND_CLASS (the default in CWindowImpl) or the DECLARE_WND_CLASS_EX macro, Register registers a new window class. In this case, the pProc parameter is not used.

If you have specified the DECLARE_WND_SUPERCLASS macro, Register registers a superclass — a window class that is based on an existing class but uses a different window procedure. The existing window class’s window procedure is returned in pProc.

CWndClassInfo Overview | Class Members

See Also CWndClassInfo::m_atom, CWndClassInfo::m_wc, CWndClassInfo::pWndProc


CWndClassInfo::m_atom

ATOM m_atom;

Remarks

Contains the unique identifier for the registered window class.

CWndClassInfo Overview | Class Members

See Also CWndClassInfo::Register


CWndClassInfo::m_bSystemCursor

BOOL m_bSystemCursor;

Remarks

If TRUE, the system cursor resource will be loaded when the window class is registered. Otherwise, the cursor resource contained in your module will be loaded.

CWndClassInfo uses m_bSystemCursor only when the DECLARE_WND_CLASS (the default in CWindowImpl) or the DECLARE_WND_CLASS_EX macro is specified. In this case, m_bSystemCursor is initialized to TRUE. For more information, see the CWndClassInfo overview.

CWndClassInfo Overview | Class Members

See Also CWndClassInfo::m_lpszCursorID


CWndClassInfo::m_lpszCursorID

LPCTSTR m_lpszCursorID;

Remarks

Specifies either the name of the cursor resource or the resource identifier in the low-order word and zero in the high-order word. When the window class is registered, the handle to the cursor identified by m_lpszCursorID is retrieved and stored by m_wc.

CWndClassInfo uses m_lpszCursorID only when the DECLARE_WND_CLASS (the default in CWindowImpl) or the DECLARE_WND_CLASS_EX macro is specified. In this case, m_lpszCursorID is initialized to IDC_ARROW. For more information, see the CWndClassInfo overview.

CWndClassInfo Overview | Class Members

See Also CWndClassInfo::m_bSystemCursor


CWndClassInfo::m_lpszOrigName

LPCTSTR m_lpszOrigName;

Remarks

Contains the name of an existing window class. CWndClassInfo uses m_lpszOrigName only when you include the DECLARE_WND_SUPERCLASS macro in your class definition. In this case, CWndClassInfo registers a window class based on the class named by m_lpszOrigName. For more information, see the CWndClassInfo overview.

CWndClassInfo Overview | Class Members

See Also CWndClassInfo::m_wc, CWndClassInfo::pWndProc


CWndClassInfo::m_szAutoName

TCHAR m_szAutoName[13];

Remarks

Holds the name of the window class. CWndClassInfo uses m_szAutoName only if NULL is passed for the WndClassName parameter to DECLARE_WND_CLASS, the DECLARE_WND_CLASS_EX or DECLARE_WND_SUPERCLASS. ATL will construct a name when the window class is registered.


CWndClassInfo::m_wc

WNDCLASSEX m_wc;

Remarks

Maintains the window class information in a WNDCLASSEX structure.

If you have specified the DECLARE_WND_CLASS (the default in CWindowImpl) or the DECLARE_WND_CLASS_EX macro, m_wc contains information about a new window class.

If you have specified the DECLARE_WND_SUPERCLASS macro, m_wc contains information about a superclass — a window class that is based on an existing class but uses a different window procedure. m_lpszOrigName and pWndProc save the existing window class’s name and window procedure, respectively.


CWndClassInfo::pWndProc

WNDPROC pWndProc;

Remarks

Points to the window procedure of an existing window class. CWndClassInfo uses pWndProc only when you include the DECLARE_WND_SUPERCLASS macro in your class definition. In this case, CWndClassInfo registers a window class that is based on an existing class but uses a different window procedure. The existing window class’s window procedure is saved in pWndProc. For more information, see the CWndClassInfo overview.

CWndClassInfo Overview | Class Members

See Also CWndClassInfo::m_wc, CWndClassInfo::m_lpszOrigName


IConnectionPointContainerImpl

template< class T >
class IConnectionPointContainerImpl

Parameters

T

Your class, derived from IConnectionPointContainerImpl.

IConnectionPointContainerImpl implements a connection point container to manage a collection of IConnectionPointImpl objects. IConnectionPointContainerImpl provides two methods that a client can call to retrieve more information about a connectable object:

  • EnumConnectionPoints allows the client to determine which outgoing interfaces the object supports.

  • FindConnectionPoint allows the client to determine whether the object supports a specific outgoing interface.

For information about using connection points in ATL, see the article Connection Points.

#include <atlcom.h>

Class Members

See Also IConnectionPointContainer


IConnectionPointContainerImpl Class Members

IConnectionPointContainer Methods

EnumConnectionPoints | Creates an enumerator to iterate through the connection points supported in the connectable object.
FindConnectionPoint | Retrieves an interface pointer to the connection point that supports the specified IID.

IConnectionPointContainerImpl Overview


IConnectionPointContainerImpl::EnumConnectionPoints

HRESULT EnumConnectionPoints( IEnumConnectionPoints **ppEnum );

See IConnectionPointContainer::EnumConnectionPoints in the Win32 SDK.

Remarks

Creates an enumerator to iterate through the connection points supported in the connectable object.

IConnectionPointContainerImpl Overview | Class Members

See Also IConnectionPointImpl, IEnumConnectionPoints


IConnectionPointContainerImpl::FindConnectionPoint

HRESULT FindConnectionPoint( REFIID riid, IConnectionPoint** ppCP );

See IConnectionPointContainer::FindConnectionPoint in the Win32 SDK.

Remarks

Retrieves an interface pointer to the connection point that supports the specified IID.

IConnectionPointContainerImpl Overview | Class Members

See Also IConnectionPointImpl


IConnectionPointImpl

template< class T, const IID* piid, class CDV = CComDynamicUnkArray >
class IConnectionPointImpl : public _ICPLocator< piid >

Parameters

T

Your class, derived from IConnectionPointImpl.

piid

A pointer to the IID of the interface represented by the connection point object.

CDV

A class that manages the connections. The default value is CComDynamicUnkArray, which allows unlimited connections. You can also use CComUnkArray, which specifies a fixed number of connections.

IConnectionPointImpl implements a connection point, which allows an object to expose an outgoing interface to the client. The client implements this interface on an object called a sink.

ATL uses IConnectionPointContainerImpl to implement the connectable object. Each connection point within the connectable object represents an outgoing interface, identified by piid. Class CDV manages the connections between the connection point and a sink. Each connection is uniquely identified by a “cookie.”

For more information about using connection points in ATL, see the article Connection Points.

#include <atlcom.h>

Class Members

See Also IConnectionPoint


IConnectionPointImpl Class Members

IConnectionPoint Methods

Advise | Establishes a connection between the connection point and a sink.
EnumConnections | Creates an enumerator to iterate through the connections for the connection point.
GetConnectionInterface | Retrieves the IID of the interface represented by the connection point.
GetConnectionPointContainer | Retrieves an interface pointer to the connectable object.
Unadvise | Terminates a connection previously established through Advise.

Data Members

m_vec Manages the connections for the connection point.

IConnectionPointImpl Overview


IConnectionPointImpl::Advise

HRESULT Advise( IUnknown* pUnkSink, DWORD* pdwCookie );

See IConnectionPoint::Advise in the Win32 SDK.

Remarks

Establishes a connection between the connection point and a sink.

To terminated the connection call, Unadvise.


IConnectionPointImpl::EnumConnections

HRESULT EnumConnections( IEnumConnections** ppEnum );

See IConnectionPoint::EnumConnections in the Win32 SDK.

Remarks

Creates an enumerator to iterate through the connections for the connection point.

IConnectionPointImpl Overview | Class Members

See Also IEnumConnections


IConnectionPointImpl::GetConnectionInterface

HRESULT GetConnectionInterface( IID* piid2 );

See IConnectionPoint::GetConnectionInterface in the Win32 SDK.

Remarks

Retrieves the IID of the interface represented by the connection point.


IConnectionPointImpl::GetConnectionPointContainer

HRESULT GetConnectionPointContainer( IConnectionPointContainer** ppCPC );

See IConnectionPoint::GetConnectionPointContainer in the Win32 SDK.

Remarks

Retrieves an interface pointer to the connectable object.

IConnectionPointImpl Overview | Class Members

See Also IConnectionPointContainerImpl


IConnectionPointImpl::Unadvise

HRESULT Unadvise( DWORD dwCookie );

See IConnectionPoint::Unadvise in the Win32 SDK.

Remarks

Terminates a connection previously established through Advise.


IConnectionPointImpl::m_vec

CDV m_vec;

Remarks

Manages the connections between the connection point object and a sink. By default, m_vec is of type CComDynamicUnkArray.


IDataObjectImpl

template< class T >
class IDataObjectImpl

Parameters

T

Your class, derived from IDataObjectImpl.

The IDataObject interface provides methods to support Uniform Data Transfer. IDataObject uses the standard format structures FORMATETC and STGMEDIUM to retrieve and store data.

IDataObject also manages connections to advise sinks to handle data change notifications. In order for the client to receive data change notifications from the data object, the client must implement the IAdviseSink interface on an object called an advise sink. When the client then calls IDataObject::DAdvise, a connection is established between the data object and the advise sink.

Class IDataObjectImpl provides a default implementation of IDataObject and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members


IDataObjectImpl Class Members

Class Methods

FireDataChange Sends a change notification back to each advise sink.

IDataObject Methods

DAdvise | Establishes a connection between the data object and an advise sink. This enables the advise sink to receive notifications of changes in the object.
DUnadvise | Terminates a connection previously established through DAdvise.
EnumDAdvise | Creates an enumerator to iterate through the current advisory connections.
EnumFormatEtc | Creates an enumerator to iterate through the FORMATETC structures supported by the data object. The ATL implementation returns E_NOTIMPL.
GetCanonicalFormatEtc | Retrieves a logically equivalent FORMATETC structure to one that is more complex. The ATL implementation returns E_NOTIMPL.
GetData | Transfers data from the data object to the client. The data is described in a FORMATETC structure and is transferred through a STGMEDIUM structure.
GetDataHere | Similar to GetData, except the client must allocate the STGMEDIUM structure. The ATL implementation returns E_NOTIMPL.
QueryGetData | Determines whether the data object supports a particular FORMATETC structure for transferring data. The ATL implementation returns E_NOTIMPL.
SetData | Transfers data from the client to the data object. The ATL implementation returns E_NOTIMPL.

IDataObjectImpl Overview


IDataObjectImpl::DAdvise

HRESULT DAdvise( FORMATETC* pformatetc, DWORD advf, IAdviseSink* pAdvSink, DWORD* pdwConnection );

See IDataObject::DAdvise in the Win32 SDK.

Remarks

Establishes a connection between the data object and an advise sink. This enables the advise sink to receive notifications of changes in the object.

To terminate the connection, call DUnadvise.

IDataObjectImpl Overview | Class Members

See Also FORMATETC, IAdviseSink


IDataObjectImpl::DUnadvise

HRESULT DUnadvise( FORMATETC* pformatetc, DWORD advf, IAdviseSink* pAdvSink, DWORD* pdwConnection );

See IDataObject::DUnadvise in the Win32 SDK.

Remarks

Terminates a connection previously established through DAdvise.

IDataObjectImpl Overview | Class Members

See Also FORMATETC, IAdviseSink


IDataObjectImpl::EnumDAdvise

HRESULT DAdvise( FORMATETC* pformatetc, DWORD advf, IAdviseSink* pAdvSink, DWORD* pdwConnection );

See IDataObject::EnumDAdvise in the Win32 SDK.

Remarks

Creates an enumerator to iterate through the current advisory connections.

IDataObjectImpl Overview | Class Members

See Also FORMATETC, IAdviseSink


IDataObjectImpl::EnumFormatEtc

HRESULT EnumFormatEtc( DWORD dwDirection, IEnumFORMATETC** ppenumFormatEtc );

See IDataObject::EnumFormatEtc in the Win32 SDK.

Remarks

Returns E_NOTIMPL.

IDataObjectImpl Overview | Class Members

See Also IEnumFORMATETC


IDataObjectImpl::FireDataChange

HRESULT FireDataChange( );

Return Value

A standard HRESULT value.

Remarks

Sends a change notification back to each advise sink that is currently being managed.


IDataObjectImpl::GetCanonicalFormatEtc

HRESULT GetCanonicalFormatEtc( FORMATETC* pformatetcIn, FORMATETC* pformatetcOut );

See IDataObject::GetCanonicalFormatEtc in the Win32 SDK.

Remarks

Returns E_NOTIMPL.

IDataObjectImpl Overview | Class Members

See Also FORMATETC


IDataObjectImpl::GetData

HRESULT GetData( FORMATETC* pformatetcIn, STGMEDIUM* pmedium );

See IDataObject::GetData in the Win32 SDK.

Remarks

Transfers data from the data object to the client. The pformatetcIn parameter must specify a storage medium type of TYMED_MFPICT.

IDataObjectImpl Overview | Class Members

See Also IDataObjectImpl::GetDataHere, IDataObjectImpl::QueryGetData, IDataObjectImpl::SetData, FORMATETC, STGMEDIUM, TYMED


IDataObjectImpl::GetDataHere

HRESULT GetDataHere( FORMATETC* pformatetc, STGMEDIUM* pmedium );

See IDataObject::GetDataHere in the Win32 SDK.

Remarks

Returns E_NOTIMPL.

IDataObjectImpl Overview | Class Members

See Also IDataObjectImpl::GetData, IDataObjectImpl::QueryGetData, IDataObjectImpl::SetData, FORMATETC, STGMEDIUM


IDataObjectImpl::QueryGetData

HRESULT QueryGetData( FORMATETC* pformatetc );

See IDataObject::QueryGetData in the Win32 SDK.

Remarks

Returns E_NOTIMPL.

IDataObjectImpl Overview | Class Members

See Also IDataObjectImpl::GetData, IDataObjectImpl::GetDataHere, IDataObjectImpl::SetData, FORMATETC


IDataObjectImpl::SetData

HRESULT SetData( FORMATETC* pformatetc, STGMEDIUM* pmedium, BOOL fRelease );

See IDataObject::SetData in the Win32 SDK.

Remarks

Returns E_NOTIMPL.

IDataObjectImpl Overview | Class Members

See Also IDataObjectImpl::GetData, IDataObjectImpl::GetDataHere, IDataObjectImpl::QueryGetData, FORMATETC, STGMEDIUM


IDispatchImpl

template< class T, const IID* piid, const GUID* plibid, WORD wMajor = 1, WORD wMinor = 0, class tihclass = CComTypeInfoHolder >
class IDispatchImpl : public T

Parameters

T

A dual interface.

piid

A pointer to the IID of T.

plibid

A pointer to the identifier of T's type library section.

wMajor

The major version of the type library. The default value is 1.

wMinor

The minor version of the type library. The default value is 0.

tihclass

The class used to manage the type information for T. The default value is CComTypeInfoHolder.

IDispatchImpl provides a default implementation for the IDispatch portion of any dual interface on your object. A dual interface derives from IDispatch and uses only Automation-compatible types. Like a dispinterface, a dual interface supports early and late binding; however, a dual interface differs in that it also supports vtable binding.

The following example shows a typical implementation of IDispatchImpl:

class CBeeper :
      public IDispatchImpl< IBeeper, &IID_IBeeper,
         &LIBID_BeeperLib >,
      public CComObjectRoot,
      public CComCoClass< CBeeper, &CLSID_Beeper >
{
   ...
};

IDispatchImpl contains a static member of type CComTypeInfoHolder that manages the type information for the dual interface. If you have multiple objects implementing the same dual interface, only a single instance of CComTypeInfoHolder will be used.

#include <atlcom.h>

Class Members

See Also ITypeInfo


IDispatchImpl Class Members

Class Methods

IdispatchImpl Constructor.

IDispatch Methods

GetIDsOfNames | Maps a set of names to a corresponding set of dispatch identifiers.
GetTypeInfo | Retrieves the type information for the dual interface.
GetTypeInfoCount | Determines whether there is type information available for the dual interface.
Invoke | Provides access to the methods and properties exposed by the dual interface.

Data Members

_tih Manages the type information for the dual interface.

IDispatchImpl Overview


IDispatchImpl::GetIDsOfNames

HRESULT GetIDsOfNames( REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid );

See IDispatch::GetIDsOfNames in the Win32 SDK.

Remarks

Maps a set of names to a corresponding set of dispatch identifiers.


IDispatchImpl::GetTypeInfo

HRESULT GetTypeInfo( UINT itinfo, LCID lcid, ITypeInfo** pptinfo );

See IDispatch::GetTypeInfo in the Win32 SDK.

Remarks

Retrieves the type information for the dual interface.

IDispatchImpl Overview | Class Members

See Also IDispatchImpl::GetTypeInfoCount


IDispatchImpl::GetTypeInfoCount

HRESULT GetTypeInfoCount( UINT* pctinfo );

See IDispatch::GetTypeInfoCount in the Win32 SDK.

Remarks

Determines whether there is type information available for the dual interface.

IDispatchImpl Overview | Class Members

See Also IDispatchImpl::GetTypeInfo


IDispatchImpl::IDispatchImpl

IDispatchImpl( );

Remarks

The constructor. Calls AddRef on the _tih member. The destructor calls Release.


IDispatchImpl::Invoke

HRESULT Invoke( DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr );

See IDispatch::Invoke in the Win32 SDK.

Remarks

Provides access to the methods and properties exposed by the dual interface.


IDispatchImpl::_tih

static tihclass _tih;

Remarks

This static data member is an instance of the class template parameter, tihclass, which by default is CComTypeInfoHolder. _tih manages the type information for the dual interface.


IDispEventImpl

template <UINT nID, class T, const IID* pdiid = &IID_NULL, const GUID* plibid = &GUID_NULL, WORD wMajor = 0, WORD wMinor = 0, class tihclass = CComTypeInfoHolder>
class ATL_NO_VTABLE IDispEventImpl : public _IDispEventLocator<nID, pdiid>

Parameters

nID

An identifier, unique to the class, that must match the nID in the SINK_ENTRY or SINK_ENTRY_EX macros in the sink map for the class T. For composite controls, use the resource ID for this parameter.

T

The user's class, which is derived from IDispEventImpl.

pdiid

The pointer to either a GUID, or its dispatch ID, for the dispatch interface of the event interface that this class implements. This interface is defined in the type library pointed to by plibid.

plibid

A pointer to the type library that defines the dispatch interface pointed to by pdiid. If &GUID_NULL, the type library will be loaded from the object sourcing the events.

wMajor

The major version of the type library. The default value is 0.

wMinor

The minor version of the type library. The default value is 0.

tihclass

The class used to manage the type information for T. The default value is a class of type CComTypeInfoHolder; however, you can override this template parameter by providing a class of a type other than CComTypeInfoHolder.

IDispEventImpl provides support for connection points for an ATL COM object. These connection points are mapped with an event sink map, which is provided by your COM object.

When you use IDispEvenImpl, you always use it from within the client, which implements the sink event.

When you implement an event sink using IDispatchImpl, there is no need to sync every event on the interface.

You must provide one IDispEventImpl interface for each object for which you must handle events. The IDispEventImpl parameter nID identifies the object associated with the interface, and, in the case of a composite control, it must match the control's id parameter listed in the SINK_ENTRY macro. The event sink map ensures that event notifications are handled by the proper function.

IDispEventSimplImpl provides the same functionality as IDispEventImpl, except it does not hold the type information.

For more information, see Supporting IDispEventImpl.

#include <atlcom.h>

Class Members

See Also

IDispatchImpl


IDispEventImpl Class Members

Class Methods

IdispEventImpl | The constructor.
GetTypeInfoCount | Retrieves the number of type information interfaces.
GetTypeInfo | Retrieves the type information for an object.
GetIDsOfNames | Maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs.
GetFuncInfoFromId | Locates the function index for the specified dispatch identifier.
GetUserDefinedType | Retrieves the basic type of a user defined type.

Typedefs

tihclass The class used to manage the type information. By default, CcomTypeInfoHolder.

IDispEventImpl Overview


IDispEventImpl::GetFuncInfoFromId

HRESULT GetFuncInfoFromId( const IID& /*iid*/, DISPID dispidMember, LCID lcid, _ATL_FUNC_INFO& info );

Return Value

A standard HRESULT value.

Parameters

/*iid*/

[in] A reference to the ID of the function.

dispidMember

[in] The dispatch ID of the function.

lcid

[in] The locale context of the function ID.

info

[in] The structure indicating how the function is called.

Remarks

Locates the function index for the specified dispatch identifier.

IDispEventImpl Overview | Class Members

See Also

Supporting IDispEventImpl


IDispEventImpl::GetIDsOfNames

HRESULT GetIDsOfNames( REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid );

See IDispatch::GetIDsOfNames

Remarks

Maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs, which can be used on subsequent calls to IDispatch::Invoke.

IDispEventImpl Overview | Class Members

See Also

IDispEventImpl::GetFuncInfoFromId, Supporting IDispEventImpl


IDispEventImpl::GetTypeInfo

HRESULT GetTypeInfo( UINT itinfo, LCID lcid, ITypeInfo** pptinfo );

See IDispatch::GetTypeInfo in the Platform SDK.

Remarks

Retrieves the type information for an object, which can then be used to get the type information for an interface.

IDispEventImpl Overview | Class Members

See Also

IDispEventImpl::GetTypeInfoCount, Supporting IDispEventImpl


IDispEventImpl::GetTypeInfoCount

HRESULT GetTypeInfoCount( UINT* pctinfo );

See IDispatch::GetTypeInfoCount in the Platform SDK.

Remarks

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

IDispEventImpl Overview | Class Members

See Also

IDispEventImpl::GetTypeInfo, Supporting IDispEventImpl


IDispEventImpl::GetUserDefinedType

VARTYPE GetUserDefinedType( ITypeInfo *pTI, HREFTYPE hrt );

See ITypeInfo::GetRefTypeInfo in the Platform SDK.

Return Value

The type of variant.

Parameters

pTI

[in] A pointer to the ITypeInfo interface containing the user-defined type.

hrt

[in] A handle to the type description to be retrieved.

Remarks

Retrieves the basic type of a user defined type.

IDispEventImpl Overview | Class Members

See Also

Supporting IDispEventImpl


IDispEventImpl::IDispEventImpl

IDispEventImpl( );

Remarks

The constructor. Contains the values of the class template parameters plibid, pdiid, wMajor, and wMinor.

IDispEventImpl Overview | Class Members

See Also

Supporting IDispEventImpl


IDispEventImpl::tihclass

typedef tihclass _tihclass;

Remarks

This typedef is an instance of the class template parameter tihclass. By default, the class is CComTypeInfoHolder. CComTypeInfoHolder manages the type information for the class.

IDispEventImpl Overview | Class Members

See Also

Supporting IDispEventImpl


IObjectSafetyImpl

template <class T, DWORD dwSupportedSafety>

class IObjectSafetyImpl

Parameters

T

Your class, derived from IObjectSafetyImpl.

dwSupportedSafety

Specifies the supported safety options for the control. Can be one of the following values:

  • INTERFACESAFE_FOR_UNTRUSTED_CALLER The interface identified by the SetInterfaceSafetyOptions parameter riid should be made safe for scripting.

  • INTERFACESAFE_FOR_UNTRUSTED_DATA The interface identified by the SetInterfaceSafetyOptions parameter riid should be made safe for untrusted data during initialization.

The IObjectSafety interface allows a client to retrieve and set an object's safety levels. For example, a web browser may call IObjectSafety::SetInterfaceSafetyOptions to make a control safe for initialization or safe for scripting.

Class IObjectSafetyImpl provides a default implementation of IObjectSafety and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also IObjectSafety in the ActiveX SDK


IObjectSafetyImpl Class Members

IObjectSafety Methods

GetInterfaceSafetyOptions | Retrieves the safety options supported by the object, as well as the safety options currently set for the object.
SetInterfaceSafetyOptions | Makes the object safe for initialization or scripting.

Data Members

m_dwSafety Stores the object's current safety level.

IObjectSafetyImpl Overview


IObjectSafetyImpl::GetInterfaceSafetyOptions

HRESULT GetInterfaceSafetyOptions( REFIID riid, DWORD* pdwSupportedOptions, DWORD* pdwEnabledOptions );

See IObjectSafety::GetInterfaceSafetyOptions in the ActiveX SDK.

Remarks

Retrieves the safety options supported by the object, as well as the safety options currently set for the object. If the riid parameter is not IID_IDispatch, this method returns E_NOINTERFACE.

IObjectSafetyImpl Overview | Class Members

See Also IObjectSafetyImpl::SetInterfaceSafetyOptions


IObjectSafetyImpl::SetInterfaceSafetyOptions

HRESULT SetInterfaceSafetyOptions( REFIID riid, DWORD dwOptionsSetMask, DWORD dwEnabledOptions );

See IObjectSafety::SetInterfaceSafetyOptions in the ActiveX SDK.

Remarks

Makes the object safe for initialization or scripting. If the riid parameter is not IID_IDispatch, this method returns E_NOINTERFACE.

IObjectSafetyImpl Overview | Class Members

See Also IObjectSafetyImpl::GetInterfaceSafetyOptions


IObjectSafetyImpl::m_dwSafety

DWORD m_dwSafety;

Remarks

Stores the object's current safety level.


IObjectWithSiteImpl

template< class T >
class IObjectWithSiteImpl

Parameters

T

Your class, derived from IObjectWithSiteImpl.

The IObjectWithSite interface allows an object to communicate with its site. Class IObjectWithSiteImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

IObjectWithSiteImpl specifies two methods. The client first calls SetSite, passing the site's IUnknown pointer. This pointer is stored within the object, and can later be retrieved through a call to GetSite.

Typically, you derive your class from IObjectWithSiteImpl when you are creating an object that is not a control. For controls, derive your class from IOleObjectImpl, which also provides a site pointer. Do not derive your class from both IObjectWithSiteImpl and IOleObjectImpl.

#include <atlcom.h>

Class Members


IObjectWithSiteImpl Class Members

IObjectWithSite Methods

GetSite | Queries the site for an interface pointer.
SetSite | Provides the object with the site's IUnknown pointer.

Data Members

m_spUnkSite Manages the site's IUnknown pointer.

IObjectWithSiteImpl Overview


IObjectWithSiteImpl::GetSite

HRESULT GetSite( REFIID riid, void **ppvSite );

See IObjectWithSite::GetSite in the Win32 SDK.

Remarks

Queries the site for a pointer to the interface identified by riid. If the site supports this interface, the pointer is returned via ppvSite. Otherwise, ppvSite is set to NULL.

IObjectWithSiteImpl Overview | Class Members

See Also IObjectWithSiteImpl::SetSite


IObjectWithSiteImpl::SetSite

HRESULT SetSite( IUnknown* pUnkSite );

See IObjectWithSite::SetSite in the Win32 SDK.

Remarks

Provides the object with the site's IUnknown pointer.

IObjectWithSiteImpl Overview | Class Members

See Also IObjectWithSiteImpl::GetSite


IObjectWithSiteImpl::m_spUnkSite

CComPtr< IUnknown > m_spUnkSite;

Remarks

Manages the site's IUnknown pointer. m_spUnkSite initially receives this pointer through a call to SetSite.

IObjectWithSiteImpl Overview | Class Members

See Also CComPtr


IOleControlImpl

template< class T >
class IOleControlImpl

Parameters

T

Your class, derived from IOleControlImpl.

Class IOleControlImpl provides a default implementation of the IOleControl interface and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also IOleObjectImpl, ActiveX Controls Interfaces in the Win32 SDK


IOleControlImpl Class Members

IOleControl Methods

FreezeEvents | Indicates whether or not the container ignores or accepts events from the control.
GetControlInfo | Fills in information about the control's keyboard behavior. The ATL implementation returns E_NOTIMPL.
OnAmbientPropertyChange | Informs a control that one or more of the container's ambient properties has changed. The ATL implementation returns S_OK.
OnMnemonic | Informs the control that a user has pressed a specified keystroke. The ATL implementation returns E_NOTIMPL.

IOleControlImpl Overview


IOleControlImpl::FreezeEvents

HRESULT FreezeEvents( BOOL bFreeze );

See IOleControl::FreezeEvents in the Win32 SDK.

Remarks

In ATL's implementation, FreezeEvents increments the control class's m_nFreezeEvents data member if bFreeze is TRUE, and decrements m_nFreezeEvents if bFreeze is FALSE. FreezeEvents then returns S_OK.

IOleControlImpl Overview | Class Members

See Also CComControl::m_nFreezeEvents


IOleControlImpl::GetControlInfo

HRESULT GetControlInfo( LPCONTROLINFO pCI );

See IOleControl:GetControlInfo in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleControlImpl::OnAmbientPropertyChange

HRESULT OnAmbientPropertyChange( DISPID dispid );

See IOleControl::OnAmbientPropertyChange in the Win32 SDK.

Remarks

Returns S_OK.


IOleControlImpl::OnMnemonic

HRESULT OnMnemonic( LPMSG pMsg );

See IOleControl::OnMnemonic in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleInPlaceActiveObjectImpl

template< class T >
class IOleInPlaceActiveObjectImpl

Parameters

T

Your class, derived from IOleInPlaceActiveObjectImpl.

The IOleInPlaceActiveObject interface assists communication between an in-place control and its container; for example, communicating the active state of the control and container, and informing the control it needs to resize itself. Class IOleInPlaceActiveObjectImpl provides a default implementation of IOleInPlaceActiveObject and supports IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also CComControl, ActiveX Controls Interfaces in the Win32 SDK


IOleInPlaceActiveObjectImpl Class Members

IOleWindow Methods

ContextSensitiveHelp | Enables context-sensitive help. The ATL implementation returns E_NOTIMPL.
GetWindow | Gets a window handle.

IOleInPlaceActiveObject Methods

EnableModeless | Enables modeless dialog boxes. The ATL implementation returns S_OK.
OnDocWindowActivate | Notifies the control when the container's document window is activated or deactivated. The ATL implementation returns S_OK.
OnFrameWindowActivate | Notifies the control when the container's top-level frame window is activated or deactivated.
ResizeBorder | Informs the control it needs to resize its borders. The ATL implementation returns S_OK.
TranslateAccelerator | Processes menu accelerator-key messages from the container. The ATL implementation returns E_NOTIMPL.

IOleInPlaceActiveObjectImpl Overview


IOleInPlaceActiveObjectImpl::ContextSensitiveHelp

HRESULT ContextSensitiveHelp( BOOL fEnterMode );

See IOleWindow::ContextSensitiveHelp in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleInPlaceActiveObjectImpl::EnableModeless

HRESULT EnableModeless( BOOL fEnable );

See IOleInPlaceActiveObject::EnableModeless in the Win32 SDK.

Remarks

Returns S_OK.


IOleInPlaceActiveObjectImpl::GetWindow

HRESULT GetWindow( HWND* phwnd );

See IOleWindow::GetWindow in the Win32 SDK.

Remarks

The container calls this function to get the window handle of the control. Some containers will not work with a control that has been windowless, even if it is currently windowed. In ATL's implementation, if the CComControl::m_bWasOnceWindowless data member is TRUE, the function returns E_FAIL. Otherwise, if *phwnd is not NULL, GetWindow assigns phwnd to the control class's data member m_hWnd and returns S_OK.

IOleInPlaceActiveObjectImpl Overview | Class Members

See Also CComControl::m_bWasOnceWindowless


IOleInPlaceActiveObjectImpl::OnDocWindowActivate

HRESULT OnDocWindowActivate( BOOL fActivate );

See IOleInPlaceActiveObject::OnDocWindowActivate in the Win32 SDK.

Remarks

Returns S_OK.


IOleInPlaceActiveObjectImpl::OnFrameWindowActivate

HRESULT OnFrameWindowActivate( BOOL fActivate );

See IOleInPlaceActiveObject::OnFrameWindowActivate in the Win32 SDK.

Remarks

Returns S_OK.


IOleInPlaceActiveObjectImpl::ResizeBorder

HRESULT ResizeBorder( LPRECT prcBorder, IOleInPlaceUIWindow* pUIWindow, BOOL fFrameWindow );

See IOleInPlaceActiveObject::ResizeBorder in the Win32 SDK.

Remarks

Returns S_OK.


IOleInPlaceActiveObjectImpl::TranslateAccelerator

HRESULT TranslateAccelerator( LPMSG lpmsg );

See IOleInPlaceActiveObject::TranslateAccelerator in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleInPlaceObjectWindowlessImpl

template< class T >
class IOleInPlaceObjectWindowlessImpl

Parameters

T

Your class, derived from IOleInPlaceObjectWindowlessImpl.

The IOleInPlaceObject interface manages the reactivation and deactivation of in-place controls and determines how much of the control should be visible. The IOleInPlaceObjectWindowless interface enables a windowless control to receive window messages and to participate in drag-and-drop operations. Class IOleInPlaceObjectWindowlessImpl provides a default implementation of IOleInPlaceObject and IOleInPlaceObjectWindowless and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also CComControl


IOleInPlaceObjectWindowlessImpl Class Members

IOleWindow Methods

ContextSensitiveHelp | Enables context-sensitive help. The ATL implementation returns E_NOTIMPL.
GetWindow | Gets a window handle.

IOleInPlaceObject Methods

InPlaceDeactivate | Deactivates an active in-place control.
ReactivateAndUndo | Reactivates a previously deactivated control. The ATL implementation returns E_NOTIMPL.
SetObjectRects | Indicates what part of the in-place control is visible.
UIDeactivate | Deactivates and removes the user interface that supports in-place activation.

IOleInPlaceObjectWindowless Methods

GetDropTarget | Supplies the IDropTarget interface for an in-place active, windowless object that supports drag and drop. The ATL implementation returns E_NOTIMPL.
OnWindowMessage | Dispatches a message from the container to a windowless control that is in-place active.

IOleInPlaceObjectWindowlessImpl Overview


IOleInPlaceObjectWindowlessImpl::ContextSensitiveHelp

HRESULT ContextSensitiveHelp( BOOL fEnterMode );

See IOleWindow::ContextSensitiveHelp in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleInPlaceObjectWindowlessImpl::GetDropTarget

HRESULT GetDropTarget( IDropTarget** ppDropTarget );

See IOleInPlaceObjectWindowless::GetDropTarget in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleInPlaceObjectWindowlessImpl::GetWindow

HRESULT GetWindow( HWND* phwnd );

See IOleWindow::GetWindow in the Win32 SDK.

Remarks

The container calls this function to get the window handle of the control. Some containers will not work with a control that has been windowless, even if it is currently windowed. In ATL's implementation, if the control class's data member m_bWasOnceWindowless is TRUE, the function returns E_FAIL. Otherwise, if phwnd is not NULL, GetWindow sets *phwnd to the control class's data member m_hWnd and returns S_OK.

IOleInPlaceObjectWindowlessImpl Overview | Class Members

See Also CComControl::m_bWasOnceWindowless


IOleInPlaceObjectWindowlessImpl::InPlaceDeactivate

HRESULT InPlaceDeactivate( HWND* phwnd );

See IOleInPlaceObject::InPlaceDeactivate in the Win32 SDK.

Remarks

Called by the container to deactivate an in-place active control. This method performs a full or partial deactivation depending on the state of the control. If necessary, the control's user interface is deactivated, and the control's window, if any, is destroyed. The container is notified that the control is no longer active in place. The IOleInPlaceUIWindow interface used by the container to negotiate menus and border space is released.

IOleInPlaceObjectWindowlessImpl Overview | Class Members

See Also CComControl::InPlaceActivate


IOleInPlaceObjectWindowlessImpl::OnWindowMessage

HRESULT OnWindowMessage( UINT msg, WPARAM WParam, LPARAM LParam, LRESULT plResultParam );

See IOleInPlaceObjectWindowless::OnWindowMessage in the Win32 SDK.

Remarks

Dispatches a message from a container to a windowless control that is in-place active.


IOleInPlaceObjectWindowlessImpl::ReactivateAndUndo

HRESULT ReactivateAndUndo( );

See IOleInPlaceObject::ReactivateAndUndo in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleInPlaceObjectWindowlessImpl::SetObjectRects

HRESULT SetObjectRects( LPCRECT prcPos, LPCRECT prcClip );

See IOleInPlaceObject::SetObjectRects in the Win32 SDK.

Remarks

Called by the container to inform the control that its size and/or position has changed. Updates the control's m_rcPos data member and the control display. Only the part of the control that intersects the clip region is displayed. If a control's display was previously clipped but the clipping has been removed, this function can be called to redraw a full view of the control.

IOleInPlaceObjectWindowlessImpl Overview | Class Members

See Also CComControl::m_rcPos


IOleInPlaceObjectWindowlessImpl::UIDeactivate

HRESULT UIDeactivate( );

See IOleInPlaceObject::UIDeactivate in the Win32 SDK.

Remarks

Deactivates and removes the control's user interface that supports in-place activation. Sets the control class's data member m_bUIActive to FALSE. The ATL implementation of this function always returns S_OK.

IOleInPlaceObjectWindowlessImpl Overview | Class Members

See Also CComControl::m_bUIActive


IOleObjectImpl

template< class T >
class IOleObjectImpl

Parameters

T

Your class, derived from IOleObjectImpl.

The IOleObject interface is the principle interface through which a container communicates with a control. Class IOleObjectImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also CComControl, ActiveX Controls Interfaces in the Win32 SDK


IOleObjectImpl Class Members

IOleObject Methods

Advise | Establishes an advisory connection with the control.
Close | Changes the control state from running to loaded.
DoVerb | Tells the control to perform one of its enumerated actions.
EnumAdvise | Enumerates the control's advisory connections.
EnumVerbs | Enumerates actions for the control.
GetClientSite | Retrieves the control's client site.
GetClipboardData | Retrieves data from the Clipboard. The ATL implementation returns E_NOTIMPL.
GetExtent | Retrieves the extent of the control's display area.
GetMiscStatus | Retrieves the status of the control.
GetMoniker | Retrieves the control's moniker. The ATL implementation returns E_NOTIMPL.
GetUserClassID | Retrieves the control's class identifier.
GetUserType | Retrieves the control's user-type name.
InitFromData | Initializes the control from selected data. The ATL implementation returns E_NOTIMPL.
IsUpToDate | Checks if the control is up to date. The ATL implementation returns S_OK.
SetClientSite | Tells the control about its client site in the container.
SetColorScheme | Recommends a color scheme to the control's application, if any. The ATL implementation returns E_NOTIMPL.
SetExtent | Sets the extent of the control's display area.
SetHostNames | Tells the control the names of the container application and container document.
SetMoniker | Tells the control what its moniker is. The ATL implementation returns E_NOTIMPL.
Unadvise | Destroys an advisory connection with the control.
Update | Updates the control. The ATL implementation returns S_OK.

DoVerb Helper Methods

DoVerbDiscardUndo | Tells the control to discard any undo state it is maintaining.
DoVerbHide | Tells the control to remove its user interface from view.
DoVerbInPlaceActivate | Runs the control and installs its window, but does not install the control's user interface.
DoVerbOpen | Causes the control to be open-edited in a separate window.
DoVerbPrimary | Performs the specified action when the user double-clicks the control. The control defines the action, usually to activate the control in-place.
DoVerbShow | Shows a newly inserted control to the user.
DoVerbUIActivate | Activates the control in-place and shows the control's user interface, such as menus and toolbars.

IOleObjectImpl Overview


IOleObjectImpl::Advise

HRESULT Advise( IAdviseSink* pAdvSink, DWORD* pdwConnection );

See IOleObject::Advise in the Win32 SDK.

Remarks

If successful, the IAdviseSink pointer is stored in the control class's m_spOleAdviseHolder data member.

IOleObjectImpl Overview | Class Members

See Also CComControl::m_spOleAdviseHolder, IOleObjectImpl::Unadvise


IOleObjectImpl::Close

HRESULT Close( DWORD dwSaveOption );

See IOleObject::Close in the Win32 SDK.

Remarks

Changes the control from the running to the loaded state. Deactivates the control and destroys the control window if it exists. If the control class data member m_bRequiresSave is TRUE and the dwSaveOption parameter is either OLECLOSE_SAVEIFDIRTY or OLECLOSE_PROMPTSAVE, the control properties are saved before closing.

The pointers held in the control class data members m_spInPlaceSite and m_spAdviseSink are released, and the data members m_bNegotiatedWnd, m_bWndless, and m_bInPlaceSiteEx are set to FALSE.


IOleObjectImpl::DoVerb

HRESULT DoVerb( LONG iVerb, LPMSG lpmsg, IOleClientSite* pActiveSite, LONG lindex, HWND hwndParent, LPCRECT lprcPosRect );

See IOleObject::DoVerb in the Win32 SDK.

Remarks

The ATL implementation of this function uses only the first parameter, iVerb. Depending on the value of iVerb, one of the ATL DoVerb helper functions is called as follows:

iVerb Value | DoVerb helper function called
OLEIVERB_DISCARDUNDOSTATE | DoVerbDiscardUndo
OLEIVERB_HIDE | DoVerbHide
OLEIVERB_INPLACEACTIVATE | DoVerbInPlaceActivate
OLEIVERB_OPEN | DoVerbOpen
OLEIVERB_PRIMARY | DoVerbPrimary
OLEIVERB_PROPERTIES | CComControl::DoVerbProperties
OLEIVERB_SHOW | DoVerbShow
OLEIVERB_UIACTIVATE | DoVerbUIActivate

IOleObjectImpl Overview | Class Members

See Also IOleObject::EnumVerbs


IOleObjectImpl::DoVerbDiscardUndo

HRESULT DoVerbDiscardUndo( LPCRECT prcPosRect, HWND hwndParent );

Return Value

Returns S_OK.

Parameters

prcPosRec

[in] Pointer to the rectangle the container wants the control to draw into.

hwndParent

[in] Handle of the window containing the control.

Remarks

The default implementation simply returns S_OK.


IOleObjectImpl::DoVerbHide

HRESULT DoVerbHide( LPCRECT prcPosRect, HWND hwndParent );

Return Value

Returns S_OK.

Parameters

prcPosRec

[in] Pointer to the rectangle the container wants the control to draw into.

hwndParent

[in] Handle of the window containing the control. Not used in the ATL implementation.

Remarks

Deactivates and removes the control's user interface, and hides the control.

IOleObjectImpl Overview | Class Members

See Also IOleObjectImpl::DoVerbShow


IOleObjectImpl::DoVerbInPlaceActivate

HRESULT DoVerbInPlaceActivate( LPCRECT prcPosRect, HWND hwndParent );

Return Value

One of the standard HRESULT values.

Parameters

prcPosRec

[in] Pointer to the rectangle the container wants the control to draw into.

hwndParent

[in] Handle of the window containing the control. Not used in the ATL implementation.

Remarks

Activates the control in place by calling CComControl::InPlaceActivate. Unless the control class's data member m_bWindowOnly is TRUE, DoVerbInPlaceActivate first attempts to activate the control as a windowless control (possible only if the container supports IOleInPlaceSiteWindowless). If that fails, the function attempts to activate the control with extended features (possible only if the container supports IOleInPlaceSiteEx). If that fails, the function attempts to activate the control with no extended features (possible only if the container supports IOleInPlaceSite). If activation succeeds, the function notifies the container the control has been activated.

IOleObjectImpl Overview | Class Members

See Also CComControl::InPlaceActivate, CComControl::m_bWindowOnly


IOleObjectImpl::DoVerbOpen

HRESULT DoVerbOpen( LPCRECT prcPosRect, HWND hwndParent );

Return Value

Returns S_OK.

Parameters

prcPosRec

[in] Pointer to the rectangle the container wants the control to draw into.

hwndParent

[in] Handle of the window containing the control.

Remarks

The default implementation simply returns S_OK.


IOleObjectImpl::DoVerbPrimary

HRESULT DoVerbPrimary( LPCRECT prcPosRect, HWND hwndParent );

Return Value

One of the standard HRESULT values.

Parameters

prcPosRec

[in] Pointer to the rectangle the container wants the control to draw into.

hwndParent

[in] Handle of the window containing the control.

Remarks

Defines the action taken when the user double-clicks the control. By default, set to display the property pages. You can override this in your control class to invoke a different behavior on double-click; for example, play a video or go in-place active.

IOleObjectImpl Overview | Class Members

See Also CComControl::DoVerbProperties


IOleObjectImpl::DoVerbShow

HRESULT DoVerbShow( LPCRECT prcPosRect, HWND hwndParent );

Return Value

One of the standard HRESULT values.

Parameters

prcPosRec

[in] Pointer to the rectangle the container wants the control to draw into.

hwndParent

[in] Handle of the window containing the control. Not used in the ATL implementation.

Remarks

Tells the container to make the control visible.

IOleObjectImpl Overview | Class Members

See Also IOleObjectImpl::DoVerbHide


IOleObjectImpl::DoVerbUIActivate

HRESULT DoVerbUIActivate( LPCRECT prcPosRect, HWND hwndParent );

Return Value

One of the standard HRESULT values.

Parameters

prcPosRec

[in] Pointer to the rectangle the container wants the control to draw into.

hwndParent

[in] Handle of the window containing the control. Not used in the ATL implementation.

Remarks

Activates the control's user interface and notifies the container that its menus are being replaced by composite menus.

IOleObjectImpl Overview | Class Members

See Also CComControl::InPlaceActivate, IOleObjectImpl::DoVerbInPlaceActivate


IOleObjectImpl::EnumAdvise

HRESULT EnumAdvise( IEnumSTATDATA** ppenumAdvise );

See IOleObject::EnumAdvise in the Win32 SDK.

Remarks

Supplies an enumeration of registered advisory connections for this control.

IOleObjectImpl Overview | Class Members

See Also IOleObjectImpl::EnumVerbs


IOleObjectImpl::EnumVerbs

HRESULT EnumVerbs( IEnumOLEVERB** ppEnumOleVerb );

See IOleObject::EnumVerbs in the Win32 SDK.

Remarks

Supplies an enumeration of registered actions (verbs) for this control by calling OleRegEnumVerbs. You can add verbs to your project's .rgs file. For example, see CIRCCTL.RGS in the CIRC sample.

IOleObjectImpl Overview | Class Members

See Also OleRegEnumVerbs, IOleObjectImpl::EnumAdvise


IOleObjectImpl::GetClientSite

HRESULT GetClientSite( IOleClientSite** ppClientSite );

See IOleObject::GetClientSite in the Win32 SDK.

Remarks

Puts the pointer in the control class data member m_spClientSite into ppClientSite and increments the reference count on the pointer.

IOleObjectImpl Overview | Class Members

See Also IOleObjectImpl::SetClientSite


IOleObjectImpl::GetClipboardData

HRESULT GetClipboardData( DWORD dwReserved, IDataObject** ppDataObject );

See IOleObject::GetClipboardData in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleObjectImpl::GetExtent

HRESULT GetExtent( DWORD dwDrawAspect, SIZEL* psizel );

See IOleObject::GetExtent in the Win32 SDK.

Remarks

Retrieves a running control's display size in HIMETRIC units (0.01 millimeter per unit). The size is stored in the control class data member m_sizeExtent.

IOleObjectImpl Overview | Class Members

See Also IOleObjectImpl::SetExtent


IOleObjectImpl::GetMiscStatus

HRESULT GetMiscStatus( DWORD dwAspect, DWORD* pdwStatus );

See IOleObject::GetMiscStatus in the Win32 SDK.

Remarks

Returns a pointer to registered status information for the control by calling OleRegGetMiscStatus. The status information includes behaviors supported by the control and presentation data. You can add status information to your project's .rgs file.

IOleObjectImpl Overview | Class Members

See Also OleRegGetMiscStatus, IOleObjectImpl::EnumVerbs, IOleObjectImpl::GetUserType


IOleObjectImpl::GetMoniker

HRESULT GetMoniker( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk );

See IOleObject::GetMoniker in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleObjectImpl::GetUserClassID

HRESULT GetUserClassID( CLSID* pClsid );

See IOleObject::GetUserClassID in the Win32 SDK.

Remarks

Returns the control's class identifier.

IOleObjectImpl Overview | Class Members

See Also IOleObjectImpl::GetUserType


IOleObjectImpl::GetUserType

HRESULT GetUserType( DWORD dwFormOfType, LPOLESTR* pszUserType );

See IOleObject::GetUserType in the Win32 SDK.

Remarks

Returns the control's user-type name by calling OleRegGetUserType. The user-type name is used for display in user-interfaces elements such as menus and dialog boxes. You can change the user-type name in your project's .rgs file.

IOleObjectImpl Overview | Class Members

See Also OleRegGetUserType, IOleObjectImpl::GetUserClassID, IOleObjectImpl::GetMiscStatus, IOleObjectImpl::EnumVerbs


IOleObjectImpl::InitFromData

HRESULT InitFromData( IDataObject* pDataObject, BOOL fCreation, DWORD dwReserved );

See IOleObject::InitFromData in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleObjectImpl::IsUpToDate

HRESULT IsUpToDate( );

See IOleObject::IsUpToDate in the Win32 SDK.

Remarks

Returns S_OK.


IOleObjectImpl::SetClientSite

HRESULT SetClientSite( IOleClientSite* pClientSite );

See IOleObject::SetClientSite in the Win32 SDK.

Remarks

Uses pClientSite as the pointer to the control's client site and stores pClientSite in the control class data member m_spClientSite. The method then returns S_OK.

IOleObjectImpl Overview | Class Members

See Also IOleObjectImpl::GetClientSite


IOleObjectImpl::SetColorScheme

HRESULT SetColorScheme( LOGPALETTE* pLogPal );

See IOleObject::SetColorScheme in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleObjectImpl::SetExtent

HRESULT SetExtent( DWORD dwDrawAspect, SIZEL* psizel );

See IOleObject::SetExtent in the Win32 SDK.

Remarks

If the control class data member m_bAutoSize is TRUE, this method returns E_FAIL because the control cannot be resized. Otherwise, SetExtent stores the value pointed to by psizel in the control class data member m_sizeExtent. This value is in HIMETRIC units (0.01 millimeter per unit).

If the control class data member m_bResizeNatural is TRUE, SetExtent also stores the value pointed to by psizel in the control class data member m_sizeNatural.

If the control class data member m_bRecomposeOnResize is TRUE, SetExtent calls SendOnDataChange and SendOnViewChange to notify all advisory sinks registered with the advise holder that the control size has changed.

IOleObjectImpl Overview | Class Members

See Also IOleObjectImpl::GetExtent, CComControl::SendOnDataChange, CComControl::SendOnViewChange


IOleObjectImpl::SetHostNames

HRESULT SetHostNames( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj );

See IOleObject::SetHostNames in the Win32 SDK.

Remarks

Returns S_OK.


IOleObjectImpl::SetMoniker

HRESULT SetMoniker( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk );

See IOleObject::SetMoniker in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IOleObjectImpl::Unadvise

HRESULT Unadvise( DWORD dwConnection );

See IOleObject::Unadvise in the Win32 SDK.

Remarks

Deletes the advisory connection stored in the control class's m_spOleAdviseHolder data member.

IOleObjectImpl Overview | Class Members

See Also CComControl::m_spOleAdviseHolder, IOleObjectImpl::Advise


IOleObjectImpl::Update

HRESULT Update( );

See IOleObject::Update in the Win32 SDK.

Remarks

Returns S_OK.


IPerPropertyBrowsingImpl

template< class T >
class IPerPropertyBrowsingImpl

Parameters

T

Your class, derived from IPerPropertyBrowsingImpl.

The IPerPropertyBrowsing interface allows a client to access the information in an object's property pages. Class IPerPropertyBrowsingImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

Note If you are using Microsoft Access as the container application, you must derive your class from IPerPropertyBrowsingImpl. Otherwise, Access will not load your control.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also IPropertyPageImpl, ISpecifyPropertyPagesImpl


IPerPropertyBrowsingImpl Class Members

IPerPropertyBrowsing Methods

GetDisplayString | Retrieves a string describing a given property.
GetPredefinedStrings | Retrieves an array of strings corresponding to the values that a given property can accept.
GetPredefinedValue | Retrieves a VARIANT containing the value of a property identified by a given DISPID. The DISPID is associated with the string name retrieved from GetPredefinedStrings. The ATL implementation returns E_NOTIMPL.
MapPropertyToPage | Retrieves the CLSID of the property page associated with a given property.

IPerPropertyBrowsingImpl Overview


IPerPropertyBrowsingImpl::GetDisplayString

HRESULT GetDisplayString( DISPID dispID, BSTR* pBstr );

See IPerPropertyBrowsing::GetDisplayString in the Win32 SDK.

Remarks

Retrieves a string describing a given property.


IPerPropertyBrowsingImpl::GetPredefinedStrings

HRESULT GetPredefinedStrings( DISPID dispID, CALPOLESTR* pCaStringsOut, CADWORD* pCaCookiesOut );

See IPerPropertyBrowsing::GetPredefinedStrings in the Win32 SDK.

Remarks

Fills each array with zero items. ATL's implementation of GetPredefinedValue returns E_NOTIMPL.

IPerPropertyBrowsingImpl Overview | Class Members

See Also CADWORD, CALPOLESTR


IPerPropertyBrowsingImpl::GetPredefinedValue

HRESULT GetPredefinedValue( DISPID dispID, DWORD dwCookie, VARIANT* pVarOut );

See IPerPropertyBrowsing::GetPredefinedValue in the Win32 SDK.

Remarks

Returns E_NOTIMPL. ATL's implementation of GetPredefinedStrings retrieves no corresponding strings.


IPerPropertyBrowsingImpl::MapPropertyToPage

HRESULT MapPropertyToPage( DISPID dispID, CLSID* pClsid );

See IPerPropertyBrowsing::MapPropertyToPage in the Win32 SDK.

Remarks

Retrieves the CLSID of the property page associated with the specified property. ATL uses the object's property map to obtain this information.

IPerPropertyBrowsingImpl Overview | Class Members

See Also BEGIN_PROP_MAP


IPersistPropertyBagImpl

template< class T >
class IPersistPropertyBagImpl

Parameters

T

Your class, derived from IPersistPropertyBagImpl.

The IPersistPropertyBag interface allows an object to save its properties to a client-supplied property bag. Class IPersistPropertyBagImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

IPersistPropertyBag works in conjunction with IPropertyBag and IErrorLog. These latter two interfaces must be implemented by the client. Through IPropertyBag, the client saves and loads the object's individual properties. Through IErrorLog, both the object and the client can report any errors encountered.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlcom.h>

Class Members

See Also BEGIN_PROP_MAP


IPersistPropertyBagImpl Class Members

IPersist Methods

GetClassID Retrieves the object's CLSID.

IPersistPropertyBag Methods

InitNew | Initializes a newly created object. The ATL implementation returns S_OK.
Load | Loads the object's properties from a client-supplied property bag.
Save | Saves the object's properties into a client-supplied property bag.

IPersistPropertyBagImpl Overview


IPersistPropertyBagImpl::GetClassID

HRESULT GetClassID( CLSID *pClassID );

See IPersist::GetClassID in the Win32 SDK.

Remarks

Retrieves the object's CLSID.


IPersistPropertyBagImpl::InitNew

HRESULT InitNew( );

See IPersistPropertyBag::InitNew in the Win32 SDK.

Remarks

Returns S_OK.


IPersistPropertyBagImpl::Load

HRESULT Load( LPPROPERTYBAG pPropBag, LPERRORLOG pErrorLog );

See IPersistPropertyBag::Load in the Win32 SDK.

Remarks

Loads the object's properties from a client-supplied property bag. ATL uses the object's property map to retrieve this information.

IPersistPropertyBagImpl Overview | Class Members

See Also BEGIN_PROP_MAP, IPersistPropertyBagImpl::Save, IPropertyBag, IErrorLog


IPersistPropertyBagImpl::Save

HRESULT Save( LPPROPERTYBAG pPropBag, BOOL fClearDirty, BOOL fSaveAllProperties );

See IPersistPropertyBag::Save in the Win32 SDK.

Remarks

Saves the object's properties into a client-supplied property bag. ATL uses the object's property map to store this information. By default, this method saves all properties, regardless of the value of fSaveAllProperties.

IPersistPropertyBagImpl Overview | Class Members

See Also BEGIN_PROP_MAP, IPersistPropertyBagImpl::Load, IPropertyBag


IPersistStorageImpl

template< class T >
class IPersistStorageImpl

Parameters

T

Your class, derived from IPersistStorageImpl.

The IPersistStorage interface allows a client to request that your object load and save its persistent data using a storage. Class IPersistStorageImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also Storages and Streams in the Win32 SDK


IPersistStorageImpl Class Members

IPersist Methods

GetClassID Retrieves the object's CLSID.

IPersistStorage Methods

HandsOffStorage | Instructs the object to release all storage objects and enter HandsOff mode. The ATL implementation returns S_OK.
InitNew | Initializes a new storage.
IsDirty | Checks whether the object's data has changed since it was last saved.
Load | Loads the object's properties from the specified storage.
Save | Saves the object's properties to the specified storage.
SaveCompleted | Notifies an object that it can return to Normal mode to write to its storage object. The ATL implementation returns S_OK.

IPersistStorageImpl Overview


IPersistStorageImpl::GetClassID

HRESULT GetClassID( CLSID *pClassID );

See IPersist::GetClassID in the Win32 SDK.

Remarks

Retrieves the object's CLSID.


IPersistStorageImpl::HandsOffStorage

HRESULT HandsOffStorage( );

See IPersistStorage::HandsOffStorage in the Win32 SDK.

Remarks

Returns S_OK.

IPersistStorageImpl Overview | Class Members

See Also IPersistStorageImpl::SaveCompleted, IPersistStorageImpl::Save


IPersistStorageImpl::InitNew

HRESULT InitNew( IStorage* pStorage );

See IPersistStorage:InitNew in the Win32 SDK.

Remarks

Initializes a new storage. The ATL implementation delegates to the IPersistStreamInit interface.

IPersistStorageImpl Overview | Class Members

See Also IStorage


IPersistStorageImpl::IsDirty

HRESULT IsDirty( );

See IPersistStorage:IsDirty in the Win32 SDK.

Remarks

Checks whether the object's data has changed since it was last saved. The ATL implementation delegates to the IPersistStreamInit interface.


IPersistStorageImpl::Load

HRESULT Load( IStorage* pStorage );

See IPersistStorage:Load in the Win32 SDK.

Remarks

Loads the object's properties. The ATL implementation delegates to the IPersistStreamInit interface. Load uses a stream named "Contents" to retrieve the object's data. The Save method originally creates this stream.

IPersistStorageImpl Overview | Class Members

See Also IStorage


IPersistStorageImpl::Save

HRESULT Save( IStorage* pStorage, BOOL fSameAsLoad );

See IPersistStorage:Save in the Win32 SDK.

Remarks

Saves the object's properties. The ATL implementation delegates to the IPersistStreamInit interface. When Save is first called, it creates a stream named "Contents" on the specified storage. This stream is then used in later calls to Save and in calls to Load.

IPersistStorageImpl Overview | Class Members

See Also IPersistStorageImpl::SaveCompleted, IStorage


IPersistStorageImpl::SaveCompleted

HRESULT SaveCompleted( IStorage* pStorage );

See IPersistStorage:SaveCompleted in the Win32 SDK.

Remarks

Returns S_OK.

IPersistStorageImpl Overview | Class Members

See Also IPersistStorageImpl::HandsOffStorage, IPersistStorageImpl::Save, IStorage


IPersistStreamInitImpl

template< class T >
class IPersistStreamInitImpl

Parameters

T

Your class, derived from IPersistStreamInitImpl.

The IPersistStreamInit interface allows a client to request that your object load and save its persistent data to a single stream. Class IPersistStreamInitImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlcom.h>

Class Members

See Also Storages and Streams in the Win32 SDK


IPersistStreamInitImpl Class Members

IPersist Methods

GetClassID Retrieves the object's CLSID.

IPersistStreamInit Methods

GetSizeMax | Retrieves the size of the stream needed to save the object's data. The ATL implementation returns E_NOTIMPL.
InitNew | Initializes a newly created object.
IsDirty | Checks whether the object's data has changed since it was last saved.
Load | Loads the object's properties from the specified stream.
Save | Saves the object's properties to the specified stream.

IPersistStreamInitImpl Overview


IPersistStreamInitImpl::GetClassID

HRESULT GetClassID( CLSID *pClassID );

See IPersist::GetClassID in the Win32 SDK.

Remarks

Retrieves the object's CLSID.


IPersistStreamInitImpl::GetSizeMax

HRESULT GetSizeMax( ULARGE_INTEGER FAR* pcbSize );

See IPersistStreamInit::GetSizeMax in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IPersistStreamInitImpl::InitNew

HRESULT InitNew( );

See IPersistStreamInit::InitNew in the Win32 SDK.

Remarks

Initializes a newly created object.


IPersistStreamInitImpl::IsDirty

HRESULT IsDirty( );

See IPersistStreamInit::IsDirty in the Win32 SDK.

Remarks

Checks whether the object's data has changed since it was last saved.


IPersistStreamInitImpl::Load

HRESULT Load( LPSTREAM pStm );

See IPersistStreamInit::Load in the Win32 SDK.

Remarks

Loads the object's properties from the specified stream. ATL uses the object's property map to retrieve this information.

IPersistStreamInitImpl Overview | Class Members

See Also BEGIN_PROP_MAP, IPersistStreamInitImpl::Save, IStream


IPersistStreamInitImpl::Save

HRESULT Save( LPSTREAM pStm, BOOL fClearDirty );

See IPersistStreamInit::Save in the Win32 SDK.

Remarks

Saves the object's properties to the specified stream. ATL uses the object's property map to store this information.

IPersistStreamInitImpl Overview | Class Members

See Also BEGIN_PROP_MAP, IPersistStreamInitImpl::Load, IStream


IPointerInactiveImpl

template< class T >
class IPointerInactiveImpl

Parameters

T

Your class, derived from IPointerInactiveImpl.

An inactive object is one that is simply loaded or running. Unlike an active object, an inactive object cannot receive Windows mouse and keyboard messages. Thus, inactive objects use fewer resources and are typically more efficient.

The IPointerInactive interface allows an object to support a minimal level of mouse interaction while remaining inactive. This functionality is particularly useful for controls.

Class IPointerInactiveImpl implements the IPointerInactive methods by simply returning E_NOTIMPL. However, it implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members


IPointerInactiveImpl Class Members

IPointerInactive Methods

GetActivationPolicy | Retrieves the current activation policy for the object. The ATL implementation returns E_NOTIMPL.
OnInactiveMouseMove | Notifies the object that the mouse pointer has moved over it, indicating the object can fire mouse events. The ATL implementation returns E_NOTIMPL.
OnInactiveSetCursor | Sets the mouse pointer for the inactive object. The ATL implementation returns E_NOTIMPL.

IPointerInactiveImpl Overview


IPointerInactiveImpl::GetActivationPolicy

HRESULT GetActivationPolicy( DWORD* pdwPolicy );

See IPointerInactive::GetActivationPolicy in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IPointerInactiveImpl::OnInactiveMouseMove

HRESULT OnInactiveMouseMove( LPCRECT pRectBounds, long x, long y, DWORD dwMouseMsg );

See IPointerInactive::OnInactiveMouseMove in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IPointerInactiveImpl::OnInactiveSetCursor

See IPointerInactive::OnInactiveSetCursor in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IPropertyNotifySinkCP

template< class T, class CDV = CComDynamicUnkArray >
class IPropertyNotifySinkCP :
public IConnectionPointImpl< T, &IID_IPropertyNotifySink, CDV >

Parameters

T

Your class, derived from IPropertyNotifySinkCP.

CDV

A class that manages the connections between a connection point and its sinks. The default value is CComDynamicUnkArray, which allows unlimited connections. You can also use CComUnkArray, which specifies a fixed number of connections.

The IPropertyNotifySink interface allows a sink object to receive notifications about property changes. Class IPropertyNotifySinkCP exposes this interface as an outgoing interface on a connectable object. The client must implement the IPropertyNotifySink methods on the sink.

Derive your class from IPropertyNotifySinkCP when you want to create a connection point that represents the IPropertyNotifySink interface.

For more information about using connection points in ATL, see the article Connection Points.

#include <atlctl.h>

Class Members

See Also IConnectionPointImpl, IConnectionPointContainerImpl


IPropertyNotifySinkCP Class Members

IPropertyNotifySinkCP inherits all methods through its base class, IConnectionPointImpl.

IPropertyNotifySinkCP Overview


IPropertyPageImpl

template< class T >
class IPropertyPageImpl

Parameters

T

Your class, derived from IPropertyPageImpl.

The IPropertyPage interface allows an object to manage a particular property page within a property sheet. Class IPropertyPageImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also IPropertyPage2Impl, IPerPropertyBrowsingImpl, ISpecifyPropertyPagesImpl


IPropertyPageImpl Class Members

Class Methods

IpropertyPageImpl | Constructor.
SetDirty | Flags the property page's state as changed or unchanged.

IPropertyPage Methods

Activate | Creates the dialog box window for the property page.
Apply | Applies current property page values to the underlying objects specified through SetObjects. The ATL implementation returns S_OK.
Deactivate | Destroys the window created with Activate.
GetPageInfo | Retrieves information about the property page.
Help | Invokes Windows help for the property page.
IsPageDirty | Indicates whether the property page has changed since it was activated.
Move | Positions and resizes the property page dialog box.
SetObjects | Provides an array of IUnknown pointers for the objects associated with the property page. These objects receive the current property page values through a call to Apply.
SetPageSite | Provides the property page with an IPropertyPageSite pointer, through which the property page communicates with the property frame.
Show | Makes the property page dialog box visible or invisible.
TranslateAccelerator | Processes a specified keystroke.

Data Members

m_bDirty | Specifies whether the property page's state has changed.
m_nObjects | Stores the number of objects associated with the property page.
m_dwHelpContext | Stores the context identifier for the help topic associated with the property page.
m_dwDocString | Stores the resource identifier associated with the text string describing the property page.
m_dwHelpFile | Stores the resource identifier associated with the name of the help file describing the property page.
m_dwTitle | Stores the resource identifier associated with the text string that appears in the tab for the property page.
m_pPageSite | Points to the IPropertyPageSite interface through which the property page communicates with the property frame.
m_ppUnk | Points to an array of IUnknown pointers to the objects associated with the property page.
m_size | Stores the height and width of the property page's dialog box, in pixels.

IPropertyPageImpl Overview


IPropertyPageImpl::Activate

HRESULT Activate( HWND hWndParent, LPCRECT pRect, BOOL bModal );

See IPropertyPage::Activate in the Win32 SDK.

Remarks

Creates the dialog box window for the property page. By default, the dialog box is always modeless, regardless of the value of the bModal parameter.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::Deactivate


IPropertyPageImpl::Apply

HRESULT Apply( );

See IPropertyPage::Apply in the Win32 SDK.

Remarks

Returns S_OK.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::SetObjects


IPropertyPageImpl::Deactivate

HRESULT Deactivate( );

See IPropertyPage::Deactivate in the Win32 SDK.

Remarks

Destroys the dialog box window created with Activate.


IPropertyPageImpl::GetPageInfo

HRESULT GetPageInfo( PROPPAGEINFO* pPageInfo );

See IPropertyPage::GetPageInfo in the Win32 SDK.

Remarks

Fills the pPageInfo structure with information contained in the data members. GetPageInfo loads the string resources associated with m_dwDocString, m_dwHelpFile, and m_dwTitle.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::m_dwHelpContext, IPropertyPageImpl::m_size, PROPPAGEINFO


IPropertyPageImpl::Help

HRESULT Help( PROPPAGEINFO* pPageInfo );

See IPropertyPage::Help in the Win32 SDK.

Remarks

Invokes Windows help for the property page.

IPropertyPageImpl Overview | Class Members

See Also PROPPAGEINFO


IPropertyPageImpl::IPropertyPageImpl

IPropertyPageImpl( );

Remarks

The constructor. Initializes all data members.


IPropertyPageImpl::IsPageDirty

HRESULT Help( PROPPAGEINFO* pPageInfo );

See IPropertyPage::Help in the Win32 SDK.

Remarks

Indicates whether the property page has changed since it was activated.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::SetDirty, IPropertyPageImpl::m_bDirty


IPropertyPageImpl::Move

HRESULT Move( LPCRECT pRect );

See IPropertyPage::Move in the Win32 SDK.

Remarks

Positions and resizes the property page dialog box.


IPropertyPageImpl::SetDirty

void SetDirty( BOOL bDirty );

Parameters

bDirty

[in] If TRUE, the property page's state is marked as changed. Otherwise, it is marked as unchanged.

Remarks

Flags the property page's state as changed or unchanged, depending on the value of bDirty. If necessary, SetDirty informs the frame that the property page has changed.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::IsPageDirty, IPropertyPageImpl::SetPageSite, IPropertyPageImpl::m_bDirty


IPropertyPageImpl::SetObjects

HRESULT SetObjects( ULONG nObjects, IUnknown** ppUnk );

See IPropertyPage::SetObjects in the Win32 SDK.

Remarks

Provides an array of IUnknown pointers for the objects associated with the property page.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::Apply, IPropertyPageImpl::m_nObjects, IPropertyPageImpl::m_ppUnk


IPropertyPageImpl::SetPageSite

HRESULT SetPageSite( IPropertyPageSite* pPageSite );

See IPropertyPage::SetPageSite in the Win32 SDK.

Remarks

Provides the property page with an IPropertyPageSite pointer, through which the property page communicates with the property frame.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::m_pPageSite, IPropertyPageSite


IPropertyPageImpl::Show

HRESULT Show( UINT nCmdShow );

See IPropertyPage::Show in the Win32 SDK.

Remarks

Makes the property page dialog box visible or invisible.


IPropertyPageImpl::TranslateAccelerator

HRESULT TranslateAccelerator( MSG* pMsg );

See IPropertyPage::TranslateAccelerator in the Win32 SDK.

Remarks

Processes the keystroke specified in pMsg.

IPropertyPageImpl Overview | Class Members

See Also MSG


IPropertyPageImpl::m_bDirty

BOOL m_bDirty;

Remarks

Specifies whether the property page's state has changed.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::IsPageDirty, IPropertyPageImpl::SetDirty


IPropertyPageImpl::m_nObjects

ULONG m_nObjects;

Remarks

Stores the number of objects associated with the property page.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::SetObjects


IPropertyPageImpl::m_dwHelpContext

DWORD m_dwHelpContext;

Remarks

Stores the context identifier for the help topic associated with the property page.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::GetPageInfo


IPropertyPageImpl::m_dwDocString

UINT m_dwDocString;

Remarks

Stores the resource identifier associated with the text string describing the property page.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::GetPageInfo


IPropertyPageImpl::m_dwHelpFile

UINT m_dwHelpFile;

Remarks

Stores the resource identifier associated with the name of the help file describing the property page.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::GetPageInfo


IPropertyPageImpl::m_dwTitle

UINT m_dwTitle;

Remarks

Stores the resource identifier associated with the text string that appears in the tab for the property page.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::GetPageInfo


IPropertyPageImpl::m_pPageSite

IPropertyPageSite* m_pPageSite;

Remarks

Points to the IPropertyPageSite interface through which the property page communicates with the property frame.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::SetPageSite


IPropertyPageImpl::m_ppUnk

IUnknown** m_ppUnk;

Remarks

Points to an array of IUnknown pointers to the objects associated with the property page.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::SetObjects


IPropertyPageImpl::m_size

SIZE m_size;

Remarks

Stores the height and width of the property page's dialog box, in pixels.

IPropertyPageImpl Overview | Class Members

See Also IPropertyPageImpl::GetPageInfo, SIZE


IPropertyPage2Impl

template< class T >
class IPropertyPage2Impl : public IPropertyPageImpl< T >

Parameters

T

Your class, derived from IPropertyPage2Impl.

The IPropertyPage2 interface extends IPropertyPage by adding the EditProperty method. This method allows a client to select a specific property in a property page object.

Class IPropertyPage2Impl simply returns E_NOTIMPL for IPropertyPage2::EditProperty. However, it inherits the default implementation of IPropertyPageImpl and implements IUnknown by sending information to the dump device in debug builds.

When you create a property page, your class is typically derived from IPropertyPageImpl. To provide the extra support of IPropertyPage2, modify your class definition and override the EditProperty method.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also IPerPropertyBrowsingImpl, ISpecifyPropertyPagesImpl


IPropertyPage2Impl Class Members

IPropertyPage2 Methods

EditProperty Specifies which property control will receive the focus when the property page is activated. The ATL implementation returns E_NOTIMPL.

IPropertyPage2Impl Overview


IPropertyPage2Impl::EditProperty

HRESULT EditProperty( DISPID dispID );

See IPropertyPage2::EditProperty in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IProvideClassInfo2Impl

template< const CLSID* pcoclsid, const IID* psrcid, const GUID* plibid, WORD wMajor = 1, WORD wMinor = 0, class tihclass = CComTypeInfoHolder >
class IProvideClassInfo2Impl : public IProvideClassInfo2

Parameters

pcoclsid

A pointer to the coclass' identifier.

psrcid

A pointer to the identifier for the coclass' default outgoing dispinterface.

plibid

A pointer to the identifier of the coclass' type library.

wMajor

The major version of the type library. The default value is 1.

wMinor

The minor version of the type library. The default value is 0.

tihclass

The class used to manage the coclass' type information. The default value is CComTypeInfoHolder.

The IProvideClassInfo2 interface extends IProvideClassInfo by adding the GetGUID method. This method allows a client to retrieve an object's outgoing interface IID for its default event set. Class IProvideClassInfo2Impl provides a default implementation of the IProvideClassInfo and IProvideClassInfo2 methods.

IProvideClassInfo2Impl contains a static member of type CComTypeInfoHolder that manages the type information for the coclass.

#include <atlcom.h>

Class Members


IProvideClassInfo2Impl Class Members

Class Methods

IProvideClassInfo2Impl Constructor.

IProvideClassInfo Methods

GetClassInfo Retrieves an ITypeInfo pointer to the coclass' type information.

IProvideClassInfo2 Methods

GetGUID Retrieves the GUID for the object's outgoing dispinterface.

Data Members

_tih Manages the type information for the coclass.

IProvideClassInfo2Impl Overview


IProvideClassInfo2Impl::GetClassInfo

HRESULT GetClassInfo( ITypeInfo** pptinfo );

See IProvideClassInfo::GetClassInfo in the Win32 SDK.

Remarks

Retrieves an ITypeInfo pointer to the coclass' type information.


IProvideClassInfo2Impl::GetGUID

HRESULT GetGUID( DWORD dwGuidKind, GUID* pGUID );

See IProvideClassInfo2::GetGUID in the Win32 SDK.

Remarks

Retrieves the GUID for the object's outgoing dispinterface.


IProvideClassInfo2Impl::IProvideClassInfo2Impl

IProvideClassInfo2Impl( );

Remarks

The constructor. Calls AddRef on the _tih member. The destructor calls Release.


IProvideClassInfo2Impl::_tih

static tihclass _tih;

Remarks

This static data member is an instance of the class template parameter, tihclass, which by default is CComTypeInfoHolder. _tih manages the type information for the coclass.


IQuickActivateImpl

template< class T >
class IQuickActivateImpl

Parameters

T

Your class, derived from IQuickActivateImpl.

The IQuickActivate interface helps containers avoid delays when loading controls by combining initialization in a single call. The QuickActivate method allows the container to pass a pointer to a QACONTAINER structure that holds pointers to all the interfaces the control needs. On return, the control passes back a pointer to a QACONTROL structure that holds pointers to its own interfaces, which are used by the container. Class IQuickActivateImpl provides a default implementation of IQuickActivate and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also CComControl


IQuickActivateImpl Class Members

IQuickActivate Methods

GetContentExtent | Gets the extent of a full rendering of the control within the container.
QuickActivate | Performs quick initialization of controls being loaded.
SetContentExtent | Informs the control how much display space the container has assigned to it.

IQuickActivateImpl Overview


IQuickActivateImpl::GetContentExtent

HRESULT GetContentExtent( LPSIZEL pSize );

See IQuickActivate::GetContentExtent in the Win32 SDK.

Remarks

Retrieves the current display size for a running control. The size is for a full rendering of the control and is specified in HIMETRIC units.

IQuickActivateImpl Overview | Class Members

See Also IQuickActivateImpl::SetContentExtent


IQuickActivateImpl::QuickActivate

HRESULT QuickActivate( QACONTAINER* pQACont, QACONTROL* pQACtrl );

See IQuickActivate::QuickActivate in the Win32 SDK.

Remarks

With the QuickActivate method, the container passes a pointer to a QACONTAINER structure. The structure contains pointers to interfaces needed by the control and the values of some ambient properties. Upon return, the control passes a pointer to a QACONTROL structure that contains pointers to its own interfaces that the container requires, and additional status information.


IQuickActivateImpl::SetContentExtent

HRESULT SetContentExtent( LPSIZEL pSize );

See IQuickActivate::SetContentExtent in the Win32 SDK.

Remarks

Informs a control of how much display space the container has assigned to it. The size is specified in HIMETRIC units.

IQuickActivateImpl Overview | Class Members

See Also IQuickActivateImpl::GetContentExtent


IRunnableObjectImpl

template< class T >
class IRunnableObjectImpl

Parameters

T

Your class, derived from IRunnableObjectImpl.

The IRunnableObject interface enables a container to determine if a control is running, force it to run, or lock it into the running state. Class IRunnableObjectImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also CComControl


IRunnableObjectImpl Class Members

IRunnable Object Methods

GetRunningClass | Returns the CLSID of the running control. The ATL implementation sets the CLSID to GUID_NULL and returns E_UNEXPECTED.
IsRunning | Determines if the control is running. The ATL implementation returns TRUE.
LockRunning | Locks the control into the running state. The ATL implementation returns S_OK.
Run | Forces the control to run. The ATL implementation returns S_OK.
SetContainedObject | Indicates that the control is embedded. The ATL implementation returns S_OK.

IRunnableObjectImpl Overview


IRunnableObjectImpl::GetRunningClass

HRESULT GetRunningClass( LPCLSID lpClsid );

See IRunnableObject::GetRunningClass in the Win32 SDK.

Remarks

The ATL implementation sets *lpClsid to GUID_NULL and returns E_UNEXPECTED.


IRunnableObjectImpl::IsRunning

virtual BOOL IsRunning( );

See IRunnableObject::IsRunning in the Win32 SDK.

Remarks

The ATL implementation returns TRUE.


IRunnableObjectImpl::LockRunning

HRESULT LockRunning( BOOL fLock, BOOL fLastUnlockCloses );

See IRunnableObject::LockRunning in the Win32 SDK.

Remarks

The ATL implementation returns S_OK.


IRunnableObjectImpl::Run

HRESULT Run( LPBINDCTX );

See IRunnableObject::Run in the Win32 SDK.

Remarks

The ATL implementation returns S_OK.


IRunnableObjectImpl::SetContainedObject

HRESULT SetContainedObject( BOOL fContained );

See IRunnableObject::SetContainedObject in the Win32 SDK.

Remarks

The ATL implementation returns S_OK.


IServiceProviderImpl

template <class T>
class ATL_NO_VTABLE IServiceProviderImpl : public IServiceProvider

Parameters

T

Your class, derived from IServiceProviderImpl.

The IServiceProvider interface locates a service specified by its GUID and returns the interface pointer for the requested interface on the service. Class IServiceProviderImpl provides a default implementation of this interface.

IServiceProviderImpl specifies one method: QueryService, which creates or accesses the specified service and returns an interface pointer to the specified interface for the service.

IServiceProviderImpl uses a service map, starting with BEGIN_SERVICE_MAP and ending with END_SERVICE_MAP.

The service map contains two entries: SERVICE_ENTRY, which indicates a specified service id (SID) supported by the object, and SERVICE_ENTRY_CHAIN, which calls QueryService to chain to another object.

#include <atlcom.h>

Class Members


Class Members

IServiceProviderImpl Class Members

Methods

QueryService Creates or accesses the specified service and returns an interface pointer to the specified interface for the service.

IServiceProviderImpl Overview


IServiceProviderImpl::QueryService

HRESULT QueryService( REFGUID guidService, REFIID riid, void** ppvObject );

See IServiceProvider::QueryService in the Platform SDK.

Remarks

Creates or accesses the specified service and returns an interface pointer to the specified interface for the service.

IServiceProviderImpl Overview | Class Members

See Also

BEGIN_SERVICE_MAP


ISpecifyPropertyPagesImpl

template< class T >
class ISpecifyPropertyPagesImpl

Parameters

T

Your class, derived from ISpecifyPropertyPagesImpl.

The ISpecifyPropertyPages interface allows a client to obtain a list of CLSIDs for the property pages supported by an object. Class ISpecifyPropertyPagesImpl provides a default implementation of this interface and implements IUnknown by sending information to the dump device in debug builds.

Note Do not expose the ISpecifyPropertyPages interface if your object does not support property pages.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also IPropertyPageImpl, IPerPropertyBrowsingImpl


ISpecifyPropertyPagesImpl Class Members

ISpecifyPropertyPages Methods

GetPages Fills a Counted Array of UUID values. Each UUID corresponds to the CLSID for one of the property pages that can be displayed in the object's property sheet.

ISpecifyPropertyPagesImpl Overview


ISpecifyPropertyPagesImpl::GetPages

HRESULT GetPages( CAUUID* pPages );

See ISpecifyPropertyPages::GetPages in the Win32 SDK.

Remarks

Fills the array in the CAUUID structure with the CLSIDs for the property pages that can be displayed in the object's property sheet. ATL uses the object's property map to retrieve each CLSID.

ISpecifyPropertyPagesImpl Overview | Class Members

See Also BEGIN_PROP_MAP


ISupportErrorInfoImpl

template< const IID* piid >
class ISupportErrorInfoImpl : public ISupportErrorInfo

Parameters

piid

A pointer to the IID of an interface that supports IErrorInfo.

The ISupportErrorInfo interface ensures that error information can be returned to the client. Objects that use IErrorInfo must implement ISupportErrorInfo.

Class ISupportErrorInfoImpl provides a default implementation of ISupportErrorInfo and can be used when only a single interface generates errors on an object. For example:

class CMyClass :
   public IDispatchImpl< ... >,
   public CComObjectRoot,
   public CComCoClass< ... >
   public ISupportErrorInfoImpl< &IID_IMyClass >
{
   ...
};

#include <atlcom.h>

Class Members


ISupportErrorInfoImpl Class Members

ISupportErrorInfo Methods

InterfaceSupportsErrorInfo Indicates whether an interface supports the IErrorInfo interface.

ISupportErrorInfoImpl Overview


ISupportErrorInfoImpl::InterfaceSupportsErrorInfo

HRESULT InterfaceSupportsErrorInfo( REFIID riid );

See ISupportErrorInfo::InterfaceSupportsErrorInfo in the Win32 SDK.

Remarks

Indicates whether the interface identified by riid supports the IErrorInfo interface.


IViewObjectExImpl

template< class T >
class IViewObjectExImpl

Parameters

T

Your class, derived from IViewObjectExImpl.

The IViewObject, IViewObject2, and IViewObjectEx interfaces enable a control to display itself directly, and to create and manage an advise sink to notify the container of changes in the control display. The IViewObjectEx interface provides support for extended control features such as flicker-free drawing, non-rectangular and transparent controls, and hit-testing (for example, how close a mouse click must be to be considered on the control). Class IViewObjectExImpl provides a default implementation of these interfaces and implements IUnknown by sending information to the dump device in debug builds.

Related Articles ATL Tutorial, Creating an ATL Project

#include <atlctl.h>

Class Members

See Also CComControl, ActiveX Controls Interfaces in the Win32 SDK


IViewObjectExImpl Class Members

IViewObject Methods

Draw | Draws a representation of the control onto a device context.
Freeze | Freezes the drawn representation of a control so that it won't change until an Unfreeze. The ATL implementation returns E_NOTIMPL.
GetAdvise | Returns information on the most recent SetAdvise.
GetColorSet | Returns the logical palette used by the control for drawing. The ATL implementation returns E_NOTIMPL.
SetAdvise | Sets up an advise sink to receive notifications of changes in the view of the control.
Unfreeze | Unfreezes the drawn representation of the control. The ATL implementation returns E_NOTIMPL.

IViewObject2 Methods

GetExtent Retrieves the size of the control from the cache.

IViewObjectEx Methods

GetNaturalExtent | Provides sizing hints from the container for the object to use as the user resizes it. The ATL implementation returns E_NOTIMPL.
GetRect | Returns a rectangle describing a requested drawing aspect. The ATL implementation returns E_NOTIMPL.
GetViewStatus | Returns information about the opacity of the object, and what drawing aspects are supported.
QueryHitPoint | Indicates whether a point is within a given drawing aspect of an object.
QueryHitRect | Indicates whether any point in a rectangle is within a given drawing aspect of an object.

IViewObjectExImpl Overview


IViewObjectExImpl::Draw

HRESULT Draw( DWORD dwDrawAspect, LONG lindex, void* pvAspect, DVTARGETDEVICE* ptd, HDC hicTargetDev, LPCRECTL prcBounds, LPCRECTL prcWBounds, BOOL(_stdcall * pfnContinue) (DWORD dwContinue), DWORD dwContinue );

See IViewObject::Draw in the Win32 SDK.

Remarks

This method calls CComControl::OnDrawAdvanced which in turn calls your control class's OnDraw method. An OnDraw method is automatically added to your control class when you create your control with the ATL Object Wizard. The Wizard's default OnDraw draws a rectangle with the label "ATL 2.0".

IViewObjectExImpl Overview | Class Members

See Also CComControl::OnDrawAdvanced, CComControl::OnDraw


IViewObjectExImpl::Freeze

HRESULT Freeze( DWORD dwAspect, LONG lindex, void* pvAspect, DWORD* pdwFreeze );

See IViewObject::Freeze in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IViewObjectExImpl::GetAdvise

HRESULT GetAdvise( DWORD* pAspects, DWORD* pAdvf, IAdviseSink** ppAdvSink );

See IViewObject::GetAdvise in the Win32 SDK.

Remarks

Retrieves an existing advisory sink connection on the control, if there is one. The advisory sink is stored in the control class data member m_spAdviseSink.

IViewObjectExImpl Overview | Class Members

See Also IViewObjectExImpl::SetAdvise


IViewObjectExImpl::GetColorSet

HRESULT GetColorSet( DWORD dwAspect, LONG lindex, void* pvAspect, DVTARGETDEVICE* ptd, HDC hicTargetDevice, LOGPALETTE** ppColorSet );

See IViewObject::GetColorSet in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IViewObjectExImpl::GetExtent

HRESULT GetExtent( DWORD dwDrawAspect, LONG lindex, DVTARGETDEVICE* ptd, LPSIZEL* lpsizel );

See IViewObject2::GetExtent in the Win32 SDK.

Remarks

Retrieves the control's display size in HIMETRIC units (0.01 millimeter per unit) from the control class data member m_sizeExtent.


IViewObjectExImpl::GetNaturalExtent

HRESULT GetNaturalExtent( DWORD dwAspect, LONG lindex, DVTARGETDEVICE* ptd, HDC hicTargetDevice, DVEXTENTINFO* pExtentInfo, LPSIZEL psizel );

See IViewObjectEx::GetNaturalExtent in the Win32 SDK.

Remarks

If dwAspect is DVASPECT_CONTENT and pExtentInfo->dwExtentMode is DVEXTENT_CONTENT, sets *psizel to the control class's data member m_sizeNatural.


IViewObjectExImpl::GetRect

HRESULT GetRect( DWORD dwAspect, LPRECTL pRect );

See IViewObjectEx::GetRect in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


IViewObjectExImpl::GetViewStatus

HRESULT GetViewStatus( DWORD* pdwStatus );

See IViewObjectEx::GetViewStatus in the Win32 SDK.

Remarks

By default, ATL sets pdwStatus to indicate that the control supports VIEWSTATUS_OPAQUE (possible values are in the VIEWSTATUS enumeration).


IViewObjectExImpl::QueryHitPoint

HRESULT QueryHitPoint( DWORD dwAspect, LPCRECT pRectBounds, POINT ptlLoc, LONG lCloseHit, DWORD* pHitResult );

See IViewObjectEx::QueryHitPoint in the Win32 SDK.

Remarks

Checks if the specified point is in the specified rectangle and returns a HITRESULT value in pHitResult. The value can be either HITRESULT_HIT or HITRESULT_OUTSIDE.

If dwAspect equals DVASPECT_CONTENT, the method returns S_OK. Otherwise, the method returns E_FAIL.

IViewObjectExImpl Overview | Class Members

See Also IViewObjectExImpl::QueryHitRect


IViewObjectExImpl::QueryHitRect

HRESULT QueryHitRect( DWORD dwAspect, LPCRECT pRectBounds, LPRECT prcLoc, LONG lCloseHit, DWORD* pHitResult );

See IViewObjectEx::QueryHitRect in the Win32 SDK.

Remarks

Checks whether the control's display rectangle overlaps any point in the specified location rectangle and returns a HITRESULT value in pHitResult. The value can be either HITRESULT_HIT or HITRESULT_OUTSIDE.

If dwAspect equals DVASPECT_CONTENT, the method returns S_OK. Otherwise, the method returns E_FAIL.

IViewObjectExImpl Overview | Class Members

See Also IViewObjectExImpl::QueryHitPoint


IViewObjectExImpl::SetAdvise

HRESULT SetAdvise( DWORD aspects, DWORD advf, IAdviseSink* pAdvSink );

See IViewObject::SetAdvise in the Win32 SDK.

Remarks

Sets up a connection between the control and an advise sink so that the sink can be notified about changes in the control's view. The pointer to the IAdviseSink interface on the advise sink is stored in the control class data member m_spAdviseSink.

IViewObjectExImpl Overview | Class Members

See Also IViewObjectExImpl::GetAdvise


IViewObjectExImpl::Unfreeze

HRESULT Unfreeze( DWORD dwFreeze );

See IViewObject::Unfreeze in the Win32 SDK.

Remarks

Returns E_NOTIMPL.


ATL Macros and Global Functions

The ATL macros and global functions offer functionality in the following categories:

Aggregation and Class Factory Macros
Category Macros
COM Map Macros and Global Functions
Composite Control Macros and Global Functions
Connection Point Macros and Global Functions
Debugging and Error Reporting Macros and Global Functions
Device Context Global Functions
Event Handling Global Functions
Marshaling Global Functions
Message Map Macros
Snap-In Macros
Object Map Macros
Pixel/HIMETRIC Conversion Global Functions
Property Map Macros
Registry Macros
Service Map Macros
Stock Property Macros
String Conversion Macros
Window Class Macros
Windows Messages

Aggregation and Class Factory Macros

DECLARE_AGGREGATABLE | Declares that your object can be aggregated (the default).
DECLARE_CLASSFACTORY | Declares the class factory to be CComClassFactory, the ATL default class factory.
DECLARE_CLASSFACTORY_EX | Declares your class factory object to be the class factory.
DECLARE_CLASSFACTORY2 | Declares CComClassFactory2 to be the class factory.
DECLARE_CLASSFACTORY_AUTO_THREAD | Declares CComClassFactoryAutoThread to be the class factory.
DECLARE_CLASSFACTORY_SINGLETON | Declares CComClassFactorySingleton to be the class factory.
DECLARE_GET_CONTROLLING_UNKNOWN | Declares a virtual GetControllingUnknown function.
DECLARE_NOT_AGGREGATABLE | Declares that your object cannot be aggregated.
DECLARE_ONLY_AGGREGATABLE | Declares that your object must be aggregated.
DECLARE_POLY_AGGREGATABLE | Checks the value of the outer unknown and declares your object aggregatable or not aggregatable, as appropriate.
DECLARE_PROTECT_FINAL_CONSTRUCT | Protects the outer object from deletion during construction of an inner object.
DECLARE_VIEW_STATUS | Specifies the VIEWSTATUS flags to the container.

Category Macros

BEGIN_CATEGORY_MAP | Marks the beginning of the category map.
END_CATEGORY_MAP | Marks the end of the category map.
IMPLEMENTED_CATEGORY | Indicates categories that are implemented by the COM object.
REQUIRED_CATEGORY | Indicates categories that are required of the container by the COM object.

COM Map Macros and Global Functions

AtlInternalQueryInterface | Delegates to the IUnknown of a nonaggregated object.
BEGIN_COM_MAP | Marks the beginning of the COM interface map entries.
COM_INTERFACE_ENTRY | Enters interfaces into the COM interface map.
END_COM_MAP | Marks the end of the COM interface map entries.
InlineIsEqualIUnknown | Generates efficient code for IUnknown.

Composite Control Macros and Global Functions

AtlAxDialogBox | Creates a modal dialog box from a dialog template provided by the user. The dialog may contain ActiveX controls.
AtlAxCreateDialog | Creates a modeless dialog box from a dialog template provided by the user. The resulting dialog box can contain ActiveX controls.
AtlAxCreateControl | Creates an ActiveX control, initializes it, and hosts it in the specified window.
AtlAxCreateControlEx | Creates an ActiveX control, initializes it, and hosts it in the specified window.
AtlAxAttachControl | Attaches a previously created control to the specified window.
AtlAxGetHost | Used to obtain a direct interface pointer to the container for a specified window (if any), given its handle.
AtlAxGetControl | Used to obtain a direct interface pointer to the control contained inside a specified window (if any), given its handle.
AtlSetChildSite | Initializes the IUnknown of the child site.
AtlAxWinInit | Initializes the hosting code for AxWin objects.
BEGIN_SINK_MAP | Marks the beginning of the event sink map for the composite control.
END_SINK_MAP | Marks the end of the event sink map for the composite control.
SINK_ENTRY | Entry to the event sink map.
SINK_ENTRY_EX | Entry to the event sink map with an additional parameter.

Connection Point Macros and Global Functions

AtlAdvise | Creates a connection between an object's connection point and a client's sink.
AtlUnadvise | Terminates the connection established through AtlAdvise.
AtlAdviseSinkMap | Advises or unadvises entries in an event sink map.
BEGIN_CONNECTION_POINT_MAP | Marks the beginning of the connection point map entries.
CONNECTION_POINT_ENTRY | Enters connection points into the map.
END_CONNECTION_POINT_MAP | Marks the end of the connection point map entries.

Snap-In Object Macros

BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP | Marks the beginning of the snap-in extension data class map for a Snap-In object.
BEGIN_SNAPINTOOLBARID_MAP | Marks the beginning of the toolbar map for a Snap-In object.
END_EXTENSION_SNAPIN_NODEINFO_MAP | Marks the end of the snap-in extension data class map for a Snap-In object.
END_SNAPINTOOLBARID_MAP | Marks the end of the toolbar map for a Snap-In object.
EXTENSION_SNAPIN_DATACLASS | Creates a data member for the data class of the snap-in extension.
EXTENSION_SNAPIN_NODEINFO_ENTRY | Enters a snap-in extension data class into the snap-in extension data class map of the Snap-In object.
SNAPINMENUID | Declares the ID of the context menu used by the Snap-In object.
SNAPINTOOLBARID_ENTRY | Enters a toolbar into the toolbar map of the Snap-In object.

Debugging and Error Reporting Macros and Global Functions

AtlReportError | Sets up IErrorInfo to provide error details to a client.
AtlTrace | Global function that sends a formatted message and/or variable values to the dump device.
ATLTRACE | Sends a formatted message and/or variable values to the dump device.
ATLTRACENOTIMPL | Sends a message to the dump device that the specified function is not implemented.
atlTraceFlags | Identifies the flags used in ATLTRACE2.
ATLTRACE2 | Reports warnings to an output device, such as the debugger window, according to the indicated flags and levels.

Device Context Global Functions

AtlCreateTargetDC Creates a device context.

Event Handling Global Functions

AtlWaitWithMessageLoop Waits for an object to be signaled, meanwhile dispatching window messages as needed.

Marshaling Global Functions

AtlFreeMarshalStream | Releases the marshal data and the IStream pointer.
AtlMarshalPtrInProc | Creates a new stream object and marshals the specified interface pointer.
AtlUnmarshalPtr | Converts a stream's marshaling data into an interface pointer.

Message Map Macros

BEGIN_MSG_MAP | Marks the beginning of the default message map.
ALT_MSG_MAP | Marks the beginning of an alternate message map.
DECLARE_EMPTY_MSG_MAP | Implements an empty message map.
MESSAGE_HANDLER | Maps a Windows message to a handler function.
MESSAGE_RANGE_HANDLER | Maps a contiguous range of Windows messages to a handler function.
COMMAND_HANDLER | Maps a WM_COMMAND message to a handler function, based on the notification code and the identifier of the menu item, control, or accelerator.
COMMAND_ID_HANDLER | Maps a WM_COMMAND message to a handler function, based on the identifier of the menu item, control, or accelerator.
COMMAND_CODE_HANDLER | Maps a WM_COMMAND message to a handler function, based on the notification code.
COMMAND_RANGE_HANDLER | Maps a contiguous range of WM_COMMAND messages to a handler function.
NOTIFY_HANDLER | Maps a WM_NOTIFY message to a handler function, based on the notification code and the control identifier.
NOTIFY_ID_HANDLER | Maps a WM_NOTIFY message to a handler function, based on the control identifier.
NOTIFY_CODE_HANDLER | Maps a WM_NOTIFY message to a handler function, based on the notification code.
NOTIFY_RANGE_HANDLER | Maps a contiguous range of WM_NOTIFY messages to a handler function.
REFLECT_NOTIFICATIONS | Reflects notification messages back to the window that sent them.
DEFAULT_REFLECTION_HANDLER | Provides a default handler for reflected messages that are not handled otherwise.
CHAIN_MSG_MAP | Chains to the default message map in the base class.
CHAIN_MSG_MAP_MEMBER | Chains to the default message map in a data member of the class.
CHAIN_MSG_MAP_ALT | Chains to an alternate message map in the base class.
CHAIN_MSG_MAP_ALT_MEMBER | Chains to an alternate message map in a data member of the class.
CHAIN_MSG_MAP_DYNAMIC | Chains to the message map in another class at run time.
END_MSG_MAP | Marks the end of a message map.

Object Map Macros

BEGIN_OBJECT_MAP | Marks the beginning of the ATL object map and initializes the array of object descriptions.
OBJECT_ENTRY | Enters an ATL object into the object map, updates the registry, and creates an instance of the object.
OBJECT_ENTRY_NON_CREATEABLE | Allows you to specify that the object should be registered and initialized, but it should not be createable via CoCreateInstance.
END_OBJECT_MAP | Marks the end of the ATL object map.
DECLARE_OBJECT_DESCRIPTION | Allows you to specify a class object's text description, which will be entered into the object map.

Pixel/HIMETRIC Conversion Global Functions

AtlHiMetricToPixel | Converts HIMETRIC units (each unit is 0.01 millimeter) to pixels.
AtlPixelToHiMetric | Converts pixels to HIMETRIC units (each unit is 0.01 millimeter).

Property Map Macros

BEGIN_PROP_MAP | Marks the beginning of the ATL property map.
PROP_DATA_ENTRY | Indicates the extent, or dimensions, of an ActiveX control.
PROP_ENTRY | Enters a property description, property DISPID, and property page CLSID into the property map.
PROP_ENTRY_EX | Enters a property description, property DISPID, property page CLSID, and IDispatch IID into the property map.
PROP_PAGE | Enters a property page CLSID into the property map.
END_PROP_MAP | Marks the end of the ATL property map.

Registry Macros

DECLARE_NO_REGISTRY | Avoids default ATL registration.
DECLARE_REGISTRY | Enters or removes the main object's entry in the system registry.
DECLARE_REGISTRY_RESOURCE | Finds the named resource and runs the registry script within it.
DECLARE_REGISTRY_RESOURCEID | Finds the resource identified by an ID number and runs the registry script within it.

Service Map Macros

BEGIN_SERVICE_MAP | Marks the beginning of an ATL service map.
END_SERVICE_MAP | Marks the end of an ATL service map.
SERVICE_ENTRY | Indicates that the object supports a specific service ID.
SERVICE_ENTRY_CHAIN | Instructs IServiceProviderImpl::QueryService to chain to the specified object.

Stock Property Macros

IMPLEMENT_BOOL_STOCKPROP | Implements a boolean stock property for an ATL object.
IMPLEMENT_BSTR_STOCKPROP | Implements a text stock property for an ATL object.
IMPLEMENT_STOCKPROP | Implements a stock property for an ATL object.

String Conversion Macros

String Conversion Macros | Set of macros that convert between string types.
DEVMODE and TEXTMETRIC String Conversion Macros | Set of macros that convert the strings within DEVMODE and TEXTMETRIC structures.

Window Class Macros

DECLARE_WND_CLASS | Allows you to specify the name of a new window class.
DECLARE_WND_SUPERCLASS | Allows you to specify the name of an existing window class on which a new window class will be based.
DECLARE_WND_CLASS_EX | Allows you to specify the parameters of a class.

Window Class Macros

WM_FORWARDMSG Use to forward a message received by a window to another window for processing.


ALT_MSG_MAP

ALT_MSG_MAP( msgMapID )

Parameters

msgMapID

[in] The message map identifier.

Remarks

Marks the beginning of an alternate message map. ATL identifies each message map by a number. The default message map (declared with the BEGIN_MSG_MAP macro) is identified by 0. An alternate message map is identified by msgMapID.

Message maps are used to process messages sent to a window. For example, CContainedWindow allows you to specify the identifier of a message map in the containing object. CContainedWindow::WindowProc then uses this message map to direct the contained window's messages either to the appropriate handler function or to another message map. For a list of macros that declare handler functions, see BEGIN_MSG_MAP.

Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps. The following example shows the default message map and one alternate message map, each containing one handler function:

BEGIN_MSG_MAP(CMyClass)
   MESSAGE_HANDLER(WM_PAINT, OnPaint)
ALT_MSG_MAP(1)
   MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
END_MSG_MAP()

The next example shows two alternate message maps. The default message map is empty.

BEGIN_MSG_MAP(CMyClass)
ALT_MSG_MAP(1)
   MESSAGE_HANDLER(WM_PAINT, OnPaint)
   MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
ALT_MSG_MAP(2)
   MESSAGE_HANDLER(WM_CREATE, OnCreate)
END_MSG_MAP()

The END_MSG_MAP macro marks the end of the message map. Note that there is always exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

MESSAGE_HANDLER, CMessageMap, CDynamicChain


AtlAdvise

HRESULT AtlAdvise( IUnknown* pUnkCP, IUnknown* pUnk, const IID& iid, LPDWORD pdw );

Return Value

A standard HRESULT value.

Parameters

pUnkCP

[in] A pointer to the IUnknown of the object the client wants to connect with.

pUnk

[in] A pointer to the client's IUnknown.

iid

[in] The GUID of the connection point. Typically, this is the same as the outgoing interface managed by the connection point.

pdw

[out] A pointer to the cookie that uniquely identifies the connection.

Remarks

Creates a connection between an object's connection point and a client's sink. The sink implements the outgoing interface supported by the connection point. The client uses the pdw cookie to remove the connection by passing it to AtlUnadvise.

ATL Macros and Global Functions


AtlAdviseSinkMap

HRESULT AtlAdviseSinkMap( T* pT, bool bAdvise );

Return Value

A standard HRESULT value.

Parameters

pT

[in] A pointer to the object containing the sink map.

bAdvise

[in] TRUE if all sink entries are to be unadvised; otherwise FALSE.

Remarks

Call this function to advise or unadvise all entries in the object's sink event map.

ATL Macros and Global Functions


AtlAxAttachControl

ATLAPI AtlAxAttachControl( IUnknown* pControl, HWND hWnd );

Parameters

pControl

[in] A pointer to the IUnknown of the control.

hWnd

[in] Handle to the window that will host the control.

Remarks

Attaches a previously created control to the specified window.

Note The control object being attached must be correctly initialized before AtlAxAttachControl.

Use AtlAxCreateControlEx and AtlAxCreateControl to simultaneously create and attach a control.

ATL Macros and Global Functions

See Also

Composite Control Fundamentals


AtlAxCreateControl

ATLAPI AtlAxCreateControl( LPCOLESTR lpszName, HWND hWnd, IStream* pStream, IUnknown** ppUnkContainer );

Parameters

lpszName

A pointer to a string to be passed to the control. Must be formatted in one of the following ways:

  • A ProgID such as "MSCAL.Calendar.7"

  • A CLSID such as "{8E27C92B-1264-101C-8A2F-040224009C02}"

  • A URL such as "http://www.microsoft.com"

  • A reference to an Active document such as "file://\\Documents\MyDoc.doc"

  • A fragment of HTML such as "MSHTML:<HTML><BODY>This is a line of text</BODY></HTML>"

    Note "MSHTML:" must precede the HTML fragment so that it is designated as being an MSHTML stream.

hWnd

[in] Handle to the window that the control will be attached to.

pStream

[in] A pointer to a stream that is used to initialize the properties of the control. Can be NULL.

ppUnkContainer

[out] The address of a pointer that will receive the IUnknown of the container. Can be NULL.

Remarks

Creates an ActiveX control, initializes it, and hosts it in the specified window.

This global function gives you the same result as calling AtlAxCreateControlEx( lpszName, hWnd, pStream, NULL, NULL, NULL, NULL );.

ATL Macros and Global Functions

See Also

Composite Control Fundamentals


AtlAxCreateControlEx

ATLAPI AtlAxCreateControlEx(LPCOLESTR lpszName, HWND hWnd, IStream* pStream, IUnknown** ppUnkContainer, IUnknown** ppUnkControl, REFIID iidSink=IID_NULL, IUnknown* punkSink=NULL);

Parameters

lpszName

A pointer to a string to be passed to the control. Must be formatted in one of the following ways:

  • A ProgID such as "MSCAL.Calendar.7"

  • A CLSID such as "{8E27C92B-1264-101C-8A2F-040224009C02}"

  • A URL such as "http://www.microsoft.com"

  • A reference to an Active document such as "file://\\Documents\MyDoc.doc"

  • A fragment of HTML such as "MSHTML:<HTML><BODY>This is a line of text</BODY></HTML>"

    Note "MSHTML:" must precede the HTML fragment so that it is designated as being an MSHTML stream.

hWnd

[in] Handle to the window that the control will be attached to.

pStream

[in] A pointer to a stream that is used to initialize the properties of the control. Can be NULL.

ppUnkContainer

[out] The address of a pointer that will receive the IUnknown of the container. Can be NULL.

ppUnkControl

[out] The address of a pointer that will receive the IUnknown of the created control. Can be NULL.

iidSink

The interface identifier of an outgoing interface on the contained object.

punkSink

A pointer to the IUnknown interface of the sink object to be connected to the connection point specified by iidSink on the contained object after the contained object has been successfully created.

Remarks

Creates an ActiveX control, initializes it, and hosts it in the specified window, similar to AtlAxCreateControl.

ATL Macros and Global Functions

See Also

Composite Control Fundamentals


AtlAxCreateDialog

ATLAPI_(HWND) AtlAxCreateDialog( HINSTANCE hInstance, LPCWSTR lpTemplateName, HWND hWndParent, DLGPROC lpDialogProc, LPARAM dwInitParam );

Parameters

hInstance

[in] Identifies an instance of the module whose executable file contains the dialog box template.

lpTemplateName

[in] Identifies the dialog box template. This parameter is either the pointer to a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.

hWndParent

[in] Identifies the window that owns the dialog box.

lpDialogProc

[in] Points to the dialog box procedure.

dwInitParam

[in] Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

Remarks

Creates a modeless dialog box from a dialog template provided by the user. The resulting dialog box can contain ActiveX controls.

See CreateDialog and CreateDialogParam in the Platform SDK.

ATL Macros and Global Functions

See Also

Composite Control Fundamentals


AtlAxDialogBox

ATLAPI_(int) AtlAxDialogBox( HINSTANCE hInstance, LPCWSTR lpTemplateName, HWND hWndParent, DLGPROC lpDialogProc, LPARAM dwInitParam );

Parameters

hInstance

[in] Identifies an instance of the module whose executable file contains the dialog box template.

lpTemplateName

[in] Identifies the dialog box template. This parameter is either the pointer to a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.

hWndParent

[in] Identifies the window that owns the dialog box.

lpDialogProc

[in] Points to the dialog box procedure.

dwInitParam

[in] Specifies the value to pass to the dialog box in the lParam parameter of the WM_INITDIALOG message.

Remarks

Creates a modal dialog box from a dialog template provided by the user. The dialog can contain ActiveX controls.

See DialogBox and CreateDialogParam in the Platform SDK.

ATL Macros and Global Functions

See Also

Composite Control Fundamentals


AtlAxGetControl

ATLAPI AtlAxGetControl( HWND h, IUnknown** pp );

Parameters

h

[in] A handle to the window that is hosting the control.

pp

[out] The IUnknown of the control being hosted.

Remarks

Obtains a direct interface pointer to the control contained inside a specified window given its handle.

ATL Macros and Global Functions

See Also

Composite Control Fundamentals


AtlAxGetHost

ATLAPI AtlAxGetHost( HWND h, IUnknown** pp );

Parameters

h

[in] A handle to the window that is hosting the control.

pp

[out] The IUnknown of the container of the control.

Remarks

Obtains a direct interface pointer to the container for a specified window (if any), given its handle.

ATL Macros and Global Functions

See Also

Composite Control Fundamentals


AtlAxWinInit

ATLAPI_(BOOL) AtlAxWinInit( );

Return Value

TRUE, if the registration of the control was successful; otherwise FALSE.

Remarks

Initializes the AxWin hosting code.

You must call this global function first by any process that uses the containment functionality.

This global function registers the window class as ATLAXWin so it can be used in calls to CreateWindow or CreateWindowEx, as described in the Platform SDK.

ATL Macros and Global Functions

See Also

Composite Control Fundamentals


AtlCreateTargetDC

HDC AtlCreateTargetDC( HDC hdc, DVTARGETDEVICE* ptd );

Return Value

Returns the handle to a device context for the device specified in the DVTARGETDEVICE. If no device is specified, returns the handle to the default display device.

Parameters

hdc

[in] The existing handle of a device context, or NULL.

ptd

[in] A pointer to the DVTARGETDEVICE structure that contains information about the target device.

Remarks

Creates a device context for the device specified in the DVTARGETDEVICE structure. If the structure is NULL and hdc is NULL, creates a device context for the default display device.

If hdc is not NULL and ptd is NULL, the function returns the existing hdc.

ATL Macros and Global Functions


AtlFreeMarshalStream

void AtlFreeMarshalStream( IStream* pStream );

Parameters

pStream

[in] A pointer to the IStream interface on the stream used for marshaling.

Remarks

Releases the marshal data in the stream, then releases the stream pointer.

ATL Macros and Global Functions

See Also

AtlMarshalPtrInProc


AtlHiMetricToPixel

extern void AtlHiMetricToPixel( const SIZEL* lpSizeInHiMetric, LPSIZEL lpSizeInPix );

Parameters

lpSizeInHiMetric

[in] Pointer to the size of the object in HIMETRIC units.

lpSizeInPix

[out] Pointer to where the object's size in pixels is to be returned.

Remarks

Converts an object's size in HIMETRIC units (each unit is 0.01 millimeter) to a size in pixels on the screen device.

ATL Macros and Global Functions

See Also

AtlPixelToHiMetric


AtlInternalQueryInterface

HRESULT AtlInternalQueryInterface( void* pThis, const _ATL_INTMAP_ENTRY* pEntries, REFIID iid, void** ppvObject );

Return Value

One of the standard HRESULT values.

Parameters

pThis

[in] A pointer to the object that contains the COM map of interfaces exposed to QueryInterface.

pEntries

[in] An array of _ATL_INTMAP_ENTRY structures that access a map of available interfaces.

iid

[in] The GUID of the interface being requested.

ppvObject

[out] A pointer to the interface pointer specified in iid, or NULL if the interface is not found.

Remarks

Retrieves a pointer to the requested interface.

AtlInternalQueryInterface only handles interfaces in the COM map table. If your object is aggregated, AtlInternalQueryInterface does not delegate to the outer unknown. You can enter interfaces into the COM map table with the macro COM_INTERFACE_ENTRY or one of its variants.

ATL Macros and Global Functions

See Also

CComObjectRootEx::InternalAddRef, CComObjectRootEx::InternalRelease


AtlMarshalPtrInProc

HRESULT AtlMarshalPtrInProc( IUnknown* pUnk, const IID& iid, IStream** ppStream );

Return Value

A standard HRESULT value.

Parameters

pUnk

[in] A pointer to the interface to be marshaled.

iid

[in] The GUID of the interface being marshaled.

ppStream

[out] A pointer to the IStream interface on the new stream object used for marshaling.

Remarks

Creates a new stream object, writes the CLSID of the proxy to the stream, and marshals the specified interface pointer by writing the data needed to initialize the proxy into the stream. The MSHLFLAGS_TABLESTRONG flag is set so the pointer can be marshaled to multiple streams. The pointer can also be unmarshaled multiple times.

If marshaling fails, the stream pointer is released.

AtlMarshalPtrInProc can only be used on a pointer to an in-process object.

ATL Macros and Global Functions

See Also

AtlUnmarshalPtr, AtlFreeMarshalStream, MSHLFLAGS in the Win32 SDK


AtlPixelToHiMetric

extern void AtlPixelToHiMetric( const SIZEL* lpSizeInPix, LPSIZEL lpSizeInHiMetric );

Parameters

lpSizeInPix

[in] Pointer to the object's size in pixels.

lpSizeInHiMetric

[out] Pointer to where the object's size in HIMETRIC units is to be returned.

Remarks

Converts an object's size in pixels on the screen device to a size in HIMETRIC units (each unit is 0.01 millimeter).

ATL Macros and Global Functions

See Also

AtlHiMetricToPixel


AtlReportError

HRESULT WINAPI AtlReportError( const CLSID& clsid, LPCOLESTR lpszDesc, const IID& iid = GUID_NULL, HRESULT hRes = 0 );

HRESULT WINAPI AtlReportError( const CLSID& clsid, LPCOLESTR lpszDesc, DWORD dwHelpID, LPCOLESTR lpszHelpFile, const IID& iid = GUID_NULL, HRESULT hRes = 0 );

HRESULT WINAPI AtlReportError( const CLSID& clsid, LPCSTR lpszDesc, const IID& iid = GUID_NULL, HRESULT hRes = 0 );

HRESULT WINAPI AtlReportError( const CLSID& clsid, LPCSTR lpszDesc, DWORD dwHelpID, LPCSTR lpszHelpFile, const IID& iid = GUID_NULL, HRESULT hRes = 0 );

HRESULT WINAPI AtlReportError( const CLSID& clsid, UINT nID, const IID& iid = GUID_NULL, HRESULT hRes = 0, HINSTANCE hInst = _Module.GetResourceInstance( ) );

HRESULT WINAPI AtlReportError( const CLSID& clsid, UINT nID, DWORD dwHelpID, LPCOLESTR lpszHelpFile, const IID& iid = GUID_NULL, HRESULT hRes = 0, HINSTANCE hInst = _Module.GetResourceInstance( ) );

Return Value

If the hRes parameter is nonzero, returns the value of hRes. If hRes is zero, then the first four versions of AtlReportError return DISP_E_EXCEPTION. The last two versions return the result of the macro MAKE_HRESULT( 1, FACILITY_ITF, nID ).

Parameters

clsid

[in] The CLSID of the object reporting the error.

lpszDesc

[in] The string describing the error. The Unicode version specifies that lpszDesc is of type LPCOLESTR; the ANSI version specifies a type of LPCSTR.

iid

[in] The IID of the interface defining the error or GUID_NULL if the error is defined by the operating system.

hRes

[in] The HRESULT you want returned to the caller.

nID

[in] The resource identifier where the error description string is stored. This value should lie between 0x0200 and 0xFFFF, inclusively. In debug builds, an ASSERT will result if nID does not index a valid string. In release builds, the error description string will be set to "Unknown Error."

dwHelpID

[in] The help context identifier for the error.

lpszHelpFile

[in] The path and name of the help file describing the error.

hInst

[in] The handle to the resource. By default, this parameter is _Module::GetResourceInstance, where _Module is the global instance of CComModule or a class derived from it.

Remarks

Sets up the IErrorInfo interface to provide error information to clients of the object. The string lpszDesc is used as the text description of the error. When the client receives the hRes you return from AtlReportError, the client can access the IErrorInfo structure for details about the error.

ATL Macros and Global Functions

See Also

MAKE_HRESULT


AtlSetChildSite

HRESULT AtlSetChildSite( IUnknown* punkChild, IUnknown* punkParent );

Return Value

A standard HRESULT value.

Parameters

punkChild

[in] A pointer to the IUnknown interface of the child.

punkParent

[in] A pointer to the IUnknown interface of the parent.

Remarks

Call this function to set the site of the child object to the IUnknown of the parent object.

ATL Macros and Global Functions


AtlTrace

void _cdecl AtlTrace( LPCTSTR lpszFormat, ... );

Parameters

lpszFormat

[in] The format of the string and variables to send to the dump device.

Remarks

Sends the specified string to the dump device.

For example:

AtlTrace(_T("The value of x is %d.\n"), x);

Note AtlTrace can be used in both debug and release builds, but it has no effect in release builds. The call to the function is evaluated, but the function does nothing. In debug builds, the function sends the specified string, after formatting, to the dump device.

AtlTrace limits the contents of the string to be sent to the dump device to no more than 511 characters, after formatting.

ATL Macros and Global Functions

See Also

ATLTRACE


ATLTRACE

ATLTRACE( exp )

Parameters

exp

[in] The formatted string and variables to send to the dump device.

Remarks

Sends the specified string to the dump device. The ATLTRACE macro performs the same as the global function AtlTrace, except that in release builds ATLTRACE compiles to (void) 0, while the function AtlTrace can still be used.

For example:

ATLTRACE(_T("The value of x is %d.\n"), x)

ATL Macros and Global Functions


ATLTRACE2

ATLTRACE2( DWORD category, UINT level, LPCSTR lpszFormat, ... )

Parameters

category

[in] The atlTraceFlags to indicate the type of event or method on which to report. See Remarks for a list of categories.

level

[in] The level of tracing to report. Must be less than or equal to the value you set for ATL_TRACE_LEVEL to appear. For example, if you set level to 4 and ATL_TRACE_LEVEL to 0, you will see no warnings. See Remarks for more information about ATL_TRACE_LEVEL.

lpszFormat

[in] The formatted string to send to the dump device.

Remarks

Use ATLTRACE2 for debugging purposes. ATLTRACE2 provides messages about how events and methods happen. ATLTRACE2 reports warnings and errors that occur as you debug the program. ATLTRACE2 sends a formatted string, lpszFormat, to a dump device, usually the debugger output window or a file.

The first parameter for ATLTRACE2, category, lists the trace flags to set. These flags correspond to the types of methods for which you want to report. The table below lists the valid trace flags you can use for the category parameter.

Category | Description
atlTraceUser | Application-defined. The value indicates the level of warnings to report.
atlTraceGeneral | Reports on all ATL applications. The default.
atlTraceCOM | Reports on COM methods.
atlTraceQI | Reports on QueryInterface calls.
atlTraceRegistrar | Reports on the registration of objects.
atlTraceRefcount | Reports on changing reference count.
atlTraceWindowing | Reports on windows methods, for example reports an invalid message map ID.
atlTraceControls | Reports on controls, for example reports when a control or its window is destroyed.
atlTraceHosting | Reports hosting messages, for example, when a client in a container is activated.
atlTraceDBClient | Reports on OLE DB Consumer Template; for example when a call to GetData fails, the output can contain the HRESULT.
atlTraceDBProvider | Reports on OLE DB Provider Template, for example reports if the creation of a column failed.
atlTraceSnapin | Reports for MMC SnapIn application.
atlTraceNotImpl | Reports that the indicated function is not implemented.

Example

// example for ATLTRACE2
int i = 1;
ATLTRACE2( atlTraceGeneral, 4, "Integer = %d\n", i );
// Output: 'Integer = 1'

You can filter for specific categories and levels at the project level by setting the two global functions described below. To specify such filtering in the preprocessor definitions, insert the global functions into Stdafx.h before the #include <atlbase.h> statement.

Alternately, you can set the filter in the preprocessor directives in the Project Settings dialog box. Click the C/C++ tab, and then insert the global into the Preprocessor definitions edit box.

To set the categories and levels, use the following global functions:

ATL_TRACE_CATEGORY 0xFFFFFFFF

Sets the trace category for which to filter. The default, 0xFFFFFFFF reports all categories. To filter for a specific category or set of categories, replace 0xFFFFFFFF with the category names you want to trace. You can use the bitwise OR (|) operator to filter for more than one category. For example, by setting ATL_TRACE_CATEGORY (atlTraceControls | atlTraceWindowing), you will see only ATLTRACE2 warnings for controls and windowing.

ATL_TRACE_LEVEL 0

Sets the trace level for which to filter. Can be 0, 1, 2, 3, or 4. The default, 0, reports only the most serious problems. Replace 0 with the level of reporting you want to see. For example, by specifying 4, you will see all levels of warnings and informational messages.

ATL Macros and Global Functions

See Also

ATLTRACE, atlTraceFlags


atlTraceFlags

int atlTraceFlags;

Remarks

Used to turn on ATL's built-in reporting features.

To use these flags, call ATLTRACE2 and use the category you want to trace as the first parameter. See ATLTRACE2 for a list of the categories and their descriptions.

Use ATLTRACE2 only for debug builds of your application.

You can filter for specific trace flags in your project by using the global functions ATL_TRACE_CATEGORY and ATL_TRACE_LEVEL. See ATLTRACE2 for a description of their use.

ATL Macros and Global Functions

See Also

ATLTRACE


ATLTRACENOTIMPL

ATLTRACENOTIMPL( funcname )

Parameters

funcname

[in] A string containing the name of the function that is not implemented.

Remarks

In debug builds of ATL, sends the string "funcname is not implemented" to the dump device and returns E_NOTIMPL. In release builds, simply returns E_NOTIMPL.

ATL Macros and Global Functions

See Also

ATLTRACE, atlTraceFlags,


AtlUnadvise

HRESULT AtlUnadvise( IUnknown* pUnkCP, const IID& iid, DWORD dw );

Return Value

A standard HRESULT value.

Parameters

pUnkCP

[in] A pointer to the IUnknown of the object that the client is connected with.

iid

[in] The GUID of the connection point. Typically, this is the same as the outgoing interface managed by the connection point.

dw

[in] The cookie that uniquely identifies the connection.

Remarks

Terminates the connection established through AtlAdvise.

ATL Macros and Global Functions


AtlUnmarshalPtr

HRESULT AtlUnmarshalPtr( IStream* pStream, const IID& iid, IUnknown** ppUnk );

Return Value

A standard HRESULT value.

Parameters

pStream

[in] A pointer to the stream being unmarshaled.

iid

[in] The GUID of the interface being unmarshaled.

ppUnk

[out] A pointer to the unmarshaled interface.

Remarks

Converts the stream's marshaling data into an interface pointer that can be used by the client.

ATL Macros and Global Functions

See Also

AtlMarshalPtrInProc


AtlWaitWithMessageLoop

BOOL AtlWaitWithMessageLoop( HANDLE hEvent );

Return Value

Returns TRUE if the object has been signaled.

Parameters

hEvent

[in] The handle of the object to wait for.

Remarks

Waits for the object to be signaled, meanwhile dispatching window messages as needed. This is useful if you want to wait for an object's event to happen and be notified of it happening, but allow window messages to be dispatched while waiting.

ATL Macros and Global Functions


BEGIN_CATEGORY_MAP

BEGIN_CATEGORY_MAP( theClass )

Parameters

theClass

[in] The name of the class containing the category map.

Remarks

Marks the beginning of the category map. This map is used to specify which component categories the COM object will implement and which categories it requires from its container.

These categories are identified by the component category ID, which the control writes to the registry to identify its abilities and its requirements.

For more information about component categories, see What are Component Categories and how do they work? in the Platform SDK.

ATL Macros and Global Functions

See Also

IMPLEMENTED_CATEGORY, REQUIRED_CATEGORY, END_CATEGORY_MAP


BEGIN_COM_MAP

BEGIN_COM_MAP( x )

Parameters

x

[in] The name of the class object you are exposing interfaces on.

Remarks

The COM map is the mechanism that exposes interfaces on an object to a client through QueryInterface. CComObjectRootEx::InternalQueryInterface only returns pointers for interfaces in the COM map. Start your interface map with the BEGIN_COM_MAP macro, add entries for each of your interfaces with the COM_INTERFACE_ENTRY macro or one of its variants, and complete the map with the END_COM_MAP macro.

For example, from the ATL BEEPER sample:

BEGIN_COM_MAP(CBeeper)
   COM_INTERFACE_ENTRY(IDispatch)
   COM_INTERFACE_ENTRY(IBeeper)
   COM_INTERFACE_ENTRY_TEAR_OFF(IID_ISupportErrorInfo, CBeeper2)
END_COM_MAP( )

See the ATL COMMAP sample for examples using the different types of COM map entry macros.

ATL Macros and Global Functions


BEGIN_CONNECTION_POINT_MAP

BEGIN_CONNECTION_POINT_MAP( x )

Parameters

x

[in] The name of the class containing the connection points.

Remarks

Marks the beginning of the connection point map entries. Start your connection point map with the BEGIN_CONNECTION_POINT_MAP macro, add entries for each of your connection points with the CONNECTION_POINT_ENTRY macro, and complete the map with the END_CONNECTION_POINT_MAP macro.

For example:

BEGIN_CONNECTION_POINT_MAP(CConnect)
   CONNECTION_POINT_ENTRY(m_cpInterfaceBeingExposed)
END_CONNECTION_POINT_MAP( )

For more information about connection points in ATL, see the article Connection Points.

ATL Macros and Global Functions


BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP

BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP( classname )

Parameters

classname

[in] The name of the snap-in extension data class.

Remarks

Marks the beginning of the snap-in extension data class map. Start your snap-in extension map with the BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP macro, add entries for each of your snap-in extension data types with the EXTENSION_SNAPIN_NODEINFO_ENTRY macro, and complete the map with the END_EXTENSION_SNAPIN_NODEINFO_MAP macro.

For example:

BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP(CMySnapInExtData)
    EXTENSION_SNAPIN_NODEINFO_ENTRY(CMySnapInExtData)
END_EXTENSION_SNAPIN_NODEINFO_MAP()

For more information about developing a snap-in extension using ATL, see the article MMC Snap-In Wizard.

ATL Macros and Global Functions

See Also

END_EXTENSION_SNAPIN_NODEINFO_MAP, EXTENSION_SNAPIN_NODEINFO_ENTRY, EXTENSION_SNAPIN_DATACLASS


BEGIN_MSG_MAP

BEGIN_MSG_MAP( theClass )

Parameters

theClass

[in] The name of the class containing the message map.

Remarks

Marks the beginning of the default message map. CWindowImpl::WindowProc uses the default message map to process messages sent to the window. The message map directs messages either to the appropriate handler function or to another message map.

The following macros map a message to a handler function. This function must be defined in theClass.

Macro | Description
MESSAGE_HANDLER | Maps a Windows message to a handler function.
MESSAGE_RANGE_HANDLER | Maps a contiguous range of Windows messages to a handler function.
COMMAND_HANDLER | Maps a WM_COMMAND message to a handler function, based on the notification code and the identifier of the menu item, control, or accelerator.
COMMAND_ID_HANDLER | Maps a WM_COMMAND message to a handler function, based on the identifier of the menu item, control, or accelerator.
COMMAND_CODE_HANDLER | Maps a WM_COMMAND message to a handler function, based on the notification code.
COMMAND_RANGE_HANDLER | Maps a contiguous range of WM_COMMAND messages to a handler function, based on the identifier of the menu item, control, or accelerator.
NOTIFY_HANDLER | Maps a WM_NOTIFY message to a handler function, based on the notification code and the control identifier.
NOTIFY_ID_HANDLER | Maps a WM_NOTIFY message to a handler function, based on the control identifier.
NOTIFY_CODE_HANDLER | Maps a WM_NOTIFY message to a handler function, based on the notification code.
NOTIFY_RANGE_HANDLER | Maps a contiguous range of WM_NOTIFY messages to a handler function, based on the control identifier.

The following macros direct a message to another message map. This process is called "chaining."

Macro | Description
CHAIN_MSG_MAP | Chains to the default message map in the base class.
CHAIN_MSG_MAP_MEMBER | Chains to the default message map in a data member of the class.
CHAIN_MSG_MAP_ALT | Chains to an alternate message map in the base class.
CHAIN_MSG_MAP_ALT_MEMBER | Chains to an alternate message map in a data member of the class.
CHAIN_MSG_MAP_DYNAMIC | Chains to the default message map in another class at run time.

Example

class CMyWindow : ...
{
public:
   ...

   BEGIN_MSG_MAP(CMyWindow)
      MESSAGE_HANDLER(WM_PAINT, OnPaint)
      MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
      CHAIN_MSG_MAP(CMyBaseWindow)
   END_MSG_MAP()

   LRESULT OnPaint(UINT uMsg, WPARAM wParam,
                   LPARAM lParam, BOOL& bHandled)
   { ... }

   LRESULT OnSetFocus(UINT uMsg, WPARAM wParam,
                      LPARAM lParam, BOOL& bHandled)
   { ... }
};

When a CMyWindow object receives a WM_PAINT message, the message is directed to CMyWindow::OnPaint for the actual processing. If OnPaint indicates the message requires further processing, the message will then be directed to the default message map in CMyBaseWindow.

In addition to the default message map, you can define an alternate message map with ALT_MSG_MAP. Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps. The following example shows the default message map and one alternate message map, each containing one handler function:

BEGIN_MSG_MAP(CMyClass)
   MESSAGE_HANDLER(WM_PAINT, OnPaint)
ALT_MSG_MAP(1)
   MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
END_MSG_MAP()

The next example shows two alternate message maps. The default message map is empty.

BEGIN_MSG_MAP(CMyClass)
ALT_MSG_MAP(1)
   MESSAGE_HANDLER(WM_PAINT, OnPaint)
   MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
ALT_MSG_MAP(2)
   MESSAGE_HANDLER(WM_CREATE, OnCreate)
END_MSG_MAP()

The END_MSG_MAP macro marks the end of the message map. Note that there is always exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

CMessageMap, CDynamicChain


BEGIN_OBJECT_MAP

BEGIN_OBJECT_MAP( x )

Parameters

x

[in] Array of ATL object definitions.

Remarks

Marks the beginning of the map of ATL objects. The parameter x is an array holding _ATL_OBJMAP_ENTRY structures that describe the objects.

Start your object map with the BEGIN_OBJECT_MAP macro, add entries for each object with the OBJECT_ENTRY macro, and complete the map with the END_OBJECT_MAP macro. When CComModule::RegisterServer is called, it updates the system registry for each object in the object map.

Typically, you follow an object map definition with CComModule::Init to initialize the instance. For example, from the CIRCCOLL sample:

BEGIN_OBJECT_MAP(ObjectMap)
   OBJECT_ENTRY(CLSID_MyCircleCollectionCreator, CMyCircleCollectionCreator)
END_OBJECT_MAP( )

//DLL Entry Point
extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
   if (dwReason == DLL_PROCESS_ATTACH)
   {
      _Module.Init(ObjectMap, hInstance);
      DisableThreadLibraryCalls(hInstance);
   }
   else if (dwReason == DLL_PROCESS_DETACH)
      _Module.Term();
   return TRUE;
}

See Also

ATL Macros and Global Functions


BEGIN_PROP_MAP

BEGIN_PROP_MAP( theClass )

Parameters

theClass

[in] Specifies the class containing the property map.

Remarks

Marks the beginning of the object's property map. The property map stores property descriptions, property DISPIDs, property page CLSIDs, and IDispatch IIDs. Classes IPerPropertyBrowsingImpl, IPersistPropertyBagImpl, IPersistStreamInitImpl, and ISpecifyPropertyPagesImpl use the property map to retrieve and set this information.

When you create an object with the ATL Object Wizard, the wizard will create an empty property map by specifying BEGIN_PROP_MAP followed by END_PROP_MAP.

BEGIN_PROP_MAP does not save out the extent (that is, the dimensions) of a property map, because an object using a property map may not have a user interface, so it would have no extent. If the object is an ActiveX control with a user interface, it has an extent. In this case, you must specify PROP_DATA_ENTRY in your property map to supply the extent.

See Also

ATL Macros and Global Functions


BEGIN_SERVICE_MAP

BEGIN_SERVICE_MAP( theClass )

Parameters

theClass

[in] Specifies the class containing the service map.

Remarks

Marks the beginning of the service map. Use the service map to implement service provider functionality on your COM object. First, you must derive your class from IServiceProviderImpl. There are two types of entries:

  • SERVICE_ENTRY Indicates support for the specified service ID (SID)

  • SERVICE_ENTRY_CHAIN Instructs IServiceProviderImpl::QueryService to chain to another, specified object.

Example

See SERVICE_ENTRY

ATL Macros and Global Functions

See Also

END_SERVICE_MAP


BEGIN_SINK_MAP

BEGIN_SINK_MAP( _class )

Parameters

_class

[in] Specifies the control.

Remarks

Declares the beginning of the event sink map for the composite control.

Example

BEGIN_SINK_MAP(CMyObj)
   SINK_ENTRY(IDC_CIRCCTL1, DISPID_CLICK, OnClick_CircCtrl1)
   SINK_ENTRY(IDC_CIRCCTL2, DISPID_CLICK, OnClick_CircCtrl2)
END_SINK_MAP()

ATL Macros and Global Functions

See Also

Composite Control Fundamentals, SINK_ENTRY, END_SINK_MAP


BEGIN_SNAPINTOOLBARID_MAP

BEGIN_SNAPINTOOLBARID_MAP( _class )

Parameters

_class

[in] Specifies the Snap-In object class.

Remarks

Declares the beginning of the toolbar ID map for the Snap-In object.

See Also

END_SNAPINTOOLBARID_MAP, SNAPINTOOLBARID_ENTRY


CHAIN_MSG_MAP

CHAIN_MSG_MAP( theChainClass )

Parameters

theChainClass

[in] The name of the base class containing the message map.

Remarks

Defines an entry in a message map. CHAIN_MSG_MAP directs messages to a base class's default message map (declared with BEGIN_MSG_MAP). To direct messages to a base class's alternate message map (declared with ALT_MSG_MAP), use CHAIN_MSG_MAP_ALT.

For example:

class CMyClass : public CMyBaseClass, ...
{
public:
  ...

  BEGIN_MSG_MAP(CMyClass)
     MESSAGE_HANDLER(WM_PAINT, OnPaint)
     // chain to default message map in CMyBaseClass
     CHAIN_MSG_MAP(CMyBaseClass)
  ALT_MSG_MAP(1)
     // chain to default message map in CMyBaseClass
     CHAIN_MSG_MAP(CMyBaseClass)
  ALT_MSG_MAP(2)
     MESSAGE_HANDLER(WM_CHAR, OnChar)
     // chain to alternate message map in CMyBaseClass
     CHAIN_MSG_MAP_ALT(CMyBaseClass, 1)
  END_MSG_MAP()

  ...
};

This example illustrates the following:

  • If a window procedure is using CMyClass's default message map and OnPaint does not handle a message, the message is directed to CMyBaseClass's default message map for processing.

  • If a window procedure is using the first alternate message map in CMyClass, all messages are directed to CMyBaseClass's default message map.

  • If a window procedure is using CMyClass's second alternate message map and OnChar does not handle a message, the message is directed to the specified alternate message map in CMyBaseClass. CMyBaseClass must have declared this message map with ALT_MSG_MAP(1).

Note Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps with ALT_MSG_MAP. The END_MSG_MAP macro marks the end of the message map. Every message map must have exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

CHAIN_MSG_MAP_MEMBER, CHAIN_MSG_MAP_DYNAMIC, MESSAGE_HANDLER


CHAIN_MSG_MAP_ALT

CHAIN_MSG_MAP_ALT( theChainClass, msgMapID )

Parameters

theChainClass

[in] The name of the base class containing the message map.

msgMapID

[in] The message map identifier.

Remarks

Defines an entry in a message map. CHAIN_MSG_MAP_ALT directs messages to an alternate message map in a base class. You must have declared this alternate message map with ALT_MSG_MAP(msgMapID). To direct messages to a base class's default message map (declared with BEGIN_MSG_MAP), use CHAIN_MSG_MAP. For an example, see CHAIN_MSG_MAP.

Note Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps with ALT_MSG_MAP. The END_MSG_MAP macro marks the end of the message map. Every message map must have exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

CHAIN_MSG_MAP_ALT_MEMBER


CHAIN_MSG_MAP_ALT_MEMBER

CHAIN_MSG_MAP_ALT_MEMBER( theChainMember, msgMapID )

Parameters

theChainMember

[in] The name of the data member containing the message map.

msgMapID

[in] The message map identifier.

Remarks

Defines an entry in a message map. CHAIN_MSG_MAP_ALT_MEMBER directs messages to an alternate message map in a data member. You must have declared this alternate message map with ALT_MSG_MAP(msgMapID). To direct messages to a data member's default message map (declared with BEGIN_MSG_MAP), use CHAIN_MSG_MAP_MEMBER. For an example, see CHAIN_MSG_MAP_MEMBER.

Note Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps with ALT_MSG_MAP. The END_MSG_MAP macro marks the end of the message map. Every message map must have exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

CHAIN_MSG_MAP_ALT


CHAIN_MSG_MAP_DYNAMIC

CHAIN_MSG_MAP_DYNAMIC( dynaChainID )

Parameters

dynaChainID

[in] The unique identifier for an object's message map.

Remarks

Defines an entry in a message map. CHAIN_MSG_MAP_DYNAMIC directs messages, at run time, to the default message map in another object. The object and its message map are associated with dynaChainID, which you define through CDynamicChain::SetChainEntry. You must derive your class from CDynamicChain in order to use CHAIN_MSG_MAP_DYNAMIC. For an example, see the CDynamicChain overview.

Note Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps with ALT_MSG_MAP. The END_MSG_MAP macro marks the end of the message map. Every message map must have exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

CHAIN_MSG_MAP, CHAIN_MSG_MAP_MEMBER


CHAIN_MSG_MAP_MEMBER

CHAIN_MSG_MAP_MEMBER( theChainMember )

Parameters

theChainMember

[in] The name of the data member containing the message map.

Remarks

Defines an entry in a message map. CHAIN_MSG_MAP_MEMBER directs messages to a data member's default message map (declared with BEGIN_MSG_MAP). To direct messages to a data member's alternate message map (declared with ALT_MSG_MAP), use CHAIN_MSG_MAP_ALT_MEMBER.

For example:

class CMyClass : ...
{
public:
  CMyContainedClass m_obj;
  ...

  BEGIN_MSG_MAP(CMyClass)
     MESSAGE_HANDLER(WM_PAINT, OnPaint)
     // chain to default message map of m_obj
     CHAIN_MSG_MAP_MEMBER(m_obj)
  ALT_MSG_MAP(1)
     // chain to default message map of m_obj
     CHAIN_MSG_MAP(m_obj)
  ALT_MSG_MAP(2)
     MESSAGE_HANDLER(WM_CHAR, OnChar)
     // chain to alternate message map of m_obj
     CHAIN_MSG_MAP_ALT(m_obj, 1)
  END_MSG_MAP()

  ...
};

This example illustrates the following:

  • If a window procedure is using CMyClass's default message map and OnPaint does not handle a message, the message is directed to m_obj's default message map for processing.

  • If a window procedure is using the first alternate message map in CMyClass, all messages are directed to m_obj's default message map.

  • If a window procedure is using CMyClass's second alternate message map and OnChar does not handle a message, the message is directed to the specified alternate message map of m_obj. Class CMyContainedClass must have declared this message map with ALT_MSG_MAP(1).

Note Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps with ALT_MSG_MAP. The END_MSG_MAP macro marks the end of the message map. Every message map must have exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

CHAIN_MSG_MAP, CHAIN_MSG_MAP_DYNAMIC, MESSAGE_HANDLER


COM_INTERFACE_ENTRY Macros

These macros enter an object's interfaces into its COM map so that they can be accessed by QueryInterface. The order of entries in the COM map is the order interfaces will be checked for a matching IID during QueryInterface.

Each object that wants to expose its interfaces via QueryInterface must have its own COM map. The COM map starts with the macro BEGIN_COM_MAP. Interface entries are added with one or more of the COM_INTERFACE_ENTRY macros, and the map is completed with the END_COM_MAP macro. For example:

BEGIN_COM_MAP(CMyObject)
    COM_INTERFACE_ENTRY(IDispatch)
    COM_INTERFACE_ENTRY(IMyObject)
END_COM_MAP( )

See the ATL COMMAP sample for examples using the different types of COM map entry macros.

Note that the first entry in the COM map must be an interface on the object containing the COM map. Thus, you cannot start your COM map entries with COM_INTERFACE_ENTRY_CHAIN, which causes the COM map of a different object to be searched at the point where COM_INTERFACE_ENTRY_CHAIN(COtherObject) appears in your object's COM map. If you want to search the COM map of another object first, add an interface entry for IUnknown to your COM map, then chain the other object's COM map. For example:

BEGIN_COM_MAP(CThisObject)
   COM_INTERFACE_ENTRY(IUnknown)
   COM_INTERFACE_ENTRY_CHAIN(COtherObject)
END_COM_MAP( )

Caution As of version 3.0, ATL uses the compiler keyword __uuidof( class ) to obtain the corresponding IID for a given class. Because of changes in the COM_INTERFACE_ENTRY macros effective in version 3.0, now you simply include the header for the interface to use, instead of also linking to a library that defines the matching IIDs for that interface. This change can cause problems if the header was previously generated by an older version of MIDL, or if it was hand-coded and not marked appropriately. If the declaration for the interface in the header has not been marked with an associated __declspec( uuid ), then any attempt to use the __uuidof keyword for that interface will fail. You can revert to the older (ATL 2.x) COM_INTERFACE_ENTRY macros by defining _ATL_NO_UUIDOF in your build settings to work around any problems with this new behavior.

The following are the available entry macros:

COM Map Entry Macros

COM_INTERFACE_ENTRY
COM_INTERFACE_ENTRY_IID
COM_INTERFACE_ENTRY2
COM_INTERFACE_ENTRY2_IID
COM_INTERFACE_ENTRY_FUNC
COM_INTERFACE_ENTRY_FUNC_BLIND
COM_INTERFACE_ENTRY_TEAR_OFF
COM_INTERFACE_ENTRY_CACHED_TEAR_OFF
COM_INTERFACE_ENTRY_AGGREGATE
COM_INTERFACE_ENTRY_AGGREGATE_BLIND
COM_INTERFACE_ENTRY_AUTOAGGREGATE
COM_INTERFACE_ENTRY_AUTOAGGREGATE_BLIND
COM_INTERFACE_ENTRY_CHAIN
COM_INTERFACE_ENTRY_BREAK
COM_INTERFACE_ENTRY_NOINTERFACE

ATL Macros and Global Functions


COM_INTERFACE_ENTRY

COM_INTERFACE_ENTRY( x )

Parameters

x

[in] The name of an interface your class object derives from directly.

Remarks

Typically, this is the entry type you use most often.

For example:

BEGIN_COM_MAP(CThisExample)
   COM_INTERFACE_ENTRY(IDispatch)
   COM_INTERFACE_ENTRY(IBaseThisExample)
   COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY2

COM_INTERFACE_ENTRY2( x, x2 )

Parameters

x

[in] The name of an interface you want to expose from your object.

x2

[in] The name of the inheritance branch from which x is exposed.

Remarks

Use this macro to disambiguate two branches of inheritance. For example, if you derive your class object from two dual interfaces, you expose IDispatch using COM_INTERFACE_ENTRY2 since IDispatch can be obtained from either one of the interfaces.

For example, from the ATL sample COMMAP:

class COuter :
   public CChainBase, // CChainBase derives from
                      // IDispatch
   public IDispatchImpl<IOuter, &IID_IOuter,
                        &LIBID_COMMAPLib)>,
   public CComCoClass<COuter, &CLSID_COuter>
{
public:
   COuter(){}
   ...

   BEGIN_COM_MAP(COuter)
      COM_INTERFACE_ENTRY2(IDispatch, IOuter)
   ...
   END_COM_MAP

};

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY2_IID

COM_INTERFACE_ENTRY2_IID( iid, x, x2 )

Parameters

iid

[in] The GUID you are specifying for the interface.

x

[in] The name of an interface that your class object derives from directly.

x2

[in] The name of a second interface that your class object derives from directly.

Remarks

As COM_INTERFACE_ENTRY2, except you can specify a different IID.

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_AGGREGATE

COM_INTERFACE_ENTRY_AGGREGATE( iid, punk )

Parameters

iid

[in] The GUID of the interface queried for.

punk

[in] The name of an IUnknown pointer.

Remarks

When the interface identified by iid is queried for, COM_INTERFACE_ENTRY_AGGREGATE forwards to punk. The punk parameter is assumed to point to the inner unknown of an aggregate or to NULL, in which case the entry is ignored. Typically, you would CoCreate the aggregate in FinalConstruct.

For example, from the ATL sample COMMAP:

BEGIN_COM_MAP(COuter)
   ...
   COM_INTERFACE_ENTRY_AGGREGATE(IID_IAgg, m_pUnkAgg.p)
   ...
END_COM_MAP()

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_AGGREGATE_BLIND

COM_INTERFACE_ENTRY_AGGREGATE_BLIND( punk )

Parameters

punk

[in] The name of an IUnknown pointer.

Remarks

Same as COM_INTERFACE_ENTRY_AGGREGATE, except that querying for any IID results in forwarding the query to punk. If the interface query fails, processing of the COM map continues.

For example, from the ATL sample COMMAP:

BEGIN_COM_MAP(COuter)
   ...
   COM_INTERFACE_ENTRY_AGGREGATE_BLIND(m_pUnkAggBlind.p)
   ...
END_COM_MAP()

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_AUTOAGGREGATE

COM_INTERFACE_ENTRY_AUTOAGGREGATE( iid, punk, clsid )

Parameters

iid

[in] The GUID of the interface queried for.

punk

[in] The name of an IUnknown pointer. Must be a member of the class containing the COM map.

clsid

[in] The identifier of the aggregate that will be created if punk is NULL.

Remarks

Same as COM_INTERFACE_ENTRY_AGGREGATE, except if punk is NULL, it automatically creates the aggregate described by the clsid.

For example, from the ATL sample COMMAP:

BEGIN_COM_MAP(COuter)
...
   COM_INTERFACE_ENTRY_AUTOAGGREGATE(IID_IAutoAgg, m_pUnkAutoAgg.p, CLSID_CAutoAgg)
...
END_COM_MAP()

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_AUTOAGGREGATE_BLIND

COM_INTERFACE_ENTRY_AUTOAGGREGATE_BLIND( punk, clsid )

Parameters

punk

[in] The name of an IUnknown pointer. Must be a member of the class containing the COM map.

clsid

[in] The identifier of the aggregate that will be created if punk is NULL.

Remarks

Same as COM_INTERFACE_ENTRY_AUTOAGGREGATE, except that querying for any IID results in forwarding the query to punk, and if punk is NULL, automatically creating the aggregate described by the clsid. If the interface query fails, processing of the COM map continues.

For example, from the ATL sample COMMAP:

BEGIN_COM_MAP(COuter)
   ...
   COM_INTERFACE_ENTRY_AUTOAGGREGATE_BLIND(m_pUnkAutoAggB.p, CLSID_CAutoAggB)
   ...
END_COM_MAP()

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_BREAK

COM_INTERFACE_ENTRY_BREAK( x )

Parameters

x

[in] Text used to construct the interface identifier.

Remarks

Causes your program to call DebugBreak when the specified interface is queried for.

The interface IID will be constructed by appending x to IID_. For example, if x is IPersistStorage, the IID will be IID_IPersistStorage.

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_CACHED_TEAR_OFF

COM_INTERFACE_ENTRY_CACHED_TEAR_OFF( iid, x, punk )

Parameters

iid

[in] The GUID of the tear-off interface.

x

[in] The name of the class implementing the interface.

punk

[in] The name of an IUnknown pointer. Must be a member of the class containing the COM map. Should be initialized to NULL in the class object's constructor.

Remarks

Saves the interface specific data for every instance. If the interface is not used, this lowers the overall instance size of your object.

For example, from the ATL sample COMMAP:

BEGIN_COM_MAP(COuter)
   ...
   COM_INTERFACE_ENTRY_CACHED_TEAR_OFF(IID_ITearOff2,
      CTearOff2, m_pUnkTearOff2.p)
   ...
END_COM_MAP()

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_CHAIN

COM_INTERFACE_ENTRY_CHAIN( classname )

Parameters

classname

[in] A base class of the current object.

Remarks

Processes the COM map of the base class when the processing reaches this entry in the COM map.

For example, from the ATL sample COMMAP:

BEGIN_COM_MAP(COuter)
...COM_INTERFACE_ENTRY2(IDispatch, IOuter)
   ...
   COM_INTERFACE_ENTRY_CHAIN(CChainBase)
   ...
END_COM_MAP()

Note that the first entry in the COM map must be an interface on the object containing the COM map. Thus, you cannot start your COM map entries with COM_INTERFACE_ENTRY_CHAIN, which causes the COM map of a different object to be searched at the point where COM_INTERFACE_ENTRY_CHAIN(COtherObject) appears in your object's COM map. If you want to search the COM map of another object first, add an interface entry for IUnknown to your COM map, then chain the other object's COM map. For example:

BEGIN_COM_MAP(CThisObject)
   COM_INTERFACE_ENTRY(IUnknown)
   COM_INTERFACE_ENTRY_CHAIN(COtherObject)
END_COM_MAP( )

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_FUNC

COM_INTERFACE_ENTRY_FUNC( iid, dw, func )

Parameters

iid

[in] The GUID of the interface exposed.

dw

[in] A parameter passed through to the func.

func

[in] The function pointer that will return iid.

Remarks

A general mechanism for hooking into ATL's QueryInterface logic. If iid matches the IID of the interface queried for, then the function specified by func is called. The declaration for the function should be:

HRESULT WINAPI func(void* pv, REFIID riid, LPVOID* ppv, DWORD dw);

When your function is called, pv points to your class object. The riid parameter refers to the interface being queried for, ppv is the pointer to the location where the function should store the pointer to the interface, and dw is the parameter you specified in the entry. The function should set *ppv to NULL and return E_NOINTERFACE or S_FALSE if it chooses not to return an interface. With E_NOINTERFACE, COM map processing terminates. With S_FALSE, COM map processing continues, even though no interface pointer was returned. If the function returns an interface pointer, it should return S_OK.

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_FUNC_BLIND

COM_INTERFACE_ENTRY_FUNC_BLIND( dw, func )

Parameters

dw

[in] A parameter passed through to the func.

func

[in] The function that gets called when this entry in the COM map is processed.

Remarks

Same as COM_INTERFACE_ENTRY_FUNC, except that querying for any IID results in a call to func. Any failure will cause processing to continue on the COM map. If the function returns an interface pointer, it should return S_OK.

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_IID

COM_INTERFACE_ENTRY_IID( iid, x )

Parameters

iid

[in] The GUID of the interface exposed.

x

[in] The name of the class whose vtable will be exposed as the interface identified by iid.

Remarks

Use this macro to enter the interface into the COM map and specify its IID.

For example:

BEGIN_COM_MAP(CThisExample)
   COM_INTERFACE_ENTRY_IID(*piid, CThisExample)
   COM_INTERFACE_ENTRY(IDispatch)
   COM_INTERFACE_ENTRY(IBaseThisExample)
   COM_INTERFACE_ENTRY(ISupportErrorInfo)
END_COM_MAP()

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_NOINTERFACE

COM_INTERFACE_ENTRY_NOINTERFACE( x )

Parameters

x

[in] Text used to construct the interface identifier.

Remarks

Returns E_NOINTERFACE and terminates COM map processing when the specified interface is queried for. You can use this macro to prevent an interface from being used in a particular case. For example, you can insert this macro into your COM map right before COM_INTERFACE_ENTRY_AGGREGATE_BLIND to prevent a query for the interface from being forwarded to the aggregate's inner unknown.

The interface IID will be constructed by appending x to IID_. For example, if x is IPersistStorage, the IID will be IID_IPersistStorage.

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COM_INTERFACE_ENTRY_TEAR_OFF

COM_INTERFACE_ENTRY_TEAR_OFF( iid, x )

Parameters

iid

[in] The GUID of the tear-off interface.

x

[in] The name of the class implementing the interface.

Remarks

Exposes your tear-off interfaces. A tear-off interface is implemented as a separate object that is instantiated every time the interface it represents is queried for. Typically, you build your interface as a tear-off if the interface is rarely used, since this saves a vtable pointer in every instance of your main object. The tear-off is deleted when its reference count becomes zero. The class implementing the tear-off should be derived from CComTearOffObjectBase and have its own COM map.

For example, from the ATL sample COMMAP:

BEGIN_COM_MAP(COuter)
   ...
   COM_INTERFACE_ENTRY_TEAR_OFF(IID_ITearOff1, CTearOff1)
   ...
END_COM_MAP()

See COM_INTERFACE_ENTRY Macros for remarks about COM map entries.

ATL Macros and Global Functions


COMMAND_CODE_HANDLER

COMMAND_CODE_HANDLER( code, func )

Parameters

code

[in] The notification code.

func

[in] The name of the message-handler function.

Remarks

Similar to COMMAND_HANDLER, but maps a WM_COMMAND message based only on the notification code.

ATL Macros and Global Functions

See Also

COMMAND_ID_HANDLER, COMMAND_RANGE_HANDLER, MESSAGE_HANDLER, NOTIFY_CODE_HANDLER


COMMAND_HANDLER

COMMAND_HANDLER( id, code, func )

Parameters

id

[in] The identifier of the menu item, control, or accelerator.

code

[in] The notification code.

func

[in] The name of the message-handler function.

Remarks

Defines an entry in a message map. COMMAND_HANDLER maps a WM_COMMAND message to the specified handler function, based on the notification code and the control identifier. For example:

class CMyClass : ...
{
public:
   ...

   BEGIN_MSG_MAP(CMyClass)
      COMMAND_HANDLER(IDC_MYCTL, EN_CHANGE, OnChange)
      ...
   END_MSG_MAP()

   // When a CMyClass object receives a WM_COMMAND
   // message identified by IDC_MYCTL and EN_CHANGE,
   // the message is directed to CMyClass::OnChange
   // for the actual processing.
   LRESULT OnChange( ... )
   { ... }

};

Any function specified in a COMMAND_HANDLER macro must defined as follows:

LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);

The message map sets bHandled to TRUE before CommandHandler is called. If CommandHandler does not fully handle the message, it should set bHandled to FALSE to indicate the message needs further processing.

Note Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps with ALT_MSG_MAP. The END_MSG_MAP macro marks the end of the message map. Every message map must have exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

In addition to COMMAND_HANDLER, you can use MESSAGE_HANDLER to map a WM_COMMAND message without regard to an identifier or code. In this case, MESSAGE_HANDLER(WM_COMMAND, OnHandlerFunction) will direct all WM_COMMAND messages to OnHandlerFunction.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

COMMAND_ID_HANDLER, COMMAND_CODE_HANDLER, COMMAND_RANGE_HANDLER, NOTIFY_HANDLER


COMMAND_ID_HANDLER

COMMAND_ID_HANDLER( id, func )

Parameters

id

[in] The identifier of the menu item, control, or accelerator sending the message.

func

[in] The name of the message-handler function.

Remarks

Similar to COMMAND_HANDLER, but maps a WM_COMMAND message based only on the identifier of the menu item, control, or accelerator.

ATL Macros and Global Functions

See Also

COMMAND_CODE_HANDLER, COMMAND_RANGE_HANDLER, MESSAGE_HANDLER, NOTIFY_ID_HANDLER


COMMAND_RANGE_HANDLER

COMMAND_RANGE_HANDLER( idFirst, idLast, func )

Parameters

idFirst

[in] Marks the beginning of a contiguous range of WM_COMMAND messages.

idLast

[in] Marks the end of a contiguous range of WM_COMMAND messages.

func

[in] The name of the message-handler function.

Remarks

Similar to COMMAND_HANDLER, but maps a range of WM_COMMAND messages to a single handler function. This range is based on the identifier of the menu item, control, or accelerator sending the message.

ATL Macros and Global Functions

See Also

COMMAND_ID_HANDLER, COMMAND_CODE_HANDLER, MESSAGE_RANGE_HANDLER, NOTIFY_RANGE_HANDLER


CONNECTION_POINT_ENTRY

CONNECTION_POINT_ENTRY( iid )

Parameters

iid

[in] The GUID of the interface being added to the connection point map.

Remarks

Enters a connection point for the specified interface into the connection point map so that it can be accessed. Connection point entries in the map are used by IConnectionPointContainerImpl. The class containing the connection point map must inherit from IConnectionPointContainerImpl. For example:

class CMyCPClass :
   public IConnectionPointContainerImpl,
   public IPropertyNotifySinkImpl<CMyCPClass>
{
public:
   ...
   BEGIN_CONNECTION_POINT_MAP(CMyCPClass)
      CONNECTION_POINT_ENTRY(IID_IPropertyNotifySink)
   END_CONNECTION_POINT_MAP( )
   ...
};

Start your connection point map with the BEGIN_CONNECTION_POINT_MAP macro, add entries for each of your connection points with the CONNECTION_POINT_ENTRY macro, and complete the map with the END_CONNECTION_POINT_MAP macro.

For more information about connection points in ATL, see the article Connection Points.

ATL Macros and Global Functions


DECLARE_AGGREGATABLE

DECLARE_AGGREGATABLE( x )

Parameters

x

[in] The name of the class you are defining as aggregatable.

Remarks

Specifies that your object can be aggregated. CComCoClass contains this macro to specify the default aggregation model. To override this default, specify either the DECLARE_NOT_AGGREGATABLE or DECLARE_ONLY_AGGREGATABLE macro in your class definition. For example:

class CMyClass : public CComCoClass< .. >, ...
{
public:
   DECLARE_NOT_AGGREGATABLE(CMyClass)
   ...
};

ATL Macros and Global Functions


DECLARE_CLASSFACTORY

DECLARE_CLASSFACTORY( )

Remarks

Declares CComClassFactory to be the class factory. CComCoClass uses this macro to declare the default class factory for your object.

ATL Macros and Global Functions

See Also

DECLARE_CLASSFACTORY_EX, DECLARE_CLASSFACTORY2, DECLARE_CLASSFACTORY_AUTO_THREAD, DECLARE_CLASSFACTORY_SINGLETON


DECLARE_CLASSFACTORY2

DECLARE_CLASSFACTORY2( lic )

Parameters

lic

[in] A class that implements VerifyLicenseKey, GetLicenseKey, and IsLicenseValid.

Remarks

Declares CComClassFactory2 to be the class factory. For example:

class CMyClass : ..., public CComCoClass< ... >
{
   ...
   DECLARE_CLASSFACTORY2(CMyLicense)
   ...
};

CComCoClass includes the DECLARE_CLASSFACTORY macro, which specifies CComClassFactory as the default class factory. However, by including the DECLARE_CLASSFACTORY2 macro in your object's class definition, you override this default.

ATL Macros and Global Functions

See Also

DECLARE_CLASSFACTORY_EX, DECLARE_CLASSFACTORY_AUTO_THREAD, DECLARE_CLASSFACTORY_SINGLETON


DECLARE_CLASSFACTORY_AUTO_THREAD

DECLARE_CLASSFACTORY_AUTO_THREAD( )

Remarks

Declares CComClassFactoryAutoThread to be the class factory. For example:

class CMyClass : ..., public CComCoClass< ... >
{
   ...
   DECLARE_CLASSFACTORY_AUTO_THREAD( )
   ...
};

CComCoClass includes the DECLARE_CLASSFACTORY macro, which specifies CComClassFactory as the default class factory. However, by including the DECLARE_CLASSFACTORY_AUTO_THREAD macro in your object's class definition, you override this default.

ATL Macros and Global Functions

See Also

DECLARE_CLASSFACTORY_EX, DECLARE_CLASSFACTORY2, DECLARE_CLASSFACTORY_SINGLETON


DECLARE_CLASSFACTORY_EX

DECLARE_CLASSFACTORY_EX( cf )

Parameters

cf

[in] The name of the class that implements your class factory object.

Remarks

Declares cf to be the class factory. cf must derive from CComClassFactory and override the CreateInstance method. For example:

class CMyClass : ..., public CComCoClass< ... >
{
   ...
   DECLARE_CLASSFACTORY_EX(CMyClassFactory)
   ...
};

CComCoClass includes the DECLARE_CLASSFACTORY macro, which specifies CComClassFactory as the default class factory. However, by including the DECLARE_CLASSFACTORY_EX macro in your object's class definition, you override this default.

ATL Macros and Global Functions

See Also

DECLARE_CLASSFACTORY2, DECLARE_CLASSFACTORY_AUTO_THREAD, DECLARE_CLASSFACTORY_SINGLETON


DECLARE_CLASSFACTORY_SINGLETON

DECLARE_CLASSFACTORY_SINGLETON( obj )

Parameters

obj

[in] The name of your class object.

Remarks

Declares CComClassFactorySingleton to be the class factory. For example:

class CMyClass : ..., public CComCoClass< ... >
{
   ...
   DECLARE_CLASSFACTORY_SINGLETON(CMyClass)
   ...
};

CComCoClass includes the DECLARE_CLASSFACTORY macro, which specifies CComClassFactory as the default class factory. However, by including the DECLARE_CLASSFACTORY_SINGLETON macro in your object's class definition, you override this default.

ATL Macros and Global Functions

See Also

DECLARE_CLASSFACTORY2, DECLARE_CLASSFACTORY_EX, DECLARE_CLASSFACTORY_AUTO_THREAD


DECLARE_EMPTY_MSG_MAP

DECLARE_EMPTY_MSG_MAP( )

Remarks

Declares an empty message map. DECLARE_EMPTY_MSG_MAP is a convenience macro that calls the macros BEGIN_MSG_MAP and END_MSG_MAP to create an empty message map:

BEGIN_MSG_MAP(...)
END_MSG_MAP

ATL Macros and Global Functions


DECLARE_GET_CONTROLLING_UNKNOWN

DECLARE_GET_CONTROLLING_UNKNOWN( )

Remarks

Declares a virtual function GetControllingUnknown. Add this macro to your object if you get the compiler error message that GetControllingUnknown is undefined (for example, in CComAggregateCreator).

ATL Macros and Global Functions

See Also

DECLARE_AGGREGATABLE


DECLARE_NO_REGISTRY

DECLARE_NO_REGISTRY( )

Remarks

Use DECLARE_NO_REGISTRY if you want to avoid any default ATL registration for the class in which this macro appears.

ATL Macros and Global Functions

See Also

DECLARE_REGISTRY, DECLARE_REGISTRY_RESOURCE, DECLARE_REGISTRY_RESOURCEID


DECLARE_NOT_AGGREGATABLE

DECLARE_NOT_AGGREGATABLE( x )

Parameters

x

[in] The name of the class object you are defining as not aggregatable.

Remarks

Specifies that your object cannot be aggregated. DECLARE_NOT_AGGREGATABLE causes CreateInstance to return an error (CLASS_E_NOAGGREGATION) if an attempt is made to aggregate onto your object.

By default, CComCoClass contains the DECLARE_AGGREGATABLE macro, which specifies that your object can be aggregated. To override this default behavior, include DECLARE_NOT_AGGREGATABLE in your class definition. For example:

class CMyClass : public CComCoClass< .. >, ...
{
public:
   DECLARE_NOT_AGGREGATABLE(CMyClass)
   ...
};

ATL Macros and Global Functions

See Also

DECLARE_ONLY_AGGREGATABLE


DECLARE_OBJECT_DESCRIPTION

DECLARE_OBJECT_DESCRIPTION( x )

Parameters

x

[in] The class object's description.

Remarks

Allows you to specify a text description for your class object. ATL enters this description into the object map through the OBJECT_ENTRY macro.

DECLARE_OBJECT_DESCRIPTION implements a GetObjectDescription function, which you can use to override the CComCoClass::GetObjectDescription method. For example:

class CMyClass : public CComCoClass< ... >, ...
{
public:
   // Override CComCoClass::GetObjectDescription
   DECLARE_OBJECT_DESCRIPTION("Account Transfer Object 1.0")

   ...
};

The GetObjectDescription function is called by IComponentRegistrar::GetComponents. IComponentRegistrar is an Automation interface that allows you to register and unregister individual components in a DLL. When you create a Component Registrar object with the ATL Object Wizard, the wizard will automatically implement the IComponentRegistrar interface. IComponentRegistrar is typically used by Microsoft Transaction Server.

For more information about the ATL Object Wizard, see the article Creating an ATL Project.

ATL Macros and Global Functions


DECLARE_ONLY_AGGREGATABLE

DECLARE_ONLY_AGGREGATABLE( x )

Parameters

x

[in] The name of the class object you are defining as only aggregatable.

Remarks

Specifies that your object must be aggregated. DECLARE_ONLY_AGGREGATABLE causes an error (E_FAIL) if an attempt is made to CoCreate your object as nonaggregated object.

By default, CComCoClass contains the DECLARE_AGGREGATABLE macro, which specifies that your object can be aggregated. To override this default behavior, include DECLARE_ONLY_AGGREGATABLE in your class definition. For example:

class CMyClass : public CComCoClass< .. >, ...
{
public:
   DECLARE_ONLY_AGGREGATABLE(CMyClass)
   ...
};

ATL Macros and Global Functions

See Also

DECLARE_NOT_AGGREGATABLE


DECLARE_POLY_AGGREGATABLE

DECLARE_POLY_AGGREGATABLE( x )

Parameters

x

[in] The name of the class object you are defining as aggregatable or not aggregatable.

Remarks

Specifies that an instance of CComPolyObject < x > is created when your object is created. During creation, the value of the outer unknown is checked. If it is NULL, IUnknown is implemented for a nonaggregated object. If the outer unknown is not NULL, IUnknown is implemented for an aggregated object.

The advantage of using DECLARE_POLY_AGGREGATABLE is that you avoid having both CComAggObject and CComObject in your module to handle the aggregated and nonaggregated cases. A single CComPolyObject object handles both cases. This means only one copy of the vtable and one copy of the functions exist in your module. If your vtable is large, this can substantially decrease your module size. However, if your vtable is small, using CComPolyObject can result in a slightly larger module size because it is not optimized for an aggregated or nonaggregated object, as are CComAggObject and CComObject.

The DECLARE_POLY_AGGREGATABLE macro is automatically declared in your object if you use the ATL Object Wizard to create a full control or Internet Explorer control.

ATL Macros and Global Functions

See Also

CComPolyObject, CComAggObject, CComObject


DECLARE_PROTECT_FINAL_CONSTRUCT

DECLARE_PROTECT_FINAL_CONSTRUCT( )

Remarks

Protects your object from being deleted if (during FinalConstruct) the internal aggregated object increments the reference count then decrements the count to 0.

ATL Macros and Global Functions


DECLARE_REGISTRY

DECLARE_REGISTRY( class, pid, vpid, nid, flags )

Parameters

class

[in] Included for backward compatibility.

pid

[in] An LPCTSTR that is a version-specific program identifier.

vpid

[in] An LPCTSTR that is a version-independent program identifier.

nid

[in] A UINT that is an index of the resource string in the registry to use as the description of the program.

flags

[in] A DWORD containing the program's threading model in the registry. Must be one of the following values: THREADFLAGS_APARTMENT, THREADFLAGS_BOTH, or AUTPRXFLAG.

Remarks

Enters the standard class registration into the system registry or removes it from the system registry. The standard registration consists of the CLSID, the program ID, the version-independent program ID, description string, and the thread model.

When you create an object or control using the ATL Object Wizard, the wizard automatically implements script-based registry support and adds the DECLARE_REGISTRY_RESOURCEID macro to your files. If you do not want script-based registry support, you need to replace this macro with DECLARE_REGISTRY. DECLARE_REGISTRY only inserts the five basic keys described above into the registry. You must manually write code to insert other keys into the registry.

ATL Macros and Global Functions

See Also

DECLARE_REGISTRY_RESOURCE


DECLARE_REGISTRY_RESOURCE

DECLARE_REGISTRY_RESOURCE( x )

Parameters

x

[in] String identifier of your resource.

Remarks

Gets the named resource containing the registry file and runs the script to either enter objects into the system registry or remove them from the system registry.

When you create an object or control using the ATL Object Wizard, the wizard will automatically implement script-based registry support and add the DECLARE_REGISTRY_RESOURCEID macro, which is similar to DECLARE_REGISTRY_RESOURCE, to your files.

You can statically link with the ATL Registry Component (Registrar) for optimized registry access. To statically link to the Registrar code, add #define _ATL_STATIC_REGISTRY to your stdafx.h.

If you want ATL to substitute replacement values at run time, do not specify the DECLARE_REGISTRY_RESOURCE or DECLARE_REGISTRY_RESOURCEID macro. Instead, create an array of _ATL_REGMAP_ENTRIES structures, where each entry contains a variable placeholder paired with a value to replace the placeholder at run time. Then call CComModule::UpdateRegistryFromResourceD or CComModule::UpdateRegistryFromResourceS, passing the array. This adds all the replacement values in the _ATL_REGMAP_ENTRIES structures to the Registrar's replacement map.

For more information about replaceable parameters and scripting, see the article The ATL Registry Component (Registrar).

ATL Macros and Global Functions

See Also

DECLARE_REGISTRY


DECLARE_REGISTRY_RESOURCEID

DECLARE_REGISTRY_RESOURCEID( x )

Parameters

x

[in] Wizard-generated identifier of your resource.

Remarks

Same as DECLARE_REGISTRY_RESOURCE except that it uses a Wizard-generated UINT to identify the resource, rather than a string name.

When you create an object or control using the ATL Object Wizard, the wizard will automatically implement script-based registry support and add the DECLARE_REGISTRY_RESOURCEID macro to your files.

You can statically link with the ATL Registry Component (Registrar) for optimized registry access. To statically link to the Registrar code, add #define _ATL_STATIC_REGISTRY to your stdafx.h.

If you want ATL to substitute replacement values at run time, do not specify the DECLARE_REGISTRY_RESOURCE or DECLARE_REGISTRY_RESOURCEID macro. Instead, create an array of _ATL_REGMAP_ENTRIES structures, where each entry contains a variable placeholder paired with a value to replace the placeholder at run time. Then call CComModule::UpdateRegistryFromResourceD or CComModule::UpdateRegistryFromResourceS, passing the array. This adds all the replacement values in the _ATL_REGMAP_ENTRIES structures to the Registrar's replacement map.

For more information about replaceable parameters and scripting, see the article The ATL Registry Component (Registrar).

ATL Macros and Global Functions

See Also

DECLARE_REGISTRY, DECLARE_REGISTRY_RESOURCE


DECLARE_VIEW_STATUS

DECLARE_VIEW_STATUS( statusFlags )

Parameters

statusFlags

[in] The VIEWSTATUS flags. See VIEWSTATUS for a list of flags.

Remarks

Place this macro in an ATL ActiveX control's control class to specify the VIEWSTATUS flags to the container.

Example

DECLARE_VIEW_STATUS(VIEWSTATUS_OPAQUE)

ATL Macros and Global Functions


DECLARE_WND_CLASS

DECLARE_WND_CLASS( WndClassName )

Parameters

WndClassName

[in] The name of the new window class. If NULL, ATL will generate a window class name.

Remarks

Place this macro in an ATL ActiveX control's control class. This macro allows you to specify the name of a new window class, whose information will be managed by CWndClassInfo. DECLARE_WND_CLASS defines the new window class by implementing the following static function:

static CWndClassInfo& GetWndClassInfo();

DECLARE_WND_CLASS specifies the following styles for the new window:

  • CS_HREDRAW

  • CS_VREDRAW

  • CS_DBLCLKS

DECLARE_WND_CLASS also specifies the default windows background color. Use the DECLARE_WND_CLASS_EX macro to provide your own styles and background color.

CWindowImpl uses the DECLARE_WND_CLASS macro to create a window based on a new window class. To override this behavior, use the DECLARE_WND_SUPERCLASS macro, or provide your own implementation of the GetWndClassInfo function.

For more information about using windows in ATL, see the article ATL Window Classes.

ATL Macros and Global Functions


DECLARE_WND_CLASS_EX

DECLARE_WND_CLASS_EX( WndClassName, style, bkgnd )

Parameters

WndClassName

[in] The name of the new window class. If NULL, ATL will generate a window class name.

style

[in] The style of the window.

bkgnd

[in] The background color of the window.

Remarks

Place this macro in an ATL ActiveX control's control class. This macro allows you to specify the class parameters of a new window class, whose information will be managed by CWndClassInfo. DECLARE_WND_CLASS_EX defines the new window class by implementing the following static function:

static CWndClassInfo& GetWndClassInfo();

If you want to use the default styles and background color, use the DECLARE_WND_CLASS macro. For more information about using windows in ATL, see the article ATL Window Classes.

ATL Macros and Global Functions

See Also

DECLARE_WND_SUPERCLASS


DECLARE_WND_SUPERCLASS

DECLARE_WND_SUPERCLASS( WndClassName, OrigWndClassName )

Parameters

WndClassName

[in] The name of the window class that will superclass OrigWndClassName. If NULL, ATL will generate a window class name.

OrigWndClassName

[in] The name of an existing window class.

Remarks

Place this macro in an ATL ActiveX control's control class. This macro allows you to specify the name of a window class that will superclass an existing window class. CWndClassInfo manages the information of the superclass.

DECLARE_WND_SUPERCLASS implements the following static function:

static CWndClassInfo& GetWndClassInfo();

By default, CWindowImpl uses the DECLARE_WND_CLASS macro to create a window based on a new window class. By specifying the DECLARE_WND_SUPERCLASS macro in a CWindowImpl-derived class, the window class will be based on an existing class but will use your window procedure. This technique is called superclassing.

Besides using the DECLARE_WND_CLASS and DECLARE_WND_SUPERCLASS macros, you can override the GetWndClassInfo function with your own implementation.

For more information about superclassing, see Window Procedure Superclassing in the Win32 SDK. For more information about using windows in ATL, see the article ATL Window Classes.

ATL Macros and Global Functions


DEFAULT_REFLECTION_HANDLER

DEFAULT_REFLECTION_HANDLER( )

Remarks

Provides a default handler for the child window (control) that will receive reflected messages; the handler will properly pass unhandled messages to DefWindowProc.

ATL Macros and Global Functions

See Also

REFLECT_NOTIFICATIONS, BEGIN_MSG_MAP


END_CATEGORY_MAP

END_CATEGORY_MAP( )

Remarks

Marks the end of the category map.

ATL Macros and Global Functions

See Also

BEGIN_CATEGORY_MAP, IMPLEMENTED_CATEGORY, REQUIRED_CATEGORY


END_COM_MAP

END_COM_MAP( )

Remarks

Ends the definition of your COM interface map.

ATL Macros and Global Functions

See Also

BEGIN_COM_MAP, COM_INTERFACE_ENTRY


END_CONNECTION_POINT_MAP

END_CONNECTION_POINT_MAP( )

Remarks

Marks the end of the connection point map entries. Start your connection point map with the BEGIN_CONNECTION_POINT_MAP macro, add entries for each of your connection points with the CONNECTION_POINT_ENTRY macro, and complete the map with the END_CONNECTION_POINT_MAP macro.

For example:

BEGIN_CONNECTION_POINT_MAP(CMyCPClass)
   CONNECTION_POINT_ENTRY(m_cpInterfaceBeingExposed)
END_CONNECTION_POINT_MAP( )

For more information about connection points in ATL, see the article Connection Points.

ATL Macros and Global Functions


END_EXTENSION_SNAPIN_NODEINFO_MAP

END_EXTENSION_SNAPIN_NODEINFO_MAP( )

Remarks

Marks the end of the snap-in extension data class map. Start your snap-in extension map with the BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP macro, add entries for each of your extension snap-in data types with the EXTENSION_SNAPIN_NODEINFO_ENTRY macro, and complete the map with the END_EXTENSION_SNAPIN_NODEINFO_MAP macro.

For example:

BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP(CMySnapInExtData)
    EXTENSION_SNAPIN_NODEINFO_ENTRY(CMySnapInExtData)
END_EXTENSION_SNAPIN_NODEINFO_MAP()

For more information about developing a snap-in extension using ATL, see the article MMC Snap-In Wizard.

ATL Macros and Global Functions

See Also

BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP, EXTENSION_SNAPIN_NODEINFO_ENTRY, EXTENSION_SNAPIN_DATACLASS


END_MSG_MAP

END_MSG_MAP( )

Remarks

Marks the end of a message map. Always use the BEGIN_MSG_MAP macro to mark the beginning of a message map. Use ALT_MSG_MAP to declare subsequent alternate message maps. The following example shows the default message map and one alternate message map, each containing one handler function:

BEGIN_MSG_MAP(CMyClass)
   MESSAGE_HANDLER(WM_PAINT, OnPaint)
ALT_MSG_MAP(1)
   MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
END_MSG_MAP()

The next example shows two alternate message maps. The default message map is empty.

BEGIN_MSG_MAP(CMyClass)
ALT_MSG_MAP(1)
   MESSAGE_HANDLER(WM_PAINT, OnPaint)
   MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
ALT_MSG_MAP(2)
   MESSAGE_HANDLER(WM_CREATE, OnCreate)
END_MSG_MAP()

Note that there is always exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions


END_OBJECT_MAP

END_OBJECT_MAP( )

Remarks

Marks the end of the map of ATL objects. When CComModule::RegisterServer is called, it updates the system registry for each object in the object map.

Start your object map with the BEGIN_OBJECT_MAP macro, add entries for each object with the OBJECT_ENTRY macro, and complete the map with the END_OBJECT_MAP macro.

ATL Macros and Global Functions


END_SERVICE_MAP

END_SERVICE_MAP( )

Remarks

Marks the end of the service map.

Example

See SERVICE_ENTRY

ATL Macros and Global Functions

See Also

BEGIN_SERVICE_MAP, SERVICE_ENTRY, SERVICE_ENTRY_CHAIN


END_SINK_MAP

END_SINK_MAP( )

Remarks

Declares the end of the event sink map for the composite control.

Example

BEGIN_SINK_MAP(CMyObj)
   SINK_ENTRY(IDC_CIRCCTL1, DISPID_CLICK, OnClick_CircCtrl1)
   SINK_ENTRY(IDC_CIRCCTL2, DISPID_CLICK, OnClick_CircCtrl2)
END_SINK_MAP()

ATL Macros and Global Functions

See Also

Composite Control Fundamentals, BEGIN_SINK_MAP, SINK_ENTRY


END_PROP_MAP

END_PROPERTY_MAP( )

Remarks

Marks the end of the object's property map. When you create an object with the ATL Object Wizard, the wizard will create an empty property map by specifying BEGIN_PROP_MAP followed by END_PROP_MAP.

Example

See BEGIN_PROP_MAP.

ATL Macros and Global Functions

See Also

PROP_ENTRY, PROP_DATA_ENTRY, PROP_ENTRY_EX, PROP_PAGE


END_SNAPINTOOLBARID_MAP

END_SNAPINTOOLBARID_MAP( _class )

Parameters

_class

[in] Specifies the Snap-In object class.

Remarks

Declares the end of the toolbar ID map for the Snap-In object.

See Also

BEGIN_SNAPINTOOLBARID_MAP, SNAPINTOOLBARID_ENTRY


EXTENSION_SNAPIN_DATACLASS

EXTENSION_SNAPIN_DATACLASS( dataClass )

Parameters

dataClass

[in] The data class of the snap-in extension.

Remarks

Adds a data member to the snap-in extension data class for an ISnapInItemImpl-derived class. This class should also be entered into a snap-in extension data class map. Start your snap-in extension data class map with the BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP macro, add entries for each of your snap-in extension data types with the EXTENSION_SNAPIN_NODEINFO_ENTRY macro, and complete the map with the END_EXTENSION_SNAPIN_NODEINFO_MAP macro.

For example:

EXTENSION_SNAPIN_DATACLASS(CMySnapInExtData)
…
BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP(CMySnapInExtData)
    EXTENSION_SNAPIN_NODEINFO_ENTRY(CMySnapInExtData)
END_EXTENSION_SNAPIN_NODEINFO_MAP()

For more information about developing a snap-in extension using ATL, see the article MMC Snap-In Wizard.

ATL Macros and Global Functions

See Also

BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP, EXTENSION_SNAPIN_NODEINFO_ENTRY, END_EXTENSION_SNAPIN_NODEINFO_MAP


EXTENSION_SNAPIN_NODEINFO_ENTRY

EXTENSION_SNAPIN_NODEINFO_ENTRY( dataClass )

Parameters

dataClass

[in] The data class of the snap-in extension.

Remarks

Adds a snap-in extension data class to the snap-in extension data class map. Start your snap-in extension data class map with the BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP macro, add entries for each of your snap-in extension data types with the EXTENSION_SNAPIN_NODEINFO_ENTRY macro, and complete the map with the END_EXTENSION_SNAPIN_NODEINFO_MAP macro.

For example:

BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP(CMySnapInExtData)
    EXTENSION_SNAPIN_NODEINFO_ENTRY(CMySnapInExtData)
END_EXTENSION_SNAPIN_NODEINFO_MAP()

For more information about developing a snap-in extension using ATL, see the article MMC Snap-In Wizard.

ATL Macros and Global Functions

See Also

BEGIN_EXTENSION_SNAPIN_NODEINFO_MAP, END_EXTENSION_SNAPIN_NODEINFO_MAP, EXTENSION_SNAPIN_DATACLASS


IMPLEMENT_BOOL_STOCKPROP

IMPLEMENT_BOOL_STOCKPROP( fname, pname, dispid )

Parameters

fname

[in] Name used to create the names of the put and get methods.

pname

[in] Name used to create the name of the data member that stores the property value.

dispid

[in] The DISPID of the property.

Remarks

Implements stock properties that are boolean values. Same as the IMPLEMENT_STOCKPROP macro except that the get method tests the value of the data member containing the property and returns VARIANT_TRUE or VARIANT_FALSE rather than returning the value. This lets containers that do not interpret all non-zero values as TRUE to use the property. Standard stock properties that are boolean values are Auto Size, Border Visible, Enabled, Tab Stop, and Valid.

IMPLEMENT_BOOL_STOCKPROP creates a data member in your control class for a property, creates a put and get method for the property, and adds code to notify and synchronize with the container if the property changes.

The put and get method names are created by appending fname to put_ and get_. For example, if fname is Enabled, the method names are put_Enabled and get_Enabled.

The data member name is created by appending pname to m_. For example, if pname is bEnabled, the data member is m_bEnabled.

ATL Macros and Global Functions

See Also

CStockPropImpl, IMPLEMENT_BSTR_STOCKPROP, IMPLEMENT_STOCKPROP, CComControl::m_bEnabled, CComControl::m_bAutoSize, CComControl::m_bBorderVisible, CComControl::m_bTabStop, CComControl::m_bValid


IMPLEMENT_BSTR_STOCKPROP

IMPLEMENT_BSTR_STOCKPROP( fname, pname, dispid )

Parameters

fname

[in] Name used to create the names of the put and get methods.

pname

[in] Name used to create the name of the data member that stores the property value.

dispid

[in] The DISPID of the property.

Remarks

Implements text stock properties. Allocates a BSTR data member in your control class and copies pname into the data member. Creates a put and get method for the property, and adds code to notify and synchronize with the container if the property changes. Standard BSTR stock properties are Caption and Text.

The put and get method names are created by appending fname to put_ and get_. For example, if fname is Caption, the method names are put_Caption and get_Caption.

The data member name is created by appending pname to m_. For example, if pname is bstrCaption, the data member is m_bstrCaption.

ATL Macros and Global Functions

See Also

CStockPropImpl, IMPLEMENT_STOCKPROP, IMPLEMENT_BOOL_STOCKPROP, CComControl::m_bstrCaption, CComControl::m_bstrText


IMPLEMENT_STOCKPROP

IMPLEMENT_STOCKPROP( type, fname, pname, dispid )

Parameters

type

[in] The data type of the property.

fname

[in] Name used to create the names of the put and get methods.

pname

[in] Name used to create the name of the data member that stores the property value.

dispid

[in] The DISPID of the property.

Remarks

Creates a data member in your control class for a property, creates a put and get method for the property, and adds code to notify and synchronize with the container if the property changes.

The put and get method names are created by appending fname to put_ and get_. For example, if fname is BorderWidth, the method names are put_BorderWidth and get_BorderWidth.

The data member name is created by appending pname to m_. For example, if pname is nBorderWidth, the data member is m_nBorderWidth.

For text stock properties, use the IMPLEMENT_BSTR_STOCKPROP macro because it will automatically allocate a new string and copy the passed text into it. For boolean stock properties, use the IMPLEMENT_BOOL_STOCKPROP macro.

ATL Macros and Global Functions

See Also

CStockPropImpl


IMPLEMENTED_CATEGORY

IMPLEMENTED_CATEGORY( catID )

Parameters

catID

The ID of the implemented category. A globally unique identifier (GUID). The list below shows a sample of stock categories.

Ability | Category | CatID (GUID)
Simple Frame Site Containment | CATID_SimpleFrameControl [in] | {157083E0-2368-11cf-87B9-00AA006C8166}
Simple Data Binding | CATID_PropertyNotifyControl [in] | {157083E1-2368-11cf-87B9-00AA006C8166}
Advanced Data Binding | CATID_VBDataBound [in] | {157083E2-2368-11cf-87B9-00AA006C8166}
Windowless Controls | CATID_WindowlessObject [in] | {1D06B600-3AE3-11cf-87B9-00AA006C8166}
Internet-Aware Objects | See Internet Aware Objects in the Platform SDK for a sample list.

Remarks

A category that is implemented by the COM object.

When a user installs a COM object, it registers itself as a control in the system registry using its component category ID. This ID identifies the control's abilities and requirements.

For more information about component categories, including a sample list, see What are Component Categories and how do they work? in the Platform SDK.

ATL Macros and Global Functions

See Also

BEGIN_CATEGORY_MAP, REQUIRED_CATEGORY, END_CATEGORY_MAP


InlineIsEqualIUnknown

BOOL InlineIsEqualUnknown( REFGUID rguid1 );

Parameters

rguid1

[in] The GUID to compare to IID_IUnknown.

Remarks

Call this function, for the special case of IUnknown, to generate more efficient code than code generated by a call to InlineIsEqualGUID.

ATL Macros and Global Functions


MESSAGE_HANDLER

MESSAGE_HANDLER( msg, func )

Parameters

msg

[in] The Windows message.

func

[in] The name of the message-handler function.

Remarks

Defines an entry in a message map. MESSAGE_HANDLER maps a Windows message to the specified handler function. For example:

class CMyClass : ...
{
public:
   ...

   BEGIN_MSG_MAP(CMyClass)
      MESSAGE_HANDLER(WM_PAINT, OnPaint)
      ...
   END_MSG_MAP()

   // When a CMyClass object receives a WM_PAINT
   // message, the message is directed to
   // CMyClass::OnPaint for the actual processing.
   LRESULT OnPaint( ... )
   { ... }

};

Any function specified in a MESSAGE_HANDLER macro must defined as follows:

LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);

The message map sets bHandled to TRUE before MessageHandler is called. If MessageHandler does not fully handle the message, it should set bHandled to FALSE to indicate the message needs further processing.

Note Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps with ALT_MSG_MAP. The END_MSG_MAP macro marks the end of the message map. Every message map must have exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

In addition to MESSAGE_HANDLER, you can use COMMAND_HANDLER and NOTIFY_HANDLER to map WM_COMMAND and WM_NOTIFY messages, respectively.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

MESSAGE_RANGE_HANDLER


MESSAGE_RANGE_HANDLER

MESSAGE_RANGE_HANDLER( msgFirst, msgLast, func )

Parameters

msgFirst

[in] Marks the beginning of a contiguous range of messages.

msgLast

[in] Marks the end of a contiguous range of messages.

func

[in] The name of the message-handler function.

Remarks

Similar to MESSAGE_HANDLER, but maps a range of Windows messages to a single handler function.

ATL Macros and Global Functions

See Also

COMMAND_RANGE_HANDLER, NOTIFY_RANGE_HANDLER


NOTIFY_CODE_HANDLER

NOTIFY_CODE_HANDLER( cd, func )

Parameters

cd

[in] The notification code.

func

[in] The name of the message-handler function.

Remarks

Similar to NOTIFY_HANDLER, but maps a WM_NOTIFY message based only on the notification code.

ATL Macros and Global Functions

See Also

NOTIFY_ID_HANDLER, NOTIFY_RANGE_HANDLER, COMMAND_CODE_HANDLER, MESSAGE_HANDLER


NOTIFY_HANDLER

NOTIFY_HANDLER( id, cd, func )

Parameters

id

[in] The identifier of the control sending the message.

code

[in] The notification code.

func

[in] The name of the message-handler function.

Remarks

Defines an entry in a message map. NOTIFY_HANDLER maps a WM_NOTIFY message to the specified handler function, based on the notification code and the control identifier. For example:

class CMyClass : ...
{
public:
   ...

   BEGIN_MSG_MAP(CMyClass)
      NOTIFY_HANDLER(IDC_MYCTL, NM_CLICK, OnClick)
      ...
   END_MSG_MAP()

   // When a CMyClass object receives a WM_NOTIFY
   // message identified by IDC_MYCTL and NM_CLICK,
   // the message is directed to CMyClass::OnClick
   // for the actual processing.
   LRESULT OnClick( ... )
   { ... }

};

Any function specified in a NOTIFY_HANDLER macro must defined as follows:

LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);

The message map sets bHandled to TRUE before NotifyHandler is called. If NotifyHandler does not fully handle the message, it should set bHandled to FALSE to indicate the message needs further processing.

Note Always begin a message map with BEGIN_MSG_MAP. You can then declare subsequent alternate message maps with ALT_MSG_MAP. The END_MSG_MAP macro marks the end of the message map. Every message map must have exactly one instance of BEGIN_MSG_MAP and END_MSG_MAP.

In addition to NOTIFY_HANDLER, you can use MESSAGE_HANDLER to map a WM_NOTIFY message without regard to an identifier or code. In this case, MESSAGE_HANDLER(WM_NOTIFY, OnHandlerFunction) will direct all WM_NOTIFY messages to OnHandlerFunction.

For more information about using message maps in ATL, see Message Maps in the article "ATL Window Classes."

ATL Macros and Global Functions

See Also

NOTIFY_ID_HANDLER, NOTIFY_CODE_HANDLER, NOTIFY_RANGE_HANDLER, COMMAND_HANDLER


NOTIFY_ID_HANDLER

NOTIFY_ID_HANDLER( id, func )

Parameters

id

[in] The identifier of the control sending the message.

func

[in] The name of the message-handler function.

Remarks

Similar to NOTIFY_HANDLER, but maps a WM_NOTIFY message based only on the control identifier.

ATL Macros and Global Functions

See Also

NOTIFY_CODE_HANDLER, NOTIFY_RANGE_HANDLER, COMMAND_ID_HANDLER, MESSAGE_HANDLER


NOTIFY_RANGE_HANDLER

NOTIFY_RANGE_HANDLER( idFirst, idLast, func )

Parameters

idFirst

[in] Marks the beginning of a contiguous range of WM_NOTIFY messages.

idLast

[in] Marks the end of a contiguous range of WM_NOTIFY messages.

func

[in] The name of the message-handler function.

Remarks

Similar to NOTIFY_HANDLER, but maps a range of WM_NOTIFY messages to a single handler function. This range is based on the identifier of the control sending the message.

ATL Macros and Global Functions

See Also

NOTIFY_ID_HANDLER, NOTIFY_CODE_HANDLER, COMMAND_RANGE_HANDLER, MESSAGE_RANGE_HANDLER


OBJECT_ENTRY

OBJECT_ENTRY( clsid, class )

Parameters

clsid

[in] The CLSID of the ATL object to be entered into the object map.

class

[in] The name of the class of the ATL object.

Remarks

Enters the function pointers of the creator class and class-factory creator class CreateInstance functions for this object into the ATL object map. When CComModule::RegisterServer is called, it updates the system registry for each object in the object map.

Start your object map with the BEGIN_OBJECT_MAP macro, add entries for each object with the OBJECT_ENTRY macro, and complete the map with the END_OBJECT_MAP macro.

ATL Macros and Global Functions

See Also

OBJECT_ENTRY_NON_CREATEABLE, DECLARE_OBJECT_DESCRIPTION


OBJECT_ENTRY_NON_CREATEABLE

OBJECT_ENTRY_NON_CREATEABLE( class )

Parameters

class

[in] The class of the object to be registered and initialized.

Remarks

Allows you to specify that an object should be registered and initialized, but it should not be createable via CoCreateInstance.

ATL Macros and Global Functions

See Also

OBJECT_ENTRY


PROP_DATA_ENTRY

PROP_DATA_ENTRY( szDesc, member, vt )

Parameters

szDesc

[in] The property description.

member

[in] The data member containing the extent; for example, m_sizeExtent.

vt

[in] Specifies the VARIANT type of the property.

Remarks

Call this function to cause the specified data member to be persisted. In the following example, the extent of the object (M_sizeExtent) is being persisted.

When you create an ActiveX control, the wizard inserts this macro after the property map macro BEGIN_PROP_MAP and before the property map macro END_PROPERTY_MAP.

Example

BEGIN_PROP_MAP(CMyControl)
PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4)
PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4)
END_PROP_MAP()

ATL Macros and Global Functions


PROP_ENTRY

PROP_ENTRY( szDesc, dispid, clsid )

Parameters

szDesc

[in] The property description.

dispid

[in] The property's DISPID.

clsid

[in] The CLSID of the associated property page. Use the special value CLSID_NULL for a property that does not have an associated property page.

Remarks

Use this macro to enter a property description, property DISPID, and property page CLSID into the object's property map. The BEGIN_PROP_MAP macro marks the beginning of the property map; the END_PROPERTY_MAP macro marks the end.

Example

See BEGIN_PROP_MAP.

ATL Macros and Global Functions

See Also

PROP_ENTRY_EX, PROP_PAGE


PROP_ENTRY_EX

PROP_ENTRY_EX( szDesc, dispid, clsid, iidDispatch )

Parameters

szDesc

[in] The property description.

dispid

[in] The property's DISPID.

clsid

[in] The CLSID of the associated property page. Use the special value CLSID_NULL for a property that does not have an associated property page.

iidDispatch

[in] The IID of the dual interface defining the property.

Remarks

Similar to PROP_ENTRY, but allows you specify a particular IID if your object supports multiple dual interfaces.

The BEGIN_PROP_MAP macro marks the beginning of the property map; the END_PROPERTY_MAP macro marks the end.

Example

The following example groups entries for IMyDual1 followed by an entry for IMyDual2. Grouping by dual interface will improve performance.

BEGIN_PROP_MAP( CMyClass )
   PROP_ENTRY_EX( "Caption", DISPID_CAPTION,
                  CLSID_CMyProps, IID_IMyDual1 )
   PROP_ENTRY_EX( "Enabled", DISPID_ENABLED,
                  CLSID_CMyProps, IID_IMyDual1 )
   PROP_ENTRY_EX( "Width", DISPID_WIDTH,
                  CLSID_CMyProps, IID_IMyDual2 )
END_PROPERTY_MAP( )

ATL Macros and Global Functions

See Also

PROP_PAGE


PROP_PAGE

PROP_PAGE( clsid )

Parameters

clsid

[in] The CLSID of a property page.

Remarks

Use this macro to enter a property page CLSID into the object's property map. PROP_PAGE is similar to PROP_ENTRY, but does not require a property description or DISPID.

Note If you have already entered a CLSID with PROP_ENTRY or PROP_ENTRY_EX, you do not need to make an additional entry with PROP_PAGE.

The BEGIN_PROP_MAP macro marks the beginning of the property map; the END_PROPERTY_MAP macro marks the end.

Example

BEGIN_PROPERTY_MAP( CMyClass )
   PROP_PAGE( CLSID_CMyClassPropPage1 )
   PROP_PAGE( CLSID_CMyClassPropPage2 )
END_PROPERTY_MAP( )

ATL Macros and Global Functions


REFLECT_NOTIFICATIONS

REFLECT_NOTIFICATIONS( )

Remarks

Reflects notification messages back to the child window (control) that sent them. Specify this macro as part of your message map.

ATL Macros and Global Functions

See Also

DEFAULT_REFLECTION_HANDLER, BEGIN_MSG_MAP


REQUIRED_CATEGORY

REQUIRED_CATEGORY( catID )

Parameters

catID

The ID of the required category. A globally unique identifier (GUID). The list below shows a sample of the stock categories.

Ability | Category | CatID (GUID)
Simple Frame Site Containment | CATID_SimpleFrameControl [in] | {157083E0-2368-11cf-87B9-00AA006C8166}
Simple Data Binding | CATID_PropertyNotifyControl [in] | {157083E1-2368-11cf-87B9-00AA006C8166}
Advanced Data Binding | CATID_VBDataBound [in] | {157083E2-2368-11cf-87B9-00AA006C8166}
Windowless Controls | CATID_WindowlessObject [in] | {1D06B600-3AE3-11cf-87B9-00AA006C8166}
Internet-Aware Objects | See Internet Aware Objects in the Platform SDK for a sample list.

Remarks

A category that the COM object requires of its container.

When a user installs a COM object, it registers itself as a control in the system registry using its component category ID. This ID identifies the control's abilities and requirements. For example, the COM object may require that a container support data binding. If the container does not support the required feature, the container can refuse to host the COM object.

For more information about component categories, including a sample list, see What are Component Categories and how do they work? in the Platform SDK.

Example

See SERVICE_ENTRY

ATL Macros and Global Functions

See Also

BEGIN_CATEGORY_MAP, IMPLEMENTED_CATEGORY, END_CATEGORY_MAP


SERVICE_ENTRY

SERVICE_ENTRY( SID )

Parameters

SID

The service ID.

Remarks

Indicates that the object supports the service id specified by SID.

ATL Macros and Global Functions

See Also

SERVICE_ENTRY_CHAIN, BEGIN_SERVICE_MAP, END_SERVICE_MAP


SERVICE_ENTRY_CHAIN

SERVICE_ENTRY_CHAIN( punk )

Parameters

punk

A pointer to the IUnknown interface to which to chain.

Remarks

Instructs IServiceProviderImpl::QueryService to chain to the object specified by punk.

Example

BEGIN_SERVICE_MAP(CMyService)
SERVICE_ENTRY(SID_SBindHost)  // This object supports the SBindHost service
SERVICE_ENTRY_CHAIN(m_spClientSite) // Everything else, just ask the container
END_SERVICE_MAP( )

ATL Macros and Global Functions

See Also

SERVICE_ENTRY, BEGIN_SERVICE_MAP, END_SERVICE_MAP


SINK_ENTRY

SINK_ENTRY( id, dispid, fn )

Parameters

id

[in] Identifies the control.

dispid

[in] Identifies the specified event.

fn

[in] Name of the event handler function. This function must use the _stdcall calling convention.

Remarks

Declares the handler function (fn) for the specified event (dispid), of the control identified by id.

Example

BEGIN_SINK_MAP(CMyObj)
   SINK_ENTRY(IDC_CIRCCTL1, DISPID_CLICK, OnClick_CircCtrl1)
   SINK_ENTRY(IDC_CIRCCTL2, DISPID_CLICK, OnClick_CircCtrl2)
END_SINK_MAP()

ATL Macros and Global Functions

See Also

Composite Control Fundamentals, BEGIN_SINK_MAP, SINK_ENTRY_EX


SINK_ENTRY_EX

SINK_ENTRY_EX( id, iid, dispid, fn )

Parameters

id

[in] Identifies the control.

iid

[in] Identifies the dispatch interface.

dispid

[in] Identifies the specified event.

fn

[in] Name of the event handler function. This function must use the _stdcall calling convention.

Remarks

Declares the handler function (fn) for the specified event (dispid), of the dispatch interface (iid), for the control identified by id.

Example

BEGIN_SINK_MAP(CMyObj)
   SINK_ENTRY_EX(IDC_CIRCCTL1, CIRCLib::DIID__CircEvents, DISPID_CLICK,
      OnClick_CircCtrl1)
   SINK_ENTRY_EX(IDC_CIRCCTL2, CIRCLib::DIID__CircEvents, DISPID_CLICK,
      OnClick_CircCtrl2)
END_SINK_MAP()

ATL Macros and Global Functions

See Also

Composite Control Fundamentals, BEGIN_SINK_MAP, SINK_ENTRY


SNAPINMENUID

SNAPINMENUID( id )

Parameters

id

[in] Identifies the context menu of the Snap-In object.

Remarks

Use this macro to declare the context menu resource of the Snap-In object.

ATL Macros and Global Functions


SNAPINTOOLBARID_ENTRY

SNAPINTOOLBARID_ENTRY( id )

Parameters

id

[in] Identifies the toolbar control.

Remarks

Use this macro to enter a toolbar ID into the Snap-In object's toolbar ID map. The BEGIN_SNAPINTOOLBARID_MAP macro marks the beginning of the property map; the END_SNAPINTOOLBARID_MAP macro marks the end.

ATL Macros and Global Functions


WM_FORWARDMSG

WM_FORWARDMSG

WPARAM - DWORD dwUserData

LPARAM - LPMSG pMsg

Return Value

Nonzero if the message was processed, zero if not.

Parameters

DWORD dwUserData = (DWORD)wParam

Data defined by user.

LPMSG pMsg = (LPMSG)lParam

A pointer to a MSG structure that contains information about a message.

Remarks

WM_FORWARDMSG is defined by ATL. Use WM_FORWARDMSG to forward a message received by a window to another window for processing. In the following example, hWndOther represents the other window that receives this message.

Example

LRESULT CMyWindow::OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
   MSG msg = { m_hWnd, uMsg, wParam, lParam, 0, { 0, 0 } };
   LRESULT lRet = SendMessage(hWndOther, 0, (LPARAM)&msg);
   if(lRet == 0)   // not handled
      bHandled = FALSE;
   return 0;
}

ATL Macros and Global Functions


String Conversion Macros

The string conversion macros discussed here are valid for both ATL and MFC. For more information on MFC string conversion, see TN059: Using MFC MBCS/Unicode Conversion Macros and MFC Macros and Globals.

The syntax of the string-conversion macros is:

MACRONAME( string_address )

For example:

A2W(lpa)

In the macro names, the source string type is on the left (for example, A) and the destination string type is on the right (for example, W). A stands for LPSTR, OLE stands for LPOLESTR, T stands for LPTSTR, and W stands for LPWSTR.

Thus, A2W converts an LPSTR to an LPWSTR, OLE2T converts an LPOLESTR to an LPTSTR, and so on.

The destination string is created using _alloca, except when the destination type is BSTR. Using _alloca allocates memory off the stack, so that when your function returns, it is automatically cleaned up.

If there is a C in the macro name, the macro converts to a const string. For example, W2CA converts an LPWSTR to an LPCSTR.

Note When using an ATL string conversion macro, specify the USES_CONVERSION macro at the beginning of your function in order to avoid compiler errors. For example:

void func( LPSTR lpsz )
{
   USES_CONVERSION;
   ...
   LPWSTR x = A2W(lpsz)
   // Do something with x
   ...
}

The behavior of the ATL string conversion macros depends on the compiler directive in effect, if any. If the source and destination types are the same, no conversion takes place. Compiler directives change T and OLE as follows:

Compiler directive in effect | T becomes | OLE becomes
none | A | W
_UNICODE | W | W
OLE2ANSI | A | A
_UNICODE and OLE2ANSI | W | A

The following table lists the ATL string conversion macros.

ATL String Conversion Macros

A2BSTR | OLE2A | T2A | W2A
A2COLE | OLE2BSTR | T2BSTR | W2BSTR
A2CT | OLE2CA | T2CA | W2CA
A2CW | OLE2CT | T2COLE | W2COLE
A2OLE | OLE2CW | T2CW | W2CT
A2T | OLE2T | T2OLE | W2OLE
A2W | OLE2W | T2W | W2T

ATL Macros and Global Functions

See Also

DEVMODE and TEXTMETRIC String Conversion Macros


DEVMODE and TEXTMETRIC String Conversion Macros

These macros create a copy of a DEVMODE or TEXTMETRIC structure and convert the strings within the new structure to a new string type. The macros allocate memory on the stack for the new structure and return a pointer to the new structure.

The syntax is:

MACRONAME( address_of_structure )

For example:

DEVMODEA2W(lpa)

and

TEXTMETRICA2W(lptma)

In the macro names, the string type in the source structure is on the left (for example, A) and the string type in the destination structure is on the right (for example, W). A stands for LPSTR, OLE stands for LPOLESTR, T stands for LPTSTR, and W stands for LPWSTR.

Thus, DEVMODEA2W copies a DEVMODE structure with LPSTR strings into a DEVMODE structure with LPWSTR strings, TEXTMETRICOLE2T copies a TEXTMETRIC structure with LPOLESTR strings into a TEXTMETRIC structure with LPTSTR strings, and so on.

The two strings converted in the DEVMODE structure are the device name (dmDeviceName) and the form name (dmFormName). The DEVMODE string conversion macros also update the structure size (dmSize).

The four strings converted in the TEXTMETRIC structure are the first character (tmFirstChar), the last character (tmLastChar), the default character (tmDefaultChar), and the break character (tmBreakChar).

The behavior of the DEVMODE and TEXTMETRIC string conversion macros depends on the compiler directive in effect, if any. If the source and destination types are the same, no conversion takes place. Compiler directives change T and OLE as follows:

Compiler directive in effect | T becomes | OLE becomes
none | A | W
_UNICODE | W | W
OLE2ANSI | A | A
_UNICODE and OLE2ANSI | W | A

The following table lists the DEVMODE and TEXTMETRIC string conversion macros.

DEVMODE and TEXTMETRIC String Conversion Macros

DEVMODEA2W | TEXTMETRICA2W
DEVMODEOLE2T | TEXTMETRICOLE2T
DEVMODET2OLE | TEXTMETRICT2OLE
DEVMODEW2A | TEXTMETRICW2A

ATL Macros and Global Functions

See Also

String Conversion Macros


Obsolete ATL Topics

The following items are now obsolete in ATL:

Classes

  • CComConnectionPoint

  • CComConnectionPointContainerImpl

  • CComDualImpl

  • CComDynamicArrayCONNECTDATA

  • CComISupportErrorInfoImpl

  • CComProvideClassInfo2Impl

  • CComStaticArrayCONNECTDATA

Methods, Macros, and Global Functions

  • CComModule::UpdateRegistryFromResource

  • BEGIN_PROPERTY_MAP

  • COM_INTERFACE_ENTRY_IMPL

  • COM_INTERFACE_ENTRY_IMPL_IID

  • DECLARE_STATIC_REGISTRY_RESOURCE

  • DECLARE_STATIC_REGISTRY_RESOURCEID

  • END_PROPERTY_MAP

  • RELEASE_AND_DESTROY


CComConnectionPoint

Beginning with ATL 2.0, the CComConnectionPoint class is obsolete and is replaced by IConnectionPointImpl.

Obsolete ATL Topics


CComConnectionPointContainerImpl

Beginning with ATL 2.0, the CComConnectionPointContainerImpl class is obsolete and is replaced by IConnectionPointContainerImpl. For backward compatibility, ATL defines the following:

#define CComConnectionPointContainerImpl
        IConnectionPointContainerImpl

Obsolete ATL Topics


CComDualImpl

Beginning with ATL 2.0, the CComDualImpl class name is obsolete and is replaced by IDispatchImpl. For backward compatibility, ATL defines the following:

#define CComDualImpl IDispatchImpl

Obsolete ATL Topics


CComDynamicArrayCONNECTDATA

Beginning with ATL 2.0, the CComDynamicArrayCONNECTDATA class is obsolete and is replaced by CComDynamicUnkArray.

Obsolete ATL Topics


COM_INTERFACE_ENTRY_IMPL

Beginning with ATL 3.0, the COM_INTERFACE_ENTRY_IMPL macro is obsolete and is replaced by COM_INTERFACE_ENTRY.

Obsolete ATL Topics


COM_INTERFACE_ENTRY_IMPL_IID

Beginning with ATL 3.0, the COM_INTERFACE_ENTRY_IMPL_IID macro is obsolete and is replaced by COM_INTERFACE_ENTRY_IID.

Obsolete ATL Topics


CComISupportErrorInfoImpl

Beginning with ATL 2.0, the CComISupportErrorInfoImpl class name is obsolete and is replaced by ISupportErrorInfoImpl. For backward compatibility, ATL defines the following:

#define CComISupportErrorInfoImpl
        ISupportErrorInfoImpl

Obsolete ATL Topics


CComModule::UpdateRegistryFromResource

Beginning with ATL 2.0, the CComModule::UpdateRegistryFromResource method is obsolete and is replaced by CComModule::UpdateRegistryFromResourceD. For backward compatibility, ATL defines the following:

#define UpdateRegistryFromResource
        UpdateRegistryFromResourceD

Obsolete ATL Topics


CComProvideClassInfo2Impl

Beginning with ATL 2.0, the CComProvideClassInfo2Impl class name is obsolete and is replaced by IProvideClassInfo2Impl. For backward compatibility, ATL defines the following:

#define CComProvideClassInfo2Impl
        IProvideClassInfo2Impl

Obsolete ATL Topics


CComStaticArrayCONNECTDATA

Beginning with ATL 2.0, the CComStaticArrayCONNECTDATA class is obsolete and is replaced by CComUnkArray.

Obsolete ATL Topics


BEGIN_PROPERTY_MAP

Beginning with ATL 3.0, BEGIN_PROPERTY_MAP is replaced by BEGIN_PROP_MAP. BEGIN_PROPERTY_MAP could be used only with controls, and it automatically saved out and read in the extent, or dimensions, of the map. This limitation no longer exists in ATL 3.0, and no need exists for read in the property map’s extent.

For backward compatibility, ATL defines the following:

#define BEGIN_PROPERTY_MAP(theClass) \
   typedef _ATL_PROP_NOTIFY_EVENT_CLASS __ATL_PROP_NOTIFY_EVENT_CLASS; \
   typedef theClass _PropMapClass; \
   static ATL_PROPMAP_ENTRY* GetPropertyMap()\
   {\
      static ATL_PROPMAP_ENTRY pPropMap[] = \
      { \
         {OLESTR("_cx"), 0, &CLSID_NULL, NULL, offsetof(_PropMapClass, m_sizeExtent.cx), sizeof(long), VT_UI4}, \
         {OLESTR("_cy"), 0, &CLSID_NULL, NULL, offsetof(_PropMapClass, m_sizeExtent.cy), sizeof(long), VT_UI4},

Obsolete ATL Topics


DECLARE_STATIC_REGISTRY_RESOURCE

Beginning with ATL 2.0, the DECLARE_STATIC_REGISTRY_RESOURCE macro is obsolete. To statically link to the Registrar, you specify the #define _ATL_STATIC_REGISTRY statement in stdafx.h and use the DECLARE_REGISTRY_RESOURCE macro.

For backward compatibility, ATL defines the following:

#define DECLARE_STATIC_REGISTRY_RESOURCE(x)
        DECLARE_REGISTRY_RESOURCE(x)

Obsolete ATL Topics


DECLARE_STATIC_REGISTRY_RESOURCEID

Beginning with ATL 2.0, the DECLARE_STATIC_REGISTRY_RESOURCEID macro is obsolete. To statically link to the Registrar, you specify the #define _ATL_STATIC_REGISTRY statement in stdafx.h and use the DECLARE_REGISTRY_RESOURCEID macro.

For backward compatibility, ATL defines the following:

#define DECLARE_STATIC_REGISTRY_RESOURCEID(x)
        DECLARE_REGISTRY_RESOURCEID(x)

Obsolete ATL Topics


END_PROPERTY_MAP

Beginning with ATL 3.0, END_PROPERTY_MAP is replaced by END_PROP_MAP. See BEGIN_PROPERTY_MAP for more information about the update.

For backward compatibility, ATL defines the following:

#define END_PROPERTY_MAP() \
         {NULL, 0, NULL, &IID_NULL, 0, 0, 0} \
      }; \
      return pPropMap; \
   }

Obsolete ATL Topics


RELEASE_AND_DESTROY

Beginning with ATL 2.0, the RELEASE_AND_DESTROY macro is obsolete.

Obsolete ATL Topics


OLE DB Templates

The OLE DB Templates wrap the OLE DB data access technology. Visual C++ includes consumer templates and provider templates.
Consumer Articles Background and how-to-use information.
Consumer Reference Reference information about the classes.
Provider Articles Background and how-to-use information.
Provider Reference Reference information about the classes.
What else do you want to do?
Look at some OLE DB Templates samples.
Read an overview that compares consumer and provider applications.

Interesting home pages


Overview of OLE DB Templates

The OLE DB Templates make the high-performance OLE DB database technology easier to use by providing classes that implement many of the commonly used OLE DB interfaces. Along with this template library comes wizard support for creating OLE DB starter applications.

This template library contains two parts:

  • OLE DB Consumer Templates Used to implement an OLE DB client (consumer) application.

  • OLE DB Provider Templates Used to implement an OLE DB server (provider) application.

To use the OLE DB Templates, you should be familiar with C++ templates, COM, and the OLE DB interfaces. If you aren't familiar with OLE DB, see the OLE DB Programmer's Reference.

What do you want to do?

  • Read the articles on the OLE DB Consumer Templates or the OLE DB Provider Templates.

  • Create an OLE DB consumer or an OLE DB provider.

  • See the list of OLE DB consumer classes or OLE DB provider classes.

  • See the list of OLE DB samples.

  • Read the FAQs on using the OLE DB Consumer Templates or the OLE DB Provider Templates.


Using the OLE DB Consumer Templates

The OLE DB Consumer Templates support the OLE DB version 1.1 specification. The Consumer Templates minimize the amount of code you must write in order to implement a level-0 compliant OLE DB consumer. The templates provide:

  • Easy access to OLE DB features and easy integration with ATL and MFC.

  • An easy binding model for database parameters and columns.

  • Native C/C++ data types for OLE DB programming.

To use the OLE DB Templates, you should be familiar with C++ templates, COM, and the OLE DB interfaces. If you are not familiar with OLE DB, refer to the OLE DB Programmer's Reference.

What would you like to know more about?

The OLE DB Consumer Templates Architecture

Creating an OLE DB Consumer

Common OLE DB Consumer Scenarios (Examples)

Implementing an OLE DB Template Consumer

See Also

FAQ: Using the OLE DB Consumer Templates, Overview of OLE DB Templates


The OLE DB Consumer Templates Architecture

The following figure shows the architecture of the OLE DB Consumer Templates.

The OLE DB Templates support the existing OLE DB object model, rather than adding a new object model. The top-layer classes in the OLE DB Consumer Templates parallel the components defined in the OLE DB specification. The design of the OLE DB Consumer Templates includes advanced features such as multiple accessors on a rowset. The use of templates and multiple inheritance makes the library small and flexible.

The topics covered in this section are:

  • General data source support

  • Rowset and binding support

  • Table and command support

  • User records

Back to Using the OLE DB Consumer Templates


General Data Source Support

The following figure shows the three classes that support connecting to and accessing a data source. Each class is based on a standard OLE DB component implementation, as described in the OLE DB Programmer's Reference.

The classes are:

  • CDataSource Represents the data source component. It manages the connection to a data source.

  • CEnumerator Provides a way to select a provider from a list of available providers. It is equivalent to the SQLBrowseConnect or SQLDriverConnect function.

  • CSession Handles transactions. For each session, you can create rowsets, commands, and other objects.

Back to the OLE DB Consumer Template Architecture


OLE DB Rowset and Binding Support

To set and retrieve data, OLE DB Templates use an accessor and a rowset through the CAccessorRowset class, as shown in the following figure. This class can handle multiple accessors of different types.

Accessor Types

All accessors derive from CAccessorBase. CAccessorBase provides both parameter and column binding.

There are four accessor types and three rowset types, which are shown in the following figure.

  • CAccessor Use this accessor when you know the structure of the database source at design time. CAccessor statically binds a database record, which contains the buffer, to the data source.

  • CDynamicAccessor Use this accessor when you do not know the structure of the database at design time. CDynamicAccessor calls IColumnsInfo::GetColumnInfo to get the database column information. It creates and manages an accessor and the buffer.

  • CDynamicParameterAccessor Use this accessor to handle unknown command types. When you prepare the commands, CDynamicParameterAccessor can get parameter information from the ICommandWithParameters interface, if the provider supports ICommandWithParameters.

  • CManualAccessor With this class, you can use whatever data types you want as long as the provider can convert the type. It handles both result columns and command parameters.

The following table summarizes the four accessor types.

Accessor type | Dynamic | Params | Buffer | Multiple accessors
CAccessor | No | Yes | User | Yes
CDynamicAccessor | Yes | No | OLE DB Templates | No
CDynamicParameterAccessor | Yes | Yes | OLE DB Templates | No
CManualAccessor | Yes | Yes | User | No

Rowset Types

The OLE DB Templates support three kinds of rowsets (see the preceding figure): single rowsets (implemented by CRowset), bulk rowsets (implemented by CBulkRowset), and array rowsets (implemented by CArrayRowset). Single rowsets fetch a single row handle when MoveNext is called. Bulk rowsets can fetch multiple row handles. Array rowsets are rowsets that can be accessed using array syntax.

Back to the OLE DB Consumer Template Architecture


OLE DB Table and Command Support

To open the rowset, execute commands, and initiate bindings, you need to create instances of CTable and CCommand. These classes derive from CAccessorRowset as shown in the following figure.

The CTable class supports accessing data sources without commands. This simple class opens a table on a data source using a table name that you specify.

For data sources that support commands, you can use the CCommand class instead. To execute a command, call Open on this class. As an alternative, you can call Prepare to prepare a command that you want to execute more than once.

CCommand has three template arguments: an accessor class, a rowset class, and CNoMultipleResults (by default) or CMultipleResults. If you specify CMultipleResults, the CCommand class will support the IMultipleResults interface and handle multiple rowsets. The DBVIEWER sample shows how to handle the multiple results.

Back to the OLE DB Consumer Template Architecture


OLE DB User Records

To use a static accessor, your consumer must have a user record. The user record is a C++ class that contains data elements to handle input or output. The ATL Object Wizard generates a user record for your consumer. You can add methods to the user record for optional tasks like handling commands.

The following code shows a sample record that handles commands. In the user record, BEGIN_OLUMN_MAP represents a data rowset passed to the consumer from a provider. BEGIN_PARAM_MAP represents a set of command parameters. This example uses a CCommand class to handle the command parameters. The data members in the map entries represent offsets into one contiguous block of memory for each instance of the class. The COLUMN_ENTRY macros correspond to the PROVIDER_COLUMN_ENTRY macros on the provider side.

For more information on the COLUMN_MAP and PARAM_MAP macros, see Macros for OLE DB Consumer Templates.

class CArtists
{
public:
// Data Elements
   CHAR m_szFirstName[20];
   CHAR m_szLastName[30];
   short m_nAge;

// output binding map
BEGIN_COLUMN_MAP(CArtists)
   COLUMN_ENTRY(1, m_szFirstName)
   COLUMN_ENTRY(2, m_szLastName)
   COLUMN_ENTRY(3, m_nAge)
END_COLUMN_MAP()

// parameter binding map
BEGIN_PARAM_MAP(CArtists)
   COLUMN_ENTRY(1, m_nAge)
END_PARAM_MAP
};

The following example shows the user record modified to support multiple accessors on the rowset. Instead of BEGIN_COLUMN_MAP and END_COLUMN_MAP, it uses BEGIN_ACCESSOR_MAP and BEGIN_ACCESSOR for each accessor. The BEGIN_ACCESSOR macro specifies the accessor number (offset from zero) and whether the accessor is an autoaccessor. Autoaccessors call GetData to retrieve data automatically on a call to MoveNext. Non-automatic accessors require you to explicitly retrieve the data. Use a non-automatic accessor if you are binding to a large data field (like a bitmap image) that you may not want to retrieve for every record.

class CMultiArtists
{
public:
// Data Elements
   CHAR m_szFirstName[20];
   CHAR m_szLastName[30];
   short m_nAge;

// output binding map
BEGIN_ACCESSOR_MAP(CMultiArtists, 2)
   BEGIN_ACCESSOR(0, true)
    COLUMN_ENTRY(1, m_szFirstName)
    COLUMN_ENTRY(2, m_szLastName)
   END_ACCESSOR()
   BEGIN_ACCESSOR(1, false) // not an auto accessor
    COLUMN_ENTRY(3, m_nAge)
   END_ACCESSOR()
END_ACCESSOR_MAP()
};

Back to the OLE DB Consumer Template Architecture


Creating an OLE DB Consumer

You can use the ATL COM AppWizard and ATL Object Wizard to generate an OLE DB Template consumer.

To create an ATL project for an OLE DB consumer

  1. From the File menu, choose New. The New dialog box appears.

  2. On the Projects tab, choose ATL COM AppWizard.

    Name the project on the Projects tab, then click OK. The ATL COM AppWizard appears.

  3. In the ATL COM AppWizard, choose a project type.

  4. Click Finish and OK.

Next, use the ATL Object Wizard.

To use the ATL Object Wizard

  1. From the Insert menu, choose New ATL Object. The ATL Object Wizard appears.

  2. In the left pane, choose Data Access. The Consumer icon appears in the right pane.

  3. Select the Consumer icon and click Next. The ATL Object Wizard Properties dialog box appears.

Use the ATL Object Wizard to set properties for your consumer.

To set consumer properties using the ATL Object Wizard

  1. In the ATL Object Wizard Properties dialog box, click the Select Datasource button. The Create New Datalink dialog box appears.

  2. In the Create New Datalink dialog box, select an OLE DB Provider and appropriate options, including:
    • Location and data source for the data to be used by the Provider.

    • Logon ID and password for your data source.

    After selecting your provider and other settings, click Test Connection to verify the selections made on the previous dialog box pages. If the Results box reports PASSED, click Finish to create the data link. The Select Database Table dialog box appears.

  3. In the Select Database Table dialog box, use the tree control to select a table, query, or stored procedure and click OK. You return to the ATL Object Wizard Properties dialog box.

  4. The dialog box fills in the names for the Short Name, Class, Accessor, and .H File. The last four are based on the short name. You can edit these names if desired.

  5. The wizard creates a CCommand-based consumer by default. If you prefer a CTable-based consumer, select the Table button.

  6. Choose Change, Insert, and Delete to support the changing, inserting, and deleting of records in the rowset, if required.

  7. Click OK.

The wizard generators an accessor class and a command (or table) class, as shown in the sample output below. The command class contains code to open the data source and rowset you specified in the wizard. The accessor class contains a column map for the database table you selected.

// Product.H : Declaration of the CProduct class
#ifndef __PRODUCT_H_
#define __PRODUCT_H_
class CProductAccessor
{
public:
   LONG m_ProductID;   // Number automatically assigned to new product.
   TCHAR m_ProductName[41];   // Number automatically assigned to new product.
   LONG m_SupplierID;   // Same entry as in Suppliers table.
   LONG m_CategoryID;   // Same entry as in Categories table.
   TCHAR m_QuantityPerUnit[21];   // (e.g., 24-count case, 1-liter bottle).
   DB_NUMERIC m_UnitPrice;   // (e.g., 24-count case, 1-liter bottle).
   SHORT m_UnitsInStock;   // (e.g., 24-count case, 1-liter bottle).
   SHORT m_UnitsOnOrder;   // (e.g., 24-count case, 1-liter bottle).
   SHORT m_ReorderLevel;   // Minimum units to maintain in stock.
   VARIANT_BOOL m_Discontinued;   // Yes means item is no longer available.

BEGIN_COLUMN_MAP(CProductAccessor)
   COLUMN_ENTRY(1, m_ProductID)
   COLUMN_ENTRY(2, m_ProductName)
   COLUMN_ENTRY(3, m_SupplierID)
   COLUMN_ENTRY(4, m_CategoryID)
   COLUMN_ENTRY(5, m_QuantityPerUnit)
   COLUMN_ENTRY(6, m_UnitPrice)
   COLUMN_ENTRY(7, m_UnitsInStock)
   COLUMN_ENTRY(8, m_UnitsOnOrder)
   COLUMN_ENTRY(9, m_ReorderLevel)
   COLUMN_ENTRY_TYPE(10, DBTYPE_BOOL, m_Discontinued)
END_COLUMN_MAP()
DEFINE_COMMAND(CProductAccessor, _T(" \
   SELECT \
      ProductID, \
      ProductName, \
      SupplierID, \
      CategoryID, \
      QuantityPerUnit, \
      UnitPrice, \
      UnitsInStock, \
      UnitsOnOrder, \
      ReorderLevel, \
      Discontinued  \
      FROM Products"))};
class CProduct : public CCommand<CAccessor<CProductAccessor> >
{
public:
   HRESULT Open()
   {
      HRESULT      hr;
      hr = OpenDataSource();
      if (FAILED(hr))
         return hr;
      return OpenRowset();
   }
   HRESULT OpenDataSource()
   {
      HRESULT      hr;
      CDataSource db;
      CDBPropSet   dbinit(DBPROPSET_DBINIT);
      dbinit.AddProperty(DBPROP_INIT_DATASOURCE, OLESTR("OLE_DB_NWind_Jet"));
      dbinit.AddProperty(DBPROP_INIT_PROMPT, (short)4);
      dbinit.AddProperty(DBPROP_INIT_LCID, (long)1033);
      hr = db.Open(_T("MSDASQL"), &dbinit);
      if (FAILED(hr))
         return hr;
      return m_session.Open(db);
   }
   HRESULT OpenRowset()
   {
      // Set properties for open
      CDBPropSet   propset(DBPROPSET_ROWSET);
      propset.AddProperty(DBPROP_IRowsetChange, true);
      propset.AddProperty(DBPROP_UPDATABILITY, DBPROPVAL_UP_CHANGE);
      return CCommand<CAccessor<CProductAccessor> >::Open(m_session, NULL, &propset);
   }
   CSession   m_session;
};
#endif // __PRODUCT_H_

Back to Using the OLE DB Consumer Templates


Common OLE DB Consumer Scenarios (Examples)

The following topics provide some examples of how to use the OLE DB Consumer Templates in common scenarios:

  • How to traverse a simple rowset

  • How to issue a parameterized query

  • How to use multiple accessors on a rowset

For a more complete example of implementing an OLE DB Consumer, see Implementing a Simple Consumer.

You can also find examples of how to use the OLE DB Consumer Templates in the following samples:

  • CatDB

  • DBViewer

  • ComplexDB

  • MultiRead

  • ATLAgent

Back to Using the OLE DB Consumer Templates


Traversing a Simple Rowset

The following example shows a quick and easy database access that does not involve commands. The code retrieves records from a table called Artists in a Microsoft Access database using the Microsoft ODBC OLE DB Provider. The code creates an instance of CTable with CAccessor<CArtists> as a template parameter. It opens a connection, opens a session on the connection, and opens the table on the session.

#include <atldbcli.h>

CDataSource connection;
CSession session;
CTable<CAccessor<CArtists> > artists;

// Open the connection, session, and table
connection.Open(CLSID_MSDASQL, "NWind", "sa", "");
session.Open(connection);
artists.Open(session, "Artists");

// Get data from the rowset
while (artists.MoveNext() == S_OK)
{
   cout << artists.m_szFirstName;
   cout << artists.m_szLastName;
}

The user record, CArtists, looks like this:

class CArtists
{
public:
// Data Elements
   CHAR m_szFirstName[20];
   CHAR m_szLastName[30];
   short m_nAge;

// output binding map
BEGIN_COLUMN_MAP(CArtists)
   COLUMN_ENTRY(1, m_szFirstName)
   COLUMN_ENTRY(2, m_szLastName)
   COLUMN_ENTRY(3, m_nAge)
END_COLUMN_MAP()

Back to Common OLE DB Consumer Scenarios (Examples)


Issuing a Parameterized Query

This example issues a simple parameterized query that retrieves records with an age field (that is greater than 30) from a table in a Microsoft Access database. To support the parameter, the user record must have an additional map. The code uses the CCommand class instead of the CTable class used in the previous example, Traversing a Simple Rowset.

#include <atldbcli.h>

CDataSource connection;
CSession session;
CCommand<CAccessor<CArtists> > artists;

connection.Open(CLSID_MSDASQL, "NWind", "sa", "");
session.Open(connection);

// Set the parameter for the query
artists.m_nAge = 30;
artists.Open(session, "select * from artists where age > ?");

// Get data from the rowset
while (artists.MoveNext() == S_OK)
{
   cout << artists.m_szFirstName;
   cout << artists.m_szLastName;
}

The user record, CArtists, looks like this:

class CArtists
{
public:
// Data Elements
   CHAR m_szFirstName[20];
   CHAR m_szLastName[30];
   short m_nAge;

// output binding map
BEGIN_COLUMN_MAP(CArtists)
   COLUMN_ENTRY(1, m_szFirstName)
   COLUMN_ENTRY(2, m_szLastName)
   COLUMN_ENTRY(3, m_nAge)
END_COLUMN_MAP()

// parameter binding map
BEGIN_PARAM_MAP(CArtists)
   COLUMN_ENTRY(1, m_nAge)
END_PARAM_MAP
};

Back to Common OLE DB Consumer Scenarios (Examples)


Using Multiple Accessors on a Rowset

This example uses multiple accessors to retrieve one set of data. An application might use multiple accessors to optimize data access. The rowset retrieves one block of data that can be used by multiple accessors. (The accessor is defined in OLE DB User Records.)

#include <atldbcli.h>

CDataSource connection;
CSession session;
CTable<CAccessor< CMultiArtists> > artists;

// Connect the database, session, and accessors
connection.Open(CLSID_MSDASQL, "NWind", "sa", "");
session.Open(connection);
artists.Open(session, "artists");

// Retrieve the data
while (artists.MoveNext() == S_OK)
{
   cout << artists.m_szFirstName;
   cout << artists.m_szLastName;
   artists.GetData(1);   // Retrieve data for other accessor
   cout << artists.m_nAge;
}

The user record looks like this:

class CMultiArtists
{
public:
// Data Elements
   CHAR m_szFirstName[20];
   CHAR m_szLastName[30];
   short m_nAge;

// output binding map
BEGIN_ACCESSOR_MAP(CMultiArtists, 2)
   BEGIN_ACCESSOR(0, true)
    COLUMN_ENTRY(1, m_szFirstName)
    COLUMN_ENTRY(2, m_szLastName)
   END_ACCESSOR(0)
   BEGIN_ACCESSOR(1, false) // not an auto accessor
    COLUMN_ENTRY(3, m_nAge)
   END_ACCESSOR()
END_ACCESSOR_MAP()
};

Back to Common OLE DB Consumer Scenarios (Examples)


Implementing an OLE DB Template Consumer

The following topics show how to edit the files created by the ATL COM AppWizard to create a simple consumer that works with the simple provider shown in Implementing a Simple Read-Only Provider. Ordinarily, you would use the ATL Object Wizard to create most of the code shown in the following topics. The code generated by the ATL Object Wizard assumes that the provider supports schema rowset functionality. Because the simple provider does not support schema rowsets, the examples show how to create the code manually.

The extended example is presented in two sections:

  • The first section shows how to implement a simple consumer that reads a pair of strings from the simple provider.

  • The second section shows how to modify the consumer for use with the enhanced provider that supports IRowsetLocate interface.

You can find the finished code for the enhanced simple provider and consumer in the sample MyProv: A Simple Read-Only Provider.

Back to Using the OLE DB Consumer Templates


Implementing a Simple Consumer

To construct this consumer, you must create an MFC AppWizard application with the following options:

  • In the Project Name box, name the project TestProv.

  • In the Step 1 dialog box, select Dialog-based.

  • In the Step 2 dialog box, select Automation.

Selecting Automation means you do not have to add a CoIntialize call in CTestProvApp::InitInstance.

After creating the dialog-based MFC application, you must:

  • Edit the dialog resource.

  • Edit the user record.

  • Add a handler for the Run button.

Back to Implementing an OLE DB Template Consumer


Editing the Consumer Resource File

To create a user interface for the consumer, you must modify the default dialog created by MFC AppWizard. In the dialog resource IDD_TESTPROV_DIALOG, you must add a Run button and two list boxes (for the two strings that will be returned from the provider).

In the Workspace window, in the ResourceView tab, open the IDD_TESTPROV_DIALOG resource.

To add the Run button

  1. From the Controls toolbar, select the button icon and drag it to the IDD_TESTPROV_DIALOG dialog box.

  2. Right-click on the button you just created and choose Properties.

  3. In the Properties dialog box, change the button caption to Run.

  4. Close the Properties dialog box.

To add a list box

  1. From the Controls toolbar, select the list box icon and drag it to the IDD_TESTPROV_DIALOG dialog box.

  2. Right-click on the button you have just created and choose Properties.

  3. In the Properties dialog box, select the Styles tab and clear the Sort check box.

  4. Close the Properties dialog box.

To complete the consumer, you must edit the code in the user record.

Back to Implementing an OLE DB Template Consumer


Editing the User Record

In the dialog header file TestProvDlg.H, you must edit the user record as shown below. The COLUMN_ENTRY macros specify the ordinal, type, length, and data member for the two strings. The consumer uses this information to specify which columns to bind when it calls IAccessor::CreateAccessor.

////////////////////////////////////////////////////////////////////////
// TestProvDlg.h

class CProvider
{
// Attributes
public:
   char   szCommand[256];
   char   szText[256];

// Binding Maps
BEGIN_COLUMN_MAP(CProvider)
   COLUMN_ENTRY(1, szCommand)
   COLUMN_ENTRY(2, szText)
END_COLUMN_MAP()
};

Next, you must add a handler for the Run button.

Back to Implementing an OLE DB Template Consumer


Adding the Run Button Handler

You must add a handler function for the Run button you created in the dialog resource file.

To create a Run button handler

  • In the Dialog editor, press CTRL and double-click on the Run button. The CTestProvDlg::OnRun function appears in a source window.

  • Add your handler code to the CTestProvDlg::OnRun function.

To create the handler, you must use the following OLE DB Consumer Template classes:

  • CCommand

  • CDataSource

  • CSession

Each of these classes corresponds to a COM object in the provider.

Add the code shown below. In this handler code, the CCommand object takes a CProvider class as a template parameter. This parameter represents the bindings used by the provider to access the data.

///////////////////////////////////////////////////////////////////////
// TestProvDlg.cpp

void CTestProvDlg::OnRun()
{
   CCommand<CAccessor<CProvider>> table;
   CDataSource source;
   CSession   session;

   if (source.Open(“MyProvider.MyProvider.1”, NULL) != S_OK)
      return;

   if (session.Open(source) != S_OK)
      return;

   if (table.Open(session, _T("c:\\public\\testprf2\\gloo.txt")) != S_OK)
      return;

   while (table.MoveNext() == S_OK)
   {
      m_ctlString1.AddString(table.szCommand);
      m_ctlString2.AddString(table.szText);
   }
}

The handler uses the three Open calls, shown below, which correspond to three COM objects in the provider. It locates the provider by using its ProgID. You can obtain the ProgID from the system registry or by looking in the provider rgs file (MyProvider.rgs for the simple provider shown in Implementing a Simple Read-Only Provider). The provider opens a text file named gloo.txt, which contains an even number of strings separated by carriage returns. Open passes the file pathname to the provider as a string to the provider.

   if (source.Open(“MyProvider.MyProvider.1”, NULL) != S_OK)
      return;

   if (session.Open(source) != S_OK)
      return;

   if (table.Open(session, _T("c:\\public\\testprf2\\gloo.txt")) != S_OK)
      return;

To fetch the data, the handler calls table.MoveNext, as shown below. When there are no more rows, the provider returns DB_S_ENDOFROWSET and the loop terminates. The loop control statement compares the return value to S_OK. If the code used the SUCCEEDED macro, the loop would not terminate because DB_S_ENDOFROWSET is considered a successful return code.

   while (table.MoveNext() == S_OK)
   {
      m_ctlString1.AddString(table.szCommand);
      m_ctlString2.AddString(table.szText);
   }

The consumer is now ready to test with the simple provider (constructed in Implementing a Simple Read-Only Provider).

The next topic shows how to modify the consumer for use with an enhanced provider that implements the IRowsetLocate interface.

Back to Implementing an OLE DB Template Consumer


Modifying the Consumer for Use with the Enhanced Provider

To run the test consumer with the enhanced provider, you must make a few changes to handle bookmarks:

  • Change the Run button handler to request a bookmark from the provider

  • Add an entry to handle the bookmark in the user record

Back to Implementing an OLE DB Template Consumer


Changing the Run Button Handler

You must add code to set the DBPROP_IRowsetLocate property, as shown below. This property tells the provider that the consumer wants a bookmark column. In this code, the while loop contains a call to IRowsetLocate::Compare. This call should always succeed, since it compares a bookmark to itself. The call stores the bookmark in a temporary variable, so that the value will be available later to call MoveToBookmark.

//////////////////////////////////////////////////////////////////////
// TestProv Consumer Application in TestProvDlg.cpp

void CTestProvDlg::OnRun()
{
   CCommand<CAccessor<CProvider>> table;
   CDataSource source;
   CSession   session;

   if (source.Open(“MyProvider.MyProvider.1”, NULL, NULL, NULL,
          NULL) != S_OK)
      return;

   if (session.Open(source) != S_OK)
      return;

   CDBPropSet propset(DBPROPSET_ROWSET);
   propset.AddProperty(DBPROP_IRowsetLocate, true);
   if (table.Open(session, _T("c:\\public\\testprf2\\foo.txt"),
          &propset) != S_OK)
      return;

   CBookmark<4> tempBookmark;
   ULONG ulCount=0;
   while (table.MoveNext() == S_OK)
   {

      DBCOMPARE compare;
      if (ulCount == 2)
         tempBookmark = table.bookmark;
         hr = table.Compare(table.bookmark, table.bookmark,
                 &compare);
      if (FAILED(hr))
         ATLTRACE(_T("Compare failed: 0x%X\n"), hr);
      else
         ATLASSERT (compare == DBCOMPARE_EQ);

      m_ctlString1.AddString(table.szCommand);
      m_ctlString2.AddString(table.szText);
      ulCount++;
   }

   table.MoveToBookmark(tempBookmark);
   m_ctlString1.AddString(table.szCommand);
   m_ctlString2.AddString(table.szText);
}

Back to Modifying the Consumer for Use with the Enhanced Provider


Handling a Bookmark in the User Record

In the user record, you must add an entry in the COLUMN_MAP macro to handle the bookmark:

///////////////////////////////////////////////////////////////////////
// TestProvDlg.cpp

class CProvider
{
// Attributes
public:
   CBookmark<4>    bookmark;  // Add this line
   char   szCommand[256];
   char   szText[256];

Binding Maps
BEGIN_COLUMN_MAP(CProvider)
   BOOKMARK_ENTRY(bookmark)  // Add this line
   COLUMN_ENTRY(1, szCommand)
   COLUMN_ENTRY(2, szText)
END_COLUMN_MAP()
};

Back to Modifying the Consumer for Use with the Enhanced Provider


FAQ: Using the OLE DB Consumer Templates

  • How do I fetch data?

  • How do I determine data types on a rowset?

  • How do I use schema rowsets?

  • How do I use an existing ADO recordset?

  • How do I write a consumer without using the wizard?

  • How do I use multiple result sets from one stored procedure?

  • Which accessor should I use and when?

  • How do I handle a command I know nothing about?

  • How can I update a column when another table contains a reference to the row?

  • How do I override a dynamic accessor?

  • How do I use bookmarks?

  • How can I retrieve a BLOB?

  • How can I receive notifications?

  • How do I use multiple accessors?

  • How do I retrieve the length or status of a column?

See Also

FAQ: Using the OLE DB Provider Templates


How Do I Fetch Data?

After you open the data source, session, and rowset objects, you can fetch data. Depending upon the type of accessor you are using, you may need to bind columns. To fetch data, follow these steps:

  1. Open the rowset using the appropriate Open command.

  2. If you are using CManualAccessor, bind the output columns if you have not already done so. To bind the columns, call GetColumnInfo, then create an accessor with the bindings, as shown here:
    // From the DBViewer Sample CDBTreeView::OnQueryEdit
// Get the column information
ULONG ulColumns       = 0;
DBCOLUMNINFO* pColumnInfo  = NULL;
LPOLESTR pStrings      = NULL;
if (rs.GetColumnInfo(&ulColumns, &pColumnInfo, &pStrings) != S_OK)
AfxThrowOLEDBException(rs.m_pRowset, IID_IColumnsInfo);
struct MYBIND* pBind = new MYBIND[ulColumns];
rs.CreateAccessor(ulColumns, &pBind[0], sizeof(MYBIND)*ulColumns);
for (ULONG l=0; l<ulColumns; l++)
rs.AddBindEntry(l+1, DBTYPE_STR, sizeof(TCHAR)*40, &pBind[l].szValue, NULL, &pBind[l].dwStatus);
rs.Bind();
  3. Write a while loop to retrieve the data. In the loop, call MoveNext to advance the cursor and test the return value against S_OK, as shown in the following example:
    while (rs.MoveNext() == S_OK)
{
   // Add code to fetch data here
   // If you are not using an auto accessor, call rs.GetData()
}
  4. Within the while loop, you can fetch the data according to your accessor type.
    • If you use the CAccessor class, you should have a user record that contains data members. You can access your data using those data members, as shown here:
      while (rs.MoveNext() == S_OK)
{
   // Use the data members directly. In this case, m_nFooID
   // is declared in a user record that derives from
   // CAccessor
   wsprintf("%d", rs.m_nFooID);
}
    • If you use the CDynamicAccessor or CDynamicParameterAccessor class, you can fetch data by using the accessing functions GetValue and GetColumn, as shown in the following code. If you want to determine the type of data you are using, use GetType.
      while (rs.MoveNext() == S_OK)
{
   // Use the dynamic accessor functions to retrieve your
   // data

   ULONG ulColumns = rs.GetColumnCount();
   for (ULONG i=0; i<ulColumns; i++)
   {
     rs.GetValue(i);
   }
}
    • If you use CManualAccessor, you must specify your own data members, bind them yourself, and access them directly, as shown here:
      while (rs.MoveNext() == S_OK)
{
   // Use the data members you specified in the calls to
   // AddBindEntry.

   wsprintf("%s", szFoo);
}


How Do I Determine Data Types on a Rowset?

You can determine data types on a rowset at compile time or at run time.

If you need to determine data types at compile time, you are probably using a static CAccessor class. You can determine the data types manually or by using the ATL Object Wizard. If you use the wizard, this information will be available to you.

If you need to determine the data types at run time, you are probably using a dynamic or manual accessor. If you use the manual accessor, you can call GetColumnInfo on the rowset to return the column binding information, from which you can determine types.


How Do I Use Schema Rowsets?

There will be times when you will want to get information about the provider, rowset, table, columns, or whatever without opening the rowset. This data is called meta-data and can be retrieved by a number of different methods. One of the methods is to use schema rowsets. See Schema Rowset Classes and Typedef Classes for more information.


How Do I Use an Existing ADO Recordset?

To mix OLE DB consumer templates and Active Data Objects, use ADO to open a recordset (corresponding to a rowset in the OLE DB consumer templates). Once you have a recordset, do the following to connect to an OLE DB rowset:

  1. Call QueryInterface for the IRecordset and IAccessor pointers.
    IRowset* lpRowset = NULL;
IAccessor* lpAccessor = NULL;
lpUnk->QueryInterface(IID_IRowset, (void**)&lpRowset);
lpUnk->QueryInterface(IID_IAccessor, (void**)&lpAccessor);
  2. Attach the accessor and rowset to their appropriate OLE DB consumer template classes.
    CRowset rs;
CAccessor accessor;

accessor.Attach(lpAccessor);
rs.Attach(lpRowset);
rs.SetAccessor(accessor);


How Do I Add OLE DB Consumer Support To an MFC Application Without Using the Wizard?

The following example assumes you are adding OLE DB Consumer support to an existing ATL project. If you want to add OLE DB Consumer support to an MFC application, you should run the MFC AppWizard, which creates all of the support necessary and invokes MFC routines necessary to execute the application.

To add OLE DB Consumer support without using the ATL Object Wizard:

  • In your Stdafx.h file, add the following code below the afx include statement:
    #include <atlbase.h>
extern CComModule _Module;
#include <atlcom.h>
#include <atldbcli.h>
#include <atldbsch.h> // if you are using schema templates
  • In your Stdafx.cpp file, add the following code below the stdafx.h include statement:
    #include <atlimpl.cpp>
CComModule _Module;
  • Decide what type of accessor and rowset to use.

  • See Creating an OLE DB Consumer for more information.


How Do I Use Multiple Result Sets from One Stored Procedure?

Most stored procedures return multiple result sets. Such a stored procedure usually includes one or more select statements. The consumer needs to take this into account to handle all of the result sets.

To handle multiple result sets:

  1. Create a CCommand class with CMultipleResults as a template argument and with the accessor of your choice. Usually, this will be a dynamic or manual accessor. If you use another type of accessor, you may not be able to determine the output columns for each rowset.

  2. Execute the stored procedure as usual and bind the columns (see How do I fetch data?).

  3. Use the data.

  4. Call GetNextResult on the CCommand class. If another result rowset is available, GetNextResult returns S_OK and you should rebind your columns if you are using a manual accessor. If GetNextResult returns an error, there are no further result sets available.


Which Accessor Should I Use?

There are four main types of accessors in the consumer templates. Each accessor has its own advantages and disadvantages. Depending upon your situation one accessor type should suit your needs.

CAccessor

Binding | Parameters | Comments
Create a user record with COLUMN_ENTRY macros. The macros bind a data member in that record to the accessor. Once the rowset is created, columns cannot be unbound. | Yes, by using a PARAM_MAP macro entry. Once bound, parameters cannot be unbound. | Fastest accessor because of small amount of code.

CDynamicAccessor

Binding | Parameters | Comments
Automatic. | No. | Useful if you do not know the type of data in a rowset.

CDynamicParameterAccessor

Binding | Parameters | Comments
Automatic, but can be overridden. | Yes, if the provider supports ICommandWithParameters. Parameters bound automatically. | Slower than CDynamicAccessor but useful for calling generic stored procedures.

CManualAccessor

Binding | Parameters | Comments
Manual using AddBindEntry | Manually using AddParameterEntry. | Very fast since parameters and columns are bound only once. You determine the type of data you want to deal with. (See the DBVIEWER sample as an example.) Requires more code than CDynamicAccessor or CAccessor. Code tends to be more like calling OLE DB directly.


How Do I Handle a Command I Know Nothing About?

There are four things to do when handling an unknown command: determine the parameters, execute the command, determine the output columns, and see if there are multiple return rowsets. To do this with the OLE DB Consumer Templates, use the CManualAccessor class and follow these steps:

  1. Open a CCommand object with CManualAccessor as a template parameter.
    CCommand<CManualAccessor, CRowset, CMultipleResults> rs;
  2. Query the session for the IDBSchemaRowset interface and use the procedure parameters rowset. If the IDBSchemaRowset interface is not available, query for the ICommandWithParameters interface. Call GetParameterInfo for information. If neither interface is available, you can assume there are no parameters.

  3. For each of the parameters, call AddParameterEntry to add the parameters and set them.

  4. Open the rowset but set the bind parameter to false.

  5. Call GetColumnInfo to retrieve the output columns. Use AddBindEntry to add the output column to the binding.

  6. Call GetNextResult to determine if more rowsets are available. Repeat steps 2 through 5.

See CDBListView::CallProcedure in the DBVIEWER sample for an example.


How Can I Update a Column When Another Table Contains a Reference to the Row?

Some providers can detect which columns in the row change, but many providers cannot. As a result, updating a column can result in an error when there is a reference to the row you are attempting to update. To solve this problem, create a separate accessor containing only the columns you want to change. Pass the number of that accessor to SetData.


How Do I Override a Dynamic Accessor?

When you use CDynamicAccessor, the command Open method creates an accessor for you automatically, based on the column information of the opened rowset. You can override the dynamic accessor to control exactly how the columns are bound.

To override the dynamic accessor, pass false as the last parameter to the CCommand::Open method. This prevents Open from creating an accessor automatically. You can then call GetColumnInfo and call AddBindEntry for each column you want to bind. The following code shows how to do it:

USES_CONVERSION;
double   dblProductID;

CCommand<CDynamicAccessor> product;
// Open the table, passing false to prevent automatic binding
product.Open(session, _T("Select * FROM Products"), NULL, NULL, DBGUID_DEFAULT, false);

ULONG         nColumns;
DBCOLUMNINFO*   pColumnInfo;
// Get the column information from the opened rowset
product.GetColumnInfo(&nColumns, &pColumnInfo);

// Bind the product ID as a double
pColumnInfo[0].wType          = DBTYPE_R8;
pColumnInfo[0].ulColumnSize = 8;
product.AddBindEntry(pColumnInfo[0]);

// Bind the product name as it is
product.AddBindEntry(pColumnInfo[1]);

// Bind the reorder level as a string
pColumnInfo[8].wType          = DBTYPE_STR;
pColumnInfo[8].ulColumnSize = 10;
product.AddBindEntry(pColumnInfo[8]);

// We've finished specifying the bindings. Go ahead and bind
product.Bind();
// Free the memory for the column information that we retrieved in
// previous call to GetColumnInfo
CoTaskMemFree(pColumnInfo);

char*   pszProductName;
char*   pszReorderLevel;
bool   bRC;

// Loop through the records tracing out the information.
while (product.MoveNext() == S_OK)
{
   bRC = product.GetValue(1, &dblProductID);
   pszProductName   = (char*)product.GetValue(2);
   pszReorderLevel  = (char*)product.GetValue(9);

   ATLTRACE(_T("Override = %lf \"%s\" \"%s\"\n"), dblProductID,
      A2T(pszProductName), A2T(pszReorderLevel));
}


How Do I Use Bookmarks?

Before you open the rowset, you must tell the provider that you want to use bookmarks. To do this, set the DBPROP_BOOKMARKS property to true in your property set. The provider retrieves bookmarks as column zero, so you must use the special macro BOOKMARK_ENTRY and the CBookmark class if you’re using a static accessor. CBookmark is a templated class where the argument is the length in bytes of the bookmark buffer. The length of the buffer required for a bookmark depends on the provider. If you are using the ODBC OLE DB provider, as shown in the following example, the buffer must be 4 bytes.

class CProduct
{
public:
   CBookmark<4>   bookmark;

   BEGIN_COLUMN_MAP(CProduct)
      BOOKMARK_ENTRY(bookmark)
   END_COLUMN_MAP()
};

CDBPropSet propset(DBPROPSET_ROWSET);
propset.AddProperty(DBPROP_BOOKMARKS, true);

CTable<CAccessor<CProduct> > product;
product.Open(session, "Products", &propset);

If you use CDynamicAccessor, the buffer is dynamically allocated at run time. In this case, you can use a specialized version of CBookmark for which you do not specify a buffer length. Use the function GetBookmark to retrieve the bookmark from the current record, as shown here:

CTable<CDynamicAccessor> product;
CBookmark<>              bookmark;
CDBPropSet propset(DBPROPSET_ROWSET);

propset.AddProperty(DBPROP_BOOKMARKS, true);
product.Open(session, "Products", &propset);
product.MoveNext();
product.GetBookmark(&bookmark);


How Can I Retrieve a BLOB?

You can retrieve a binary large object (BLOB) in various ways. You can use DBTYPE_BYTES to retrieve the BLOB as a sequence of bytes, or you can use an interface like ISequentialStream. For more information, see BLOBS and OLE Objects in the OLE DB Programmer’s Reference.

The following code shows how to retrieve a BLOB using ISequentialStream. The macro BLOB_ENTRY allows you to specify the interface and the flags used for the interface. After opening the table, the code calls Read repeatedly on ISequentialStream to read bytes from the BLOB. The code calls Release to dispose of the interface pointer before calling MoveNext to obtain the next record.

class CCategories
{
public:
   ISequentialStream*   pPicture;

BEGIN_COLUMN_MAP(CCategories)
   BLOB_ENTRY(4, IID_ISequentialStream, STGM_READ, pPicture)
END_COLUMN_MAP()
};

CTable<CAccessor<CCategories> > categories;
ULONG          cb;
BYTE            myBuffer[65536];

categories.Open(session, "Categories");
while (categories.MoveNext() == S_OK)
{
   do
   {
      categories.pPicture->Read(myBuffer, 65536, &cb);
      // Do something with the buffer
   } while (cb > 0);
   categories.pPicture->Release();
}


How Can I Receive Notifications?

OLE DB provides interfaces for receiving notifications when events occur. These are described in the Notifications chapter of the OLE DB Programmer’s Reference. Setup of these events uses the standard COM connection-point mechanism. For example, an ATL object that wants to retrieve events through IRowsetNotify implements the IRowsetNotify interface by adding IRowsetNotify to the class-derived list and exposing it through a COM_INTERFACE_ENTRY macro.

IRowsetNotify has three methods, which can be called at various times. If you want to respond to only one of these methods, you can use the IRowsetNotifyImpl class, which returns E_NOTIMPL for the methods you are not interested in.

When you create the rowset, you must tell the provider that you want the returned rowset object to support IConnectionPointContainer, which is needed to set up the notification.

The following code shows how to open the rowset from an ATL object, then use the AtlAdvise function to set up the notification sink. AtlAdvise returns a cookie that will be used when you call AtlUnadvise.

CDBPropSet propset(DBPROPSET_ROWSET);
propset.AddProperty(DBPROP_IConnectionPointContainer, true);

product.Open(session, _T("Products"), &propset);

AtlAdvise(product.m_spRowset, GetUnknown(), IID_IRowsetNotify, &m_dwCookie);


How Do I Use Multiple Accessors?

Accessors are normally created using the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros. This ensures that MoveNext will retrieve data for all specified columns automatically. In some instances, you may not want to retrieve all the columns on every move (for example, if one of the columns contains a large graphic). In that case, you can place one particular column in a separate accessor and make that a nonautomatic accessor, as shown below. When you call MoveNext, this code retrieves only the Product ID automatically. If you need the long name, you must call GetData explicitly, passing the accessor number (1, in this case) to retrieve the data.

class CProduct
{
public:
   long      nProductID;
   char      szVeryLongName[2048];

   BEGIN_ACCESSOR_MAP(CProduct, 2)   // Pass number of accessors
      BEGIN_ACCESSOR(0, true)         // true = an auto accessor
         COLUMN_ENTRY(1, nProductID)
      END_ACCESSOR()
      BEGIN_ACCESSOR(1, false)       // false = not an autoaccessor
         COLUMN_ENTRY(2, szVeryLongName)
      END_ACCESSOR()
   END_ACCESSOR_MAP()
};


How Do I Retrieve the Length or Status of a Column?

You can retrieve the length of a variable-length column or the status of a column (to check for DBSTATUS_S_ISNULL, for example).

To get the length, use the COLUMN_ENTRY_LENGTH macro.

To get the status, use the COLUMN_ENTRY_STATUS macro.

To get both, use COLUMN_ENTRY_LENGTH_STATUS, as shown below.

class CProduct
{
public:
   char      szName[40];
long      nNameLength;
DBSTATUS   nNameStatus;

BEGIN_COLUMN_MAP(CProduct)
   COLUMN_ENTRY_LENGTH_STATUS(2, szName, nNameLength, nNameStatus)
END_COLUMN_MAP()
};

CTable<CAccessor<CProduct > > product;

product.Open(session, "Product");
while (product.MoveNext() == S_OK)
{
   // Check the product name isn’t NULL before tracing it
   if (product.nNameStatus == DBSTATUS_S_OK)
      ATLTRACE(“%s is %d characters\n”, szName, nNameLength);
}

When you use CDynamicAccessor, the length and status are bound for you automatically. To retrieve the length and status values, use the GetLength and GetStatus member functions.


List of OLE DB Consumer Templates

The OLE DB Consumer Templates contain the following classes. The reference material also includes topics on the macros for OLE DB Consumer Templates.

Session Classes

CDataSource

Corresponds to an OLE DB data source object, representing a connection through a provider to a data source. One or more database sessions, each represented by a CSession object, can take place on a single connection.

CEnumerator

Corresponds to an OLE DB enumerator object, which retrieves rowset information about available data sources.

CSession

Represents a single database access session. One or more sessions can be associated with each CDataSource object.

CEnumeratorAccessor

Used by CEnumerator to access the data from the enumerator rowset. This rowset consists of the data sources and enumerators visible from the current enumerator.

Accessor Classes

CAccessorBase

Base class for all accessor classes.

CAccessor

Used for records that are statically bound to a data source. Use this accessor class when you know the structure of the data source.

CDynamicAccessor

An accessor that can be created at run time, based on the column information of the rowset. Use this class to retrieve data if you don’t know the structure of the data source.

CDynamicParameterAccessor

An accessor that can be used when command types are unknown. Obtains the parameter information by calling the ICommandWithParameters interface, if the provider supports the interface.

CManualAccessor

An accessor with methods to handle both columns and command parameters. With this class, you can use any data types as long as the provider can convert the type.

Rowset Classes

CRowset

Used to manipulate, set, and retrieve rowset data.

CBulkRowset

Used to fetch and manipulate rows in bulk by retrieving multiple row handles with a single call.

CAccessorRowset

Encapsulates a rowset and its associated accessors.

CArrayRowset

Used to access elements of a rowset using array syntax.

IRowsetNotifyImpl

Provides a dummy implementation for IRowsetNotify, with empty functions for the IRowsetNotify methods OnFieldChange, OnRowChange, and OnRowsetChange.

CRestrictions

Used to specify restrictions for schema rowsets.

Schema Rowset Classes and Typedef Classes

The OLE DB Templates provide you with a set of classes that correspond to the OLE DB schema rowsets.

Command Classes

CCommand

Used to set and execute a parameter-based OLE DB command. To merely open a simple rowset, use CTable instead.

CTable

Used to access a simple rowset with no parameters.

CMultipleResults

Used as a template argument for the CCommand template when you want the command to handle multiple result sets.

CNoMultipleResults

Used as a template argument for the CCommand template when you want the command to handle a single rowset. CNoMultipleResults is the default value for the template argument.

CNoAccessor

Used as a template argument for template classes, such as CCommand and CTable, that take an accessor class argument. Use CNoAccessor if you do not want the class to support parameters or output columns.

CNoRowset

Used as a template argument for CCommand or CTable if the command or table does not return a rowset.

Property Classes

CDBPropIDSet

Used to pass an array of property IDs for which the consumer wants property information. The properties belong to one property set.

CDBPropSet

Used to set properties on a provider.

Bookmark Class

CBookmark

Used as an index for accessing data in a rowset.

Error Class

CDBErrorInfo

Used to retrieve OLE DB error information.

See also

List of OLE DB Provider Templates, Home Page for OLE DB Template Classes


CAccessor

template < class T >
class CAccessor : public T, CAccessorBase

Parameters

T

The user record class.

The CAccessor class represents one of the accessor types. It is used when a record is statically bound to a data source. The record contains the buffer. This class supports multiple accessors on a rowset.

Use this accessor type when you know the structure and the type of the database.

If your accessor contains fields that point to memory (such as a BSTR or interface) that must be freed, call the member function CAccessorRowset::FreeRecordMemory before the next record is read.

#include <atldbcli.h>

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CAccessorBase

All accessors in the OLE DB Templates derive from this class. CAccessorBase allows one rowset to manage multiple accessors. It also provides binding for both parameters and output columns.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CAccessorBase Class Members

Methods

Close | Closes the accessors.
GetNumAccessors | Retrieves the number of accessors created by the class.
GetHAccessor | Retrieves the accessor handle.
ReleaseAccessors | Releases the accessors.
IsAutoAccessor | Tests whether the specified accessor is an autoaccessor.

CAccessorBase Overview


CAccessorBase::Close

void Close( );

Remarks

Closes the accessors. You must call ReleaseAccessors first.


CAccessorBase::GetHAccessor

HACCESSOR GetHAccessor( int nAccessor ) const;

Return Value

The accessor handle.

Parameters

nAccessor

[in] The zero-offset number for the accessor.

Remarks

Retrieves the accessor handle of a specified accessor.


CAccessorBase::GetNumAccessors

int GetNumAccessors( ) const;

Return Value

The number of accessors created by the class.

Remarks

Retrieves the number of accessors created by the class.


CAccessorBase::IsAutoAccessor

bool IsAutoAccessor( ULONG nAccessor ) const;

Return Value

Returns true if the accessor is an autoaccessor. Otherwise, it returns false.

Parameters

nAccessor

[in] The zero-offset number for the accessor.

Remarks

Returns true if data is automatically retrieved for the accessor during a Move operation.


CAccessorBase::ReleaseAccessors

HRESULT ReleaseAccessors( IUnknown* pUnk );

Return Value

A standard HRESULT.

Parameters

pUnk

[in] A pointer to an IUnknown interface for the COM object for which the accessors have been created.

Remarks

Releases the accessors created by the class. Called from CAccessorRowset::Close.


CAccessorRowset

template < class TAccessor, class TRowset >
class CAccessorRowset : public TAccessor, public TRowset

Parameters

TAccessor

An accessor class.

TRowset

A rowset class.

CAccessorRowset encapsulates a rowset and its associated accessors in a single class. Class TAccessor manages the accessor. Class TRowset manages the rowset.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CAccessorRowset Class Members

Methods

CAccessorRowset | Constructor.
Bind | Creates bindings (used when bBind is specified as false in CCommand::Open).
FreeRecordMemory | Frees any columns in the current record that need to be freed.
GetColumnInfo | Implements IColumnsInfo::GetColumnInfo.
Close | Closes the rowset and any accessors.

CAccessorRowset Overview


CAccessorRowset::Bind

HRESULT Bind( );

Return Value

A standard HRESULT.

Remarks

Call this function to create the bindings if you specified bBind as false in CCommand::Open.


CAccessorRowset::CAccessorRowset

CAccessorRowset( );

Remarks

Initializes the CAccessorRowset object.


CAccessorRowset::Close

void Close( );

Remarks

Releases any active accessors and the rowset. Releases any associated memory.


CAccessorRowset::FreeRecordMemory

void FreeRecordMemory( );

Remarks

Frees any columns in the current record that need to be freed. Calls SysFreeString, described in the Platform SDK, on any BSTRs and Release on any interfaces


CAccessorRowset::GetColumnInfo

HRESULT GetColumnInfo( ULONG* pulColumns, DBCOLUMNINFO** ppColumnInfo, LPOLESTR* ppStrings ) const;
HRESULT GetColumnInfo( ULONG* pColumns, DBCOLUMNINFO** ppColumnInfo );

Return Value

A standard HRESULT.

Parameters

See IColumnsInfo::GetColumnInfo in the OLE DB Programmer's Reference.

Remarks

Gets column information from the opened rowset. The user must free the returned column information and string buffer. Use the second version of this method when you use CDynamicAccessor and need to override the bindings.

For more information, see IColumnsInfo::GetColumnInfo in the OLE DB Programmer's Reference.


CArrayRowset

template < class T, class TRowset = CRowset >
class CArrayRowset : public CVirtualBuffer <T> , public TRowset

Parameters

T

Type of information stored in the rowset.

TRowset

A rowset class.

Use this class when you want to access elements of a rowset using array syntax.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart, CRowset


CArrayRowset Class Members

Methods

CArrayRowset Constructor.

Operators

Operator[] Accesses an element of the rowset.

CArrayRowset Overview

See Also

CRowset Class Members


CArrayRowset::CArrayRowset

CArrayRowset( );

Remarks

Creates a new CArrayRowset object.


CArrayRowset::operator[]

T& operator[]( ULONG nRow );

Return Value

The contents of the requested row.

Template Argument

T

Type of information stored in the rowset.

Parameters

nRow

[in] Number of the row (array element) you want to access.

Remarks

Provides array-like syntax for accessing a row in the rowset. If nRow exceeds the number of rows in the rowset, an exception is thrown.


CBookmark

template < ULONG nSize = 0 >
class CBookmark : public CBookmarkBase

template < >
class CBookmark< 0 > : public CBookmarkBase

Parameters

nSize

The size of the bookmark buffer in bytes. When nSize is zero, the bookmark buffer will be dynamically created at run time.

This class holds a bookmark value in its buffer. CBookmark<0> is a template specialization of CBookmark; its buffer is dynamically created at run time.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CBookmark Class Members

Methods

CBookmark | The constructor
GetBuffer | Retrieves the pointer to the buffer.
GetSize | Retrieves the size of the buffer in bytes.
SetBookmark | Sets the bookmark value.

Operators

operator = Assigns one CBookmark class to another.

CBookmark Overview


CBookmark::CBookmark

CBookmark( );

CBookmark( ULONG nSize );

Parameters

nSize

[in] Size of the bookmark buffer in bytes.

Remarks

The constructor. The first function sets the buffer to NULL and the buffer size to 0. The second function sets the buffer size to nSize, and the buffer to a byte array of nSize bytes.

Note This function is only available in CBookmark<0>.


CBookmark::GetBuffer

virtual BYTE* GetBuffer( ) const;

Return Value

A pointer to the bookmark buffer.

Remarks

Retrieves the pointer to the bookmark buffer.


CBookmark::GetSize

virtual ULONG GetSize( ) const;

Return Value

The size of the buffer in bytes.

Remarks

Retrieves the size of the bookmark buffer.


CBookmark::SetBookmark

void SetBookmark( ULONG nSize, BYTE* pBuffer );

Parameters

nSize

[in] The size of the bookmark buffer.

pBuffer

[in] A pointer to the byte array containing the bookmark value.

Remarks

This function copies the bookmark value referenced by pBuffer to the CBookmark buffer, and sets the buffer size to nSize.

Note This function is only available in CBookmark<0>.


CBookmark::operator =

CBookmark& operator = ( const CBookmark& bookmark );

Remarks

Assigns a CBookmark object to another.

Note This operator is needed only in CBookmark<0>.


CBulkRowset

class CBulkRowset : public CRowset

CBulkRowset fetches and manipulates rows to work on data in bulk by retrieving multiple row handles with a single call.

#include <atlbdcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CBulkRowset Class Members

Methods

CBulkRowset | Constructor.
SetRows | Sets the number of row handles to be retrieved by one call.
AddRefRows | Increments the reference count.
ReleaseRows | Sets the current row (m_nCurrentRow) to zero and releases all rows.
MoveFirst | Retrieves the first row of data, performing a new bulk fetch if necessary.
MoveNext | Retrieves the next row of data.
MovePrev | Moves to the previous row.
MoveLast | Moves to the last row.
MoveToBookmark | Fetches the row marked by a bookmark or the row at a specified offset from that bookmark.
MoveToRatio | Fetches rows starting from a fractional position in the rowset.

CBulkRowset Overview


CBulkRowset::AddRefRows

HRESULT AddRefRows( );

Return Value

A standard HRESULT.

Remarks

Calls IRowset::AddRefRows to increment the reference count for all rows currently retrieved from the bulk rowset.

CBulkRowset Overview | Class Members

See Also

CBulkRowset::ReleaseRows


CBulkRowset::CBulkRowset

CBulkRowset( );

Remarks

Creates a new CBulkRowset object and sets the default row count to 10.


CBulkRowset::MoveFirst

HRESULT MoveFirst( );

Return Value

A standard HRESULT.

Remarks

Retrieves the first row of data.


CBulkRowset::MoveLast

HRESULT MoveLast( );

Return Value

A standard HRESULT.

Remarks

Moves to the last row.


CBulkRowset::MoveNext

HRESULT MoveNext( );

Return Value

A standard HRESULT.

Remarks

Retrieves the next row of data.


CBulkRowset::MovePrev

HRESULT MovePrev( );

Return Value

A standard HRESULT.

Remarks

Moves to the previous row.


CBulkRowset::MoveToBookmark

HRESULT MoveToBookMark( const CBookmarkBase& bookmark, LONG lSkip = 0 );

Return Value

See IRowset::GetData in the OLE DB Programmer's Reference.

Parameters

bookmark

[in] A bookmark marking the location from which you want to fetch data.

lSkip

[in] The number count of rows from the bookmark to the target row. If lSkip is zero, the first row fetched is the bookmarked row. If lSkip is 1, the first row fetched is the row after the bookmarked row. If lSkip is –1, the first row fetched is the row before the bookmarked row.

Remarks

Fetches the row marked by a bookmark or the row at a specified offset (lSkip) from that bookmark.


CBulkRowset::MoveToRatio

HRESULT MoveToRatio( ULONG nNumerator, ULONG nDenominator );

Return Value

A standard HRESULT.

Parameters

nNumerator

[in] The numerator used to determine the fractional position from which to fetch data.

nDenominator

[in] The denominator used to determine the fractional position from which to fetch data.

Remarks

Fetches rows starting from a fractional position in the rowset, roughly according to the following formula:

( nNumerator *  RowsetSize ) / nDenominator

Where RowsetSize is the size of the rowset, measured in rows. The accuracy of this formula depends on the specific provider. For details, see IRowsetScroll::GetRowsAtRatio in the OLE DB Programmer's Reference.


CBulkRowset::ReleaseRows

HRESULT ReleaseRows( );

Return Value

A standard HRESULT.

Remarks

Calls IRowset::ReleaseRows to decrement the reference count for all rows currently retrieved from the bulk rowset.

CBulkRowset Overview | Class Members

See Also

CBulkRowset::AddRefRows


CBulkRowset::SetRows

void SetRows( ULONG nRows );

Parameters

nRows

[in] The new size of the rowset (number of rows).

Remarks

Sets the number of row handles retrieved by each call. If you call this function, it must be before the rowset is opened.


CCommand

template <class TAccessor = CNoAccessor, class TRowset = CRowset, class TMultiple = CNoMultiple>
class CCommand : public CAccessorRowset<TAccessor, TRowset>, public CCommandBase

Parameters

TAccessor

An accessor class.

TRowset

A rowset class.

TMultiple

To use an OLE DB command that can return multiple results, specify CMultipleResults. Otherwise, use CNoMultipleResults. For details, see IMultipleResults.

This class provides methods to set and execute a command. Use this class when you need to perform a parameter-based operation or execute a command. If you merely need to open a simple rowset, use CTable instead.

The accessor class you are using determines the method of binding parameters and data.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CCommand Class Members

Methods

Ccommand | Constructor.
Open | Executes and optionally binds the command.
GetNextResult | Fetches the next result when using multiple result sets.

Inherited Methods

CreateCommand | Creates a new command.
Prepare | Validates and optimizes the current command.
Unprepare | Discards the current command execution plan.
Create | Creates a new command for the specified session, then sets the command text.
ReleaseCommand | Releases the parameter accessor if necessary, then releases the command.
GetParameterInfo | Gets a list of the command's parameters, their names, and their types.
SetParameterInfo | Specifies the native type of each command parameter.

CCommand Overview


CCommand::CCommand

CCommand( );

Remarks

Constructor. Initializes the parameter accessor to NULL.


CCommand::Create

HRESULT Create( const CSession& session, LPCTSTR szCommand, REFGUID guidCommand = DBGUID_DEFAULT );

Return Value

A standard HRESULT.

Parameters

session

[in] A session on which to create the command.

szCommand

[in] A pointer to the text of the command to be set.

guidCommand

[in] A GUID that specifies the syntax and general rules for the provider to use in parsing the command text. For a complete description of dialects, see ICommandText::GetCommandText in the OLE DB Programmer's Reference.

Remarks

Calls CCommand::CreateCommand to create a new command for the specified session, then calls ICommandText::SetCommandText to set the command text.


CCommand::CreateCommand

HRESULT CreateCommand( const CSession& session );

Return Value

A standard HRESULT.

Parameters

session

[in] A CSession object to be associated with the new command.

Remarks

Creates a new command. This method releases the current command, if one exists.


CCommand::GetNextResult

HRESULT GetNextResult( LONG* pulRowsAffected, bool bBind = true );

Return Value

A standard HRESULT.

Parameters

pulRowsAffected

[in/out] A pointer to memory where the count of rows affected by a command is returned.

bBind

[in] Determines whether or not the command is bound after being executed.

Remarks

Fetches the next result set if one is available. If a result set has been previously fetched, this function releases the previous result set and unbinds the columns. If bBind is true, it binds the new columns.


CCommand::GetParameterInfo

HRESULT GetParameterInfo( ULONG* pParams, DBPARAMINFO** ppParamInfo, OLECHAR** ppNamesBuffer );

Return Value

A standard HRESULT.

Parameters

See ICommandWithParameters::GetParameterInfo in the OLE DB Programmer's Reference.

Remarks

Gets a list of the command's parameters, their names, and their types.


CCommand::Open

HRESULT Open( DBPROPSET *pPropSet = NULL, LONG* pRowsAffected = NULL, bool bBind = true );

HRESULT Open( const CSession& session, LPCTSTR szCommand = NULL, DBPROPSET *pPropSet = NULL, LONG* pRowsAffected = NULL, REFGUID guidCommand = DBGUID_DEFAULT, bool bBind = true );

Return Value

A standard HRESULT.

Parameters

pPropSet

[in/out] An array of DBPROPSET structures containing properties and values to be set. The properties specified in these structures must belong to the Rowset property group.

pRowsAffected

[in/out] A pointer to memory where the count of rows affected by a command is returned. If *pRowsAffected is NULL, no row count is returned. Otherwise, Open sets *pRowsAffected according to the following conditions:

If | Then
The cParamSets element of pParams is greater than 1 | *pRowsAffected represents the total number of rows affected by all of the parameter sets specified in the execution.
The number of affected rows is not available | *pRowsAffected is set to –1.
The command does not update, delete, or insert rows | *pRowsAffected is undefined.

bBind

[in] True if command is bound after being executed. Otherwise, false.

session

[in] The session in which to execute the command.

szCommand

[in] The command to execute. Can be NULL when using CAccessor, in which case the command will be retrieved from the value passed to the DEFINE_COMMAND macro. See ICommand::Execute in the OLE DB Programmer's Reference for details.

guidCommand

[in] A GUID that specifies the syntax and general rules for the provider to use in parsing the command text. See ICommandText::GetCommandText and ICommandText::SetCommandText in the OLE DB Programmer's Reference for details.

Remarks

Use the first version of this method when a command has already been created and you want to perform a single Prepare and multiple executions. The second version of the method takes a session, creates a command, and executes the command, binding any parameters as necessary.


CCommand::Prepare

HRESULT Prepare( ULONG cExpectedRuns = 0 );

Return Value

A standard HRESULT.

Parameters

cExpectedRuns

[in] The number of times you expect to execute the command.

Remarks

Validates and optimizes the current command. This method wraps the OLE DB method ICommandPrepare::Prepare.


CCommand::ReleaseCommand

ReleaseCommand( );

Remarks

Releases the parameter accessor, if necessary, then releases the command itself.


CCommand::SetParameterInfo

HRESULT SetParameterInfo( ULONG ulParams, const ULONG* pOrdinals, const DBPARAMBINDINFO* pParamInfo );

Return Value

A standard HRESULT.

Parameters

See ICommandWithParameters::SetParameterInfo in the OLE DB Programmer's Reference.

Remarks

Specifies the native type of each command parameter.


CCommand::Unprepare

HRESULT Unprepare( );

Return Value

A standard HRESULT.

Remarks

Discards the current command execution plan. This method wraps the OLE DB method ICommandPrepare::Unprepare.


CDataSource

class CDataSource

The CDataSource class corresponds to an OLE DB data source object, which represents a connection through a provider to a data source. One or more database sessions can be created for a single connection. These sessions are represented by CSession. You must call CDataSource::Open to open the connection before creating a session with CSession::Open.

For an example of how to use CDataSource, see the CatDB sample.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CDataSource Class Members

Methods

Close | Closes the connection.
GetProperties | Gets the values of properties currently set for the provider connection. (See IDBProperties::GetProperties.)
GetProperty | Gets the value of a single property currently set for the provider connection.
Open | Creates a connection to a provider (data source) using either a CLSID, ProgID, or a Cenumerator provided by the caller.
OpenWithPromptFileName | Allows the user to select a previously created data link file to open the corresponding data source.
OpenFromFileName | Opens the data source specified by a data link file.
OpenFromInitializationString | Opens the data source specified by an initialization string.
GetInitializationString | Retrieves the initialization string of the data source that is currently open.

Data Members

m_spInit A smart pointer to the data source object.

CDataSource Overview


CDataSource::Close

void Close( );

Remarks

Closes the connection by releasing the m_spInit pointer.


CDataSource::GetInitializationString

HRESULT GetInitializationString( BSTR* pInitializationString, bool bIncludePassword = false );

Return Value

A standard HRESULT.

Parameters

pInitializationString

[out] A pointer to the initialization string.

bIncludePassword

[in] True if string includes a password. Otherwise, false.

Remarks

Retrieves the initialization string of a data source that is currently open. The resulting initialization string can be used to reopen this data source connection at a later time.


CDataSource::GetProperties

HRESULT GetProperties( ULONG ulPropIDSets, const DBPROPIDSET* pPropIDSet, ULONG* pulPropertySets, DBPROPSET** ppPropsets );

Return Value

A standard HRESULT.

Parameters

See IDBProperties::GetProperties in the OLE DB Programmer's Reference.

Remarks

Returns the property information requested for the data source object. To get a single property, use GetProperty.


CDataSource::GetProperty

HRESULT GetProperty( const GUID& guid, DWORD dwID, VARIANT* pVariant );

Return Value

A standard HRESULT.

Parameters

guid

[in] A GUID identifying the property set for which to return the property.

dwID

[in] Property ID for the property to return.

pVariant

[out] A pointer to the variant where GetProperty returns the value of the property.

Remarks

Returns the value of a specified property. To get multiple properties, use GetProperties.


CDataSource::Open

HRESULT Open( const CLSID& clsid, DBPROPSET* pPropSet = NULL );

HRESULT Open( const CLSID& clsid, LPCTSTR pName = NULL, LPCTSTR pUserName = NULL, LPCTSTR pPassword = NULL, long nInitMode = 0 );

HRESULT Open( LPCTSTR szProgID, DBPROPSET* pPropSet );

HRESULT Open( LPCTSTR szProgID, LPCTSTR pName = NULL, LPCTSTR pUserName = NULL, LPCTSTR pPassword = NULL, long nInitMode = 0 );

HRESULT Open( const CEnumerator& enumerator, DBPROPSET* pPropSet = NULL );

HRESULT Open( const CEnumerator& enumerator, LPCTSTR pName = NULL, LPCTSTR pUserName = NULL, LPCTSTR pPassword = NULL, long nInitMode = 0 );

HRESULT Open( HWND hWnd = GetActiveWindow(), DBPROMPTOPTIONS dwPromptOptions = DBPROMPTOPTIONS_WIZARDSHEET );

Return Value

A standard HRESULT.

Parameters

clsid

[in] The CLSID of the data provider.

pPropSet

[in] A pointer to a DBPROPSET structure containing properties and values to be used to initialize the provider. The properties must belong to the Initialization property group. See CDBPropSet for further information.

pName

[in] The name of the database to connect to.

pUserName

[in] The name of the user.

pPassword

[in] The user's password.

nInitMode

[in] Database initialization mode. See Initialization Properties in the OLE DB Programmer's Reference for a list of valid initialization modes. If nInitMode is zero, no initialization mode is included in the property set used to open the connection.

szProgID

[in] A program identifier.

enumerator

[in] A CEnumerator object used to obtain a moniker for opening the connection when the caller does not specify a CLSID.

hWnd

[in] Handle to the window that is to be the parent of the dialog box.

dwPromptOptions

[in] Determines the style of locator dialog box to display. See Msdasc.h for possible values.

Remarks

Opens a connection to a data source using a CLSID, program ID, or moniker or prompts the user with a locator dialog box.


CDataSource::OpenFromFileName

HRESULT OpenFromFileName( LPCOLESTR szFileName );

Return Value

A standard HRESULT.

Parameters

szFileName

[in] The name of a file, usually a data source connection (.MDL) file.

For more information about data link files (.MDL files), see Data Link API Overview in the Platform SDK.

Remarks

Opens a data source from a file specified by the user-supplied file name.


CDataSource::OpenFromInitializationString

HRESULT OpenFromInitializationString( LPCOLESTR szInitializationString );

Return Value

A standard HRESULT.

Parameters

szInitializationString

[in] The initialization string.

Remarks

Opens a data source specified by the user-supplied initialization string.


CDataSource::OpenWithPromptFileName

HRESULT OpenWithPromptFileName( HWND hWnd = GetActiveWindow( ), DBPROMPTOPTIONS dwPromptOptions = DBPROMPTOPTIONS_NONE, LPCOLESTR szInitialDirectory = NULL );

Return Value

A standard HRESULT.

Parameters

hWnd

[in] Handle to the window that is to be the parent of the dialog box.

dwPromptOptions

[in] Determines the style of locator dialog box to display. See Msdasc.h for possible values.

szInitialDirectory

[in] The initial directory to display in the locator dialog box.

Remarks

Calls the Data Links component and asks it to open the Organize Dialog dialog box, which allows the user to select a previously created data source connect (.MDL) file. The selected file is then used to open the data source.

For more information about data link files (.MDL files), see Data Link API Overview in the Platform SDK.


CDataSource::m_spInit

CComPtr<IDBInitialize> m_spInit;

Remarks

A smart pointer to the data source object.

CDataSource Overview | Class Members

See Also

CComPtr


CDBErrorInfo

class CDBErrorInfo

This class provides support for OLE DB error processing using the OLE DB IErrorRecords interface. This interface returns one or more error records to the user. Call CDBErrorInfo::GetErrorRecords first, to get a count of error records. Then call one of the access functions, such as CDBErrorInfo::GetAllErrorInfo, to retrieve error information for each record.

#include <atldbcli.h>

Class Members

Sample

DBViewer

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CDBErrorInfo Class Members

Methods

GetErrorRecords | Gets error records for the specified object.
GetAllErrorInfo | Returns all error information contained in an error record.
GetBasicErrorInfo | Calls IErrorRecords::GetBasicErrorInfo to return basic information about the specified error.
GetCustomErrorObject | Calls IErrorRecords::GetCustomErrorObject to return a pointer to an interface on a custom error object.
GetErrorInfo | Calls IErrorRecords::GetErrorInfo to return an IErrorInfo interface pointer to the specified record.
GetErrorParameters | Calls IErrorRecords::GetErrorParameters to return the error parameters.

Data Members

m_spErrorRecords Pointer to an OLE DB IErrorRecords object.

CDBErrorInfo Overview


CDBErrorInfo::GetAllErrorInfo

HRESULT GetAllErrorInfo( ULONG ulRecordNum, LCID lcid, BSTR* pbstrDescription, GUID* pguid, DWORD* pdwHelpContext, BSTR* pbstrHelpFile, BSTR* pbstrSource );

Return Value

S_OK if successful. See IErrorRecords::GetErrorInfo in the OLE DB Programmer's Reference for other return values.

Parameters

ulRecordNum

[in] The zero-based number of the record for which to return error information.

lcid

[in] The locale ID for the error information to be returned.

pbstrDescription

[out] A pointer to a text description of the error.

pguid

[out] A pointer to the GUID of the interface that defined the error.

pdwHelpContext

[out] A pointer to the help context ID for the error.

pbstrHelpFile

[out] A pointer to a string containing the path to the help file that describes the error.

pbstrSource

[out] A pointer to a string containing the name of the component that generated the error.

Remarks

Returns all the types of error information contained in an error record.


CDBErrorInfo::GetBasicErrorInfo

HRESULT GetBasicErrorInfo( ULONG ulRecordNum, ERRORINFO* pErrorInfo );

Return Value

A standard HRESULT.

Parameters

See IErrorRecords::GetBasicErrorInfo in the OLE DB Programmer's Reference.

Remarks

Calls IErrorRecords::GetBasicErrorInfo to return basic information about the error, such as the return code and provider-specific error number.


CDBErrorInfo::GetCustomErrorObject

HRESULT GetCustomErrorObject( ULONG ulRecordNum, REFIID riid, IUnknown** ppObject );

Return Value

A standard HRESULT.

Parameters

See IErrorRecords::GetCustomErrorObject in the OLE DB Programmer's Reference.

Remarks

Calls IErrorRecords::GetCustomErrorObject to return a pointer to an interface on a custom error object.


CDBErrorInfo::GetErrorInfo

HRESULT GetErrorInfo( ULONG ulRecordNum, LCID lcid, IErrorInfo** ppErrorInfo );

Return Value

A standard HRESULT.

Parameters

See IErrorRecords::GetErrorInfo in the OLE DB Programmer's Reference.

Remarks

Calls IErrorRecords::GetErrorInfo to return an IErrorInfo interface pointer to the specified record.


CDBErrorInfo::GetErrorParameters

HRESULT GetErrorParameters( ULONG ulRecordNum, DISPPARAMS* pdispparams );

Return Value

A standard HRESULT.

Parameters

See IErrorRecords::GetErrorParameters in the OLE DB Programmer's Reference.

Remarks

Calls IErrorRecords::GetErrorParameters to return the error parameters.


CDBErrorInfo::GetErrorRecords

HRESULT GetErrorRecords( IUnknown* pUnk, const IID& iid, ULONG* pcRecords );

HRESULT GetErrorRecords( ULONG* pcRecords );

Return Value

A standard HRESULT.

Parameters

pUnk

[in] Interface to the object for which to get error records.

iid

[in] The IID of the interface associated with the error.

pcRecords

[out] A pointer to the (one-based) count of error records.

Remarks

Gets error records for the specified object. Use the first form of the function if you want to check which interface to get the error information from. Otherwise, use the second form.


CDBErrorInfo::m_spErrorRecords

CComPtr<IErrorRecords> m_spErrorRecords;

Remarks

Pointer to an IErrorRecords interface object. IErrorRecords is an interface defined by OLE DB for adding and retrieving records in an OLE DB error object. Information is passed to and from OLE DB error objects in an ERRORINFO structure. For more information, see IErrorRecords in the OLE DB Programmer's Reference.

See Also

CComPtr


CDBPropIDSet

class CDBPropIDSet : public tagDBPROPIDSET

OLE DB consumers use DBPROPIDSET structures to pass an array of property IDs for which the consumer wants to get property information. The properties identified in a single DBPROPIDSET structure belong to one property set. CDBPropIDSet inherits from the DBPROPIDSET structure and adds a constructor that initializes key fields as well as the AddPropertyID access method.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CDBPropIDSet Class Members

Methods

CDBPropIDSet | Constructor.
SetGUID | Sets the GUID of the property ID set.
AddPropertyID | Adds a property to the property ID set.

Operators

operator = Assigns the contents of one property ID set to another.

CDBPropIDSet Overview


CDBPropIDSet::AddPropertyID

void AddPropertyID( DBPROPID propid );

Parameters

propid

[in] The property ID to be added to the property ID set.

Remarks

Adds a property ID to the property ID set.


CDBPropIDSet::CDBPropIDSet

CDBPropIDSet( const GUID& guid );

CDBPropIDSet( );

Parameters

guid

[in] A GUID used to initialize the guidPropertySet field.

Remarks

The constructor initializes the rgProperties, cProperties, and (optionally) guidPropertySet fields of the DBPROPIDSET structure.


CDBPropIDSet::SetGUID

SetGUID( const GUID& guid );

Parameters

guid

[in] A GUID used to set the guidPropertySet field of the DBPROPIDSET structure.

Remarks

Sets the GUID field in the DBPROPIDSET structure. This field can be set by the constructor as well. Call this function if you use the default constructor for this class.


CDBPropIDSet::operator =

CDBPropIDSet& operator=( CDBPropIDSet& propset );

Remarks

Assigns the contents of one property ID set to another ID property set.


CDBPropSet

class CDBPropSet : public tagDBPROPSET

OLE DB providers and consumers use DBPROPSET structures to pass arrays of DBPROP structures. Each DBPROP structure represents a single property that can be set. CDBPropSet inherits from the DBPROPSET structure and adds a constructor that initializes key fields as well as the AddProperty access method.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart, CDBPropIDSet

DBPROPSET Structure, DBPROP Structure in the OLE DB Programmer's Reference


CDBPropSet Class Members

Methods

CDBPropSet | Constructor.
SetGUID | Sets the guidPropertySet field of the DBPROPSET structure.
AddProperty | Adds a property to the property set.

Operators

operator = Assigns the contents of one property set to another.

CDBPropSet Overview


CDBPropSet::AddProperty

bool AddProperty( DWORD dwPropertyID, const VARIANT& var );

bool AddProperty( DWORD dwPropertyID, LPCTSTR szValue );

bool AddProperty( DWORD dwPropertyID, LPCWSTR szValue );

bool AddProperty( DWORD dwPropertyID, bool bValue );

bool AddProperty( DWORD dwPropertyID, BYTE bValue );

bool AddProperty( DWORD dwPropertyID, short nValue );

bool AddProperty( DWORD dwPropertyID, long nValue );

bool AddProperty( DWORD dwPropertyID, float fltValue );

bool AddProperty( DWORD dwPropertyID, double dblValue );

bool AddProperty( DWORD dwPropertyID, CY cyValue );

Return Value

true if the property was successfully added. Otherwise, false.

Parameters

dwPropertyID

[in] The ID of the property to be added. Used to initialize the dwPropertyID of the DBPROP structure added to the property set.

var

[in] A variant used to initialize the property value for the DBPROP structure added to the property set.

szValue

[in] A string used to initialize the property value for the DBPROP structure added to the property set.

bValue

[in] A BYTE or boolean value used to initialize the property value for the DBPROP structure added to the property set.

nValue

[in] An integer value used to initialize the property value for the DBPROP structure added to the property set.

fltValue

[in] A floating-point value used to initialize the property value for the DBPROP structure added to the property set.

dblValue

[in] A double-precision floating-point value used to initialize the property value for the DBPROP structure added to the property set.

cy

[in] A CY currency value used to initialize the property value for the DBPROP structure added to the property set.

Remarks

Adds a property to the property set.

CDBPropSet Overview | Class Members

See Also

DBPROP Structure in the OLE DB Programmer's Reference


CDBPropSet::CDBPropSet

CDBPropSet( const GUID& guid );

CDBPropSet( );

Parameters

guid

[in] A GUID used to initialize the guidPropertySet field.

Remarks

The constructor initializes the rgProperties, cProperties, and guidPropertySet fields of the DBPROPSET structure.

CDBPropSet Overview | Class Members

See Also

DBPROP Structure in the OLE DB Programmer's Reference


CDBPropSet::SetGUID

SetGUID( const GUID& guid );

Parameters

guid

[in] A GUID used to set the guidPropertySet field of the DBPROPSET structure.

Remarks

Sets the guidPropertySet field in the DBPROPSET structure. This field can be set by the constructor as well.


CDBPropSet::operator =

CDBPropSet& operator=( CDBPropSet& propset );

Remarks

Assigns the contents of one property set to another property set.


CDynamicAccessor

class CDynamicAccessor : public CAccessorBase

This class will dynamically create an accessor at run time based on the column information of the rowset. Use this class when you retrieve data from a data source with unknown structure.

The buffer is created and managed by this class. You can obtain data from the buffer by using the GetValue function.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart, CAccessor, CDynamicParameterAccessor, CManualAccessor


CDynamicAccessor Class Members

Methods

Close | Unbinds all of the columns, releases the allocated memory, and releases the IAccessor interface pointer in the class.
GetColumnType | Retrieves the data type of a specified column.
GetColumnFlags | Retrieves the column characteristics.
GetOrdinal | Retrieves the column index given a column name.
GetValue | Retrieves the data from the buffer.
SetValue | Stores the data to the buffer.
GetLength | Retrieves the maximum possible length of a column in bytes.
SetLength | Sets the length of the of the column in bytes
GetStatus | Retrieves the status of a specified column.
SetStatus | Sets the status of a specified column.
GetBookmark | Retrieves the bookmark for the current row.
GetColumnCount | Retrieves the number of columns in the rowset.
GetColumnName | Retrieves the name of a specified column.
GetColumnInfo | Retrieves the column meta data.
AddBindEntry | Adds a bind entry to the output columns when overriding the default accessor.

CDynamicAccessor Overview


CDynamicAccessor::AddBindEntry

HRESULT AddBindEntry( const DBCOLUMNINFO& info );

Return Value

One of the standard HRESULT values.

Parameters

info

[in] A DBCOLUMNINFO structure containing column information.

Remarks

Adds a bind entry to the output columns. Use this method when overriding the default accessor created with CDynamicAccessor (see How Do I Fetch Data?).


CDynamicAccessor::Close

void Close( );

Remarks

Call this function to unbind all of the columns, release the allocated memory, and release the IAccessor interface pointer in the class.


CDynamicAccessor::GetBookmark

bool GetBookmark( CBookmark< >* pBookmark ) const;

Return Value

Returns true if a bookmark is available. Otherwise, it returns false.

Parameters

pBookmark

[out] A pointer to the CBookmark object.

Remarks

Call this function to retrieve the bookmark for the current row.


CDynamicAccessor::GetColumnCount

ULONG GetColumnCount( ) const;

Return Value

The number of columns retrieved.

Remarks

Call this function to retrieve the number of columns.


CDynamicAccessor::GetColumnFlags

bool GetColumnFlags( ULONG nColumn, DBCOLUMNFLAGS* pFlags ) const;

Return Value

Returns true if the column characteristics are successfully retrieved. Otherwise, it returns false.

Parameters

nColumn

[in] The column number.

pFlags

[out] A pointer to a bitmask that describes column characteristics. See IColumnsInfo::GetColumnInfo in the OLE DB Programmer's Reference for more information.

Remarks

Call this function to retrieve the column characteristics. The column number is offset from one. Column zero is a special case; it is the bookmark if available.


CDynamicAccessor::GetColumnInfo

HRESULT GetColumnInfo( IRowset* pRowset, ULONG* pColumns, DBCOLUMNINFO** ppColumnInfo );

See IColumnsInfo::GetColumnInfo in the OLE DB Programmer's Reference.

Return Value

One of the standard HRESULT values.

Parameters

pRowset

[in] A pointer to the IRowset interface.

pColumns

[in] A pointer to memory in which to return the number of columns in the rowset; this number includes the bookmark column, if there is one.

ppColumnInfo

[in] A pointer to memory in which to return an array of DBCOLUMNINFO structures.

Remarks

Returns the column meta data needed by most consumers.


CDynamicAccessor::GetColumnName

LPOLESTR GetColumnName( ULONG nColumn ) const;

Return Value

The name of the specified column.

Parameters

nColumn

[in] The column number.

Remarks

Retrieves the name of the specified column.


CDynamicAccessor::GetColumnType

bool GetColumnType( ULONG nColumn, DBTYPE* pType ) const;

Return Value

Indicates success or failure.

Parameters

nColumn

[in] The column number.

pType

[out] A pointer to the data type of the specified column.

Remarks

Retrieves the data type of a specified column.

CDynamicAccessor Overview | Class Members

See Also

DBTYPE


CDynamicAccessor::GetLength

bool GetLength( ULONG nColumn, ULONG* pLength ) const;

bool GetLength( TCHAR* pColumnName, ULONG* pLength ) const;

Return Value

Returns true if the specified column is found. Otherwise, this function returns false.

Parameters

nColumn

[in] The column number.

pColumnName

[in] A pointer to the character string containing the column name.

pLength

[out] A pointer to the integer containing the length of the column in bytes.

Remarks

Retrieves the length of the specified column.

CDynamicAccessor Overview | Class Members

See Also

CDynamicAccessor::SetLength


CDynamicAccessor::GetOrdinal

bool GetOrdinal( TCHAR* pColumnName, ULONG* pOrdinal ) const;

Return Value

Returns true if a column with the specified name is found. Otherwise, this function returns false.

Parameters

pColumnName

[in] A pointer to the character string containing the column name.

pOrdinal

[out] A pointer to the column number.

Remarks

Call this function to retrieve the column number given a column name.


CDynamicAccessor::GetStatus

bool GetStatus( ULONG nColumn, DBSTATUS* pStatus ) const;

bool GetStatus( TCHAR* pColumnName, DBSTATUS* pStatus ) const;

Return Value

Returns true if the specified column is found. Otherwise, this function returns false.

Parameters

nColumn

[in] The column number.

pColumnName

[in] A pointer to the character string containing the column name.

pStatus

[out] A pointer to the variable containing the column status. See DBSTATUS in the OLE DB Programmer's Reference for more information.

Remarks

Retrieves the status of the specified column.

CDynamicAccessor Overview | Class Members

See Also

CDynamicAccessor::SetStatus


CDynamicAccessor::GetValue

void* GetValue( ULONG nColumn ) const;

void* GetValue( TCHAR* pColumnName ) const;

template < class ctype >
bool GetValue( ULONG nColumn, ctype* pData ) const;

template < class ctype >
bool GetValue( TCHAR *pColumnName, ctype* pData ) const;

Return Value

The nontemplated versions of GetValue return void*, which points to the part of the buffer that contains the specified column data. Returns NULL if the column is not found. The templated versions return true or false, which indicates success or failure.

Template Arguments

ctype

[in] A templated parameter to handle all of the various data types except TCHAR (which requires special handling). When you use a data type, GetValue uses the appropriate data type.

Parameters

nColumn

[in] The column number.

pColumnName

[in] The column name.

pData

[out] The pointer to the contents of the specified column.

Remarks

Retrieves the data for a specified column. Use the nontemplated versions to return a column that contains a string and the templated versions for other data types.


CDynamicAccessor::SetLength

bool SetLength( ULONG nColumn, ULONG nLength );

bool SetLength( TCHAR* pColumnName, ULONG nLength );

Return Value

Returns true if the specified column length is set successfully. Otherwise, this function returns false.

Parameters

nColumn

[in] The column number.

nLength

[in] The length of the column in bytes.

pColumnName

[in] A pointer to the column name.

Remarks

Sets the length of the specified column.

CDynamicAccessor Overview | Class Members

See Also

CDynamicAccessor::GetLength


CDynamicAccessor::SetStatus

bool SetStatus( ULONG nColumn, DBSTATUS status );

bool SetStatus( TCHAR* pColumnName, DBSTATUS status );

Return Value

Returns true if the specified column status is set successfully. Otherwise, this function returns false.

Parameters

nColumn

[in] The column number.

status

[in] The column status. See DBSTATUS in the OLE DB Programmer's Reference for more information.

pColumnName

[in] A pointer to the column name.

Remarks

Sets the status of the specified column.

CDynamicAccessor Overview | Class Members

See Also

CDynamicAccessor::GetStatus


CDynamicAccessor::SetValue

template < class ctype >
bool SetValue( TCHAR *pColumnName, const ctype& data );

template < class ctype >
bool SetValue( ULONG nColumn, const ctype& data );

Return Value

Returns true if the specified column exists. Otherwise, it returns false.

Template Arguments

ctype

[in] A templated parameter to handle all of the various data types except TCHAR (which requires special handling). When you use a data type, SetValue uses the appropriate data type.

Parameters

pColumnName

[in] The column name.

data

[in] The pointer to the memory containing the data.

nColumn

[in] The column number.

Remarks

Stores data to a specified column.


CDynamicParameterAccessor

class CDynamicParameterAccessor : public CDynamicAccessor

This class is similar to the CDynamicAccessor class, but it obtains the parameter information to be set by calling the ICommandWithParameters interface. The provider must support ICommandWithParameters for this class to be used.

The buffer is created and managed by this class. You can obtain parameter data from the buffer by using the GetParam and GetParamType functions.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart, CAccessor, CDynamicAccessor, CManualAccessor


CDynamicParameterAccessor Class Members

Methods

CDynamicParameterAccessor | The constructor.
GetParam | Retrieves the parameter data from the buffer.
SetParam | Sets the buffer using the parameter data.
GetParamCount | Retrieves the number of parameters in the accessor.
GetParamName | Retrieves the name of a specified parameter.
GetParamType | Retrieves the data type of a specified parameter.

CDynamicParameterAccessor Overview


CDynamicParameterAccessor::CDynamicParameterAccessor

CDynamicParameterAccessor( );

Remarks

The constructor.


CDynamicParameterAccessor::GetParam

void* GetParam( ULONG nParam ) const;

void* GetParam( TCHAR* pParamName ) const;

template < class ctype >
bool GetParam( ULONG nParam, ctype* pData ) const;

template < class ctype >
bool GetParam( TCHAR* pParamName, ctype* pData ) const;

Return Value

For nontemplated versions, points to the memory containing the data retrieved from the buffer. For templated versions, returns true or false depending on success or failure.

Template Arguments

ctype

The data type.

Parameters

nParam

[in] The parameter number.

pParamName

[in] The parameter name.

pData

[out] The pointer to the memory containing the data retrieved from the buffer.

Remarks

Retrieves the data for a specified parameter from the parameter buffer.


CDynamicParameterAccessor::GetParamCount

ULONG GetParamCount( ) const;

Return Value

The number of parameters.

Remarks

Call this function to retrieve the number of parameters stored in the buffer.


CDynamicParameterAccessor::GetParamName

LPOLESTR GetParamName( ULONG ulParam ) const;

Return Value

The name of the specified parameter.

Parameters

ulParam

[in] The parameter number.

Remarks

Retrieves the name of the specified parameter.


CDynamicParameterAccessor:GetParamType

bool GetParamType( ULONG nParam , DBTYPE* pType ) const;

Return Value

Returns true if success. Otherwise, it returns false.

Parameters

nParam

[in] The parameter number.

pType

[out] The data type of the specified parameter.

Remarks

Retrieves the data type of a specified parameter.


CDynamicParameterAccessor:SetParam

template < class ctype >
bool SetParam( ULONG nParam, ctype* pData ) const;

template < class ctype >
bool SetParam( TCHAR* pParamName, ctype* pData ) const;

Return Value

Returns true if success. Otherwise, it returns false.

Template Arguments

ctype

The data type.

Parameters

nParam

[in] The parameter number.

pParamName

[in] The parameter name.

pData

[in] The pointer to the memory containing the data to be written to the buffer.

Remarks

Sets the parameter buffer using the specified data.


CEnumerator

class CEnumerator : public CAccessorRowset< CAccessor <CEnumeratorAccessor >>

Uses an OLE DB enumerator object, which exposes the ISourcesRowset interface to return a rowset describing all data sources and enumerators.

You can retrieve the ISourcesRowset data indirectly from this class. See the CatDB sample file ENUMDLG.CPP, where you can find an example of using ISourcesRowset data from the CEnumeratorAccessor class.

#include <atldbcli.h>

Class Members

Samples CatDB | DBViewer

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CEnumerator Class Members

Methods

Open | Opens the enumerator.
GetMoniker | Retrieves the Imoniker interface for the current record.
Find | Searches through available providers (data sources) looking for one with the specified name.

CEnumerator Overview


CEnumerator::Find

bool Find( TCHAR* szSearchName );

Return Value

true if the name was found. Otherwise, false.

Parameters

szSearchName

[in] The name to search for.

Remarks

Looks for a specified name among available providers. This name maps to the SOURCES_NAME member of the ISourcesRowset interface.


CEnumerator::GetMoniker

HRESULT GetMoniker( LPMONIKER* ppMoniker ) const;

HRESULT GetMoniker( LPMONIKER* ppMoniker, LPCTSTR lpszDisplayName ) const;

Return Value

A standard HRESULT.

Parameters

ppMoniker

[out] The moniker parsed from the display name (CEnumeratorAccessor::m_szParseName) of the current row.

lpszDisplayName

[in] The display name to parse.

Remarks

Parses the display name to extract the component of the string that can be converted into a moniker.


CEnumerator::Open

HRESULT Open( LPMONIKER* pMoniker );

HRESULT Open( const CLSID* pClsid = &CLSID_OLEDB_ENUMERATOR );

HRESULT Open( const CEnumerator& enumerator );

Return Value

A standard HRESULT.

Parameters

pMoniker

[in] A pointer to a moniker for an enumerator.

pClsid

[in] A pointer to the CLSID of an enumerator.

enumerator

[in] A reference to an enumerator.

Remarks

Binds the moniker for the enumerator, if one is specified, then retrieves the rowset for the enumerator by calling ISourcesRowset::GetSourcesRowset.


CEnumeratorAccessor

class CEnumeratorAccessor

This class is used by CEnumerator to access the data from the enumerator rowset. This rowset consists of the data sources and enumerators visible from the current enumerator.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CEnumeratorAccessor Class Members

Data Members

m_bIsParent | A variable indicating whether the enumerator is a parent enumerator, if the row is an enumerator.
m_nType | A variable indicating whether the row describes a data source or an enumerator.
m_szDescription | The description of the data source or enumerator.
m_szName | The name of the data source or enumerator.
m_szParseName | String to pass to IParseDisplayName to obtain a moniker for the data source or enumerator.

CEnumeratorAccessor Overview


CEnumeratorAccessor::m_bIsParent

VARIANT_BOOL m_bIsParent;

Remarks

A variable indicating whether the enumerator is a parent enumerator, if the row is an enumerator. See ISourcesRowset::GetSourcesRowset in the OLE DB Programmer's Reference for more information.


CEnumeratorAccessor::m_nType

USHORT m_nType;

Remarks

A variable indicating whether the row describes a data source or an enumerator. See ISourcesRowset::GetSourcesRowset in the OLE DB Programmer's Reference for more information.


CEnumeratorAccessor::m_szDescription

WCHAR m_szDescription[129];

Remarks

The description of the data source or enumerator. See ISourcesRowset::GetSourcesRowset in the OLE DB Programmer's Reference for more information.


CEnumeratorAccessor::m_szName

WCHAR m_szName[129];

Remarks

The name of the data source or enumerator. See ISourcesRowset::GetSourcesRowset in the OLE DB Programmer's Reference for more information.


CEnumeratorAccessor::m_szParseName

WCHAR m_szParseName[129];

Remarks

String to pass to IParseDisplayName to obtain a moniker for the data source or enumerator. See ISourcesRowset::GetSourcesRowset in the OLE DB Programmer's Reference for more information.


CManualAccessor

class CManualAccessor : public CAccessorBase

This class represents an accessor type designed for advanced use. Using CManualAccessor, you can specify the parameter and output column binding by run-time function calls.

#include <atldbcli.h>

Class Members

Sample DBViewer

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart, CAccessor, CDynamicAccessor, CDynamicParameterAccessor


CManualAccessor Class Members

Methods

AddBindEntry | Adds a bind entry to the output columns.
AddParameterEntry | Adds a parameter entry to the parameter accessor.
CreateAccessor | Allocates memory for the column bind structures and initializes the column data members.
CreateParameterAccessor | Allocates memory for the parameter bind structures and initializes the parameter data members.

CManualAccessor Overview


CManualAccessor::AddBindEntry

void AddBindEntry( ULONG nOrdinal, DBTYPE wType, ULONG nColumnSize, void* pData, void* pLength = NULL, void* pStatus = NULL );

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] Column number.

wType

[in] Data type.

nColumnSize

[in] Column size in bytes.

pData

[in] A pointer to the column data stored in the buffer.

pLength

[in] A pointer to the field length, if required.

pStatus

[in] A pointer to the variable to be bound to the column status, if required.

Remarks

Adds a bind entry to the output columns. To use this function, you must first call CreateAccessor. You cannot add more entries than the number of columns specified in CreateAccessor.

CManualAccessor Overview | Class Members

See Also

DBViewer sample


CManualAccessor::AddParameterEntry

void AddParameterEntry( ULONG nOrdinal, DBTYPE wType, ULONG nColumnSize, void* pData, void* pLength = NULL, void* pStatus = NULL, DBPARAMIO eParamIO = DBPARAMIO_INPUT );

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] Parameter number.

wType

[in] Data type.

nColumnSize

[in] Column size in bytes.

pData

[in] A pointer to the column data stored in the buffer.

pLength

[in] A pointer to the field length, if required.

pStatus

[in] A pointer to the variable to be bound to the column status, if required.

eParamIO

[in] Specifies whether the parameter with which the binding is associated is an input, input/output, or output parameter.

Remarks

Adds a parameter entry to the parameter entry structures. To use this function, you must first call CreateParameterAccessor.

CManualAccessor Overview | Class Members

See Also

CManualAccessor::AddBindEntry, DBViewer sample


CManualAccessor::CreateAccessor

HRESULT CreateAccessor( int nBindEntries, void* pBuffer, ULONG nBufferSize );

Return Value

One of the standard HRESULT values.

Parameters

nBindEntries

[in] Number of columns. This number should match the number of calls to the CManualAccessor::AddBindEntry function.

pBuffer

[in] A pointer to the buffer where the output columns are stored.

nBufferSize

[in] The size of the buffer in bytes.

Remarks

Call this function to allocate memory for the column bind structures and initialize the column data members. Call this function before you call the CManualAccessor::AddBindEntry function.

CManualAccessor Overview | Class Members

See Also

DBViewer sample


CManualAccessor::CreateParameterAccessor

HRESULT CreateParameterAccessor( int nBindEntries, void* pBuffer, ULONG nBufferSize );

Return Value

One of the standard HRESULT values.

Parameters

nBindEntries

[in] Number of columns.

pBuffer

[in] A pointer to the buffer where the input columns are stored.

nBufferSize

[in] The size of the buffer in bytes.

Remarks

Call this function to allocate memory for the parameter bind structures and initialize the parameter data members. You must call this function before calling AddParameterEntry.

CManualAccessor Overview | Class Members

See Also

CManualAccessor::CreateAccessor, CManualAccessor::AddParameterEntry


CMultipleResults

class CMultipleResults

To handle multiple result sets, CCommand must inherit from this class. If you want a command to handle multiple result sets, use CMultipleResults for the CCommand template argument TMultiple.

#include <atldbcli>

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CNoAccessor

class CNoAccessor

This class can be used as a template argument (TAccessor) for template classes, such as CCommand and CTable, that require an accessor class argument. Use CNoAccessor as a template argument when you do not want the class to support parameters or output columns.

#include <atldbcli.h>

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CNoMultipleResults

class CNoMultipleResults

Used as a template argument (TMultiple) to CCommand to create an optimized command that handles a single result set. If you want a command to handle multiple result sets, use CMultipleResults instead.

#include <atldbcli.h>

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CNoRowset

class CNoRowset

This class can be used as a template argument (TRowset) for CCommand or CTable. Use CNoRowset as a template argument if the command does not return a rowset.

#include <atldbcli>

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CRestrictions

template < class T, short nRestrictions const GUID* pguid >
class CRestrictions : public CSchemaRowset< T, nRestrictions >

Parameters

T

The class used for the accessor.

nRestrictions

The number of restriction columns for the schema rowset.

pguid

A pointer to the GUID for the schema.

Remarks

CRestrictions is a generic class that allows you to specify restrictions for schema rowsets.

#include <atldbsch.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CRestrictions Class Members

Operations

Open Returns a result set according to the user-supplied restrictions.

CRestrictions Overview

See Also

Schema Rowset Classes and Typedef Classes


CRestrictions::Open

HRESULT Open( const CSession& session, LPCTSTR lpszParam1 = NULL, LPCTSTR lpszParam2 = NULL, LPCTSTR lpszParam3 = NULL, LPCTSTR lpszParam4 = NULL, LPCTSTR lpszParam5 = NULL, LPCTSTR lpszParam6 = NULL, LPCTSTR lpszParam7 = NULL );

Return Value

One of the standard HRESULT values.

Parameters

session

[in] Specifies an existing session object used to connect to the data source.

lpszParam

[in] Specifies the restrictions on the schema rowset.

Remarks

You can specify a maximum of seven restrictions on a schema rowset. See IDBSchemaRowset for information about the defined restrictions on each schema rowset.

CRestrictions Overview

See Also

Schema Rowset Classes and Typedef Classes


CRowset

class Rowset

In OLE DB, a rowset is the object through which a program sets and retrieves data. CRowset encapsulates an OLE DB rowset object and several related interfaces and provides manipulation methods for rowset data.

#include <atldbcli.h>

Class Members

Sample

DBViewer

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CRowset Class Members

Methods

CRowset | Constructor.
Close | Releases rows and the current IRowset interface.
AddRefRows | Increments the reference count associated with the current row.
ReleaseRows | Calls IRowset::ReleaseRows to release the current row handle.
Compare | Compares two bookmarks using IRowsetLocate::Compare.
IsSameRow | Compares the specified row with the current row.
MovePrev | Moves to the previous record.
MoveNext | Fetches data from the next sequential row or a specified number of positions beyond the next row.
MoveFirst | Repositions the next-fetch location to the initial position.
MoveLast | Moves to the last record.
MoveToBookmark | Fetches the row marked by a bookmark or the row at a specified offset from that bookmark.
GetDataHere | Gets data from the specified buffer.
Insert | Creates and inserts a new row using IRowsetChange:InsertRow.
Delete | Deletes rows from the row set using IRowsetChange:DeleteRows.
GetData | Retrieves data from the rowset's copy of the row.
GetOriginalData | Gets the data most-recently fetched from or transmitted to the data source, ignoring pending changes.
SetData | Sets data values in one or more columns of a row using IRowsetChange:SetData.
GetRowStatus | Returns the status of all rows.
Undo | Undoes any changes made to a row since the last fetch or Update.
Update | Transmits any changes made to a row since the last fetch or Update.
GetApproximatePosition | Returns the approximate position of a row corresponding to a bookmark.
MoveToRatio | Fetches rows starting from a fractional position in the rowset.

Data Members

m_pRowset Points to an OLE DB IRowset.

CRowset Overview


CRowset::CRowset

CRowset();

CRowset( IRowset* pRowset );

Parameters

pRowset

[in] Pointer to an IRowset interface to be associated with this class.

Remarks

Creates a new CRowset object and (optionally) associates it with an IRowset interface supplied as a parameter.


CRowset::AddRefRows

HRESULT AddRefRows( );

Return Value

A standard HRESULT.

Parameters

None.

Remarks

Calls IRowset::AddRefRows to increment, by one, the reference count associated with the current row handle.


CRowset::Close

void Close( );

Remarks

Releases rows and the current IRowset interface.


CRowset::Compare

HRESULTCompare( const CBookmarkBase& bookmark1, const CBookmarkBase& bookmark2, DBCOMPARE* pComparison );

Return Value

A standard HRESULT.

Parameters

See IRowsetLocate::Compare.

Bookmark1

[in] The first bookmark to compare.

Bookmark2

[in] The second bookmark to compare.

pComparison

[out] Pointer to the result of the comparison.

Remarks

Compares two bookmarks using IRowsetLocate::Compare.


CRowset::Delete

HRESULT Delete( );

Return Value

A standard HRESULT.

Remarks

Calls IRowsetChange::DeleteRows to delete the current row from the rowset.


CRowset::GetApproximatePosition

HRESULT GetApproximatePosition( const CBookmarkBase*& pBookmark, ULONG* pPosition, ULONG* pcRows );

Return Value

A standard HRESULT.

Parameters

pBookmark

[in] A pointer to a bookmark that identifies the row whose position is to be found. NULL if only the row count is required.

pPosition

[out] A pointer to the location where GetApproximatePosition returns the position of the row. NULL if the position is not required.

pcRows

[out] A pointer to the location where GetApproximatePosition returns the total number of rows. NULL if the row count is not required.

Remarks

Returns the approximate position of a row corresponding to a bookmark.

CRowset Overview | Class Members

See Also

IRowsetScroll::GetApproximatePosition


CRowset::GetData

HRESULT GetData( );

HRESULT GetData( int nAccessor );

Return Value

A standard HRESULT.

Parameters

nAccessor

[in] The (zero-offset) index number of the accessor to use for accessing the data.

Remarks

Retrieves data from the rowset's copy of the row. If you specify an accessor that is not an autoaccessor in BEGIN_ACCESSOR, use this method to explicitly get the data by passing the accessor number.


CRowset::GetDataHere

HRESULT GetDataHere( int nAccessor, void* pBuffer );

Return Value

A standard HRESULT.

Parameters

nAccessor

[in] The index number of the accessor to use for accessing the data.

pBuffer

[out] A buffer into which to place the data for the current record.

Remarks

Retrieves data from the current row and places it into the specified buffer. For an example of how to use this function, see the MultiRead sample.

CRowset Overview | Class Members

See Also

CRowset::GetData


CRowset::GetOriginalData

HRESULT GetOriginalData( );

Return Value

A standard HRESULT.

Remarks

Gets the data most-recently fetched from or transmitted to the data source. Does not get values based on pending changes.

CRowset Overview | Class Members

See Also

IRowsetUpdate::GetOriginalData


CRowset::GetRowStatus

HRESULT GetRowStatus( DBPENDINGSTATUS* pStatus ) const;

Return Value

A standard HRESULT.

Parameters

pStatus

[out] A pointer to a location where GetRowStatus returns the status value.

Remarks

Returns the status of all rows.

CRowset Overview | Class Members

See Also

IRowsetUpdate::GetRowStatus


CRowset::Insert

HRESULT Insert( int nAccessor = 0, bool bGetHRow = false );

Return Value

A standard HRESULT.

Parameters

nAccessor

[in] The number of the accessor to use for inserting the data.

bGetHRow

[in] Indicates whether the handle for the inserted row is retrieved.

Remarks

Creates and initializes a new row using data from the accessor.


CRowset::IsSameRow

HRESULT IsSameRow( HROW hRow ) const;

Return Value

A standard HRESULT. S_OK indicates the rows are the same. For other values see IRowsetIndentity::IsSameRowin the OLE DB Programmer's Reference.

Parameters

hRow

[in] A Handle to the row to compare to the current row.

Remarks

Compares the specified row with the current row.


CRowset::MoveFirst

HRESULT MoveFirst( );

Return Value

A standard HRESULT.

Remarks

Repositions the next-fetch location to the initial position (the position that was the next-fetch location when the rowset was created) and retrieves the initial row.

CRowset Overview | Class Members

See Also

CRowset::MoveNext, CRowset::MoveToBookmark, CRowset::MovePrev, CRowset::MoveLast, IRowset::RestartPosition


CRowset::MoveLast

HRESULT MoveLast( );

Return Value

A standard HRESULT.

Remarks

Moves the cursor to the last record.

CRowset Overview | Class Members

See Also

CRowset::MoveNext, CRowset::MoveToBookmark, CRowset::MovePrev


CRowset::MoveNext

HRESULT MoveNext( );

HRESULT MoveNext( LONG lSkip, bool bForward );

Return Value

A standard HRESULT.

Parameters

lSkip

[in] The number of rows to skip before fetching.

bForward

[in] Pass true to move forward to the next record, false to move backward.

Remarks

Fetches the next sequential row from the CRowset object, remembering the previous position. Optionally, you can choose to skip ahead lSkip rows or move backward.

CRowset Overview | Class Members

See Also

CRowset::MoveFirst, CRowset::MoveToBookmark, CRowset::MovePrev, CRowset::MoveLast


CRowset::MovePrev

HRESULT MovePrev( );

Return Value

A standard HRESULT.

Remarks

Moves the cursor to the previous record.

CRowset Overview | Class Members

See Also

CRowset::MoveNext, CRowset::MoveToBookmark, CRowset::MoveLast


CRowset::MoveToBookmark

HRESULT MoveToBookmark( const CBookmarkBase& bookmark, LONG lSkip );

Return Value

A standard HRESULT.

Parameters

bookmark

[in] A bookmark marking the location from which you want to fetch data.

lSkip

[in] The number count of rows from the bookmark to the target row. If lSkip is zero, the first row fetched is the bookmarked row. If lSkip is 1, the first row fetched is the row after the bookmarked row. If lSkip is –1, the first row fetched is the row before the bookmarked row.

Remarks

Fetches the row marked by a bookmark or the row at a specified offset (lSkip) from that bookmark.

CRowset Overview | Class Members

See Also

CRowset::MoveNext, CRowset::MoveFirst, IRowsetLocate::GetRowsAt, CRowset::MovePrev, CRowset::MoveLast


CRowset::MoveToRatio

HRESULT MoveToRatio( ULONG nNumerator, ULONG nDenominator, bool bForward = true );

Return Value

A standard HRESULT.

Parameters

nNumerator

[in] The numerator used to determine the fractional positional from which to fetch data.

nDenominator

[in] The denominator used to determine the fractional positional from which to fetch data.

bForward

[in] Indicates whether to move forward or backward. The default is forward.

Remarks

Fetches rows starting from a fractional position in the rowset, according (roughly) to the following formula:

( nNumerator *  RowsetSize ) / nDenominator

Where RowsetSize is the size of the rowset, measured in rows. The accuracy of this formula depends on the specific provider. For details, see IRowsetScroll::GetRowsAtRatio.


CRowset::ReleaseRows

HRESULT ReleaseRows \( );

Return Value

A standard HRESULT.

Remarks

Calls IRowset::ReleaseRows to release the current row handle.


CRowset::SetData

HRESULT SetData( );

HRESULT SetData( int nAccessor );

Return Value

A standard HRESULT.

Parameters

nAccessor

[in] The number of the accessor to use for accessing the data.

Remarks

Sets data values in one or more columns of a row. In the case of the SetData function that accepts no arguments, all accessors are used for updating.


CRowset::Undo

HRESULT Undo( ULONG* pcRows = NULL, HROW* phRow = NULL, DBROWSTATUS* pStatus = NULL );

Return Value

A standard HRESULT.

Parameters

pcRows

[out] A pointer to the location where Undo returns the number of rows it attempted to undo if required.

phRow

[out] A pointer to the location where Undo returns an array of handles to all rows it attempted to undo if required.

pStatus

[out] A pointer to the location where Undo returns the row status value. No status is returned if pStatus is null.

Remarks

Undoes any changes made to a row since the last fetch or Update.

CRowset Overview | Class Members

See Also

IRowsetUpdate::Undo


CRowset::Update

HRESULT Update( ULONG* pcRows = NULL, HROW* phRow = NULL, DBROWSTATUS* pStatus = NULL );

Return Value

A standard HRESULT.

Parameters

pcRows

[out] A pointer to the location where Update returns the number of rows it attempted to update, if required.

phRow

[out] A pointer to the location where Update returns the handle of the row it attempted to update. No handle is returned if phRow is null.

pStatus

[out] A pointer to the location where Update returns the row status value. No status is returned if pStatus is null.

Remarks

Transmits any pending changes made to a row since the last fetch or Update.

CRowset Overview | Class Members

See Also

IRowsetUpdate::Update


CRowset::m_spRowset

CComPtr<IRowset> m_spRowset;

Remarks

An IRowset interface used by CRowset to store and access data.


CSession

class CSession

A CSession object represents a single database access session. One or more sessions can be associated with each provider connection (data source), which is represented by a CDataSource object. To create a new CSession for a CDataSource, call CSession::Open. To begin a database transaction, CSession provides the StartTransaction method. Once a transaction is started, you can commit to it using the Commit method, or cancel it using the Abort method.

#include <atldbcli.h>

Class Members

Sample

CatDB

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


CSession Class Members

Methods

Open | Opens a new session.
Close | Closes the session.
StartTransaction | Begins a new transaction for this session.
Abort | Cancels (terminates) the transaction.
Commit | Commits the transaction.
GetTransactionInfo | Returns information regarding a transaction.

Data Members

m_spOpenRowset Points to the IOpenRowset interface for this session.

CSession Overview


CSession::Abort

HRESULT Abort( BOID* pboidReason = NULL, BOOL bRetaining = FALSE, BOOL bAsync = FALSE );

Return Value

A standard HRESULT.

Parameters

See ITransaction::Abort in the OLE DB Programmer's Reference.

Remarks

Terminates the transaction.


CSession::Close

void Close ( );

Remarks

Closes the session, which was opened by CSession::Open. Releases the m_spOpenRowset pointer.


CSession::Commit

HRESULT Commit( BOOL bRetaining = FALSE, DWORD grfTC = XACTTC_SYNC, DWORD grfRM = 0) const;

Return Value

A standard HRESULT.

Parameters

See ITransaction::Commit in the OLE DB Programmer's Reference.

Remarks

Commits the transaction. For more information, see ITransaction::Commit.


CSession::GetTransactionInfo

HRESULT GetTransactionInfo( XACTTRANSINFO* pInfo ) const;

Return Value

A standard HRESULT.

Parameters

See ITransaction::GetTransactionInfo in the OLE DB Programmer's Reference.

Remarks

See ITransaction::GetTransactionInfo in the OLE DB Programmer's Reference.


CSession::Open

HRESULT Open( const CDataSource& ds );

Return Value

A standard HRESULT.

Parameters

ds

[in] The data source for which the session is to be opened.

Remarks

Creates a new session for the data source object ds. You must open the data source object using CDataSource::Open before passing it to CSession::Open.


CSession::StartTransaction

HRESULT StartTransaction( ISOLEVEL isoLevel = ISOLATIONLEVEL_READCOMMITTED, ULONG isoFlags = 0, ITransactionOptions* pOtherOptions = NULL, ULONG* pulTransactionLevel = NULL ) const;

Return Value

A standard HRESULT.

Parameters

See ITransactionLocal::StartTransaction in the OLE DB Programmer's Reference.

Remarks

See ITransactionLocal::StartTransaction in the OLE DB Programmer's Reference.


CSession::m_spOpenRowset

CComPtr<IOpenRowset> m_spOpenRowset;

Remarks

A smart pointer to the IOpenRowset interface for this session.

CSession Overview | Class Members

See Also

CComPtr


CTable

template <class TAccessor = CNoAccessor, class TRowset = CRowset >
class Table : public CAccessorRowset <T, TRowset>

Parameters

TAccessor

An accessor class.

TRowset

A rowset class.

Provides a means to directly access a simple rowset (one with no parameters). See CCommand for information on how to execute a command to access a rowset.

#include <atldbcli.h>

Class Members

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart, IOpenRowset::OpenRowset


CTable Class Members

Methods

Open Opens the table.

CTable Overview


CTable::Open

HRESULT Open( const CSession& session, LPCTSTR szTableName, DBPROPSET* pPropSet = NULL );

HRESULT Open( const CSession& session, DBID& dbid, DBPROPSET* pPropSet = NULL );

Return Value

A standard HRESULT.

Parameters

session

[in] The session for which the table is opened.

szTableName

[in] The string containing the name of a table to open.

pPropSet

[in/out] An array of DBPROPSET structures containing properties and values to be set. The properties specified in these structures must belong to the Rowset property group.

dbid

[in] The DBID of the table to open.

Remarks

Opens the table. For more details, see IOpenRowset::OpenRowset in the OLE DB Programmer's Reference.


IRowsetNotifyImpl

IRowsetNotifyImpl provides a dummy implementation for IRowsetNotify, with empty functions for the IRowsetNotify methods OnFieldChange, OnRowChange, and OnRowsetChange. If you inherit from this class when you implement an IRowsetNotify interface, you can implement only the methods you need. You also need to provide empty implementations for the other methods yourself.

#include <atldbcli.h>

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart


Schema Rowset Classes and Typedef Classes

A schema is a collection of database objects that are owned, or have been created by, a particular user. A catalog can contain one or more schemas, but must always contain a schema called INFORMATION_SCHEMA, which contains the views and domains of the information schema. Schema information in OLE DB is retrieved using predefined schema rowsets, and includes types, tables, columns, indexes, views, assertions and constraints, statistics, character sets, collations, and domains.

Schema rowsets are predefined rowsets representing metadata. Schema rowsets are generally used in dynamic programming, where the database structure is not known at compile time. You can use these schema rowsets to obtain information about a database at run time.

Use the typedef classes to instantiate the schema rowsets. The corresponding typedef and schema rowset classes are listed below. You must call CRestrictions::Open after you have created an instance of the schema rowset. This method returns a result set based on the restrictions you specify. See IDBSchemaRowset for information on restriction columns associated with each schema rowset.

The following table displays each OLE DB Schema Rowset and its corresponding OLE DB Templates typedef class and info class.

OLE DB Schema Rowset Typedef class Info class
ASSERTIONS CAssertions CAssertionInfo
CATALOGS CCatalogs CCatalogInfo
CHARACTER_SETS CCharacterSets CCharacterSetInfo
COLLATIONS CCollations CCollationInfo
COLUMN_PRIVILEGES CColumnPrivileges CColumnPrivilegeInfo
COLUMNS CColumns CColumnsInfo
CONSTRAINT_COLUMN_USAGE CConstraintColumnUsage CConstraintColumnUsageInfo
CONSTRAINT_TABLE_USAGE CConstraintTableUsage CConstraintTableUsageInfo
CHECK_CONSTRAINTS CCheckConstraints CCheckConstraintInfo
COLUMN_DOMAIN_USAGE CColumnDomainUsage CColumnDomainUsageInfo
FOREIGN_KEYS CForeignKeys CForeignKeysInfo
INDEXES CIndexes CIndexInfo
KEY_COLUMN_USAGE CKeyColumnUsage CKeyColumnUsageInfo
PRIMARY_KEYS CPrimaryKeys CPrimaryKeyInfo
PROCEDURES CProcedures CProcedureInfo
PROCEDURE_COLUMNS CProcedureColumns CProcedureColumnInfo
PROCEDURE_PARAMETERS CProcedureParameters CProcedureParameterInfo
PROVIDER_TYPES CProviderTypes CProviderInfo
REFERENTIAL_CONSTRAINTS CReferentialConstraints CReferentialConstraintInfo
SCHEMATA CSchemata CSchemataInfo
SQL_LANGUAGES CSQLLanguages CSQLLanguageInfo
STATISTICS CStatistics CStatisticInfo
TABLE_CONSTRAINTS CTableConstraints CTableConstraintInfo
TABLES CTables CTableInfo
TABLE_PRIVILEGES CTablePrivileges CTablePrivilegeInfo
TRANSLATIONS CTranslations CTranslationInfo
USAGE_PRIVILEGES CUsagePrivileges CUsagePrivilegeInfo
VIEW_COLUMN_USAGE CViewColumnUsage CViewColumnInfo
VIEWS CViews CViewInfo
VIEW_TABLE_USAGE CViewTableUsage CViewTableInfo

#include <atldbsch.h>

See Also

CRestrictions


Schema Rowset Classes


CAssertions, CAssertionInfo

Remarks

Call the typedef class CAssertions to implement its parameter class CAssertionInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the assertions defined in the catalog that are owned by a given user.

The following table lists the class data members for CAssertionInfo and their corresponding OLE DB Columns. See ASSERTIONS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | CONSTRAINT_CATALOG
m_szSchema | CONSTRAINT_SCHEMA
m_szName | CONSTRAINT_NAME
m_bIsDeferrable | IS_DEFERRABLE
m_bInitiallyDeferred | INITIALLY_DEFERRED
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CCatalogs, CCatalogInfo

Remarks

Call the typedef class CCatalogs to implement its parameter class CCatalogInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the physical attributes associated with catalogs accessible from the DBMS.

The following table lists the class data members and their corresponding OLE DB Columns. See CATALOGS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szName | CATALOG_NAME
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CCharacterSets, CCharacterSetInfo

Remarks

Call the typedef class CCharacterSets to implement its parameter class CCharacterSetInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the character sets defined in the catalog that are accessible to a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See CHARACTER_SETS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | CHARACTER_SET_CATALOG
m_szSchema | CHARACTER_SET_SCHEMA
m_szName | CHARACTER_SET_NAME
m_szFormOfUse | FORM_OF_USE
m_nNumCharacters | NUMBER_OF_CHARACTERS
m_szCollateCatalog | DEFAULT_COLLATE_CATALOG
m_szCollateSchema | DEFAULT_COLLATE_SCHEMA
m_szCollateName | DEFAULT_COLLATE_NAME

#include <atldbsch.h>

See Also

CRestrictions


CCheckConstraints, CCheckConstraintInfo

Remarks

Call the typedef class CCheckConstraints to implement its parameter class CCheckConstraintInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the check constraints, defined in the catalog, that are owned by a given user. A check constraint specifies the data values or formats that are acceptable in one or more columns in a table.

The following table lists the class data members and their corresponding OLE DB Columns. See CHECK_CONSTRAINTS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | CONSTRAINT_CATALOG
m_szSchema | CONSTRAINT_SCHEMA
m_szName | CONSTRAINT_NAME
m_szCheckClause | CHECK_CLAUSE
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CCollations, CCollationInfo

Remarks

Call the typedef class CCollations to implement its parameter class CCollationInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the character collations, defined in the catalog, that are accessible to a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See COLLATIONS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | COLLATION_CATALOG
m_szSchema | COLLATION_SCHEMA
m_szName | COLLATION_NAME
m_szCharSetCatalog | CHARACTER_SET_CATALOG
m_szCharSetSchema | CHARACTER_SET_SCHEMA
m_szCharSetName | CHARACTER_SET_NAME
m_szPadAttribute | PAD_ATTRIBUTE

#include <atldbsch.h>

See Also

CRestrictions


CColumnDomainUsage, CColumnDomainUsageInfo

Remarks

Call the typedef class CColumnDomainUsage to implement its parameter class CColumnDomainUsageInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the columns, defined in the catalog, that are dependent on a domain defined in the catalog and owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See COLUMN_DOMAIN_USAGE Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | DOMAIN_CATALOG
m_szSchema | DOMAIN_SCHEMA
m_szName | DOMAIN_NAME
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID

#include <atldbsch.h>

See Also

CRestrictions


CColumnPrivileges, CColumnPrivilegeInfo

Remarks

Call the typedef class CColumnPrivileges to implement its parameter class CColumnPrivilegeInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the privileges on columns of tables, defined in the catalog, that are available to or granted by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See COLUMN_PRIVILEGES Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szGrantor | GRANTOR
m_szGrantee | GRANTEE
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID
m_szPrivilegeType | PRIVILEGE_TYPE
m_bIsGrantable | IS_GRANTABLE

#include <atldbsch.h>

See Also

CRestrictions


CColumns, CColumnsInfo

Remarks

Call the typedef class CColumns to implement its parameter class CColumnsInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the columns of tables defined in the catalog that are accessible to a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See COLUMNS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID
m_nOrdinalPosition | ORDINAL_POSITION
m_bColumnHasDefault | COLUMN_HASDEFAULT
m_szColumnDefault | COLUMN_DEFAULT
m_nColumnFlags | COLUMN_FLAGS
m_bIsNullable | IS_NULLABLE
m_nDataType | DATA_TYPE
m_guidType | TYPE_GUID
m_nMaxLength | CHARACTER_MAXIMUM_LENGTH
m_nOctetLength | CHARACTER_OCTET_LENGTH
m_nNumericPrecision | NUMERIC_PRECISION
m_nNumericScale | NUMERIC_SCALE
m_nDateTimePrecision | DATETIME_PRECISION
m_szCharSetCatalog | CHARACTER_SET_CATALOG
m_szCharSetSchema | CHARACTER_SET_SCHEMA
m_szCharSetName | CHARACTER_SET_NAME
m_szCollationCatalog | COLLATION_CATALOG
m_szCollationSchema | COLLATION_SCHEMA
m_szCollationName | COLLATION_NAME
m_szDomainCatalog | DOMAIN_CATALOG
m_szDomainSchema | DOMAIN_SCHEMA
m_szDomainName | DOMAIN_NAME
m_szDescription | DESCRIPTION

#include <atldbsch.h>

Sample

CatDB

See Also

CRestrictions


CConstraintColumnUsage, CConstraintColumnUsageInfo

Remarks

Call the typedef class CConstraintColumnUsage to implement its parameter class CConstraintColumnUsageInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the columns used by referential constraints, unique constraints, check constraints, and assertions, defined in the catalog and owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See CONSTRAINT_COLUMN_USAGE Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID
m_szConstraintCatalog | CONSTRAINT_CATALOG
m_szConstraintSchema | CONSTRAINT_SCHEMA
m_szConstraintName | CONSTRAINT_NAME

#include <atldbsch.h>

See Also

CRestrictions


CConstraintTableUsage, CConstraintTableUsageInfo

Remarks

Call the typedef class CConstraintTableUsage to implement its parameter class CConstraintTableUsageInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the tables used by referential constraints, unique constraints, check constraints, and assertions, defined in the catalog and owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See CONSTRAINT_TABLE_USAGE Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data Members | OLE DB Columns
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szConstraintCatalog | CONSTRAINT_CATALOG
m_szConstraintSchema | CONSTRAINT_SCHEMA
m_szConstraintName | CONSTRAINT_NAME

#include <atldbsch.h>

See Also

CRestrictions


CForeignKeys, CForeignKeysInfo

Remarks

Call the typedef class CForeignKeys to implement its parameter class CForeignKeysInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the foreign key columns defined in the catalog by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See FOREIGN_KEYS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szPKTableCatalog | PK_TABLE_CATALOG
m_szPKTableSchema | PK_TABLE_SCHEMA
m_szPKTableName | PK_TABLE_NAME
m_szPKColumnName | PK_COLUMN_NAME
m_guidPKColumn | PK_COLUMN_GUID
m_nPKColumnPropID | PK_COLUMN_PROPID
m_szFKTableCatalog | FK_TABLE_CATALOG
m_szFKTableSchema | FK_TABLE_SCHEMA
m_szFKTableName | FK_TABLE_NAME
m_szFKColumnName | FK_COLUMN_NAME
m_guidFKColumn | FK_COLUMN_GUID
m_nFKColumnPropID | FK_COLUMN_PROPID
m_nOrdinal | ORDINAL
m_szUpdateRule | UPDATE_RULE
m_szDeleteRule | DELETE_RULE

#include <atldbsch.h>

See Also

CRestrictions


CIndexes, CIndexInfo

Remarks

Call the typedef class CIndexes to implement its parameter class CIndexInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the indexes, defined in the catalog, that are owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See INDEXES Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szIndexCatalog | INDEX_CATALOG
m_szIndexSchema | INDEX_SCHEMA
m_szIndexName | INDEX_NAME
m_bPrimaryKey | PRIMARY_KEY
m_bUnique | UNIQUE
m_bClustered | CLUSTERED
m_nType | TYPE
m_nFillFactor | FILL_FACTOR
m_nInitialSize | INITIAL_SIZE
m_nNulls | NULLS
m_bSortBookmarks | SORT_BOOKMARKS
m_bAutoUpdate | AUTO_UPDATE
m_nNullCollation | NULL_COLLATION
m_nOrdinalPosition | ORDINAL_POSITION
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID
m_nCollation | COLLATION
m_nCardinality | CARDINALITY
m_nPages | PAGES
m_szFilterCondition | FILTER_CONDITION

#include <atldbsch.h>

See Also

CRestrictions


CKeyColumns, CKeyColumnInfo

Remarks

Call the typedef class CKeyColumns to implement its parameter class CKeyColumnInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the columns, defined in the catalog, that are constrained as keys by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See KEY_COLUMN_USAGE Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szConstraintCatalog | CONSTRAINT_CATALOG
m_szConstraintSchema | CONSTRAINT_SCHEMA
m_szConstraintName | CONSTRAINT_NAME
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID
m_nOrdinalPosition | ORDINAL_POSITION

#include <atldbsch.h>

See Also

CRestrictions


CPrimaryKeys, CPrimaryKeyInfo

Remarks

Call the typedef class CPrimaryKeys to implement its parameter class CPrimaryKeyInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the primary key columns defined in the catalog by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See PRIMARY_KEYS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID
m_nOrdinal | ORDINAL

#include <atldbsch.h>

See Also

CRestrictions


CProcedureColumns, CProcedureColumnInfo

Remarks

Call the typedef class CProcedureColumns to implement its parameter class CProcedureColumnInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class returns information about the columns of rowsets returned by procedures.

The following table lists the class data members and their corresponding OLE DB Columns. See PROCEDURE_COLUMNS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | PROCEDURE_CATALOG
m_szSchema | PROCEDURE_SCHEMA
m_szName | PROCEDURE_NAME
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID
m_nRowsetNumber | ROWSET_NUMBER
m_nOrdinalPosition | ORDINAL_POSITION
m_bIsNullable | IS_NULLABLE
m_nDataType | DATA_TYPE
m_guidType | TYPE_GUID
m_nMaxLength | CHARACTER_MAXIMUM_LENGTH
m_nOctetLength | CHARACTER_OCTET_LENGTH
m_nPrecision | NUMERIC_PRECISION
m_nScale | NUMERIC_SCALE
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CProcedureParameters CProcedureParamInfo

Remarks

Call the typedef class CProcedureParameters to implement its parameter class CProcedureParamInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class returns information about the parameters and return codes of procedures.

The following table lists the class data members and their corresponding OLE DB Columns. See PROCEDURE_PARAMETERS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | PROCEDURE_CATALOG
m_szSchema | PROCEDURE_SCHEMA
m_szName | PROCEDURE_NAME
m_szParameterName | PARAMETER_NAME
m_nOrdinalPosition | ORDINAL_POSITION
m_nType | PARAMETER_TYPE
m_bHasDefault | PARAMETER_HASDEFAULT
m_szDefault | PARAMETER_DEFAULT
m_bIsNullable | IS_NULLABLE
m_nDataType | DATA_TYPE
m_nMaxLength | CHARACTER_MAXIMUM_LENGTH
m_nOctetLength | CHARACTER_OCTET_LENGTH
m_nPrecision | NUMERIC_PRECISION
m_nScale | NUMERIC_SCALE
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CProcedures, CProcedureInfo

Remarks

Call the typedef class CProcedures to implement its parameter class CProcedureInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the procedures, defined in the catalog, that are owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See PROCEDURES Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | PROCEDURE_CATALOG
m_szSchema | PROCEDURE_SCHEMA
m_szName | PROCEDURE_NAME
m_nType | PROCEDURE_TYPE
m_szDefinition | PROCEDURE_DEFINITION
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CProviderTypes, CProviderInfo

Remarks

Call the typedef class CProviderTypes to implement its parameter class CProviderInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the (base) data types supported by the data provider.

The following table lists the class data members and their corresponding OLE DB Columns. See PROVIDER_TYPES Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szTypeName | TYPE_NAME
m_nDataType | DATA_TYPE
m_nColumnSize | COLUMN_SIZE
m_szLiteralPrefix | LITERAL_PREFIX
m_szLiteralSuffix | LITERAL_SUFFIX
m_szCreateParams | CREATE_PARAMS
m_bIsNullable | IS_NULLABLE
m_bCaseSensitive | CASE_SENSITIVE
m_nSearchable | SEARCHABLE
m_bUnsignedAttribute | UNSIGNED_ATTRIBUTE
m_bFixedPrecScale | FIXED_PREC_SCALE
m_bAutoUniqueValue | AUTO_UNIQUE_VALUE
m_szLocalTypeName | LOCAL_TYPE_NAME
m_nMinScale | MINIMUM_SCALE
m_nMaxScale | MAXIMUM_SCALE
m_guidType | GUID
m_szTypeLib | TYPELIB
m_szVersion | VERSION
m_bIsLong | IS_LONG
m_bBestMatch | BEST_MATCH

#include <atldbsch.h>

See Also

CRestrictions


CReferentialConstraints, CReferentialConstraintInfo

Remarks

Call the typedef class CReferentialConstraints to implement its parameter class CReferentialConstraintInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the referential constraints, defined in the catalog, that are owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See REFERENTIAL_CONSTRAINTS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | CONSTRAINT_CATALOG
m_szSchema | CONSTRAINT_SCHEMA
m_szName | CONSTRAINT_NAME
m_szUniqueCatalog | UNIQUE_CONSTRAINT_CATALOG
m_szUniqueSchema | UNIQUE_CONSTRAINT_SCHEMA
m_szUniqueName | UNIQUE_CONSTRAINT_NAME
m_szMatchOption | MATCH_OPTION
m_szUpdateRule | UPDATE_RULE
m_szDeleteRule | DELETE_RULE
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CSchemata, CSchemataInfo

Remarks

Call the typedef class CSchemata to implement its parameter class CSchemataInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the schemas that are owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See SCHEMATA Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | CATALOG_NAME
m_szName | SCHEMA_NAME
m_szOwner | SCHEMA_OWNER
m_szCharCatalog | DEFAULT_CHARACTER_SET_CATALOG
m_szCharSchema | DEFAULT_CHARACTER_SET_SCHEMA
m_szCharName | DEFAULT_CHARACTER_SET_NAME

#include <atldbsch.h>

See Also

CRestrictions


CSQLLanguages, CSQLLanguageInfo

Remarks

Call the typedef class CSQLLanguages to implement its parameter class CSQLLanguageInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the conformance levels, options, and dialects supported by the SQL-implementation processing data defined in the catalog.

The following table lists the class data members and their corresponding OLE DB Columns. See SQL_LANGUAGES Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szSource | SQL_LANGUAGE_SOURCE
m_szYear | SQL_LANGUAGE_YEAR
m_szConformance | SQL_LANGUAGE_CONFORMANCE
m_szIntegrity | SQL_LANGUAGE_INTEGRITY
m_szImplementation | SQL_LANGUAGE_IMPLEMENTATION
m_szBindingStyle | SQL_LANGUAGE_BINDING_STYLE
m_szProgrammingLanguage | SQL_LANGUAGE_PROGRAMMING_LANGUAGE

#include <atldbsch.h>

See Also

CRestrictions


CStatistics, CStatisticInfo

Remarks

Call the typedef class CStatistics to implement its parameter class CStatisticInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the statistics, defined in the catalog, that are owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See STATISTICS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_nCardinality | CARDINALITY

#include <atldbsch.h>

See Also

CRestrictions


CTableConstraints, CTableConstraintInfo

Remarks

Call the typedef class CTableConstraints to implement its parameter class CTableConstraintInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the table constraints, defined in the catalog, that are owned by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See TABLE_CONSTRAINTS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | CONSTRAINT_CATALOG
m_szSchema | CONSTRAINT_SCHEMA
m_szName | CONSTRAINT_NAME
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szType | CONSTRAINT_TYPE
m_bIsDeferrable | IS_DEFERRABLE
m_bInitiallyDeferred | INITIALLY_DEFERRED
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CTablePrivileges, CTablePrivilegeInfo

Remarks

Call the typedef class CTablePrivileges to implement its parameter class CTablePrivilegeInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the tables defined in the catalog that are accessible to a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See TABLE_PRIVILEGES Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szGrantor | GRANTOR
m_szGrantee | GRANTEE
m_szCatalog | TABLE_CATALOG
m_szSchema | TABLE_SCHEMA
m_szName | TABLE_NAME
m_szType | PRIVILEGE_TYPE
m_bIsGrantable | IS_GRANTABLE

#include <atldbsch.h>

See Also

CRestrictions


CTables, CTableInfo

Remarks

Call the typedef class CTables to implement its parameter class CTableInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the privileges on tables, defined in the catalog, that are available to or granted by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See TABLES Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | TABLE_CATALOG
m_szSchema | TABLE_SCHEMA
m_szName | TABLE_NAME
m_szType | TABLE_TYPE
m_guidTable | TABLE_GUID
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CTranslations, CTranslationInfo

Remarks

Call the typedef class CTranslations to implement its parameter class CTranslationInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the character translations defined in the catalog that are accessible to a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See TRANSLATIONS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | TRANSLATION_CATALOG
m_szSchema | TRANSLATION_SCHEMA
m_szName | TRANSLATION_NAME
m_szSourceCatalog | SOURCE_CHARACTER_SET_CATALOG
m_szSourceSchema | SOURCE_CHARACTER_SET_SCHEMA
m_szSourceName | SOURCE_CHARACTER_SET_NAME
m_szTargetCatalog | TARGET_CHARACTER_SET_CATALOG
m_szTargetSchema | TARGET_CHARACTER_SET_SCHEMA
m_szTargetName | TARGET_CHARACTER_SET_NAME

#include <atldbsch.h>

Sample

CatDB

See Also

CRestrictions


CUsagePrivileges, CUsagePrivilegeInfo

Remarks

Call the typedef class CUsagePrivileges to implement its parameter class CUsagePrivilegeInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the USAGE privileges on objects defined in the catalog that are available to or granted by a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See USAGE_PRIVILEGES Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szGrantor | GRANTOR
m_szGrantee | GRANTEE
m_szObjectCatalog | OBJECT_CATALOG
m_szObjectSchema | OBJECT_SCHEMA
m_szObjectName | OBJECT_NAME
m_szObjectType | OBJECT_TYPE
m_szPrivilegeType | PRIVILEGE_TYPE
m_bIsGrantable | IS_GRANTABLE

#include <atldbsch.h>

See Also

CRestrictions


CViewColumnUsage, CViewColumnInfo

Remarks

Call the typedef class CViewColumnUsage to implement its parameter class CViewColumnInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the columns on which viewed tables, defined in the catalog and owned by a given user, are dependent.

The following table lists the class data members and their corresponding OLE DB Columns. See VIEW_COLUMN_USAGE Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | VIEW_CATALOG
m_szSchema | VIEW_SCHEMA
m_szName | VIEW_NAME
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szColumnName | COLUMN_NAME
m_guidColumn | COLUMN_GUID
m_nColumnPropID | COLUMN_PROPID

#include <atldbsch.h>

See Also

CRestrictions


CViews, CViewInfo

Remarks

Call the typedef class CViews to implement its parameter class CViewInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the tables on which viewed tables, defined in the catalog and owned by a given user, are dependent.

The following table lists the class data members and their corresponding OLE DB Columns. See VIEWS Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME
m_szDefinition | VIEW_DEFINITION
m_bCheckOption | CHECK_OPTION
m_bIsUpdatable | IS_UPDATABLE
m_szDescription | DESCRIPTION

#include <atldbsch.h>

See Also

CRestrictions


CViewTableUsage, CViewTableInfo

Remarks

Call the typedef class CViewTableUsage to implement its parameter class CViewTableInfo. See Schema Rowset Classes and Typedef Classes for more information on using typedef classes.

This class identifies the viewed tables, defined in the catalog, that are accessible to a given user.

The following table lists the class data members and their corresponding OLE DB Columns. See VIEW_TABLE_USAGE Rowset in the OLE DB Programmer's Reference for more information about the schema and columns.

Data members | OLE DB columns
m_szCatalog | VIEW_CATALOG
m_szSchema | VIEW_SCHEMA
m_szName | VIEW_NAME
m_szTableCatalog | TABLE_CATALOG
m_szTableSchema | TABLE_SCHEMA
m_szTableName | TABLE_NAME

#include <atldbsch.h>

See Also

CRestrictions


Macros for OLE DB Consumer Templates

The OLE DB Consumer Templates include the following macros:

Accessor Map Macros

BEGIN_ACCESSOR | Marks the beginning of an accessor entry.
BEGIN_ACCESSOR_MAP | Marks the beginning of the accessor map entries.
END_ACCESSOR | Marks the end of an accessor entry.
END_ACCESSOR_MAP | Marks the end of the accessor map entries.

Column Map Macros

BEGIN_COLUMN_MAP | Marks the beginning of the column map entries in the user record class.
BOOKMARK_ENTRY | Represents a bookmark entry on the rowset. A bookmark entry is a special kind of column entry.
COLUMN_ENTRY | Represents a binding to the specific column in the database.
COLUMN_ENTRY_TYPE | Represents a binding to the specific column in the database. Supports type parameter.
COLUMN_ENTRY_TYPE_SIZE | Represents a binding to the specific column in the database. Supports type and size parameters
BLOB_ENTRY | Used to bind a binary large object.
BLOB_ENTRY_STATUS | Reports the status of the BLOB field.
COLUMN_ENTRY_EX | Represents a binding to the specific column in the database. Supports type, length, precision, scale, and status parameters.
COLUMN_ENTRY_LENGTH | Represents a binding to the specific column in the database. Supports the length variable.
COLUMN_ENTRY_LENGTH_STATUS | Represents a binding to the specific column in the database. Supports status and length parameters.
COLUMN_ENTRY_PS | Represents a binding to the specific column in the database. Supports precision and scale parameters.
COLUMN_ENTRY_PS_LENGTH | Represents a binding to the specific column in the database. Supports the length variable, precision and scale parameters.
COLUMN_ENTRY_PS_STATUS | Represents a binding to the specific column in the database. Supports the status variable, precision and scale parameters.
COLUMN_ENTRY_PS_LENGTH_STATUS | Represents a binding to the specific column in the database. Supports status and length variables, precision and scale parameters.
COLUMN_ENTRY_STATUS | Represents a binding to the specific column in the database. Supports the status variable.
END_COLUMN_MAP | Marks the end of the column map entries.

Command Macro

DEFINE_COMMAND Specifies the command that will be used to create the rowset when using the CCommand class.

Parameter Map Macros

BEGIN_PARAM_MAP | Marks the beginning of the parameter map entries in the user record class.
END_PARAM_MAP | Marks the end of the parameter map entries.
SET_PARAM_TYPE | Specifies COLUMN_ENTRY macros that follow the SET_PARAM_TYPE macro as input, output, or input/output.

See Also

Using the OLE DB Consumer Templates, Consumer Architecture Chart, Visual C++ OLE DB Consumer Templates


BEGIN_ACCESSOR

BEGIN_ACCESSOR( num, bAuto )

Parameters

num

[in] The zero-offset number for the accessor in this accessor map.

bAuto

[in] Specifies if this accessor is an auto accessor or a manual accessor. If true, the accessor is auto; if false, the accessor is manual. An auto accessor means data is fetched for you on move operations.

Remarks

Marks the beginning of an accessor entry. In the case of multiple accessors on a rowset, you need to specify BEGIN_ACCESSOR_MAP, and use the BEGIN_ACCESSOR macro for each individual accessor. The BEGIN_ACCESSOR macro is completed with the END_ACCESSOR macro. The BEGIN_ACCESSOR_MAP macro is completed with the END_ACCESSOR_MAP macro.

Macros for OLE DB Consumer Templates

Example

See BEGIN_ACCESSOR_MAP.

See Also

BEGIN_ACCESSOR_MAP, END_ACCESSOR, END_ACCESSOR_MAP


BEGIN_ACCESSOR_MAP

BEGIN_ACCESSOR_MAP( x, num )

Parameters

x

[in] The name of the user record class.

num

[in] The number of accessors in this accessor map.

Remarks

Marks the beginning of the accessor map entries. In the case of multiple accessors on a rowset, you need to specify BEGIN_ACCESSOR_MAP at the beginning, and use the BEGIN_ACCESSOR macro for each individual accessor. The BEGIN_ACCESSOR macro is completed with the END_ACCESSOR macro. The accessor map is completed with the END_ACCESSOR_MAP macro.

If you have only one accessor in the user record, use the macro BEGIN_COLUMN_MAP.

Macros for OLE DB Consumer Templates

Example

Here is a sample accessor map:

class CArtists : public CAccessor<CArtists>
{
public:
// Data Elements
   TCHAR m_szFirstName[20];
   TCHAR m_szLastName[30];
   short m_nAge;

// output binding map
BEGIN_ACCESSOR_MAP(CArtists, 2)
   BEGIN_ACCESSOR(0, true)
          COLUMN_ENTRY(1, m_szFirstName)
        COLUMN_ENTRY(2, m_szLastName)
   END_ACCESSOR()
   BEGIN_ACCESSOR(1, false) // not an auto accessor
        COLUMN_ENTRY(3, m_nAge)
   END_ACCESSOR()
END_ACCESSOR_MAP()
};

See Also

BEGIN_ACCESSOR, END_ACCESSOR, END_ACCESSOR_MAP


BEGIN_COLUMN_MAP

BEGIN_COLUMN_MAP( x )

Parameters

x

[in] The name of the user record class derived from CAccessor.

Remarks

Marks the beginning of a column map entry. This macro is used in the case of a single accessor on a rowset. If you have multiple accessors on a rowset, use BEGIN_ACCESSOR_MAP.

The BEGIN_COLUMN_MAP macro is completed with the END_COLUMN_MAP macro. This macro is used when there is only one accessor required in the user record.

Columns correspond to fields in the rowset you wish to bind.

Macros for OLE DB Consumer Templates

Example

Here is a sample column and parameter map:

class CArtists
{
public:
// Data Elements
   TCHAR m_szFirstName[20];
   TCHAR m_szLastName[30];
   short m_nAge;

// output binding map
BEGIN_COLUMN_MAP(CArtists)
   COLUMN_ENTRY(1, m_szFirstName)
   COLUMN_ENTRY(2, m_szLastName)
   COLUMN_ENTRY(3, m_nAge)
END_COLUMN_MAP()

// parameter binding map
BEGIN_PARAM_MAP(CArtists)
   COLUMN_ENTRY(1, m_nAge)
END_PARAM_MAP()
};

See Also

END_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX


BEGIN_PARAM_MAP

BEGIN_PARAM_MAP( x )

Parameters

x

[in] The name of the user record class.

Remarks

Marks the beginning of the parameter map entries. Parameters are used by commands.

Macros for OLE DB Consumer Templates

Example

See BEGIN_COLUMN_MAP.

See Also

END_PARAM_MAP, SET_PARAM_TYPE


BLOB_ENTRY

BLOB _ENTRY( nOrdinal, IID, flags, data )

Parameters

nOrdinal

[in] The column number.

IID

[in] Interface guid, such as IDD_ISequentialStream, used to retrieve the BLOB.

flags

[in] Storage-mode flags as defined by the OLE Structured Storage model (for example, STGM_READ).

data

[in] The corresponding data member in the user record.

Remarks

Used with BEGIN_COLUMN_MAP and END_COLUMN_MAP to bind a binary large object ( BLOB).

Macros for OLE DB Consumer Templates

Example

See How Can I Retrieve a BLOB? in FAQ: Using the OLE DB Consumer Templates.

See Also

BEGIN_COLUMN_MAP, END_COLUMN_MAP, COLUMN_ENTRY


BLOB_ENTRY_STATUS

BLOB_ENTRY_STATUS( nOrdinal, IID, flags, data, status );

Parameters

nOrdinal

[in] The column number.

IID

[in] Interface GUID, such as IDD_ISequentialStream, used to retrieve the BLOB.

flags

[in] Storage-mode flags as defined by the OLE Structured Storage model (for example, STGM_READ).

data

[in] The corresponding data member in the user record.

status

[out] The status of the BLOB field.

Remarks

Used with BEGIN_COLUMN_MAP or BEGIN_ACCESSOR_MAP to bind a binary large object ( BLOB). The same as BLOB_ENTRY, but provides the status of the BLOB field.

Macros for OLE DB Consumer Templates

Example

See How Can I Retrieve a BLOB?.

See Also

BEGIN_COLUMN_MAP, END_COLUMN_MAP, COLUMN_ENTRY


BOOKMARK_ENTRY

BOOKMARK_ENTRY( variable )

Parameters

variable

[in] The variable to be bound to the bookmark column.

Remarks

Use this macro to bind the bookmark column.

Example

This sample shows how to use the BOOKMARK_ENTRY macro:

class CArtists
{
public:
// Data Elements
   CBookmark<4> m_bookmark;
   TCHAR m_szFirstName[20];
   TCHAR m_szLastName[30];
   short m_nAge;

// output binding map
BEGIN_COLUMN_MAP(CArtists)
   BOOKMARK_ENTRY(bookmark)
   COLUMN_ENTRY(1, m_szFirstName)
   COLUMN_ENTRY(2, m_szLastName)
   COLUMN_ENTRY(3, m_nAge)
END_COLUMN_MAP()
};

Macros for OLE DB Consumer Templates

See Also

CBookMark, DBPROP_BOOKMARKS in the OLE DB Programmer's Reference.


COLUMN_ENTRY

COLUMN_ENTRY( nOrdinal, data )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number.

data

[in] The corresponding data member in the user record.

Remarks

Represents a binding on the rowset to the specific column in the rowset. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

Example

See BEGIN_COLUMN_MAP or BEGIN_ACCESSOR_MAP.

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY_EX, COLUMN_ENTRY_PS, COLUMN_ENTRY_PS_LENGTH, COLUMN_ENTRY_LENGTH, COLUMN_ENTRY_LENGTH_STATUS, COLUMN_ENTRY_PS_LENGTH_STATUS, COLUMN_ENTRY_STATUS, COLUMN_ENTRY_PS_STATUS, COLUMN_ENTRY_TYPE, COLUMN_ENTRY_TYPE_SIZE, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_EX

COLUMN_ENTRY_EX( nOrdinal, wType, nLength, nPrecision, nScale, data, length, status )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number.

wType

[in] The data type.

nLength

[in] The data size in bytes.

nPrecision

[in] The maximum precision to use when getting data and wType is DBTYPE_NUMERIC. Otherwise, this parameter is ignored.

nScale

[in] The scale to use when getting data and wType is DBTYPE_NUMERIC or DBTYPE_DECIMAL.

data

[in] The corresponding data member in the user record.

length

[in] The variable to be bound to the column length.

status

[in] The variable to be bound to the column status.

Remarks

Represents a binding on the rowset to the specific column in the database. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

Example

See BOOKMARK_ENTRY.

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_PS, COLUMN_ENTRY_PS_LENGTH, COLUMN_ENTRY_LENGTH, COLUMN_ENTRY_LENGTH_STATUS, COLUMN_ENTRY_PS_LENGTH_STATUS, COLUMN_ENTRY_STATUS, COLUMN_ENTRY_PS_STATUS, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_LENGTH

COLUMN_ENTRY_LENGTH( nOrdinal, data, length )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number, starting with one. Bookmark corresponds to column zero.

data

[in] The corresponding data member in the user record.

length

[in] The variable to be bound to the column length.

Remarks

Represents a binding on the rowset to the specific column in the database. This macro supports the length variable. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX, COLUMN_ENTRY_PS, COLUMN_ENTRY_PS_LENGTH, COLUMN_ENTRY_LENGTH_STATUS, COLUMN_ENTRY_PS_LENGTH_STATUS, COLUMN_ENTRY_STATUS, COLUMN_ENTRY_PS_STATUS, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_LENGTH_STATUS

COLUMN_ENTRY_LENGTH_STATUS( nOrdinal, data, length, status )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number.

data

[in] The corresponding data member in the user record.

length

[in] The variable to be bound to the column length.

status

[in] The variable to be bound to the column status.

Remarks

Represents a binding on the rowset to the specific column in the database. Use this macro when you want to support length and status variables. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX, COLUMN_ENTRY_LENGTH, COLUMN_ENTRY_PS, COLUMN_ENTRY_PS_LENGTH, COLUMN_ENTRY_PS_LENGTH_STATUS, COLUMN_ENTRY_STATUS, COLUMN_ENTRY_PS_STATUS, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_PS

COLUMN_ENTRY_PS( nOrdinal, nPrecision, nScale, data )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number.

nPrecision

[in] The precision of the column you wish to bind.

nScale

[in] The scale of the column you wish to bind.

data

[in] The corresponding data member in the user record.

Remarks

Represents a binding on the rowset to the specific column in the rowset. Allows you to specify the precision and scale of the column you wish to bind. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX, COLUMN_ENTRY_LENGTH, COLUMN_ENTRY_PS_LENGTH, COLUMN_ENTRY_LENGTH_STATUS, COLUMN_ENTRY_PS_LENGTH_STATUS, COLUMN_ENTRY_STATUS, COLUMN_ENTRY_PS_STATUS, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_PS_LENGTH

COLUMN_ENTRY_PS_LENGTH( nOrdinal, nPrecision, nScale, data, length )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number, starting with one. Bookmark corresponds to column zero.

nPrecision

[in] The precision of the column you wish to bind.

nScale

[in] The scale of the column you wish to bind.

data

[in] The corresponding data member in the user record.

length

[in] The variable to be bound to the column length.

Remarks

Represents a binding on the rowset to the specific column in the database. Allows you to specify the precision and scale of the column you wish to bind. This macro supports the length variable. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX, COLUMN_ENTRY_LENGTH, COLUMN_ENTRY_PS, COLUMN_ENTRY_LENGTH_STATUS, COLUMN_ENTRY_PS_LENGTH_STATUS, COLUMN_ENTRY_STATUS, COLUMN_ENTRY_PS_STATUS, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_PS_LENGTH_STATUS

COLUMN_ENTRY_PS_LENGTH_STATUS( nOrdinal, nPrecision, nScale, data, length, status )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number.

nPrecision

[in] The precision of the column you wish to bind.

nScale

[in] The scale of the column you wish to bind.

data

[in] The corresponding data member in the user record.

length

[in] The variable to be bound to the column length.

status

[in] The variable to be bound to the column status.

Remarks

Represents a binding on the rowset to the specific column in the database. Allows you to specify the precision and scale of the column you wish to bind. Use this macro when you want to support length and status variables. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX, COLUMN_ENTRY_LENGTH, COLUMN_ENTRY_PS, COLUMN_ENTRY_PS_LENGTH, COLUMN_ENTRY_LENGTH_STATUS, COLUMN_ENTRY_STATUS, COLUMN_ENTRY_PS_STATUS, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_PS_STATUS

COLUMN_ENTRY_PS_STATUS( nOrdinal, nPrecision, nScale, data, status )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number.

nPrecision

[in] The precision of the column you wish to bind.

nScale

[in] The scale of the column you wish to bind.

data

[in] The corresponding data member in the user record.

status

[in] The variable to be bound to the column status.

Remarks

Represents a binding on the rowset to the specific column in the database. Allows you to specify the precision and scale of the column you wish to bind. This macro supports the status variable. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX, COLUMN_ENTRY_LENGTH, COLUMN_ENTRY_PS, COLUMN_ENTRY_PS_LENGTH, COLUMN_ENTRY_LENGTH_STATUS, COLUMN_ENTRY_PS_LENGTH_STATUS, COLUMN_ENTRY_STATUS, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_STATUS

COLUMN_ENTRY_STATUS( nOrdinal, data, status )

Parameters

See DBBINDING in the OLE DB Programmer's Reference.

nOrdinal

[in] The column number.

wType

[in] The data type.

nLength

[in] The data size in bytes.

data

[in] The corresponding data member in the user record.

status

[in] The variable to be bound to the column status.

Remarks

Represents a binding on the rowset to the specific column in the database. This macro supports the status variable. It is used in the following places:

  • Between the BEGIN_COLUMN_MAP and END_COLUMN_MAP macros.

  • Between the BEGIN_ACCESSOR and END_ACCESSOR macros.

  • Between the BEGIN_PARAM_MAP and END_PARAM_MAP macros.

Macros for OLE DB Consumer Templates

See Also

BEGIN_ACCESSOR, BEGIN_ACCESSOR_MAP, BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX, COLUMN_ENTRY_LENGTH, COLUMN_ENTRY_PS, COLUMN_ENTRY_PS_LENGTH, COLUMN_ENTRY_LENGTH_STATUS, COLUMN_ENTRY_PS_LENGTH_STATUS, COLUMN_ENTRY_PS_STATUS, END_ACCESSOR, END_ACCESSOR_MAP, END_COLUMN_MAP


COLUMN_ENTRY_TYPE

COLUMN_ENTRY_TYPE ( nOrdinal, wType, data )

Parameters

nOrdinal

[in] The column number.

wType

[in] Data type of column entry.

data

[in] The corresponding data member in the user record.

Remarks

A specialized variant of the COLUMN_ENTRY macro that provides a means of specifying data type.

Macros for OLE DB Consumer Templates

See Also

BEGIN_COLUMN_MAP, END_COLUMN_MAP


COLUMN_ENTRY_TYPE_SIZE

COLUMN_ENTRY_TYPE_SIZE( nOrdinal, wType, nLength, data )

Parameters

nOrdinal

[in] The column number.

wType

[in] Data type of column entry..

nLength

[in] Size of column entry in bytes.

data

[in] The corresponding data member in the user record.

Remarks

A specialized variant of the COLUMN_ENTRY macro that provides a means of specifying data size and type.

Macros for OLE DB Consumer Templates

See Also

BEGIN_COLUMN_MAP, END_COLUMN_MAP


DEFINE_COMMAND

DEFINE_COMMAND( x, szCommand )

Parameters

x

[in] The name of the user-record class.

szCommand

[in] The command that will be used to create the rowset when using CCommand.

Remarks

Use this macro to specify the command that will be used to create the rowset when using the CCommand class. This default command will be used if you do not specify command text in the Open method.

Macros for OLE DB Consumer Templates

Example

See BOOKMARK_ENTRY.


END_ACCESSOR

END_ACCESSOR( )

Remarks

Marks the end of an accessor entry. In the case of multiple accessors on a rowset, you need to specify BEGIN_ACCESSOR_MAP, and use the BEGIN_ACCESSOR macro for each individual accessor. The BEGIN_ACCESSOR macro is completed with the END_ACCESSOR macro. The BEGIN_ACCESSOR_MAP macro is completed with the END_ACCESSOR_MAP macro.

Macros for OLE DB Consumer Templates

Example

See BEGIN_ACCESSOR_MAP.

See Also

BEGIN_ACCESSOR_MAP, BEGIN_ACCESSOR, END_ACCESSOR_MAP


END_ACCESSOR_MAP

END_ACCESSOR_MAP( )

Remarks

Marks the end of the accessor map entries. In the case of multiple accessors on a rowset, you need to specify BEGIN_ACCESSOR_MAP, and use the BEGIN_ACCESSOR macro for each individual accessor. The BEGIN_ACCESSOR macro is completed with the END_ACCESSOR macro. The BEGIN_ACCESSOR_MAP macro is completed with the END_ACCESSOR_MAP macro.

Macros for OLE DB Consumer Templates

Example

See BEGIN_ACCESSOR_MAP.

See Also

BEGIN_ACCESSOR_MAP, BEGIN_ACCESSOR, END_ACCESSOR_MAP


END_COLUMN_MAP

END_COLUMN_MAP( )

Remarks

Marks the end of the column map entries. It is used in the case of a single accessor on a rowset. The BEGIN_COLUMN_MAP macro is completed with the END_COLUMN_MAP macro.

Macros for OLE DB Consumer Templates

Example

See BEGIN_COLUMN_MAP.

See Also

BEGIN_COLUMN_MAP, COLUMN_ENTRY, COLUMN_ENTRY_EX


END_PARAM_MAP

END_PARAM_MAP( )

Remarks

Marks the end of the parameter map entries.

Macros for OLE DB Consumer Templates

Example

See BEGIN_PARAM_MAP.

See Also

BEGIN_PARAM_MAP, SET_PARAM_TYPE


SET_PARAM_TYPE

SET_PARAM_TYPE( type )

Parameters

type

[in] The type to set for the parameter.

Remarks

Specifies COLUMN_ENTRY macros that follow the SET_PARAM_TYPE macro input, output, or input/output. Providers support only parameter I/O types that are supported by the underlying data source. The type is a combination of one or more DBPARAMIOENUM values:

  • DBPARAMIO_NOTPARAM The accessor is not used for parameters. In most cases eParamIO is set to this value in row accessors to remind the programmer that it is ignored.

  • DBPARAMIO_INPUT An input parameter.

  • DBPARAMIO_OUTPUT An output parameter.

  • DBPARAMIO_NOTPARAM The accessor has no parameters. Setting eParamIO to this value in row accessors reminds the user that parameters are ignored.

Macros for OLE DB Consumer Templates

Example

class CGetProperty
{
public:
   LONG    m_nReturn
   LONG   m_nAge;
   TCHAR m_name[31];
   TCHAR m_property[65];

BEGIN_PARAM_MAP(CGetProperty)
   SET_PARAM_TYPE(DBPARAMIO_OUTPUT)
   COLUMN_ENTRY(1, m_nReturn)
   SET_PARAM_TYPE(DBPARAMIO_INPUT)
   COLUMN_ENTRY(2, m_nAge)
END_PARAM_MAP()

BEGIN_COLUMN_MAP(CGetProperty)
   COLUMN_ENTRY(1, m_name)
   COLUMN_ENTRY(2, m_property)
END_COLUMN_MAP()

};


Using the OLE DB Provider Templates

The OLE DB Provider Templates support the OLE DB version 1.1 specification. Using the OLE DB Provider Templates, you can implement a level-0 compliant provider. The provider sample, for example, uses the templates to implement a non-SQL (DOS) command server that executes the DOS DIR command to query the file system. The provider sample returns the directory information in a rowset, which is the standard OLE DB mechanism for returning tabular data.

The simplest type of provider supported by the OLE DB Templates is a read-only provider with no commands. Providers with commands are also supported, but read/write providers are not supported automatically by the current version of the OLE DB Templates. (You can implement a read/write provider by writing additional code.) Dynamic rowsets and transactions are not supported by the current version either, but you can add them if you desire.

To use the OLE DB Templates, you should be familiar with C++ templates, COM, and the OLE DB interfaces. If you are not familiar with OLE DB, refer to the OLE DB Programmer's Reference before proceeding.

What would you like to know more about?

The OLE DB Provider Template Architecture

Creating an OLE DB Template Provider

Overview of OLE DB Templates

See Also

FAQ: Using the OLE DB Provider Templates


The OLE DB Provider Template Architecture

The OLE DB provider architecture includes a data source object and one or more sessions. The data source object is the initial object every provider must instantiate. When a consumer application needs data, it cocreates the data source object to start the provider. The data source object creates a session object (using the IDBCreateSession interface) through which the consumer connects to the data source object. ODBC programmers can think of the data source object as being equivalent to the HENV and the session object as equivalent to the HDBC.

Together with the source files created by the OLE DB Provider Template Wizard, the OLE DB Templates implement a data source object. A session is an object that corresponds to the OLE DB TSession.

There are mandatory and optional interfaces defined by OLE DB for several types of objects:

  • Data Source

  • Session

  • Rowset

  • Command

What would you like to know more about?

Property Maps

The User Record

Back to Using the OLE DB Provider Templates


Data Source Object Interfaces

The following table shows the mandatory and optional interfaces defined by OLE DB for a data source object.

Data Source Object

Interface
Required? 		Implemented by OLE DB Template Classes?
IDBInitialize | Mandatory | Yes
IDBCreateSession | Mandatory | Yes
IDBProperties | Mandatory | Yes
IDBDataSourceAdmin | Optional | No
IDBInfo | Optional | No
IPersistFile | Optional | No
ISupportErrorInfo | Optional | No

The data source object implements the IDBProperties, IDBInitialize, and IDBCreateSession interfaces through inheritance. You can choose to support additional functionality by inheriting or not inheriting from one of these implementation classes. If you want to support the IDBDataSourceAdmin interface, you must inherit from the IDBDataSourceAdminImpl class.

Back to the OLE DB Provider Template Architecture


Session Object Interfaces

The following table shows the mandatory and optional interfaces defined by OLE DB for a session object.

Session

Interface
Required? 		Implemented by OLE DB Template Classes?
IGetDataSource | Mandatory | Yes
IOpenRowset | Mandatory | Yes
ISessionProperties | Mandatory | Yes
IDBCreateCommand | Optional | Yes
IDBSchemaRowset | Optional | Yes
IIndexDefinition | Optional | No
ISupportErrorInfo | Optional | No
ITableDefinition | Optional | No
ITransactionJoin | Optional | No
ITransactionLocal | Optional | No
ITransactionObject | Optional | No

The session object creates a rowset object. If the provider supports commands, the session also creates a command object (CCommand, implementing the OLE DB TCommand). The command object implements the ICommand interface and uses the ICommand::Execute method to execute commands on the rowset, as shown in the following figure.

Back to the OLE DB Provider Template Architecture


Rowset Object Interfaces

The following table shows the mandatory and optional interfaces defined by OLE DB for a rowset object.

Rowset

Interface
Required? 		Implemented by OLE DB Template Classes?
IAccessor | Mandatory | Yes
IColumnsInfo | Mandatory | Yes
IConvertType | Mandatory | Yes
IRowset | Mandatory | Yes
IRowsetInfo | Mandatory | Yes
IColumnsRowset | Optional | No
IConnectionPointContainer | Optional | Yes, through ATL
IRowsetChange | Optional | No
IRowsetIdentity | Required for level-0 providers | Yes
IRowsetLocate | Optional | No
IRowsetScroll | Optional | No
IRowsetUpdate | Optional | No
ISupportErrorInfo | Optional | No

The wizard-generated rowset object implements IAccessor, IRowset, and IRowsetInfo through inheritance. The IAccessorImpl binds both output columns. The IRowset interface handles fetches rows and data. The IRowsetInfo interface handles the rowset properties.

Back to the OLE DB Provider Template Architecture


Command Object Interfaces

The following table shows the mandatory and optional interfaces defined by OLE DB for a command object.

Command

Interface
Required? 		Implemented by OLE DB Template Classes?
IAccessor | Mandatory | Yes
IColumnsInfo | Mandatory | Yes
ICommand | Mandatory | Yes
ICommandProperties | Mandatory | Yes
ICommandText | Mandatory | Yes
IConvertType | Mandatory | Yes
IColumnsRowset | Optional | No
ICommandPrepare | Optional | No
ICommandWithParameters | Optional | No
ISupportErrorInfo | Optional | No

The command object uses the IAccessor to specify parameter bindings. The consumer calls IAccessor::CreateAccessor, passing it an array of DBBINDING structures. DBBINDING contains information on the column bindings (type, length, and so on). The provider receives the structures and determines how the data should be transferred and whether conversions are necessary.

The ICommandText interface provides a way to specify a text command. The ICommandProperties interface handles all of the command properties.

Back to the OLE DB Provider Template Architecture


Property Maps

In addition to the session, rowset, and optional command object, each provider supports one or more properties. These properties are defined in property maps contained in the header files created by the OLE DB Provider Template Wizard. Each header file contains a map for the properties in the OLE DB property group defined for the object or objects defined in that file. The header file that contains the data source object also contains the property map for the DataSource properties. Session.h contains the property map for the Session properties. The rowset and command objects reside in a single header file, called projectnameRS.h. These properties are members of the Rowset properties group.

Back to The OLE DB Provider Architecture


The User Record

The User Record provides the code and data structure that represents the column data for a rowset. A User Record can be created at compile time or at run time. When you create a Provider using the ATL Object Wizard, the wizard creates a default user record that looks like this:

class CWindowsFile:
   public WIN32_FIND_DATA
{
public:

BEGIN_PROVIDER_COLUMN_MAP(CWindowsFile)
   PROVIDER_COLUMN_ENTRY("FileAttributes", 1, dwFileAttributes)
   PROVIDER_COLUMN_ENTRY("FileSizeHigh", 2, nFileSizeHigh)
   PROVIDER_COLUMN_ENTRY("FileSizeLow", 3, nFileSizeLow)
   PROVIDER_COLUMN_ENTRY("FileName", 4, cFileName)
   PROVIDER_COLUMN_ENTRY("AltFileName", 5, cAlternateFileName)
END_PROVIDER_COLUMN_MAP()

};

The OLE DB Provider Templates handle all OLE DB specifics regarding interactions with the client. To acquire the column data needed for a response, the provider calls the GetColumnInfo function, which you must place in the User Record:

template <class T>
static ATLCOLUMNINFO* GetColumnInfo(T* pThis, ULONG* pcCols)

The PROVIDER_COLUMN_MAP macros aid in creating a GetColumnInfo function:

  • BEGIN_PROVIDER_COLUMN_MAP defines the function prototype and a static array of ATLCOLUMNINFO structures.

  • PROVIDER_COLUMN_ENTRY macro defines and initializes a single ATLCOUMNINFO.

  • END_PROVIDER_COLUMN_MAP closes the array and the function. It also places the array element count into the pcCols parameter.

When a User Record is created at run time, GetColumnInfo uses the pThis parameter to receive a pointer to a rowset or command instance. Commands and rowsets must support the IColumnsInfo interface, so column information can be obtained from this pointer.

You can explicitly override GetColumnInfo in the User Record, as shown here:

template <class T>
static ATLCOLUMNINFO* GetColumnInfo(T* pThis, ULONG* pcCols)

This is equivalent to:

static ATLCOLUMNINFO* GetColumnInfo(CommandClass* pThis, ULONG* pcCols)
static ATLCOLUMNINFO* GetColumnInfo(RowsetClass* pThis, ULONG* pcCols)

CommandClass and RowsetClass are the command and rowset that use the User Record.

For an additional example of how to override GetColumnInfo in a User Record, see Creating a Simple Read-Only Provider.

Back to the OLE DB Provider Template Architecture


Schema Support

The OLE DB Provider session object supports the optional OLE DB IDBSchemaRowset interface. The ATL Object Wizard creates three schema classes in the session header file:

  • C ShortName SessionTRSchemaRowset

  • C ShortName SessionColSchemaRowset

  • C ShortName SessionPTSchemaRowset

These classes respond to consumer requests for schema information. C ShortName SessionTRSchemaRowset handles requests for table information. C ShortName SessionColSchemaRowset handles requests for column information. The wizard supplies sample implementations for these classes, which return schema information for a DOS provider. C ShortName SessionPTSchemaRowset handles requests for schema information about the provider type. The default implementation provided by the wizard simply returns S_OK.

You can customize these classes to handle schema information appropriate to your provider:

  • In C ShortName SessionTRSchemaRowset, you must fill out the catalog, table, and description fields (trData.m_szType, trData.m_szTable, trData.m_szDesc). The wizard-generated example uses only one row (table). Other providers may return more than one table.

  • In C ShortName SessionColSchemaRowset, you pass the name of the table as a DBID.


Creating an OLE DB Template Provider

To create an OLE DB provider using the OLE DB Templates

  1. Use the ATL COM AppWizard and ATL Object Wizard to create the basic project files.

  2. Modify the code in the Execute method in CMyProviderRS.h. (For an example, see Reading Strings Into an OLE DB Provider.)

  3. Edit the property maps in MyProviderDS.h, MyProviderSess.h, and MyProviderRS.h. The wizard creates property maps that contain all properties that a provider might implement. Go through the property maps and remove or comment out properties your provider does not need to support.

  4. Update the PROVIDER_COLUMN_MAP, which can be found in MyProviderRS.h. (See Storing Strings In the OLE DB Provider for an example.)

  5. When you are ready to test your provider, you can test it by trying to find the provider in a provider enumeration. For examples of test code that finds a provider in an enumeration, look at the CATDB and DBVIEWER samples or the example in Implementing A Simple Consumer.

  6. Add any additional interfaces you desire. (See Enhancing the Simple Read-Only Provider for an example.)

Note By default, the wizards generate code that is OLE DB level-0 complaint. To ensure that your application remains level-0 compliant, do not remove any of the wizard-generated interfaces from the code.

To create an OLE DB provider using the OLE DB Templates, begin with the ATL COM AppWizard.

To create an ATL project for an OLE DB provider

  1. From the File menu, choose New. The New dialog box appears.

  2. On the Projects tab, choose ATL COM AppWizard.

  3. Name the project on the Projects tab, then click OK. The ATL COM AppWizard appears.

  4. In the ATL COM AppWizard, choose Dynamic Link Library (DLL) for Server Type.

  5. Click Finish and OK.
  • Next, use the ATL Object Wizard.

To use the ATL Object Wizard for an OLE DB provider

  1. From the Insert menu, choose New ATL Object. The ATL Object Wizard appears.

  2. In the left pane, choose Data Access. The Provider icon appears in the right pane.

  3. Select the Provider icon and click Next. The OLE DB Provider tab appears.

  4. On the OLE DB Provider tab, enter a short name for your provider in the Short Name box (MyProvider, for example). The other name boxes populate according to the name you enter.

  5. Edit the other name boxes, if desired. In addition to the object and file names, you can edit the following:
    • CoClass: The name that COM uses to create the provider.

    • ProgID: The programmatic identifier, a text string that can be used instead of a GUID.

    • Version: Used with the ProgID and CoClass to generate a version-dependent programmatic ID.
  6. Click OK.

The ATL Object Wizard generates the following files. (The exact file names depend on the choices you made on the OLE DB Provider tab.)

File name | Description
MyProviderRS.cpp | Contains the command helper Execute method and the provider column map.
MyProviderDS.h | Implements the data source object. This header file contains the property map for data source properties.
MyProviderRS.h | Implements the command and rowset objects. This header file contains the property map for rowset and command properties.
MyProviderSess.h | Implements the session object. This header file contains the property map for session properties.
MyProvider.rgs | Contains the registered objects generated by the OLE DB Provider wizard.

Back to Using the OLE DB Provider Templates


Implementing an OLE DB Template Provider

Once you have created an OLE DB provider using the ATL COM AppWizard and ATL Object Wizard, you can add commands, transactions, and other optional objects you want to support.

The extended example in this article shows how to edit the wizard-created files to create a simple provider. The example is presented in two parts:

  • The first part shows how to create a simple read-only provider that reads a pair of strings.

  • The second part shows how to enhance the simple read-only provider by adding the IRowsetLocate interface.

You can find the finished code for the enhanced simple provider in the sample MyProv: A Simple Read-Only Provider.


Implementing a Simple Read-Only Provider

The extended example in this article shows how to edit the wizard-created files to create a provider that reads a set of two strings from a file. To create this provider from the wizard files, you must add code to complete the following tasks:

  • Read the strings into the provider

  • Store the strings in the provider

Back to Implementing an OLE DB Template Provider


Reading Strings into the OLE DB Provider

The RMyProviderRowset::Execute function opens a file and reads strings. The consumer passes the filename to the provider by calling ICommandText::SetCommandText. The provider receives the filename and stores it in the member variable m_szCommandText. Execute reads the filename from m_szCommandText. If the filename is invalid or the file is unavailable, Execute returns an error. Otherwise, it opens the file and calls fgets to retrieve the strings. For each set of strings it reads, Execute creates an instance of the User Record (CAgentMan) and places it into an array.

If the file can’t be opened, Execute must return DB_E_NOTABLE. If it returns E_FAIL instead, the provider will not work with many consumers and will not pass the OLE DB conformance tests.

The edited Execute function looks like this:

/////////////////////////////////////////////////////////////////////////
// MyProviderRS.h
class RMyProviderRowset : public CRowsetImpl< RMyProviderRowset, CAgentMan, CRMyProviderCommand>
{
public:

HRESULT Execute(DBPARAMS * pParams, LONG* pcRowsAffected)
{
 USES_CONVERSION;
 FILE* pFile;
 TCHAR szString[256];
 TCHAR szFile[MAX_PATH];
 size_t nLength;
 ObjectLock lock(this);

 // From a filename, passed in as a command text, scan the file
 // placing data in the data array.
 if (!m_szCommandText)
 {
    ATLTRACE("No filename specified");
    return E_FAIL;
 }

 // Open the file
 _tcscpy(szFile, m_szCommandText);
 if (szFile[0] == _T('\0') || ((pFile = fopen(&szFile[0], "r")) == NULL))
 {
    ATLTRACE("Could not open file");
    return DB_E_NOTABLE;
 }

 // scan and parse the file.  The file should contain two strings per record
 LONG cFiles = 0;
 while (fgets(szString, 256, pFile) != NULL)
 {
    nLength = strlen(szString);
    szString[nLength-1] = '\0';   // Strip off trailing CR/LF
    CAgentMan am;
    _tcscpy(am.szCommand, szString);
    _tcscpy(am.szCommand2, szString);

    if (fgets(szString, 256, pFile) != NULL)
    {
       nLength = strlen(szString);
       szString[nLength-1] = '\0';   // Strip off trailing CR/LF
       _tcscpy(am.szText, szString);
       _tcscpy(am.szText2, szString);
    }

    am.dwBookmark = ++cFiles;
    if (!m_rgRowData.Add(am))
    {
       ATLTRACE("Couldn't add data to array");
       fclose(pFile);
       return E_FAIL;
    }
 }

 if (pcRowsAffected != NULL)
    *pcRowsAffected = cFiles;
 return S_OK;
}


Storing Strings in the OLE DB Provider

In MyProviderRS.h, the ATL Object Wizard creates a default User Record called CWindowsFile. To handle the two strings, either edit CWindowsFile or add your own User Record, as shown here:

////////////////////////////////////////////////////////////////////////
class CAgentMan:
   public WIN32_FIND_DATA
   DWORD dwBookmark;              // Add this
   TCHAR szCommand[256];          // Add this
   TCHAR szText[256];             // Add this
   TCHAR szCommand2[256];         // Add this
   TCHAR szText2[256];            // Add this
{
public:
BEGIN_PROVIDER_COLUMN_MAP(CAgentMan)
   PROVIDER_COLUMN_ENTRY("FileAttributes", 1, dwFileAttributes)
   PROVIDER_COLUMN_ENTRY("FileSizeHigh", 2, nFileSizeHigh)
   PROVIDER_COLUMN_ENTRY("FileSizeLow", 3, nFileSizeLow)
   PROVIDER_COLUMN_ENTRY("FileName", 4, cFileName)
   PROVIDER_COLUMN_ENTRY("AltFileName", 5, cAlternateFileName)
END_PROVIDER_COLUMN_MAP()
   bool operator==(const CAgentMan& am) // This is optional
   {
      return (lstrcmpi(cFileName, wf.cFileName) == 0);
   }
};

The data members szCommand and szText represent the two strings, with szCommand2 and szText2 providing additional columns if needed. The data member dwBookmark is not needed for this simply read-only provider, but will be used later to add an IRowsetLocate interface. The == operator compares instances. (Implementing this operator is optional.)

To support the two strings, the PROVIDER_COLUMN_MAP needs modification as well. Replace the PROVIDER_COLUMN_MAP shown above with the one shown here:

BEGIN_PROVIDER_COLUMN_MAP()
    PROVIDER_COLUMN_ENTRY_STR(OLESTR("Command"), 1, 256, GUID_NULL, CAgentMan, szCommand)
    PROVIDER_COLUMN_ENTRY_STR(OLESTR("Text"),2, 256, GUID_NULL, CAgentMan, szText)
    PROVIDER_COLUMN_ENTRY_STR(OLESTR("Command2"), 3, 256, GUID_NULL, CAgentMan, szCommand2)
    PROVIDER_COLUMN_ENTRY_STR(OLESTR("Text2"),4, 256, GUID_NULL, CAgentMan, szText2)
END_PROVIDER_COLUMN_MAP()

When this is done, your provider should be ready to compile and run. To test the provider, you need a consumer with matching functionality. Implementing a Simple Consumer shows how to create such a test consumer. Run the test consumer with the provider. Verify that the test consumer retrieves the proper strings from the provider when you click the Run button on the test consumer dialog box.

Once you have successfully tested your provider, you may want to enhance its functionality by implementing additional interfaces. An example is shown in the next section, Enhancing the Simple Read-Only Provider.


Enhancing the Simple Read-Only Provider

This section shows how to add the IRowsetLocate interface to enhance the simple read-only provider created in the previous section.

Once you have a working provider, you might want to enhance it to make the provider update, to handle transactions, or to enhance the performance of the row-fetching algorithm. Most provider enhancements involve adding an interface to an existing COM object.

The example in the following topics enhances the row-fetching mechanism by adding the IRowsetLocate interface to CAgentRowset. The topics show you how to:

  • Make RMyProviderRowset inherit from IRowsetLocate

  • Create an implementation for the IRowsetLocate interface

  • Complete the implementation of IRowsetLocate by adding bookmark support

  • Dynamically determine the columns returned to the consumer

(You can find the final code for MyProvider in the sample MyProv: A Simple Read-Only Provider.)

Back to Implementing an OLE DB Template Provider


Modifying the Inheritance of RMyProviderRowset

To add the IRowsetLocate interface to the simple read-only provider example, modify the inheritance of RMyProviderRowset. Initially, RMyProviderRowset inherits from CRowsetImpl. You need to modify it to inherit from CRowsetBaseImpl. To do this, create a new class, CMyRowsetImpl, in MyProviderRS.h:

////////////////////////////////////////////////////////////////////////
// MyProviderRS.h

template <class T, class Storage, class CreatorClass, class ArrayType = CSimpleArray<Storage> >
class CMyRowsetImpl:
   public CRowsetBaseImpl<T, Storage, CreatorClass, ArrayType>,
   public IRowsetLocateImpl<T>
{
   typedef CRowsetBaseImpl< T, Storage, CreatorClass, ArrayType> _RowsetBaseClass;

BEGIN_COM_MAP(CMyRowsetImpl)
   COM_INTERFACE_ENTRY_IID(IID_IRowsetLocate, IRowset)
   COM_INTERFACE_ENTRY(IRowset)
   COM_INTERFACE_ENTRY_CHAIN(_RowsetBaseClass)
END_COM_MAP()
};

Now, create a COM interface map that tells CMyRowsetImpl to call QueryInterface for both the IRowset and IRowsetLocate interfaces.

////////////////////////////////////////////////////////////////////////
// MyProviderRS.h

BEGIN_COM_MAP(CMyRowsetImpl)
   COM_INTERFACE_ENTRY_IID(IID_IRowsetLocate, IRowset)
   COM_INTERFACE_ENTRY(IRowset)
END_COM_MAP()

To get all of the implementation for the other rowset classes, link the CMyRowsetImpl class back to the CRowsetBaseImpl class defined by the OLE DB Templates. To do this, use a COM_INTERFACE_ENTRY_CHAIN macro, as shown in the following code. The COM_INTERFACE_ENTRY_CHAIN macro tells OLE DB Templates to scan the COM map in CRowsetBaseImpl in response to a QueryInterface call.

////////////////////////////////////////////////////////////////////////
// MyProviderRS.h

BEGIN_COM_MAP(CMyRowsetImpl)
   COM_INTERFACE_ENTRY_IID(IID_IRowsetLocate, IRowset)
   COM_INTERFACE_ENTRY(IRowset)
   COM_INTERFACE_ENTRY_CHAIN(_RowsetBaseClass)
END_COM_MAP()

Finally, link RAgentRowset to CMyRowsetBaseImpl by modifying RAgentRowset to inherit from CMyRowsetImpl, as shown here:

class RAgentRowset : public CMyRowsetImpl<RAgentRowset, CAgentMan, CMyProviderCommand>

RAgentRowset can now use the IRowsetLocate interface while taking advantage of the rest of the implementation for the rowset class.

When this is done, you are ready to implement IRowsetLocateImpl.


Implementing IRowsetLocate

After modifying the inheritance of RMyProviderRowset, you need to implement the IRowsetLocate interface. You can find the interface definition in the Interface Summary of the OLE DB Programmer's Reference and in the OLEDB.H file in the OLE DB SDK include directory.

To implement this interface:

  1. Create a new file named RowLoc.h and add the file to the project.

  2. In RowLoc.h, create a class definition for IRowsetLocateImpl, derived from IRowset, and implement the class.

  3. Copy the methods for the interface from the OLE DB header file OLEDB.H to RowLoc.h. Change the HRESULT return codes to STDMETHOD and put parentheses around the method names, as shown in the following code.

  4. Complete the implementation (covered in the next topic).
////////////////////////////////////////////////////////////////////////
// RowLoc.h
// class IRowsetLocateImpl

template <class T>
class ATL_NO_VTABLE IRowsetLocateImpl : public IRowsetImpl<T>
{
public:
   STDMETHOD (Compare)(HCHAPTER hReserved, ULONG cbBookmark1,
      const BYTE * pBookmark1, ULONG cbBookmark2, const BYTE *
          pBookmark2, DBCOMPARE * pComparison)
   {
      return S_OK;
   }

   STDMETHOD (GetRowsAt)(HWATCHREGION hReserved1, HCHAPTER hReserved2,
      ULONG cbBookmark, const BYTE * pBookmark, LONG lRowsOffset,
      LONG cRows, ULONG * pcRowsObtained, HROW ** prghRows)
   {
      return S_OK;
   }

   STDMETHOD (GetRowsByBookmark)(HCHAPTER hReserved, ULONG cRows,
      const ULONG rgcbBookmarks[], const BYTE * rgpBookmarks[],
      HROW rghRows[], DBROWSTATUS rgRowStatus[])
   {
      return S_OK;
   }

   STDMETHOD (Hash)(HCHAPTER hReserved, ULONG cBookmarks,
      const ULONG rgcbBookmarks[], const BYTE * rgpBookmarks[],
      DWORD rgHashedValues[], DBROWSTATUS rgBookmarkStatus[])
   {
      ATLTRACENOTIMPL("IRowsetLocateImpl::GetRowsByBookmark");
   }
};

In the next topic, you will see how to complete the implementation by adding bookmarks.


Completing the Implementation of IRowsetLocateImpl

To complete your implementation of the IRowsetLocate interface, you must implement bookmarks. Bookmarks are indices into a rowset that allow high-speed access to data. The provider determines what bookmarks can uniquely identify a row. This example uses the index of the m_rgAgentInfo array.

The provider can receive a bookmark in any format. To make sure that the bookmark is valid:

  1. Call ValidateBookmark to check that you have a valid bookmark pointer.

  2. Check the size of the bookmark to make sure it is either the size of a DWORD or one byte. (The User Record, CAgentMan, specifies the dwBookmark entry to be a DWORD. The single-byte length is used for the special bookmarks DBMRK_FIRST and DBMRK_LAST.)

  3. Check that the index points to a valid location in the array (between DBMRK_FIRST and DBMRK_LAST).

After validating both bookmarks (one for each string), call the Compare method, which takes two bookmarks and determines if one is less than, greater than, or equal to the other.

To fetch rows, implement the GetRowsAt and GetRowsByBookmark functions.

GetRowsAt works the same as the IRowset::GetNextRows method except that it uses a bookmark to fetch the data. It validates the bookmark and then calls IRowsetImpl::GetNextRows to get the rows.

GetRowsByBookmark fetches one row at a number of locations. Use it to fetch specific rows. GetRowsByBookmark validates each of the bookmarks, then fetches the row by calling IRowsetImpl::CreateRow, which creates a new row, if necessary. The rows are returned in the array pointed to by rghRows.

(Because this example uses simple fixed-length bookmarks, it does not implement the IRowsetLocate::Hash method. If your provider uses variable-length bookmarks or computationally expensive bookmarks, you might want to implement the IRowsetLocate::Hash method as well.)

The complete implementation of IRowsetLocateImpl looks like this:

/////////////////////////////////////////////////////////////////////////// RowLoc.h
// class IRowsetLocateImpl

template <class T>
class ATL_NO_VTABLE IRowsetLocateImpl : public IRowsetImpl<T>
{
public:
   STDMETHOD (Compare)(HCHAPTER hReserved, ULONG cbBookmark1,
      const BYTE * pBookmark1, ULONG cbBookmark2, const BYTE * pBookmark2,
      DBCOMPARE * pComparison)
   {
      ATLTRACE("IRowsetLocateImpl::Compare");

      HRESULT hr = ValidateBookmark(cbBookmark1, pBookmark1);
      if (hr != S_OK)
         return hr;

      hr = ValidateBookmark(cbBookmark2, pBookmark2);
      if (hr != S_OK)
         return hr;

      // Return the value based on the bookmark values
      if (*pBookmark1 == *pBookmark2)
         *pComparison = DBCOMPARE_EQ;

      if (*pBookmark1 < *pBookmark2)
         *pComparison = DBCOMPARE_LT;

      if (*pBookmark1 > *pBookmark2)
         *pComparison = DBCOMPARE_GT;

      return S_OK;
   }

   STDMETHOD (GetRowsAt)(HWATCHREGION hReserved1, HCHAPTER hReserved2,
      ULONG cbBookmark, const BYTE * pBookmark, LONG lRowsOffset,
      LONG cRows, ULONG * pcRowsObtained, HROW ** prghRows)
   {
      ATLTRACE("IRowsetLocateImpl::GetRowsAt");
      T* pT = (T*)this;

      // Check bookmark
      HRESULT hr = ValidateBookmark(cbBookmark, pBookmark);
      if (hr != S_OK)
         return hr;

      // Check the other pointers
      if (pcRowsObtained == NULL || prghRows == NULL)
         return E_INVALIDARG;

      // Set the current row position to the bookmark.  Handle any
      // normal values
      pT->Lock();
      LONG iRowsetTemp = m_iRowset;  // Cache the current rowset
      m_iRowset = *pBookmark;
      if (*pBookmark == DBBMK_FIRST)
         m_iRowset = 1;

      if (*pBookmark == DBBMK_LAST)
         m_iRowset = pT->m_rgRowData.GetSize();

      // Call IRowsetImpl::GetNextRows to actually get the rows.
      hr = GetNextRows(hReserved2, lRowsOffset,
         cRows, pcRowsObtained, prghRows);
      m_iRowset = iRowsetTemp;
      pT->Unlock();
      return hr;
   }

   STDMETHOD (GetRowsByBookmark)(HCHAPTER hReserved, ULONG cRows,
      const ULONG rgcbBookmarks[], const BYTE * rgpBookmarks[],
      HROW rghRows[], DBROWSTATUS rgRowStatus[])
   {
      HRESULT hr = S_OK;
      ATLTRACE("IRowsetLocateImpl::GetRowsByBookmark");

      T* pT = (T*)this;
      if (rgcbBookmarks == NULL || rgpBookmarks == NULL || rghRows == NULL)
         return E_INVALIDARG;

      if (cRows == 0)
         return S_OK;   // No rows fetched in this case.

      bool bErrors = false;
      pT->Lock();
      for (ULONG l=0; l<cRows; l++)
      {
         // Validate each bookmark before fetching the row.  Note, it is
         // an error for the bookmark to be one of the standard values
         hr = ValidateBookmark(rgcbBookmarks[l], rgpBookmarks[l]);
         if (hr != S_OK)
         {
            bErrors = TRUE;
            if (rgRowStatus != NULL)
            {
               rgRowStatus[l] = DBROWSTATUS_E_INVALID;
               continue;
            }
         }

         // Fetch the validated row
         ULONG ulRowsObtained = 0;
         if (CreateRow((long)*rgpBookmarks[l], ulRowsObtained, &rghRows[l]) != S_OK)
         {
            bErrors = TRUE;
         }
         else
         {
            if (rgRowStatus != NULL)
               rgRowStatus[l] = DBROWSTATUS_S_OK;
         }
      }

      pT->Unlock();
      if (bErrors)
         return DB_S_ERRORSOCCURRED;
      else
         return hr;
   }

   STDMETHOD (Hash)(HCHAPTER hReserved, ULONG cBookmarks,
      const ULONG rgcbBookmarks[], const BYTE * rgpBookmarks[],
      DWORD rgHashedValues[], DBROWSTATUS rgBookmarkStatus[])
   {
      ATLTRACENOTIMPL("IRowsetLocateImpl::GetRowsByBookmark");
   }

   // Implementation
   protected:
   HRESULT ValidateBookmark(ULONG cbBookmark, const BYTE* pBookmark)
   {
      T* pT = (T*)this;
      if (cbBookmark == 0 || pBookmark == NULL)
         return E_INVALIDARG;

      // All of our bookmarks are DWORDs, if they are anything other than
      // sizeof(DWORD) then we have an invalid bookmark
      if ((cbBookmark != sizeof(DWORD)) && (cbBookmark != 1))
      {
         ATLTRACE("Bookmarks are invalid length, should be DWORDs");
         return DB_E_BADBOOKMARK;
      }

      // If the contents of our bookmarks are less than 0 or greater than
      // rowcount, then they are invalid
      UINT nRows = pT->m_rgRowData.GetSize();
      if ((*pBookmark <= 0 || *pBookmark > nRows)
         && *pBookmark != DBBMK_FIRST && *pBookmark != DBBMK_LAST)
      {
         ATLTRACE("Bookmark has invalid range");
         return DB_E_BADBOOKMARK;
      }

      return S_OK;
   }
};

In the next topic, you will see how to dynamically determine the columns returned to the consumer.


Dynamically Determining Columns Returned to the Consumer

The PROVIDER_COLUMN_ENTRY macros normally handle the IColumnsInfo::GetColumnsInfo call. Since a consumer may or may not choose to use bookmarks, however, the provider must be able to change the columns returned depending upon whether or not the consumer asks for a bookmark.

To handle the IColumnsInfo::GetColumnsInfo call, delete the PROVIDER_COLUMN_MAP (which defines a function _GetColumnInfo) from the CAgentMan user record in MyProviderRS.h and replace it with the definition for your own _GetColumnInfo function:

////////////////////////////////////////////////////////////////////////
// MyProviderRS.H
class CAgentMan
{
public:
   DWORD dwBookmark;
   TCHAR szCommand[256];
   TCHAR szText[256];
   TCHAR szCommand2[256];
   TCHAR szText2[256];

   static ATLCOLUMNINFO* _GetColumnInfo(void* pThis, ULONG* pcCols);
   bool operator==(const CAgentMan& am)
   {
      return (lstrcmpi(szCommand, am.szCommand) == 0);
   }

};

Next, implement the _GetColumnInfo function in MyProviderRS.cpp, as shown in the following code.

_GetColumnInfo checks first to see if the OLE DB property DBPROP_IRowsetLocate is set. To get the property, _GetColumnInfo uses a pointer (pRowset) to the rowset object. The pThis pointer represents the class that created the rowset (which is the class where the property map is stored). _GetColumnInfo typecasts the pThis pointer to a RMyProviderRowset pointer.

To check for the DBPROP_IRowsetLocate property, _GetColumnInfo uses the IRowsetInfo interface, which you can obtain by calling QueryInterface on the pRowset interface. (As an alternative, you can use an ATL CComQIPtr instead.)

////////////////////////////////////////////////////////////////////
// MyProviderRS.cpp
ATLCOLUMNINFO* CAgentMan::_GetColumnInfo(void* pThis, ULONG* pcCols)
{
   static ATLCOLUMNINFO _rgColumns[5];
   ULONG ulCols = 0;

   // Check the property flag for bookmarks, if it is set, set the zero ordinal
   // entry in the column map with the bookmark information.
   CAgentRowset* pRowset = (CAgentRowset*) pThis;
   CComQIPtr<IRowsetInfo, &IID_IRowsetInfo> spRowsetProps = pRowset;

   CDBPropIDSet set(DBPROPSET_ROWSET);
   set.AddPropertyID(DBPROP_BOOKMARKS);
   DBPROPSET* pPropSet = NULL;
   ULONG ulPropSet = 0;
   HRESULT hr;

   if (spRowsetProps)
      hr = spRowsetProps->GetProperties(1, &set, &ulPropSet, &pPropSet);

   if (pPropSet)
   {
      CComVariant var = pPropSet->rgProperties[0].vValue;
      CoTaskMemFree(pPropSet->rgProperties);
      CoTaskMemFree(pPropSet);

      if (SUCCEEDED(hr) && (var.boolVal == VARIANT_TRUE))
      {
         ADD_COLUMN_ENTRY_EX(ulCols, OLESTR("Bookmark"), 0, sizeof(DWORD), DBTYPE_BYTES,
            0, 0, GUID_NULL, CAgentMan, dwBookmark, DBCOLUMNFLAGS_ISBOOKMARK)
         ulCols++;
      }
   }

   // Next set the other columns up.
   ADD_COLUMN_ENTRY(ulCols, OLESTR("Command"), 1, 256, DBTYPE_STR, 0xFF, 0xFF,
      GUID_NULL, CAgentMan, szCommand)
   ulCols++;
   ADD_COLUMN_ENTRY(ulCols, OLESTR("Text"), 2, 256, DBTYPE_STR, 0xFF, 0xFF,
      GUID_NULL, CAgentMan, szText)
   ulCols++;

   ADD_COLUMN_ENTRY(ulCols, OLESTR("Command2"), 3, 256, DBTYPE_STR, 0xFF, 0xFF,
      GUID_NULL, CAgentMan, szCommand2)
   ulCols++;
   ADD_COLUMN_ENTRY(ulCols, OLESTR("Text2"), 4, 256, DBTYPE_STR, 0xFF, 0xFF,
      GUID_NULL, CAgentMan, szText2)
   ulCols++;

   if (pcCols != NULL)
      *pcCols = ulCols;

   return _rgColumns;
}

This example uses a static array to contain the column information. If the consumer does not want the bookmark column, one entry in the array is unused. To handle the information, you create two array macros, ADD_COLUMN_ENTRY and ADD_COLUMN_ENTRY_EX. ADD_COLUMN_ENTRY_EX takes an extra parameter, flags, that is needed if you designate a bookmark column.

////////////////////////////////////////////////////////////////////////
// MyProviderRS.h

#define ADD_COLUMN_ENTRY(ulCols, name, ordinal, colSize, type, precision, scale, guid, dataClass, member) \
   _rgColumns[ulCols].pwszName = (LPOLESTR)name; \
   _rgColumns[ulCols].pTypeInfo = (ITypeInfo*)NULL; \
   _rgColumns[ulCols].iOrdinal = (ULONG)ordinal; \
   _rgColumns[ulCols].dwFlags = 0; \
   _rgColumns[ulCols].ulColumnSize = (ULONG)colSize; \
   _rgColumns[ulCols].wType = (DBTYPE)type; \
   _rgColumns[ulCols].bPrecision = (BYTE)precision; \
   _rgColumns[ulCols].bScale = (BYTE)scale; \
   _rgColumns[ulCols].cbOffset = offsetof(dataClass, member);

#define ADD_COLUMN_ENTRY_EX(ulCols, name, ordinal, colSize, type, precision, scale, guid, dataClass, member, flags) \
   _rgColumns[ulCols].pwszName = (LPOLESTR)name; \
   _rgColumns[ulCols].pTypeInfo = (ITypeInfo*)NULL; \
   _rgColumns[ulCols].iOrdinal = (ULONG)ordinal; \
   _rgColumns[ulCols].dwFlags = flags; \
   _rgColumns[ulCols].ulColumnSize = (ULONG)colSize; \
   _rgColumns[ulCols].wType = (DBTYPE)type; \
   _rgColumns[ulCols].bPrecision = (BYTE)precision; \
   _rgColumns[ulCols].bScale = (BYTE)scale; \
   _rgColumns[ulCols].cbOffset = offsetof(dataClass, member); \
   memset(&(_rgColumns[ulCols].columnid), 0, sizeof(DBID)); \
   _rgColumns[ulCols].columnid.uName.pwszName = (LPOLESTR)name;

In the _GetColumnInfo function, the bookmark macro is used like this:

ADD_COLUMN_ENTRY_EX(ulCols, OLESTR("Bookmark"), 0, sizeof(DWORD),
   DBTYPE_BYTES, 0, 0, GUID_NULL, CAgentMan, dwBookmark,
   DBCOLUMNFLAGS_ISBOOKMARK)

You can now compile and run the enhanced provider. To test the provider, modify the test consumer, as described in Modifying the Consumer for Use with the Enhanced Provider. Run the test consumer with the provider. Verify that the test consumer retrieves the proper strings from the provider when you click the Run button on the test consumer dialog box.

Back to Implementing an OLE DB Template Provider


FAQ: Using the OLE DB Provider Templates

  • How do I add an interface to my provider?

  • How do I reference a property in my provider?

  • How do I add a property in my provider?

  • How do I dynamically bind columns in my provider?

  • How do I support free threading in my provider?

  • How do I test my provider?

  • How do I debug my provider?

  • Do I need to link Oledb.lib or Uuid.lib?

  • How does data conversion work?

See Also

FAQ: Using the OLE DB Consumer Templates


How Do I Add an Interface to My Provider?

Determine which object you want to add the interface to (usually data source, rowset, command, or session objects created by the ATL Provider Wizard). It is possible that the object you need to add the interface to is one that your provider does not currently support. In that case, run the ATL Object Wizard to create the object (right-click in the Project Workspace window ClassView pane and choose New ATL Object).

If you created a new class to support the interface, make the object inherit from that class. For example, you might add the class IRowsetIndexImpl to a rowset object:

template <class Creator>
class CAgentRowset :
public CRowsetImpl< CAgentRowset<Creator>, CAgentMan, Creator>,
   public IRowsetIndexImpl< … >

Add the interface to the COM_MAP in the object using the COM_INTERFACE_ENTRY macro. If there is no map, create one. For example:

BEGIN_COM_MAP(CAgentRowset)
     COM_INTERFACE_ENTRY(IRowsetIndex)
END_COM_MAP()

For the rowset object, chain the map of its parent object so that the object can delegate to the parent class. In this example, add the COM_INTERFACE_ENTRY_CHAIN macro to the map:

BEGIN_COM_MAP(CAgentRowset)
     COM_INTERFACE_ENTRY(IRowsetIndex)
     COM_INTERFACE_ENTRY_CHAIN(CRowsetImpl)
END_COM_MAP()


How Do I Reference a Property in My Provider?

Find the property group and property ID for the property you want. (See OLE DB Properties in the OLE DB Programmer's Reference.)

The following example assumes you are trying to get a property from the rowset. The code for using the session or command is similar, but uses a different interface.

Create a CDBPropset object using the property group as the parameter to the constructor. For example:

CDBPropSet propset(DBPROPSET_ROWSET);

Call AddProperty, passing it the Property ID and a value to be assigned to the property. The type of the value depends on the property you are using.

CDBPropSet propset(DBPROPSET_ROWSET);
propset.AddProperty(DBPROP_IRowsetChange, true);
propset.AddProperty(DBPROP_UPDATABILITY,
DBPROPVAL_UP_INSERT | DBPROPVAL_UP_CHANGE | DBPROPVAL_UP_DELETE);

Use the data member m_spUnkSite to get the pointer to the object that created your object.

CAgentRowset<CMyProviderCommand>* pRowset = (CAgentRowset<CMyProviderCommand>*) pThis;

CComQIPtr<IRowsetInfo, &IID_IRowsetInfo> spRowsetProps = pRowset;

Use the IRowset interface to call GetProperties. Pass the property set as a parameter. Here's the final code:

CAgentRowset<CMyProviderCommand>* pRowset = (CAgentRowset<CMyProviderCommand>*) pThis;

CComQIPtr<IRowsetInfo, &IID_IRowsetInfo> spRowsetProps = pRowset;

set.AddPropertyID(DBPROP_BOOKMARKS);
DBPROPSET* pPropSet = NULL;
ULONG ulPropSet = 0;
HRESULT hr;

if (spRowsetProps)
   hr = spRowsetProps->GetProperties(1, &set, &ulPropSet, &pPropSet);

if (pPropSet)
{
   CComVariant var = pPropSet->rgProperties[0].vValue;
   CoTaskMemFree(pPropSet->rgProperties);
   CoTaskMemFree(pPropSet);

   if (SUCCEEDED(hr) && (var.boolVal == VARIANT_TRUE))
   {
      …
   }
}


How Do I Add a Property in My Provider?

Find the property group and property ID for the property you want. (See OLE DB Properties in the OLE DB Programmer's Reference.)

In the provider code generated by the Wizard, find the property map corresponding to the property group. (The name of the property group usually corresponds to the name of the object. Command and rowset properties can be found in the command or rowset; data source and initialization properties can be found in the data source object.)

In the property map, add a PROPERTY_INFO_ENTRY macro. PROPERTY_INFO_ENTRY takes four parameters:

  • The property ID corresponding to your property. You must remove the first seven characters ("DBPROP_") from the front of the property name. For example, if you want to add DBPROP_MAXROWS, pass MAXROWS as the first element.

  • The variant type of the property (find in OLE DB Properties in the OLE DB Programmer's Reference). Enter the VT_ type (such as VT_BOOL or VT_I2) corresponding to the data type.

  • Flags to indicate whether the property is readable and writeable and the group it belongs to. For example, the following code indicates a read/write property belonging to the rowset group:
    DBPROPFLAGS_ROWSET | DBPROPFLAGS_READ | DBPROPFLAGS_WRITE
  • The base value of the property. This might be VARIANT_FALSE for a boolean type or zero for an integer type, for example. The property will have this value unless someone changes it.

    Note Some properties are connected or "chained" to other properties, such as bookmarks or updating. When a consumer sets one property to true, another property may also be set. The OLE DB Provider templates support this through the method CUtlProps::OnPropertyChanged. For an example of how to use OnPropertyChanged, see the MyProv: Sample.


How Do I Dynamically Bind Columns in My Provider?

Make sure you really need dynamic column binding. You may need it because:

  • Your rowset columns are not defined at compile time, or

  • You support an element such as bookmarks that adds columns.

To implement dynamic column binding:

  • Remove any PROVIDER_COLUMN_MAPs from your code.

  • In the user record (your structure), add the following declaration:
    static ATLCOLUMNINFO* _GetColumnInfo(void* pThis, ULONG* pcCols);
  • Implement the _GetColumnInfo function. This function lays out how the information is stored. You may need to get properties or other information for this function. You may want to create a macro, similar to the COLUMN_ENTRY macro, to add your own information.

    The following example shows a _GetColumnInfo function.

    // Check the property flag for bookmarks, if it is set, set the zero
// ordinal entry in the column map with the bookmark information.
CAgentRowset* pRowset = (CAgentRowset*) pThis;
CComQIPtr<IRowsetInfo, &IID_IRowsetInfo> spRowsetProps = pRowset;

CDBPropIDSet set(DBPROPSET_ROWSET);
set.AddPropertyID(DBPROP_BOOKMARKS);
DBPROPSET* pPropSet = NULL;
ULONG ulPropSet = 0;
HRESULT hr;

if (spRowsetProps)
hr = spRowsetProps->GetProperties(1, &set, &ulPropSet, &pPropSet);

if (pPropSet)
{
CComVariant var = pPropSet->rgProperties[0].vValue;
CoTaskMemFree(pPropSet->rgProperties);
CoTaskMemFree(pPropSet);

if (SUCCEEDED(hr) && (var.boolVal == VARIANT_TRUE))
{
ADD_COLUMN_ENTRY_EX(ulCols, OLESTR("Bookmark"), 0, sizeof(DWORD), DBTYPE_BYTES,
0, 0, GUID_NULL, CAgentMan, dwBookmark, DBCOLUMNFLAGS_ISBOOKMARK)
ulCols++;
}
}

// Next set the other columns up.
ADD_COLUMN_ENTRY(ulCols, OLESTR("Command"), 1, 256, DBTYPE_STR, 0xFF, 0xFF,
GUID_NULL, CAgentMan, szCommand)
ulCols++;
ADD_COLUMN_ENTRY(ulCols, OLESTR("Text"), 2, 256, DBTYPE_STR, 0xFF, 0xFF,
GUID_NULL, CAgentMan, szText)
ulCols++;

ADD_COLUMN_ENTRY(ulCols, OLESTR("Command2"), 3, 256, DBTYPE_STR, 0xFF, 0xFF,
GUID_NULL, CAgentMan, szCommand2)
ulCols++;
ADD_COLUMN_ENTRY(ulCols, OLESTR("Text2"), 4, 256, DBTYPE_STR, 0xFF, 0xFF,
GUID_NULL, CAgentMan, szText2)
ulCols++;

if (pcCols != NULL)
*pcCols = ulCols;

return _rgColumns;
}


How Do I Support Free Threading in My Provider?

All of the OLE DB provider classes are thread safe and register entries are set accordingly. It is a good idea to support free threading to enhance performance in multiuser situations. To keep your provider thread safe, you must ensure that your code is blocked properly. Whenever you write or store data, you must block the access with critical sections.

Each OLE DB template provider object has its own critical section. To make blocking easier, each new class you create should be a template class taking the parent class name as an argument.

The following example shows how to block your code:

template <class T>
class CMyObject<T> : public…

HRESULT MyObject::MyMethod(void)
{
   T* pT = (T*)this;      // this gets the parent class

// You don't need to do anything if you are only reading information

// if you wish to write information, do the following
   pT->Lock();         // engages critical section in the object
   …;                  // write whatever information you wish
   pT->Unlock();       // disengages the critical section
}

For more information on how to protect critical sections with Lock and Unlock, see Multithreading:How To Use the Synchronization Classes.

You must also ensure that any methods you override (like Execute) are thread safe.


How Do I Test My Provider?

Before you release a provider, you should perform the following tests, in the order indicated. These tests will ensure that the provider functions properly for most potential users.

  1. Test the provider using a consumer application written with the OLE DB consumer templates. The test consumer should cover all functional areas of your provider (all code that you have added or modified).

  2. Test the provider using a consumer application written with ADO. Most developers (especially Microsoft Visual Basic and Microsoft J++ developers) use ADO for consumer applications. Again, the test consumer should cover all functional areas of your provider.

  3. Run the OLE DB conformance tests (including ADO conformance tests) to ensure that your provider meets the level 0 standard for OLE DB providers. These tests and associated documentation are included with Visual C++. These tests also help to ensure that your provider runs well when aggregated by other service providers and are especially useful if you modify or add properties.


How Do I Debug My Provider?

There are two ways to debug your provider.

  • Because providers are created in process, you can create some consumer code using the OLE DB consumer templates and step into the provider normally.

  • You can use the ITEST utility that comes with Visual C++.

To use the ITEST utility

  1. Open the provider project.

  2. From the Projects menu, click Settings.

  3. In the Project Settings dialog box, select the Debug tab.

  4. In the Executable for Debug Session box, select the ITEST application.

  5. Set breakpoints and debug as usual.


Do I Need to Link Oledb.lib or Uuid.lib?

No. Visual C++ places the appropriate information from Oledb.lib into Uuid.lib.


How Does Data Conversion Work?

When the consumer requests a data type not supported by the provider, the OLE DB template provider code for IRowsetImpl::GetData calls Msdaenum.dll to convert the data type.

If you implement an interface like IRowsetChange that requires data conversion, you can call Msdaenum.dll to do the conversion. Use GetData, defined in Atldb.h, as an example.


List of OLE DB Provider Templates

The classes and interfaces for the OLE DB Provider Templates can be grouped into the following categories. The reference material also includes information about the macros for OLE DB Provider Templates.

The classes use the following naming convention: a class named with the pattern IWidgetImpl would provide an implementation of the interface IWidget.

Session Classes

IDBCreateCommandImpl

Creates a new command from the session object and returns the requested interface on the newly created command. Optional interface on session objects.

ISessionPropertiesImpl

Implements session properties by calling a static function defined by the property set map. The property set map should be specified in your session class. Mandatory interface on sessions.

IGetDataSourceImpl

Obtains an interface pointer to the data source object. Mandatory interface on the session.

IOpenRowsetImpl

Opens and returns a rowset that includes all rows from a single base table or index. Mandatory interface for a session object.

Rowset Classes

CRowsetImpl

Provides a standard OLE DB rowset implementation without requiring multiple inheritance of many implementation interfaces. The only method for which you must provide implementation is Execute.

IRowsetImpl

Provides an implementation of the IRowset interface, which is the base rowset interface.

CSimpleRow

Provides a default implementation for the row handle, which is used in the IRowsetImpl class. A row handle is logically a unique tag for a result row. IRowsetImpl creates a new CSimpleRow for every row requested in IRowsetImpl::GetNextRows.

IAccessorImpl

OLE DB requires providers to implement an HACCESSOR, which is a tag to an array of DBBINDING structures. Provides HACCESSORs that are addresses of the BindType structures. Mandatory on rowsets and commands.

IRowsetInfoImpl

Implements the rowset properties by using the property set map defined in your command class. Mandatory interface on rowsets.

IColumnsInfoImpl

Delegates to a static function defined by the provider column map. Mandatory interface on rowsets and commands.

IConvertTypeImpl

Gives information on the availability of type conversions on a command or on a rowset. Mandatory on commands, rowsets, and index rowsets. Implements the IConvertType interface by delegating to the conversion object supplied by OLE DB.

IDBSchemaRowsetImpl

Implements the IDBSchemaRowset interface and the templatized creator function CreateSchemaRowset.

Command Classes

ICommandTextImpl

Sets, stores, and returns the command text. Mandatory on commands.

ICommandImpl

Provides an implementation of the ICommand interface. This interface is not visible, but is handled by ICommandTextImpl. A mandatory interface on the command object.

ICommandPropertiesImpl

This implementation of the ICommandProperties interface is provided by a static function defined by the BEGIN_PROPSET_MAP macro. Mandatory on commands.

Other command classes are IColumnsInfoImpl and IAccessorImpl, described in the Rowset Classes section above.

Data Source Classes

IDBInitializeImpl

Creates and deletes the connection with the consumer. Mandatory interface on data source objects and optional interface on enumerators.

IDBPropertiesImpl

IDBProperties is a mandatory interface for data source objects and an optional interface for enumerators. However, if an enumerator exposes IDBInitialize, it must expose IDBProperties (properties on the data source).

IDBCreateSessionImpl

Creates a new session from the data source object and returns the requested interface on the newly created session. Mandatory interface on data source objects.

Other Classes

CUtlProps

Implements properties for a variety of OLE DB property interfaces (for example, IDBProperties, ISessionProperties, and IRowsetInfo).

See Also

List of OLE DB Consumer Templates, Home Page for OLE DB Template Classes


CRowsetImpl

template <class T, class Storage, class PropClass, class ArrayType = CSimpleArray<Storage>> class CRowsetImpl

Parameters

T

The user’s class that derives from CRowsetImpl.

Storage

The user record class.

PropClass

The class that contains properties for the rowset; typically the command.

ArrayType

The class that will act as storage for the rowset’s data. This parameter defaults to CSimpleArray, but it can be any class that supports the required functionality. See the ATLMTO sample for an example of changing the default array parameter.

CRowsetImpl provides a standard OLE DB rowset implementation without requiring multiple inheritance of many implementation interfaces. CRowsetImpl provides overrides in the form of static upcasts. The methods control the manner in which a given rowset will validate command text. You can create your own CRowsetImpl-style class by making your implementation interfaces multiple-inherited. See the MyProv sample for an example of this technique. The only method for which you must provide implementation is Execute. Depending on what type of rowset you are creating, the creator methods will expect different signatures for Execute. For example, if you are using a CRowsetImpl-derived class to implement a schema rowset, the Execute method will have the following signature:

HRESULT Execute(LONG* pcRows, ULONG cRestrictions, const VARIANT* rgRestrictions)

If you are creating a CRowsetImpl-derived class to implement a command or session’s rowset, the Execute method will have the following signature:

HRESULT Execute(LONG* pcRows, DBPARAMS* pParams)

To implement any of the CRowsetImpl-derived Execute methods, you must populate your internal data buffers (m_rgRowData).

#include < atldb.h >

CRowsetImpl Class Members


CRowsetImpl Class Members

Methods |
SetCommandText | Validates and stores the DBIDs in the two strings (m_strCommandText and m_strIndexText).
NameFromDBID | Extracts a string from a DBID and copies it to the bstr passed in.

Overridable Methods |
GetCommandFromID | Checks to see if either or both parameters contain string values, and if so, copies the string values to the data members m_strCommandText and m_strIndexText.
ValidateCommandID | Checks to see if either or both DBIDs contain string values, and if so, copies them to its data members m_strCommandText and m_strIndexText.
GetColumnInfo | Retrieves column information for a particular client request.

Data Members |
m_strCommandText | Contains the rowset’s initial command.
m_strIndexText | Contains the rowset’s initial index.
m_rgRowData | By default, a CSimpleArray that templatizes on the user record template argument to CRowsetImpl. Another array type class can be used by changing the ArrayType template argument to CRowsetImpl.

CRowsetImpl Overview


CRowsetImpl::GetColumnInfo

static ATLCOLUMNINFO* GetColumnInfo( T* pv, ULONG* pcCols );

Return Value

A pointer to a static ATLCOLUMNINFO structure.

Parameters

pv

[in] A pointer to the user’s CRowsetImpl derived class.

pcCols

[in] A pointer (output) to the number of columns returned.

Remarks

This method is an advanced override.

This method is called by several base implementation classes to retrieve column information for a particular client request. Usually, this method would be called by IColumnsInfoImpl. If you override this method, you must place a version of the method in your CRowsetImpl-derived class. Because the method may be placed in a non-templatized class, you must change pv to the appropriate CRowsetImpl-derived class.

The following example demonstrates GetColumnInfo's usage. In this example, CMyRowset is a CRowsetImpl-derived class. In order to override GetColumnInfo for all instances of this class, place the following method in the CMyRowset class definition:

   static ATLCOLUMNINFO* GetColumnInfo(CMyRowset* pRowset, ULONG* pcCols)
{
   ....
}

Both the ATLMTO sample and the MyProv sample demonstrate overriding this method.


CRowsetImpl::GetCommandFromID

HRESULT GetCommandFromID( DBID* pTableID, DBID* pIndexID );

Return Value

A standard HRESULT.

Parameters

PTableID

[in] A pointer to the DBID representing the Table ID.

pIndexID

[in] A pointer to the DBID representing the Index ID.

Remarks

This method is called through a static upcast by CRowsetImpl to populate the data members m_strCommandText and m_strIndexText. By default, this method checks to see if either or both parameters contain string values. If they contain string values, this method copies the string values to the data members. By placing a method with this signature in your CRowsetImpl-derived class, your method will be called instead of the base implementation.

CRowsetImpl Overview | CRowsetImpl Class Members

See Also

CRowsetImpl::SetCommandText


CRowsetImpl::NameFromDBID

HRESULT NameFromDBID( DBID* pDBID, CComBSTR& bstr, bool bIndex );

Return Value

A standard HRESULT. Depending on whether the DBID is a table or an index (denoted by bIndex), the method will either return DB_E_NOINDEX or DB_E_NOTABLE.

Parameters

pDBID

[in] A pointer to the DBID from which to extract a string.

bstr

[in] A CComBSTR reference to place a copy of the DBID string.

bIndex

[in] true if an index DBID; false if a table DBID.

Remarks

This method is called by the CRowsetImpl implementations of ValidateCommandID and GetCommandFromID. It extracts a string from a DBID and copies it to the bstr passed in.


CRowsetImpl::SetCommandText

HRESULT SetCommandText( DBID* pTableID, DBID* pIndexID );

Return Value

A standard HRESULT.

Parameters

pTableID

[in] A pointer to the DBID representing the table ID.

pIndexID

[in] A pointer to the DBID representing the index ID.

Remarks

This method is called by CreateRowset, a static templatized method of IOpenRowsetImpl. It validates and stores the DBIDs in the two strings (m_strCommandText and m_strIndexText). This method delegates its work by calling ValidateCommandID and GetCommandFromID through an upcasted pointer.


CRowsetImpl::ValidateCommandID

HRESULT ValidateCommandID( DBID* pTableID, DBID* pIndexID );

Return Value

A standard HRESULT.

Parameters

pTableID

[in] A pointer to the DBID representing the table ID.

pIndexID

[in] A pointer to the DBID representing the index ID.

Remarks

This method is called through a static upcast by CRowsetImpl to populate its data members m_strCommandText and m_strIndexText. By default, this method checks to see if either or both DBIDs contain string values, and if so, copies them to its data members. By placing a method with this signature in your CRowsetImpl derived class, your method will be called instead of the base implementation.

CRowsetImpl Overview | CRowsetImpl Class Members

See Also

CRowsetImpl::SetCommandText


CRowsetImpl::m_rgRowData

ArrayType m_rgRowData;

Remarks

ArrayType is a template parameter to CRowsetImpl. By default, this will be a CSimpleArray that templatizes on the user record template argument to CRowsetImpl. See the ATLMTO sample for an example of using a non-default template argument for ArrayType.

CRowsetImpl Overview | CRowsetImpl Class Members

See Also

CRowsetImpl::m_strCommandText, CRowsetImpl::m_strIndexText


CRowsetImpl::m_strCommandText

CComBSTR m_strCommandText;

Remarks

Contains the rowset’s initial command.

CRowsetImpl Overview | CRowsetImpl Class Members

See Also

CRowsetImpl::m_strIndexText, CRowsetImpl::m_rgRowData, CRowsetImpl::GetCommandFromID, CRowsetImpl::SetCommandText, CRowsetImpl::ValidateCommandID


CRowsetImpl::m_strIndexText

CComBSTR m_strIndexText;

Remarks

Contains the rowset’s initial index.

CRowsetImpl Overview | CRowsetImpl Class Members

See Also

CRowsetImpl::m_strCommandText, CRowsetImpl::m_rgRowData, CRowsetImpl::GetCommandFromID, CRowsetImpl::SetCommandText, CRowsetImpl::ValidateCommandID


CSimpleRow

class CSimpleRow

Remarks

This class provides a default implementation for the row handle, which is used in the IRowsetImpl class. A row handle is logically a unique tag for a result row. IRowsetImpl creates a new CSimpleRow for every row requested in IRowsetImpl::GetNextRows. CSimpleRow can also be replaced with your own implementation of the row handle, as it is a default template argument to IRowsetImpl. The only requirement to replacing this class is to have the replacement class provide a constructor that accepts a single parameter of type LONG.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, IRowsetImpl


CSimpleRow Class Members

Methods

AddRefRow | Adds a reference count to an existing row handle.
CSimpleRow | The constructor.
ReleaseRow | Releases rows.
Compare | Compares two rows to see if they refer to the same row instance.

Data Members

m_dwRef | Reference count to an existing row handle.
m_iRowset | An index to the rowset representing the cursor.

CSimpleRow Overview


CSimpleRow::CSimpleRow

CSimpleRow( LONG iRowsetCur );

Parameters

iRowsetCur

[in] Index to the current rowset.

Remarks

The constructor. Sets m_iRowset to iRowsetCur.


CSimpleRow::AddRefRow

DWORD AddRefRow( );

Remarks

Adds a reference count to an existing row handle in a thread-safe manner.

CSimpleRow Overview | Class Members

See Also

CSimpleRow::ReleaseRow, IRowsetImpl::AddRefRows


CSimpleRow::Compare

HRESULT Compare( CSimpleRow* pRow )

Return Value

An HRESULT value, usually S_OK, indicating the two rows are the same row instance, or S_FALSE, indicating the two rows are different. See IRowsetIdentity::IsSameRow in the OLE DB Programmer's Reference for other possible return values.

Parameters

pRow

A pointer to a CSimpleRow object.

Remarks

Compares two rows to see if they refer to the same row instance.

CSimpleRow Overview | Class Members

See Also

CSimpleRow::ReleaseRow, IRowsetImpl::RefRows


CSimpleRow::ReleaseRow

DWORD ReleaseRow( );

Remarks

Releases rows in a thread-safe manner.

CSimpleRow Overview | Class Members

See Also

CSimpleRow::AddRefRow, IRowsetImpl::RefRows


CSimpleRow::m_dwRef

DWORD m_dwRef;

Remarks

Reference count to an existing row handle.

CSimpleRow Overview | Class Members

See Also

CSimpleRow::AddRefRow, CSimpleRow::ReleaseRow


CSimpleRow::m_iRowset

LONG m_iRowset;

Remarks

Index to the rowset representing the cursor.

CSimpleRow Overview | Class Members

See Also

CSimpleRow::CSimpleRow


CUtlProps

template < class T >
class CUtlProps : public CBitFieldOps, public CDBIDOps

Parameters

T

The class that contains the BEGIN_PROPSET_MAP.

Remarks

CUtlProps implements properties for a variety of OLE DB property interfaces (for example, IDBProperties, IDBProperties, and IRowsetInfo). Most of this class is an implementation detail.

CUtlProps contains two members for setting properties internally: GetPropValue and SetPropValue.

For more information on the macros used in a property set map, see BEGIN_PROPSET_MAP and END_PROPSET_MAP.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


CUtlProps Class Members

Methods

GetPropValue | Gets a property from a property set.
SetPropValue | Sets a property in a property set.
IsValidValue | Used to validate a value before setting a property.
OnPropertyChanged | Called after setting a property to handle chained properties.

CUtlProps Overview


CUtlProps::GetPropValue

HRESULT GetPropValue( const GUID* pguidPropSet, DBPROPID dwPropId, VARIANT* pvValue );

Return Value

Failure on failure and S_OK if successful.

Parameters

pguidPropSet

[in] The GUID for the PropSet.

dwPropId

[in] The property index.

pvValue

[out] A pointer to a variant that contains the new property value.

Remarks

Gets a property from a property set.


CUtlProps::IsValidValue

virtual HRESULT IsValidValue( ULONG iCurSet, DBPROP* pDBProp );

Return Value

A standard HRESULT. The default return value is S_OK.

Parameters

iCurSet

The index into the property-set array; zero if there is only one property set.

pDBProp

The property ID and new value in a DBPROP structure.

Remarks

If you have any validation routines you want to run on a value that you are about to use to set a property, you should override this function. For example, you could validate DBPROP_AUTH_PASSWORD against a password table to determine a valid value.


CUtlProps::OnPropertyChanged

virtual HRESULT OnPropertyChanged( ULONG iCurSet, DBPROP* pDBProp );

Return Value

A standard HRESULT. The default return value is S_OK.

Parameters

iCurSet

The index into the property-set array; zero if there is only one property set.

pDBProp

The property ID and new value in a DBPROP structure.

Remarks

If you want to handle chained properties, such as bookmarks or updates whose values are dependent on another property’s value, you should override this function. The MYPROV sample demonstrates how to use OnPropertyChanged to handle bookmarking.

Example

In this function, the user gets the property ID from the DBPROP* parameter. Now, it is possible to compare the ID against a property to chain. When the property is found, SetProperties is called with the property that will now be set in conjunction with the other property. In this case, if one gets the DBPROP_IRowsetLocate, DBPROP_LITERALBOOKMARKS, or DBPROP_ORDEREDBOOKMARKS property, one can set the DBPROP_BOOKMARKS property.

HRESULT OnPropertyChanged(ULONG iCurSet, DBPROP* pDBProp)
{
   ATLASSERT(pDBProp != NULL);

   DWORD dwPropertyID = pDBProp->dwPropertyID;

   if (dwPropertyID == DBPROP_IRowsetLocate ||
      dwPropertyID == DBPROP_LITERALBOOKMARKS ||
      dwPropertyID == DBPROP_ORDEREDBOOKMARKS)
   {
      CComVariant var = pDBProp->vValue;

      if (var.boolVal == VARIANT_TRUE)
      {
         // Set the bookmarks property as these are chained
         CComVariant bookVar(true);
         CDBPropSet set(DBPROPSET_ROWSET);
         set.AddProperty(DBPROP_BOOKMARKS, bookVar);

         return SetProperties(1, &set);
      }
   }

   return S_OK;
}


CUtlProps::SetPropValue

HRESULT SetPropValue( const GUID* pguidPropSet, DBPROPID dwPropId, VARIANT* pvValue );

Return Value

Failure on failure and S_OK if successful.

Parameters

pguidPropSet

[in] The GUID for the PropSet.

dwPropId

[in] The property index.

pvValue

[in] A pointer to a variant that contains the new property value.

Remarks

Sets a property in a property set.


IAccessorImpl

template <class T, class BindType = ATLBINDINGS, class BindingVector = CSimpleMap < int, BindType* > >

class ATL_NO_VTABLE IAccessorImpl : public IAccessorImplBase<BindType>

Parameters

T

Your rowset or command object class.

BindType

Storage unit for binding information.

BindingVector

Storage unit for column information.

Remarks

This is mandatory on rowsets and commands. Provides an implementation of the IAccessor interface. OLE DB requires providers to implement an HACCESSOR, which is a tag to an array of DBBINDING structures. HACCESSORs provided by IAccessorImpl are addresses of the BindType structures. By default, BindType is defined as an ATLBINDINGS in IAccessorImpl’s template definition. BindType provides a mechanism used by IAccessorImpl to track the number of elements in its DBBINDING array as well as a reference count and accessor flags.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IAccessorImpl Class Members

Methods

IAccessorImpl The constructor.

Interface Methods

AddRefAccessor | Adds a reference count to an existing accessor.
CreateAccessor | Creates an accessor from a set of bindings.
GetBindings | Returns the bindings in an accessor.
ReleaseAccessor | Releases an accessor.

Base Class Methods

CreateAccessor Creates an accessor from a set of bindings.

IAccessorImpl Overview


IAccessorImpl::AddRefAccessor

HRESULT AddRefAccessor( HACCESSOR hAccessor, ULONG *pcRefCount );

See IAccessor::AddRefAccessor in the OLE DB Programmer's Reference.

Remarks

Adds a reference count to an existing accessor.

IAccessorImpl Overview | Class Members

See Also

IAccessorImpl::CreateAccessor, IAccessorImpl::ReleaseAccessor


IAccessorImpl::CreateAccessor

HRESULT CreateAccessor( DBACCESSORFLAGS dwAccessorFlags, ULONG cBindings, const DBBINDING rgBindings[], ULONG cbRowSize, HACCESSOR *phAccessor, DBBINDSTATUS rgStatus[] );

See IAccessor::CreateAccessor in the OLE DB Programmer's Reference.

Remarks

Creates an accessor from a set of bindings.

IAccessorImpl Overview | Class Members

See Also

IAccessorImpl::AddRefAccessor, IAccessorImpl::ReleaseAccessor


IAccessorImpl::GetBindings

HRESULT GetBindings( HACCESSOR hAccessor, DBACCESSORFLAGS *pdwAccessorFlags, ULONG *pcBindings, DBBINDING **prgBindings );

See IAccessor::GetBindings in the OLE DB Programmer's Reference.

Remarks

Returns the basic columns bindings from the consumer in an accessor.


IAccessorImpl::IAccessorImpl

IAccessorImpl( );

Remarks

The constructor.


IAccessorImpl::ReleaseAccessor

ReleaseAccessor( HACCESSOR hAccessor, ULONG *pcRefCount );

See IAccessor::ReleaseAccessor in the OLE DB Programmer's Reference.

Remarks

Releases an accessor.

IAccessorImpl Overview | Class Members

See Also

IAccessorImpl::CreateAccessor, IAccessorImpl::AddRefAccessor


IColumnsInfoImpl

template <class T>
class ATL_NO_VTABLE IColumnsInfoImpl : public IcolumnsInfo, public CDBIDOps

Parameters

T

Your class, derived from IColumnsInfoImpl.

Remarks

A mandatory interface on rowsets and commands. IColumnsInfoImpl provides an implementation of the IColumnsInfo interface. To modify the behavior of your provider's IColumnsInfo implementation, you need to modify the provider column map.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IColumnsInfoImpl Class Members

Methods

CheckCommandText | Determines whether there is a valid command to execute). Not called directly by user.
GetColumnInfo | Returns the column metadata needed by most consumers.
MapColumnIDs | Returns an array of ordinals of the columns in a rowset that are identified by the specified column IDs.

IColumnsInfoImpl Overview


IColumnsInfoImpl::CheckCommandText

HRESULT CheckCommandText( );

Remarks

Called to determine if the command text is NULL or not (in other words, whether there is a valid command to execute). This is a helper method not called directly by user.


IColumnsInfoImpl::GetColumnInfo

HRESULT GetColumnInfo( ULONG *pcColumns, DBCOLUMNINFO **prgInfo, OLECHAR **ppStringsBuffer );

See IColumnsInfo::GetColumnInfo in the OLE DB Programmer’s Reference.

Remarks

Returns the column metadata needed by most consumers.

IColumnsInfoImpl Overview | Class Members

See Also

IColumnsInfoImpl::MapColumnIDs


IColumnsInfoImpl::MapColumnIDs

HRESULT MapColumnIDs( ULONG cColumnIDs, const DBID rgColumnIDs[], ULONG rgColumns[] );

See IColumnsInfo::MapColumnIDs in the OLE DB Programmer's Reference.

Remarks

Returns an array of ordinals of the columns in a rowset that are identified by the specified column IDs.

IColumnsInfoImpl Overview | Class Members

See Also

IColumnsInfoImpl::GetColumnInfo


ICommandImpl

template <class T>
class ATL_NO_VTABLE ICommandImpl : public ICommand

Parameters

T

Your class, derived from ICommandImpl.

Remarks

A mandatory interface on the command object. This class provides implementation for the ICommand interface.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


ICommandImpl Class Members

Methods

ICommandImpl | The constructor.
CancelExecution | Cancels the current command execution.
CreateRowset | Creates a rowset object.
Cancel | Cancels the current command execution.
Execute | Executes the command.
GetDBSession | Returns an interface pointer to the session that created the command.

Data Members

m_bIsExecuting | Indicates whether the command is currently executing.
m_bCancelWhenExecuting | Indicates whether the command is to be canceled when executing.
m_bCancel | Indicates whether the command is to be canceled.

ICommandImpl Overview


ICommandImpl::Cancel

HRESULT Cancel( );

See ICommand::Cancel in the OLE DB Programmer's Reference.

Remarks

Cancels the current command execution.

ICommandImpl Overview | Class Members

See Also

ICommandImpl::CancelExecution


ICommandImpl::CancelExecution

HRESULT CancelExecution( );

Remarks

Cancels the current command execution.

ICommandImpl Overview | Class Members

See Also

ICommandImpl::Execute, ICommandImpl::Cancel


ICommandImpl::CreateRowset

template <class RowsetClass>
HRESULT CreateRowset( IUnknown* pUnkOuter, REFIID riid, DBPARAMS * pParams, LONG * pcRowsAffected, IUnknown** ppRowset, RowsetClass*& pRowsetObj );

See ICommand::Execute in the OLE DB Programmer's Reference.

Return Value

A standard HRESULT value. See ICommand::Execute for a list of typical values.

Parameters

RowsetClass

A template class member representing the user's rowset class. Usually generated by the wizard.

pUnkOuter

[in] A pointer to the controlling IUnknown interface if the rowset is being created as part of an aggregate; otherwise, it is null.

riid

[in] Corresponds to riid in ICommand::Execute.

pParams

[in/out] Corresponds to pParams in ICommand::Execute.

pcRowsAffected

Corresponds to pcRowsAffected in ICommand::Execute.

ppRowset

[in/out] Corresponds to ppRowset in ICommand::Execute.

pRowsetObj

[out] A pointer to a rowset object. Typically this parameter is not used, but it can be used if you must perform more work on the rowset before passing it to a COM object. The lifetime of pRowsetObj is bound by ppRowset.

Remarks

Called by Execute to create a single rowset. To create more than one rowset, or to provide your own conditions for creating different rowsets, place different calls to CreateRowset from within Execute.


ICommandImpl::Execute

HRESULT Execute( IUnknown * pUnkOuter, REFIID riid, DBPARAMS * pParams, LONG * pcRowsAffected, IUnknown ** ppRowset );

See ICommand::Execute in the OLE DB Programmer's Reference.

Remarks

Executes the command. The outgoing interface requested will be an interface acquired from the rowset object that this function creates.

Execute calls CreateRowset. Override the default implementation to create more than one rowset or to provide your own conditions for creating different rowsets.

For an example of overriding Execute, see the Provider sample.

ICommandImpl Overview | Class Members

See Also

ICommandImpl::CancelExecution


ICommandImpl::GetDBSession

HRESULT GetDBSession( REFIID riid, IUnknown ** ppSession );

See ICommand::GetDBSession in the OLE DB Programmer's Reference.

Remarks

Returns an interface pointer to the session that created the command. Useful for retrieving properties from the session.


ICommandImpl::ICommandImpl

ICommandImpl( );

Remarks

The constructor.


ICommandImpl::m_bCancel

unsigned m_bCancel:1;

Remarks

Indicates whether the command is canceled. You can retrieve this variable in the Execute method of your command class and cancel as appropriate.

ICommandImpl Overview | Class Members

See Also

ICommandImpl::m_bCancelWhenExecuting


ICommandImpl::m_bCancelWhenExecuting

unsigned m_bCancelWhenExecuting:1;

Remarks

Indicates whether the command can be canceled when executing. Defaults to true (can be canceled).

ICommandImpl Overview | Class Members

See Also

ICommandImpl::m_bCancel


ICommandImpl::m_bIsExecuting

unsigned m_bIsExecuting:1;

Remarks

Indicates whether the command is currently executing. The Execute method of your command class can set this variable to true.

ICommandImpl Overview | Class Members

See Also

ICommandImpl::m_bCancelWhenExecuting


ICommandPropertiesImpl

template <class T, class PropClass = T>
class ATL_NO_VTABLE ICommandPropertiesImpl : public ICommandProperties, public CUtlProps<PropClass>

Parameters

T

Your class, derived from ICommandPropertiesImpl.

PropClass

Your properties class.

Remarks

This is mandatory on commands. ICommandPropertiesImpl provides an implementation of the ICommandProperties interface. The implementation is provided by a static function defined by the BEGIN_PROPSET_MAP macro.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


ICommandPropertiesImpl Class Members

Interface Methods

GetProperties | Returns the list of properties in the Rowset property group that are currently requested for the rowset.
SetProperties | Sets properties in the Rowset property group.

ICommandPropertiesImpl Overview


ICommandPropertiesImpl::GetProperties

HRESULT GetProperties( const ULONG cPropertyIDSets, const DBPROPIDSET rgPropertyIDSets[], ULONG *pcPropertySets, DBPROPSET **prgPropertySets );

See ICommandProperties::GetProperties in the OLE DB Programmer's Reference.

Remarks

Returns all the requested property sets using the command’s property map. See BEGIN_PROPSET_MAP.

ICommandPropertiesImpl Overview | Class Members

See Also

ICommandPropertiesImpl::SetProperties


ICommandPropertiesImpl::SetProperties

HRESULT SetProperties( ULONG cPropertySets, DBPROPSET rgPropertySets[] );

See ICommandProperties::SetProperties in the OLE DB Programmer's Reference.

Remarks

Sets properties for the command object.

ICommandPropertiesImpl Overview | Class Members

See Also

ICommandPropertiesImpl::GetProperties


ICommandTextImpl

template <class T >
class ATL_NO_VTABLE ICommandTextImpl : public ICommandImpl<T>

Parameters

T

The command class derived from ICommandTextImpl.

Remarks

A mandatory interface on commands. ICommandTextImpl provides an implementation for the ICommandText interface.

#include <altdb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


ICommandTextImpl Class Members

Interface Methods

GetCommandText | Returns the text command set by the last call to SetCommandText.
SetCommandText | Sets the command text, replacing the existing command text.

Data Members

m_strCommandText Stores the command text.

ICommandTextImpl Overview


ICommandTextImpl::GetCommandText

HRESULT GetCommandText( GUID * pguidDialect, LPOLESTR * ppwszCommand );

See ICommandText::GetCommandText in the OLE DB Programmer's Reference. The pguidDialect parameter is ignored by default.

Remarks

Returns the text command set by the last call to SetCommandText.


ICommandTextImpl::SetCommandText

HRESULT SetCommandText( REFGUID rguidDialect, LPCOLESTR pwszCommand );

See ICommandText::SetCommandText in the OLE DB Programmer’s Reference.

Remarks

Sets the command text, replacing the existing command text.

ICommandTextImpl Overview | Class Members

See Also

ICommandTextImpl::GetCommandText


ICommandTextImpl::m_strCommandText

CComBSTR m_strCommandText;

Remarks

Stores the command text string.

ICommandTextImpl Overview | Class Members

See Also

ICommandTextImpl::GetCommandText, ICommandTextImpl::SetCommandText


IConvertTypeImpl

template <class T>
class ATL_NO_VTABLE IConvertTypeImpl : public IConvertType, public CConvertHelper

Parameters

T

Your class, derived from IConvertTypeImpl.

Remarks

This interface is mandatory on commands, rowsets, and index rowsets. IConvertTypeImpl provides an implementation of the IConvertType interface. IConvertTypeImpl implements the interface by delegating to the conversion object supplied by OLE DB.

#include <atldb.h>

Class Members

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IConvertTypeImpl Class Members

Interface Methods

CanConvert Gives information on the availability of type conversions on a command or on a rowset.

IConvertTypeImpl Overview


IConvertTypeImpl::CanConvert

HRESULT CanConvert( DBTYPE wFromType, DBTYPE wToType, DBCONVERTFLAGS dwConvertFlags );

See IConvertType::CanConvert in the OLE DB Programmer's Reference.

Remarks

Gives information on the availability of type conversions on a command or on a rowset. Uses OLE DB data conversion in MSADC.DLL.


IDBCreateCommandImpl

template <class T, class CommandClass >
class ATL_NO_VTABLE IDBCreateCommandImpl : public IDBCreateCommand

Parameters

T

The session object derived from IDBCreateCommandImpl.

CommandClass

Your command class.

Remarks

An optional interface on the session object to obtain a new command. IDBCreateCommandImpl provides an implementation of the IDBCreateCommand interface.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IDBCreateCommandImpl Class Members

Interface Methods

CreateCommand Creates a new command.

IDBCreateCommandImpl Overview


IDBCreateCommandImpl::CreateCommand

HRESULT CreateCommand( IUnknown *pUnkOuter, REFIID riid, IUnknown **ppvCommand );

See IDBCreateCommand::CreateCommand in the OLE DB Programmer’s Reference.

Parameters

Some parameters correspond to OLE DB Programmer’s Reference parameters of different names, which are described in IDBCreateCommand::CreateCommand:

OLE DB Template parameters | OLE DB Programmer's Reference parameters
ppvCommand | ppCommand

Remarks

Creates a new command and returns the requested interface.


IDBCreateSessionImpl

template <class T, class SessionClass>
class ATL_NO_VTABLE IDBCreateSessionImpl : public IDBCreateSession

Parameters

T

Your class, derived from IDBCreateSessionImpl.

SessionClass

The session object.

Remarks

A mandatory interface on data source objects. IDBCreateSessionImpl provides an implementation for the IDBCreateSession interface.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IDBCreateSessionImpl Class Members

Interface Methods

CreateSession Creates a new session from the data source object and returns the requested interface on the newly created session.

IDBCreateSessionImpl Overview


IDBCreateSessionImpl::CreateSession

HRESULT CreateSession( IUnknown *pUnkOuter, REFIID riid, IUnknown **ppDBSession );

See IDBCreateSession::CreateSession in the OLE DB Programmer's Reference.

Remarks

Creates a new session from the data source object and returns the requested interface on the newly created session.


IDBInitializeImpl

template <class T>
class ATL_NO_VTABLE IDBInitializeImpl : public IDBInitialize

Parameters

T

Your class, derived from IDBInitializeImpl.

A mandatory interface on data source objects and optional interface on enumerators. IDBInitializeImpl provides an implementation for the IDBInitialize interface.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IDBInitializeImpl Class Members

Methods

IDBInitializeImpl The constructor.

Interface Methods

Initialize | Starts the provider.
Uninitialize | Stops the provider.

Data Members

m_dwStatus | Data source flags.
m_pCUtlPropInfo | A pointer to implementation of DB Properties information.

IDBInitializeImpl Overview


IDBInitializeImpl::IDBInitializeImpl

HRESULT IDBInitializeImpl( );

Remarks

The constructor. Initializes all data members.


IDBInitializeImpl::Initialize

HRESULT Initialize( void );

See IDBInitializeImpl::Initialize in the OLE DB Programmer’s Reference.

Remarks

Initializes the data source object by preparing its property support.

IDBInitializeImpl Overview | Class Members

See Also

IDBInitializeImpl::Uninitialize


IDBInitializeImpl::Uninitialize

HRESULT Uninitialize( void );

See IDBInitializeImpl::Uninitialize in the OLE DB Programmer’s Reference.

Remarks

Places the data source object in an uninitialized state by freeing internal resources such as the property support.

IDBInitializeImpl Overview | Class Members

See Also

IDBInitializeImpl::Initialize


IDBInitializeImpl::m_dwStatus

DWORD m_dwStatus;

Remarks

Contains one or more of the following enum.

enum DATASOURCE_FLAGS {
   DSF_MASK_INIT         = 0xFFFFF00F,
   DSF_PERSIST_DIRTY      = 0x00000001,   // Set if init string changes.
   DSF_INITIALIZED         = 0x00000010,   // Have we been initialized.
};

where,

DSF_MASK_INIT | A mask to restore the uninitialized state.
DSF_PERSIST_DIRTY | Set if object requires persistence.
DSF_INITIALIZED | Set if data source is initialized.

IDBInitializeImpl Overview | Class Members

See Also

IDBInitializeImpl::IDBInitializeImpl, IDBInitializeImpl::Uninitialize


IDBInitializeImpl::m_pCUtlPropInfo

CUtlPropInfo<T>* m_pCUtlPropInfo;

Remarks

A pointer to implementation object for DB Properties information.


IDBPropertiesImpl

template <class T>
class ATL_NO_VTABLE IDBPropertiesImpl : public IDBProperties, public CUtlProps<T>

Parameters

T

Your class, derived from IDBPropertiesImpl.

Remarks

IDBProperties is a mandatory interface for data source objects and an optional interface for enumerators. However, if an enumerator exposes IDBInitialize, it must expose IDBProperties. IDBPropertiesImpl provides an implementation for the IDBProperties interface. IDBPropertiesImpl implements IDBProperties by using a static function defined by BEGIN_PROPSET_MAP.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IDBPropertiesImpl Class Members

Interface Methods

GetProperties | Returns the values of properties in the Data Source, Data Source Information, and Initialization property groups that are currently set on the data source object or the values of properties in the Initialization property group that are currently set on the enumerator.
GetPropertyInfo | Returns information about all properties supported by the provider.
SetProperties | Sets properties in the Data Source and Initialization property groups, for data source objects, or the Initialization property group, for enumerators.

IDBPropertiesImpl Overview


IDBPropertiesImpl::GetProperties

HRESULT GetProperties( ULONG cPropertySets, const DBPROPIDSET rgPropertySets[], ULONG *pcProperties, DBPROPSET **prgProperties );

See IDBProperties::GetProperties in the OLE DB Programmer's Reference.

Parameters

Some parameters correspond to OLE DB Programmer's Reference parameters of different names, which are described in IDBProperties::GetProperties:

OLE DB Template parameters | OLE DB Programmer's Reference parameters
cPropertySets | cPropertyIDSets
rgPropertySets | rgPropertyIDSets
pcProperties | pcPropertySets
prgProperties | prgPropertySets

Remarks

If the provider is initialized, this method returns the values of properties in the DBPROPSET_DATASOURCE, DBPROPSET_DATASOURCEINFO, DBPROPSET_DBINIT property groups that are currently set on the data source object. If the provider is not initialized, it returns DBPROPSET_DBINIT group properties only.

IDBPropertiesImpl Overview | Class Members

See Also

IDBPropertiesImpl::GetPropertyInfo, IDBPropertiesImpl::SetProperties


IDBPropertiesImpl::GetPropertyInfo

HRESULT GetPropertyInfo( ULONG cPropertySets, const DBPROPIDSET rgPropertySets[], ULONG *pcPropertyInfoSets, DBPROPINFOSET **prgPropertyInfoSets, OLECHAR **ppDescBuffer );

See IDBProperties::GetPropertyInfo in the OLE DB Programmer's Reference.

Some parameters correspond to OLE DB Programmer’s Reference parameters of different names, which are described in IDBProperties::GetPropertyInfo:

OLE DB Template parameters | OLE DB Programmer’s Reference parameters
cPropertySets | cPropertyIDSets
rgPropertySets | rgPropertyIDSets

Remarks

Returns property information supported by the data source. Uses IDBInitializeImpl::m_pCUtlPropInfo to implement this functionality.

IDBPropertiesImpl Overview | Class Members

See Also

IDBPropertiesImpl::GetProperties, IDBPropertiesImpl::SetProperties


IDBPropertiesImpl::SetProperties

HRESULT SetProperties( ULONG cPropertySets, DBPROPSET rgPropertySets[] );

See IDBProperties::SetProperties in the OLE DB Programmer’s Reference.

Remarks

If the provider is initialized, this method sets the values of properties in the DBPROPSET_DATASOURCE, DBPROPSET_DATASOURCEINFO, DBPROPSET_DBINIT property groups for the data source object. If the provider is not initialized, it sets DBPROPSET_DBINIT group properties only.

IDBPropertiesImpl Overview | Class Members

See Also

IDBPropertiesImpl::GetProperties, IDBPropertiesImpl::GetPropertyInfo


IDBSchemaRowsetImpl

template <class SessionClass>
class IDBSchemaRowsetImpl: public IDBSchemaRowset

SessionClass

The class IDBSchemaRowsetImpl is inherited by. Typically this class will be the user’s session class.

Implementation of the IDBSchemaRowset interface and the templatized creator function CreateSchemaRowset.

IDBSchemaRowsetImpl provides implementation for schema rowsets. OLE DB uses schema rowsets to return data about the data in a provider. (Such data is often called "meta-data.") By default, a provider must always support DBSCHEMA_TABLES, DBSCHEMA_COLUMNS, and DBSCHEMA_PROVIDER_TYPES, as described in IDBSchemaRowset in the OLE DB Programmer's Reference. Schema rowsets are designated in a schema map. For more information about the schema map entries, see SCHEMA_ENTRY. For more information about schema rowsets, see Schema Rowsets in the OLE DB Programmer's Reference.

The OLE DB Provider Wizard, in the ATL Object Wizard, automatically generates code for the schema rowsets in your project. By default, it supports the DBSCHEMA_TABLES, DBSCHEMA_COLUMNS, and DBSCHEMA_PROVIDER_TYPES schema rowsets.

When you create a consumer using the ATL Object Wizard, the wizard uses schema rowsets bind the correct data to a provider. If you do not implement your schema rowsets to provide the correct meta-data, the wizard will not bind the correct data.

#include <atldb.h>

IDBSchemaRowsetImpl Class Members

See Also

Schema Rowset Classes and Typedef Classes


IDBSchemaRowsetImpl Class Members

Methods

CreateSchemaRowset | Implements a COM object creator function for the object specified by the template parameter.
SetRestrictions | The default implementation of this function sets the array elements to 0.
GetSchemas | Returns a list of schema rowsets accessible by IDBSchemaRowsetImpl::GetRowset.
GetRowset | Returns a schema rowset.

IDBSchemaRowsetImpl Overview

See Also

Schema Rowset Classes and Typedef Classes


IDBSchemaRowsetImpl::CreateSchemaRowset

template < class SchemaRowsetClass >
HRESULT CreateSchemaRowset( IUnknown *pUnkOuter, ULONG cRestrictions, const VARIANT rgRestrictions[], REFIID riid, ULONG cPropertySets, DBPROPSET rgPropertySets[], IUnknown** ppRowset, SchemaRowsetClass*& pSchemaRowset );

Return Value

A standard HRESULT value.

Parameters

pUnkOuter

[in] An outer IUnknown when aggregating, otherwise NULL.

cRestrictions

[in] The count of restrictions applied to the schema rowset.

rgRestrictions

[in] An array of cRestrictions VARIANTs to be applied to the rowset.

riid

[in] The interface to QueryInterface for on the output IUnknown.

cPropertySets

[in] The number of property sets being set.

rgPropertySets

[in] An array of cPropertySets DBPROPSETS that specify the properties being set. For information about the structure DBPROPSETS, see Chapter 11 in the OLE DB Programmer's Reference.

ppRowset

[out] The outgoing IUnknown requested by riid. This IUnknown is an interface on the schema rowset object.

pSchemaRowset

[out] A pointer to an instance of the schema rowset class. Typically this parameter is not used, but it can be used if you must perform more work on the schema rowset before handing it out to a COM object. The lifetime of pSchemaRowset is bound by ppRowset.

Remarks

This function implements a COM object creator function for the object specified by the template parameter. In effect this function implements a generic creator for all types of schema rowsets. Typically, the user does not call this function. It is called by the implementation of the schema map.

IDBSchemaRowsetImpl Overview | IDBSchemaRowsetImpl Class Members

See Also

SCHEMA_ENTRY, Schema Rowset Classes and Typedef Classes


IDBSchemaRowsetImpl::GetRowset

HRESULT GetRowset( IUnknown *pUnkOuter, REFGUID rguidSchema, ULONG cRestrictions, const VARIANT rgRestrictions[], REFIID riid, ULONG cPropertySets, DBPROPSET rgPropertySets[], IUnknown **ppRowset );

See IDBSchemaRowset::GetRowset in the Platform SDK.

Parameters

pUnkOuter

[in] An outer IUnknown when aggregating; otherwise NULL.

rguidSchema

[in] A reference to the requested schema GUID.

cRestrictions

[in] A count of restrictions to be applied to the rowset.

rgRestrictions

[in] An array of cRestrictions VARIANTs that represent the restrictions.

riid

[in] The IID to request of the newly created schema rowset.

cPropertySets

[in] The count of Property Sets to set on the newly created schema rowset.

rgPropertySets

[in/out] An array of cPropertySets to set on the newly created schema rowset.

ppRowset

[out] A pointer to the requested interface on the newly created schema rowset.

Remarks

This method requires the user to have a schema map in the session class. Using the schema map information, it creates a given rowset object if the rguidSchema parameter is equal to one of the map entries GUIDs. See SCHEMA_ENTRY for a description of the map entry.

IDBSchemaRowsetImpl Overview | IDBSchemaRowsetImpl Class Members

See Also

IDBSchemaRowsetImpl::GetSchemas, Schema Rowset Classes and Typedef Classes


IDBSchemaRowsetImpl::GetSchemas

HRESULT GetSchemas( ULONG * pcSchemas, GUID ** prgSchemas, ULONG** prgRest );

This method returns an array of all of the schema rowsets supported by the provider. See IDBSchemaRowset::GetSchemas in the Platform SDK.

Parameters

pcSchemas

[out] A pointer to a ULONG that is filled in with the number of schemas.

prgSchemas

[out] A pointer to an array of GUIDs that is filled with a pointer to an array of schema rowset GUIDs.

prgRest

[out] A pointer to an array of ULONGs that is to be filled with the restriction array.

Remarks

The implementation of this function requires the user to have a schema map in their session class. Using the schema map information, it then responds with the array of GUIDs for the schemas in the map. This represents the schemas supported by the provider.

IDBSchemaRowsetImpl Overview | IDBSchemaRowsetImpl Class Members

See Also

IDBSchemaRowsetImpl::GetRowset, IDBSchemaRowset::GetRowset, Schema Rowset Classes and Typedef Classes


IDBSchemaRowsetImpl::SetRestrictions

void SetRestrictions( REFIID rguidSchema, ULONG cRestrictions, ULONG* rgRestrictions );

Parameters

rguidSchema

[in] The schema rowset for which to set restrictions.

cRestrictions

[in] The number of restrictions to be set.

rgRestrictions

[in] An array of cRestrictions ULONGs to be set.

Remarks

Called by GetSchemas through an upcasted pointer. Override the default in your Session class to set restrictions other than the default. The default implementation of this method sets the rgRestrictions array elements to 0.

IDBSchemaRowsetImpl Overview | IDBSchemaRowsetImpl Class Members

See Also

Schema Rowset Classes and Typedef Classes


IGetDataSourceImpl

template <class T>
class ATL_NO_VTABLE IGetDataSourceImpl : public IGetDataSource

Parameters

T

Your class, derived from IGetDataSourceImpl.

Remarks

This is a mandatory interface on the session for obtaining an interface pointer to the data source object. IGetDataSourceImpl provides an implementation of the IGetDataSource object.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IGetDataSourceImpl Class Members

Interface Methods

GetDataSource Returns an interface pointer on the data source object that created the session.

IGetDataSourceImpl Overview


IGetDataSourceImpl::GetDataSource

HRESULT GetDataSource( REFIID riid, IUnknown **ppDataSource );

See IGetDataSource::GetDataSource in the OLE DB Programmer's Reference.

Remarks

Returns an interface pointer on the data source object that created the session. Useful if you need to acess properties in the data source object.


IOpenRowsetImpl

template <class SessionClass>
class ATL_NO_VTABLE IOpenRowsetImpl : public IOpenRowset

Parameters

SessionClass

Your class, derived from IOpenRowsetImpl.

Remarks

The IOpenRowset interface is mandatory for a session object. This class provides implementation for this interface. It opens and returns a rowset that includes all rows from a single base table or index.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IOpenRowsetImpl Class Members

Methods

CreateRowset | Creates a rowset object. Not called directly by user.
OpenRowset | Opens and returns a rowset that includes all rows from a single base table or index. (Not in ATLDB.H)

IOpenRowsetImpl Overview


IOpenRowsetImpl::CreateRowset

template <class RowsetClass>
HRESULT CreateRowset( IUnknown* pUnkOuter, DBID *pTableID, DBID *pIndexID, REFIID riid, ULONG cPropertySets, DBPROPSET rgPropertySets[], IUnknown** ppRowset, RowsetClass*& pRowsetObj )

Parameters

RowsetClass

A template class member representing the user's rowset class. Usually generated by the wizard.

pRowsetObj

[out] A pointer to a rowset object. Typically this parameter is not used, but it can be used if you must perform more work on the rowset before passing it to a COM object. The lifetime of pRowsetObj is bound by ppRowset.

For other parameters, see IOpenRowset::OpenRowset in the OLE DB Programmer’s Reference.

Remarks

See IOpenRowset::OpenRowset in the OLE DB Programmer’s Reference.


IOpenRowsetImpl::OpenRowset

HRESULT OpenRowset( IUnknown *pUnkOuter, DBID *pTableID, DBID *pIndexID, REFIID riid, ULONG cPropertySets, DBPROPSET rgPropertySets[], IUnknown **ppRowset );

See IOpenRowset::OpenRowset in the OLE DB Programmer’s Reference.

Remarks

Opens and returns a rowset that includes all rows from a single base table or index. This method is not found in ATLDB.H. It is created by the ATL Object Wizard when you create a provider.


IRowsetImpl

template < class T, class RowClass = CSimpleRow, class MapClass = CSimpleMap.<RowClass::keyType, RowClass>>
class ATL_NO_VTABLE IRowsetInfoImpl : public IRowsetInfo, public CUtlProps<T>

Parameters

T

Your class, derived from IRowsetImpl.

RowClass

Storage unit for the HROW.

MapClass

Storage unit for all row handles held by the provider.

Remarks

IRowset is the base rowset interface. IRowsetImpl provides an implementation of the IRowset interface.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IRowsetImpl Class Members

Methods

IRowsetImpl | The constructor. Not called directly by user.
RefRows | Called by AddRefRows and ReleaseRows. Not called directly by user.
CreateRow | Called by GetNextRows to allocate a new HROW. Not called directly by user.
AddRefRows | Adds a reference count to an existing row handle.
GetData | Retrieves data from the rowset's copy of the row.
GetNextRows | Fetches rows sequentially, remembering the previous position.
ReleaseRows | Releases rows.
RestartPosition | Repositions the next fetch position to its initial position; that is, its position when the rowset was first created.

Data Members

m_bReset | Indicates whether a provider has reset its cursor position. This has special meaning when scrolling backwards or fetching backwards in GetNextRows.
m_bCanFetchBack | Indicates whether a provider supports backward fetching.
m_bCanScrollBack | Indicates whether a provider can have its cursor scroll backwards.
m_iRowset | An index to the rowset, representing the cursor.
m_rgRowHandles | A list of row handles.

IRowsetImpl Overview


IRowsetImpl::AddRefRows

STDMETHOD( AddRefRows )( ULONG cRows, const HROW rghRows[], ULONG rgRefCounts[], DBROWSTATUS rgRowStatus[] );

See IRowset::AddRefRows in the OLE DB Programmer's Reference.

Remarks

Adds a reference count to an existing row handle.

IRowsetImpl Overview | Class Members

See Also

IRowsetImpl::RefRows, IRowsetImpl::GetNextRows, IRowsetImpl::ReleaseRows


IRowsetImpl::CreateRow

HRESULT CreateRow(LONG lRowsOffset, ULONG& cRowsObtained, HROW* rgRows)

Parameters

lRowsOffset

Cursor position of the row being created.

cRowsObtained

A reference passed back to the user indicating the number of rows created.

RgRows

An array of HROWs returned to the caller with the newly created row handles.

Remarks

A helper method called by GetNextRows to allocate a new HROW. If the row exists, it calls AddRefRows and returns. Otherwise, it allocates a new instance of the the RowClass template variable and adds it to m_rgRowHandles.


IRowsetImpl::GetData

STDMETHOD( GetData )( HROW hRow, HACCESSOR hAccessor, void *pDstData );

See IRowset::GetData in the OLE DB Programmer's Reference.

Parameters

Some parameters correspond to OLE DB Programmer's Reference parameters of different names, which are described in IRowset::GetData:

OLE DB Template parameters | OLE DB Programmer's Reference parameters
pDstData | pData

Remarks

Retrieves data from the rowset's copy of the row. Also handles data conversion using the OLE DB data conversion DLL.


IRowsetImpl::GetNextRows

STDMETHOD( GetNextRows )( HCHAPTER hReserved, LONG lRowsOffset, LONG cRows, ULONG *pcRowsObtained, HROW **prghRows );

See IRowset::GetNextRows in the OLE DB Programmer's Reference.

Remarks

Fetches rows sequentially, remembering the previous position.

IRowsetImpl Overview | Class Members

See Also

IRowsetImpl::AddRefRows, IRowsetImpl::ReleaseRows


IRowsetImpl::IRowsetImpl

IRowsetImpl( );

Remarks

The constructor. You usually don't need to call this directly.


IRowsetImpl::RefRows

HRESULT RefRows( ULONG cRows, const HROW rghRows[], ULONG rgRefCounts[], DBROWSTATUS rgRowStatus[], BOOL bAdd );

Return Value

A standard HRESULT value.

See IRowset::AddRefRows in the OLE DB Programmer's Reference.

Remarks

Called by AddRefRows and ReleaseRows to either increment or release a reference count to an existing row handle.

IRowsetImpl Overview | Class Members

See Also

CSimpleRow


IRowsetImpl::ReleaseRows

STDMETHOD( ReleaseRows )( ULONG cRows, const HROW rghRows[], DBROWOPTIONS rgRowOptions[], ULONG rgRefCounts[], DBROWSTATUS rgRowStatus[] );

See IRowset::ReleaseRows in the OLE DB Programmer's Reference.

Remarks

Releases rows.

IRowsetImpl Overview | Class Members

See Also

IRowsetImpl::AddRefRows, IRowsetImpl::RefRows


IRowsetImpl::RestartPosition

STDMETHOD( RestartPosition )( HCHAPTER hReserved );

See IRowset::RestartPosition in the OLE DB Programmer's Reference.

Remarks

Repositions the next fetch position to its initial position; that is, its position when the rowset was first created. The rowset position is undefined until GetNextRow is called. You can move backwards in a rowet by calling RestartPosition and then fetching or scrolling backwards.


IRowsetImpl::m_bCanFetchBack

unsigned m_bCanFetchBack:1;

Remarks

Indicates whether a provider supports backward fetching. Linked to the DBPROP_CANFETCHBACKWARDS property in the DBPROPSET_ROWSET group. The provider must support DBPROP_CANFETCHBACKWARDS for m_bCanFetchBackwards to be true.

IRowsetImpl Overview | Class Members

See Also

IRowsetImpl::m_bCanScrollBack


IRowsetImpl::m_bCanScrollBack

unsigned m_bCanScrollBack:1;

Remarks

Indicates whether a provider can have its cursor scroll backwards. Linked to the DBPROP_CANSCROLLBACKWARDS property in the DBPROPSET_ROWSET group. The provider must support DBPROP_CANSCROLLBACKWARDS for m_bCanFetchBackwards to be true.

IRowsetImpl Overview | Class Members

See Also

IRowsetImpl::m_bCanFetchBack


IRowsetImpl::m_bReset

unsigned m_bReset:1;

Remarks

A bit flag used to determine if the cursor position is defined on the rowset. If the consumer calls GetNextRows with a negative lOffset or cRows and m_bReset is true, GetNextRows moves to the end of the rowset. If m_bReset is false, the consumer receives an error code, in conformance with the OLE DB specification. The m_bReset flag gets set to true when the rowset is first created and when the consumer calls IRowsetImpl::RestartPosition. It gets set to false when you call GetNextRows.


IRowsetImpl::m_iRowset

DWORD m_iRowset;

Remarks

An index to the rowset, representing the cursor.


IRowsetImpl::m_rgRowHandles

MapClass m_rgRowHandles;

Remarks

A map of row handles currently contained by the provider in response to GetNextRows. Row handles are removed by calling ReleaseRows. See IRowsetImpl overview for the definition of MapClass.


IRowsetInfoImpl

template <class T, class PropClass = T>
class ATL_NO_VTABLE IRowsetInfoImpl : public IRowsetInfo, public CUtlProps<T>

Parameters

T

Your class, derived from IRowsetInfoImpl.

PropClass

A user-defineable property class that defaults to T.

Remarks

A mandatory interface on rowsets. IRowsetInfoImpl provides an implementation for the IRowsetInfo interface. This class implements the rowset properties by using the property set map defined in your command class. Although the rowset class appears to be using the command class' property sets, the rowset is supplied with its own copy of the run-time properties, when it is created by a command or session object.

#include <altdb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


IRowsetInfoImpl Class Members

Interface Methods

GetProperties | Returns the current settings of all properties supported by the rowset.
GetReferencedRowset | Returns an interface pointer to the rowset to which a bookmark applies.
GetSpecification | Returns an interface pointer on the object (command or session) that created this rowset.

IRowsetInfoImpl Overview


IRowsetInfoImpl::GetProperties

HRESULT GetProperties( const ULONG cPropertyIDSets, const DBPROPIDSET rgPropertyIDSets[], ULONG *pcPropertySets, DBPROPSET **prgPropertySets );

See IRowsetInfo::GetProperties in the OLE DB Programmer's Reference.

Remarks

Returns the current settings for properties in the DBPROPSET_ROWSET group..

IRowsetInfoImpl Overview | Class Members

See Also

IRowsetInfoImpl::GetReferencedRowset, IRowsetInfoImpl::GetSpecification


IRowsetInfoImpl::GetReferencedRowset

GetReferencedRowset( ULONG iOrdinal, REFIID riid, IUnknown **ppReferencedRowset );

See IRowsetInfo::GetReferencedRowset in the OLE DB Programmer's Reference. The iOrdinal parameter must be a bookmark column.

Remarks

Returns an interface pointer to the rowset to which a bookmark applies.

IRowsetInfoImpl Overview | Class Members

See Also

IRowsetInfoImpl::GetSpecification, IRowsetInfoImpl::GetProperties


IRowsetInfoImpl::GetSpecification

GetSpecification( REFIID riid, IUnknown **ppSpecification );

See IRowsetInfo::GetSpecification in the OLE DB Programmer's Reference.

Remarks

Returns an interface pointer on the object (command or session) that created this rowset. Use this method with IGetDataSourceImpl to retrieve properties from the data source object.

IRowsetInfoImpl Overview | Class Members

See Also

IRowsetInfoImpl::GetReferencedRowset, IRowsetInfoImpl::GetProperties


ISessionPropertiesImpl

template <class T, class PropClass = T>
class ATL_NO_VTABLE ISessionPropertiesImpl : public ISessionProperties, public CUtlProps<T>

Parameters

T

Your class, derived from ISessionPropertiesImpl.

PropClass

A user-defineable property class that defaults to T.

Remarks

A mandatory interface on sessions. ISessionPropertiesImpl provides an implementation of the ISessionProperties interface. This class implements session properties by calling a static function defined by the property set map. The property set map should be specified in your session class.

#include <atldb.h>

Class Members

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture


ISessionPropertiesImpl Class Members

Interface Methods

GetProperties | Returns the list of properties in the Session property group that are currently set on the session.
SetProperties | Sets properties in the Session property group.

ISessionPropertiesImpl Overview


ISessionPropertiesImpl::GetProperties

HRESULT GetProperties( ULONG cPropertyIDSets, const DBPROPIDSET rgPropertyIDSets[], ULONG *pcPropertySets, DBPROPSET **prgPropertySets );

See ISessionProperties::GetProperties in the OLE DB Programmer's Reference.

Remarks

Returns the list of properties in the DBPROPSET_SESSION property group that are currently set on the session.

ISessionPropertiesImpl Overview | Class Members

See Also

ISessionPropertiesImpl::SetProperties


ISessionPropertiesImpl::SetProperties

HRESULT SetProperties( ULONG cPropertySets, DBPROPSET rgPropertySets[] );

See ISessionProperties::SetProperties in the OLE DB Programmer's Reference.

Remarks

Sets properties in the DBPROPSET_SESSION property group.

ISessionPropertiesImpl Overview | Class Members

See Also

ISessionPropertiesImpl::GetProperties


Macros for OLE DB Provider Templates

The OLE DB Templates Provider macros offer functionality in the following categories:

Property Set Map Macros

BEGIN_PROPERTY_SET | Marks the beginning of a property set.
BEGIN_PROPERTY_SET_EX | Marks the beginning of a property set.
BEGIN_PROPSET_MAP | Marks the beginning of a property set that can be hidden or defined outside the scope of the provider.
CHAIN_PROPERTY_SET | Chains property groups together.
END_PROPERTY_SET | Marks the end of a property set.
END_PROPSET_MAP | Marks the end of a property set map.
PROPERTY_INFO_ENTRY | Sets a specific property in a property set to a default value.
PROPERTY_INFO_ENTRY_EX | Sets a specific property in a property set to a value supplied by you. Also enables you to set flags and options.
PROPERTY_INFO_ENTRY_VALUE | Sets a specific property in a property set to a value supplied by you.

Column Map Macros

BEGIN_PROVIDER_COLUMN_MAP | Marks the beginning of the provider column map entries.
END_PROVIDER_COLUMN_MAP | Marks the end of the provider column map entries.
PROVIDER_COLUMN_ENTRY | Represents a specific column supported by the provider.
PROVIDER_COLUMN_ENTRY_FIXED | Represents a specific column supported by the provider. Allows you to specify the column data type.
PROVIDER_COLUMN_ENTRY_LENGTH | Represents a specific column supported by the provider. Allows you to specify the column size.
PROVIDER_COLUMN_ENTRY_STR | Represents a specific column supported by the provider. It assumes the column type is a string.
PROVIDER_COLUMN_ENTRY_WSTR | Represents a specific column supported by the provider. It assumes the column type is a Unicode character string.

Schema Rowset Macros

BEGIN_SCHEMA_MAP | Marks the beginning of a SCHEMA Map.
SCHEMA_ENTRY | Marks the beginning of the property set map.
END_SCHEMA_MAP | Marks the end of a SCHEMA Map.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


BEGIN_PROPERTY_SET

BEGIN_PROPERTY_SET( pguid )

Parameters

pguid

[in] The property GUID.

Remarks

Marks the beginning of a property set in a property set map.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROPSET_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


BEGIN_PROPERTY_SET_EX

BEGIN_PROPERTY_SET(pguid, flags)

Parameters

pguid

[in] The property GUID.

flags

[in] UPROPSET_HIDDEN for any property sets you do not wish to expose, or UPROPSET_PASSTHROUGH for a provider exposing properties defined outside the scope of the provider.

Remarks

Marks the beginning of a property set in a property set map.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROPSET_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


BEGIN_PROPSET_MAP

BEGIN_PROPSET_MAP( Class )

Parameters

Class

[in] The class in which this property set is specified. A property set can be specified in the following OLE DB objects:

  • Data Source Objects

  • Sessions

  • Commands

num

[in] The number of properties in this property set.

Remarks

Marks the beginning of the property set map entries.

Macros for OLE DB Provider Templates

Example

Here is a sample property set map:

BEGIN_PROPSET_MAP(CDataSource)
   BEGIN_PROPERTY_SET(0, &DBPROPSET_DATASOURCEINFO, 0, InitSrcInfoSupported)
      PROPERTY_INFO_ENTRY(ACTIVESESSIONS, VT_I4, DBPROPFLAGS_DATASOURCEINFO | DBPROPFLAGS_READ, 0)
      PROPERTY_INFO_ENTRY(ASYNCTXNABORT,   VT_BOOL, DBPROPFLAGS_DATASOURCEINFO | DBPROPFLAGS_READ, VARIANT_FALSE)
   END_PROPERTY_SET(0)
   BEGIN_PROPERTY_SET(1, &DBPROPSET_DBINIT, 0, InitDBInitSupported)
      PROPERTY_INFO_ENTRY(AUTH_PASSWORD,VT_BSTR,   DBPROPFLAGS_DBINIT | DBPROPFLAGS_READ | DBPROPFLAGS_WRITE, OLESTR("JanPass"))
      PROPERTY_INFO_ENTRY(AUTH_PERSIST_SENSITIVE_AUTHINFO, VT_BOOL, DBPROPFLAGS_DBINIT | DBPROPFLAGS_READ | DBPROPFLAGS_WRITE, VARIANT_FALSE)
   END_PROPERTY_SET(1)
END_PROPSET_MAP()

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


BEGIN_PROVIDER_COLUMN_MAP

BEGIN_PROVIDER_COLUMN_MAP( theClass )

Parameters

theClass

[in] The name of the class this map belongs to.

Remarks

Marks the beginning of the provider column map entries.

Macros for OLE DB Provider Templates

Example

Here is a sample provider column map:

BEGIN_PROVIDER_COLUMN_MAP(CWindowsFile)
   PROVIDER_COLUMN_ENTRY("FileAttributes", 1, dwFileAttributes)
   PROVIDER_COLUMN_ENTRY("FileSizeHigh", 2, nFileSizeHigh)
   PROVIDER_COLUMN_ENTRY("FileSizeLow", 3, nFileSizeLow)
   PROVIDER_COLUMN_ENTRY("FileName", 4, cFileName)
   PROVIDER_COLUMN_ENTRY("AltFileName", 5, cAlternateFileName)
END_PROVIDER_COLUMN_MAP()

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


BEGIN_SCHEMA_MAP

BEGIN_SCHEMA_MAP( SchemaClass );

Parameters

SchemaClass

The class that contains the MAP. Typically this will be the Session class.

Remarks

Denotes the beginning of a SCHEMA Map.

See IDBSchemaRowset in the Platform SDK for more information about schema rowsets.

See Also

SCHEMA_ENTRY, END_SCHEMA_MAP, IDBSchemaRowsetImpl


CHAIN_PROPERTY_SET

CHAIN_PROPERTY_SET( ChainClass )

Parameters

ChainClass

[in] The name of the class to chain properties for. This is a class generated by the ATL Object Wizard that already contains a map (such as a session, command, or data source object class).

Remarks

This macro chains property groups together. You can chain a property set from another class to your own class, then access the properties directly from your class.

CAUTION Use this macro sparingly. Improper use can cause a consumer to fail the OLE DB conformance tests.


END_PROPERTY_SET

END_PROPERTY_SET( guid )

Parameters

guid

[in] A group GUID.

Remarks

Marks the end of a property set.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROPSET_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


END_PROPSET_MAP

END_PROPSET_MAP( )

Remarks

Marks the end of property set map entries.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROPSET_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


END_PROVIDER_COLUMN_MAP

END_PROVIDER_COLUMN_MAP( )

Remarks

Marks the end of the provider column map entries.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROVIDER_COLUMN_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


END_SCHEMA_MAP

END_SCHEMA_MAP( );

Remarks

Denotes the end of the SCHEMA map.

Macros for OLE DB Provider Templates

See Also

BEGIN_SCHEMA_MAP, SCHEMA_ENTRY, IDBSchemaRowsetImpl


PROVIDER_COLUMN_ENTRY

PROVIDER_COLUMN_ENTRY_GN ( name, ordinal, flags, colSize, dbtype, precision, scale, guid )

Parameters

name

[in] The column name.

ordinal

[in] The column number. Unless the column is a Bookmark column, the column number must not be 0.

flags

[in] Specifies how data is returned. See the dwFlags description in DBBINDING Structures.

colSize

[in] The column size.

dbtype

[in] Indicates the data type of the value. See the wType description in DBBINDING Structures.

precision

[in] Indicates the precision to use when getting data if dbType is DBTYPE_NUMERIC or DBTYPE_DECIMAL. See the bPrecision description in DBBINDING Structures.

scale

[in] Indicates the scale to use when getting data if dbType is DBTYPE_NUMERIC or DBTYPE_DECIMAL. See the bScale description in DBBINDING Structures.

member

[in] The member variable in dataClass corresponding to the column.

Remarks

Represents a specific column supported by the provider.

Macros for OLE DB Provider Templates

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


PROVIDER_COLUMN_ENTRY_FIXED

PROVIDER_COLUMN_ENTRY_FIXED( name, ordinal, dbtype, member )

Parameters

name

[in] The column name.

ordinal

[in] The column number. Unless the column is a Bookmark column, the column number must not be 0.

dbtype

[in] The data type in DBTYPE.

member

[in] The member variable in dataClass that stores the data.

Remarks

Represents a specific column supported by the provider. Allows you to specify the column data type.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROVIDER_COLUMN_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


PROVIDER_COLUMN_ENTRY_LENGTH

PROVIDER_COLUMN_ENTRY_LENGTH( name, ordinal, size, member )

Parameters

name

[in] The column name.

ordinal

[in] The column number. Unless the column is a Bookmark column, the column number must not be 0.

size

[in] The column size in bytes.

member

[in] The member variable in dataClass that stores the column data.

Remarks

Represents a specific column supported by the provider. Allows you to specify the column size.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROVIDER_COLUMN_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


PROVIDER_COLUMN_ENTRY_STR

PROVIDER_COLUMN_ENTRY_STR( name, ordinal, member )

Parameters

name

[in] The column name.

ordinal

[in] The column number. Unless the column is a Bookmark column, the column number must not be 0.

member

[in] The member variable in the data class that stores the data.

Remarks

Represents a specific column supported by the provider. Use this macro when the column data is assumed to be DBTYPE_STR.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROVIDER_COLUMN_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


PROVIDER_COLUMN_ENTRY_WSTR

PROVIDER_COLUMN_ENTRY_WSTR( name, ordinal, member )

Parameters

name

[in] The column name.

ordinal

[in] The column number. Unless the column is a Bookmark column, the column number must not be 0.

member

[in] The member variable in the data class that stores the data.

Remarks

Represents a specific column supported by the provider. Use this macro when the column data is a null terminated Unicode character string, DBTYPE_WSTR.

Macros for OLE DB Provider Templates

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


PROPERTY_INFO_ENTRY

PROPERTY_INFO_ENTRY( dwPropID )

Parameters

dwPropID

[in] A DBPROPID value that can be used in conjunction with the property set GUID to identify a property.

Remarks

Represents a specific property in a property set. This macro sets the property value of type DWORD to a default value defined in ATLDB.H. To set the property to a value of your choosing, use PROPERTY_INFO_ENTRY_VALUE. To set the VARTYPE and DBPROPFLAGS for the property at the same time, use PROPERTY_INFO_ENTRY_EX.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROPSET_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


PROPERTY_INFO_ENTRY_EX

PROPERTY_INFO_ENTRY( dwPropID, vt, dwFlags, value, options)

Parameters

dwPropID

[in] A DBPROPID value that can be used in conjunction with the property set GUID to identify a property.

vt

[in] The VARTYPE of this property entry.

dwFlags

[in] A DBPROPFLAGS value describing this property entry.

value

[in] The property value of type DWORD.

Options

Either DBPROPOPTIONS_REQUIRED or DBPROPOPTIONS_SETIFCHEAP. Normally, a provider does not need to set Options since it is set by the consumer.

Remarks

Represents a specific property in a property set. With this macro, you can directly specify the property value of type DWORD as well as options and flags. To merely set a property to a default value defined in ATLDB.H, use for the property at the same time, use PROPERTY_INFO_ENTRY. To set a property to a value of your choice, without setting options or flags on it, use PROPERTY_INFO_ENTRY_VALUE

Macros for OLE DB Provider Templates

Example

See BEGIN_PROPSET_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


PROPERTY_INFO_ENTRY_VALUE

PROPERTY_INFO_ENTRY( dwPropID, value )

Parameters

dwPropID

[in] A DBPROPID value that can be used in conjunction with the property set GUID to identify a property.

value

[in] The property value of type DWORD.

Remarks

Represents a specific property in a property set. With this macro, you can directly specify the property value of type DWORD. To sets the property to default value defined in ATLDB.H, use PROPERTY_INFO_ENTRY. To set the value, flags, and options for the property, use PROPERTY_INFO_ENTRY_EX.

Macros for OLE DB Provider Templates

Example

See BEGIN_PROPSET_MAP.

See Also

Using the OLE DB Provider Templates, The OLE DB Provider Architecture, Creating an OLE DB Provider


SCHEMA_ENTRY

SCHEMA_ENTRY( guid, rowsetClass );

Parameters

guid

A schema rowset GUID. See IDBSchemaRowset in the OLE DB Programmer's Reference for a list of schema rowsets and their GUIDs.

rowsetClass

The class that will be created to represent the schema rowset.

Remarks

This macro associates a GUID with a class. IDBSchemaRowsetImpl can then query the map for a list of GUIDs, or it can create a rowset if it is given a GUID. The schema rowset IDBSchemaRowsetImpl creates is similar to a standard CRowsetImpl-derived class, except it must provide an Execute method that has the following signature:

HRESULT Execute (LONG* pcRowsAffected, ULONG cRestrictions , const VARIANT* rgRestrictions)

This Execute function populates the rowset's data. The ATL Object Wizard creates three initial schema rowsets in the project: one for each of the three mandatory OLE DB schemas (DBSCHEMA_TABLES, DBSCHEMA_COLUMNS, and DBSCHEMA_PROVIDER_TYPES, as described in IDBSchemaRowset in the OLE DB Programmer's Reference). The wizard also adds three corresponding entries in the schema map. See Creating an OLE DB Template Provider for more information about using the wizard to create a provider.

Macros for OLE DB Provider Templates

See Also

BEGIN_SCHEMA_MAP, END_SCHEMA_MAP


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.


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.