About Win32++

This documentation describes the features of Win32++, version 7.3. To download a copy of Win32++ proceed to the project's hosting at SourceForge here.

Win32++ is a C++ library used to build windows applications. Win32++ is a free alternative to MFC. It has the added advantage of being able to run on a wide range of free compilers, including Visual Studio Express, and the MinGW compiler provided with CodeBlocks and Dev-C++.

Win32++ supports all Windows operating systems, from Windows 95 through to Windows 7 and Windows Server 2008. It also supports the Windows CE operating system which runs on runs on the various Pocket PCs, Smartphones, as well as industrial devices and embedded systems.


Overview

Win32++ Overview

Introduction

Win32++ consists of a C++ library used to create window applications. It is a free alternative to MFC, and can be used on a larger range of compilers including those from Borland, Microsoft and MinGW. The library can be used to create a variety of programs, including simple windows, dialogs, property sheets, as well as frame and MDI frame applications. Information on how to use these classes to build your own Win32 applications is available in the Tutorial section.

Frame based applications usually have an outer frame window which looks after the menu, toolbar and status bar, and a separate window (sometimes referred to as a view window) over the client area. Many of the windows applications you are familiar with are likely to be frame based applications. You can use this library to produce not just simple windows and dialogs, but also professional looking frame based applications, complete with a menu, toolbar, status bar, and tooltips.

About the Downloads

To download a copy of Win32++ proceed to the Download section of the projects listing at SourceForge. The Downloads section provides a number of sample applications which use Win32++, including:

  • Browser
  • CustomControl
  • Dialog
  • DialogBars
  • DialogDemo
  • DialogResizing
  • DialogTab
  • DirectX
  • DLL
  • Dock
  • DockContainer
  • DockTabbedMDI
  • Explorer
  • Fast GDI
  • Form Demo
  • Frame
  • GDIPlus
  • MDI Frame
  • MDI Frame Demo
  • MDI Frame Splitter
  • Networking
  • Notepad
  • Picture
  • PropertySheet
  • RibbonFrame
  • RibbonSimple
  • Scribble
  • Simple Window
  • Splitter
  • Tab Demo
  • TaskDialog
  • Themes
  • Threads Demo
  • Tray Demo

Features

Win32++ provides a library for developing applications, using the Windows API directly. It supports all MS operating systems which run 32bit and 64bit Windows, from Windows 95 through to Windows 7 and Server 2008. Win32++ is designed to produce programs with a similar look and feel to those created using MFC. This library can develop applications based on simple windows, dialogs, frames and MDI frames. The frames produced by Win32++ have the following features:

  • Rebar control
  • MenuBar (a menu housed inside the rebar control).
  • ToolBar
  • Status bar
  • Tool tips

Win32++ also brings an object oriented approach to programming directly with the Windows API. Each window created is a C++ class object capable of having its own window procedure for routing messages.

A summary of the features of Win32++ are as follows:

  • Support for both Win32 and Windows CE operating systems. It supports all Win32 operating systems, from Windows 95 through to Windows 7. The Windows CE operating systems supported range from WCE400 (Windows mobile 2003) to WCE600 (Windows mobile 6).
  • Supports a wide range of C++ compilers, including those from Borland and Microsoft, as well as the GNU compiler used in Dev-C++.
  • Supports applications based on simple windows, dialogs, forms, property sheets, SDI frames and MDI frames. The SDI and MDI frames include rebars, status bars, menu bars, toolbars and tooltips. The frames use a separate window, often referred to as a view window, for the frame's client area.
  • Support for docking, tabbed containers and TabbedMDIs.
  • Message routing. The messages for each window are routed to the WndProc function of the associated CWnd object. All messages are passed to the WndProc function, including all those associated with window creation.
  • Automatic Subclassing. When creating a window using a predefined class type, Win32++ automatically subclasses the window so that messages can be routed via WndProc. Predefined class types include all the common controls, such as the toolbar, status bar, tree-view etc.
  • Existing windows can be attached to CWnd objects. This is particularly useful for controls in dialogs. These can be attached to to CWnd objects with the AttachDlgItem function.
  • Notification reflection. When a notification (WM_NOTIFY message) is received from a child window, OnNotifyReflect is called for the CWnd object associated with the child window.
  • Message reflection. Older common controls pass messages other than WM_NOTIFY to notify the parent window of events. The OnMessageReflect is called to pass these messages back to the CWnd object associated with the child window.
  • Network support. Win32++ provides a CSocket class which is a thin wrapper for much of the Winsock SPI. This class also provides notification of network events. Supports IPv4 and IPv6.
  • Tracing. Trace output is sent to the Output pane of the IDE when the program is compiled with debugging enabled.
  • Multi-Thread support. Win32++ is thread safe, and windows can be created in separate threads.
  • 64 bit support. Win32++ can be used to create 64bit applications.
  • Multilingual support. SetResourceHandle can be used to load resources from a resource dll to provide support for different languages.
  • Support for Task Dialogs available on the Windows Vista and later operating systems.
  • Support for the Ribbon Framework available on Windows 7.

Requirements for using the Win32++

In order to use Win32++, you will need the following:

  • A C++ compiler.
  • Some knowledge of C++, including how to use classes
  • Some knowledge of the Windows API

You should also have a copy of the Microsoft Platform Software Development Kit, as this includes the documentation for programming with the Windows API. You will find this, as well as a selection of free C+ compilers and Windows API tutorials on the links page.

Getting Started

The library itself can be downloaded here. Simply start with one of the samples provided. The samples include the project files for Visual Studio 6, Visual Studio.Net 2003, VS2005 Express, VS2008 Express, VS2010 Express, Dev-C++ and CodeBlocks. If you're using one of these, the samples are pre-configured, and ready to compile.

If you're new to C++ programming and looking for a free compiler to use, I recommend Microsoft's Visual C++ 2008 Express Edition. I found this compiler to be the easiest free compiler to set up and use. If you are using an older Microsoft compiler you may also need to install and incorporate the Platform SDK. Information on how to do this is provided by Microsoft here. To compile the DirectX sample you will need to install the DirectX SDK.


Overview

Using Win32++

This section describes how to use Win32++ to build window applications.

  • Getting Started
  • Simple Windows
  • Dialogs
  • Frames
  • MDI Frames
  • Graphics Device Interface (GDI)
  • Docking
  • Text Conversion Functions


Getting Started

Before we begin

In order to use Win32++ you will need a C++ compiler. If you don't already have one, there are several free C++ compilers available for download from the internet. Some of the more popular choices are:

  • Microsoft's Visual C++ 2008 or 2010 Express
  • Code::Blocks
  • Dev-C++

Different compilers have their various strengths and weaknesses. My personal favourite is Microsoft's Visual C++ 2008 Express. If you use Visual Studio 2010 Express, be sure to enable the "Expert Settings" to access features such as the Class View, and the ability to clean and rebuild a project.

You should also download and install a copy of the Windows Software Development Kit (SDK). The Windows SDK includes the documentation of the Windows API, which is the primary reference document for windows programming. This is a free download available from Microsoft. The Windows SDK can be downloaded at: http://msdn.microsoft.com/en-us/windows/bb980924.aspx

Finally if you are planning to develop dialog applications or work with resources, you will need a resource editor. The commercial compilers generally include a resource a resource editor, but the free ones don't. Fortunately there are some free resource editors available. One such resource editor is ResEdit, available for download at: http://www.resedit.net/

Installing Win32++

Win32++ is available for download as a zip archive from SourceForge at http://sourceforge.net/projects/win32-framework/. Extract the files into a directory of your choosing, perhaps a subdirectory of your documents folder. When extracting the files, be sure to retain Win32++'s directory structure.

The Win32++ zip archive contains the Win32++ library files in the "include" directory, as well as a number of program samples which demonstrate the various type of applications that Win32++ can be used to create. Each sample contains a "ProjectFiles" directory, which contains a collection of project files matching a range of commonly used compilers. To compile the sample code, run the project which matches your compiler.

Creating a new project

Perhaps the simplest way to create a new project is to take one of the samples, and copy it to a new directory within the same parent directory as the samples. Alternatively you could use one of the project files from the "Win32++\new projects" directory which are provided for this purpose.

If you are looking to create your own project from scratch, you will typically need to do the following:

  • Start with a Win32 GUI application
  • Add "..\..\include" to the C++ Additional Include Directories.
  • Add "..\..\include" to the Resources Additional Include Directories.
  • Add additional libraries to the Linker Additional Dependencies (usually comctl32.lib).

You can use the existing project files as a guide as to how this should be done.

A Simple Window Application

The following code is a complete program for creating and displaying a window using Win32++. This program creates a simple window, and ends the application when the window is closed.

///////////////////////////////////
// main.cpp

// Add the Win32++\include  directory to project's additional include directories

#include "wincore.h"

class CView : public CWnd
{
public:
    CView() {}
    virtual ~CView() {}
    virtual LRESULT WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        switch (uMsg)
        {
        case WM_DESTROY:
            //End the program when window is destroyed
            ::PostQuitMessage(0);
            break;
        }

        //Use the default message handling for remaining messages
        return WndProcDefault(uMsg, wParam, lParam);
    }
};

int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    // Start Win32++
    CWinApp MyApp;

    // Create our view window
    CView m_View;
    m_View.Create();

    // Run the application
    return MyApp.Run();
}

In this code we inherit the CView class from CWnd to represent our view window. CView includes the WndProc member function to provide a means of handling window messages. Here we process the WM_DESTROY message to end the application when the window is destroyed.

The Tutorials

The tutorials contain a step by step guide to building a windows application using Win32++. The description of the each tutorial is contained within this help document, and the code is provided in the "tutorials" folder.


Simple Window

Description

A window typically occupies a rectangular portion of the screen. It is managed by the Windows operating system, and is capable of responding to events and redrawing itself. A window has a handle (often referred to as a HWND) through which a program can control the window or send it messages.

There are many different types of windows. In this section we will focus on a simple application window. The following sections will focus on more specialized widows, such as dialogs, toolbars, status bars, edit controls and so forth.

In Win32++, the CWnd class is used to create and control windows. We inherit a class from CWnd and override OnPaint to control the way our window looks, and override WndProc to control how it responds to messages. Refer to the description of CWnd in the Class Library section of this documentation for a description of the functions which can be overridden.

Components

The following diagram illustrates the components of a typical application window.

Typically an application will draw over the client area of the window, but leave the drawing of the non-client area to the operating system. Note that a child window (a window contained within another window) might not have a visible non-client area.

This diagram was created from an image capture of the window created by the "Simple" sample (one of the samples that ship with Win32++).

Creating a Window

Its important to note that the CWnd's window isn't created when the CWnd is constructed. The window is created some time later, when either the Create or the CreateEx function is called.

Normally the Create function is used to create the window. This function allows us to specify the handle (HWND) of the parent window, if any. It also calls PreRegisterClass to set the window class parameters, and PreCreate to set the creation parameters before creating the window. The PreRegisterClass and PreCreate can be overridden to set these parameters prior to window creation, as shown below.

void CView::PreRegisterClass(WNDCLASS &wc)
{
  // Set the background brush, class name and cursor
  wc.hbrBackground = m_hBrush;
  wc.lpszClassName = _T("Scribble Window");
  wc.hCursor = ::LoadCursor(GetApp()->GetResourceHandle(), MAKEINTRESOURCE(IDC_CURSOR1));
}

Additional notes for PreRegisterClass:

  • The lpszClassName must be set for this function to take effect.
  • The lpfnWndProc is always CWnd::StaticWindowProc.
  • The styles that can be set here are "class" styles. These are a different set of styles to those set by CREATESTRUCT (used in PreCreate).
  • Default class creation parameters are not set when PreRegisterClass is used, so the following settings might prove useful:
    • wc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
    • wc.hbrBackground = (HBRUSH)::GetStockObject(WHITE_BRUSH);
    • wc.hIcon = ::LoadIcon(NULL, IDI_APPLICATION);
void CView::PreCreate(CREATESTRUCT &cs)
{
  // Set the extra style to provide a sunken effect
  cs.dwExStyle = WS_EX_CLIENTEDGE;
}

Additional notes for PreCreate:

  • The cs.lpszClass parameter will be ignored if the PreRegisterClass function is used to create a window class.
  • The styles that can be set here are "window" styles. These are a different to the set of "class" styles used in PreRegisterClass.
  • A default style of WS_VISIBLE and possibly WS_OVERLAPPEDWINDOW is used if no style is specified. Be sure to add these styles if required when specifying the window style.

Create is the function which would normally be used to create a window, but sometimes it is more convenient to take more direct control over the various window creation parameters. CreateEx is the function which allows the various window parameters to be set directly when the window is created.

The OnCreate function is called during window creation. This function can be overridden to perform addition tasks during window creation, such as creating child windows. The OnInitialUpdate function is called once window creation is complete, so this function can be overridden to perform tasks after the window has been successfully created.

Painting the Window

In order to paint on the window, we override OnDraw and put our drawing code there. OnDraw is called automatically whenever all, or a part of the window needs to be redrawn. OnDraw provides us with a pointer to the client area's device context. All normal drawing for a window is done via a device context.

The following code loads a text string from a string resource and centers it on the client area of the window.

void CView::OnDraw(CDC* pDC)
{
  // OnDraw is called automatically whenever a part of the window needs to be redrawn.

  // Centre some text in our view window
  CRect rc = GetClientRect();
  pDC->DrawText(LoadString(IDW_MAIN), rc, DT_CENTER|DT_VCENTER|DT_SINGLELINE);
}

Handling Messages

Each CWnd handles the messages for its window. Override WndProc to specify how the CWnd should handle messages. Any unhandled messages are passed on to the default window procedure.

A WndProc function could look something like this:

LRESULT CView::WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  // This function is our message procedure. We process the messages for
  // the view window here.  Unprocessed messages are passed on for
  //  default processing.

  switch(uMsg)
  {
  case WM_DESTROY:
    OnDestroy();
    return 0;	// return a value. No default processing

  case WM_SIZE:
    OnSize();
    break;	// and also do default processing for this message
  }

  // pass unhandled messages on for default processing
  return WndProcDefault(uMsg, wParam, lParam);
}


Dialogs

Description

A dialog or dialog box is a specialised window, design to host other controls, such as buttons, toolbars, tree-views, list-views and so forth. A dialog is typically used to gather information from or present information to the user.

In Win32++, the CDialog class is used to create and control dialogs. We inherit a class from CDialog and override functions to control the way the dialog interacts with its controls. Refer to the description of CDialog in the Class Library section of this documentation for a description of the functions which can be overridden.

Dialog Components

The following picture shows a dialog with several controls, namely: a slider control; a scrollbar control; a progress bar control, a static control (for text); and a button control. These controls are actually specialised windows, and they are child windows of the dialog.

Modal and Modeless Dialogs

The behaviour of dialog boxes vary, depending on whether the dialog box is modal or modeless. A modal dialog box requires the user to close the dialog box before activating another window in the application. A modeless dialog box does not require an immediate response from the user. It is similar to a main window containing controls.

Working with resources

The resources used in an application are defined in a resource script. In the Win32++ samples this file is called Resource.rc. The resource script can be used to define the following types of resources.

  • Accelerator
  • Bitmap
  • Cursor
  • Dialog
  • Icon
  • Manifest
  • Menu
  • String table
  • User defined
  • Version Information

Typically a resource editor is used to create the resource script. The commercial compilers generally include a resource a resource editor, but the free ones don't. Fortunately there are some free resource editors available. One such resource editor is ResEdit, available for download at: http://www.resedit.net/.

When resources are defined, they will have an associated resource ID. These resource IDs are defined in a header file (typically resource.h). The resource script and its associated header file should be added to your project. When building your project, the resource script is compiled and linked to your executable or dll.

Its important to note that the resources defined in the resource script are actually embedded in your program. A very large resource, (a large bitmap for example) can increase the size of the executable considerably. If the size of the executable is an important consideration, large bitmaps and icons could be loaded from files during runtime rather than defining them in the resource script.

Creating the dialog

The first step in creating the dialog is to define the dialog resource using a resource editor. The resource ID defined in this process is then used to construct the object inherited from CDialog.

This is an example of how a dialog would be constructed for a simple dialog application. The CDialogApp is inherited from CWinApp, and would be instanciated in WinMain. CDialogApp's constructor initialization list provides the resource ID of the dialog to CMyDialog's constructor. When the application runs, InitInstance is called which creates a modeless dialog.

// Declaration of the CDialogApp class
class CDialogApp : public CWinApp
{
public:
  CDialogApp() : m_MyDialog(IDD_DIALOG1) {}
  virtual ~CDialogApp() {}
  virtual BOOL InitInstance();
  {
    //Display the Modal Dialog
    m_MyDialog.DoModal();

    //End the program
    ::PostQuitMessage(0);

    return TRUE;
  }

  CMyDialog& GetDialog() {return m_MyDialog;}

private:
  CMyDialog m_MyDialog;
};

Working with controls

The OnInitDialog function is called when the dialog is created. We can override this function to determine what happens when the dialog starts. In example the dialog's icon is set, and the dialog's controls are attached to classes inherited from CWnd.

BOOL CMyDialog::OnInitDialog()
{
  // Set the Icon
  SetIconLarge(IDW_MAIN);
  SetIconSmall(IDW_MAIN);

  // Attach the dialog controls
  AttachItem(IDC_PROGRESS1, m_ProgressBar);
  AttachItem(IDC_SCROLLBAR1, m_ScrollBar);
  AttachItem(IDC_SLIDER1, m_Slider);

  return true;
}

Attaching the progress bar control to m_Progressbar like this allows us to intercept the messages for the progress bar control, and handle them in m_Progrossbar's WndProc function.

Responding to Events

When a button is pressed on a dialog, a WM_COMMAND message is sent to the dialog window. Override OnCommand to respond to these commands as demonstrated in the following code.

BOOL CMyDialog::OnCommand(WPARAM wParam, LPARAM /*lParam*/)
{
  switch (LOWORD(wParam))
  {
    case IDC_BUTTON1:
      OnButton();
      return TRUE;
    case IDC_RADIO1:
      OnRadio1();
      return TRUE;
    case IDC_RADIO2:
      OnRadio2();
      return TRUE;
    case IDC_RADIO3:
      OnRadio3();
      return TRUE;
    case IDC_CHECK1:
      OnCheck1();
      return TRUE;
    case IDC_CHECK2:
      OnCheck2();
      return TRUE;
    case IDC_CHECK3:
      OnCheck3();
      return TRUE;
  } //switch (LOWORD(wParam))

  return FALSE;
}

The Ok and Cancel buttons call the OnOK and OnCancel functions when pressed. The default behaviour of these functions is to close the dialog. Override these functions to perform other tasks.

Handling Messages

Each CDialog handles the messages for its window. Override DialogProc to specify how the messages should be handled. Any unhandled messages are passed on to the default dialog procedure.

When overriding the DialogProc function, it could look something like this:

BOOL CMyDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
//  switch (uMsg)
//  {
//      //Additional messages to be handled go here
//  }

    // Pass unhandled messages on to parent DialogProc
    return DialogProcDefault(uMsg, wParam, lParam);
}

Handling Notifications

Common controls (for example an Edit control) send notification messages to their parent window to notify them of events, usually by way of a WM_NOTIFY message. The CDialog's OnNotify function is called in response to a WM_NOTIFY message. It can be overridden to handle these notification events.

OnNotify is used to handle notification messages in the CWnd of the parent window. However, users can choose to use the OnNotifyReflect to handle the notification in the CWnd of the child window that generated the notification instead.

When overriding the OnNotifyReflect function, it could look something like this:

LRESULT CMyTreeView::OnNotifyReflect(WPARAM, LPARAM lParam)
{
  LPNMHDR  lpnmh = (LPNMHDR) lParam;

  switch(lpnmh->code)
  {
  case NM_RCLICK:
    // Handle the mouse right button click notification
    {
      CPoint ptScreen = GetCursorPos();
      DoContextMenu(ptScreen);
    }
    break;

  } //switch LPNMHDR

  return 0L;
}

Likewise, OnMessage and OnMessageReflect can also be used to handle a small set of older messages that behave like notifications. The set of messages which are handled by OnMessage and OnMessageReflect are as follows:

WM_CTLCOLORBTN
WM_CTLCOLOREDIT
WM_CTLCOLORDLG
WM_CTLCOLORLISTBOX
WM_CTLCOLORSCROLLBAR
WM_CTLCOLORSTATIC
WM_DRAWITEM
WM_MEASUREITEM
WM_DELETEITEM
WM_COMPAREITEM
WM_CHARTOITEM
WM_VKEYTOITEM
WM_HSCROLL
WM_VSCROLL
WM_PARENTNOTIFY

When overriding OnMessageReflect, it might look something like this:

LRESULT CMySlider::OnMessageReflect(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  UNREFERENCED_PARAMETER(wParam);
  UNREFERENCED_PARAMETER(lParam);

  switch (uMsg)
  {
  case WM_HSCROLL:
    {
      // Get the slider bar position
      int nPos = GetPos();

      // Get a pointer to the MyDialog object
      CMyDialog* pDialog = (CMyDialog*)GetParent();

      pDialog->SetProgress(nPos);		// Set the progress bar position
      pDialog->SetScroll(nPos);		// Set the scroll bar position
      pDialog->SetStatic(TRUE, nPos);	// Set the static text

      break;
    }
  }

  return 0;
}


Frames

Description

Frames provides application developers with a standard way of presenting their applications to users. Frames usually display a menu, and often also display a toolbar and status bar.

There are two styles of frames used in Microsoft Windows. The Single Document Interface (SDI) frame allows the application to display a single view window. The Multiple Document Interface (MDI) frame allows the application to manage and display multiple view windows at the same time. The frames described in this section are SDI frames.

Refer to CFrame in the Class library section for a description of its member functions.

Frame components

The following diagram illustrates a typical frame application.

The toolbar and menubar are used to accept input from the user. The status bar is used to display status information. The view window is a child window of the frame, positioned over the are that is not occupied by the menu, toolbar and status bar.

Defining the Frame

To create a CMainFrame class, override Win32++'s CFrame class as follows:

// Declaration of the CMainFrame class
class CMainFrame : public CFrame
{
public:
  CMainFrame(void);
  virtual ~CMainFrame();

protected:
  virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
  virtual void OnCreate();
  virtual void OnInitialUpdate();
  virtual LRESULT OnNotify(WPARAM wParam, LPARAM lParam);
  virtual void SetupToolBar();
  virtual LRESULT WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam);

private:
  CView m_View;  // The view window
};

The View Window

Every frame must be provided with a view window. The view window can be any sort of window, providing it is a child window, and it is capable of being resized. The types of windows that might be used as view windows include simple windows, rich edit controls, tree view controls, list view controls, tab controls modeless dialogs, Win32++ dockers, etc.

The view is a window class inherited from CWnd. The view window must be set before the frame window is created. This is usually done in the constructor as follows:

CMainFrame::CMainFrame()
{
  //Set m_View as the view window of the frame
  SetView(m_View);
}

Incidentally, other parts of Win32++ use view windows as well. View windows are used in:

  • Frames
  • MDI children
  • Tab controls
  • TabbedMDIs
  • Dockers
  • Dock containers

Each of these use view windows in the same way.

Customising the Frame's creation

The OnCreate function determines how the frame will be created. It is this function which creates the various child windows used by the frame, namely the status bar, toolbar, rebar, menu bar, and the view window. Override OnCreate if you wish to modify the creation of the various child windows.

There are several member variables used in OnCreate that affect the appearance of the frame. The following code is part of the generic starter for a frame application. The appearance of the frame can be altered by removing the comment from in front of one or more of the member variables listed.

void CMainFrame::OnCreate()
{
  // OnCreate controls the way the frame is created.
  // Overriding CFrame::Oncreate is optional.
  // The default for the following variables is TRUE

  // m_bShowIndicatorStatus = FALSE;  // Don't show statusbar indicators
  // m_bShowMenuStatus = FALSE;       // Don't show toolbar or menu status
  // m_bUseReBar = FALSE;             // Don't use rebars
  // m_bUseThemes = FALSE;            // Don't use themes

  // call the base class function
  CFrame::OnCreate();
}

Defining the toolbar buttons

The bitmap image (or images) associated with the toolbar buttons is specified in the resource script file (Resource.rc). To modify the images displayed on the toolbar buttons, the bitmaps associated with the toolbar will need to be edited accordingly. If the programming environment doesn't include a resource editor for this purpose, a free resource editor such as ResEdit might prove useful. By default, the frame uses the bitmap resource associated with IDW_MAIN when displaying the toolbar. The entry in Resource.rc that associates the bitmap with the resource ID looks like this.

IDW_MAIN                 BITMAP                  "res\\toolbar.bmp"

The following code demonstrates how configure the commands issued by the toolbar when the button is pressed. This code should be placed in CMainFrame::SetupToolBar. This is an typical exanple SetupToolBar.

void CMainFrame::SetupToolBar()
{
  // Set the Resource IDs for the toolbar buttons
  AddToolBarButton( IDM_FILE_NEW   );
  AddToolBarButton( IDM_FILE_OPEN  );
  AddToolBarButton( IDM_FILE_SAVE  );

  AddToolBarButton( 0 );                      // Separator
  AddToolBarButton( IDM_EDIT_CUT,   FALSE );  // disabled button
  AddToolBarButton( IDM_EDIT_COPY,  FALSE );  // disabled button
  AddToolBarButton( IDM_EDIT_PASTE, FALSE );  // disabled button

  AddToolBarButton( 0 );                      // Separator
  AddToolBarButton( IDM_FILE_PRINT );

  AddToolBarButton( 0 );                      // Separator
  AddToolBarButton( IDM_HELP_ABOUT );
}

Refer to the tutorial for a demonstration of customising the toolbar buttons.

Responding Menu and Toolbar Input

When a menu item is selected or a toolbar button is pressed, a WM_COMMAND message is sent to the frame window. Override OnCommand to respond to these commands as demonstrated in the following code.

BOOL CMainFrame::OnCommand(WPARAM wParam, LPARAM /*lParam*/)
{
  // OnCommand responds to menu and and toolbar input

  switch(LOWORD(wParam))
  {
  case IDM_FILE_EXIT:
    // End the application when exit is selected from the menu
    PostQuitMessage(0);
    return TRUE;
  case IDM_HELP_ABOUT:
    // Display the help dialog
    OnHelp();
    return TRUE;
  }
  return FALSE;
}

Customising the Toolbar

Various aspects of the toolbar can be configured. The image list associated with normal, hot, and disabled toolbar buttons are set by the SetToolBarImages function. The following code demonstrates the use of the SetToolBarImages function, and shows how to add text to toolbar buttons.

void CMainFrame::SetupToolBar()
{
  // Set the Resource IDs for the toolbar buttons
  AddToolBarButton( IDM_FILE_NEW   );
  AddToolBarButton( IDM_FILE_OPEN  );
  AddToolBarButton( IDM_FILE_SAVE  );

  AddToolBarButton( 0 );                      // Separator
  AddToolBarButton( IDM_EDIT_CUT,   FALSE );  // disabled button
  AddToolBarButton( IDM_EDIT_COPY,  FALSE );  // disabled button
  AddToolBarButton( IDM_EDIT_PASTE, FALSE );  // disabled button

  AddToolBarButton( 0 );                      // Separator
  AddToolBarButton( IDM_FILE_PRINT );

  AddToolBarButton( 0 );                      // Separator
  AddToolBarButton( IDM_HELP_ABOUT );

  // Use larger buttons
  SetToolBarImages(RGB(192,192,192), IDB_TOOLBAR_NORM, IDB_TOOLBAR_HOT, IDB_TOOLBAR_DIS);

  // Add some text to the buttons
  CToolBar& TB = GetToolBar();
  TB.SetButtonText(IDM_FILE_NEW,   _T("New"));
  TB.SetButtonText(IDM_FILE_OPEN,  _T("Open"));
  TB.SetButtonText(IDM_FILE_SAVE,  _T("Save"));
  TB.SetButtonText(IDM_EDIT_CUT,   _T("Cut"));
  TB.SetButtonText(IDM_EDIT_COPY,  _T("Copy"));
  TB.SetButtonText(IDM_EDIT_PASTE, _T("Paste"));
  TB.SetButtonText(IDM_FILE_PRINT, _T("Print"));
  TB.SetButtonText(IDM_VIEWMENU,   _T("View Menu"));
  TB.SetButtonText(IDM_HELP_ABOUT, _T("About"));
}

Themes

Themes provide an opportunity to set the colour and styles of various parts of the frame, namely the menu, the toolbar and the rebar. By default, the frame will call the SetTheme function from inside OnCreate to set these various colours and styles. SetTheme can be overridden to modify these. This is example shows how set the theme to grey.

void CMainFrame::SetTheme()
{
  BOOL T = TRUE;
  BOOL F = FALSE;

  ToolBarTheme tt = {T, RGB(182, 189, 210), RGB(182, 189, 210), RGB(133, 146, 181), RGB(133, 146, 181), RGB(10, 36, 106)};
  ReBarTheme rt = {T, RGB(212, 208, 200), RGB(230, 226, 222), RGB(230, 226, 222), RGB(220, 218, 208), F, T, T, T, T, F};
  MenuTheme mt = {T, RGB(182, 189, 210), RGB( 182, 189, 210), RGB(200, 196, 190), RGB(200, 196, 190), RGB(100, 100, 100)};

  GetToolBar().SetToolBarTheme(tt);
  SetMenuTheme(mt); // Sets the theme for popup menus
  if (IsReBarUsed())
  {
    GetReBar().SetReBarTheme(rt);
    GetMenuBar().SetMenuBarTheme(mt); // Sets the theme for MenuBar buttons
  }
}

The definition of the various theme structures are as follows:

struct ReBarTheme
{
  BOOL UseThemes;      // TRUE if themes are used
  COLORREF clrBkgnd1;  // Colour 1 for rebar background
  COLORREF clrBkgnd2;  // Colour 2 for rebar background
  COLORREF clrBand1;   // Colour 1 for rebar band background. Use NULL if not required
  COLORREF clrBand2;   // Colour 2 for rebar band background. Use NULL if not required
  BOOL FlatStyle;      // Bands are rendered with flat rather than raised style
  BOOL KeepBandsLeft;  // TRUE if we always keep bands left
  BOOL LockMenuBand;   // Lock MenuBar's band up top, without gripper
  BOOL RoundBorders;   // Use rounded band borders
  BOOL ShortBands;     // Allows bands to be shorter than maximum available width
  BOOL UseLines;       // Displays horizontal lines between bands
};

struct MenuTheme
{
  BOOL UseThemes;       // TRUE if themes are used
  COLORREF clrHot1;     // Colour 1 for hot button
  COLORREF clrHot2;     // Colour 2 for hot button
  COLORREF clrPressed1; // Colour 1 for pressed button
  COLORREF clrPressed2; // Colour 2 for pressed button
  COLORREF clrOutline;  // Colour for border outline
};

struct ToolBarTheme
{
  BOOL UseThemes;       // TRUE if themes are used
  COLORREF clrHot1;     // Colour 1 for hot button
  COLORREF clrHot2;     // Colour 2 for hot button
  COLORREF clrPressed1; // Colour 1 for pressed button
  COLORREF clrPressed2; // Colour 2 for pressed button
  COLORREF clrOutline;  // Colour for border outline
};

Refer to the themes sample application for a demonstration of the different sorts of effects that can be achieved by altering a frame's theme.

Using the registry

Modern applications are expected to save their settings in the registry. To enable the loading and saving of program settings use the LoadRegistrySettings function in CMainFrame's constructor. If you also wish to load and save a list of Most Recently Used (MRU) files, call the LoadRegistryMRU function settings as well.

CMainFrame::CMainFrame()
{
  // Set m_View as the view window of the frame
  SetView(m_View);

  // Set the registry key name, and load the initial window position
  // Use a registry key name like "CompanyName\\Application"
  LoadRegistrySettings(_T("Win32++\\Scribble Sample"));

  // Load the settings from the registry with 4 MRU entries
  LoadRegistryMRUSettings(4);
}

By default CFrame saves the frame size and position in the registry. To load and save other settings, override the LoadRegistyrSettings and SaveRegistrySettings functions in CMainFrame.


MDI Frames

Description

Multiple Document Interface (MDI) frames are capable of managing and displaying a number of MDI children. These MDI Children have their own view window.

Refer to the MDIFrame and MDIFrameDemo samples for demonstration of how to CMDIFrame and CMDIChild to create MDI applications.

MDI Frame Components

The following diagram illustrates a typical MDI frame application.

The toolbar and menubar are used to accept input from the user. The status bar is used to display status information.

Defining the MDI Frame

To define a MDI frame, inherit a class from CMDIFrame as shown below.

// MDI frames are inherrited from CMDIFrame
class CMainMDIFrame : public CMDIFrame
{
public:
  CMainMDIFrame(void);
  virtual ~CMainMDIFrame();

protected:
  virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
  virtual void OnCreate();
  virtual void OnInitialUpdate();
  virtual void SetupToolBar();
  virtual LRESULT WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
};

Unlike SDI frames, we do not need to specify a view window for the frame. The Win32++ framework automatically assigns the MDI client window as the view window for the frame. The constructor for our MDI frame could look like this.

CMainMDIFrame::CMainMDIFrame()
{
  // Set the registry key name, and load the initial window position
  // Use a registry key name like "CompanyName\\Application"
  LoadRegistrySettings(_T("Win32++\\MDI Frame"));
}

Defining a MDI Child

To define a MDI child, inherit a class from CMDIChild as shown below.

// Declaration of CSimpleMDIChild
class CSimpleMDIChild : public CMDIChild
{
public:
  CSimpleMDIChild();
  virtual ~CSimpleMDIChild();

protected:
  virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
  virtual void OnInitialUpdate();
  virtual LRESULT WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam);

private:
    CSimpleView m_View;
};

The MDI Child's Menu and View

Normally each different type of MDI child has a different menu. The MDI Frame's menu is changed to the MDI child's menu when the MDI child becomes the active window. The menu for each MDI child is usually defined in the resource script file (resource.rc).

The view window for the MDI child is set in the same way we would set the view window for a SDI frame. The constructor for the class inherited from CMDIChild would typically look something like this.

CMDIChildSimple::CMDIChildSimple()
{
  SetView(m_View);

  HINSTANCE hResource = GetApp()->GetResourceHandle();
  HMENU hChildMenu = LoadMenu(hResource, _T("MdiMenuSimple"));
  SetHandles(hChildMenu, NULL);
}

Adding a MDI child window

The AddMDIChild function is used to add a MDI child window. The following code demonstrates how to create a new MDI child window in response to a selection from the frame's menu or toolbar.

BOOL CMainMDIFrame::OnCommand(WPARAM wParam, LPARAM /*lParam*/)
{
  switch (LOWORD(wParam))
  {
  case IDM_FILE_NEW:
    AddMDIChild(new CMDIChildView); // CMDIFrame deletes this pointer
    return TRUE;
  }
  return FALSE;
}

Note that the pointer created by "new" is deleted automatically by CMDIFrame when the MDI child window is destroyed.


GDI

Graphics Device Interface (GDI)

About the GDI

The Graphics Device Interface (GDI) is part of the Windows operating system. It provides applications with a means of sending graphics information to devices such as the video display and printer.

When using the GDI, the graphics device is represented as a device context (DC). All drawing calls are made through a device-context object, which encapsulates the Windows APIs for drawing lines, shapes, and text. Device contexts allow device-independent drawing in Windows. GDI objects such as bitmaps, brushes, palettes and pens are selected into the device context before they can be used to display the graphic information. Fonts can also be selected into the device context to manage the rendering of text.

The GDI classes in Win32++

The set of GDI classes provided by Win32++ are as follows:

  • CDC
  • CClientDC
  • CMemDC
  • CMetaFileDC
  • CPaintDC
  • CWindowDC
  • CGDIObject
  • CBitmap
  • CBrush
  • CFont
  • CPalette
  • CPen
  • CRgn

The CDC class provides a GDI device context. It can also create the various GDI objects for use with the device context, such as Bitmaps, Brushes, Bitmaps, Fonts and Pens. This class automatically handles the creation, selection, de-selection and deletion of the various GDI objects it creates. It also automatically deletes or releases the device context itself as appropriate.

The CDC classes are sufficient for most GDI programming needs. Sometimes however, we need to have the GDI object separated from the device context. Wrapper classes for GDI objects are provided for this purpose. These classes are CBitmap, CBrush, CFont, CPalette, CPen and CRgn. Instances of these classes can be 'attached' to and 'detached' from the CDC as required.

The lifetime of a GDI resource attached to the CDC is managed by the GDI object wrapper class (e.g. CBitmap in the case of Bitmaps). These classes automatically delete the GDI resource assigned to them when their destructor is called.

Using the GDI classes

Using the Windows API without CDC

This code demonstrates how to use the Windows API functions directly to draw a line with the GDI.

void DrawLine()
{
  HDC hdcClient = ::GetDC(m_hWnd);
  HDC hdcMem = ::CreateCompatibleDC(hdcClient);
  HBITMAP hBitmap = ::CreateCompatibleBitmap(hdcClient, cx, cy);
  HBITMAP hOldBitmap = (HBITMAP)::SelectObject(hdcMem, hBitmap);
  HPEN hPen = ::CreatePen(PS_SOLID, 1, RGB(255,0,0);
  HPEN hOldPen = (HPEN)::SelectObject(hdcMem, hPen);
  ::MoveToEx(hdcMem, 0, 0, NULL);
  ::LineTo(hdcMem, 50, 50);
  ::BitBlt(hdcClient, 0, 0, cx, cy, hdcMem, 0, 0);
  ::SelectObject(hdcMem, hOldPen);
  ::DeleteObject(hPen);
  ::SelectObject(hdcMem, hOldBitmap);
  ::DeleteObject(hBitmap);
  ::DeleteDC(hdcMem);
  ::ReleaseDC(m_hWnd, hdcClient);
}
Using CDC classes alone

This code performs the same task as shown above using the CDC class.

void DrawLine()
{
  CClientDC dcClient(this)
  CMemDC dcMem(&dcClient);
  CBitmap* pOldBitmap = dcMem.CreateCompatibleBitmap(&dcClient, cx, cy);
  CPen* pOldPen = CMemDC.CreatePen(PS_SOLID, 1, RGB(255,0,0);
  CMemDC.MoveTo(0, 0);
  CMemDC.LineTo(50, 50);
  dcClient.BitBlt(0, 0, cx, cy, &CMemDC, 0, 0);
}
Using CDC classes with CPen

This code uses a CDC and CPen to draw the line.

void DrawLine()
{
  CClientDC dcClient(this)
  CMemDC dcMem(&dcClient);
  CBitmap* pOldBitmap = dcMem.CreateCompatibleBitmap(&dcClient, cx, cy);
  CPen MyPen(PS_SOLID, 1, RGB(255,0,0));
  CPen* pOldPen = dcMem.SelectObject(&MyPen);
  dcMem.MoveTo(0, 0);
  dcMem.LineTo(50, 50);
  dcClient.BitBlt(0, 0, cx, cy, &dcMem, 0, 0);
}

Notes:

  • When the CDC object drops out of scope, it's destructor is called, cleaning up any GDI objects it created, as well as the device context.
  • When the CPen object drops out of scope, it's destructor is called, deleting its associated GDI object (HPEN).
Creating a Window DC

A window DC is a device context which represents the entire window, including the non-client area. We can create a window DC as follows:

CMemDC dcMem(this);
Creating a Window Client DC

The following code creates a device context for the client area of the window. The following code shows how we can create a DC for the window's client area.

CClientDC dcClient(this);
Creating a Memory DC

As the name suggests, a memory DC is created in memory. Memory DCs are typically used for double buffering. With this programming technique we perform the drawing tasks to a memory DC, and then copy the bitmap to our window.

When creating a memory DC we provide a pointer to the CWindowDC or CClientDC that the memory DC is compatible with. We then create the compatible bitmap that the memory DC will draw to. The following code demonstrates how this is done.

// Create our memory client DC
CRect rc = GetClientRect();
CClientDC dcClient(this);

// Create our memory DC and compatible bitmap
CMemDC dcMem(&dcClient);
dcMem.CreateCompatibleBitmap(&dcClient, rc.Width(), rc.Height());

// Draw some stuff on the memory DC
dcMemC.CreatePen(PS_SOLID, 1, RGB(255,0,0);
dcMem.MoveTo(0, 0);
dcMem.LineTo(50, 50);

// Copy the Memory DC's bitmap to the window's client DC
dcClient.BitBlt(0, 0, rc.Width(), rc.Height(), &dcMem, 0, 0, SRCCOPY);

The use of a memory DC doesn't necessarily make the graphics any faster, but can reduce or even eliminate annoying flicker.

Handling OnDraw and OnEraseBkgnd

The OnDraw and OnEraseBkgnd functions provide a reference to the CDC for us to use. The following code demonstrates how these functions can be used.

void CView::OnDraw(CDC* pDC)
{
  CRect rc = GetClientRect();

  // Centre some text in our view window
  pDC->DrawText(_T("View Window"), -1, rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
}
BOOL CView::OnEraseBkgnd(CDC* pDC)
{
  CBrush MyBrush(RGB(255,255,230)); // this could also be a member variable
  CRect rc = GetClientRect();
  FillRect(rc, MyBrush);
}
Notes:
  • A device context assigned to a CDC object will be released or deleted when the CDC is destroyed, unless it is detached.
  • A GDI object created by one of the CDC member functions will be deleted when the CDC object is destroyed.
  • The GDI objects selected into the CDC with SelectObject are not deleted when the CDC goes out of scope. Only GDI objects created by the CDC are automatically deleted.
  • GDI objects belonging to the various GDI wrapper classes (eg. CPen) are automatically deleted when the class object is destroyed, unless they are detached .
  • A bitmap GDI object can only be selected into one device context at a time.
  • Set the region's shape before selecting it into a DC.


Docking

Description

The CDocker class adds both docking and splitter windows to the Win32++ framework. Splitter windows have a subset of the functionality of docking windows. Splitter windows are child windows that can be dynamically re-sized. Docking windows have this feature too, but they also allow windows to be docked and undocked.

Docking is a mechanism which allows a separate popup window to be converted to a child window of some parent and displayed within it. Undocking is a mechanism which allows a child window to be separated from its parent window and displayed as a separate popup window. The various Integrated Development Environments from Microsoft, including Visual Studio.Net 2008 and Visual Studio.Net 2010 illustrated docking.

The CDocker class adds docking to the Win32++ framework. It creates specialized windows called "Dockers" capable of allowing other Dockers to dock to and undock from them. When docking, the undocked Docker is dragged over another Docker. Various visual clues such has the dock targeting (small arrow-like images), and the dock hinting (where a portion of the destination window turns blue) provide a hint as to where the Docker will be docked. To facilitate undocking, the caption of the docked window is dragged and dropped.

Every Docker has a view window. These views can be any child window, and are set in the same way as views for Frames and MDI children. Containers (provided by the CDockContainer class) are a specialized view which add additional docking features when used as the view window for a Docker.

A Docker which is docked within another Docker is said to be a "dock child" of that Docker. There is no theoretical limit to how many dock children a Docker may have. There is also no theoretical limit as to the depth of the child/parent relationship. That's to say there can be any number of dock children within dock children within dock children etc.

The primary or first Docker is referred to as the Dock Ancestor. This would typically be the view window of a Frame. Other Dockers are added to this dock hierarchy using the AddDockedChild or AddUndockedChild functions. This group of Dockers is said to be "related" or in the same docking group. These Dockers can dock and undock from each other. It would be possible for an application to have more than one Dock Ancestor, but this is uncommon. Dockers which have a different Dock Ancestor are not "related", and cannot dock within each other.

A Docker will dock to any one of the four sides of another related Docker (left, right, top or bottom). When a Docker is docked within a child Docker, this is referred to as "inner docking". When a Docker is docked to the side of the Dock Ancestor, this is referred to as "outer docking". Outer docking and inner docking have different dock targeting visual cues. When a Docker has a Container as its view window, it also supports "Container within Container" docking which adds another tab for the newly docked Container.

Docker Components

The following image illustrates some of the components of Docker windows. In this case the window being docked is dragged over a Docker with a Container view. Hence we see the center target option within the Inner Dock Targets for Container within Container docking.

Setting the Docker's view

The following code shows how the Docker's view is assigned, and how to set the width of the splitter bar.

CDockClasses::CDockClasses()
{
  SetView(m_Classes);
}

void CDockClasses::OnInitialUpdate()
{
  // Set the width of the splitter bar
  SetBarWidth(8);
}

Dockers can have a number of styles. These styles can determine where the Docker is docked, whether or not it can be undocked, and where dock children are permitted to dock. The dock style is initially specified when the Docker is added to the docking hierarchy . The complete set of dock styles are as follows:

DS_DOCKED_LEFT | Dock the child left
DS_DOCKED_RIGHT | Dock the child right
DS_DOCKED_TOP | Dock the child top
DS_DOCKED_BOTTOM | Dock the child bottom
DS_NO_DOCKCHILD_LEFT | Prevent a child docking left
DS_NO_DOCKCHILD_RIGHT | Prevent a child docking right
DS_NO_DOCKCHILD_TOP | Prevent a child docking at the top
DS_NO_DOCKCHILD_BOTTOM | Prevent a child docking at the bottom
DS_NO_RESIZE | Prevent resizing
DS_NO_CAPTION | Prevent display of caption when docked
DS_NO_CLOSE | Prevent closing of a docker while docked
DS_NO_UNDOCK | Prevent undocking and dock closing
DS_CLIENTEDGE | Has a 3D border when docked
DS_FIXED_RESIZE | Perform a fixed resize instead of a proportional resize on dock children
DS_DOCKED_CONTAINER | Dock a container within a container
DS_DOCKED_LEFTMOST | Leftmost outer docking
DS_DOCKED_RIGHTMOST | Rightmost outer docking
DS_DOCKED_TOPMOST | Topmost outer docking
DS_DOCKED_BOTTOMMOST | Bottommost outer docking

Adding Dock Children

The following code shows how to add Dock Children. In this case m_DockView is the Dock Ancestor and happens to have a view window which displays "Simple View". Note that the newly added Dockers can be children of the Dock Ancestor or any other Dock Child.

void CMainFrame::LoadDefaultDockers()
{
  // Note: The  DockIDs are used for saving/restoring the dockers state in the registry

  DWORD dwStyle = DS_CLIENTEDGE; // The style added to each docker

  // Add the parent dockers
  CDocker* pDockRight  = m_DockView.AddDockedChild(new CDockClasses, DS_DOCKED_RIGHT | dwStyle, 200, ID_DOCK_CLASSES1);
  CDocker* pDockBottom = m_DockView.AddDockedChild(new CDockText, DS_DOCKED_BOTTOM | dwStyle, 100, ID_DOCK_TEXT1);

  // Add the remaining dockers
  pDockRight->AddDockedChild(new CDockFiles, DS_DOCKED_CONTAINER | dwStyle, 200, ID_DOCK_FILES1);
  pDockRight->AddDockedChild(new CDockClasses, DS_DOCKED_CONTAINER | dwStyle, 200, ID_DOCK_CLASSES2);
  pDockRight->AddDockedChild(new CDockFiles, DS_DOCKED_CONTAINER | dwStyle, 200, ID_DOCK_FILES2);

  pDockBottom->AddDockedChild(new CDockOutput, DS_DOCKED_CONTAINER | dwStyle, 100, ID_DOCK_OUTPUT1);
  pDockBottom->AddDockedChild(new CDockText, DS_DOCKED_CONTAINER | dwStyle, 100, ID_DOCK_TEXT2);
  pDockBottom->AddDockedChild(new CDockOutput, DS_DOCKED_CONTAINER | dwStyle, 100, ID_DOCK_OUTPUT2);
}

Saving the Dockers in the Registry

CDocker provides built in support for saving the Dockers in the registry. The functions which perform this task are CDocker::LoadRegistrySettings and CDocker::SaveRegistrySettings.

The first step in using these functions is to override CDocker::NewDockerFromID for the Dock Ancestor. This function can create a new Docker from the specified Docker ID. In this case CDockSimple is the CDocker class for our Dock Ancestor, so the NewDockerFromID function looks like this:

CDocker* CDockSimple::NewDockerFromID(int nID)
{
  CDocker* pDock = NULL;
  switch(nID)
  {
  case ID_DOCK_CLASSES1:
    pDock = new CDockClasses;
    break;
  case ID_DOCK_CLASSES2:
    pDock = new CDockClasses;
    break;
  case ID_DOCK_FILES1:
    pDock = new CDockFiles;
    break;
  case ID_DOCK_FILES2:
    pDock = new CDockFiles;
    break;
  case ID_DOCK_OUTPUT1:
    pDock = new CDockOutput;
    break;
  case ID_DOCK_OUTPUT2:
    pDock = new CDockOutput;
    break;
  case ID_DOCK_TEXT1:
    pDock = new CDockText;
    break;
  case ID_DOCK_TEXT2:
    pDock = new CDockText;
    break;
  default:
    TRACE(_T("Unknown Dock ID\n"));
    break;
  }

  return pDock;
}

All that remains now is to use the CDocker's LoadRegistrySettings and SaveRegistrySettings in CMainFrame. The following code demonstrates how this might be done.

void CMainFrame::OnInitialUpdate()
{
  m_DockView.SetDockStyle(DS_CLIENTEDGE);

  // Load dock settings
  if (!m_DockView.LoadRegistrySettings(GetRegistryKeyName()))
    LoadDefaultDockers();

  // PreCreate initially set the window as invisible, so show it now.
  ShowWindow();
}

void CMainFrame::SaveRegistrySettings()
{
  CFrame::SaveRegistrySettings();
  m_DockView.SaveRegistrySettings(GetRegistryKeyName());
}

Refer to the DockSimple, DockContainer and DockTabbedMDI samples for a demonstration of docking.

Dock Containers

Dock containers (also known simply as containers) are a specialized view window for Dockers. It is a tab control which has been designed to co-operate with docking. While dockers allows any child window to be used as the view window, containers add additional features when used as the view window for dockers. These additional features include container within container docking (where the newly docked Container adds another tab), as well as additions to the dock targeting and dock hinting visual cues. Containers can also have a toolbar. The use of a toolbar is optional, but when used they are set up in the same way as toolbars for Frames.

The CDockContainer class adds "Containers" to the Win32++ framework. CDockContainers also have views of their own. These views can be any child window, and are set in the same way as views for Frames and MDI children.

It is typical to set various attributes of the Container in its constructor. The following code demonstrates how to specify a Container's tab text, tab icon, view window, and the text which will be displayed in the docked caption.

CContainClasses::CContainClasses()
{
  // Note: CContainClasses inherits from CDockContainer

  SetTabText(_T("ClassView"));
  SetTabIcon(IDI_CLASSVIEW);
  SetDockCaption (_T("Class View - Docking container"));
  SetView(m_ViewClasses);
}

If the Container has a toolbar, it is set up in the same way as the toolbar for a Frame. The following code demonstrates how the SetupToolBar function is used to specify the ToolBar's bitmap and resource IDs, as well as how to configure the toolbar themes to match those of the Frame.

void CContainClasses::SetupToolBar()
{
  // Set the Bitmap resource for the toolbar
  GetToolBar().SetImages(RGB(192,192,192), IDW_MAIN, 0, 0);

  // Set the Resource IDs for the toolbar buttons
  AddToolBarButton( IDM_FILE_NEW         );
  AddToolBarButton( IDM_FILE_OPEN, FALSE );

  AddToolBarButton( 0 );	// Separator
  AddToolBarButton( IDM_FILE_SAVE, FALSE );

  AddToolBarButton( 0 );	// Separator
  AddToolBarButton( IDM_EDIT_CUT         );
  AddToolBarButton( IDM_EDIT_COPY        );
  AddToolBarButton( IDM_EDIT_PASTE       );

  AddToolBarButton( 0 );	// Separator
  AddToolBarButton( IDM_FILE_PRINT, FALSE );

  AddToolBarButton( 0 );	// Separator
  AddToolBarButton( IDM_HELP_ABOUT       );

  // Add the ComboBarEx control to the toolbar
  AddCombo();

  // Match the Container's ToolBar theme to the MainFrame's toolbar theme
  ThemeToolBar tt = GetTabbedMDIApp().GetMainFrame().GetToolBar().GetToolBarTheme();
  GetToolBar().SetToolBarTheme(tt);
}

The following example demonstrates how to add Containers to an exiting Docker. Note that the DS_DOCKED_CONTAINER style is used to dock a container within a container. Only Containers support this style.

void CMainFrame::LoadDefaultDockers()
{
  // Note: The  DockIDs are used for saving/restoring the dockers state in the registry
  // Note: CDockClasses, CDockFiles, CDockOutput and CDockText inherit from CDocker, and
           have a view which inherits from CDockContainer. The m_DockTabbedMDI member also
           inherits from CDocker.

  DWORD dwStyle = DS_CLIENTEDGE; // The style added to each docker

  // Add the parent dockers
  CDocker* pDockRight  = m_DockTabbedMDI.AddDockedChild(new CDockClasses, DS_DOCKED_RIGHT | dwStyle, 200, ID_DOCK_CLASSES1);
  CDocker* pDockBottom = m_DockTabbedMDI.AddDockedChild(new CDockText, DS_DOCKED_BOTTOM | dwStyle, 100, ID_DOCK_TEXT1);

  // Add the remaining dockers
  pDockRight->AddDockedChild(new CDockFiles, DS_DOCKED_CONTAINER | dwStyle, 200, ID_DOCK_FILES1);
  pDockRight->AddDockedChild(new CDockClasses, DS_DOCKED_CONTAINER | dwStyle, 200, ID_DOCK_CLASSES2);
  pDockRight->AddDockedChild(new CDockFiles, DS_DOCKED_CONTAINER | dwStyle, 200, ID_DOCK_FILES2);

  pDockBottom->AddDockedChild(new CDockOutput, DS_DOCKED_CONTAINER | dwStyle, 100, ID_DOCK_OUTPUT1);
  pDockBottom->AddDockedChild(new CDockText, DS_DOCKED_CONTAINER | dwStyle, 100, ID_DOCK_TEXT2);
  pDockBottom->AddDockedChild(new CDockOutput, DS_DOCKED_CONTAINER | dwStyle, 100, ID_DOCK_OUTPUT2);
}


Text Conversions

Text Conversion

Introduction

There are several different types of text strings used in windows programming. These include:

ANSI

ANSI is an acronym for the American National Standards Institute. In windows programming, the term ANSI usually refers to single-byte ISO-8859 encodings. ANSI text strings are stored as an array of single byte char (or CHAR).

BSTR

BSTR is an abbreviation of Basic String (or perhaps Binary String). It was originally used in Visual Basic, and is often used in COM programming today. A BSTR string is a specialized Unicode string. It begins with a length field, which is followed by a string of Unicode characters. A BSTR is always NULL terminated, but can also contain NULL characters within the string.

OLE

Microsoft introduced a number of macros with "OLE" in the name, such as LPOLESTR. The term as it relates to text strings is largely superseded by Unicode (i.e. Wide) strings, however there are still a few Windows API functions that take LPOLESTR arguments. In modern Windows programming, OLE strings are Unicode strings.

TCHAR

TCHAR text strings are Unicode if the UNICODE macro is defined, otherwise they are ANSI. TCHAR is the type of text string used in most Windows API functions. It helps developers to produce code capable of supporting both ANSI and Unicode text strings.

Wide or Unicode

Unicode is an international standard for the representation of text characters. Unlike ANSI which uses a single byte for each character, Unicode (in Windows) uses two bytes for each character. Unicode text strings are stored as an array of wchar (or WCHAR). Modern Microsoft Windows operating systems (since WinME) have standardised on Unicode.

String Conversion Functions in Win32++

Win32++ contains the following functions to convert from one string type to another.

A2BSTR | Convert from ANSI to BSTR
A2OLE | Convert from ANSI to OLE
A2T | Convert from ANSI to TCHAR
A2W | Convert from ANSI to WCHAR
OLE2A | Convert from OLE to ANSI
OLE2T | Convert from OLE to TCHAR
OLE2W | Convert from OLE to WCHAR
T2A | Convert from TCHAR to ANSI
T2BSTR | Convert from TCHAR to BSTR
T2OLE | Convert from TCHAR to OLE
T2W | Convert from TCHAR to WCHAR
W2A | Convert from WCHAR to ANSI
W2BSTR | Convert from WCHAR to BSTR
W2OLE | Convert from WCHAR to OLE
W2OLE | Convert from WCHAR to OLE

Using the Text Conversion Functions

Each of the text conversion functions described above are actually typedefs of text conversion classes such as CA2W and CW2A. They each return a pointer to the appropriate text string type. These text conversions can be used as either classes or functions. When using them as functions it is important to remember that the returned pointer goes out of scope immediately. This means the returned pointer cannot be saved for later use. The following examples illustrate this.

Example 1 - Using the text converter as a class

In this example W2A is used as a class. A W2A object is created using its constructor, and this object remains in scope until the example function ends.

void ExampleFunctionW( LPCWSTR pWide )
{
  // Use the converion class as a class.
  W2A MyAnsiString( pWide );

  // MyAnsiString works like an LPCSTR (pointer to const CHAR), and can be used like this:
  SetWindowTextA( MyAnsiString );	// The ANSI version of SetWindowText

  // Note: MyAnsiString remains in scope until the function ends.
}

Example 2 - Using the text converter as as a function.

In this example the result of the W2A text conversion is used immediately. The destructor of W2A is called after the call to SetWindowTextA.

void ExampleFunctionW( LPCWSTR pWide)
{
  // Convert from Wide (Unicode) to ANSI and use the result.
  SetWindowTextA( W2A( pWide ) );    // The ANSI version of SetWindowText
}

Example 3 - Storing a result for later use.

This examples demonstrates some correct techniques for storing our text conversion result for later use. Note that we cannot simply store the pointer because it goes out of scope immediately.

void ExampleFunctionW( LPCWSTR pWide )
{
  // Store the result in a std::string
  std::string str = W2A( pWide ); // or std::string str = (LPCTSTR)W2A( pWide ); for some compilers

  // Store the result in an array
  char szArray[80];
  strcpy( szArray, W2A( pWide ) );

  // Store the result in a vector
  std::vector<char> MyAnsiVector(strlen(W2A(pWide))+1, '\0');
  strcpy(&MyAnsiVector.front(), W2A(pWide);

  // Do something with our stored string conversion
  // ...
}

Example 4 - Incorrect use of the text conversion function.

In this example the destructor for W2A is called before the call to SetWindowTextA. As a result, the contents of pAnsi are destroyed and the pointer no longer points to a valid character array.

void ExampleFunctionW( LPCWSTR pWide )
{
  // THIS IS INCORRECT!
  LPCSTR pAnsi = W2A( pWide );

  // W2A's destructor has already been called, so pAnsi is no longer points to a valid value.
  SetWindowTextA( pAnsi ); // Behaviour of this line is undefined!
}


Class Library Reference

Library Reference

Classes

CAnimation | A class used to create an animation control.
CBitmap | A class used to create a bitmap resource.
CBitmapInfoPtr | A class used to create the BITMAPINFO structure.
CBrush | A class used to create a brush resource.
CButton | A class used to create a button control.
CClientDC | The class used to device contect for the client area of the window.
CCmdBar | The class used to create a command bar control. (Windows CE only).
CComboBox | A class used to create a combo box control.
CComboBoxEx | A class used to create a ComboBoxEx control.
CContainer | A class used for docking tabbed window.
CCriticalSection | The class used for thread synchronisation.
CDateTime | This class is used to create a date and time picker control.
CDC | This class is used to simplify working with device contexts and GDI graphics.
CDialog | The class responsible for creating modal and modeless dialogs. It can also be used to create dialog applications.
CDockContainer | The class is used to create docking containers.
CDocker | The class used for a docking window. Docking windows can also be used as splitter windows.
CEdit | A class used to create an edit control.
CFile | A class used to read from and write to files.
CFont | A class used to create a font resource.
CFrame | The class used to create a frame window. The frame window has a menu, toolbar, and a status bar. The client area of the frame window is occupied by a separate CWnd window, often called the view window.
CGDIObject | The base class for GDI objects including CBitmap, CBrush, CFont, CPalette, CPen, and CRgn.
CHeader | A class used to create a header control.
CHotKey | A class used to create a hot key control.
CIPAddress | The class used to create an IP address control.
CListBox | A class used to create a list-box control.
CListView | A class that used to create a List-View control.
CMDIChild | The class for MDI child windows. All MDI children should be inherited from this class.
CMDIFrame | The class for MDI frames.
CMemDC | The class used to create memory device context.
CMenu | The class used to create and modify menus.
CMenuBar | The class used to create the menubar. A menubar is a specialized toolbar which mimics the behaviour of a menu. It is usually used within a rebar control.
CMetaFileDC | A class used to create metafile device context.
CMonthCalendar | A class used to create a month calendar control.
CPaintDC | A class used to create device context for the WM_PAINT message.
CPalette | A class used to create a palette resource.
CPen | A class used to create a pen resource.
CPoint | A class that can be used in place of a POINT structure.
CProgressBar | A class used to create a progress bar control.
CPropertyPage | The class used to create a property page. A property sheet has one or more property pages.
CPropertySheet | The class used to create a property sheet.
CReBar | The class used to create a rebar control.
CRect | A class that can be used in place of a RECT structure.
CRgn | A class used to create a region.
CRibbon | The class used to add a Window 7 ribbon framework to a window.
CRibbonFrame | The class used to create a frame window with a Window 7 ribbon framework. A menu and toolbar will be used if the operating system doesn't support the ribbon.
CScrollBar | A class used to create a scroll bar control.
CSize | A class that can be used in place of a SIZE structure.
CSlider | The class used to create a slider control (sometimes referred to as a track bar control).
CSocket | The class used for networking.
CSpinButton | The class used to create a spin button control (sometimes referred to as an up down control).
CStatic | The class used to create a static control.
CStatusBar | The class used to create a status bar.
CString | The class used to create and modify character strings.
CTab | The class used to create a Tab control.
CTabbedMDI | The class used for Tabbed MDI window.
CTaskDialog | The class used for to create a Task Dialog.
CThread | The class used to to create worker threads and GUI threads. A window can run in a GUI thread.
CToolBar | The class used to create a rebar control.
CToolTip | The class used to create a tool tip control.
CTreeView | A class used to create a Tree-View control.
CWceFrame | The class used to create a frame window on Pocket PCs. (Windows CE only).
CWebBrowser | The class used to create a web browser in a window.
CWinApp | The class responsible for initializing Win32++, and also provides the message loop. You inherit from this class to start the application.
CWindowDC | The class used to create a device context for the entire window, including the non-client area.
CWinException | A class which handles exceptions.
CWnd | The CWnd class represents a window. CWnd handles such things as window creation and window destruction, as well as determining how the window messages are handled.
Shared_Ptr | A smart pointer that can be used in a STL container such as a vector.

Global Functions

Defined in WinUtils.h
GetApp
CWinApp* GetApp();
 Returns a pointer to the CWinApp derrived class.
GetCursorPos
CPoint GetCursorPos();
 Returns a CPoint containing the cursor position.
GetComCtlVersion
int GetComCtlVersion();
 Returns an integer which indicates the version of of the ComCtl32.dll used.
GetSizeofMenuItemInfo
UINT GetSizeofMenuItemInfo();
 Returns the correct size of the MENUITEMINFO structure for all versions of windows.
GetSizeofNonClientMetrics
UINT GetSizeofNonClientMetrics();
 Returns the correct size of the NONCLIENTMETRICS structure for all versions of windows.
GetWinVersion
int GetWinVersion();
 Returns an integer indicating the version of windows running.
IsAeroThemed
BOOL IsAeroThemed();
 Returns TRUE if Aero themes are being used.
IsXPThemed
BOOL IsXPThemed();
 Returns TRUE if XP themes are being used.
IsLeftButtonDown
BOOL IsLeftButtonDown();
 Returns TRUE if the left mouse button is pressed.
lstrcpyn
LPTSTR lstrcpyn(LPTSTR lpstrDest, LPCTSTR lpstrSrc, int nLength);
 Copies a specified number of characters from a source string to a destination string. (Windows CE only).
LoadBitmap
HBITMAP LoadBitmap (LPCTSTR lpszName);
HBITMAP LoadBitmap (int nID);
 Retrieves a bitmap resource.
LoadString
CString LoadString(UINT nID);
 Retrieves a string resource and returns the result as a CString.
TRACE
void TRACE(LPCTSTR str);
 Sends a string to the debug/output pane, or an external debugger.
String Conversion Functions
A2BSTR | Converts an ANSI string to a BSTR string.
A2OLE | Converts an ANSI string to an OLE string.
A2T | Converts an ANSI string to a TCHAR string.
A2W | Converts an ANSI string to a WCHAR string.
OLE2A | Converts an OLE string to an ANSI string.
OLE2T | Converts an OLE string to a TCHAR string.
OLE2W | Converts an OLE string to a WCHAR string.
T2A | Converts a TCHAR string to an ANSI string.
T2BSTR | Converts a TCHAR string to a BSTR string.
T2OLE | Converts a TCHAR string to an OLE string.
T2W | Converts a TCHAR string to a WCHAR string.
W2A | Converts a WCHAR string to an ANSI string.
W2BSTR | Converts a WCHAR string to a BSTR string.
W2OLE | Converts a WCHAR string to an OLE string.
W2T | Converts a WCHAR string to a TCHAR string.
Defined in GDI.h
CreateDisabledImageList
HIMAGELIST CreateDisabledImageList( HIMAGELIST himlNormal );
Creates a gray scale image list from the specified color image list.
FromHandle
CDC* FromHandle(HDC hDC);
Returns the CDC object associated with the device context handle. If a CDC object doesn't already exist, a temporary CDC object is created. The HDC belonging to a temporary CDC is not released or destroyed when the temporary CDC is deconstructed..
FromHandle
CBitmap* FromHandle(HBITMAP hBitmap);
Returns the CBitmap associated with the Bitmap handle. If a CBitmap object doesn't already exist, a temporary CBitmap object is created. The HBITMAP belonging to a temporary CBitmap is not released or destroyed when the temporary CBitmap is deconstructed.
FromHandle
CBrush* FromHandle(HBRUSH hBrush);
Returns the CBrush associated with the Brush handle. If a CBrush object doesn't already exist, a temporary CBrush object is created. The HBRUSH belonging to a temporary CBrush is not released or destroyed when the temporary CBrush is deconstructed..
FromHandle
CFont* FromHandle(HFONT hFont);
Returns the CFont associated with the Font handle. If a CFont object doesn't already exist, a temporary CFont object is created. The HFONT belonging to a temporary CFont is not released or destroyed when the temporary CFont is deconstructed..
FromHandle
CPalette* FromHandle(HPALETTE hPalette);
Returns the CPalette associated with the palette handle. If a CPalette object doesn't already exist, a temporary CPalette object is created. The HPALETTE belonging to a temporary CPalette is not released or destroyed when the temporary CPalette is deconstructed..
FromHandle
CPen* FromHandle(HPEN hPen);
Returns the CPen associated with the HPEN. If a CPen object doesn't already exist, a temporary CPen object is created. The HPEN belonging to a temporary CPen is not released or destroyed when the temporary CPen is deconstructed..
FromHandle
CRgn* FromHandle(HRGN hRgn);
Returns the CRgn associated with the HRGN. If a CRgn object doesn't already exist, a temporary CRgn object is created. The HRGN belonging to a temporary CRgn is not released or destroyed when the temporary CRgn is deconstructed..
GrayScaleBitmap
void GrayScaleBitmap(HBITMAP hbmSource);
Creates a gray scale bitmap from the specified bitmap.
TintBitmap
HIMAGELIST CreateDisabledImageList( HIMAGELIST himlNormal );
Modifies the colour of the supplied Device Dependant Bitmap, by the colour correction values specified. The correction values can range from -255 to +255.

Macros

GET_X_LPARAM | Retrieves the signed x-coordinate from the given LPARAM value.
GET_Y_LPARAM | Retrieves the signed y-coordinate from the given LPARAM value.
MAX | Returns the higher of two values.
MIN | Returns the lower of two values.
NO_USING_NAMESPACE | Define this macro to suppress using the Win32xx namespace.

Type declarations

tString | typedef std::basic_string<TCHAR> tString;
tStringStream | typedef std::basic_stringstream<TCHAR> tStringStream;


CAnimation

CAnimation Class

Description

The CAnimation class adds support for the Animation control. An animation control is a rectangular window that displays an AVI (Audio Video Interleaved) format. An AVI clip is a series of bitmap frames, like a movie. Animation controls can only display AVI clips that do not contain audio.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of animation controls.

CAnimation Members

CAnimation
CAnimation();
Constructs a CAnimation control.
Close
BOOL Close() const;
Closes an AVI clip.
Open
BOOL Open(LPTSTR lpszName) const;
Opens an AVI clip and displays its first frame in an animation control.
Play
BOOL Play(UINT uFrom, UINT uTo, UINT cRepeat) const;
Plays an AVI clip in an animation control. The control plays the clip in the background while the thread continues executing.
Seek
BOOL Seek(UINT uFrame) const;
Directs an animation control to display a particular frame of an AVI clip. The control displays the clip in the background while the thread continues executing.
Stop
BOOL Stop() const;
Stops playing an AVI clip in an animation control.
Overridables
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

The AVI clip can be added to the application as a resource, or it can be separate file. Only simple AVI files supported by the Windows API animation control can be played.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CBitmap

CBitmap Class

Description

The class responsible for creating and managing bitmap resources.

CBitmap Members

Initialization and Assignment
CBitmap
CBitmap();
CBitmap(HBITMAP hBitmap);
CBitmap(LPCTSTR lpstr);
CBitmap(int nID);
Constructs a CBitmap object.
operator HBITMAP()
operator HBITMAP() const;
Allows a CBitmap object to be used as a bitmap handle (HBITMAP).
Attributes
GetBitmapData
BITMAP GetBitmapData() const;
Retrieves the BITMAP structure of the attached bitmap.
GetBitmapDimensionEx
CSize GetBitmapDimensionEx() const;
Retrieves the dimensions of a compatible bitmap. The retrieved dimensions must have been set by the SetBitmapDimensionEx function.
GetDIBits
int GetDIBits(CDC* pDC, UINT uStartScan, UINT cScanLines,
              LPVOID lpvBits, LPBITMAPINFO lpbmi, UINT uColorUse) const;
Retrieves the bits of the specified compatible bitmap and copies them into a buffer as a DIB using the specified format.
SetBitmapDimensionEx
CSize SetBitmapDimensionEx(int nWidth, int nHeight);
Assigns preferred dimensions to a bitmap. These dimensions can be used by applications; however, they are not used by the system.
SetDIBits
int SetDIBits(CDC* pDC, UINT uStartScan, UINT cScanLines,
              CONST VOID* lpvBits, CONST BITMAPINFO* lpbmi, UINT uColorUse);
Sets the pixels in a compatible bitmap (DDB) using the color data found in the specified DIB.
Operations
CreateBitmap
HBITMAP CreateBitmap(int nWidth, int nHeight, UINT nPlanes,
                      UINT nBitsPerPixel, LPCVOID lpBits);
Creates a bitmap with the specified width, height, and color format (color planes and bits-per-pixel).
CreateBitmapIndirect
HBITMAP CreateBitmapIndirect(LPBITMAP lpBitmap);
Creates a bitmap with the width, height, and color format specified in the BITMAP structure.
CreateCompatibleBitmap
HBITMAP CreateCompatibleBitmap(CDC* pDC, int nWidth, int nHeight);
Creates a bitmap compatible with the device that is associated with the specified device context.
CreateDIBitmap
HBITMAP CreateDIBitmap(CDC* pDC, CONST BITMAPINFOHEADER* lpbmih, DWORD dwInit,
                       LPCVOID lpbInit, CONST BITMAPINFO* lpbmi, UINT uColorUse);
Creates a compatible bitmap (DDB) from a DIB and, optionally, sets the bitmap bits.
CreateDIBSection
HBITMAP CreateDIBSection(CDC* pDC, CONST BITMAPINFO* lpbmi, UINT uColorUse,
                         LPVOID* ppvBits, HANDLE hSection, DWORD dwOffset);
Creates a DIB that applications can write to directly. The function gives you a pointer to the location of the bitmap bit values.
CreateMappedBitmap
HBITMAP CreateMappedBitmap(UINT nIDBitmap, UINT nFlags = 0,
                          LPCOLORMAP lpColorMap = NULL, int nMapSize = 0);
Creates a new bitmap using the bitmap data and colors specified by the bitmap resource and the color mapping information.
LoadBitmap
BOOL LoadBitmap(LPCTSTR lpszName);
BOOL LoadBitmap(int nID);
Loads a bitmap from a resource using the resource string.
LoadImage
BOOL LoadImage(LPCTSTR lpszName, int cxDesired, int cyDesired, UINT fuLoad);
BOOL LoadImage(UINT nID, int cxDesired, int cyDesired, UINT fuLoad);
Loads a bitmap from a resource using the resource ID.
LoadOEMBitmap
BOOL LoadOEMBitmap(UINT nIDBitmap);
Loads a predefined bitmap.
Base class Members

For base class members, refer to the members of CGDIObject.

Remarks

CBitmap objects can be used anywhere a a handle to a brush (HBITMAP) might be used. They can be substituted for the HBITMAP in any of the Windows API functions which use a HBITMAP as a function argument. The benefit of using a CBitmap object is that it automatically deletes the brush when it is destroyed.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CBitmapInfoPtr

CBitmapInfoPtr Class

Description

The CBitmapInfoPtr class simplifies the creation and use of the BITMAPINFO structure. The BITMAPINFO structure is used in the GetDIBits and SetDIBits Window API functions.

Remarks

The traditional BITMAPINFO structure is defined like this.

typedef struct tagBITMAPINFO {
  BITMAPINFOHEADER bmiHeader;
  RGBQUAD         bmiColors[1];
} BITMAPINFO, *PBITMAPINFO;

The thing that makes the traditional BITMAPINFO structure difficult to use is that the bmiColors member is an array. This array has a different number of elements depending on the color depth of the Bitmap. As a result the bmiColors member needs to be created dynamically on the heap before the structure can be declared. CBitmapInfoPtr takes care of these details for for us.

To use CBitmapInfoPtr, simply construct its object by providing a handle (HBITMAP) to the bitmap in its constructor. The CBitmapInfoPtr object can then be used anywhere in place of a pointer to BITMAPINFO. The following example demonstrates the use of CBitmapInfoPtr.

// Create our LPBITMAPINFO object
CBitmapInfoPtr pbmi(hbmSource);

// Create the DC for GetDIBits to use
CDC MemDC = CreateCompatibleDC(NULL);

// Use GetDIBits to create a DIB from our DDB, and extract the colour data
MemDC.GetDIBits(hbmSource, 0, pbmi->bmiHeader.biHeight, NULL, pbmi, DIB_RGB_COLORS);

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CBrush

CBrush Class

Description

The class responsible for creating and managing brush resources.

CBrush Members

Initialization and Assignment
CBrush
CBrush();
CBrush(HBRUSH hBrush);
CBrush(COLORREF crColor);
Constructs a CBrush object.
operator HBRUSH()
operator HBRUSH() const;
Allows a CBrush object to be used as a brush handle (HBRUSH).
Attributes
GetLogBrush
LOGBRUSH GetLogBrush() const;
Retrieves the LOGBRUSH structure that defines the style, color, and pattern of a physical brush.
Operations
CreateBrushIndirect
HBRUSH CreateBrushIndirect(LPLOGBRUSH lpLogBrush);
Creates a logical brush from style, color, and pattern specified in the LOGPRUSH struct.
CreateDIBPatternBrush
HBRUSH CreateDIBPatternBrush(HGLOBAL hglbDIBPacked, UINT fuColorSpec);
Creates a logical brush that has the pattern specified by the device-independent bitmap (DIB).
CreateDIBPatternBrushPt
HBRUSH CreateDIBPatternBrushPt(LPCVOID lpPackedDIB, UINT nUsage);
Creates a logical brush that has the pattern specified by the device-independent bitmap (DIB).
CreateHatchBrush
HBRUSH CreateHatchBrush(int nIndex, COLORREF crColor);
Creates a logical brush that has the specified hatch pattern and color.
CreatePatternBrush
HBRUSH CreatePatternBrush(CBitmap* pBitmap);
Creates a logical brush with the specified bitmap pattern. The bitmap can be a DIB section bitmap, which is created by the CreateDIBSection function, or it can be a device-dependent bitmap.
CreateSolidBrush
HBRUSH CreateSolidBrush(COLORREF crColor);
Creates a logical brush that has the specified solid color.
Base class Members

For base class members, refer to the members of CGDIObject.

Remarks

CBrush objects can be used anywhere a a handle to a brush (HBRUSH) might be used. They can be substituted for the HBRUSH in any of the Windows API functions which use a HBRUSH as a function argument. The benefit of using a CBrush object is that it automatically deletes the brush when it is destroyed.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CButton

CButton Class

Description

A button is a control the user can click to provide input to an application. The button control provides several types of buttons, including Push Buttons, Check Boxes and Radio Buttons.

CButton is the class responsible for creating a button control. It is typically used in a Dialog, but could also by a child of another window.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of button controls.

CButton Members

Construction

CButton
CButton();
Constructor for CButton.

Attributes

GetBitmap
HBITMAP GetBitmap() const;
Returns a handle to the bitmap associated with the button.
GetButtonStyle
UINT GetButtonStyle() const;
Returns the button style. This can be a combination of possible button styles.
GetCheck
int GetCheck() const;
Returns the check state of the a radio button or check box.
GetCursor
HCURSOR GetCursor() const;
Returns a handle to the cursor associated with the button.
GetIcon
HICON GetIcon() const;
Returns a handle to the Icon associated with the button.
GetState
UINT GetState() const;
Returns the state of the button (pushed, checked focused etc).
SetBitmap
HBITMAP SetBitmap(HBITMAP hBitmap) const;
Sets the bitmap associated with the button.
SetButtonStyle
void SetButtonStyle(DWORD dwStyle, BOOL bRedraw) const;
Sets the style of the button.
SetCheck
void SetCheck(int nCheckState) const;
Sets the check state of the a radio button or check box.
SetCursor
HCURSOR SetCursor(HCURSOR hCursor) const;
Sets the cursor associated with the button.
SetIcon
HICON SetIcon(HICON hIcon) const;
Sets the Icon associated with the button.
SetState
void SetState(BOOL bHighlight) const;
Sets the state of the button.

Overridables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the button control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a button control.

Refer to the DialogDemo sample to see a demonstration of the CButton class.

Summary Information

Header file | stdcontrols.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CClientDC

CClientDC Class

Description

The class responsible for creating a device context for the client area of a window.

CClientDC Members

Initialization and Assignment

Initialization and Assignment
CClientDC
CClientDC(const CWnd* pWnd);
Constructs a CClientDC object.
Base class Members

For base class members, refer to the members of CDC.

Remarks

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CCmdBar

CCmdBar Class

Description

The class responsible for creating a Commandbar control. A Commandbar control is supported on the Windows CE operating system. It is not supported on the Win32/64 operating systems.

The command bar is unique to Windows CE. It combines a menu bar, toolbar, and an optional address bar. Windows CE supports multiple command bars, each containing gripper controls that enable users to hide buttons and menus. Command bars can contain combo boxes, edit boxes, and buttons, as well as other types of controls. They also can include the Close (X) button, the Help (?) button, and the OK button.

CCmdBar Members

CCmdBar
CCmdBar();
Constructor for CCmdBar.
AddAdornments
BOOL AddAdornments(DWORD dwFlags);
Adds a button, and optionally, Help and OK buttons, to the command bar.
AddBitmap
int AddBitmap(int idBitmap, int iNumImages, int iImageWidth, int iImageHeight);
Adds one or more images to the list of button images available in the command bar.
AddButtons
BOOL AddButtons(int nButtons, TBBUTTON* pTBButton);
Adds one or more toolbar buttons to a command bar control.
GetHeight
int GetHeight() const;
Retrieves the height of the command bar in pixels.
InsertComboBox
HWND InsertComboBox(int iWidth, UINT dwStyle, WORD idComboBox, WORD iButton);
Inserts a combo box into the command bar.
IsVisible
BOOL IsVisible();
Retrieves the visibility state of the command bar.
Show
BOOL Show(BOOL fShow);
Shows or hides the command bar.
Base class Members

For base class members, refer to the members of CWnd.

Summary Information

Header file | wceframe.h
Win32/64 support | No
WinCE support | Yes


CComboBox

CComboBox Class

Description

The CComboBox class is used to create and manage a ComboBox control. A ComboBox control displays a drop-down list of predefined values and an edit field into which the user can enter a value.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of combo box controls.

CComboBox Members

CComboBox
CComboBox();
Constructor for the CComboBox.
AddString
int AddString(LPCTSTR lpszString) const;
Adds a string to the list.
Clear
void Clear() const;
Deletes the edit selection.
Copy
void Copy() const;
Copies the edit selection to the clipboard.
Cut
void Cut() const;
Deletes the edit selection and places it on the clipboard.
DeleteString
int DeleteString(int nIndex) const;
Deletes a string from the list.
Dir
int Dir(UINT attr, LPCTSTR lpszWildCard ) const;
Adds the file names matching the specified attributes and path to the list.
FindString
int FindString(int nIndexStart, LPCTSTR lpszString) const;
Searches the list box of the combo box for an item beginning with the characters in a specified string.
FindStringExact
int FindStringExact(int nIndexStart, LPCTSTR lpszString) const;
Returns the index of the firs list item exactly matching the specified string.
GetCount
int GetCount() const;
Returns the number of list items.
GetCurSel
int GetCurSel() const;
Returns the index of the currently selected item, if any.
GetDroppedControlRect
CRect GetDroppedControlRect() const;
Fills the specified rectangle structure with the screen coordinates of a drop-down list.
GetDroppedState
BOOL GetDroppedState() const;
Returns TRUE of a drop-down list is open, otherwise it returns FALSE.
GetDroppedWidth
int GetDroppedWidth() const;
Returns the minimum allowable width, in pixels, of the drop-down list.
GetEditSel
DWORD GetEditSel() const;
Returns the starting and ending position of the current selection.
GetExtendedUI
BOOL GetExtendedUI() const;
Returns TRUE if the combo box is a drop-down combo box or drop-down list box and the user-interface flag is set, otherwise it returns FALSE.
GetHorizontalExtent
int GetHorizontalExtent() const;
Returns the scrollable width, in pixels, of the drop-down list.
GetItemData
DWORD GetItemData(int nIndex) const;
Returns the value associated with the specified list item.
GetItemHeight
int GetItemHeight(int nIndex) const;
Returns the height, in pixels, of the specified owner-drawn list item.
GetLBText
int GetLBText(int nIndex, LPTSTR lpszText) const;
Copies the specified list text to the specified buffer.
GetLBTextLen
int GetLBTextLen(int nIndex) const;
Returns the length, in TCHARs, of the specified list text.
GetLocale
LCID GetLocale() const;
Returns the current locale for the list.
GetTopIndex
int GetTopIndex() const;
Returns the index of the first visible item in the drop-down list.
InitStorage
int InitStorage(int nItems, int nBytes) const;
Initializes space for the specified number of items and the specified number of bytes for item strings.
InsertString
int InsertString(int nIndex, LPCTSTR lpszString) const;
Inserts a list item at the specified position.
LimitText
void LimitText(int nMaxChars) const;
Sets the maximum number of characters a user can enter in the edit control.
Paste
void Paste() const;
Replaces the edit selection with the contents of the clipboard.
ResetContent
void ResetContent() const;
Removes the contents of the list.
SelectString
int SelectString(int nStartAfter, LPCTSTR lpszString) const;
Selects the first list item, if any, that begins with the characters in the specified text.
SetCurSel
int SetCurSel(int nIndex) const;
Sets the current selection.
SetDroppedWidth
int SetDroppedWidth(int nWidth) const;
Sets the minimum allowable width, in pixels, of the drop-down list.
SetEditSel
BOOL SetEditSel(int nStartChar, int nEndChar) const;
Selects the specified range of text.
SetExtendedUI
int SetExtendedUI(BOOL bExtended = TRUE) const;
Sets or cleats the extended user-interface flag. This flag changes the keys that open and close the list in a drop-down list.
SetHorizontalExtent
void SetHorizontalExtent(UINT nExtent ) const;
Sets the scrollable width, in pixels, of the drop-down list.
SetItemData
int SetItemData(int nIndex, DWORD dwItemData) const;
Associates the specified value with a list item.
SetItemHeight
int SetItemHeight(int nIndex, UINT cyItemHeight) const;
Sets the height of the specified owner-drawn list item or the selection field.
SetLocale
LCID SetLocale( LCID NewLocale ) const;
Sets the current local for the list.
SetTopIndex
SetTopIndex(int nIndex) const;
Scroll the drop-down list so the specified item is at the top of the visible range.
ShowDropDown
void ShowDropDown(BOOL bShow = TRUE) const;
Shows or hide the drop-down list.

Overridables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the combobox control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for an combobox control.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes


CComboBoxEx

CComboBoxEx Class

Description

The CComboBoxEx class is used to create and manage a ComboBoxEx control. ComboBoxEx controls are an extension of the combo box control that provides native support for item images.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of ComboBoxEx controls.

CComboBoxEx Members

CComboBoxEx
CComboBoxEx();
Constructor for the ComboBoxEx.
DeleteItem
int DeleteItem(int nIndex ) const;
Removes an item.
GetComboBoxCtrl
CWnd* GetComboBoxCtrl() const;
Retrieves the handle to the child combo box control.
GetEditCtrl
CEdit* GetEditCtrl() const;
Retrieves the handle to the edit control portion of a ComboBoxEx control.
GetExtendedStyle
DWORD GetExtendedStyle() const;
Retrieves the extended style that are in use for a ComboBoxEx control.
GetImageList
HIMAGELIST GetImageList() const;
Retrieves the handle to the image list assigned to the ComboBoxEx control.
GetItem
BOOL GetItem(COMBOBOXEXITEM* pCBItem) const;
Retrieves item information for a given ComboBoxEx item.
HasEditChanged
BOOL HasEditChanged () const;
Returns TRUE if the use has changed text of the ComboBoxEx edit control.
InsertItem
int InsertItem(COMBOBOXEXITEM* lpcCBItem) const;
Inserts a new item in the ComboBoxEx control.
SetExtendedStyle
DWORD SetExtendedStyle(DWORD dwExMask, DWORD dwExStyles ) const;
Sets the extend styles for the ComboBoxEx controls.
SetImageList
HIMAGELIST SetImageList(HIMAGELIST himl) const;
Sets the image list for the ComboBoxEx control.
SetItem
BOOL SetItem(PCOMBOBOXEXITEM lpcCBItem) const;
Sets the attributes for an item of the ComboBoxEx control.

Overridables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the ComboBoxEx control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a ComboBoxEx control.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes


CCriticalSection

CCriticalSection Class

Description

Critical sections are a feature of the Windows API. They are used to prevent a section of code from being executed by more than one thread at a time. Once a thread has locked a critical section, any other thread wishing to execute that code must wait until the critical section is released so it can lock the critical section.

For example, we might wish to prevent a situation where one thread is changing a global variable while another thread is using it. The CCriticalSection class provides a convenient and object orientated approach to using critical sections. It is used internally by the Win32++ library, but will also be useful to developers when coding their own multi-threaded applications.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of critical sections to assist with synchronisation in multi-threaded applications.

CCriticalSection Members

CCriticalSection
CCriticalSection();
Constructor for CCriticalSection.
Lock
void Lock();
Enter a critical section. Only one thread at a time runs code protected by a critical section.
Release
void Release();
Leave a critical section.

Remarks

The following example demonstrates the use of CCriticalSection.

// m_csVar is a class member variable of type CCriticalSection

// Lock the critical section while we change its value
m_csVar.Lock();

// Modify the global variable
g_Var = 10;

// Release the critical section
m_csVar.Release();

// Note: we would also protect any reads from the global
// variable with the same m_csVar CCriticalSection

Summary Information

Header file | wincore.h
Win32/64 support | Yes
WinCE support | Yes


CDateTime

CDateTime Class

Description

The CDateTime class adds support for the date and time picker control. A date and time picker (DTP) control provides a simple and intuitive interface through which to exchange date and time information with a user.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of date and time picker controls.

CDateTime Members

Construction
CDateTime
CDateTime();
Constructs the date and time picker control.
Attributes
GetMonthCalColor
COLORREF GetMonthCalColor(int iColor) const;
Gets the color for a given portion of the month calendar within a date and time picker (DTP) control.
GetMonthCalCtrl
MonthCalendar* GetMonthCalCtrl() const;
Gets the handle to a date and time picker's (DTP) child month calendar control.
GetMonthCalFont
CFont* GetMonthCalFont() const;
Gets the font that the date and time picker (DTP) control's child month calendar control is currently using.
GetRange
DWORD GetRange(LPSYSTEMTIME lpSysTimeArray) const;
Gets the current minimum and maximum allowable system times for a date and time picker (DTP) control.
GetTime
DWORD GetTime(LPSYSTEMTIME pTimeDest) const;
Gets the currently selected time from a date and time picker (DTP) control and places it in a specified SYSTEMTIME structure.
SetMonthCalColor
COLORREF SetMonthCalColor(int iColor, COLORREF ref);
Sets the color for a given portion of the month calendar within a date and time picker (DTP) control.
SetFormat
BOOL SetFormat(LPCTSTR pstrFormat);
Sets the display of a date and time picker (DTP) control based on a given format string.
SetMonthCalFont
void SetMonthCalFont(HFONT hFont, BOOL bRedraw = TRUE);
Sets the font to be used by the date and time picker (DTP) control's child month calendar control.
SetRange
BOOL SetRange(DWORD flags, LPSYSTEMTIME lpSysTimeArray);
Sets the minimum and maximum allowable system times for a date and time picker (DTP) control.
SetTime
BOOL SetTime(DWORD flag, LPSYSTEMTIME pTimeNew = NULL);
Sets a date and time picker (DTP) control to a given date and time.
Overridables
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Sets a date and time picker (DTP) control to a given date and time.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Date and time picker (DTP) controls have several Date and Time Picker Control Styles that determine a control's appearance and behavior. Specify the style when creating the control with the dwStyle parameter of CreateWindowEx. To retrieve or change the window style after you have created the control, use GetWindowLong and SetWindowLong.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CDC

CDC Class

Description

A device context is a Windows data structure containing 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, which encapsulates the Windows APIs for drawing lines, shapes, and text. Device contexts allow device-independent drawing in Windows.

The CDC class provides a GDI device context, along with a set of member functions to perform the various tasks with the device context. Member functions can also be used to create the various GDI objects, such as brushes and pens. Alternatively, GDI objects can be attached to the device context using SelectObject.

CDC Members

Initialisation and Assignment
CDC
CDC();
CDC(HDC hDC, HWND hWnd = 0);
Constructor for CDC.
Attach
void Attach(HDC hDC);
Attach an existing device context to the CDC object.
Detach
HDC Detach();
Detach a device context from the CDC object. The device context will be destroyed when the CDC is destroyed, unless it is detached.
GetHDC
HDC GetHDC() const;
Returns the Device Context associated with this CDC object.
operator HDC ()
operator HDC() const;
Allow a CDC object to be used as a handle to a device context (HDC).
operator HDC =
void operator = (const HDC hDC);
Used to assign a HDC to a CDC when it is created.
Create and Select Bitmaps
SelectObject
CBitmap* SelectObject(const CBitmap* pBitmap);
Attach an existing bitmap to the CDC.
CreateBitmap
void CreateBitmap(int cx, int cy, UINT Planes, UINT BitsPerPixel, LPCVOID pvColors);
Creates a bitmap with the specified width, height, and color format (color planes and bits-per-pixel).
CreateBitmapIndirect
void CreateBitmapIndirect(LPBITMAP pBitmap);
Creates a bitmap with the specified width, height, and color format (color planes and bits-per-pixel), specified in the BITMAP struct.
CreateCompatibleBitmap
void CreateCompatibleBitmap(CDC* pDC, int cx, int cy);
Creates a bitmap compatible with the device that is associated with the specified device context.
CreateDIBSection
void CreateDIBSection(CDC* pDC, const BITMAPINFO& bmi, UINT iUsage,
                 LPVOID *ppvBits, HANDLE hSection, DWORD dwOffset);
Creates a DIB that applications can write to directly. The function gives you a pointer to the location of the bitmap bit values. You can supply a handle to a file-mapping object that the function will use to create the bitmap, or you can let the system allocate the memory for the bitmap.
CreateDIBitmap
void CreateDIBitmap(CDC* pDC, const BITMAPINFOHEADER& bmih,
           DWORD fdwInit, LPCVOID lpbInit, BITMAPINFO& bmi, UINT fuUsage);
Creates a compatible bitmap (DDB) from a DIB and, optionally, sets the bitmap bits.
CreateMappedBitmap
void CreateMappedBitmap(UINT nIDBitmap, UINT nFlags /*= 0*/,
                       LPCOLORMAP lpColorMap /*= NULL*/, int nMapSize /*= 0*/);
Creates a bitmap for use in a toolbar.
DetachBitmap
CBitmap DetachBitmap();
Provides a convenient method of detaching a bitmap from a memory device context.
GetBitmapData
BITMAP GetBitmapData() const;
Retrieves the current bitmap information.
LoadBitmap
BOOL LoadBitmap(UINT nID);
BOOL LoadBitmap(LPCTSTR lpszName);
Loads the specified bitmap resource from a module's executable file.
LoadImage
BOOL LoadImage(UINT nID, int cxDesired, int cyDesired, UINT fuLoad);
BOOL LoadImage(LPCTSTR lpszName, int cxDesired, int cyDesired, UINT fuLoad);
Loads the specified bitmap resource from a module's executable file.
LoadOEMBitmap
BOOL LoadOEMBitmap(UINT nIDBitmap);
Loads a predefined bitmap used by Windows.
Create and Select Brushes
SelectObject
CBrush* SelectObject(const CBrush* pBrush);
Attach an existing brush to the CDC.
CreateBrushIndirect
void CreateBrushIndirect(LPLOGBRUSH pLogBrush);
Creates a logical brush that has the specified style, color, and pattern.
CreateDIBPatternBrush
void CreatePatternBrush(HBITMAP hbmp);
Creates a logical brush that has the pattern specified by the specified device-independent bitmap (DIB).
CreateDIBPatternBrushPt
void CreateDIBPatternBrushPt(LPCVOID lpPackedDIB, UINT iUsage);
Creates a logical brush that has the pattern specified by the device-independent bitmap (DIB).
CreateHatchBrush
void CreateHatchBrush(int fnStyle, COLORREF rgb);
Creates a logical brush that has the specified hatch pattern and color.
CreatePatternBrush
void CreatePatternBrush(CBitmap* pBitmap);
Creates a logical brush with the specified bitmap pattern.
CreateSolidBrush
void CreateSolidBrush(COLORREF rbg);
Creates a logical brush that has the specified solid color.
GetLogBrush
LOGBRUSH GetLogBrush() const;
Retrieves the current brush information.
Create and Select Fonts
SelectObject
CFont* SelectObject(const CFont* pFont);
Attach an existing font to the CDC.
CreateFont
void CreateFont(int nHeight, int nWidth, int nEscapement, int nOrientation, int fnWeight,
          DWORD fdwItalic, DWORD fdwUnderline, DWORD fdwStrikeOut, DWORD fdwCharSet,
          DWORD fdwOutputPrecision, DWORD fdwClipPrecision, DWORD fdwQuality,
          DWORD fdwPitchAndFamily, LPCTSTR lpszFace);
Creates a logical font with the specified characteristics.
CreateFontIndirect
void CreateFontIndirect(LPLOGFONT plf);
Creates a logical font that has the specified characteristics.
GetLogFont
LOGFONT GetLogFont() const;
Retrieves the current font information.
Create and Select Palettes
SelectPalette
CPalette* SelectPalette(const CPalette* pPalette, BOOL bForceBkgnd);
Attach an existing palette to the CDC.
Create and Select Pens
SelectObject
CPen* SelectObject(const CPen* pPen);
Attach an existing pen to the CDC.
CreatePen
void CreatePen(int nStyle, int nWidth, COLORREF rgb);
Creates a logical pen that has the specified style, width, and color.
CreatePenIndirect
void CreatePenIndirect(LPLOGPEN pLogPen);
Creates a logical cosmetic pen that has the style, width, and color specified in a structure.
GetLogPen
LOGPEN GetLogPen();
Retrieves the current pen information.
Create and Select Regions
CreateRectRgn
int CreateRectRgn(int left, int top, int right, int bottom);
Creates a rectangular region from the specified rectangle co-ordinates.
CreateRectRgnIndirect
int CreateRectRgnIndirect(const RECT& rc);
Creates a rectangular region from a specified RECT.
CreateEllipticRgn
int CreateEllipticRgn(int left, int top, int right, int bottom);
Creates an elliptical region from the specified rectangle co-ordinates.
CreateEllipticRgnIndirect
int CreateEllipticRgnIndirect(const RECT& rc);
Creates an elliptical region from the specified RECT.
CreatePolygonRgn
int CreatePolygonRgn(LPPOINT ppt, int cPoints, int fnPolyFillMode);
Creates a polygonal region from an array of points.
CreatePolygonRgn
int CreatePolyPolygonRgn(LPPOINT ppt, LPINT pPolyCounts,
                         int nCount, int fnPolyFillMode);
Creates a polygonal region from an array of points.

Wrappers for Window API functions

Initialization

CreateCompatibleDC
BOOL CreateCompatibleDC(CDC* pDC);
Creates a memory device context (DC) compatible with the specified device.
CreateDC
BOOL CreateDC(LPCTSTR lpszDriver, LPCTSTR lpszDevice,
        LPCTSTR lpszOutput, const DEVMODE* pInitData);
Creates a device context (DC) for a device using the specified name.
CreateIC
BOOL CreateIC(LPCTSTR lpszDriver, LPCTSTR lpszDevice,
         LPCTSTR lpszOutput, const DEVMODE* pInitData);
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 (DC).
GetDeviceCaps
int GetDeviceCaps(int nIndex) const;
Retrieves device-specific information for the specified device.
Point and Line Drawing Functions
GetCurrentPositition
CPoint GetCurrentPosition() const;
Returns the current drawing position.
MoveTo
CPoint MoveTo(int x, int y) const;
CPoint MoveTo(POINT pt) const;
Updates the current position to the specified point.
LineTo
BOOL LineTo(int x, int y) const;
BOOL LineTo(POINT pt) const;
Draws a line from the current position up to, but not including, the specified point.
GetPixel
COLORREF GetPixel(int x, int y) const;
COLORREF GetPixel(POINT pt) const;
Retrieves the red, green, blue (RGB) color value of the pixel at the specified coordinates.
SetPixel
COLORREF SetPixel(int x, int y, COLORREF crColor) const;
COLORREF SetPixel(POINT pt, COLORREF crColor) const;
Sets the pixel at the specified coordinates to the specified color.
Arc
BOOL Arc(int x1, int y1, int x2, int y2, int x3,
         int y3, int x4, int y4) const;
BOOL Arc(RECT& rc, POINT ptStart, POINT ptEnd) const;
Draws an elliptical arc.
ArcTo
BOOL ArcTo(int x1, int y1, int x2, int y2,
        int x3, int y3, int x4, int y4) const;
BOOL ArcTo(RECT& rc, POINT ptStart, POINT ptEnd) const;
Draws an elliptical arc.
AngleArc
BOOL AngleArc(int x, int y, int nRadius, float fStartAngle,
              float fSweepAngle) const;
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.
GetArcDirection
int GetArcDirection() const;
Retrieves the current arc direction for the specified device context. Arc and rectangle functions use the arc direction.
SetArcDirection
int SetArcDirection(int nArcDirection) const;
Sets the drawing direction to be used for arc and rectangle functions.
PolyDraw
BOOL PolyDraw(const POINT* lpPoints, const BYTE* lpTypes, int nCount) const;
Draws a set of line segments and Bzier curves.
Polyline
BOOL Polyline(LPPOINT lpPoints, int nCount) const;
Draws a series of line segments by connecting the points in the specified array.
PolyPolyline
BOOL PolyPolyline(const POINT* lpPoints, const DWORD* lpPolyPoints,
                 int nCount) const;
Draws multiple series of connected line segments.
PolylineTo
BOOL PolylineTo(const POINT* lpPoints, int nCount) const;
Draws one or more straight lines.
PolyBezier
BOOL PolyBezier(const POINT* lpPoints, int nCount) const;
Draws one or more Bezier curves.
PolyBezierTo
BOOL PolyBezierTo(const POINT* lpPoints, int nCount) const;
Draws one or more Bzier curves.
SetPixelV
BOOL SetPixelV(int x, int y, COLORREF crColor) const;
BOOL SetPixelV(POINT pt, COLORREF crColor) const;
Sets the pixel at the specified coordinates to the closest approximation of the specified color.
Shape Drawing Functions
Chord
BOOL Chord(int x1, int y1, int x2, int y2,
           int x3, int y3, int x4, int y4) const;
BOOL Chord(const RECT& rc, POINT ptStart, POINT ptEnd) const;
Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a secant). The chord is outlined by using the current pen and filled by using the current brush..
DrawFocusRect
void DrawFocusRect(const RECT& rc) const;
Draws a rectangle in the style used to indicate that the rectangle has the focus.
Ellipse
BOOL Ellipse( int x1, int y1, int x2, int y2 ) const;
BOOL Ellipse(const RECT& rc) const;
Draws an ellipse. The center of the ellipse is the center of the specified bounding rectangle. The ellipse is outlined by using the current pen and is filled by using the current brush.
Pie
BOOL Pie(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) const;
BOOL Pie(const RECT& rc, POINT ptStart, POINT ptEnd) const;
Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials. The pie is outlined by using the current pen and filled by using the current brush.
Polygon
BOOL Polygon(LPPOINT lpPoints, int nCount) const;
Draws a polygon consisting of two or more vertices connected by straight lines. The polygon is outlined by using the current pen and filled by using the current brush and polygon fill mode.
PolyPolygon
BOOL PolyPolygon(LPPOINT lpPoints, LPINT lpPolyCounts, int nCount) const;
Draws a series of closed polygons. Each polygon is outlined by using the current pen and filled by using the current brush and polygon fill mode. The polygons drawn by this function can overlap.
Rectangle
BOOL Rectangle(int x1, int y1, int x2, int y2) const;
BOOL Rectangle( const RECT& rc ) const;
Draws a rectangle. The rectangle is outlined by using the current pen and filled by using the current brush.
RoundRect
BOOL RoundRect(int x1, int y1, int x2, int y2, int nWidth, int nHeight) const;
BOOL RoundRect(const RECT& rc, int nWidth, int nHeight) const;
Draws a rectangle with rounded corners. The rectangle is outlined by using the current pen and filled by using the current brush.
Fill and Image Drawing functions
FillRect
BOOL FillRect(const RECT& rc, CBrush* pBrushr) const;
Fills a rectangle by using the specified brush. This function includes the left and top borders, but excludes the right and bottom borders of the rectangle.
InvertRect
BOOL InvertRect(const RECT& rc) const;
Inverts a rectangle in a window by performing a logical NOT operation on the color values for each pixel in the rectangle's interior.
DrawIconEx
BOOL DrawIconEx(int xLeft, int yTop, HICON hIcon, int cxWidth, int cyWidth,
             INT istepIfAniCur, CBrush* pFlickerFreeDraw, UINT diFlags) const;
Draws an icon or cursor into the specified device context, performing the specified raster operations, and stretching or compressing the icon or cursor as specified.
DrawEdge
BOOL DrawEdge(const RECT& rc, UINT nEdge, UINT nFlags) const;
Draws one or more edges of rectangle.
DrawFrameControl
BOOL DrawFrameControl(const RECT& rc, UINT nType, UINT nState) const;
Draws a frame control of the specified type and style.
FillRgn
BOOL FillRgn(CRgn* pRgn, CBrush* pBrush) const;
Fills a region by using the specified brush.
GradientFill
void GradientFill(COLORREF Color1, COLORREF Color2, const RECT& rc, BOOL bVertical);
Fills the specified rectangle with a color gradient .
SolidFill
void SolidFill(COLORREF Color, const RECT& rc);
Fills a rectangle with a solid color.
DrawIcon
BOOL DrawIcon(int x, int y, HICON hIcon) const;
BOOL DrawIcon(POINT point, HICON hIcon) const;
Draws an icon or cursor into the specified device context.
FrameRect
BOOL FrameRect(const RECT& rc, CBrush* pBrush) const;
Draws a border around the specified rectangle by using the specified brush. The width and height of the border are always one logical unit.
PaintRgn
BOOL PaintRgn(CRgn* pRgn) const;
Paints the specified region by using the brush currently selected into the device context.
Bitmap Functions
StretchDIBits
int StretchDIBits(int XDest, int YDest, int nDestWidth, int nDestHeight, int XSrc,
                  int YSrc, int nSrcWidth, int nSrcHeight, CONST VOID *lpBits,
                  BITMAPINFO& bi, UINT iUsage, DWORD dwRop) const;
Copies the color data for a rectangle of pixels in a DIB to the specified destination rectangle. If the destination rectangle is larger than the source rectangle, this function stretches the rows and columns of color data to fit the destination rectangle. If the destination rectangle is smaller than the source rectangle, this function compresses the rows and columns by using the specified raster operation.
PatBlt
BOOL PatBlt(int x, int y, int nWidth, int nHeight, DWORD dwRop) const;
Paints the specified rectangle using the brush that is currently selected into the device context. The brush color and the surface color or colors are combined by using the specified raster operation.
BitBlt
BOOL BitBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC,
                                     int xSrc, int ySrc, DWORD dwRop) const;
Performs a bit-block transfer of the color data corresponding to a rectangle of pixels from the specified source device context.
DrawBitmap
virtual void DrawBitmap(int x, int y, int cx, int cy, HBITMAP hbmImage, COLORREF clrMask);
Draws the specified bitmap to the specified DC using the mask colour provided as the transparent colour. Suitable for use with a Window DC or a memory DC.
StretchBlt
BOOL StretchBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc,
                int ySrc, int nSrcWidth, int nSrcHeight, DWORD dwRop) const;
Copies a bitmap from a source rectangle into a destination rectangle, stretching or compressing the bitmap to fit the dimensions of the destination rectangle, if necessary.
GetDIBits
int GetDIBits(CBitmap* pBitmap, UINT uStartScan, UINT cScanLines,
              LPVOID lpvBits, LPBITMAPINFO lpbi, UINT uUsage) const;
Retrieves the bits of the specified compatible bitmap and copies them into a buffer as a DIB using the specified format.
SetDIBits
int SetDIBits(CBitmap* pBitmap, UINT uStartScan, UINT cScanLines,
              CONST VOID *lpvBits, LPBITMAPINFO lpbi, UINT fuColorUse) const;
Sets the pixels in a compatible bitmap (DDB) using the color data found in the specified DIB .
GetStretchBltMode
int GetStretchBltMode() const;
Retrieves the current stretching mode. The stretching mode defines how color data is added to or removed from bitmaps that are stretched or compressed when the StretchBlt function is called.
SetStretchBltMode
int SetStretchBltMode(int iStretchMode) const;
Sets the bitmap stretching mode in the device context.
FloodFill
BOOL FloodFill(int x, int y, COLORREF crColor) const;
Fills an area of the display surface with the current brush. The area is assumed to be bounded as specified by the crFill parameter.
ExtFloodFill
BOOL ExtFloodFill(int x, int y, COLORREF crColor, UINT nFillType) const;
Fills an area of the display surface with the current brush.
Clipping Functions
ExcludeClipRect
int ExcludeClipRect(int Left, int Top, int Right, int BottomRect);
int ExcludeClipRect(const RECT& rc);
Creates a new clipping region that consists of the existing clipping region minus the specified rectangle.
GetClipBox
int GetClipBox(RECT& rc);
Retrieves the dimensions of the tightest bounding rectangle that can be drawn around the current visible area on the device. The visible area is defined by the current clipping region or clip path, as well as any overlapping windows.
GetClipRgn
int GetClipRgn(HRGN hrgn);
Retrieves a handle identifying the current application-defined clipping region for the specified device context.
IntersectClipRect
int IntersectClipRect(int Left, int Top, int Right, int Bottom);
int IntersectClipRect(const RECT& rc);
Creates a new clipping region from the intersection of the current clipping region and the specified rectangle.
RectVisible
BOOL RectVisible(const RECT& rc);
Determines whether any part of the specified rectangle lies within the clipping region of a device context.
SelectClipRgn
int SelectClipRgn(CRgn* pRgn);
Selects a region as the current clipping region for the device context.
ExtSelectClipRgn
int ExtSelectClipRgn(CRgn* pRgn, int fnMode);
Combines the specified region with the current clipping region using the specified mode.
OffsetClipRgn
int OffsetClipRgn(int nXOffset, int nYOffset);
Moves the clipping region of the device context by the specified offsets.
PtVisible
BOOL PtVisible(int X, int Y);
Determines whether the specified point is within the clipping region of a device context.
Co-ordinate Functions
DPtoLP
BOOL DPtoLP(LPPOINT lpPoints, int nCount) const;
BOOL DPtoLP(LPRECT lpRect) const;
Converts device coordinates into logical coordinates. The conversion depends on the mapping mode of the device context, the settings of the origins and extents for the window and viewport, and the world transformation.
LPtoDP
BOOL LPtoDP(LPPOINT lpPoints, int nCount) const;
BOOL LPtoDP(LPRECT lpRect) const;
Converts logical coordinates into device coordinates. The conversion depends on the mapping mode of the device context, the settings of the origins and extents for the window and viewport, and the world transformation.
Layout Functions
GetLayout
DWORD GetLayout() const;
Returns the layout of a device context (DC). Can be used to retrieve the LAYOUT_RTL (for Win2000 and above).
SetLayout
DWORD SetLayout(DWORD dwLayout) const;
Changes the layout of a device context (DC). Can be used to set the LAYOUT_RTL style (for Win2000 and above).
Mapping Functions
GetMapMode
int GetMapMode() const;
Retrieves the current mapping mode.
SetMapMode
int SetMapMode(int nMapMode) const;
Sets the mapping mode of the specified device context. The mapping mode defines the unit of measure used to transform page-space units into device-space units, and also defines the orientation of the device's x and y axes.
GetViewportOrgEx
BOOL GetViewportOrgEx(LPPOINT lpPoint) const;
Retrieves the x-coordinates and y-coordinates of the window origin for the specified device context.
SetViewportOrgEx
BOOL SetViewportOrgEx(int x, int y, LPPOINT lpPoint) const;
BOOL SetViewportOrgEx(POINT point, LPPOINT lpPointRet) const;
Specifies which window point maps to the viewport origin (0,0).
OffsetViewportOrgEx
BOOL OffsetViewportOrgEx(int nWidth, int nHeight, LPPOINT lpPoint) const;
Modifies the viewport origin for a device context using the specified horizontal and vertical offsets.
GetViewportExtEx
BOOL GetViewportExtEx(LPSIZE lpSize) const;
Retrieves the x-extent and y-extent of the current viewport for the specified device context.
SetViewportExtEx
BOOL SetViewportExtEx(int x, int y, LPSIZE lpSize) const;
BOOL SetViewportExtEx(SIZE size, LPSIZE lpSizeRet) const;
Sets the horizontal and vertical extents of the viewport for a device context by using the specified values.
ScaleViewportExtEx
BOOL ScaleViewportExtEx(int xNum, int xDenom, int yNum,
                        int yDenom, LPSIZE lpSize) const;
Modifies the viewport for a device context using the ratios formed by the specified multiplicands and divisors.
OffsetWindowOrg
BOOL OffsetWindowOrg(int nWidth, int nHeight, LPPOINT lpPoint) const;
Modifies the viewport for a device context using the ratios formed by the specified multiplicands and divisors.
GetWindowExtEx
BOOL GetWindowExtEx(LPSIZE lpSize) const;
Retrieves the x-extent and y-extent of the window for the specified device context.
SetWindowExtEx
BOOL SetWindowExtEx(int x, int y, LPSIZE lpSize) const;
BOOL SetWindowExtEx(SIZE size, LPSIZE lpSizeRet) const;
Sets the horizontal and vertical extents of the window for a device context by using the specified values.
ScaleWindowExtEx
BOOL ScaleWindowExtEx(int xNum, int xDenom, int yNum, int yDenom, LPSIZE lpSize) const;
Modifies the window for a device context using the ratios formed by the specified multiplicands and divisors.
GetWindowOrgEx
BOOL GetWindowOrgEx(LPPOINT lpPoint) const;
Retrieves the x-coordinates and y-coordinates of the window origin for the specified device context.
SetWindowOrgEx
BOOL SetWindowOrgEx(int x, int y, LPPOINT lpPoint) const;
BOOL SetWindowOrgEx(POINT point, LPPOINT lpPointRet) const;
Specifies which window point maps to the viewport origin (0,0).
OffsetWindowOrgEx
BOOL OffsetWindowOrgEx(int nWidth, int nHeight, LPPOINT lpPoint) const;
Modifies the window origin for a device context using the specified horizontal and vertical offsets.
Printer Functions
StartDoc
int StartDoc(LPDOCINFO lpDocInfo) const;
Starts a print job.
EndDoc
int EndDoc() const;
Ends a print job.
AbortDoc
int AbortDoc() const;
Stops the current print job and erases everything drawn since the last call to the StartDoc function.
StartPage
int StartPage() const;
Prepares the printer driver to accept data.
EndPage
int EndPage() const;
Notifies the device that the application has finished writing to a page. This function is typically used to direct the device driver to advance to a new page.
SetAbortProc
int SetAbortProc( BOOL (CALLBACK* lpfn)(HDC, int) ) const;
Sets the application-defined abort function that allows a print job to be cancelled during spooling.
Text Functions
ExtTextOut
BOOL ExtTextOut(int x, int y, UINT nOptions, const RECT& rc, LPCTSTR lpszString,
                UINT nCount, LPINT lpDxWidths) const;
Draws text using the currently selected font, background color, and text color. You can optionally provide dimensions to be used for clipping, opaquing, or both.
DrawText
int DrawText(LPCTSTR lpszString, int nCount, const RECT& rc, UINT nFormat) const;
Draws formatted text in the specified rectangle. It formats the text according to the specified method (expanding tabs, justifying characters, breaking lines, and so forth).
GetTextAlign
UINT GetTextAlign() const;
Retrieves the text-alignment setting for the specified device context.
SetTextAlign
UINT SetTextAlign(UINT nFlags) const;
Sets the text-alignment flags for the specified device context.
GetTextFace
int GetTextFace(int nCount, LPTSTR lpszFacename) const;
Retrieves the typeface name of the font that is selected into the specified device context.
GetTextMetrics
BOOL GetTextMetrics(TEXTMETRIC& Metrics) const;
Fills the specified buffer with the metrics for the currently selected font.
GetBkColor
COLORREF GetBkColor() const;
Returns the current background color for the specified device context.
SetBkColor
COLORREF SetBkColor(COLORREF crColor) const;
Sets the current background color to the specified color value, or to the nearest physical if the device cannot represent the specified color value.
GetTextColor
COLORREF GetTextColor() const;
Retrieves the current text color for the specified device context.
SetTextColor
COLORREF SetTextColor(COLORREF crColor) const;
Sets the text color for the specified device context to the specified color.
GetBkMode
int GetBkMode() const;
Returns the current background mix mode for a specified device context. The background mix mode of a device context affects text, hatched brushes, and pen styles that are not solid lines.
SetBkMode
int SetBkMode(int iBkMode) const;
Sets the background mix mode of the specified device context. The background mix mode is used with text, hatched brushes, and pen styles that are not solid lines.
GetTextExtentPoint32
CSize GetTextExtentPoint32(LPCTSTR lpszString, int nCount) const;
Computes the width and height of the specified string of text.
GetTabbedTextExtent
CSize GetTabbedTextExtent(LPCTSTR lpszString, int nCount, int nTabPositions,
                          LPINT lpnTabStopPositions) const;
Computes the width and height of a character string. If the string contains one or more tab characters, the width of the string is based upon the specified tab stops. The GetTabbedTextExtent function uses the currently selected font to compute the dimensions of the string.
TextOut
BOOL TextOut(int x, int y, LPCTSTR lpszString, int nCount) const;
Writes a character string at the specified location, using the currently selected font, background color, and text color.
TabbedTextOut
CSize TabbedTextOut(int x, int y, LPCTSTR lpszString, int nCount, int nTabPositions,
                    LPINT lpnTabStopPositions, int nTabOrigin) const;
Writes a character string at a specified location, expanding tabs to the values specified in an array of tab-stop positions. Text is written in the currently selected font, background color, and text color.
DrawTextEx
int DrawTextEx(LPTSTR lpszString, int nCount, const RECT& rc, UINT nFormat,
               LPDRAWTEXTPARAMS lpDTParams) const;
Draws formatted text in the specified rectangle.
GrayString
BOOL GrayString(HBRUSH hBrush, GRAYSTRINGPROC lpOutputFunc, LPARAM lpData,
                int nCount, int x, int y, int nWidth, int nHeight) const;
Draws gray text at the specified location. The function draws the text by copying it into a memory bitmap, graying the bitmap, and then copying the bitmap to the screen. The function grays the text regardless of the selected brush and background. GrayString uses the currently selected font.
SetTextJustification
int SetTextJustification(int nBreakExtra, int nBreakCount) const;
Specifies the amount of space the system should add to the break characters in a string of text. The space is added when an application calls the TextOut or ExtTextOut functions.
GetTextCharacterExtra
int GetTextCharacterExtra() const;
Retrieves the current intercharacter spacing for the specified device context.
SetTextCharacterExtra
int SetTextCharacterExtra(int nCharExtra) const;
Sets the inter-character spacing. Inter-character spacing is added to each character, including break characters, when the system writes a line of text.

Remarks

CDC objects can be used anywhere a a handle to a device context (a HDC) might be used. They can be substituted for the HDC in any of the Windows API functions which use a HDC as a function argument. The benefit of using a CDC object is that it automatically deletes the device context when it is destroyed, along with any GDI objects created by the CDC.

There are a number of classes inherited from CDC, namely CClientDC, CMemDC, CMetaFileDC, CPaintDC, and CWindowDC. Typically one of these more specialized classes would be used to create the device context.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CDialog

CDialog Class

Description

CDialog adds support for dialogs to Win32++. Dialogs are specialised windows which are a parent window for common controls. Common controls are special window types such as buttons, edit controls, tree views, list views, static text etc.

The layout of a dialog is typically defined in a resource script file (often Resource.rc). While this script file can be constructed manually, it is often created using a resource editor. If your compiler doesn't include a resource editor, you might find ResEdit useful. It is a free resource editor available for download at: http://www.resedit.net/

CDialog supports modal and modeless dialogs. It supports the creation of dialogs defined in a resource script file, as well as those defined in a dialog template.

The Dialog sample program can be used as the starting point for your own dialog applications.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of dialogs.

CDialog Members

Construction

CDialog
CDialog(UINT nResID, HWND hParent = NULL);
CDialog(LPCTSTR lpszResName, HWND hParent = NULL);
CDialog(LPCDLGTEMPLATE lpTemplate, HWND hParent = NULL);
Constructor for CDialog. There are three forms of the CDialog constructor, one each for dialogs based on a resource ID, a resource string, and a dialog template.

Overridables

DialogProc
virtual BOOL DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
The window procedure for this CDialog object. Override this function to specify how the messages for this window are to be handled. Return all unhandled messages to DialogProcDefault.
EndDialog
virtual void EndDialog(INT_PTR nResult);
Ends a modal or modeless dialog.
OnCancel
virtual void OnCancel();
Called when the Cancel button is pressed.
OnInitDialog
virtual BOOL OnInitDialog();
Called when the dialog starts, before it is displayed. Override the function to specify what happens when the dialog is created.
OnOK
virtual void OnOK();
Called when the OK button is pressed. The default behavior is to end the dialog when the OK button is pressed.
PreTranslateMessage
virtual BOOL PreTranslateMessage(MSG* pMsg);
Override this function to filter mouse and keyboard messages prior to being passed to the message loop.

Operations

AttachItem
virtual void AttachItem(int nID, CWnd& Wnd);
Attach a dialog item to a CWnd.
Create
virtual HWND Create(HWND hParent = 0);
Creates a modeless dialog.
DialogProcDefault
virtual BOOL DialogProcDefault(UINT uMsg, WPARAM wParam, LPARAM lParam);
The default dialog procedure. All unhandled messages should be passed to this function.
DoModal
virtual INT_PTR DoModal();
Create a modal dialog. A modal dialog must be closed before the owner window can be made active.
DoModeless
virtual HWND DoModeless();
Create a modeless dialog.
SetDlgParent
virtual void SetDlgParent(HWND hParent);
Sets what the parent window of the dialog will be once it is created. Use this function before creating the dialog.

State functions

IsModal
BOOL IsModal() const;
Returns TRUE of the dialog is modal.
IsIndirect
BOOL IsIndirect() const;
Returns TRUE of the dialog is created from a dialog box template in memory.

Base class Members

For base class members, refer to the members of CWnd.

Remarks

Modal dialogs are always the application's active window. While it is are running, the modal dialog is the only window that can accept user input for the application. Modeless dialogs, on the other hand, allow other windows to become active and accept user input while they are running.

Modal dialogs run their own internal message loop, whereas modeless dialogs run the message loop provided by CWinApp. While the modal dialog is running, its internal message loop processes all messages for the thread the dialog runs in, including those of other windows.

Dialogs are used to display various controls, such as buttons, TreeViews, ListViews, static text and so forth. Each of these controls is actually a child window of the dialog. The following function are often used to manage dialog controls:

  • AttachDlgItem
  • CheckDlgButton
  • GetDlgItem
  • GetDlgItemInt
  • GetDlgItemText
  • SendDlgMessage
  • SetDlgItemInt
  • SetDlgItemText

The AttachDlgItem function is used to attach a dialog control to CWnd derived object. This allows the CWnd derived object to handle the control's messages in WndProc, and the control's notifications in OnNotifyReflect.

A modeless dialog can be used as a view window for a frame, MDIChild, docker etc. The FormDemo sample demonstrate how to use a dialog as a view window in a CFrame. This sample also demonstrates how to use CResizer to automatically reposition the dialog's controls when the frame is resized.

Refer to the Dialog section for more information on how to use CDialog to create dialogs.

Summary Information

Header file | dialog.h
Win32/64 support | Yes
WinCE support | Yes


CDocker

CDocker Class

Description

The CDocker class adds both docking and splitter windows to the Win32++ framework. Splitter windows have a subset of the functionality of docking windows. Splitter windows are child windows that can be dynamically re-sized. Docking windows have this feature too, but they also allow windows to be docked and undocked.

CDocker Members

CDocker
CDocker();
Constructor for CDocker.
AddDockedChild
virtual CDocker* AddDockedChild(CDocker* pDocker, DWORD dwDockStyle,
                                int DockWidth, int nDockID = 0);
Adds the specified Docker as a docked child.
AddUndockedChild
virtual CDocker* AddUndockedChild(CDocker* pDocker, DWORD dwDockStyle,
                                  int DockWidth, RECT rc, int nDockID = 0);
Adds the specified Docker as an undocked member of this docking group.
Close
virtual void Close();
Closes the Docker.
CloseAllDockers
virtual void CloseAllDockers();
Closes all Dock children.
Dock
virtual void Dock(CDocker* pDocker, UINT uDockSide);
Docks the Docker to the side of another Docker.
DockInContainer
virtual void DockInContainer(CDocker* pDock, DWORD dwDockStyle);
Docks the Container inside another Container (by adding a tab).
GetAccelerators
HACCEL GetAccelerators() const;
Returns a reference to the vector containing pointers to all Dock Children in this docking group.
GetActiveDocker
virtual CDocker* GetActiveDocker() const;
Returns a reference to the vector containing pointers to all Dock Children in this docking group.
GetAllDockers
std::vector <DockPtr> & GetAllDockers() const;
Returns a reference to the vector containing pointers to all Dock Children in this docking group.
GetDockChildren
std::vector <CDocker*> & GetDockChildren() const;
Returns a reference to the vector containing pointers to this docker's Dock Children.
GetBarWidth
int GetBarWidth() const;
Returns the width of the Docker's splitter bar.
GetCaption
CString& GetCaption() const;
Returns the Docker's caption text.
GetContainer
virtual CDockContainer* GetContainer() const;
Returns a pointer to the container used as the Docker's view. If the view is not a container, this function returns NULL.
GetDockAncestor
virtual CDocker* GetDockAncestor() const;
Returns a pointer to the Dock Ancestor of this docking group.
GetDockBar
virtual CDockBar& GetDockBar() const;
Returns a reference to this docker's splitter bar.
GetDockChildren
std::vector <CDocker*> & GetDockChildren() const;
Returns a reference to the vector containing pointers to all of this docker's dock children.
GetDockClient
virtual CDockClient& GetDockClient();
Returns a reference to the Window of this docker's client area. The dock caption an view window are child windows of the dock client.
GetDockFromID
virtual CDocker* GetDockFromID(int n_DockID) const;
Returns a pointer to the docker, given its ID.
GetDockFromPoint
virtual CDocker* GetDockFromPoint(POINT pt) const;
Returns a pointer to the Docker whose Dock client area includes the specified point .
GetDockFromView
virtual CDocker* GetDockFromView(CWnd* pView) const;
Returns a pointer to the Docker which has the the specified view window.
GetDockHint
virtual CDockHint& GetDockHint() const;
Returns a reference to the Docker's hint window. The hint window as a blue tint and is displayed during dock dragging.
GetDockID
int GetDockID() const;
Return the ID of this Docker.
GetDockParent
CDocker* GetDockParent() const;
Returns the Dock Parent of this Docker.
GetDockStyle
DWORD GetDockStyle() const;
Returns the dock style of this Docker.
GetDockWidth
virtual int GetDockWidth() const;
Returns the width of a docker which is dock to the left or right of another docker, or its height if docked to the top or bottom.
GetTabbedMDI
virtual CTabbedMDI* GetTabbedMDI() const;
Returns a TabbedMDI pointer to the view window of this docker, or NULL if the view window is not a TabbedMDI.
GetTopmostDocker
virtual CDocker* GetTopmostDocker() const;
Returns the top level Dock parent of this Docker. Any undocked Docker (not just the Dock Ancestor) can be a top level Dock parent.
GetView
CWnd* GetView() const;
Returns a pointer to the view window of this docker.
Hide
virtual void Hide();
Undocks the Docker (if necessary) and hides it.
IsChildOfDocker
BOOL IsChildOfDocker(HWND hwnd) const;
Returns TRUE if the specified window handle is a decendant of this docker.
IsDocked
BOOL IsDocked() const;
Returns TRUE if this Docker is docked within another Docker.
IsDragAutoResize
BOOL IsDragAutoResize();
Returns the TRUE of the dockers will be automatically re-arrange as the splitter bar is moved.
IsRelated
BOOL IsRelated(HWND hWnd) const;
Returns TRUE if the specified Docker is in this docker family. Dockers in the same dock family share the one dock ancestor.
IsUndocked
BOOL IsUndocked() const;
Returns TRUE if the docker is Undocked. The dock ancestor is always undocked, but other dockers can dock within it.
LoadRegistrySettings
virtual BOOL LoadRegistrySettings(LPCTSTR szRegistryKeyName);
Adds dockers to the dock ancestor according to the docking information stored in the registry.
RecalcDockLayout
virtual void RecalcDockLayout();
Recalculates and repositions all dockers which are dock decendants of this docker's top level dock parent.
SaveRegistrySettings
virtual BOOL SaveRegistrySettings(LPCTSTR szRegistryKeyName);
Saves the docking styles, state and position in the registry.
SetBarColor
void SetBarColor(COLORREF color);
Sets the color of the splitter bar.
SetBarWidth
void SetBarWidth(int nWidth);
Sets the width of the splitter.
SetCaption
void SetCaption(LPCTSTR szCaption);
Sets the dock caption text.
SetCaptionColors
vvoid SetCaptionColors(COLORREF Foregnd1, COLORREF Backgnd1, COLORREF ForeGnd2, COLORREF BackGnd2);
Sets the caption's foreground and background colours.
SetCaptionHeight
void SetCaptionHeight(int nHeight);
Sets the caption's height.
SetDockStyle
void SetDockStyle(DWORD dwDockStyle);
Set the dock style.
SetDockWidth
void SetDockWidth(int DockWidth);
Sets the width of a docker docked to the left or right of its parent, or the height of the docker docked to the top or bottom.
SetDragAutoResize
void SetDragAutoResize(BOOL bAutoResize);
Set the DragAutoSize mode. When TRUE, dockers will be automatically re-arranged as the splitter bar is moved. When FALSE the dockers will be re-arranged when the splitter bar dragging is complete.
SetView
void SetView(CWnd& wndView);
Sets the view window for the docker.
Undock
virtual void Undock(CPoint pt, BOOL bShowUndocked = TRUE);
Undocks the Docker and positions it at the specified point.
UndockContainer
virtual void UndockContainer(CDockContainer* pContainer,
                             CPoint pt, BOOL bShowUndocked);
Undocks the Container and positions it at the specified point.
VerifyDockers
virtual BOOL VerifyDockers();
A built in diagnostic which verifies the integrity of the docking hierarchy.

Overridables

NewDockerFromID
virtual CDocker* NewDockerFromID(int idDock);
Override this function to create a new Docker given its docker ID.
OnActivate
virtual void OnActivate(WPARAM wParam, LPARAM lParam);
Called when the window is activated or deactivated.
OnCreate
virtual void OnCreate();
Called when the window is created.
OnDestroy
virtual void OnDestroy(WPARAM wParam, LPARAM lParam);
Called when the window is destroyed.
OnDockDestroyed
virtual void OnDockDestroyed(WPARAM wParam, LPARAM lParam);
Called when the docker is destroyed.
OnExitSizeMove
virtual void OnExitSizeMove(WPARAM wParam, LPARAM lParam);
Called after the window has completed a resize or move.
OnIdle
virtual BOOL OnIdle(LONG lCount);
Called to perform idle processing, when the message queue is empty.
OnNotify
virtual LRESULT OnNotify(WPARAM wParam, LPARAM lParam);
Called when the window receives a notification.
OnSetFocus
virtual void OnSetFocus(WPARAM wParam, LPARAM lParam);
Called when the window receives window focus.
OnSysColorChange
virtual void OnSysColorChange(WPARAM wParam, LPARAM lParam);
Called when a change is made to a system color setting.
OnSysCommand
virtual LRESULT OnSysCommand(WPARAM wParam, LPARAM lParam);
Called when the window is minimized, maximized, restored or closed.
OnWindowPosChanged
virtual void OnWindowPosChanged(WPARAM wParam, LPARAM lParam);
Called after the window position has changed.
OnWindowPosChanging
virtual LRESULT OnWindowPosChanging(WPARAM wParam, LPARAM lParam);
Called before the window position has changed.
PreCreate
virtual void PreCreate(CREATESTRUCT &cs);
Sets the window creation parameters.
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Sets the window class parameters.
PreTranslateMessage
virtual BOOL PreTranslateMessage(MSG Msg);
This functions is called by the MessageLoop. It processes the keyboard accelerator keys and calls CWnd::PreTranslateMessage for keyboard and mouse events.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Refer to the Docking section for information on how to use CDocker to create splitter windows and docking windows.

Summary Information

Header file | docking.h
Win32/64 support | Yes
WinCE support | Yes


CDockContainer

CDockContainer Class

Description

The CDockContainer class adds "Containers" to the Win32++ framework. A Container is a tab control which has been designed to co-operate with docking. While Dockers allows any child window to be used as the view window, Containers add additional features when used as the view window for Dockers. These additional features include Container within Container docking (where the newly docked Container adds another tab), as well as additions to the dock targeting and dock hinting visual cues. Containers can also have a toolbar. The use of a toolbar is optional, but when used they are set up in the same way as toolbars for Frames.

CDockContainers have views of their own. These views can be any child window, and are set in the same way as views for Frames and MDI children.

CDockContainer Members

CDockContainer
CDockContainer();
Constructor for CDockContainer.
AddContainer
virtual void AddContainer(CDockContainer* pContainer);
Adds the specified container as a child to this container.
AddToolBarButton
virtual void AddToolBarButton(UINT nID, BOOL bEnabled = TRUE);
Adds a resource ID to the container's toolbar.
GetActiveContainer
CDockContainer* GetActiveContainer() const;
Returns a pointer to the currently active container.
GetActiveView
CWnd* GetActiveView() const;
Returns a pointer to the view window for the currently active container.
GetAllContainers
std::vector<ContainerInfo>& GetAllContainers() const;
Returns a reference to the vector of container information.
GetContainerFromIndex
virtual CDockContainer* GetContainerFromIndex(UINT nPage);
Returns a pointer to the container at the specified tab number.
GetContainerFromView
virtual CDockContainer* GetContainerFromView(CWnd* pView) const;
Returns a pointer to the container with the specified view.
GetContainerIndex
virtual int GetContainerIndex(CDockContainer* pContainer);
Returns the tab index of the specified container.
GetContainerParent
CDockContainer* GetContainerParent() const;
Returns a pointer to the container which is the parent of this container group.
GetDockCaption
tString GetDockCaption() const;
Returns the tString which contains the text displayed in the caption of a docked container.
GetMaxTabTextSize
virtual SIZE GetMaxTabTextSize();
Returns the size (width and height) of the caption text.
GetTabIcon
HICON GetTabIcon() const;
Returns the icon handle for this container's tab.
GetTabText
LPCTSTR GetTabText() const;
Returns the text for this container's tab.
GetToolBar
virtual CToolBar& GetToolBar() const;
Returns a reference to the container's toolbar.
GetView
CWnd* GetView() const;
Returns a pointer to the view window for this container.
GetViewPage
virtual CViewPage& GetViewPage() const;
Returns a pointer to the container's page. The container's page holds the toolbar and view window.
RecalcLayout
virtual void RecalcLayout();
Recalculates the positions of the child windows for the container, and repositions them.
RemoveContainer
virtual void RemoveContainer(CDockContainer* pWnd);
Removes the specified child container from this container group.
SelectPage
virtual void SelectPage(int nPage);
Activates the specified page number.
SetActiveContainer
void SetActiveContainer(CDockContainer* pContainer);
Sets the active container.
SetDockCaption
void SetDockCaption(LPCTSTR szCaption);
Sets the text associated with a docked container.
SetTabIcon
void SetTabIcon(HICON hTabIcon);
void SetTabIcon(UINT nID_Icon);
Sets the icon for this container's tab.
SetTabText
void SetTabText(LPCTSTR szText);
void SetTabText(UINT nTab, LPCTSTR szText);
Sets the text for this container's tab.
SetupToolBar
virtual void SetupToolBar();
Override this function to specify the container's toolbar's bitmap and resource IDs.
SetView
void SetView(CWnd& Wnd);
Sets the view window for this container.
Base class Members

For base class members, refer to the members of CTab.

Remarks

The CDockContainer could be also used as a view window for other window types, such as Frames and MDI children, although using a CTab for these other views is more common.

Summary Information

Header file | docking.h
Win32/64 support | Yes
WinCE support | No
Library required | Comctl32.lib


CEdit

CEdit Class

Description

An edit control is a rectangular control window typically used in a dialog box to permit the user to enter and edit text by typing on the keyboard.Edit controls are typically used in dialog boxes, but you can use them in the client area of a standard window as well. Single-line edit controls are useful for retrieving a single string from the user. Multiline edit controls make it easy for your application to implement most of the features of a simple word processor.

CEdit is the class responsible for creating a list-view control. It can be used as a control in a Dialog, or as the View window in a Frame, Docker, or MDI child.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of edit controls.

CEdit Members

Construction

CEdit
CEdit();
Constructor for CEdit.

Attributes

GetFirstVisibleLine
int GetFirstVisibleLine() const;
Returns the zero-based index of the first visible character in a single-line edit control or the zero-based index of the uppermost visible line in a multiline edit control.
GetHandle
HLOCAL GetHandle() const;
Returns a handle identifying the buffer containing the multiline edit control's text. It is not processed by single-line edit controls.
GetLimitText
UINT GetLimitText() const;
Returns the current text limit, in characters.
GetLine
int GetLine(int nIndex, LPTSTR lpszBuffer) const;
int GetLine(int nIndex, LPTSTR lpszBuffer, int nMaxLength) const;
Copies characters in a single-line edit control to a buffer and returns the number of characters copied. In a multiline edit control, retrieves a line of text from the control and returns the number of characters copied.
GetLineCount
int GetLineCount() const;
Returns the number of lines in the edit control.
GetMargins
DWORD GetMargins() const;
Returns the widths of the left and right margins.
GetModify
BOOL GetModify() const;
Returns a flag indicating whether the content of an edit control has been modified.
GetPasswordChar
TCHAR GetPasswordChar() const;
Returns the character that edit controls use in conjunction with the ES_PASSWORD style.
GetRect
void GetRect(LPRECT lpRect) const;
Returns the coordinates of the formatting rectangle in an edit control.
GetSel
void GetSel(int& nStartChar, int& nEndChar) const;
Returns the starting and ending character positions of the current selection in the edit control.
SetHandle
void SetHandle(HLOCAL hBuffer) const;
Sets a handle to the memory used as a text buffer, empties the undo buffer, resets the scroll positions to zero, and redraws the window.
SetLimitText
void SetLimitText(UINT nMax) const;
Sets the maximum number of characters the user may enter in the edit control.
SetMargins
void SetMargins(UINT nLeft, UINT nRight) const;
Sets the widths of the left and right margins, and redraws the edit control to reflect the new margins.
SetModify
void SetModify(BOOL bModified = TRUE) const;
Sets or clears the modification flag to indicate whether the edit control has been modified.
SetPasswordChar
void SetPasswordChar(TCHAR ch) const;
Defines the character that edit controls use in conjunction with the ES_PASSWORD style.
SetReadOnly
BOOL SetReadOnly(BOOL bReadOnly = TRUE) const;
Sets or removes the read-only style (ES_READONLY) in an edit control.
SetRect
void SetRect(LPCRECT lpRect) const;
Sets the formatting rectangle for the multiline edit control and redraws the window. It is not processed by single-line edit controls.
SetRectNP
void SetRectNP(LPCRECT lpRect) const;
Sets the formatting rectangle for the multiline edit control but does not redraw the window. It is not processed by single-line edit controls.
SetSel
void SetSel(DWORD dwSelection, BOOL bNoScroll) const;
void SetSel(int nStartChar, int nEndChar, BOOL bNoScroll) const;
Selects a range of characters in the edit control by setting the starting and ending positions to be selected.
SetTabStops
BOOL SetTabStops(int nTabStops, LPINT rgTabStops) const;
BOOL SetTabStops(const int& cxEachStop) const;
BOOL SetTabStops() const;
Sets tab-stop positions in the multiline edit control. It is not processed by single-line edit controls.

Operations

CanUndo
BOOL CanUndo() const;
Returns TRUE if the edit control operation can be undone.
CharFromPos
int CharFromPos(CPoint pt) const;
Returns TRUE if the edit control operation can be undone.
Clear
void Clear() const;
Clears the current selection, if any, in an edit control. If there is no current selection, deletes the character to the right of the caret.
Copy
void Copy() const;
Copies text to the clipboard unless the style is ES_PASSWORD, in which case the message returns zero.
Cut
void Cut() const;
Cuts the selection to the clipboard, or deletes the character to the left of the cursor if there is no selection.
EmptyUndoBuffer
void EmptyUndoBuffer() const;
Empties the undo buffer and sets the undo flag retrieved by the EM_CANUNDO message to FALSE. The system automatically clears the undo flag whenever the edit control receives a WM_SETTEXT or EM_SETHANDLE message.
FmtLines
BOOL FmtLines(BOOL bAddEOL) const;
Adds or removes soft line-break characters (two carriage returns and a line feed) to the ends of wrapped lines in a multiline edit control. It is not processed by single-line edit controls.
LimitText
void LimitText(int nChars = 0) const;
Sets the text limit of an edit control. The text limit is the maximum amount of text, in TCHARs, that the user can type into the edit control.
LineFromChar
int LineFromChar(int nIndex = -1) const;
Returns the zero-based number of the line in a multiline edit control that contains a specified character index. This message is the reverse of the EM_LINEINDEX message. It is not processed by single-line edit controls.
LineIndex
int LineIndex(int nLine = -1) const;
Returns the character of a line in a multiline edit control. This message is the reverse of the EM_LINEFROMCHAR message. It is not processed by single-line edit controls.
LineLength
int LineLength(int nLine = -1) const;
Returns the length, in characters, of a single-line edit control. In a multiline edit control, returns the length, in characters, of a specified line.
LineScroll
void LineScroll(int nLines, int nChars = 0) const;
Scrolls the text vertically in a single-line edit control or horizontally in a multiline edit control (when the control has the ES_LEFT style). The lParam parameter specifies the number of lines to scroll vertically, starting from the current line. The wParam parameter specifies the number of characters to scroll horizontally, starting from the current character.
Paste
void Paste() const;
Pastes text from the clipboard into the edit control window at the caret position.
PosFromChar
CPoint PosFromChar(UINT nChar) const;
Returns the client coordinates of the specified character.
ReplaceSel
void ReplaceSel(LPCTSTR lpszNewText, BOOL bCanUndo) const;
Replaces the current selection with the text in an application-supplied buffer, sends the parent window EN_UPDATE and EN_CHANGE messages, and updates the undo buffer.
Undo
void Undo() const;
Removes any text that was just inserted or inserts any deleted characters and sets the selection to the inserted text. If necessary, sends the EN_UPDATE and EN_CHANGE notification messages to the parent window.

Overidables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the edit control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for an edit control.

Summary Information

Header file | stdcontrols.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CFile

CFile Class

Description

This class manages the reading from and writing to files.

CFile Members

Initialisation and Assignment
CFile
CFile();
CFile(HANDLE hFile);
CFile(LPCTSTR pszFileName, UINT nOpenFlags);
Constructor for CFile.
Attributes
GetFileName
const CString& GetFileName() const;
Converts the CFile to a HANDLE.
GetFilePath
const CString& GetFilePath() const;
Converts the CFile to a HANDLE.
GetFileTitle
const CString& GetFileTitle() const;
Converts the CFile to a HANDLE.
GetHandle
HANDLE GetHandle() const;
Converts the CFile to a HANDLE.
GetPosition
ULONGLONG GetPosition() const;
Returns the current value of the file pointer, which can be used in subsequent calls to Seek.
operator HANDLE
operator HANDLE() const;
Converts the CFile to a HANDLE.
Operations
Close
BOOL Close();
Closes the file associated with this object. Closed file can no longer be read or written to..
Flush
BOOL Flush();
Causes any remaining data in the file buffer to be written to the file.
LockRange
BOOL LockRange(ULONGLONG Pos, ULONGLONG Count);
Locks a range of bytes in and open file.
Open
int CollateNoCase(LPCTSTR pszText) const;
Prepares a file to be written to or read from.
OpenFileDialog
CString OpenFileDialog(LPCTSTR pszFilePathName = NULL,
   DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, LPCTSTR pszFilter = NULL,
   CWnd* pOwnerWnd = NULL);
Displays the file open dialog. Returns a CString containing either the selected file name or an empty CString.
Read
UINT Read(void* pBuf, UINT nCount);
Reads from the file, storing the contents in the specified buffer.
Remove
static BOOL Remove(LPCTSTR pszFileName);
Deletes the specified file.
Rename
static BOOL Rename(LPCTSTR pszOldName, LPCTSTR pszNewName);
Renames the specified file.
SaveFileDialog
CString SaveFileDialog(LPCTSTR pszFilePathName = NULL,
   DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, LPCTSTR pszFilter = NULL,
   LPCTSTR pszDefExt = NULL, CWnd* pOwnerWnd = NULL);
Displays the SaveFileDialog. Returns a CString containing either the selected file name or an empty CString.
Seek
ULONGLONG Seek(LONGLONG lOff, UINT nFrom);
Positions the current file pointer. Permitted values for nFrom are: FILE_BEGIN, FILE_CURRENT, or FILE_END.
SeekToBegin
void SeekToBegin();
Sets the current file pointer to the beginning of the file.
SeekToEnd
ULONGLONG SeekToEnd();
Sets the current file pointer to the end of the file.
SetFilePath
void SetFilePath(LPCTSTR pszNewName);
Specifies the full file name, including its path
SetLength
BOOL SetLength(ULONGLONG NewLen);
Changes the length of the file to the specified value.
UnlockRange
BOOL UnlockRange(ULONGLONG Pos, ULONGLONG Count);
Unlocks a range of bytes in an open file.
Write
BOOL Write(const void* pBuf, UINT nCount);
Writes the specified buffer to the file.

Remarks

The following code demonstrates how to use OpenDileDialog to retrieve the name of the file to open.

void CMainFrame::OnFileOpen()
{
  CFile File;
  CString str = File.OpenFileDialog(0, OFN_FILEMUSTEXIST, _T("Scribble Files (*.dat)\0*.dat\0\0"), this);

  if (!str.IsEmpty())
  {
    // Retrieve the PlotPoint data
    m_View.FileOpen(str);
  }
}
The following code demonstrates how to open a file for reading, and read its contents.
BOOL CView::FileOpen(LPCTSTR szFilename)
{
  DWORD nBytesRead;
  BOOL bResult = FALSE;

  // Create a handle to the file
  CFile File;
  if (File.Open(szFilename, OPEN_EXISTING))
  {
    do
    {
      nBytesRead = 0;
      PlotPoint pp;

      nBytesRead = File.Read(&pp, sizeof(PlotPoint));
      if (nBytesRead == sizeof(PlotPoint))
        m_points.push_back(pp);

    } while (nBytesRead == sizeof(PlotPoint));
  }
}

Summary Information

Header file | file.h
Win32/64 support | Yes
WinCE support | Yes


CFont

CFont Class

Description

The class responsible for creating and managing font resources.

CFont Members

Initialization and Assignment
CFont
CFont();
CFont(HFONT hFont);
CFont(const LOGFONT* lpLogFont);
Constructs a CFont object.
operator HFONT()
operator HFONT() const;
Allows a CFont object to be used as a brush handle (HFONT).
Attributes
GetLogFont
LOGFONT GetLogFont() const;
Retrieves the LOGFONT structure that contains font attributes.
Operations
CreateFont
HFONT CreateFont(int nHeight, int nWidth, int nEscapement,
                int nOrientation, int nWeight, DWORD dwItalic,
                DWORD dwUnderline, DWORD dwStrikeOut, DWORD dwCharSet,
                DWORD dwOutPrecision, DWORD dwClipPrecision, DWORD dwQuality,
                DWORD dwPitchAndFamily, LPCTSTR lpszFacename);
Creates a logical font with the specified characteristics.
CreateFontIndirect
HFONT CreateFontIndirect(const LOGFONT* lpLogFont);
Creates a logical font that has the characteristics specified in the LOGFONT struct.
CreatePointFont
HFONT CreatePointFont(int nPointSize, LPCTSTR lpszFaceName, CDC* pDC = NULL,
                     BOOL bBold = FALSE, BOOL bItalic = FALSE);
Creates a font of a specified typeface and point size.
CreatePointFontIndirect
HFONT CreatePointFontIndirect(const LOGFONT* lpLogFont, CDC* pDC = NULL);
Creates a font of a specified typeface and point size. This function automatically converts the height in the LOGFONT's lfHeight to logical units using the specified device context.
Base class Members

For base class members, refer to the members of CGDIObject.

Remarks

CFont objects can be used anywhere a a handle to a brush (HFONT) might be used. They can be substituted for the HFONT in any of the Windows API functions which use a HFONT as a function argument. The benefit of using a CFont object is that it automatically deletes the brush when it is destroyed.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CFrame

CFrame Class

Description

CFrame is responsible for creating a window which includes a menu and toolbar (usually hosted within a rebar), and a status bar, and the "view" window. The "view" window is a separate CWnd object assigned to the frame with the SetView function. This view window can be any sort of window, as long as it can be a child window of the frame. CFrame positions the view window over the part of the frame's client client area that remains after the toolbar and statusbar have been displayed.

To create a frame application, inherit a CMainFrame class from CFrame. Use the Frame sample as the starting point for your own frame applications. Refer to the Notepad and Scribble samples for examples on how to use these classes to create a frame application.

CFrame provides support for a single "view" window. This type of frame application is called a Single Document Interface or SDI. A Multiple Document Interface (or MDI) application allows several view windows to be displayed concurrently. Refer to the CMDIFrame class if your application requires several view windows to be displayed.

CFrame Members

Construction

CFrame
CFrame();
Constructs a CFrame object.

Attributes

GetFrameAccel
HACCEL GetFrameAccel() const;
Returns the accelerator handle for the frame.
GetFrameMenu
HMENU GetFrameMenu() const;
Returns the menu handle for the frame.
GetMenuItemPos
virtual int GetMenuItemPos(HMENU hMenu, LPCTSTR szItem);
Returns the position of the menu item, given it's name.
GetMenuBar
virtual CMenuBar& GetMenuBar() const;
Returns a reference to the menubar. The menubar's window is a child of the rebar, which in turn is a child of the frame. The menubar displays a menu inside the rebar.
GetMenuTheme
virtual MenuTheme& GetMenuTheme() const;
Returns a reference to the MenuTheme structure used by the frame.
GetMRUEntry
CString GetMRUEntry(UINT nIndex);
Returns a the MRU string at the specified index.
GetReBar
virtual CReBar& GetReBar() const;
Returns a reference to the rebar. The rebar's window is a child of the frame.
GetReBarTheme
virtual ReBarTheme& GetReBarTheme() const;
Returns a reference to the ReBarTheme structure used by the frame.
GetRegistryKeyName
CString GetRegistryKeyName() const;
Returns the name of the registry key used by the applications to save its setting.
GetStatusBar
virtual CStatusBar& GetStatusBar() const;
Returns a reference to the status bar. The statubar's window is a child of the frame.
GetThemeName
virtual CString GetThemeName() const;
Returns the name of the current XP theme name.
GetToolBar
virtual CToolBar& GetToolBar() const;
Returns a reference to the toolbar. The toolbar's window is a child of either the rebar or the frame.
GetToolBarTheme
virtual ToolBarTheme& GetToolBarTheme() const;
Returns a reference to the ToolBarTheme structure used by the frame.
GetView
CWnd* GetView() const;
Returns a pointer to the CWnd object positioned over the client area of the frame, commonly referred to as the View window.
GetViewRect
virtual CRect GetViewRect() const;
Returns the coordinates of the View window. The View window is positioned over the part of the client area of the frame that remains after the toolbar and statusbar have been displayed.
SetFrameMenu
void SetFrameMenu(INT ID_MENU);
void SetFrameMenu(HMENU hMenu);
Sets the menu handle for the frame.
SetMenuTheme
void SetMenuTheme(MenuTheme& Theme);
Sets the theme used when menu items are selected.
SetView
void SetView(CWnd& wndView);
Sets the CWnd object which will be positioned over the client area of the frame. This is CWnd object is typically referred to as the view window.

State functions

IsMenuBarUsed
BOOL IsMenuBarUsed() const;
Returns TRUE if the frame is using a menubar.
IsMDIFrame
virtual BOOL IsMDIFrame() const;
Returns TRUE if the frame is a MDI Frame. Refer to CMDIFrame.
IsReBarSupported
BOOL IsReBarSupported() const;
Returns TRUE if the rebar can be used.
IsReBarUsed
BOOL IsReBarUsed() const;
Returns TRUE if the frame is using a rebar control.

Overridables

These functions should not be called directly. The framework will call these functions as required.

OnActivate
virtual void OnActivate(WPARAM wParam, LPARAM lParam);
Called when the frame window is activated.
OnClose
virtual void OnClose();
Called when the frame window is closed.
OnCreate
virtual void OnCreate();
Called when the frame window is created. This creates the toolbar and status bar. Override this function in the derived class to customise the frame's creation.
OnDestroy
virtual void OnDestroy();
Called when the frame window is about to be destroyed.
OnDrawItem
virtual LRESULT OnDrawItem(WPARAM wParam, LPARAM lParam);
Called when the frame performs owner-drawing of controls or menus.
OnExitMenuLoop
virtual void OnExitMenuLoop();
Called then a popup menu modal loop has exited.
OnHelp
virtual void OnHelp();
Called when the F1 key is pressed. It displays the help dialog.
OnInitMenuPopup
virtual void OnInitMenuPopup(WPARAM wParam, LPARAM lParam);
Called when a popup menu belonging to the frame is about to be displayed.
OnInitialUpdate
virtual void OnInitialUpdate();
Override this function to specify what happens after the frame window and all child windows are created.
OnMeasureItem
virtual LRESULT OnMeasureItem(WPARAM wParam, LPARAM lParam);
Called when when the size of an owner drawn control or menu is required.
OnMenuChar
virtual LRESULT OnMenuChar(WPARAM wParam, LPARAM lParam);
Called when a menu mnemonic character that doesn’t match any of the predefined mnemonics in the current menu is pressed.
OnMenuSelect
virtual void OnMenuSelect(WPARAM wParam, LPARAM lParam);
Updates the status bar when a menu item is selected.
OnNotify
virtual LRESULT OnNotify(WPARAM wParam, LPARAM lParam);
Called when the frame receives a notification by way of a WM_NOTIFY message.
OnSetFocus
virtual void OnSetFocus();
Called when the frame gets keyboard focus.
OnSysColorChange
virtual void OnSysColorChange();
Called when the system colours are changed, perhaps in response to changing the system's theme.
OnSysCommand
virtual void OnSysCommand();
Called when the user chooses a command from the Window menu (formerly known as the system or control menu) or when the user chooses the maximize button, minimize button, restore button, or close button.
OnTimer
virtual void OnTimer(WPARAM wParam);
Called at regular intervals to update the status bar.
OnViewStatusBar
virtual void OnViewStatusBar();
Called when the StatusBar is to be displayed or hidden.
OnViewToolBar
virtual void OnViewToolBar();
Called when the toolbar is to be displayed or hidden.
PreCreate
virtual void PreCreate(CREATESTRUCT& cs);
Sets the window parameters specified in CREATESTRUCT prior to window creation.
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Sets the window class parameters specified in WNDCLASS prior to window creation.
PreTranslateMessage
virtual BOOL PreTranslateMessage(MSG* pMsg);
Used to translate window messages before they are dispatched to the TranslateMessage and DispatchMessage Windows functions.
SaveRegisterSettings
virtual BOOL SaveRegistrySettings();
Saves settings for the application to the registry. By default this saves the size and position of the frame window. Override this function to save other settings to the registry.
SetupToolBar
virtual void SetupToolBar();
Override this function to assign resource IDs to toolbar buttons using the AddToolBarButton function. All other toolbar configuration can be specified in this function as well.
SetTheme
virtual void SetTheme();
Sets the theme used when menu items are selected.

Operations

AddMenuBarBand
virtual void AddMenuBarBand();
Adds a menubar to the rebar.
AddMenuIcon
virtual BOOL AddMenuIcon(int nID_MenuItem, HICON hIcon);
Adds an icon to be used on drop down menu items from the supplied icon.
AddMenuIcons
AddMenuIcons(const std::vector<UINT>& MenuData, COLORREF crMask,
             UINT ToolBarID, UINT ToolBarDisabledID);
Adds a set of icons to be used on drop down menu items from the supplied bitmap IDs.
AddMRUEntry
virtual void AddMRUEntry(LPCTSTR szMRUEntry);
Adds the specified text to the Most Recently Used list.
AddToolBarBand
virtual void AddToolBarBand(CToolBar& TB, DWORD dwStyle, UINT nID);
Adds a toolbar to the rebar.
AddToolBarButton
virtual void AddToolBarButton(UINT nID, BOOL bEnabled = TRUE, LPCTSTR szText = 0);
Closes an AVI clip.
AdjustFrameRect
virtual void AdjustFrameRect(RECT rcView) const;
Adds a resource ID to the set used by the toolbar, and specifies if the button is initially disabled.
CreateToolBar
virtual void CreateToolBar();
Create's the frame's ToolBar.
DrawMenuItem
virtual void DrawMenuItem(LPDRAWITEMSTRUCT pdis);
Draws the icon on drop down menu items.
DrawMenuItemBkgnd
virtual void DrawMenuItemBkgnd(LPDRAWITEMSTRUCT pdis);
Draws the icon on drop down menu items.
DrawMenuItemCheckmark
virtual void DrawMenuItemCheckmark(LPDRAWITEMSTRUCT pdis);
Draws the check marks on drop down menu items.
DrawMenuItemIcon
virtual void DrawMenuItemIcon(LPDRAWITEMSTRUCT pdis);
Draws the icon on drop down menu items.
DrawMenuItemText
DrawMenuItemText(LPDRAWITEMSTRUCT pdis);
Draws the text on drop down menu items.
LoadRegistryMRUSettings
virtual BOOL LoadRegistryMRUSettings(UINT nMaxMRU = 0);
Loads a list of Most Recently Used files from the registry.
LoadRegistrySettings
virtual BOOL LoadRegistrySettings(LPCTSTR szKeyName);
Loads settings for the application from the registry. By default this loads the size and position of the frame window, and the view state of the StatusBar and ToolBar. Override this function to load other settings from the registry.
MeasureMenuItem
virtual void MeasureMenuItem(MEASUREITEMSTRUCT *pmis);
Calculates the required size of the menu item when performing owner drawing.
RecalcLayout
virtual void RecalcLayout();
Repositions the child windows of the frame, such as the toolbar, status bar and view window.
RemoveMRUEntry
virtual void RemoveMRUEntry(LPCTSTR szMRUEntry);
Removes the specified text from the Most Recently Used list.
SaveRegistrySettings
virtual BOOL SaveRegistrySettings();
Saves the frame's setting in the registry. By default this saves the size and position of the frame window, and the view state of the StatusBar and ToolBar. Override this function to save other settings in the registry.
SetMenuBarBandSize
virtual void SetMenuBarBandSize();
Adjusts the size of the MenuBar when the frame is resized.
SetMenuIcons
virtual UINT SetMenuIcons(const std::vector<UINT>& MenuData,
               COLORREF crMask, UINT ToolBarID, UINT ToolBarDisabledID);
Replaces the set of icons to be used on drop down menu icons from the supplied bitmap IDs.
SetStatusIndicators
virtual void SetStatusIndicators();
Updates the status bar with changes to the CAPS, NUM LOCK, and SCRL indicators.
SetStatusText
virtual void SetStatusText();
Sets the text of the status bar.
SetToolBarImages
virtual void SetToolBarImages(COLORREF crMask, UINT ToolBarID,
                        UINT ToolBarHotID, UINT ToolBarDisabledID);
Sets the imagelists for the toolbar from the supplied bitmap IDs.
ShowMenu
virtual void ShowMenu(BOOL bShow);
Show or hide the menu.
ShowStatusBar
virtual void ShowStatusBar(BOOL bShow);
Show or hide the statusbar.
ShowToolBar
virtual void ShowToolBar(BOOL bShow);
Show or hide the toolbar.
UpdateMRUMenu
virtual void UpdateMRUMenu();
Updates the menu to display the MRU entries added by the AddMRUEntry function.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Refer to the Frames section for information on how to use this class to create frames.

Summary Information

Header file | frame.h
Win32/64 support | Yes
WinCE support | No
Library required | Comctl32.lib


CGDIObject

CGDIObject Class

Description

This class that CBitmap, CBrush, CFont, CPalette, CPen, and CRgn inherit from.

CGDIObject Members

Initialisation and Assignment
CGDIObject
CGDIObject();
Constructor for CGDIObject.
CGDIObject
CGDIObject(const CGDIObject& rhs);
Constructor for CGDIObject that creates a copy. CGDIObjects are reference counted, and each copy manages the same underlying HGDIOBJ.
Attach
void Attach(HGDIOBJ hObject);
Attaches a GDI HANDLE to the CGDIObject. The HGDIOBJ will be automatically deleted when the destructor is called unless it is detached.
Detach
HGDIOBJ Detach();
Detaches the HGDIOBJ from this object.
GetHandle
HGDIOBJ GetHandle() const;
Detaches the HGDIOBJ from this object.
GetObject
int GetObject(int nCount, LPVOID pObject) const;
Retrieves information for the specified graphics object.
operator =
void operator = (HGDIOBJ hObject);
Assigns a HGDIOBJ to the CGDIObject.
operator =
CGDIObject& operator = ( const CGDIObject& rhs );
Creates a copy of the CGDIObject. CGDIObjects are reference counted, and each copy manages the same underlying HGDIOBJ.

Remarks

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | file.h
Win32/64 support | Yes
WinCE support | Yes


CHeader

CHeader Class

Description

The CHeader class adds support for the header control. A header control is a window that is usually positioned above columns of text or numbers. It contains a title for each column, and it can be divided into parts. The user can drag the dividers that separate the parts to set the width of each column.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of animation controls.

CHeader Members

Construction
CHeader
CHeader();
Constructs a header control.
Attributes
GetBitmapMargin
int GetBitmapMargin() const;
Gets the width of the bitmap margin for a header control.
GetImageList
HIMAGELIST GetImageList() const;
Gets the handle to the image list that has been set for the header control.
GetItem
BOOL GetItem(int nPos, HDITEM* pHeaderItem) const;
Gets information about an item in a header control.
GetItemCount
int GetItemCount() const;
Gets a count of the items in a header control.
GetItemRect
CRect GetItemRect(int nIndex) const;
Gets the bounding rectangle for a given item in a header control.
GetOrderArray
BOOL GetOrderArray(LPINT piArray, int iCount);
Gets the current left-to-right order of items in a header control.
OrderToIndex
int OrderToIndex(int nOrder) const;
Retrieves an index value for an item based on its order in the header control.
SetBitmapMargin
int SetBitmapMargin(int nWidth);
Sets the width of the margin, specified in pixels, of a bitmap in the header control.
SetImageList
HIMAGELIST SetImageList(HIMAGELIST himl);
Assigns an image list to the header control.
SetItem
BOOL SetItem(int nPos, HDITEM* pHeaderItem);
Sets the attributes of the specified item in a header control..
SetOrderArray
BOOL SetOrderArray(int iCount, LPINT piArray);
Sets the left-to-right order of header items.
Operations
ClearAllFilters
int ClearAllFilters();
Clears all of the filters for the header control.
ClearFilter
int ClearFilter(int nColumn);
Clears the filter for the header control
CreateDragImage
HIMAGELIST CreateDragImage(int nIndex);
Creates a transparent version of an item image within the header control.
DeleteItem
BOOL DeleteItem(int nPos);
Deletes an item from the header control.
EditFilter
int EditFilter(int nColumn, BOOL bDiscardChanges);
Moves the input focus to the edit box when a filter button has the focus.
InsertItem
int InsertItem(int nPos, HDITEM* phdi);
Inserts a new item into the header control.
Layout
BOOL Layout(HDLAYOUT* pHeaderLayout);
Retrieves the correct size and position of the header control within the parent window.
SetFilterChangeTimeout
int SetFilterChangeTimeout(DWORD dwTimeOut);
Sets the timeout interval between the time a change takes place in the filter attributes and the posting of an HDN_FILTERCHANGE notification.
SetHotDivider
int SetHotDivider(CPoint pt);
int SetHotDivider(int nIndex);
Changes the color of a divider between header items to indicate the destination of an external drag-and-drop operation.
Overridables
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

A header control can be created as a child window of another control, such as a list box. However, the parent control is not aware of the header control and does not allow for the space taken up by the header, with the result that list items will appear behind the header. If you wish to use a header control in a list box or other control, the parent control must be owner-drawn so that all items are displayed in the correct position.

List view controls already have header controls. Instead of creating a header control for a list view, you use LVM_GETHEADER or ListView_GetHeader to retrieve the existing control.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CHotKey

CHotKey Class

Description

The CHotKey class adds support for the hot key control. A hot key control is a window that enables the user to enter a combination of keystrokes to be used as a hot key.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of animation controls.

CHotKey Members

CHotKey
CHotKey();
Constructs a hot key control.
GetHotKey
DWORD GetHotKey() const;
Gets the virtual key code and modifier flags of a hot key from the hot key control.
GetKeyName
CString GetKeyName(UINT vk, BOOL fExtended) const;
Translates the virtual-key code to a scan code.
SetHotKey
void SetHotKey(DWORD dwKey);
PSets the hot key combination for a hot key control.
SetRules
void SetRules(WORD wInvalidComb, WORD wModifiers);
Defines the invalid combinations and the default modifier combination for a hot key control.
Overridables
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

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.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CIPAddress

CIPAddress Class

Description

The CIPAddress class adds support for the IP Address control. An Internet Protocol (IP) address control allows the user to enter an IP address in an easily understood format. This control also allows the application to obtain the address in numeric form rather than in text form.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of IP Address controls.

CIPAddress Members

CIPAddress
CIPAddress();
Constructs the IP address control.
ClearAddress
void ClearAddress();
Clears the contents of the IP address control.
GetAddress
int GetAddress(BYTE& nField0, BYTE& nField1, BYTE& nField2, BYTE& nField3);
int GetAddress(DWORD* dwAddress);
Gets the address values for all four fields in the IP address control.
IsBlank
BOOL IsBlank() const;
Determines if all fields in the IP address control are blank.
SetAddress
void SetAddress(BYTE nField0, BYTE nField1, BYTE nField2, BYTE nField3);
void SetAddress(DWORD dwAddress);
Sets the address values for all four fields in the IP address control.
SetFieldFocus
void SetFieldFocus(WORD nField);
Sets the keyboard focus to the specified field in the IP address control. All of the text in that field will be selected.
SetFieldRange
void SetFieldRange(int nField, BYTE nLower, BYTE nUpper);
Sets the valid range for the specified field in the IP address control.
Overridables
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

An IP address control is not an edit control and it will not respond to EM_ messages. It will, however, send the owner window the following edit control notifications through the WM_COMMAND message. Note that the IP address control will also send private IPN_ notifications through the WM_NOTIFY message.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CListBox

CListBox Class

Description

The ListBox control displays a list of text or iconic items. One or multiple items can be selected from the list.

CListBox is the class responsible for creating a list-box control. It is typically used in a dialog.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of list box controls.

CListBox Members

Construction

CListBox
CListBox();
Constructor for CListBox.

Attributes

GetAnchorIndex
int GetAnchorIndex() const;
Returns the index of the item that the mouse last selected.
GetCaretIndex
int GetCaretIndex() const;
Returns the index of the item that has the focus rectangle.
GetCount
int GetCount() const;
Returns the number of items in the list box.
GetCurSel
int GetCurSel() const;
Returns the index of the currently selected item.
GetHorizontalExtent
int GetHorizontalExtent() const;
Returns the scrollable width, in pixels, of a list box.
GetItemData
DWORD GetItemData(int nIndex) const;
Returns the value associated with the specified item.
GetItemDataPtr
void* GetItemDataPtr(int nIndex) const;
Returns the value associated with the specified item.
GetItemHeight
int GetItemHeight(int nIndex) const;
Returns the height, in pixels, of an item in a list box.
GetItemRect
int GetItemRect(int nIndex, LPRECT lpRect) const;
Retrieves the client coordinates of the specified list box item.
GetLocale
LCID GetLocale() const;
Retrieves the locale of the list box. The high-order word contains the country/region code and the low-order word contains the language identifier.
GetSel
int GetSel(int nIndex) const;
Returns the selection state of a list box item.
GetSelCount
int GetSelCount() const;
Returns the number of selected items in a multiple-selection list box.
GetSelItems
int GetSelItems(int nMaxItems, LPINT rgIndex) const;
Creates an array of the indexes of all selected items in a multiple-selection list box and returns the total number of selected items.
GetText
int GetText(int nIndex, LPTSTR lpszBuffer) const;
Retrieves the string associated with a specified item and the length of the string.
GetTextLen
int GetTextLen(int nIndex) const;
Returns the length, in characters, of the string associated with a specified item.
GetTopIndex
int GetTopIndex() const;
Returns the index of the first visible item in a list box.
SetAnchorIndex
void SetAnchorIndex(int nIndex) const;
Sets the item that the mouse last selected to a specified item.
SetCaretIndex
int SetCaretIndex(int nIndex, BOOL bScroll) const;
Sets the focus rectangle to a specified list box item.
SetColumnWidth
void SetColumnWidth(int cxWidth) const;
Sets the width, in pixels, of all columns in a list box.
SetCurSel
int SetCurSel(int nSelect) const;
Selects a specified list box item.
SetHorizontalExtent
void SetHorizontalExtent(int cxExtent) const;
Sets the scrollable width, in pixels, of a list box.
SetItemData
int SetItemData(int nIndex, DWORD dwItemData) const;
Associates a value with a list box item.
SetItemDataPtr
int SetItemDataPtr(int nIndex, void* pData) const;
Associates a value with a list box item.
SetItemHeight
int SetItemHeight(int nIndex, UINT cyItemHeight) const;
Sets the height, in pixels, of an item or items in a list box.
SetLocale
LCID SetLocale(LCID nNewLocale) const;
Sets the locale of a list box and returns the previous locale identifier.
SetSel
int SetSel(int nIndex, BOOL bSelect) const;
Selects an item in a multiple-selection list box.
SetTabStops
SetTabStops(int nTabStops, LPINT rgTabStops) const;
BOOL SetTabStops(const int& cxEachStop) const;
BOOL SetTabStops() const;
Sets the tab stops to those specified in a specified array.
SetTopIndex
int SetTopIndex(int nIndex) const;
Scrolls the list box so the specified item is at the top of the visible range.

Operations

AddString
int AddString(LPCTSTR lpszItem) const;
Adds a string to a list box and returns its index.
DeleteString
int DeleteString(UINT nIndex) const;
Removes a string from a list box and returns the number of strings remaining in the list.
Dir
int Dir(UINT attr, LPCTSTR lpszWildCard) const;
Adds a list of filenames to a list box and returns the index of the last filename added.
FindString
int FindString(int nStartAfter, LPCTSTR lpszItem) const;
Returns the index of the first string in the list box that begins with a specified string.
FindStringExact
int FindStringExact(int nIndexStart, LPCTSTR lpszFind) const;
Returns the index of the string in the list box that is equal to a specified string.
InsertString
int InsertString(int nIndex, LPCTSTR lpszItem) const;
Inserts a string at a specified index in a list box.
ItemFromPoint
UINT ItemFromPoint(CPoint pt, BOOL& bOutside ) const;
Retrieves the zero-based index of the item nearest the specified point in a list box.
ResetContent
void ResetContent() const;
Removes all items from a list box.
SelectString
int SelectString(int nStartAfter, LPCTSTR lpszItem) const;
Selects the first string it finds that matches a specified prefix.
SelItemRange
int SelItemRange(BOOL bSelect, int nFirstItem, int nLastItem) const;
Selects a specified range of items in a list box.

Overidables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the ListBox control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a ListBox control.

List box items can be represented by text strings, bitmaps, or both. If the list box is not large enough to display all the list box items at once, the list box provides a scroll bar. The user scrolls through the list box items, and applies or removes selection status as necessary. Selecting a list box item changes its visual appearance, usually by changing the text and background colors to those specified by the relevant operating system metrics. When the user selects or deselects an item, the system sends a notification message to the parent window of the list box.

Summary Information

Header file | stdcontrols.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CListView

CListView Class

Description

A list-view control is a window that displays a collection of items. Each item consists of an icon and a label. List-view controls provide several ways to arrange and display items. For example, additional information about each item can be displayed in columns to the right of the icon and label.

CListView is the class responsible for creating a list-view control. It can be used as a control in a Dialog, or as the View window in a Frame, Docker, or MDI child.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of list view controls.

CListView Members

Construction

CListView
CListView() const;
Constructor for CListView.

Attributes

ApproximateViewRect
CSize ApproximateViewRect(CSize sz = CSize(-1, -1), int iCount = -1) const;
Calculates the approximate width and height required to display a given number of items.
GetBkColor
COLORREF GetBkColor( ) const;
Retrieves the background color of a list-view control.
GetBkImage
BOOL GetBkImage( LVBKIMAGE& lvbkImage ) const;
Retrieves the background image in a list-view control.
GetCallbackMask
UINT GetCallbackMask( ) const;
Retrieves the callback mask for a list-view control.
GetCheckState
BOOL GetCheckState( UINT nItem ) const;
Determines if an item in a list-view control is selected.
GetColumn
BOOL GetColumn( int iCol, LVCOLUMN& Column ) const;
Retrieves the attributes of a list-view control's column.
GetColumnOrderArray
BOOL GetColumnOrderArray( LPINT piArray, int iCount = -1 );
Retrieves the current left-to-right order of columns in a list-view control.
GetColumnWidth
int GetColumnWidth( int iCol ) const;
Retrieves the width of a column in report or list-view.
GetCountPerPage
int GetCountPerPage( ) const;
Calculates the number of items that can fit vertically in the visible area of a list-view control when in list or report view. Only fully visible items are counted.
GetEditControl
CEdit* GetEditControl( ) const;
Retrieves the handle to the edit control being used to edit a list-view item's text.
GetExtendedStyle
DWORD GetExtendedStyle( ) const;
Retrieves the extended styles that are currently in use for a given list-view control.
GetHeader
CHeader* GetHeader( ) const;
Retrieves the handle to the header control used by a list-view control.
GetHotCursor
HCURSOR GetHotCursor( );
Retrieves the HCURSOR used when the pointer is over an item while hot tracking is enabled.
GetHotItem
int GetHotItem( ) const;
Retrieves the index of the hot item.
GetHoverTime
DWORD GetHoverTime( ) const;
Retrieves the amount of time that the mouse cursor must hover over an item before it is selected.
GetImageList
HIMAGELIST GetImageList( int nImageType ) const;
Retrieves the handle to an image list used for drawing list-view items.
GetItem
BOOL GetItem( LVITEM& lvItem ) const;
Retrieves some or all of a list-view item's attributes.
GetItemCount
int GetItemCount( ) const;
Retrieves the number of items in a list-view control.
GetItemData
DWORD_PTR GetItemData( int iItem ) const;
Retrieves the application data from a list-view's item.
GetItemPosition
BOOL GetItemPosition( int iItem, CPoint& pt ) const;
Retrieves the position of a list-view item.
GetItemRect
BOOL GetItemRect( int iItem, CRect& rc, UINT nCode ) const;
Retrieves the bounding rectangle for all or part of an item in the current view.
GetItemState
UINT GetItemState( int iItem, UINT nMask ) const;
Retrieves the state of a list-view item.
GetItemText
CString GetItemText( int iItem, int iSubItem, UINT nTextMax = 260 ) const;
Retrieves the text of a list-view item or subitem.
GetNextItem
int GetNextItem( int iItem, int iFlags ) const;
Retrieves the text of a list-view item or subitem.
GetNumberOfWorkAreas
UINT GetNumberOfWorkAreas( ) const;
Retrieves the number of areas in a list-view control.
GetOrigin
BOOL GetOrigin( CPoint& pt ) const;
Retrieves the current view origin for a list-view control.
GetSelectedCount
UINT GetSelectedCount( ) const;
Determines the number of selected items in a list-view control.
GetSelectionMark
int GetSelectionMark( );
Retrieves the selection mark from a list-view control.
GetStringWidth
int GetStringWidth( LPCTSTR pszString ) const;
Determines the width of a specified string using the specified list-view control's current font.
GetSubItemRect
BOOL GetSubItemRect( int iItem, int iSubItem, int iCode, CRect& rc );
Retrieves information about the rectangle that surrounds a subitem in a list-view control. This macro is intended to be used only on list-view controls that use the LVS_REPORT style.
GetTextBkColor
COLORREF GetTextBkColor( ) const;
Retrieves the text background color of a list-view control.
GetTextColor
COLORREF GetTextColor( ) const;
Retrieves the text color of a list-view control.
GetToolTips
CToolTip* GetToolTips( ) const;
Retrieves the ToolTip control that the list-view control uses to display ToolTips.
GetTopIndex
int GetTopIndex( ) const;
Retrieves the index of the topmost visible item when in list or report view.
GetViewRect
BOOL GetViewRect( CRect& rc ) const;
Retrieves the bounding rectangle of all items in the list-view control.
GetWorkAreas
void GetWorkAreas( int iWorkAreas, LPRECT pRectArray ) const;
Retrieves the working areas from a list-view control.
SetBkColor
BOOL SetBkColor( COLORREF clrBk );
Sets the background color of a list-view control.
SetBkImage
BOOL SetBkImage( LVBKIMAGE& plvbkImage );
Sets the background image in a list-view control.
SetCallbackMask
BOOL SetCallbackMask( UINT nMask );
Changes the callback mask for a list-view control.
SetCheckState
void SetCheckState( int iItem, BOOL fCheck = TRUE );
Used to select or deselect an item in a list-view control.
SetColumn
BOOL SetColumn( int iCol, const LVCOLUMN& pColumn );
Sets the attributes of a list-view column.
SetColumnOrderArray
BOOL SetColumnOrderArray( int iCount, LPINT piArray );
Sets the left-to-right order of columns in a list-view control.
SetColumnWidth
BOOL SetColumnWidth( int iCol, int cx );
Used to change the width of a column in report view or the width of all columns in list-view mode.
SetExtendedStyle
DWORD SetExtendedStyle( DWORD dwNewStyle );
Sets extended styles for list-view controls.
SetHotCursor
HCURSOR SetHotCursor( HCURSOR hCursor );
Sets the HCURSOR that the list-view control uses when the pointer is over an item while hot tracking is enabled. To check whether or not hot tracking is enabled, call SystemParametersInfo.
SetHotItem
int SetHotItem( int nIndex );
Sets the hot item in a list-view control.
SetHoverTime
DWORD SetHoverTime( DWORD dwHoverTime = (DWORD)-1 );
Sets the amount of time that the mouse cursor must hover over an item before it is selected.
SetIconSpacing
CSize SetIconSpacing( int cx, int cy ) const;
CSize SetIconSpacing( CSize sz ) const;
Sets the spacing between icons in list-view controls set to the LVS_ICON style.
SetImageList
HIMAGELIST SetImageList( HIMAGELIST himl, int iImageListType ) const;
Assigns an image list to a list-view control.
SetItem
BOOL SetItem( LVITEM& pItem ) const;
BOOL SetItem( int iItem, int iSubItem, UINT nMask, LPCTSTR pszText, int iImage,
              UINT nState, UINT nStateMask, LPARAM lParam, int iIndent ) const;
Sets some or all of a list-view item's attributes.
SetItemCount
void SetItemCount( int iCount ) const;
Causes the list-view control to allocate memory for the specified number of items.
SetItemCountEx
void SetItemCountEx( int iCount, DWORD dwFlags = LVSICF_NOINVALIDATEALL ) const;
Sets the virtual number of items in a virtual list view.
SetItemData
BOOL SetItemData( int iItem, DWORD_PTR dwData ) const;
Sets the application data for a list-view's item.
SetItemPosition
BOOL SetItemPosition( int iItem, CPoint& pt ) const;
Moves an item to a specified position in a list-view control (in icon or small icon view).
SetItemState
BOOL SetItemState( int iItem, LVITEM& Item ) const;
void SetItemState( int iItem, UINT nState, UINT nMask ) const;
Changes the state of an item in a list-view control.
SetItemText
void SetItemText( int iItem, int iSubItem, LPCTSTR pszText ) const;
Changes the text of a list-view item or subitem.
SetSelectionMark
int SetSelectionMark( int iIndex ) const;
Sets the selection mark in a list-view control.
SetTextBkColor
BOOL SetTextBkColor( COLORREF clrBkText ) const;
Sets the background color of text in a list-view control.
SetTextColor
BOOL SetTextColor( COLORREF clrText ) const;
Sets the text color of a list-view control.
SetToolTips
CToolTip* SetToolTips ( CToolTip* pToolTip ) const;
Sets the ToolTip control that the list-view control will use to display ToolTips.
SetWorkAreas
void SetWorkAreas( int nWorkAreas, CRect& pRectArray ) const;
Sets the working area within a list-view control.
SubItemHitTest
int SubItemHitTest( LVHITTESTINFO& htInfo ) const;
Determines which list-view item or subitem is located at a given position.

Operations

Arrange
BOOL Arrange( UINT nCode ) const;
Arranges items in icon view.
CreateDragImage
HIMAGELIST CreateDragImage( int iItem, CPoint& pt ) const;
Creates a drag image list for the specified item.
DeleteAllItems
BOOL DeleteAllItems( ) const;
Removes all items from a list-view control.
DeleteColumn
BOOL DeleteColumn( int iCol ) const;
Removes a column from a list-view control.
DeleteItem
BOOL DeleteItem( int iItem ) const;
Removes an item from a list-view control.
EditLabel
CEdit* EditLabel( int iItem ) const;
Begins in-place editing of the specified list-view item's text. This implicitly selects and focuses the specified item.
EnsureVisible
BOOL EnsureVisible( int iItem, BOOL fPartialOK ) const;
Ensures that a list-view item is either entirely or partially visible, scrolling the list-view control if necessary.
FindItem
int FindItem( LVFINDINFO& FindInfo, int iStart = -1 ) const;
Searches for a list-view item with the specified characteristics.
HitTest
int HitTest( LVHITTESTINFO& HitTestInfo ) const;
int HitTest( CPoint pt, UINT* pFlags = NULL ) const;
Determines which list-view item, if any, is at a specified position.
InsertColumn
int InsertColumn( int iCol, const LVCOLUMN& pColumn ) const;
int InsertColumn( int iCol, LPCTSTR pszColumnHeading, int iFormat = LVCFMT_LEFT,
                  int iWidth = -1, int iSubItem = -1 ) const;
Inserts a new column in a list-view control.
InsertItem
int InsertItem( const LVITEM& pItem ) const;
int InsertItem( int iItem, LPCTSTR pszText ) const;
int InsertItem( int iItem, LPCTSTR pszText, int iImage ) const;
Inserts a new item in a list-view control.
RedrawItems
BOOL RedrawItems( int iFirst, int iLast ) const;
Forces a list-view control to redraw a range of items.
Scroll
BOOL Scroll( CSize sz ) const;
Scrolls the content of a list-view control.
SortItems
BOOL SortItems( PFNLVCOMPARE pfnCompare, DWORD_PTR dwData ) const;
Uses an application-defined comparison function to sort the items of a list-view control. The index of each item changes to reflect the new sequence.
Update
BOOL Update( int iItem ) const;
Updates a list-view item. If the list-view control has the LVS_AUTOARRANGE style, this macro causes the list-view control to be arranged.

Overidables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the list-view control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a list-view control.

Refer to the explorer sample to see a demonstration of the CListView and CTreeView classes.

Summary Information

Header file | listview.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CMDIChild

CMDIChild Class

Description

This class provides a child window for MDI (Multi Document Interface) applications. MDI applications are capable of hosting several child windows within a frame.

The CMDIChild class inherits much of its default implementation from CWnd, and adds the additional functionality required for MDI applications.

CMDIChild Members

CMDIChild
CMDIChild();
Constructor for CMDIChild.
GetMDIFrame
CMDIFrame* GetMDIFrame() const;
Returns a pointer to the MDI Frame.
GetView
virtual CWnd* GetView() const {return m_pView;}
Returns a pointer to the MDI Child's view window.

MDIActivate

void MDIActivate() const;
Activates this MDI child.
MDIDestroy
void MDIDestroy() const;
Destroys this MDI child.
MDIMaximize
void MDIMaximize() const;
Maximizes this MDI Child.
MDIRestore
void MDIRestore() const;
Restores this MDI child from a maximized or minimized state.
RecalcLayout
virtual void RecalcLayout();
Repositions the view window when the MDI child is restored.
SetChildMenu
virtual void SetChildMenu(LPCTSTR MenuName);
Sets the MDI child menu, given its Resource ID.
SetHandles
void SetHandles(HMENU MenuName, HACCEL AccelName);
Sets the MDI child's menu and accelerator table.
SetView
virtual void SetView(CWnd& pwndView);
Sets the view window for the MDI child.

Overridables

Create
virtual HWND Create(HWND hWndParent = NULL);
Creates the MDI child window.
OnCreate
virtual void OnCreate();
Called when the MDI child window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Setting the MDI Child's View window and Menu

Each type of MDI child will have a view window and will usually have a unique menu. The menu which is displayed in the MDI frame will belong the the MDI child that has keyboard focus, or the MDI frame's menu if no MDI child is active. The SetView function sets the view window, and the SetChildMenu seta the menu of a MDI child, as follows.

CSimpleMDIChild::CSimpleMDIChild()
{
  // Set m_View as the view window of the MDI child
  SetView(m_View);

  // Set the menu for this MDI child
  SetChildMenu(_T("MdiMenuView"));
}

The MDI child's menu would be defined in the resource script file (usually Resource.rc) as follows.

MDIMENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "New &View\tCtrl+N",           IDM_FILE_NEW
        MENUITEM "&Close",                      IDM_FILE_CLOSE
        MENUITEM SEPARATOR
        MENUITEM "E&xit",                       IDM_FILE_EXIT
    END
    POPUP "&View"
    BEGIN
        MENUITEM "&Tool Bar",                   IDW_VIEW_TOOLBAR, CHECKED
        MENUITEM "&Status Bar",                 IDW_VIEW_STATUSBAR, CHECKED
    END
    POPUP "&Window"
    BEGIN
        MENUITEM "&Cascade\tShift+F5",          IDW_WINDOW_CASCADE
        MENUITEM "&Tile\tShift+F4",             IDW_WINDOW_TILE
        MENUITEM "Arrange &Icons",              IDW_WINDOW_ARRANGE
        MENUITEM "Close &All",                  IDW_WINDOW_CLOSEALL
    END
    POPUP "&Help"
    BEGIN
        MENUITEM "&About",                      IDM_HELP_ABOUT
    END
END

Setting the MDI Child's Title and Icon

Each type of MDI child usually has an icon. The MDI child's icon and title are is set as follows.

void CMDIChildView::OnInitialUpdate()
{
  ::SetWindowText(m_hWnd, _T("MDI Child Window"));
  SetIconLarge(IDI_VIEW);
  SetIconSmall(IDI_VIEW);
}

Refer to the MDI Frames section for information on how to use CMDIChild with CMDIFrame.

Summary Information

Header file | mdi.h
Win32/64 support | Yes
WinCE support | No


CMDIFrame

CMDIFrame Class

Description

This class provides a frame for MDI (Multi Document Interface) applications. MDI applications are capable of hosting several child windows within a frame.

The CMDIFrame class inherits much of its default implementation from CFrame, and adds the additional functionality required for MDI frames. The CWnd classes for the MDI child windows should be inherited from CMDIChild.

CMDIFrame Members

Constructor

CMDIFrame
CMDIFrame();
Constructor for CMDIFrame.

Attributes

GetActiveMDIChild
CMDIChild* GetActiveMDIChild() const;
Returns the CMDIChild pointer to the active MDI child.
GetAllMDIChildren
std::vector <MDIChildPtr>& GetAllMDIChildren();
Returns the vector containing the MDI child handles.
GetMDIClient
virtual CMDIClient& GetMDIClient() const;
Returns a pointer to the MDI client window.
SetActiveMDIChild
void SetActiveMDIChild(CMDIChild* pChild);
Activates the specified MDI child.

State functions

IsMDIChildMaxed
BOOL IsMDIChildMaxed() const;
Returns TRUE if the MDI child is maximised.

Operations

AddMDIChild
virtual CMDIChild* AddMDIChild(MDIChildPtr pMDIChild);
Adds a MDI child window.
MDICascade
void MDICascade(int nType = 0) const;
Arrange all MDI child windows in a cascade format.
MDIIconArrange
void MDIIconArrange() const;
Arrange all minimized MDI child windows.
MDIMaximize
void MDIMaximize() const;
Maximize a MDI child window.
MDINext
void MDINext() const;
Activate the next MDI child.
MDIPrev
void MDIPrev() const;
Activate the previous MDI child.
MDIRestore
void MDIRestore() const;
Restores a MDI child window from maximized or minimized size.
MDITile
void MDITile(int nType = 0) const;
Arrange all MDI child windows in a tile format.
RemoveAllMDIChildren
virtual BOOL RemoveAllMDIChildren();
Removes all MDI child windows.
RemoveMDIChild
virtual void RemoveMDIChild(HWND hWnd);
Removes a MDI child, given its window handle.
UpdateCheckMarks
virtual void UpdateCheckMarks();
Updates the menu checkmarks for View ToolBar and View StatusBar.

Overridables

OnClose
virtual void OnClose();
Called when the frame window is closed.
OnViewStatusBar
virtual void OnViewStatusBar();
Called when the StatusBar is shown.
OnViewToolBar
virtual void OnViewToolBar();
Called when the ToolBar window is shown.
OnWindowPosChanged
virtual void OnWindowPosChanged();
Called when the size, position, or Z-order of the frame window has changed
PreTranslateMessage
virtual BOOL PreTranslateMessage(MSG* pMsg);
Used to translate window messages before they are dispatched to the TranslateMessage and DispatchMessage Windows functions.
Base class Members

For base class members, refer to the members of CFrame.

Remarks

Refer to the MDI Frames section for information on how to create MDI Frames and MDI Children.

Summary Information

Header file | mdi.h
Win32/64 support | Yes
WinCE support | No
Library required | Comctl32.lib


CMemDC

CMemDC Class

Description

The class responsible for creating a memory device context.

CMemDC Members

Initialization and Assignment

Initialization and Assignment
CMemDC
CMemDC(const CDC* pDC);
Constructs a CMemDC object.
Base class Members

For base class members, refer to the members of CDC.

Remarks

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CMenu

CMenu Class

Description

CMenu adds support for menus to Win32++. A menu is a list of items that specify options or groups of options (a submenu) for an application. Clicking a menu item opens a submenu or causes the application to carry out a command.

A menu is arranged in a hierarchy. At the top level of the hierarchy is the menu bar which contains a list of menus, which in turn can contain submenus. A menu bar is sometimes called a top-level menu, and the and submenus are also known as pop-up menus.

A menu item can either carry out a command or open a submenu. An item that carries out a command is called a command item or a command.

CMenu Members

Initialisation and Assignment
CMenu
CMenu();
CMenu(UINT nID);
Constructor for CMenu.
Attach
void Attach(HMENU hMenu);
Attaches an existing menu to this CMenu.
CreateMenu
void CreateMenu();
Creates an empty menu.
CreatePopupMenu
void CreatePopupMenu();
Creates a drop-down menu, submenu, or shortcut menu. The menu is initially empty..
DestroyMenu
void DestroyMenu();
Destroys the menu.
Detach
HMENU Detach();
Detaches the HMENU from this CMenu. If the HMENU is not detached it will be destroyed when this CMenu is deconstructed.
GetHandle
HMENU GetHandle() const;
Returns the HMENU assigned to this CMenu.
LoadMenu
BOOL LoadMenu(LPCTSTR lpszResourceName);
BOOL LoadMenu(UINT uIDResource);
BOOL LoadMenuIndirect(const void* lpMenuTemplate);
Loads the menu from the specified windows resource or template.
TrackPopupMenu
BOOL TrackPopupMenu(UINT uFlags, int x, int y, CWnd* pWnd, LPCRECT lpRect = 0);
Displays a shortcut menu at the specified location and tracks the selection of items on the menu..
TrackPopupMenuEx
BOOL TrackPopupMenuEx(UINT uFlags, int x, int y, CWnd* pWnd, LPTPMPARAMS lptpm);
Displays a shortcut menu at the specified location and tracks the selection of items on the shortcut menu.
Menu Item Operations
AppendMenu
BOOL AppendMenu(UINT uFlags, UINT_PTR uIDNewItem = 0, LPCTSTR lpszNewItem = NULL);
BOOL AppendMenu(UINT uFlags, UINT_PTR uIDNewItem, const CBitmap* pBmp);
Appends a new item to the end of the specified menu bar, drop-down menu, submenu, or shortcut menu.
CheckMenuItem
UINT CheckMenuItem(UINT uIDCheckItem, UINT uCheck);
Sets the state of the specified menu item's check-mark attribute to either selected or clear.
CheckMenuRadioItem
BOOL CheckMenuRadioItem(UINT uIDFirst, UINT uIDLast, UINT uIDItem, UINT uFlags);
Checks a specified menu item and makes it a radio item. At the same time, the function clears all other menu items in the associated group and clears the radio-item type flag for those items.
DeleteMenu
BOOL DeleteMenu(UINT uPosition, UINT uFlags);
Deletes an item from the specified menu.
EnableMenuItem
UINT EnableMenuItem(UINT uIDEnableItem, UINT uEnable);
Enables, disables, or grays the specified menu item. The uEnable parameter must be a combination of either MF_BYCOMMAND or MF_BYPOSITION and MF_ENABLED, MF_DISABLED, or MF_GRAYED.
GetDefaultItem
UINT GetDefaultItem(UINT gmdiFlags, BOOL fByPos = FALSE);
Determines the default menu item. The gmdiFlags parameter specifies how the function searches for menu items. This parameter can be zero or more of the following values: GMDI_GOINTOPOPUPS; GMDI_USEDISABLED.
GetMenuContextHelpId
DWORD GetMenuContextHelpId() const;
Retrieves the Help context identifier associated with the menu.
GetMenuInfo
BOOL GetMenuInfo(LPMENUINFO lpcmi) const;
Retrieves the menu information.
GetMenuItemCount
UINT GetMenuItemCount() const;
Retrieves the number of menu items.
GetMenuItemID
UINT GetMenuItemID(int nPos) const;
Retrieves the menu item identifier of a menu item located at the specified position
GetMenuItemInfo
BOOL GetMenuItemInfo(UINT uItem, LPMENUITEMINFO lpMenuItemInfo, BOOL fByPos = FALSE);
Retrieves information about the specified menu item.
GetMenuState
UINT GetMenuState(UINT uID, UINT uFlags) const;
Retrieves the menu flags associated with the specified menu item. Possible values for uFlags are: MF_BYCOMMAND (default) or MF_BYPOSITION.
GetMenuString
int GetMenuString(UINT uIDItem, LPTSTR lpString, int nMaxCount, UINT uFlags) const;
int GetMenuString(UINT uIDItem, CString& rString, UINT uFlags) const;
Copies the text string of the specified menu item into the specified buffer.
GetSubMenu
CMenu* GetSubMenu(int nPos);
Retrieves the CMenu object of a pop-up menu.
InsertMenu
BOOL InsertMenu(UINT uPosition, UINT uFlags, UINT_PTR uIDNewItem = 0, LPCTSTR lpszNewItem = NULL);
BOOL InsertMenu(UINT uPosition, UINT uFlags, UINT_PTR uIDNewItem, const CBitmap* pBmp);
Inserts a new menu item into a menu, moving other items down the menu.
InsertMenuItem
BOOL InsertMenuItem(UINT uItem, LPMENUITEMINFO lpMenuItemInfo, BOOL fByPos = FALSE);
Inserts a new menu item at the specified position in a menu.
ModifyMenu
BOOL ModifyMenu(UINT uPosition, UINT uFlags, UINT_PTR uIDNewItem = 0, LPCTSTR lpszNewItem = NULL);
BOOL ModifyMenu(UINT uPosition, UINT uFlags, UINT_PTR uIDNewItem, const CBitmap* pBmp);
Changes an existing menu item. This function is used to specify the content, appearance, and behavior of the menu item.
RemoveMenu
BOOL RemoveMenu(UINT uPosition, UINT uFlags);
Deletes a menu item or detaches a submenu from the menu.
SetDefaultItem
BOOL SetDefaultItem(UINT uItem, BOOL fByPos = FALSE);
Sets the default menu item for the menu.
SetMenuContextHelpId
BOOL SetMenuContextHelpId(DWORD dwContextHelpId);
Associates a Help context identifier with the menu.
SetMenuInfo
BOOL SetMenuInfo(LPCMENUINFO lpcmi);
Writes the specified buffer to the file.
SetMenuItemBitmaps
BOOL SetMenuItemBitmaps(UINT uPosition, UINT uFlags, const CBitmap* pBmpUnchecked, const CBitmap* pBmpChecked);
Associates the specified bitmap with a menu item.
SetMenuItemInfo
BOOL SetMenuItemInfo(UINT uItem, LPMENUITEMINFO lpMenuItemInfo, BOOL fByPos = FALSE);
Changes information about a menu item.
Operators
operator !=
BOOL operator != (const CMenu& menu) const;
Returns TRUE if the two menu objects are not equal.
operator ==
BOOL operator == (const CMenu& menu) const;
Returns TRUE of the two menu object are equal.
operator HMENU ()
operator HMENU () const;
Retrieves the menu's handle.

Remarks

CMenu objects can be used anywhere a a handle to a menu (HMENU) might be used. They can be substituted for the HMENU in any of the Windows API functions which use a HMENU as a function argument. The benefit of using a CMenu object is that it automatically deletes the menu when it is destroyed.

Summary Information

Header file | file.h
Win32/64 support | Yes
WinCE support | Yes


CMenuBar

CMenuBar Class

Description

The CMenuBar class provides a menu inside a rebar control. This menu is based on a toolbar control, and CMenuBar inherits from CToolBar.

Member functions

CMenuBar
CMenuBar();
Constructor for CMenuBar.
GetMenu
HMENU GetMenu() const;
Returns the handle to the menu displayed by the menubar.
GetMenuBarTheme
MenuTheme& GetMenuBarTheme();
Returns the theme structure associated with the menubar.
SetMenu
virtual void SetMenu(HMENU hMenu);
Sets the menu for the MenuBar.
SetMenuBarTheme
virtual void SetMenuBarTheme(MenuTheme& Theme);
Set the theme structure associated with the menubar.

Overridables

OnCreate
virtual void OnCreate();
Called when the window is created.
OnCustomDraw
virtual LRESULT OnCustomDraw(NMHDR* pNMHDR);
Called to perform custom drawing.
OnKeyDown
virtual void OnKeyDown(WPARAM wParam, LPARAM lParam);
Called when a key is pressed.
OnLButtonDown
virtual void OnLButtonDown(WPARAM wParam, LPARAM lParam);
Called when the left mouse button is pressed.
OnLButtonUp
virtual void OnLButtonUp(WPARAM wParam, LPARAM lParam);
Called when a key is released.
OnMenuChar
virtual void OnMenuChar(WPARAM wParam, LPARAM lParam);
Called when the user presses a menu mnemonic character that doesn't match any of the predefined mnemonics in the current menu.
OnMenuInput
virtual BOOL OnMenuInput(UINT uMsg, WPARAM wParam, LPARAM lParam);
Called to process menu input.
OnMouseLeave
virtual void OnMouseLeave();
Called when the cursor leave the client area of the window.
OnMouseMove
virtual void OnMouseMove(WPARAM wParam, LPARAM lParam);
Called when the cursor moves.
OnNotifyReflect
virtual LRESULT OnNotifyReflect(WPARAM wParam, LPARAM lParam);
Called in response to a notification from the menubar.
OnSysCommand
virtual void OnSysCommand(WPARAM wParam, LPARAM lParam);
Called to processes keys when the Alt or F10 key is pressed.
OnWindowPosChanged
virtual void OnWindowPosChanged();
Called when the windows size or position has changed.
PreCreate
virtual void PreCreate(CREATESTRUCT &cs);
Sets the window creating parameters.
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Sets the window class parameters.
Base class Members

For base class members, refer to the members of CToolBar.

Remarks

CMenuBar is used by CFrame and CMDIFrame to provide the menu.

Summary Information

Header file | frame.h
Win32/64 support | Yes
WinCE support | No
Library required | Comctl32.lib


CMetaFileDC

CMetaFileDC Class

Description

The class responsible for creating a metafile device context.

A metafile, also called a vector image, is an image that is stored as a sequence of drawing commands and settings. The commands and settings recorded in a Metafile object can be stored in memory or saved to a file or stream.

CMetaFileDC Members

Initialization and Assignment

Initialization and Assignment
CMetaFileDC
CMetaFileDC();
Constructs a CMetaFileDC object.
Operations
Create
void Create(LPCTSTR lpszFilename = NULL);
Creates a metafile and attaches it to the device context.
CreateEnhanced
void CreateEnhanced(CDC* pDCRef, LPCTSTR lpszFileName, LPCRECT lpBounds, LPCTSTR lpszDescription);
Creates an enhanced metafile and attaches it to the device context.
Close
HMETAFILE Close();
Closes the metafile.
CloseEnhanced
HENHMETAFILE CloseEnhanced();
Closes the enhanced metafile.
Base class Members

For base class members, refer to the members of CDC.

Remarks

To use the CMetaFileDC, create the CMetafileDC object, and then create the metafile or enhanced metafile. Enhanced metafiles are supported by all 32-bit and 64-bit Windows operating systems. These should be the default metafiles used by all modern windows applications.

Once the Metafile is closed the HMETAFILE or HENHMETADILE handle can be used to play the metafile. The handle returned by Close or CloesEnhanced should be deleted when it no longer required.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CMonthCalendar

CMonthCalendar Class

Description

The CHotKey class adds support for the month calendar control. The month calendar control provides the user with an intuitive and recognizable method of entering or selecting a date. The control also provides the application with the means to obtain and set the date information in the control using existing data types.

CMonthCalendar Members

Construction
CMonthCalendar
CMonthCalendar();
Constructs a month calendar control.
Attributes
GetColor
COLORREF GetColor(int nRegion) const;
Retrieves the color for a given portion of the month calendar control.
GetFirstDayOfWeek
int GetFirstDayOfWeek(BOOL* pbLocal = NULL) const;
Retrieves the first day of the week for the month calendar control.
GetMinReqRect
CRect GetMinReqRect() const;
Retrieves the minimum size required to display a full month in the month calendar control.
GetMonthDelta
int GetMonthDelta() const;
Retrieves 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.
SetColor
COLORREF SetColor(int nRegion, COLORREF ref);
Sets the color for a given portion of the month calendar control.
SetFirstDayOfWeek
BOOL SetFirstDayOfWeek(int iDay, int* lpnOld = NULL);
Sets the first day of the week for the month calendar control.
SetMonthDelta
int SetMonthDelta(int iDelta);
Sets 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.
Operations
GetCurSel
BOOL GetCurSel(LPSYSTEMTIME pDateTime) const;
Retrieves the currently selected date.
GetMaxSelCount
int GetMaxSelCount() const;
Retrieves the maximum date range that can be selected in a month calendar control.
GetMonthRange
int GetMonthRange(LPSYSTEMTIME pMinRange, LPSYSTEMTIME pMaxRange, DWORD dwFlags) const;
Retrieves date information (using SYSTEMTIME structures) that represents the high and low limits of the month calendar control's display.
GetSelRange
DWORD GetRange(LPSYSTEMTIME pMinRange, LPSYSTEMTIME pMaxRange) const;
Retrieves date information that represents the upper and lower limits of the date range currently selected by the user.
GetToday
BOOL GetToday(LPSYSTEMTIME pDateTime) const;
Retrieves the date information for the date specified as "today" for the month calendar control.
HitTest
DWORD HitTest(PMCHITTESTINFO pMCHitTest);
Determines which portion of the month calendar control is at a given point on the screen.
SetCurSel
BOOL SetCurSel(const LPSYSTEMTIME pDateTime);
Sets the currently selected date for the month calendar control. If the specified date is not in view, the control updates the display to bring it into view.
SetDayState
BOOL SetDayState(int nMonths, LPMONTHDAYSTATE pStates);
Sets the day states for all months that are currently visible within the month calendar control.
SetMaxSelCount
BOOL SetMaxSelCount(int nMax);
Sets the maximum number of days that can be selected in the month calendar control.
SetRange
BOOL SetRange(const LPSYSTEMTIME pMinRange, const LPSYSTEMTIME pMaxRange);
Sets the minimum and maximum allowable dates for the month calendar control.
SetSelRange
BOOL SetSelRange(const LPSYSTEMTIME pMinRange, const LPSYSTEMTIME pMaxRange);
Sets the selection for a month calendar control to the given date range.
SetToday
void SetToday(const LPSYSTEMTIME pDateTime);
Sets the "today" selection for a month calendar control.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes


CPaintDC

CPaintDC Class

Description

The class responsible for creating a device context for drawing to a window during the handling of the WM_PAINT message. This device context is used by CWnd::OnDraw.

CPaintDC Members

Initialization and Assignment

Initialization and Assignment
CPaintDC
CPaintDC(const CWnd* pWnd);
Constructs a CPaintDC object.
Base class Members

For base class members, refer to the members of CDC.

Remarks

This class automatically calls CWnd::BeginPaint when it is constructed, and automatically calls CWnd::EndPaint when it is destroyed.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CPalette

CPalette Class

Description

The class responsible for creating and managing palette resources.

CPalette Members

Initialization and Assignment

Initialization and Assignment
CPalette
CPalette();
CPalette(HPALETTE hPalette);
Constructs a CPaletteBrush object.
operator HPALETTE()
operator HPALETTE() const;
Allows a CPalette object to be used as a palette handle (HPALETTE).
Attributes
GetEntryCount
int GetEntryCount() const;
Retrieve the number of entries in the palette.
GetNearestPaletteIndex
UINT GetNearestPaletteIndex (COLORREF crColor) const;
Retrieves the index for the entry in the palette most closely matching a specified color value.
GetPaletteEntries
UINT GetPaletteEntries(UINT nStartIndex, UINT nNumEntries,
                       LPPALETTEENTRY lpPaletteColors) const;
Retrieves a specified range of palette entries from the palette.
SetPaletteEntries
UINT SetPaletteEntries(UINT nStartIndex, UINT nNumEntries,
                       LPPALETTEENTRY lpPaletteColors);
Sets RGB (red, green, blue) color values and flags in a range of entries in the palette.
Operations
AnimatePalette
void AnimatePalette(UINT nStartIndex, UINT nNumEntries,
               LPPALETTEENTRY lpPaletteColors);
Replaces entries in the palette.
CreateHalftonePalette
HPALETTE CreateHalftonePalette(CDC* pDC);
Creates a halftone palette for the specified device context (DC).
CreatePalette
HPALETTE CreatePalette(LPLOGPALETTE lpLogPalette);
Creates a logical palette from the information in the specified LOGPALETTE structure.
Base class Members

For base class members, refer to the members of CGDIObject.

Remarks

CPalette objects can be used anywhere a a handle to a brush (HPALETTE) might be used. They can be substituted for the HPALETTE in any of the Windows API functions which use a HPALETTE as a function argument. The benefit of using a CPalette object is that it automatically deletes the brush when it is destroyed.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CPen

CPen Class

Description

The class responsible for creating and managing pen resources.

CPen Members

Initialization and Assignment
CPen
CPen();
CPen(HPEN hPen);
CPen(int nPenStyle, int nWidth, COLORREF crColor);
CPen(int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush,
               int nStyleCount = 0, const DWORD* lpStyle = NULL);
Constructs a CPen object.
operator HPEN()
operator HPEN() const;
Allows a CPen object to be used as a pen handle (HPEN).
Attributes
GetExtLogPen
EXTLOGPEN GetExtLogPen() const;
Retrieves the EXTLOGPEN struct that specifies the pen's style, width, color and brush attributes.
GetLogPen
LOGPEN GetLogPen() const;
Retrieves the LOGPEN struct that specifies the pen's style, width, and color.
Operations
CreatePen
HPEN CreatePen(int nPenStyle, int nWidth, COLORREF crColor);
Creates a logical brush from style, color, and pattern specified in the LOGPRUSH struct.
CreatePenIndirect
HPEN CreatePenIndirect(LPLOGPEN lpLogPen);
Creates a logical brush that has the pattern specified by the device-independent bitmap (DIB).
ExtCreatePen
HPEN ExtCreatePen(int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush,
                  int nStyleCount = 0, const DWORD* lpStyle = NULL);
Creates a logical brush that has the specified hatch pattern and color.
Base class Members

For base class members, refer to the members of CGDIObject.

Remarks

CPen objects can be used anywhere a a handle to a brush (HPEN) might be used. They can be substituted for the HPEN in any of the Windows API functions which use a HPEN as a function argument. The benefit of using a CPen object is that it automatically deletes the brush when it is destroyed.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CPoint

CPoint Class

Description

A CPoint can be used anywhere that a POINT structure could be used.

CPoint Members

CPoint
CPoint();
CPoint(int X, int Y);
CPoint(SIZE sz);
CPoint(POINT pt);
CPoint(DWORD dw);
Various methods of constructing a CPoint.
operator LPPOINT()
operator LPPOINT();
Returns a pointer to the POINT associated with this object.
operator ==
BOOL operator == (POINT pt) const;
Returns TRUE if the co-ordinates of the source point and the CPoint are equal.
operator !=
BOOL operator != (POINT pt) const;
Returns TRUE if the of the source point and the CPoint are not equal.
operator +=
void operator += (SIZE sz);
void operator += (POINT pt);
Adds the specified point.
operator -=
void operator -= (SIZE sz);
void operator -= (POINT pt);
Subtracts the specified point.
operator -
CPoint operator - () const;
Returns the unary minus (additive inverse).
operator +
CPoint operator + (SIZE sz) const;
CPoint operator + (POINT pt) const;
CRect operator + (RECT rc) const;
Adds the point and returns the value.
operator -
CPoint operator - (SIZE sz) const;
CPoint operator - (POINT pt) const;
CRect operator - (RECT rc) const;
Subtracts the point and returns the value.
Offset
void Offset(int dx, int dy);
void Offset(POINT pt);
void Offset(SIZE sz);
Moves the CPoint by the specified offsets.
SetPoint
void SetPoint(int X, int Y);
Sets the coordinates of the CPoint.

Remarks

By default, the constructor sets all the size coordinates zero, but the CPoint can also be constructed from two integers, a size, a point, or a dword.

The CPoint class inherits from the POINT structure. As a result, the data members of the underlying POINT struct are also accessible as data members.

Summary Information

Header file | winutils.h
Win32/64 support | Yes
WinCE support | Yes


CProgressBar

CProgressBar Class

Description

The CProgressBar class is used to create and manage a progress bar control. A progress bar is a window that an application can use to indicate the progress of a lengthy operation. It consists of a rectangle that is gradually filled with the system highlight color as an operation progresses.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of progress bar controls.

CProgressBar Members

CProgressBar
CProgressBar();
Constructor for the CProgressBar.
GetPos
int GetPos() const;
Retrieves the current position of the progress bar.
GetRange
int GetRange(BOOL fWhichLimit, PPBRANGE ppBRange) const;
Retrieves the information about the current high and low limits of the progress bar.
OffsetPos
int OffsetPos(int nIncrement) const;
Advances the current position of a progress bar bt the specified increment and redraws the bar to reflect the new position.
SetPos
int SetPos(int nNewPos) const;
Sets the current position of the progress bar and redraws the bar to reflect the new position.
SetRange
int SetRange(short nMinRange, short nMaxRange) const;
Sets the minimum and maximum values for the progress bar and redraws the bar to reflect the new range.
SetStep
int SetStep(int nStepInc) const;
Specifies the step increment for the progress bar, used by StepIt. The default value is 10.
StepIt
int StepIt() const;
Advances the current position of the progress bar by the step increment and redraws the progress bar to reflect the new position.

Overridables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the progress bar control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a progress bar control.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes


CPropertyPage

CPropertyPage Class

Description

This class is used to create and manage a property page A property sheet will have one or more property pages. These pages are much like dialogs which are presented within a tabbed dialog or within a wizard. The data on a property page can be validated before the next page is presented.

Refer to the PropertySheet demo program for an example of how property pages can be used.

CPropertyPage Members

Construction

CPropertyPage
CPropertyPage (UINT nIDTemplate, LPCTSTR szTitle = NULL);
The constructor for CPropertyPage.

Attributes and State functions

GetPSP
PROPSHEETPAGE GetPSP() const {return m_PSP;}
Retrieves the PROPSHEETPAGE struct for this property page.
IsButtonEnabled
BOOL IsButtonEnabled(int iButton) const;
Returns TRUE if the specified button is active.
SetModified
void SetModified(BOOL bChanged) const;
Flags a property page as modified or unmodified.

Overridables

DialogProc
virtual BOOL DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam);;
Override this function to handle messages received by the property page.
OnApply
virtual int OnApply();
Called when the Apply button is pressed.
OnCancel
virtual void OnCancel();
Called when the Cancel button is pressed.
OnHelp
virtual void OnHelp();
Called when the Help button is pressed.
OnInitDialog
virtual BOOL OnInitDialog();
Called when the property page is created.
OnKillActive
virtual BOOL OnKillActive();
Called when the property page becomes inactive in response to an OK or Apply button press.
OnNotify
virtual LRESULT OnNotify(WPARAM wParam, LPARAM lParam);
Called when a notification from a child control is received.
OnOK
virtual int OnOK();
Called when the OK button is pressed.
OnQueryCancel
virtual BOOL OnQueryCancel();
Called when the Cancel button is press, before the cancel has taken place.
OnQuerySiblings
virtual BOOL OnQuerySiblings(WPARAM wParam, LPARAM lParam);
Called in response to a query from the property sheet. Return zero to indicate passed, or nonzero to indicated failed.
OnSetActive
virtual int OnSetActive();
Called when the property page becomes active.
OnWizardBack
virtual int OnWizardBack();
Called when the Back button is pressed on a wizard.
OnWizardFinish
virtual BOOL OnWizardFinish();
Called when the Finish button is pressed on a wizard.
OnWizardNext
virtual int OnWizardNext();
Called when the Next button is pressed on a wizard.
PretranslateMessage
virtual BOOL PreTranslateMessage(MSG* pMsg);
Called allow the tab control to translate keyboard input before the message is passed on to the message loop.

Operations

CancelToClose
void CancelToClose() const;
Disables the Cancel button and changes the text of the OK button to "Close."
QuerySiblings
LRESULT QuerySiblings(WPARAM wParam, LPARAM lParam) const;
Used to query other property pages belonging to this property sheet.
SetTitle
void SetTitle(LPCTSTR szTitle);
Sets the property sheet's title.
SetWizardButtons
void SetWizardButtons(DWORD dwFlags) const;
Sets the wizard buttons.
Base class Members

For base class members, refer to the members of CWnd.

Summary Information

Header file | propertysheet.h
Win32/64 support | Yes
WinCE support | Yes


CPropertySheet

CPropertySheet Class

Description

This class is used to create and manage a property sheet. A property sheet will have one or more property pages. These pages are much like dialogs which are presented within a tabbed dialog or within a wizard. The data on a property page can be validated before the next page is presented. Property sheets have three modes of use: Modal, Modeless, and Wizard.

Refer to the PropertySheet demo program for an example of how property sheets can be used.

CPropertySheet Members:

Construction

CPropertySheet
CPropertySheet(UINT nIDCaption, HWND hwndParent = NULL);
CPropertySheet(LPCTSTR pszCaption = NULL, HWND hwndParent = NULL);
Constructs a CPropertySheet object.

Attributes

GetActivePage
CPropertyPage* GetActivePage() const;
Retrieves the active CPropertyPage.
GetPageCount
int GetPageCount() const;
Retrieves the number of pages in the property sheet.
GetPageIndex
int GetPageIndex(CPropertyPage* pPage) const;
Retrieves the index of the specified page
GetTabControl
HWND GetTabControl() const;
Retrieves the window handle of the property sheet's tab control.
SetActivePage
virtual BOOL SetActivePage(int nPage);
virtual BOOL SetActivePage(CPropertyPage* pPage);
Sets the active property page.
SetWizardMode
virtual void SetWizardMode(BOOL bWizard);
Set to TRUE if the property sheet is a wizard.

State functions

IsModeless
BOOL IsModeless() const;
Returns TRUE if the property sheet is modeless.
IsWizard
BOOL IsWizard() const;
Returns TRUE if the property sheet is a wizard.

Overridables

Destroy
virtual void Destroy();
Called when CPropertySheet is about to be deconstructed.
PreTranslateMessage
virtual BOOL PreTranslateMessage(MSG* pMsg);
Translates keyboard and mouse messages before they are passed to TranslateMessage.

Operations

AddPage
virtual CPropertyPage* AddPage(CPropertyPage* pPage);
Adds a property page to the property sheet.
Create
virtual HWND Create(HWND hWndParent = 0);
Creates a modeless property sheet.
CreatePropertySheet
virtual INT_PTR CreatePropertySheet(LPCPROPSHEETHEADER ppsph);
Creates a property sheet.
DestroyButton
virtual void DestroyButton(int iButton);
Removes a button.
DoModal
virtual int DoModal();
Creates a modal property sheet.
RemovePage
virtual void RemovePage(CPropertyPage* pPage);
Remove a property page.
SetTitle
virtual void SetTitle(LPCTSTR szTitle);
Sets the title of the property sheet.
Base class Members

For base class members, refer to the members of CWnd.

Summary Information

Header file | propertysheet.h
Win32/64 support | Yes
WinCE support | Yes


CReBar

CReBar Class

Description

The class responsible for creating a ReBar control. ReBar controls act as containers for child windows. An application assigns child windows, which are often other controls, to a rebar control band. ReBar controls contain one or more bands, and each band can have any combination of a gripper bar, a bitmap, a text label, and a child window.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of rebar controls.

CReBar Members

CReBar
CReBar();
Constructor for CReBar.
DeleteBand
BOOL DeleteBand(const int nBand) const;
Deletes a band from the rebar control.
GetBand
int GetBand(const HWND hWnd) const;
Returns the band number given the band's window handle.
GetBandBorders
CRect GetBandBorders(int nBand) const;
Retrieves the borders of a band. The result of this message can be used to calculate the usable area in a band.
GetBandCount
int GetBandCount() const;
Retrieves the count of bands currently in the rebar control.
GetBandInfo
BOOL GetBandInfo(const int nBand, REBARBANDINFO& rbbi) const;
Retrieves information about a specified band in a rebar control.
GetBandRect
CRect GetBandRect(int i) const;
Retrieves the bounding rectangle for a given band in a rebar control.
GetBarHeight
UINT GetBarHeight() const;
Retrieves the height of the rebar control.
GetBarInfo
BOOL GetBarInfo(REBARINFO& rbi) const;
Retrieves information about the rebar control and the image list it uses.
GetReBarTheme
ReBarTheme& GetReBarTheme() {return m_Theme;}
Returns the theme structure for the rebar. The Theme structure defines the background colors and the characteristics of the rebar bands.
GetRowCount
UINT GetRowCount() const;
Retrieves the number of rows of bands in a rebar control.
GetRowHeight
int GetRowHeight(int nRow) const;
Retrieves the height of a specified row in a rebar control.
GetSizeofRBBI
UINT GetSizeofRBBI() const;
Returns the correct value for sizeof(REBARBANDINFO).
GetToolTips
CToolTip* GetToolTips() const;
Retrieves the handle to any ToolTip control associated with the rebar control.
HitTest
int HitTest(RBHITTESTINFO& rbht);
HWND HitTest(POINT pt);
Determines which portion of a rebar band is at a given point on the screen, if a rebar band exists at that point.
IDToIndex
int IDToIndex(UINT uBandID) const;
Converts a band identifier to a band index in a rebar control.
InsertBand
BOOL InsertBand(const int nBand, REBARBANDINFO& rbbi) const;
Inserts a new band in a rebar control.
IsBandVisible
BOOL IsBandVisible(int nBand) const;
Returns TRUE if band is visible, otherwise FALSE
MaximizeBand
void MaximizeBand(UINT uBand, BOOL fIdeal = FALSE);
Resizes a band in a rebar control to either its ideal or largest size.
MinimizeBand
void MinimizeBand(UINT uBand);
Resizes a band in a rebar control to its smallest size.
MoveBand
BOOL MoveBand(UINT uFrom, UINT uTo);
Moves a band from one index to another.
MoveBandsLeft
void MoveBandsLeft();
Repositions the bands so that they are moved to the left.
ResizeBand
BOOL ResizeBand(const int nBand, const CSize& sz) const;
Changes the size of a rebar band.
SetBandBitmap
BOOL SetBandBitmap(const int nBand, const HBITMAP hBackground) const;
Sets a bitmap to the ReBar control
SetBandColor
BOOL SetBandColor(const int nBand, const COLORREF clrFore,
                  const COLORREF clrBack) const;
Sets the colour of a ReBar band
SetBandInfo
BOOL SetBandInfo(const int nBand, REBARBANDINFO& rbbi) const;
Sets characteristics of an existing band in the rebar control.
SetBarInfo
BOOL SetBarInfo(REBARINFO& rbi) const;
Sets the characteristics of a rebar control.
SetReBarTheme
void SetReBarTheme(ReBarTheme& Theme);
Sets the theme structure for the rebar. The Theme structure defines the background colors and the characteristics of the rebar bands.
ShowBand
BOOL ShowGripper(int nBand, BOOL fShow) const;
Shows or hides a band
ShowGripper
BOOL ShowBand(int nBand, BOOL fShow) const;
Shows or hides a band's gripper.
SizeToRect
BOOL SizeToRect(CRect& rect) const;
Finds the best layout of the bands from the given rectangle.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the rebar control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a rebar control.

The following code creates a ComboBox and adds it to the rebar.

void CMainFrame::AddListboxBand(int Listbox_Height)
{
  // Get the reference to the rebar object
  CReBar& RB = GetReBar();
  ThemeReBar RBTheme = RB.GetReBarTheme();

  // Create the ComboboxEx window
  CREATESTRUCT cs = {0};
  cs.lpszClass = _T("COMBOBOXEX32");
  cs.style = WS_VISIBLE | WS_CHILD | CBS_DROPDOWN;
  cs.cy = 100;	// required to display list
  cs.hMenu = (HMENU)IDC_COMBOBOXEX;
  m_ComboboxEx.PreCreate(cs);
  m_ComboboxEx.Create(GetReBar().GetHwnd());

  // Put the window in a new rebar band
  REBARBANDINFO rbbi = {0};
  rbbi.cbSize     = GetSizeofRBBI();
  rbbi.fMask      = RBBIM_COLORS | RBBIM_CHILDSIZE | RBBIM_STYLE | RBBIM_CHILD | RBBIM_TEXT;
  rbbi.cyMinChild = Listbox_Height;
  rbbi.cyMaxChild = Listbox_Height;
  rbbi.cxMinChild = 200;
  rbbi.fStyle     = RBBS_BREAK | RBBS_VARIABLEHEIGHT | RBBS_GRIPPERALWAYS;
  rbbi.clrFore    = GetSysColor(COLOR_BTNTEXT);
  rbbi.clrBack    = RBTheme.clrBand1;
  rbbi.hwndChild  = m_ComboboxEx.GetHwnd();
  rbbi.lpText     = _T("Address");

  RB.InsertBand(-1, rbbi);
}

CRebar is used by CFrame to contain a CMenuBar and a CToolBar.

Summary Information

Header file | rebar.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CRect

CRect Class

Description

A CRect can be used anywhere that a RECT structure could be used.

CRect Members

CRect
CRect();
CRect(int Left, int Top, int Right, int Bottom);
CRect(RECT rc);
CRect(POINT pt, SIZE sz);
CRect(POINT topLeft, POINT bottomRight);
Constructs the CRect.
operator =
void operator=(const RECT& srcRect);
Assigns a RECT to this CRect.
operator ()
operator LPRECT();
Returns a pointer to the RECT associated with this CRect.
operator ==
BOOL operator == (const RECT& rc) const;
Returns TRUE if the co-ordinates of the source rectangle and the CRect are equal.
operator !=
BOOL operator != (const RECT& rc) const;
Returns TRUE if the of the source rectangle and the CRect are not equal.
operator +=
void operator += (POINT pt);
void operator += (SIZE size);
void operator += (RECT rc);
Adds the specified values to the CRect.
operator -=
void operator -= (POINT pt);
void operator -= (SIZE sz);
void operator -= (RECT rc);
Subtracts the specified values from the CRect.
operator &=
void operator &= (RECT rc);
Determines the intersection with the specified RECT.
operator |=
void operator |= (RECT rc);
Determins the union with the specified RECT.
operator +
CRect operator + (POINT pt) const;
CRect operator + (SIZE sz) const;
CRect operator + (RECT rc) const;
Offsets the CRect and returns the result.
operator -
CRect operator - (POINT pt) const;
CRect operator - (SIZE sz) const;
CRect operator - (RECT rc) const;
Offsets the CRect and returns the result.
operator &
CRect operator & (RECT rc) const;
Returns the intersection with the specified RECT.
operator |
CRect operator | (RECT rc) const;
Returns the union with the specified RECT.
CopyRect
void CopyRect(const RECT& rc);
Copies the coordinates of the source rectangle to the CRect.
DeflateRect
BOOL DeflateRect(int x, int y);
BOOL DeflateRect(SIZE size);
BOOL DeflateRect(RECT rc);
BOOL DeflateRect(int l, int t, int r, int b);
Decreases the width and height of the CRect.
EqualRect
BOOL EqualRect(const RECT& rc);
Determines whether the source rectangle and the CRect are equal by comparing the coordinates of their upper-left and lower-right corners.
InflateRect
BOOL InflateRect(int dx, int dy);
BOOL InflateRect(SIZE sz);
BOOL InflateRect(RECT rc);
BOOL InflateRect(int l, int t, int r, int b);
Increases the width and height of the CRect.
IntersectRect
BOOL IntersectRect(const RECT& rc1, const RECT& rc2);
Calculates the intersection of two source rectangles and places the coordinates of the intersection rectange into the CRect.
IsRectEmpty
BOOL IsRectEmpty() const;
Determines whether the CRect is empty.
IsRectNull
BOOL IsRectNull() const;
Determines whether the CRect is NULL.
MoveToX
void MoveToX (int x);
Moves the rect to the specified left position.
MoveToY
void MoveToY (int y);
Moves the rect to the specified top position.
MoveToXY
void MoveToXY (int x, int y);
void MoveToXY (POINT pt);
Moves to rect to the specified left and top positions.
MulDiv
CRect MulDiv(int nMult, int nDiv) const;
Multiplies the CRect values by nMult, and then divides the result by nDiv.
NormalizeRect
void NormalizeRect()
Normalizes CRect so that both the height and width are positive.
OffsetRect
BOOL OffsetRect(int dx, int dy);
BOOL OffsetRect(POINT pt);
BOOL OffsetRect(SIZE size);
Moves the CRect by the specified offsets.
PtInRect
BOOL PtInRect(POINT pt) const;
Determines whether the specified point lies within the CRect.
SetRect
BOOL SetRect(int left, int top, int right, int bottom);
BOOL SetRect(POINT TopLeft, POINT BtmRight);
Sets the coordinates of the CRect.
SetRectEmpty
BOOL SetRectEmpty();
Sets all the coordinates of the CRect to zero.
SubtractRect
BOOL SubtractRect(const RECT& rc1, const RECT& rc2);
Sets the coordinates of the CRect to those formed by subtracting one rectangle from another.
UnionRect
BOOL UnionRect(const RECT& rc1, const RECT& rc2);
Creates the union of two rectangles.
Height
int Height() const;
Returns the height of the CRect.
Width
int Width() const;
Returns the width of the CRect.
Size
CSize Size() const;
Determines the size (width and height) of the CRect.
CenterPoint
CPoint CenterPoint() const;
Returns the point at the center of the CRect.
TopLeft
CPoint TopLeft() const;
Returns the top left point of the CRect.
BottomRight
CPoint BottomRight() const;
Returns the bottom left point of the CRect.

Remarks

By default, the constructor sets all the rectangle coordinates zero, but the CRect can also be constructed from four integers, a rectangle, a point and size, or two points.

The CRect class inherits from the RECT structure. As a result, the data members of the underlying RECT struct are also accessible as data members (left, top, right and bottom).

Summary Information

Header file | winutils.h
Win32/64 support | Yes
WinCE support | Yes


CResizer

CResizer Class

Description

The CResizer class can be used to automatically rearrange the position of child windows when the parent window is resized. Typically this is used to reposition the controls for a dialog.

CResizer Members

CResizer
CResizer();
Constructor for the CResizer.
AddChild
virtual void AddChild(CWnd* pWnd, Alignment corner, DWORD dwStyle);
virtual void AddChild(HWND hWnd, Alignment corner, DWORD dwStyle);
Adds a child window to be managed by the CResizer.
GetMinRect
CRect GetMinRect() const;
Returns the minimum allowed rectangle.
GetMaxRect
CRect GetMaxRect() const;
Returns the maximum allowed rectangle.
HandleMessage
virtual void HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam);
Call this function from within the window's DialogProc.
Initialize
virtual void Initialize(CWnd* pParent, RECT rcMin, RECT rcMax = CRect(0,0,0,0));
Specifies the parent window, as well as its minimum and maximum size.
RecalcLayout
virtual void RecalcLayout();
Repositions the child windows.

Remarks

To use the CResizer class to manage the position of child windows, perform the following steps.

  • Use Initialize to specify the parent window, along with the minimum and maximum permitted sizes.
  • Use AddChild for each child window we wish to manage.
  • Call HandleMessage from within DialogProc or WndProc to pass messages on to CResizer

The following code demonstrates how to initialize CResizer for a dialog.

BOOL CMyDialog::OnInitDialog()
{
    // Perform other tasks ...

    // Initialize dialog resizing
    m_Resizer.Initialize( this, CRect(0, 0, 300, 200) );
    m_Resizer.AddChild(m_RadioA,   topleft, 0);
    m_Resizer.AddChild(m_RadioB,   topleft, 0);
    m_Resizer.AddChild(m_RadioC,   topleft, 0);
    m_Resizer.AddChild(m_Button,   topleft, 0);
    m_Resizer.AddChild(m_CheckA,   bottomright, 0);
    m_Resizer.AddChild(m_CheckB,   bottomright, 0);
    m_Resizer.AddChild(m_CheckC,   bottomright, 0);
    m_Resizer.AddChild(m_RichEdit1, topright, RD_STRETCH_WIDTH);
    m_Resizer.AddChild(m_RichEdit2, bottomleft, RD_STRETCH_WIDTH| RD_STRETCH_HEIGHT);

    return true;
}

The following code shows how to add the CResizer message handling.

INT_PTR CMyDialog::DialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    // Pass resizing messages on to the resizer
    m_Resizer.HandleMessage(uMsg, wParam, lParam);

//  switch (uMsg)
//  {
//      Additional messages to be handled go here
//  }

    // Pass unhandled messages on to parent DialogProc
    return DialogProcDefault(uMsg, wParam, lParam);
}

Summary Information

Header file | dialog.h
Win32/64 support | Yes
WinCE support | Yes


CRgn

CRgn Class

Description

The class responsible for creating and managing regions.

CRgn Members

Initialization and Assignment
CRgn
CRgn();
CRgn(HRGN hRgn);
Constructs a CRgn object.
operator HRGN()
operator HRGN() const;
Allows a CRgn object to be used as a region handle (HRGN).
Attributes
GetRegionData
int GetRegionData(LPRGNDATA lpRgnData, int nDataSize) const;
Fills the specified buffer with data describing a region.
GetRgnBox
int GetRgnBox(RECT& rc) const;
Retrieves the bounding rectangle of the region, and stores it in the specified RECT. The return value indicates the region's complexity: NULLREGION;SIMPLEREGION; or COMPLEXREGION.
Operations
CombineRgn
int CombineRgn(HRGN hRgnSrc1, HRGN hRgnSrc2, int nCombineMode);
int CombineRgn(HRGN hRgnSrc, int nCombineMode);
Combines two sepcified regions and stores the result.
CopyRgn
int CopyRgn(HRGN hRgnSrc);
Assigns the specified region to the current region.
CreateEllipticRgn
HRGN CreateEllipticRgn(int x1, int y1, int x2, int y2);
Creates an elliptical region.
CreateEllipticRgnIndirect
HRGN CreateEllipticRgnIndirect(const RECT& rc);
Creates an elliptical region.
CreateFromData
HRGN CreateFromData(const XFORM* lpXForm, int nCount,
                    const RGNDATA* pRgnData);
Creates a region from the specified region and transformation data.
CreateFromPath
HRGN CreateFromPath(HDC hDC);
Creates a region from the path that is selected into the specified device context. The resulting region uses device coordinates.
CreatePolygonRgn
HRGN CreatePolygonRgn(LPPOINT lpPoints, int nCount, int nMode);
Creates a polygonal region.
CreatePolyPolygonRgn
HRGN CreatePolyPolygonRgn(LPPOINT lpPoints, LPINT lpPolyCounts,
                          int nCount, int nPolyFillMode);
Creates a polygonal region.
EqualRgn
BOOL EqualRgn(HRGN hRgn) const;
Creates a region consisting of a series of polygons. The polygons can overlap.
OffsetRgn
int OffsetRgn(int x, int y);
int OffsetRgn(POINT& pt);
Moves a region by the specified offsets.
PtInRegion
BOOL PtInRegion(int x, int y) const;
BOOL PtInRegion(POINT& pt) const;
Determines whether the specified point is inside the specified region.
RectInRegion
BOOL RectInRegion(const RECT& rc) const;
Determines whether the specified rect is inside the specified region.
SetRectRgn
void SetRectRgn(int x1, int y1, int x2, int y2);
void SetRectRgn(const RECT& rc);
Converts the region into a rectangular region with the specified coordinates.
Base class Members

For base class members, refer to the members of CGDIObject.

Remarks

CRgn objects can be used anywhere a a handle to a brush (HRGN) might be used. They can be substituted for the HRGN in any of the Windows API functions which use a HRGN as a function argument. The benefit of using a CRgn object is that it automatically deletes the brush when it is destroyed.

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CRibbon

CRibbon Class

Description

CRibbon allows a ribbon to be added to a windows. Only Windows 7 (and above) supports the ribbon framework.

CRibbon Members

CRibbon
CRibbon();
Constructs a CRibbon object.
CreateRibbon
bool virtual CreateRibbon(CWnd* pWnd);
Creates the ribbon
DestroyRibbon
void virtual DestroyRibbon();
Destroys the ribbon
GetRibbonFramework
IUIFramework* GetRibbonFramework();
Returns the pointer to IUIFramwork, assigned when the ribbon is created.

IUnknown Methods

AddRef
STDMETHOD_(ULONG, AddRef());
Increments the reference count for the interface on the object.
Release
STDMETHOD_(ULONG, Release());
Decrements the reference count for the interface on the object.
QueryInterface
STDMETHOD(QueryInterface(REFIID iid, void** ppv));
Retrieves pointers to the supported interfaces on the object.

IUIApplication Methods

OnCreateUICommand
STDMETHOD(OnCreateUICommand)(UINT nCmdID, __in UI_COMMANDTYPE typeID,
            __deref_out IUICommandHandler** ppCommandHandler);
Called by the Ribbon framework for each command specified in the Ribbon markup to bind the Command to an IUICommandHandler.
OnDestroyUICommand
STDMETHOD(OnDestroyUICommand)(UINT32 commandId, __in UI_COMMANDTYPE typeID,
           __in_opt IUICommandHandler* commandHandler);
Called for each Command specified in the Ribbon markup when the Ribbon host application window is destroyed.
OnViewChanged
STDMETHOD(OnViewChanged)(UINT viewId, __in UI_VIEWTYPE typeId,
            __in IUnknown* pView, UI_VIEWVERB verb, INT uReasonCode);
Called when the state of the Ribbon changes, for example, created, destroyed, or resized.

IUICommandHandle methods

Execute
STDMETHODIMP Execute(UINT nCmdID, UI_EXECUTIONVERB verb, __in_opt const PROPERTYKEY* key,
                     __in_opt const PROPVARIANT* ppropvarValue,
                     __in_opt IUISimplePropertySet* pCommandExecutionProperties);
Executes or previews the Commands bound to the Command handler.
UpdateProperty
STDMETHODIMP UpdateProperty(UINT nCmdID, __in REFPROPERTYKEY key,
                            __in_opt const PROPVARIANT* ppropvarCurrentValue,
                            __out PROPVARIANT* ppropvarNewValue);
Called by the Ribbon framework when a command property (PKEY) needs to be updated.

Remarks

Microsoft's RibbonUI framework uses COM to implement the ribbon. The COM interfaces involved are IUIApplication and IUICommandHandler. The CRibbon class inherits from both IUIApplication and IUICommandHandler.

To create and interact with the ribbon, we override the relevant functions from both IUIApplication and IUICommandHandler.

The functions you may wish to override are:

  • IUIApplication::OnCreateUICommand - Called for each Command specified in the Ribbon markup to bind the Command to an IUICommandHandler.
  • IUIApplication::OnDestroyUICommand - Called for each Command specified in the Ribbon markup when the Ribbon host application window is destroyed.
  • IUIApplication::OnViewChanged - Called when the state of a View changes.
  • IUICommandHandler::Execute - Executes or previews the Commands bound to the Command handler.
  • IUICommandHandler::UpdateProperty - Sets a property value for a bound Command, for example, setting a Command to enabled or disabled depending on the state of a View.

Refer to the RibbonSimple sample for a demonstration of how to add a ribbon to a simple window.

Summary Information

Header file | ribbon.h
Win32/64 support | Yes
WinCE support | No
Library required | Comctl32.lib, Shlwapi.lib


CRibbonFrame

CRibbonFrame Class

Description

CRibbonFrame provides a Frame window with a Ribbon in place of the traditional MenuBar and ToolBar. Only Windows 7 (and above) supports the ribbon framework. By default, a ToolBar and MenuBar is displayed instead of the ribbon if the ribbon framework is not supported by the Operating System.

CRibbonFrame Members

CRibbonFrame
CRibbonFrame();
Constructs a CRibbonFrame object.
GetRibbonHeight
UINT GetRibbonHeight() const;
Returns the height of the ribbon in pixels
GetViewRect
virtual CRect GetViewRect() const;
Returns a CRect containing the dimensions of the view window.
OnCreate
virtual void OnCreate();
Called when the frame window is created.
OnDestroy
virtual void OnDestroy();
Called when the frame window is destroyed.
OnViewChanged
virtual STDMETHODIMP OnViewChanged(UINT32 viewId, UI_VIEWTYPE typeId,
                      IUnknown* pView, UI_VIEWVERB verb, INT32 uReasonCode);
Called when the state of the view changes.
PopulateRibbonRecentItems
virtual HRESULT PopulateRibbonRecentItems(__deref_out PROPVARIANT* pvarValue);
Populates the list of Most Recently Used files.
UpdateMRUMenu
virtual void UpdateMRUMenu();
Updates the frame with the MRU list.
Base class Members

For base class members, refer to the members of CFrame and CRibbon.

Remarks

Microsoft's RibbonUI framework uses COM to implement the ribbon. The COM interfaces involved are IUIApplication and IUICommandHandler. The Win32++ CRibbon class inherits from both IUIApplication and IUICommandHandler. CRibbonFrame inherits from both CFrame and and CRibbon.

To add a ribbon to your frame, inherit CMainFrame from CRibbonFrame, and add the Ribbon.xml file containing the definitions for your ribbon to the project. The Ribbon.xml is compiled to produce the RibbonUI.h and Ribbon.rc before the files C++ files are compiled. To compile Ribbon.xml, specify it's custom build properties in the IDE as follows:

  • Command Line:- uicc.exe ..\src\Ribbon.xml ..\src\Ribbon.bml /header:..\src\RibbonUI.h /res:..\src\RibbonUI.rc
  • Outputs:- Ribbon.bml;RibbonUI.rc;RibbonUI.h

To create and interact with the ribbon, we override the relevant functions from both IUIApplication and IUICommandHandler. The functions you may wish to override are:

  • IUIApplication::OnCreateUICommand - Called for each Command specified in the Ribbon markup to bind the Command to an IUICommandHandler.
  • IUIApplication::OnDestroyUICommand - Called for each Command specified in the Ribbon markup when the Ribbon host application window is destroyed.
  • IUIApplication::OnViewChanged - Called when the state of a View changes.
  • IUICommandHandler::Execute - Executes or previews the Commands bound to the Command handler.
  • IUICommandHandler::UpdateProperty - Sets a property value for a bound Command, for example, setting a Command to enabled or disabled depending on the state of a View.

Refer to the RibbonFrame sample for a demonstration of how to create an application with a ribbon frame.

Summary Information

Header file | ribbon.h
Win32/64 support | Yes
WinCE support | No
Library required | Comctl32.lib, Shlwapi.lib


CScrollBar

CScrollBar Class

Description

The CScrollBar class is used to create and manage a scroll bar control. Scroll bars are used when the window isn't large enough to display all of its content, such as a bitmap or a document. Scroll bars can be used to bring into view the portions of the content that extend beyond the borders of the window.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of scroll bar controls.

CScrollBar Members

CScrollBar
CScrollBar();
Constructor for the CScrollBar.
EnableScrollbar
BOOL EnableScrollBar( UINT nArrowFlags = ESB_ENABLE_BOTH ) const;
Enables or disables one or both scroll bar arrows.
GetScrollInfo
BOOL GetScrollInfo(LPSCROLLINFO lpsi) const;
Retrieves information that the SCROLLINFO structure maintains about the scroll bar.
GetScrollPos
int GetScrollPos() const;
Retrieves the current position of the scroll box.
GetScrollRange
BOOL GetScrollRange(LPINT lpMinPos, LPINT lpMaxPos ) const;
Retrieves the current minimum and maximum scroll box positions.
SetScrollInfo
BOOL SetScrollInfo(LPSCROLLINFO lpsi, BOOL bRedraw = TRUE ) const;
Sets the information that the SCROLLINFO structure maintains about the scroll bar.
SetScrollPos
int SetScrollPos(int nPos, BOOL bRedraw) const;
Sets the position of the scroll box and, if requested, refraws the scroll bar to reflect the new position of the scroll box.
SetScrollRange
BOOL SetScrollRange( int nMinPos, int nMaxPos, BOOL bRedraw = TRUE ) const;
Sets the minimum and maximum scroll box positions for the scroll bar.
ShowScrollBar
BOOL ShowScrollBar(BOOL bShow) const;
Shows or hides the scroll bar.

Overridables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the scroll bar control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a scroll bar control.

There are two ways to add scroll bars to a window.

  • Create the window with the WS_HSCROLL and/or WS_VSCROLL styles.
  • Create a horizontal and/or vertical scroll bar control as a child window we wish to scroll.

Use the SBS_HORZ style to create a horizontal scroll bar control, and the SBS_VERT style to create a vertical scroll bar control.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes


CSize

CSize Class

Description

A CSize can be used anywhere that a SIZE structure could be used.

CSize Members

CSize
CSize();
CSize(int CX, int CY);
CSize(SIZE sz);
CSize(POINT pt);
CSize(DWORD dw)
Various methods of constructing the CSize object.
operator LPSIZE()
operator LPSIZE();
Returns the pointer to the SIZE object associated with this CSize.
operator ==
BOOL operator == (SIZE sz) const;
Returns TRUE if the co-ordinates of the source size and the CSize are equal.
operator !=
BOOL operator != (SIZE sz) const;
Returns TRUE if the of the source size and the CSize are not equal.
operator +=
void operator += (SIZE sz);
Adds the specified SIZE.
operator -=
void operator -= (SIZE sz);
Subtracts the specified SIZE.
operator -
CSize operator - () const;
Returns the unary minus (additive inverse).
operator +=
CSize operator + (SIZE sz) const;
CPoint operator + (POINT point) const;
CRect operator + (RECT rc) const;
Adds the point and returns the value.
operator -=
CSize operator - (SIZE sz) const;
CPoint operator - (POINT point) const;
CRect operator - (RECT rc) const;
Subtracts the point and returns the value.
SetSize
void SetSize(int CX, int CY);
Sets the coordinates of the CSize.

Remarks

By default, the constructor sets all the size coordinates zero, but the CSize can also be constructed from two integers, a size, a point, or a dword.

The CSize class inherits from the SIZE structure. As a result, the data members of the underlying SIZE struct are also accessible as data members.

Summary Information

Header file | winutils.h
Win32/64 support | Yes
WinCE support | Yes


CSlider

CSlider Class

Description

The CSlider class is used to create and manage a slider control.

CSlider Members

CSlider
CSlider();
Constructor for the CSlider.
ClearSel
void ClearSel() const;
Clears the current selection range
ClearTics
void ClearTics(BOOL bRedraw = FALSE ) const;
Removes the current tick marks
GetBuddy
HWND GetBuddy(BOOL fLocation = TRUE ) const;
Retrieves the handle to the trackbar control buddy window at the given location.
GetChannelRect
CRect GetChannelRect() const;
Retrieves the size and position of the bounding rectangle fro the trackbar's channel.
GetLineSize
int GetLineSize() const;
Retrieves the number of logical positions the trackbar's slide moves in response to keyboard input from the arrow keys.
GetNumTics
int GetNumTics() const;
Retrieves the number of tick marks in the trackbar.
GetPageSize
int GetPageSize() const;
Retrieve the number of logical positions the trackbar's slider move in response to keyboard input, or mouse input such as clicks in the trackbar's channel.
GetPos
int GetPos() const;
Retrieves the current logical position of the slider in the trackbar.
GetRangeMax
int GetRangeMax() const;
Retrieves the maximum position for the slider in the trackbar.
GetRangeMin
int GetRangeMin() const;
Retrieves the minimum position for the slider in the trackbar.
GetSelEnd
int GetSelEnd() const;
Retrieves the ending position of the current selection range in the trackbar.
GetSetStart
int GetSelStart() const;
Retrieves the starting position of the current selection range in the trackbar.
GetThumbLength
int GetThumbLength() const;
Retrieves the length of the slider in the trackbar.
GetThumbRect
CRect GetThumbRect() const;
Retrieve the size and position of the bounding rectangle for the slider in the trackbar.
GetTic
int GetTic(int nTic ) const;
Retrieves the logical position of a tick mark in the trackbar.
GetTicPos
int GetTicPos(int nTic) const;
Retrieves the current physical position of a tick mark in the trackbar.
GetToolTips
HWND GetToolTips() const;
Retrieves the handle to the ToolTip control assigned to the trackbar, if any.
SetBuddy
HWND SetBuddy(HWND hwndBuddy, BOOL fLocation = TRUE ) const;
Assigns a window as the buddy window for the trackbar control.
SetLineSize
int SetLineSize(int nSize) const;
Sets the number of logical positions the trackbar's slider moves in response to keyboard input from arrow keys.
SetPageSize
int SetPageSize(int nSize) const;
Sets the number of logical positions the trackbar's slider moves in response to keyboard input, or mouse input such as clicks in the trackbar's channel.
SetPos
void SetPos(int nPos, BOOL bRedraw = FALSE) const;
Sets the current logical position of the slider in the trackbar.
SetRangeMax
void SetRangeMax(int nMax, BOOL bRedraw = FALSE) const;
Set the maximum logical position for the slider in the trackbar.
SetRangeMin
void SetRangeMin(int nMax, BOOL bRedraw = FALSE) const;
Sets the minimum logical position for the slider in the trackbar.
SetSelection
void SetSelection(int nMin, int nMax, BOOL bRedraw = FALSE) const;
Sets the starting and ending positions for the available selection range in the trackbar.
SetTic
BOOL SetTic(int nTic) const;
Sets a tick mark in the trackbar at the specified logical position.
SetTicFreq
void SetTicFreq(int nFreq) const;
Sets the interval frequency for tick marks in the trackbar.
SetTipSide
int SetTipSide(int nLocation) const;
Positions the ToolTip control used by the trackbar control.
SetToolTips
void SetToolTips(HWND hwndTip) const;
Assigns a ToolTip control to the trackbar control.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the slider control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a slider control.

A slider control is often referred to as a trackbar control.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes


CSocket

CSocket Class

Description

The CSocket class represents a network socket. It encapsualtes many of the Windows Socket SPI fuctions, providing an object-oriented approach to network programming. After StartEvents is called, CSocket monitors the socket and responds automatically to network events. This event monitoring, for example, automatically calls OnReceive when there is data on the socket to be read, and OnAccept when a server should accept a connection from a client.

Users of this class should be aware that functions like OnReceive, OnAccept, etc. are called on a different thread from the one CSocket is instanciated on. The thread for these functions needs to respond quickly to other network events, so it shouldn't be delayed. It also doesn't run a message loop, so it can't be used to create windows. For these reasons it might be best to use PostMessage in response to these functions in a windows environment.

Refer to the network samples for an example of how to use this class to create a TCP client & server, and a UDP client and server.

To compile programs with CSocket, link with ws2_32.lib for Win32/64, and ws2.lib for Windows CE. Windows 95 systems will need to install the "Windows Sockets 2.0 for Windows 95". It's available from: http://support.microsoft.com/kb/182108/EN-US/

CSocket Members:

Construction

CSocket
CSocket();
Constructs a CSocket object. A CWinException will be thrown if CSocket can't be constructed properly.

Operations

Accept
virtual void Accept(CSocket& rClientSock, struct sockaddr* addr, int* addrlen);
Constructs a CSocket object.
Bind
virtual int Bind(LPCTSTR addr, LPCTSTR port);
virtual int Bind(const struct sockaddr* name, int namelen);
Associates a local address with the socket.
Connect
virtual int Connect(LPCTSTR addr, LPCTSTR port);
virtual int Connect(const struct sockaddr* name, int namelen);
Establishes a connection to a peer socket.
Create
virtual bool Create( int family, int type, int protocol = IPPROTO_IP);
Creates a socket.
Disconnect
virtual void Disconnect();
Ends any event notification for the socket, shuts the socket down, and removes it from CSocket.
FreeAddrInfo
virtual void FreeAddrInfo( struct addrinfo* ai );
Frees address information that the getaddrinfo function dynamically allocates in its addrinfo structures.
GetAddrInfo
virtual int GetAddrInfo( LPCTSTR nodename, LPCTSTR servname, const struct addrinfo* hints, struct addrinfo** res);
Provides a protocol-independent translation from host name to address.
ioCtlSocket
virtual int ioCtlSocket(long cmd, u_long* argp);
Controls the I/O mode of the socket.
Listen
virtual int Listen(int backlog = SOMAXCONN);
Establishes a socket to listen for incoming connection requests.
Receive
virtual int Receive(TCHAR* buf, int len, int flags);
Receives data from the socket.
ReceiveFrom
ReceiveFrom(TCHAR* buf, int len, int flags, struct sockaddr* from, int* fromlen);
Receives a datagram and stores the source address.
Send
virtual int Send(LPCTSTR buf, int len, int flags);
Sends data to a connected socket.
SendTo
virtual int SendTo(LPCTSTR send, int len, int flags, LPCTSTR addr, LPCTSTR port);
virtual int SendTo(LPCTSTR buf, int len, int flags, const struct sockaddr* to, int tolen);
Sends data to a specific destination.
StartEvents
virtual void StartEvents();
Starts the thread which produces the notification of network events.
StopEvents
virtual void StopEvents();
Stops the thread which produces the notification of network events.

Attributes

GetLastError
virtual LPCTSTR GetLastError();
Retrieves the calling thread's last-error code value.
GetPeerName
virtual int GetPeerName(struct sockaddr* name, int* namelen);
Gets the address of the peer socket connected to socket.
GetSocket
SOCKET& GetSocket();
Gets the SOCKET associated with this CSocket.
GetSockName
virtual int GetSockName(struct sockaddr* name, int* namelen);
Gets the local name of a socket.
GetSockOpt
virtual int GetSockOpt(int level, int optname, char* optval, int* optlen);
Gets a socket option.
IsIPV6Supported
virtual bool IsIPV6Supported();
Returns TRUE if the operating system supports IP version 6.
SetSockOpt
virtual int SetSockOpt(int level, int optname, const char* optval, int optlen);
Sets a socket option.

Overridables

OnAccept
virtual void OnAccept();
Notifies a listening socket that it can accept pending connection requests by calling Accept.
OnAddressListChange
virtual void OnAddresListChange();
Notifies a socket that there has been a local address list change.
OnConnect
virtual void OnDisconnect();
Notifies a connecting socket that the connection attempt is complete.
OnDisconnect
virtual void OnConnect();
Notifies a socket that the socket connected to it has closed.
OnOutOfBand
virtual void OnOutOfBand();
Notifies a receiving socket that there is out-of-band data to be read on the socket, usually an urgent message.
OnQualityOfService
virtual void OnQualityOfService();
Notifies a socket that there has been a QOS change.
OnReceive
virtual void OnReceive();
Notifies a listening socket that there is data to be retrieved by calling Receive.
OnRoutingChange
virtual void OnRoutingChange();
Notifies a socket that there has been routing interface change.
OnSend
virtual void OnSend();
Notifies a socket that it can send data by calling Send.

Remarks

CSocket's constructor will throw a CWinException if WSAStartup fails or if the WS2_32.dll DLL fails to load. You can catch this exception if you wish to handle this rather unlikely situation gracefully. Note that windows 95 may not have WS2_32.dll.

IP version 6 support

IP version 6 is not supported on all operating systems or all development environments. Keep the following in mind when offering support for IP version 6 in your applications.

  • IPv6 is supported on Windows Vista and above. Windows XP with SP2 provides "experimental" support, which can be enabled by entering "ipv6 install" at a command prompt.
  • IPv6 is not supported by all compilers and development environments. In particular, it is not supported by Dev-C++ or Borland 5.5. A modern Platform SDK needs to be added to Visual Studio 6 for it to support IPv6.
  • The IsIPV6Supported function returns false if either the operating system or the development environment fails to support IPv6.
Network client code

The following code segments are complete programs which demonstrate how to write a simple network client and server.

#include
#include
#include "winsock2.h"
#include "../../Win32++/socket.h"

using namespace std;
using namespace Win32xx;

class CClientSocket : public CSocket
{
public:
  CClientSocket() {}
  virtual void OnReceive()
  {
    // This function is called automatically when there is data to receive
    char str[1024] = {0};
    int i = Receive(str, 1024, 0);

    cout << i << " chars received: " << str << endl;
  }
};

int main()
{
  CClientSocket Client;

  // Create the socket to communicate with the Server
  if (!Client.Create(SOCK_STREAM))
  {
    cout << "Failed to create socket\n" ;
    return 0;
  }

  // Connect to the server
  if (SOCKET_ERROR == Client.Connect(_T("127.0.0.1", 3000)))
  {
    cout << "Failed to connect to server. Was it running?\n";
    return 0;
  }
  cout << "Connected to server.\n";
  cout << "Type data to send, type quit to exit\n";

  // Monitor the client socket for network events, such as data ready to receive
  Client.StartEvents();

  // Send data to the server
  string s;
  for (;;)	// Infinite loop
  {
    getline(cin, s);
    if (s == "quit") break;
    int i = Client.Send(s.c_str(), (int)s.length(), 0);
    cout << "Sending  " << i << " characters\n";
  }

  return 0;
}
Network server code
#include
#include
#include "winsock2.h"
#include "../../Win32++/socket.h"

using namespace std;
using namespace Win32xx;

class CServerSocket : public CSocket
{
public:
  CServerSocket() {}
  virtual ~CServerSocket() {}
  virtual void OnReceive()
  {
    // This function is called automatically when there is data to receive
    TCHAR str[1024] = {0};
    int i = Receive(str, 1024, 0);
    cout << i <<" chars received: " << str << endl;
  }
};

int main()
{
  // Create the main server socket.
  // It is used to listen for clients
  CServerSocket Server;
  if (!Server.Create(SOCK_STREAM))
  {
    cout << "Failed to create socket\n" ;
    return 0;
  }

  // Bind the IP address and port# to the main socket
  if (SOCKET_ERROR == Server.Bind(_T("127.0.0.1", 3000)))
  {
    cout << "Failed to bind IP address to socket\n" ;
    return 0;
  }

  // Listen on the socket for clients to connect
  if (SOCKET_ERROR == Server.Listen())
  {
    cout << "Listen on socket failed\n";
    return 0;
  }

  // Create the socket to communicate with the Client
  CServerSocket Client;
  cout << "Waiting for the client to connect\n";
  do
  {
    Server.Accept(Client, NULL, NULL);
  }
  while (SOCKET_ERROR == Client.GetSocket());

  cout << "Client connected\n";

  // Monitor the client socket for network events, such as data ready to receive
  Client.StartEvents();

  // Send data to the client
  cout << "Type data to send, type quit to exit\n";
  string s;
  for (;;)   // infinite loop
  {
    getline(cin, s);
    if (s == "quit") break;
    int i = Client.Send(s.c_str(), (int)s.length(), 0);
    cout << "Sending  " << i << " characters\n";
  }

  return 0;
}

Refer to the Networking ClientDlg and ServerDlg sample for a more comprehensive demonstration of the features of CSocket.

Summary Information

Header file | socket.h
Win32/64 support | Yes
WinCE support | Yes
Library required | ws2_32.lib, or ws2.lib for WinCE


CSpinButton

CSpinButton Class

Description

The CSpinButton class is used to create and manage a spin button control.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of spin button controls.

CSpinButton Members

CSpinButton
CSpinButton();
Constructor for the CSpinButton.
GetAccel
int GetAccel(int cAccels, LPUDACCEL paAccels) const;
Retrieves acceleration information for the up-down control.
GetBase
int GetBase() const;
Retrieves the current radix base (either base 10 or 16) for the up-down control.
GetBuddy
HWND GetBuddy() const;
Retrieves the handle to the current buddy window.
GetPos
int GetPos() const;
Retrieves the current position of the upd-down control with 16-bit precision.
GetRange
DWORD GetRange() const;
Retrieves the minimum and maximum positions (range) for the up-down control.
SetAccel
BOOL SetAccel(int cAccels, LPUDACCEL paAccels) const;
Sets the acceleration for the up-down control.
SetBase
int SetBase(int nBase) const;
Sets the radix base (either 10 or 16) for the up-down control.
SetBuddy
HWND SetBuddy(HWND hwndBuddy) const;
Sets the buddy window for the up-down control.
SetPos
int SetPos(int nBase) const;
Sets the current position for the up-down control with 16-bit precision.
SetRange
void SetRange(int nLower, int nUpper) const;
Sets the minimum and maximum positions (range) for the up-down control.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the spin button control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a spin button control.

A spin button control is often referred to as an up-down control.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes


CStatusBar

CStatusBar Class

Description

The class responsible for creating and managing a status bar. Status bars display status information in a horizontal window at the bottom of an application window. Status bars are often divided into parts, and each part displays different status information.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of status bar controls.

CStatusBar Members:

CStatusBar
CStatusBar();
Constructor for CStatusBar.
CreateParts
BOOL CreateParts(int iParts, const int iPaneWidths[]) const;
Creates one or more status bar parts.
GetPartIcon
HICON GetPartIcon(int iPart);
Retrieves the icon for a part in the status bar.
GetPartRect
CRect GetPartRect(int iPart);
Retrieves the bounding rectangle of a part in the status bar.
GetParts
int GetParts();
Retrieves a count of the parts in the status bar.
GetPartText
CString GetPartText(int iPart) const;
Retrieves the text from a part in the status bar.
SetPartIcon
BOOL SetPartIcon(int iPart, HICON hIcon);
Sets the icon for a part in the status bar.
SetPartText
BOOL SetPartText(int iPart, LPCTSTR szText, UINT Style = 0) const;
Sets the text for a part in the status bar.
SetPartWidth
BOOL SetPartWidth(int iPart, int iWidth) const;
Sets the width of an existing status bar pane, or creates a new pane with the specified width.
SetSimple
void SetSimple(BOOL fSimple = TRUE);
Specifies whether a status window displays simple text or displays all window parts set by a previous SB_SETPARTS message.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the status control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a status control.

The following code segment demonstrates how to create four panes in a status bar, and add some text.

void CMainFrame::SetStatusText()
{
  if (::IsWindow(GetStatusBar()))
  {
    // Get the coordinates of the frame window's client area.
    CRect rcClient = GetClientRect();

    // width = max(300, rcClient.right)
    int width = (300 > rcClient.right) ? 300 : rcClient.right;
    int iPaneWidths[] = {width - 110, width - 80, width - 50, width - 20};

    if (m_bShowIndicatorStatus)
    {
      // Create 4 panes
      GetStatusBar().CreateParts(4, iPaneWidths);

      // Or you could create the 4 panes this way
      //  GetStatusBar().SetPartWidth(0, width - 110);
      //  GetStatusBar().SetPartWidth(1, 30);
      //  GetStatusBar().SetPartWidth(2, 30);
      //  GetStatusBar().SetPartWidth(3, 30);

      SetStatusIndicators();
    }

    // Place text in the 1st pane
    GetStatusBar().SetPartText(0, _T("Some Text"));
  }
}

Summary Information

Header file | statusbar.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CStatic

CStatic Class

Description

Applications often use static controls to label other controls or to separate a group of controls. Although static controls are child windows, they cannot be selected. Therefore, they cannot receive the keyboard focus and cannot have a keyboard interface. A static control that has the SS_NOTIFY style receives mouse input, notifying the parent window when the user clicks or double clicks the control. Static controls belong to the STATIC window class.

CStatic is the class responsible for creating a static control.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of static controls.

CStatic Members

Construction

CStatic
CStatic();
Constructs a CStatic

Attributes

GetBitmap
HBITMAP GetBitmap() const;
Returns the handle of the bitmap associated with the static control.
GetCursor
HCURSOR GetCursor() const;
Returns the handle of the cursor associated with the static control.
GetEnhMetaFile
HENHMETAFILE GetEnhMetaFile() const;
Returns the handle of the enhanced metafile associated with the static control.
GetIcon
HICON GetIcon() const;
Returns a handle to the icon associated with the static control.
SetBitmap
HBITMAP SetBitmap(HBITMAP hBitmap) const;
Specifies the bitmap to be displayed in the static control.
SetCursor
HCURSOR SetCursor(HCURSOR hCursor) const;
Specifies the cursor to be displayed in the static control.
SetEnhMetaFile
HENHMETAFILE SetEnhMetaFile(HENHMETAFILE hMetaFile) const;
Specifies the handle of the enhanced metafile for the static control.
SetIcon
HICON SetIcon(HICON hIcon) const;
Specifies the handle of the icon to be displayed in the static control.

Overidables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the static control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a static control.

Although static controls can be used in overlapped, pop-up, and child windows, they are designed for use in dialog boxes, where the system standardizes their behavior. By using static controls outside dialog boxes, a developer increases the risk that the application might behave in a nonstandard fashion. Typically, a developer either uses static controls in dialog boxes or uses the SS_OWNERDRAW style to create customized static controls.

Summary Information

Header file | stdcontrols.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CString

CString Class

Description

This class is intended to provide much the same functionality of the MFC/ATL CString class that ships with Microsoft compilers. The CString class specified here is compatible with other compilers such as Borland 5.5 and MinGW.

CString Members

Initialisation and Assignment
CString
CString();
CString(LPCSTR pszText);
CString(LPCWSTR pszText);
CString(TCHAR ch, int nLength = 1);
CString(LPCTSTR pszText, int nLength);
Constructor for CString.
operator =
CString& operator = (const CString& str);
CString& operator = (const TCHAR ch);
CString& operator = (LPCSTR pszText);
CString& operator = (LPCWSTR pszText);
Assigns a value to the CString.
Attributes
c_str
LPCTSTR c_str() const;
Converts the CString to a LPCTSTR.
GetString
tString& GetString();
Returns a reference to the underlying std::basic_string<TCHAR>.
GetLength
int GetLength() const;
Returns the length in characters.
operator LPCTSTR
operator LPCTSTR() const;
Converts the CString to a LPCTSTR.
operator BSTR
operator BSTR() const;
Converts the CString to a BSTR.
Operations
AllocSysString
BSTR AllocSysString() const;
Allocates a BSTR from the CString content.
AppendFormat
void AppendFormat(LPCTSTR pszFormat,...);
void AppendFormat(UINT nFormatID, ...);
Appends formatted data to an the CString content.
Collate
int Collate(LPCTSTR pszText) const;
Performs a case sensitive comparison of the two strings using locale-specific information.
CollateNoCase
int CollateNoCase(LPCTSTR pszText) const;
Performs a case insensitive comparison of the two strings using locale-specific information.
Compare
int Compare(LPCTSTR pszText) const;
Performs a case sensitive comparison of the two strings.
CompareNoCase
int CompareNoCase(LPCTSTR pszText) const;
Performs a case insensitive comparison of the two strings.
Delete
int Delete(int nIndex, int nCount = 1);
Deletes a character or characters from the string.
Empty
void Empty();
Erases the contents of the string.
Find
int Find(TCHAR ch, int nIndex = 0 ) const;
int Find(LPCTSTR pszText, int nStart = 0) const;
Finds a character in the string.
FindOneOf
int FindOneOf(LPCTSTR pszText) const;
Finds the first matching character from a set.
Format
void Format(UINT nID, ...);
void Format(LPCTSTR pszFormat,...);
Formats the string as sprintf does.
FormatV
void FormatV(LPCTSTR pszFormat, va_list args);
Formats the string using a variable list of arguments.
FormatMessage
void FormatMessage(LPCTSTR pszFormat,...);
Formats a message string.
FormatMessageV
void FormatMessageV(LPCTSTR pszFormat, va_list args);
Formats a message string using a variable argument list.
GetAt
TCHAR GetAt(int nIndex) const;
Returns the character at the specified location within the string.
GetBuffer
LPTSTR GetBuffer(int nMinBufLength);
Creates a buffer of nMinBufLength charaters (+1 extra for NULL termination) and returns a pointer to this buffer. This buffer can be used by any function which accepts a LPTSTR. Care must be taken not to exceed the length of the buffer. Use ReleaseBuffer to copy this buffer back to the CString object.
GetEnvironmentVariable
BOOL GetEnvironmentVariable(LPCTSTR pszVar);
Sets the string to the value of the specified environment variable.
GetErrorString
void GetErrorString(DWORD dwError);
Returns the error string for the specified System Error Code (e.g from GetLastErrror).
Insert
int Insert(int nIndex, TCHAR ch);
int Insert(int nIndex, const CString& str);
Inserts a single character or a substring at the given index within the string.
IsEmpty
BOOL IsEmpty() const;
Returns TRUE if the string is empty.
Left
CString Left(int nCount) const;
Extracts the left part of a string.
LoadString
BOOL LoadString(UINT nID);
Loads the string from a Windows resource.
MakeLower
void MakeLower();
Converts all the characters in this string to lowercase characters.
MakeReverse
void MakeReverse();
Reverses the string.
MakeUpper
void MakeUpper();
Converts all the characters in this string to uppercase characters.
Mid
CString Mid(int nFirst) const;
CString Mid(int nFirst, int nCount) const;
Extracts the middle part of a string.
ReleaseBuffer
void ReleaseBuffer( int nNewLength = -1 );
This copies the contents of the buffer (acquired by GetBuffer) to this CString, and releases the contents of the buffer. The default length of -1 copies from the buffer until a null terminator is reached. If the buffer doesn't contain a null terminator, you must specify the buffer's length.
Remove
int Remove(LPCTSTR pszText);
Removes each occurrence of the specified substring from the string.
Replace
int Replace(TCHAR chOld, TCHAR chNew);
int Replace(const LPCTSTR pszOld, LPCTSTR pszNew);
Replaces each occurance of the old character with the new character.
ReverseFind
int ReverseFind(LPCTSTR pszText, int nStart = -1) const;
Search for a substring within the string, starting from the end.
Right
CString Right(int nCount) const;
Extracts the right part of a string.
SetAt
void SetAt(int nIndex, TCHAR ch);
Creates a logical brush that has the specified solid color.
SetSysString
BSTR SetSysString(BSTR* pBstr) const;
Sets an existing BSTR object to the string.
SpanExcluding
CString SpanExcluding(LPCTSTR pszText) const;
Extracts characters from the string, starting with the first character, that are not in the set of characters identified by pszCharSet.
SpanIncluding
CString SpanIncluding(LPCTSTR pszText) const;
Extracts a substring that contains only the characters in a set.
Tokenize
CString Tokenize(LPCTSTR pszTokens, int& iStart) const;
Extracts specified tokens in a target string.
Trim
void Trim();
Trims all leading and trailing whitespace characters from the string.
TrimLeft
void TrimLeft();
void TrimLeft(TCHAR chTarget);
void TrimLeft(LPCTSTR pszTargets);
Trims white space characters or the specified set of characters from the beginning of the string.
TrimRight
TrimRight();
void TrimRight(TCHAR chTarget);
void TrimRight(LPCTSTR pszTargets);
Trims trailing whitespace characters or the specified set of characters from the string.
Truncate
void Truncate(int nNewLength);
Reduces the length of the string to the specified amount.
operator +
friend CString operator + (const CString& string1, const CString& string2);
friend CString operator + (const CString& string, LPCTSTR pszText);
friend CString operator + (const CString& string, TCHAR ch);
friend CString operator + (LPCTSTR pszText, const CString& string);
friend CString operator + (TCHAR ch, const CString& string);
Appends the specified characters to the string.
operator +=
CString& operator += (const CString& str);
CString& operator += (LPCSTR szText);
CString& operator += (LPCWSTR szText);
Appends and then assigns the specified characters to the string.
operator []
TCHAR& operator [] (int nIndex);
Returns the character at the specified index.
Comparisons
operator ==
bool operator == (LPCTSTR pszText);
Performs a case sensitive comparison of the two strings. Returns true of the two strings are the same.
operator !=
bool operator != (LPCTSTR pszText);
Performs a case sensitive comparison of the two strings. Returns true if the two strings are not the same.
operator <
friend bool operator < (const CString& string1, const CString& string2);
friend bool operator < (const CString& string1, LPCTSTR pszText);
Performs a case sensitive comparison of the two strings.
operator >
friend bool operator > (const CString& string1, const CString& string2);
friend bool operator > (const CString& string1, LPCTSTR pszText);
Performs a case sensitive comparison of the two strings.
operator <=
friend bool operator <= (const CString& string1, const CString& string2);
friend bool operator <= (const CString& string1, LPCTSTR pszText);
Performs a case sensitive comparison of the two strings.
operator >=
friend bool operator >= (const CString& string1, const CString& string2);
friend bool operator >= (const CString& string1, LPCTSTR pszText);
Performs a case sensitive comparison of the two strings.

Remarks

Using the CString class

The following code demonstrates how to assign strings to a CString.

// Assign some text to CString
CString str1 = _T("Hello World.");
CString str2 = _T(" I like strings.");
CString str3 = str1 + str2;
SetWindowText(str3);
// How to use GetBuffer and SetBuffer with functions expecting a TCHAR array
CString str4;
LPTSTR szText = str4.GetBuffer(80);
::GetWindowText(m_hWnd, szText, 80);
str4.ReleaseBuffer();

Differences between this class and the MFC/ATL CString class

  • The constructors for this class accepts only TCHARs. The various text conversion functions can be used to convert from other character types to TCHARs.
  • This class is not reference counted, so these CStrings should be passed as references or const references when used as function arguments. As a result there
    is no need for functions like LockBuffer and UnLockBuffer.
  • The Format functions only accepts POD (Plain Old Data) arguments. It does not accept arguments which are class or struct objects. In particular it does not accept CString objects, unless these are cast to LPCTSTR. This is demonstrates valid and invalid usage:
    CString string1(_T("Hello World"));
CString string2;

// This is invalid, and produces undefined behaviour.
string2.Format(_T("String1 is: %s"), string1); // No! you can't do this

// This is ok
string2.Format(_T("String1 is: %s"), (LPCTSTR)string1); // Yes, this is correct
  • This class provides a few additional functions:
    • c_str Returns a const TCHAR string. This is an alternative for casting to LPCTSTR.
    • GetErrorString Assigns CString to the error string for the specified System Error Code.
    • GetString Returns a reference to the underlying std::basic_string<TCHAR>.

Summary Information

Header file | cstring.h
Win32/64 support | Yes
WinCE support | Yes


CTab

CTab Class

Description

A tab control is window that displays one or more tabs, and a window page. It is somewhat 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.

CTab is the class which creates a tab control. The tabs typically have an icon, and some text. The tabs can be displayed either at the top or bottom of the window. Additional buttons to allow the tabs to be listed or closed can also be displayed.

The AddTabPage function is used to add new tabs to the control. This function provides an opportunity to specify the tab's icon and text, as well as the window which will be used as this tab's page.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of tab controls.

CTab Members

Operations

CTab
CTab();
Constructor for CTab
AddTabPage
virtual int AddTabPage(ViewPtr pView, LPCTSTR szTabText, HICON hIcon, UINT idTab);
virtual int AddTabPage(ViewPtr pView, LPCTSTR szTabText, UINT nID_Icon, UINT idTab = 0);
virtual int AddTabPage(ViewPtr pView, LPCTSTR szTabText);
Adds a tab page from the specified view window, tab text and tab icon.
AdjustRect
void AdjustRect(BOOL fLarger, RECT *prc) const;
Calculates a tab control's display area given a window rectangle, or calculates the window rectangle that would correspond to a specified display area.
GetActiveView
CWnd* GetActiveView() const;
Returns a pointer to the currently active view window
GetAllTabs
std::vector <TabPageInfo>& GetAllTabs() const;
Returns a reference to the vector of tab page information for all tabs.
GetCloseRect
virtual CRect GetCloseRect() const;
Returns the dimensions of the bounding rectangle of the close button.
GetCurFocus
int GetCurFocus() const;
Returns the index of the item that has the focus in a tab control.
GetCurSel
int GetCurSel() const;
Determines the currently selected tab in a tab control.
GetImageList
HIMAGELIST GetImageList() const;
Returns the handle of the tab control's image list.
GetItem
BOOL GetItem(int iItem, LPTCITEM pitem) const;
Retrieves information about a tab in a tab control.
GetItemCount
int GetItemCount() const;
Retrieves the number of tabs in the tab control.
GetListMenu
virtual HMENU GetListMenu();
Returns the a handle to the list menu.
GetListRect
virtual CRect GetListRect() const;
Returns the dimensions of the bounding rectangle of the list button.
GetShowButtons
BOOL GetShowButtons() const;
Returns TRUE if the list and close buttons are displayed.
GetTabHeight
int GetTabHeight() const;
Returns the height of the tabs.
GetTabIndex
virtual int GetTabIndex(CWnd* pWnd) const;
Returns the index of the tab given its view window.
GetTabPageInfo
virtual TabPageInfo GetTabPageInfo(UINT nTab) const;
Returns the tab page info struct for the specified tab.
GetTabsAtTop
virtual BOOL GetTabsAtTop() const;
Returns TRUE if the tabs are displayed at the top of the control, and FALSE if they are displayed at the bottom.
HitTest
int HitTest(TCHITTESTINFO& info) const;
Determines which tab, if any, is at a specified screen position.
RecalcLayout
virtual void RecalcLayout();
Repositions the child windows of the tab control.
RemoveTabPage
virtual void RemoveTabPage(int nPage);
Removes a tab page from the control.
SelectPage
virtual void SelectPage(int nPage);
Makes the specified tab index the selected tab page.
SetCurFocus
void SetCurFocus(int iItem) const;
Sets the focus to a specified tab in a tab control.
SetCurSel
int SetCurSel(int iItem) const;
Selects a tab in a tab control.
SetFixedWidth
virtual void SetFixedWidth(BOOL bEnabled);
Enable or disable fixed tab width.
SetItemSize
DWORD SetItemSize(int cx, int cy) const;
Sets the width and height of tabs.
SetMinTabWidth
int SetMinTabWidth(int cx) const;
Sets the minimum width of items in a tab control.
SetOwnerDraw
virtual void SetOwnerDraw(BOOL bEnabled);
Enable or disable owner draw. Set owner draw to TRUE to display the tab icons.
SetPadding
void SetPadding(int cx, int cy) const;
Sets the amount of space (padding) around each tab's icon and label in a tab control.
SetShowButtons
virtual void SetShowButtons(BOOL bShow);
Allows the list and close buttons to be shown or hidden.
SetTabHeight
void SetTabHeight(int nTabHeight);
Sets the height of the tabs.
SetTabIcon
virtual void SetTabIcon(int i, HICON hIcon);
Change the tab's existing icon, or assigns a new icon if one didn't previously exist.
SetTabsAtTop
virtual void SetTabsAtTop(BOOL bTop);
Positions the tabs at the top or bottom of the control.
SetTabText
virtual void SetTabText(UINT nTab, LPCTSTR szText);
Sets the text of the specified tab
SwapTabs
virtual void SwapTabs(UINT nTab1, UINT nTab2);
Swaps the two specified tabs.

Overridables

DrawCloseButton
virtual void DrawCloseButton(CDC& DrawDC);
Draws the close button.
DrawListButton
virtual void DrawListButton(CDC& DrawDC);
Draws the list button.
DrawTabs
virtual void DrawTabs(CDC& dcMem);
Draws the tabs.
DrawTabBorders
virtual void DrawTabBorders(CDC& dcMem, CRect& rcTab);
Draws the tab borders.
OnCreate
virtual void OnCreate();
Called when the tab control is created.
OnLButtonUp
virtual void OnLButtonUp(WPARAM wParam, LPARAM lParam);
Called when the left mouse button is released.
OnMouseLeave
virtual void OnMouseLeave(WPARAM wParam, LPARAM lParam);
Called when the mouse leaves the tab control.
OnMouseMove
virtual void OnMouseMove(WPARAM wParam, LPARAM lParam);
Called when the mouse moves over the tab control.
OnNCHitTest
virtual LRESULT OnNCHitTest(WPARAM wParam, LPARAM lParam);
Called when the mouse moves, or when a mouse button is pressed or released over the tab control (non-client hit test).
OnNotifyReflect
virtual void NotifyChanged();
Called when the tab control sends a notification.
Paint
virtual void Paint();
Paints the tab control.
PreCreate
virtual void PreCreate(CREATESTRUCT& cs);
Specifies the window creation parameters before the window is created.
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created
SetTabSize
virtual void SetTabSize();
Sets the size of the tabs.
ShowListDialog
virtual void ShowListDialog();
Displays the list of windows in a dialog.
ShowListMenu
virtual void ShowListMenu();
Displays the list of windows in a popup menu.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the tab control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a tab control.

The following example shows how to add pages to a tab control.

void CMainFrame::OnInitialUpdate()
{
  // Add some tabs to the tab control
  SetOwnerDraw(TRUE);
  SetFixedWidth(TRUE);
  m_View.AddTabPage(new CViewClasses, _T("Classes"), IDI_CLASSVIEW);
  m_View.AddTabPage(new CViewFiles, _T("Files"), IDI_FILEVIEW);
  m_View.AddTabPage(new CViewClasses, _T("Classes"), IDI_CLASSVIEW);
  m_View.AddTabPage(new CViewFiles, _T("Files"), IDI_FILEVIEW);
  m_View.SelectPage(0);
}

SetOwnerDraw disables or enables owner drawing for the tab control. When owner drawing is enabled, flickering in the tab's view window is reduced and tabs at the bottom of the tab control are drawn properly. When owner drawing is disabled, the tab control reverts back to its default drawing and tab rendering.

Refer to the TabDemo for a demonstration of using CTab as the view window within a Frame, and TabDialogDemo for a demonstration of using CTab in a dialog.

Summary Information

Header file | tab.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CTabbedMDI

CTabbedMDI Class

Description

CTabbedMDI class combines the features of a tab control and a MDI window. Each MDI child is displayed as a separate tab page. Buttons which allow the MDI children to be listed or closed are displayed to the right of the tabs. The tabs can be displayed either at the top or bottom of the window.

CTabbedMDI Members

Operations

CTabbedMDI
CTabbedMDI();
Constructor for CTabbedMDI
AddMDIChild
virtual CWnd* AddMDIChild(CWnd* pView, LPCTSTR szTabText, int idMDIChild = 0);
Adds a MDI tab, given a pointer to the view window, and the tab's text.
CloseActiveMDI
virtual void CloseActiveMDI();
Closes the active MDI child
CloseAllMDIChildren
virtual void CloseAllMDIChildren();
Closes all MDI children
CloseMDIChild
virtual void CloseMDIChild(int nTab);
Closes the MDI child, given the tab's index.
GetActiveMDIChild
virtual CWnd* GetActiveMDIChild() const;
Retrieves a pointer to the active MDI child's view window.
GetActiveMDITab
virtual int GetActiveMDITab() const;
Retrieves the index of the current active MDI tab.
GetListMenu
virtual HMENU GetListMenu() const
Retrieves a pointer to the MDI child's view window, give the tab's index.
GetMDIChild
virtual CWnd* GetMDIChild(int nTab) const;
Retrieves a pointer to the MDI child's view window, give the tab's index.
GetMDIChildCount
virtual int GetMDIChildCount() const;
Retrieves the number of MDI children.
GetMDIChildID
virtual int GetMDIChildID(int nTab) const;
Retrieves the MDI child's ID, given the tab's index.
GetMDIChildTitle
virtual LPCTSTR GetMDIChildTitle(int nTab) const;
Retrieves the MDI child's text, given the tab's index
GetTab
virtual CTab& GetTab() const {return (CTab&)m_Tab;}
Retrieves a reference to the TabbedMDI's tab control.
LoadRegistrySettings
virtual BOOL LoadRegistrySettings(tString tsRegistryKeyName);
Loads the TabbedMDI information from the registry.
RecalcLayout
virtual void RecalcLayout();
Repositions the child windows of the TabbedMDI window.
SaveRegistrySettings
virtual BOOL SaveRegistrySettings(tString tsRegistryKeyName);
Saves the TabbedMDI information in the registry
SetActiveMDIChild
virtual void SetActiveMDIChild(CWnd* pWnd);
Sets the active MDI child, given its view window.
SetActiveMDITab
virtual void SetActiveMDITab(int nTab);
Sets the active MDI child given its tab index.

Overridables

NewMDIFromID
virtual CWnd* NewMDIChildFromID(int idMDIChild);
Override this function to create a new Docker given its TabbedMDI ID.
OnCreate
virtual void OnCreate() ;
Called when the TabbedMDI window is created.
OnDestroy
virtual void OnDestroy(WPARAM wParam, LPARAM lParam);
Called when the TabbedMDI window is destroyed.
OnNotify
virtual LRESULT OnNotify(WPARAM wParam, LPARAM lParam);
Called when the TabbedMDI recieves a notification.
OnWindowPosChanged
virtual void OnWindowPosChanged(WPARAM wParam, LPARAM lParam);
Called when the TabbedMDI window is resized or repositioned.

Remarks

The following example demonstrates how to toggle the MDI tab position between the top and bottom of the window.

void CMainFrame::OnMDITabsAtTop()
// Toggle the TabbedMDI's tabs between the top to bottom of window
{
  CTabbedMDI* pTabbedMDI = m_DockTabbedMDI.GetTabbedMDI();

  BOOL bTop = pTabbedMDI->GetTab().GetTabsAtTop();
  pTabbedMDI->GetTab().SetTabsAtTop(!bTop);

  // Set the menu checkmark
  UINT uCheck = (bTop)? MF_UNCHECKED : MF_CHECKED;
  ::CheckMenuItem(GetFrameMenu(), IDM_TABBEDMDI_TOP, uCheck);
}

The following example demonstrates how to add MDI children to the TabbedMDI control.

void CMainFrame::LoadDefaultMDIs()
{
  // Add some MDI tabs
  CTabbedMDI* pTabbedMDI = (CTabbedMDI*)m_DockTabbedMDI.GetView();
  pTabbedMDI->AddMDIChild(new CViewSimple, _T("Simple View"), ID_MDI_SIMPLE);
  pTabbedMDI->AddMDIChild(new CViewRect, _T("Rectangles"), ID_MDI_RECT);
  pTabbedMDI->AddMDIChild(new CViewText, _T("TextView"), ID_MDI_TEXT);
  pTabbedMDI->AddMDIChild(new CViewClasses, _T("Classes"), ID_MDI_CLASSES);
  pTabbedMDI->AddMDIChild(new CViewFiles, _T("Files"), ID_MDI_FILES);
  pTabbedMDI->SetActiveMDITab(0);
}
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Refer to the DockTabbedMDI sample for a demonstration of the use of CTabbedMDI.

Summary Information

Header file | tab.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CTaskDialog

CTaskDialog Class

Description

The CTaskDialog class is used to create Task Dialogs.A task dialog is a dialog box that can be used to display information and receive simple input from the user. Like a message box, it is formatted by the operating system according to parameters you set. However, a task dialog has many more features than a message box.

CTaskDialog Members

Construction
CTaskDialog
CTaskDialog();
Constructor for the CTaskDialog.
Attributes
GetConfig
TASKDIALOGCONFIG GetConfig() const;
Returns the TASKDIALOGCONFIG structure for the Task Dialog.
GetOptions
TASKDIALOG_FLAGS GetOptions() const;
Returns the Task Dialog's options.
GetSelectedButtonID
int GetSelectedButtonID() const;
Returns the ID of the selected button.
GetSelectedRadioButtonID
int GetSelectedRadioButtonID() const;
Returns the ID of the selected radio button.
GetVerificationCheckboxState
BOOL GetVerificationCheckboxState() const;
Returns the state of the verification check box.
IsSupported
static BOOL IsSupported();
Returns true if TaskDialogs are supported on this system.
SetCommonButtons
void SetCommonButtons(TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons);
Sets the common buttons for the task dialog.
SetContent
void SetContent(LPCTSTR pszContent);
Sets the task dialog's primary content.
SetDefaultButton
void SetDefaultButton(int nButtonID);
Sets the task dialog's default button.
SetDefaultRadioButton
void SetDefaultRadioButton(int nRadioButtonID);
Sets the default radio button.
SetDialogWidth
void SetDialogWidth(UINT nWidth = 0);
The width of the task dialog's client area. If 0, the task dialog manager will calculate the ideal width.
SetExpansionArea
void SetExpansionArea(LPCTSTR pszExpandedInfo, LPCTSTR pszExpandedLabel = _T(""),
                      LPCTSTR pszCollapsedLabel = _T(""));
Sets the text in the expandable area of the Task Dialog.
SetFooterIcon
void SetFooterIcon(HICON hFooterIcon);
void SetFooterIcon(LPCTSTR lpszFooterIcon);
Sets the icon that will be displayed in the Task Dialog's footer.
SetFooterText
void SetFooterText(LPCTSTR pszFooter);
Sets the text that will be displayed in the Task Dialog's footer.
SetMainIcon
void SetMainIcon(HICON hMainIcon);
void SetMainIcon(LPCTSTR lpszMainIcon);
Sets Task Dialog's main icon.
SetMainInstruction
void SetMainInstruction(LPCTSTR pszMainInstruction);
Sets the Task Dialog's main instruction text.
SetOptions
void SetOptions(TASKDIALOG_FLAGS dwFlags);
Sets the Task Dialog's options.
SetProgressBarMarquee
void SetProgressBarMarquee(BOOL bEnabled = TRUE, int nMarqueeSpeed = 0);
Starts and stops the marquee display of the progress bar, and sets the speed of the marquee.
SetProgressBarPosition
void SetProgressBarPosition(int nProgressPos);
Sets the current position for a progress bar.
SetProgressBarRange
void SetProgressBarRange(int nMinRange, int nMaxRange);
Sets the minimum and maximum values for the hosted progress bar.
SetProgressBarState
void SetProgressBarState(int nNewState = PBST_NORMAL);
Sets the current state of the progress bar.
SetVerificationCheckbox
void SetVerificationCheckbox(BOOL bChecked);
Simulates a click on the verification checkbox of the Task Dialog, if it exists.
SetVerificationCheckboxText
void SetVerificationCheckboxText(LPCTSTR pszVerificationText);
Sets the text for the verification check box.
SetWindowTitle
void SetWindowTitle(LPCTSTR pszWindowTitle);
Sets the Task Dialog's window title.
Operations
AddCommandControl
void AddCommandControl(int nButtonID, LPCTSTR pszCaption);
Adds a command control or push button to the Task Dialog.
AddRadioButton
void AddRadioButton(int nRadioButtonID, LPCTSTR pszCaption);
Adds a radio button to the Task Dialog.
AddRadioButtonGroup
void AddRadioButtonGroup(int nIDRadioButtonsFirst, int nIDRadioButtonsLast);
Adds a range of radio buttons to the Task Dialog. The resource ID of the button and it's string must match.
ClickButton
void ClickButton(int nButtonID) const;
Simulates the action of a button click in the Task Dialog.
ClickRadioButton
void ClickRadioButton(int nRadioButtonID) const;
Simulates the action of a radio button click in the TaskDialog.
DoModal
LRESULT DoModal(CWnd* pParent = NULL);
Creates and displays the Task Dialog.
ElevateButton
void ElevateButton(int nButtonID, BOOL bElevated);
Adds a shield icon to indicate that the button's action requires elevated privilages.
EnableButton
void EnableButton(int nButtonID, BOOL bEnabled);
Enables or disables a push button in the TaskDialog.
EnableRadioButton
void EnableRadioButton(int nButtonID, BOOL bEnabled);
Enables or disables a radio button in the TaskDialog.
NavigateTo
void NavigateTo(CTaskDialog& TaskDialog) const;
Replaces the information displayed by the task dialog.
RemoveAllButtons
void RemoveAllButtons();
Removes all push buttons from the task dialog.
RemoveAllRadioButtons
void RemoveAllRadioButtons();
Removes all radio buttons from the task dialog.
Reset
void Reset();
Returns the dialog to its default state.
UpdateElementText
void UpdateElementText(TASKDIALOG_ELEMENTS eElement, LPCTSTR pszNewText);
Updates a text element on the Task Dialog.
Overridables
OnTDButtonClicked
virtual BOOL OnTDButtonClicked(int nButtonID);
Called when the user selects a button or command link.
OnTDConstructed
virtual void OnTDConstructed();
Called when the task dialog is constructed, before it is displayed.
OnTDCreated
virtual void OnTDCreated();
Called when the task dialog is displayed.
OnTDDestroyed
virtual void OnTDDestroyed();
Called when the task dialog is destroyed.
OnTDExpandButtonClicked
virtual void OnTDExpandButtonClicked(BOOL bExpanded);
Called when the expand button is clicked.
OnTDHelp
virtual void OnTDHelp();
Called when the user presses F1 on the keyboard.
OnTDHyperlinkClicked
virtual void OnTDHyperlinkClicked(LPCTSTR pszHref);
Called when the user clicks on a hyperlink.
OnTDNavigatePage
virtual void OnTDNavigatePage();
Called when a navigation has occurred.
OnTDRadioButtonClicked
virtual BOOL OnTDRadioButtonClicked(int nRadioButtonID);
Called when the user selects a radio button.
OnTDTimer
virtual void OnTDTimer(DWORD dwTickCount);
Called every 200 milliseconds (aproximately) when the TDF_CALLBACK_TIMER flag is set.
OnTDVerificationCheckboxClicked
virtual void OnTDVerificationCheckboxClicked(BOOL bChecked);
Called when the user clicks the Task Dialog verification check box.
TaskDialogProc
virtual LRESULT TaskDialogProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
Override this function to specify how the messages for this window are to be handled. Return all unhandled messages to TaskDialogProcDefault.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Task dialogs require Windows Vista or above. They are not supported on Windows XP. The IsSupported function can be used to test if the operating system is capable of supporting task dialogs.

The following diagram illustrates the various components of a task dialog.

Summary Information

Header file | taskdialog.h
Win32/64 support | Yes
WinCE support | No


CThread

CThread Class

Description

The CThread class simplifies the use of threads with WIn32++. Inherit from this class and override InitInstance to specify what the thread does when it starts.

A new thread is created when the CThread derived class is instantiated. By default the thread is created in the suspended state and will need to be resumed. When the thread is resumed, it runs the InitInstance function.

CThread Members

CThread
CThread();
CThread(LPSECURITY_ATTRIBUTES pSecurityAttributes, unsigned stack_size, unsigned initflag);
Constructs the CThread. Optionally, the security attributes, stack size and init flag can be set when CThread is constructed.
GetThread
HANDLE GetThread() const;
Returns the thread handle
GetThreadID
int GetThreadID() const;
Returns the thread ID
GetThreadPriority
int GetThreadPriority() const;
Returns the thread's priority
ResumeThread
DWORD ResumeThread() const;
Resumes the execution of the thread. By default, the thread is created in a suspended state, and should be resumed when the application is ready to have the thread run.
SetThreadPriority
BOOL SetThreadPriority(int nPriority) const;
Sets the thread's priority.
SuspendThread
DWORD SuspendThread() const;
Suspends the execution of the thread.

Overridables

InitInstance
virtual BOOL InitInstance();
The function which runs when the thread starts. Override this function to specify what the thread does when it starts. Return TRUE if the message loop should run, otherwise return FALSE.
MessageLoop
virtual int MessageLoop();
The MessageLoop function is called if InitInstance returns TRUE. Override this function if you wish to customise the message loop run by this thread.

Remarks

If your thread is used to run one or more windows, InitInstance should return TRUE, causing the MessageLoop function to be called. If your thread doesn't require a MessageLoop, it should return FALSE. Threads which don't run a message loop as sometimes referred to as "worker" threads.

Note: It is your job to end the thread before CThread ends! To end a thread with a message loop, post a WM_QUIT message to the thread. To end a thread without a message loop, set an event, and end the thread when the event is received.

Programming Hints:

  • It is never a good idea to use things like TerminateThread or ExitThread to end your thread. These represent poor programming techniques, and are likely to leak memory and resources.
  • Avoid using SendMessage between threads, as this will cause one thread to wait for the other to respond. Use PostMessage between threads to avoid this problem.
  • Access to variables and resources shared between threads need to be made thread safe. Having one thread modify a resource or variable while another thread is accessing it is a recipe for disaster.
  • Thread Local Storage (TLS) can be used to replace global variables to make them thread safe. With TLS, each thread gets its own copy of the variable.
  • Critical Sections can be used to make shared resources thread safe.
  • Window messages (including user defined messages) can be posted between GUI threads to communicate information between them.
  • Events (created by CreateEvent) can be used to communicate information between threads (both GUI and worker threads).
  • Avoid using sleep to synchronise threads. Generally speaking, the various wait functions (e.g. WaitForSingleObject) will be better for this.

About Threads:
Each program that executes has a "process" allocated to it. A process has one or more threads. Threads run independantly of each other. It is the job of the operating system to manage the running of the threads, and do the task switching between threads as required. Systems with multiple CPUs will be able to run as many threads simultaneously as there are CPUs.

Threads behave like a program within a program. When the main thread starts, the application runs the WinMain function and ends when WinMain ends. When another thread starts, it too will run the function provided to it, and end when that function ends.

Summary Information

Header file | thread.h
Win32/64 support | Yes
WinCE support | Yes


CToolBar

CToolBar Class

Description

The class responsible for creating and managing a toolbar. A toolbar is a control window that contains one or more buttons. Each button, when clicked by a user, sends a command message to the parent window. Typically, the buttons in a toolbar correspond to items in the application's menu, providing an additional and more direct way for the user to access an application's commands.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of toolbar controls.

CToolBar Members

CToolBar
CToolBar();
Constructor for CToolBar.
AddBitmap
virtual int AddBitmap(UINT ToolBarID);
Adds a bitmap to the toolbar. See also SetImages.
AddButton
virtual BOOL AddButton(UINT nID, BOOL bEnabled = TRUE);
Adds one button to the toolbar.
AddButtons
BOOL AddButtons(UINT uNumButtons, LPTBBUTTON lpButtons) const;
Adds one or more buttons to the toolbar.
AddString
int AddString(UINT nStringID) const;
Adds resource IDs to toolbar buttons.
AddStrings
int AddStrings(LPCTSTR lpszStrings) const;
Adds strings to the toolbar's string pool.
AutoSize
void Autosize() const;
Resizes the toolbar.
CheckButton
void CheckButton(int idButton, BOOL fCheck) const;
Checks or unchecks a given toolbar in a toolbar.
CommandToIndex
int CommandToIndex(int idButton) const;
Returns the button index, given the command ID.
DeleteButton
BOOL DeleteButton(int iButton) const;
Deletes a button from the toolbar
DisableButton
BOOL DisableButton(int idButton) const;
Disables a toolbar button.
EnableButton
BOOL EnableButton(int idButton) const;
Enables a toolbar button.
GetButton
BOOL GetButton(int iButton, LPTBBUTTON lpButton) const;
Retrieves information about the specified button in the toolbar.
GetButtonCount
int GetButtonCount() const;
Returns the number of buttons in the toolbar control.
GetButtonSize
DWORD GetButtonSize() const;
Retrieves the current width and height of toolbar buttons, in pixels.
GetButtonState
UINT GetButtonState(int idButton) const;
Returns the state of a toolbar button.
GetButtonStyle
BYTE GetButtonStyle(int idButton) const
Returns the style of toolbar button.
GetButtonText
LPCTSTR GetButtonText(int idButton) const;
Retrieves the display text of a button on the toolbar.
GetCommandID
int GetCommandID(int iIndex) const;
Returns the command ID given the button index.
GetDisabledImageList
HIMAGELIST GetDisabledImageList() const;
Retrieves the image list that the toolbar uses to display inactive buttons.
GetHotImageList
HIMAGELIST GetImageList() const;
Retrieves the image list that the toolbar uses to display hot buttons.
GetHotItem
int GetHotItem() const;
Retrieves the index of the hot button.
GetImageList
HIMAGELIST GetImageList() const;
Retrieves the image list that the toolbar uses to display buttons in their default state.
GetItemRect
CRect GetItemRect(int iIndex) const;
Returns the bounding rectangle of a button in a toolbar.
GetMaxSize
CSize GetMaxSize() const;
Returns the SIZE required to contain the toolbar's buttons.
GetPadding
DWORD GetPadding() const;
Retrieves the padding for the toolbar.
GetRect
CRect GetRect(int idButton) const;
Retrieves the bounding rectangle for a specified toolbar button.
GetRows
int GetRows() const;
Retrieves the number of rows of buttons in the toolbar.
GetTextRows
int GetTextRows() const;
Retrieves the maximum number of text rows that can be displayed on a toolbar button.
GetToolBarData
std::vector<UINT>& GetToolBarData() const
Returns a reference to the vector of resource IDs for toolbar buttons.
GetToolBarTheme
ToolBarTheme& GetToolBarTheme();
Returns the toolbar's theme structure. The theme structure defines the background colors of buttons when they are hot or pressed.
GetToolTips
CToolTip* GetToolTips() const;
Retrieves the handle to the TooTip control, if any, associated with the toolbar.
HasText
BOOL HasText() const;
Returns TRUE if the button has text.
HideButton
BOOL HideButton(int idButton, BOOL fShow) const;
Hides or shows the specified toolbar button.
HitTest
int HitTest() const;
Determines which button a point lies in a toolbar control.
Indeterminate
BOOL Indeterminate(int idButton, BOOL fIndeterminate) const;
Sets or clears the indeterminate state of the specified toolbar button.
InsertButton
BOOL InsetButton(int iButton, LPTBBUTTON lpButton) const;
Inserts a button in the toolbar.
IsButtonHidden
BOOL IsButtonHidden(int idButton) const;
Determines whether the specified toolbar button is hidden.
IsButtonHighlighted
BOOL IsButtonHighlighted(int idButton) const;
Checks the highlight state of the toolbar button.
IsButtonIndeterminate
BOOL IsButtonIndeterminate(int idButton) const;
Determines whether the specified toolbar button is indeterminate.
IsButtonPressed
BOOL IsButtonPressed(int idButton) const;
Determines whether the specified toolbar button is pressed.
MapAccelerator
int MapAccelerator(TCHAR chAccel) const;
Determines the ID of the button that corresponds to the specified accelerator character.
MarkButton
BOOL MarkButton(int idButton) const;
Sets the highlight state of a given button in a toolbar control.
MoveButton
BOOL MoveButton(UINT uOldPos, UINT uNewPos) const;
Moves a button from one index to another.
PressButton
BOOL PressButton(int idButton, BOOL fPress) const;
Presses or releases the specified toolbar button.
ReplaceBitmap
virtual BOOL ReplaceBitmap(UINT NewToolBarID);
Replaces a toolbar's bitmap. See also SetImages.
SaveRestore
void SaveRestore(BOOL fSave, TBSAVEPARAMS* ptbsp) const;
Initiates saving or restoring the toolbar's state.
SetBitmap
virtual BOOL SetBitmap(UINT nID);
Sets a toolbar's bitmap. See also SetImages.
SetBitmapSize
BOOL SetBitmapSize(int cx, int cy) const;
Sets the size of the bitmapped images to be added to a toolbar. Use this before adding the bitmap.
SetButtons
virtual int SetButtons(const std::vector<UINT>& vToolBarData) const;
Sets the resource IDs for the toolbar buttons.
SetButtonSize
BOOL SetBitmapSize(int cx, int cy) const;
Sets the size of the buttons to be added to a toolbar.
SetButtonState
BOOL SetButtonState(int idButton, UINT State) const;
Sets the state of a toolbar button.
SetButtonStyle
BOOL SetButtonStyle(int idButton, BYTE Style) const;
Sets the style of a toolbar button.
SetButtonText
virtual BOOL SetButtonText(int idButton, LPCTSTR szText);
Sets the text for a toolbar button.
SetButtonWidth
BOOL SetButtonWidth(int idButton, int nWidth) const;
Adjusts the width of a toolbar button after it is created. This is useful when replacing a button with a ComboBox or other control.
SetCommandID
BOOL SetCommandID(int iIndex, int idButton) const;
Sets the Command ID of a toolbar button.
SetDisabledImageList
HIMAGELIST SetDisableImageList(HIMAGELIST himlNewDisabled) const;
Sets the image list that the toolbar will use to display disabled buttons.
SetDrawTextFlags
DWORD SetDrawTextFlags(DWORD dwMask, DWORD dwDTFlags) const;
Sets the text drawing flags for the toolbar.
SetExtendedStyle
DWORD SetExtendedStyle(DWORD dwExStyle) const;
Sets the extended styles for the toolbar.
SetHotImageList
HIMAGELIST SetHotImageList(HIMAGELIST himlNewHot) const;
Sets the image list that the toolbar will use to display hot buttons.
SetHotItem
int SetHotItem(int iHot);
Sets the hot item in the toolbar. This message is ignored for toolbars that do not have the TBSTYLE_FLAT style.
SetImageList
HIMAGELIST SetImageList(HIMAGELIST himlNew) const;
Sets the image list that the toolbar will use to display buttons that are in their default state.
SetImages
virtual BOOL SetImages(COLORREF crMask, UINT ToolBarID,
              UINT ToolBarHotID, UINT ToolBarDisabledID);
Sets the image list (or lists) for the toolbar. The image lists are for default, hot and disabled buttons.
SetIndent
BOOL SetIndent(int iIndent) const;
Sets the indentation for the first toolbar button.
SetMaxTextRows
BOOL SetMaxTextRows(int iMaxRows) const;
Sets the maximum number of text rows displayed on a toolbar button.
SetPadding
BOOL SetPadding(int cx, int cy) const;
Sets the padding for the toolbar.
SetToolTips
void SetToolTips(CToolTip* pToolTip) const;
Associates a ToolTip control with a toolbar.
SetToolBarTheme
void SetToolBarTheme(ToolBarTheme& Theme);
Sets the toobar's theme structure. The theme structure defines the background colors of buttons when they are hot or pressed.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the toolbar control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a toolbar control.

The following code demonstrates how to display a ComboBoxEx control in a toolbar. Before displaying the control over the 'File Save' button, the button's width is adjusted, and the button is converted to a separator.

void CMainFrame::AddCombo()
{
  // We'll be placing the ComboBoxEx control over the 'File Save' toolbar button
  int nComboWidth = 120;
  CToolBar& TB = GetToolBar();
  if (TB.CommandToIndex(IDM_FILE_SAVE) < 0) return;

  TB.SetButtonStyle(IDM_FILE_SAVE, TBSTYLE_SEP);	// Convert the button to a separator
  TB.SetButtonWidth(IDM_FILE_SAVE, nComboWidth);

  // Determine the size and position of the ComboBox
  int nIndex = TB.CommandToIndex(IDM_FILE_SAVE);
  CRect rc = TB.GetItemRect(nIndex);

  // Create and position the ComboboxEx window
  m_ComboBoxEx.Create(TB.GetHwnd());
  m_ComboBoxEx.SetWindowPos(NULL, rc, SWP_NOACTIVATE);

  // Set ComboBox Height
  m_ComboBoxEx.SendMessage(CB_SETITEMHEIGHT, (WPARAM)-1, (LPARAM)rc.Height()-6);

  m_ComboBoxEx.AddItems();
  RecalcLayout();
}

Refer to the remarks section in the documentation for CFrame for an illustration on how to define an configure the toolbar.

Summary Information

Header file | toolbar.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CToolTip

CToolTip Class

Description

The CToolTip class adds support for the tool tip control. ToolTips appear automatically, or pop up, when the user pauses the mouse pointer over a tool or some other UI element. The ToolTip appears near the pointer and disappears when the user clicks a mouse button, moves the pointer away from the tool, or simply waits for a few seconds.

CToolTip Members

Construction
CToolTip
CToolTip();
Constructs a tool tip control.
Attributes
GetBubbleSize
CSize GetBubbleSize(LPTOOLINFO lpToolInfo) const;
Returns the width and height of the ToolTip control.
GetDelayTime
int GetDelayTime(DWORD dwDuration) const;
Retrieves the initial, pop-up, and reshow durations currently set for the ToolTip control.
GetMargin
void GetMargin(LPRECT lprc) const;
Retrieves the top, left, bottom, and right margins set for the ToolTip window.
GetMaxTipWidth
int GetMaxTipWidth() const;
Retrieves the maximum width for the ToolTip window.
GetText
void GetText(CString& str, CWnd* pWnd, UINT_PTR nIDTool = 0) const;
Retrieves the text from the tool tip control.
GetTipBkColor
COLORREF GetTipBkColor() const;
Retrieves the background color in the ToolTip window.
GetTipTextColor
COLORREF GetTipTextColor() const;
Retrieves the text color in a ToolTip window.
GetToolCount
int GetToolCount() const;
Retrieves a count of the tools maintained by the ToolTip control.
GetToolInfo
BOOL GetToolInfo(TOOLINFO& ToolInfo, CWnd* pWnd, UINT_PTR nIDTool = 0) const;
Retrieves the information that a ToolTip control maintains about the tool.
SetDelayTime
void SetDelayTime(UINT nDelay);
void SetDelayTime(DWORD dwDuration, int iTime);
Sets the initial, pop-up, and reshow durations for the ToolTip control
SetMargin
void SetMargin(LPRECT lprc);
Sets the top, left, bottom, and right margins for the ToolTip window.
SetMaxTipWidth
int SetMaxTipWidth(int iWidth);
Sets the maximum width for the ToolTip window.
SetTipBkColor
void SetTipBkColor(COLORREF clr);
Sets the background color in the ToolTip window.
SetTipTextColor
void SetTipTextColor(COLORREF clr);
Sets the text color in the ToolTip window.
SetToolInfo
void SetToolInfo(LPTOOLINFO lpToolInfo);
Sets the information that the ToolTip control maintains for a tool.
Operations
Activate
void Activate(BOOL bActivate);
Activates or deactivates the ToolTip control.
AddTool
BOOL AddTool(CWnd* pWnd, UINT nIDText, LPCRECT lpRectTool = NULL, UINT_PTR nIDTool = 0);
BOOL AddTool(CWnd* pWnd, LPCTSTR lpszText = LPSTR_TEXTCALLBACK, LPCRECT lpRectTool = NULL, UINT_PTR nIDTool = 0);
Registers a tool with a ToolTip control.
AdjustRect
BOOL AdjustRect(LPRECT lprc, BOOL bLarger = TRUE);
Calculates a ToolTip control's text display rectangle from its window rectangle, or the ToolTip window rectangle needed to display a specified text display rectangle.
DelTool
void DelTool(CWnd* pWnd, UINT_PTR nIDTool = 0);
Removes a tool from the ToolTip control.
HitTest
BOOL HitTest(CWnd* pWnd, CPoint pt, LPTOOLINFO lpToolInfo) const;
Tests a point to determine whether it is within the bounding rectangle of the specified tool and, if it is, retrieves information about the tool.
Pop
void Pop();
Removes a displayed ToolTip window from view.
RelayEvent
void RelayEvent(LPMSG lpMsg);
Passes a mouse message to a ToolTip control for processing.
SetTitle
BOOL SetTitle(UINT uIcon, LPCTSTR lpstrTitle);
Adds a standard icon and title string to a ToolTip.
SetToolRect
void SetToolRect(CWnd* pWnd, UINT_PTR nIDTool, LPCRECT lpRect);
Sets a new bounding rectangle for the tool.
SetWindowTheme
HRESULT SetWindowTheme(LPCWSTR lpstrTheme);
Sets the visual style of a ToolTip control.
Update
void Update();
Forces the current tool to be redrawn.
UpdateTipText
void UpdateTipText(LPCTSTR lpszText, CWnd* pWnd, UINT_PTR nIDTool = 0);
void UpdateTipText(UINT nIDText, CWnd* pWnd, UINT_PTR nIDTool = 0);
Sets the ToolTip text for a tool.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

ToolTip controls can display a single line of text or multiple lines. Their corners can be rounded or square. They might or might not have a stem that points to the tools like a cartoon speech balloon. ToolTip text can be stationary or can move with the mouse pointer, called tracking. Stationary text can be displayed adjacent to a tool or it can be displayed over a tool, which is referred to as in-place. Standard ToolTips are stationary, display a single line of text, have square corners, and have no stem pointing to the tool.

Summary Information

Header file | controls.h
Win32/64 support | Yes
WinCE support | Yes


CTreeView

CTreeView Class

Description

A tree-view control is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it. By clicking an item, the user can expand or collapse the associated list of subitems.

CTreeView is the class which creates a tree-view control. It can be used as a control in a Dialog, or as the View window in a Frame, Docker, MDI child.

Refer to the documentation that ships with the Microsoft Windows Software Development Kit for more information on the use of tree view controls.

CTreeView Members

Constructor

CTreeView
CTreeView();
Constructs a CTreeView.

Attributes

GetBkColor
COLORREF GetBkColor() const;
Retrieves the current background color of the control.
GetChild
HTREEITEM GetChild(HTREEITEM hItem) const;
Retrieves the first child item of the specified tree-view item.
GetCount
UINT GetCount() const;
Retrieves a count of the items in a tree-view control.
GetDropHiLightItem
HTREEITEM GetDropHiLightItem() const;
Retrieves the tree-view item that is the target of a drag-and-drop operation.
GetEditControl
CEdit* GetEditControl() const;
Retrieves the handle to the edit control being used to edit a tree-view item's text.
GetFirstVisible
HTREEITEM GetFirstVisible() const;
Retrieves the first visible item in a tree-view control window.
GetImageList
HIMAGELIST GetImageList(int iImageType) const;
Retrieves the handle to the normal or state image list associated with a tree-view control.
GetIndent
UINT GetIndent() const;
Retrieves the amount, in pixels, that child items are indented relative to their parent items.
GetInsertMarkColor
COLORREF GetInsertMarkColor() const;
Retrieves the color used to draw the insertion mark for the tree-view.
GetItem
BOOL GetItem(TVITEM& Item) const;
Retrieves some or all of a tree-view item's attributes.
GetItemData
DWORD_PTR GetItemData(HTREEITEM hItem) const;
Retrieves the application data from a tree-view item.
GetItemHeight
int GetItemHeight() const;
Retrieves the current height of the tree-view items.
GetItemImage
BOOL GetItemImage(HTREEITEM hItem, int& nImage, int& nSelectedImage) const;
Retrieves the index of the normal image and the selected image.
GetItemRect
BOOL GetItemRect(HTREEITEM hItem, CRect& rc, BOOL bTextOnly) const;
Retrieves the bounding rectangle for a tree-view item and indicates whether the item is visible.
GetItemText
tString GetItemText(HTREEITEM hItem, UINT nTextMax /* = 260 */) const;
Retrieve the text from a tree-view item.
GetLastVisible
HTREEITEM GetLastVisible() const;
Retrieves the last expanded item in a tree-view control. This does not retrieve the last item visible in the tree-view window.
GetNextItem
HTREEITEM GetNextItem(HTREEITEM hItem, UINT nCode) const;
Retrieves the tree-view item that bears the specified relationship to a specified item.
GetNextSibling
HTREEITEM GetNextSibling(HTREEITEM hItem) const;
Retrieves the next sibling item of a specified item in a tree-view control.
GetNextVisible
HTREEITEM GetNextVisible(HTREEITEM hItem) const;
Retrieves the next visible item that follows a specified item in a tree-view control.
GetParentItem
HTREEITEM GetParentItem(HTREEITEM hItem) const;
Retrieves the parent item of the specified tree-view item.
GetPrevSibling
HTREEITEM GetPrevSibling(HTREEITEM hItem) const;
Retrieves the previous sibling item of a specified item in a tree-view control.
GetPrevVisible
HTREEITEM GetPrevVisible(HTREEITEM hItem) const;
Retrieves the first visible item that precedes a specified item in a tree-view control.
GetRootItem
HTREEITEM GetRootItem() const;
Retrieves the topmost or very first item of the tree-view control.
GetScrollTime
int GetScrollTime() const;
Retrieves the maximum scroll time for the tree-view control.
GetSelection
HTREEITEM GetSelection() const;
Retrieves the currently selected item in a tree-view control.
GetTextColor
COLORREF GetTextColor() const;
Retrieves the current text color of the control.
GetToolTips
CToolTip* GetToolTips() const;
Retrieves the handle to the child ToolTip control used by a tree-view control.
GetVisibleCount
UINT GetVisibleCount() const;
Obtains the number of items that can be fully visible in the client window of a tree-view control.
ItemHasChildren
BOOL ItemHasChildren(HTREEITEM hItem) const;
Returns TRUE if the item has children.
SetBkColor
COLORREF SetBkColor(COLORREF clrBk) const;
Sets the background color of the control.
SetImageList
HIMAGELIST SetImageList(HIMAGELIST himl, int nType) const;
Sets the normal or state image list for a tree-view control and redraws the control using the new images.
SetIndent
void SetIndent(int indent) const;
Sets the width of indentation for a tree-view control and redraws the control to reflect the new width.
SetInsertMark
BOOL SetInsertMark(HTREEITEM hItem, BOOL fAfter = TRUE) const;
Sets the insertion mark in a tree-view control.
SetInsertMarkColor
COLORREF SetInsertMarkColor(COLORREF clrInsertMark) const;
Sets the color used to draw the insertion mark for the tree view.
SetItem
BOOL SetItem(TVITEM& Item) const;
BOOL SetItem(HTREEITEM hItem, UINT nMask, LPCTSTR szText, int nImage,
    int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam) const;
Sets some or all of a tree-view item's attributes.
SetItemData
BOOL SetItemData(HTREEITEM hItem, DWORD_PTR dwData) const;
Sets the application data for a tree-view item.
SetItemHeight
int SetItemHeight(SHORT cyItem) const;
Sets the height of the tree-view items.
SetItemImage
BOOL SetItemImage(HTREEITEM hItem, int nImage, int nSelectedImage) const;
Sets the index of the normal image and the selected image.
SetItemText
BOOL SetItemText(HTREEITEM hItem, LPCTSTR szText) const;
Sets the text of a tree-view item.
SetScrollTime
UINT SetScrollTime(UINT uScrollTime) const;
Sets the maximum scroll time for the tree-view control.
SetTextColor
COLORREF SetTextColor(COLORREF clrText) const;
Sets the text color of the control.
SetToolTips
CToolTip* SetToolTips(CToolTip* pToolTip) const;
Sets a tree-view control's child ToolTip control.

Operations

CreateDragImage
HIMAGELIST CreateDragImage(HTREEITEM hItem) const;
Creates a dragging bitmap for the specified item in a tree-view control. An application can display the image when dragging the item by using the image list functions.
DeleteAllItems
BOOL DeleteAllItems() const;
Deletes all items from a tree-view control.
DeleteItem
BOOL DeleteItem(HTREEITEM hItem) const;
Removes an item and all its children from a tree-view control.
EditLabel
HWND EditLabel(HTREEITEM hItem) const;
Begins in-place editing of the specified item's text, replacing the text of the item with a single-line edit control containing the text. This function implicitly selects and focuses the specified item.
EndEditLabelNow
BOOL EndEditLabelNow(BOOL fCancel) const;
Ends the editing of a tree-view item's label.
EnsureVisible
BOOL EnsureVisible(HTREEITEM hItem) const;
Ensures that a tree-view item is visible, expanding the parent item or scrolling the tree-view control, if necessary.
Expand
BOOL Expand(HTREEITEM hItem, UINT nCode) const;
The TreeView_Expand macro expands or collapses the list of child items associated with the specified parent item, if any.
HitTest
HTREEITEM HitTest(TVHITTESTINFO& ht) const;
Determines the location of the specified point relative to the client area of a tree-view control.
InsertItem
HTREEITEM InsertItem(TVINSERTSTRUCT& tvIS) const;
Inserts a new item in a tree-view control.
Select
BOOL Select(HTREEITEM hitem, UINT flag) const;
Selects the specified tree-view item, scrolls the item into view, or redraws the item in the style used to indicate the target of a drag-and-drop operation.
SelectDropTarget
BOOL SelectDropTarget(HTREEITEM hItem) const;
Redraws a specified tree-view control item in the style used to indicate the target of a drag-and-drop operation.
SelectItem
BOOL SelectItem(HTREEITEM hItem) const;
Selects the specified tree-view item.
SelectSetFirstVisible
BOOL SelectSetFirstVisible(HTREEITEM hItem) const;
Scrolls the tree-view control vertically to ensure that the specified item is visible. If possible, the specified item becomes the first visible item at the top of the control's window.
SortChildren
BOOL SortChildren(HTREEITEM hItem, BOOL fRecurse) const;
Sorts the child items of the specified parent item in a tree-view control.
SortChildrenCB
BOOL SortChildrenCB(TVSORTCB& sort, BOOL fRecurse) const;
Sorts tree-view items using an application-defined callback function that compares the items.

Overridables

PreRegisterClass
virtual void PreRegisterClass(WNDCLASS &wc);
Set the window class parameters before the window is created.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Like all common controls, the Tree-VIew control requires a parent window. This parent window is often a dialog, but simple windows can also be the parent window for a Tree-View control.

Refer to the explorer sample to see a demonstration of the CListView and CTreeView classes.

Summary Information

Header file | treeview.h
Win32/64 support | Yes
WinCE support | Yes
Library required | Comctl32.lib


CWceFrame

CWceFrame Class

Description

The WceFrame class provides a simple frame for the Windows CE operating system. It uses a command bar to provide the menu and toolbar buttons.

Use the PocketPCFrame sample as the starting point for your own frame based application for Windows CE.

CWceFrame Members

CWceFrame
CWceFrame();
Constructor for CWceFrame.
AddToolBarButton
virtual void AddToolBarButton(UINT nID);
Adds a button to the toolbar.
GetViewRect
CRect GetViewRect() const;
Returns a RECT structure which contains the dimensions of the client area of the frame.
GetMenuBar
CCmdBar& GetMenuBar() const;
Returns a reference to the frame's CCmdBar object, which manages the frame's command bar.
RecalcLayout
virtual void RecalcLayout();
Repositions the client area of the frame.
SetButtons
virtual void SetButtons(const std::vector<UINT> ToolBarData);
Sets the toolbar buttons of the command bar.

Overridables

OnActivate
virtual void OnActivate(WPARAM wParam, LPARAM lParam);
Called when the frame is activated.
OnCreate
virtual void OnCreate();
Called during window creation. Override this function to perform tasks such as creating child windows.
PreCreate
virtual void PreCreate(CREATESTRUCT &cs);
Called before the window is created. Override this function to set the window creation parameters.
PreTranslateMessage
virtual BOOL PreTranslateMessage(MSG* pMsg);
Override this function to filter mouse and keyboard messages prior to being passed to the message loop.
Base class Members

For base class members, refer to the members of CWnd.

Summary Information

Header file | wceframe.h
Win32/64 support | No
WinCE support | Yes


CWebBrowser

CWebBrowser Class

Description

This class provides a web browser in a window. It can be used to provide a web browser in any place a view window is used.

CWebBrowser Members

Construction
CWebBrowser
CWebBrowser();
Constructs a CWebBrowser object.
Attributes
GetApplication
LPDISPATCH GetApplication() const;
Retrieves the automation object for the application that is hosting the WebBrowser Control.
GetAXWindow
CAXWindow& GetAXWindow() const;
Returns a reference to the ActiveX container window.
GetBusy
BOOL GetBusy() const;
Retrieves a value that indicates whether the object is engaged in a navigation or downloading operation.
GetContainer
LPDISPATCH GetContainer() const;
Retrieves an object reference to a container.
GetFullScreen
BOOL GetFullScreen() const;
Retrieves a value that indicates whether Internet Explorer is in full-screen mode or normal window mode.
GetHeight
long GetHeight() const;
RRetrieves the height of the object.
GetIWebBrowser2
IWebBrowser2* GetIWebBrowser2();
Returns the pointer to the IWebBrowser interface.
GetLeft
long GetLeft() const;
Retrieves the coordinate of the left edge of the object.
GetLocateName
CString GetLocationName() const;
Retrieves the path or title of the resource that is currently displayed.
GetLocationURL
CString GetLocationURL() const;
Retrieves the URL of the resource that is currently displayed.
GetOffline
BOOL GetOffline() const;
Retrieves a value that indicates whether the object is operating in offline mode.
GetReadyState
READYSTATE GetReadyState() const;
Retrieves the ready state of the object.
GetRegisterAsBrowser
BOOL GetRegisterAsBrowser() const;
Retrieves a value that indicates whether the object is registered as a top-level browser window.
GetTheaterMode
BOOL GetTheaterMode() const;
Retrieves the theater mode state of the object.
GetTop
long GetTop() const;
Retrieves the coordinate of the top edge of the object.
GetTopLevelContainer
BOOL GetTopLevelContainer() const;
Retrieves a value that indicates whether the object is a top-level container.
GetType
CString GetType() const;
Retrieves the user type name of the contained document object.
GetVisible
BOOL GetVisible() const;
Retrieves a value that indicates whether the object is visible or hidden.
GetWidth
long GetWidth() const;
Retrieves the width of the object.
SetFullScreen
void SetFullScreen(BOOL bNewValue);
Sets a value that indicates whether Internet Explorer is in full-screen mode or normal window mode.
SetHeight
void SetHeight(long nNewValue);
Sets the height of the object.
SetLeft
void SetLeft(long nNewValue);
Sets the coordinate of the left edge of the object.e.
SetOffline
void SetOffline(BOOL bNewValue);
Sets a value that indicates whether the object is operating in offline mode.
SetRegisterAsBrowser
void SetRegisterAsBrowser(BOOL bNewValue);
Sets a value that indicates whether the object is registered as a top-level browser window.
SetTheaterMode
void SetTheaterMode(BOOL bNewValue);
Sets the theatre mode state of the object.
SetTop
void SetTop(long nNewValue);
Sets the coordinate of the top edge of the object.
SetVisible
void SetVisible(BOOL bNewValue);
Sets a value that indicates whether the object is visible or hidden.
SetWidth
void SetWidth(long nNewValue);
Sets the width of the object.
Operations
AddWebBrowserControl
void AddWebBrowserControl(void);
Adds the IWebBrowser interface to the ActiveX container window.
Exec
void ExecWB(OLECMDID cmdID, OLECMDEXECOPT cmdexecopt, VARIANT* pvaIn, VARIANT* pvaOut);
Executes a command using the IOleCommandTarget interface.
GetProperty
BOOL GetProperty(LPCTSTR pszProperty, CString& strValue);
VARIANT GetProperty( LPCTSTR pszProperty);
Gets the value associated with the specified property name.
GoBack
void GoBack();
Navigates backward one item in the history list.
GoForward
void GoForward();
Navigates forward one item in the history list.
GoHome
void GoHome();
Navigates to the current home or start page.
GoSearch
void GoSearch();
Navigates to the current search page.
Navigate
void Navigate(LPCTSTR pszURL, DWORD dwFlags = 0, LPCTSTR pszTargetFrameName = NULL,
     LPCTSTR pszHeaders = NULL, LPVOID pvPostData = NULL, DWORD dwPostDataLen = 0);
Navigates to a resource identified by a URL or to a file identified by a full path.
Navigate2
void Navigate2(LPITEMIDLIST pIDL, DWORD dwFlags = 0, LPCTSTR pszTargetFrameName = NULL);
void Navigate2(LPCTSTR pszURL, DWORD dwFlags = 0, LPCTSTR pszTargetFrameName = NULL,
     LPCTSTR pszHeaders = NULL, LPVOID lpvPostData = NULL, DWORD dwPostDataLen = 0);
Navigates the browser to a location specified by a pointer to an item identifier list (PIDL) for an entity in the Microsoft Windows Shell namespace, or a URL.
PutProperty
void PutProperty(LPCTSTR pszPropertyName, const VARIANT& vtValue);
void PutProperty(LPCTSTR pszPropertyName, double dValue);
void PutProperty(LPCTSTR pszPropertyName, long lValue);
void PutProperty(LPCTSTR pszPropertyName, LPCTSTR lpszValue);
void PutProperty(LPCTSTR pszPropertyName, short nValue);
Sets the value of a property associated with the object.
Refresh
void Refresh();
Reloads the file that is currently displayed in the object.
Refresh2
void Refresh2(int nLevel);
Reloads the file that is currently displayed with the specified refresh level.
Stop
void Stop();
Cancels a pending navigation or download, and stops dynamic page elements, such as background sounds and animations.
Overridables
OnCreate
virtual void OnCreate();
Called when the window is created.
OnSize
virtual void OnSize(int width, int height);
Called when the window is resized.
Base class Members

For base class members, refer to the members of CWnd.

Remarks

Refer to the Browser sample for a demonstration of how to use CWebBrowser to implement a simple web browser.

Summary Information

Header file | webbrowser.h
Win32/64 support | Yes
WinCE support | No
Library required |


CWinApp

CWinApp Class

Description

The class responsible for initializing Win32++, and also provides the message loop. You inherit from this class to start the application.

CWinApp Members

Construction

CWinApp
CWinApp();
Constructs a CWinApp object.

Attributes

GetAccelerators
HACCEL GetAccelerators() const;
Returns the handle to the accelerators used for the application
GetInstanceHandle
HINSTANCE GetInstanceHandle() const;
Returns the instance handle (HINSTANCE) of the application
GetResourceHandle
HINSTANCE GetResourceHandle() const;
Returns the instance handle of resources. This can the the HINSTANCE of the application or the HINSTANCE of a resource dll.
SetAccelerators
void SetAccelerators(HACCEL hAccel, CWnd* pWndAccel);
Sets the accelerator table for the application.
SetResourceHandle
void SetResourceHandle(HINSTANCE hResource);
Sets the instance handle of resources.

Operations

MessageLoop
virtual int MessageLoop();
Gets messages queued for the application, and dispatches them. Override this function to cater for specialised applications such as DirectX or OpenGL.
Run
virtual int Run();
Calls InitInstance and runs the message loop. Use this in WinMain to run the application.

Overridables

InitInstance
virtual BOOL InitInstance();
This function is called when the application starts. Override this to perform tasks such as creating a window.
OnIdle
virtual BOOL OnIdle(LONG lCount);
This function is called to perform idle processing. This function is called while the message queue is empty, and is called repeatedly until the function returns FALSE. Override this function to perform idle processing.
PreTranslateMessage
virtual BOOL PreTranslateMessage(MSG Msg);
This functions is called by the MessageLoop. It processes the keyboard accelerator keys and calls CWnd::PreTranslateMessage for keyboard and mouse events..

Remarks

Starting a Win32++ application

CWinApp (or a class inherited from CWinApp) must be used to run a Win32++ application. Here we see a simple example of a class inherited from CWinApp.

////////////////////////////////////////////////////////
// The class inherited from CWinApp which starts Win32++
class CSimpleApp : public CWinApp
{
public:
  CSimpleApp() {}
  virtual ~CSimpleApp() {}
  virtual BOOL InitInstance();

private:
  CView m_View;
};

BOOL CSimpleApp::InitInstance()
{
  // This function is called by Run

  m_View.Create(); // Create the Window
  return TRUE;
}

Notice that InitInstance is used to specify what happens when we use the Run function. In this case it is used to create the CView window.

Running a Win32++ application

Once we have our CWinApp derived class, we use it in WinMain start our application. The following code demonstrates a typical use of the class inherited from CWinApp.

//////////////////////////////////////////////
// The entry point for our windows application
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
  // Start Win32++
  CSimpleApp MyApp;

  // Run the application until the window is destroyed
  return MyApp.Run();
}

Note that this simple program has two key steps

  • Constructs MyApp, which is a CSimpleApp object. CSimpleApp is inherited from WinApp.
  • Uses the Run function to call MyApp's InitInstance, and run the message loop.

Separating the construction and the running of CWinApp like this allows the CWinApp derived class (including all member objects) to be fully constructed, before attempting to do things which could generate exceptions, such as creating windows.

A complete simple application

Sometimes it is easier to fit the pieces together when we see a complete application rather than a collection of code snippets. The following code sample is a complete simple windows application. It creates an ordinary window, and ends the application when the window is destroyed.

#include "../Win32++/Wincore.h"

/////////////////////////////////////////////
// A class inherited from CWnd for the window
class CView : public CWnd
{
public:
  CView() {}
  virtual ~CView() {}
  virtual LRESULT WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
};

LRESULT CView::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  // Handle the messages for this window
  switch (uMsg)
  {
  case WM_DESTROY:
    //End the program when window is destroyed
    ::PostQuitMessage(0);
    break;
  }

  //Use the default message handling for remaining messages
  return WndProcDefault(hWnd, uMsg, wParam, lParam);
}

////////////////////////////////////////////////////////
// The class inherited from CWinApp which starts Win32++
class CSimpleApp : public CWinApp
{
public:
  CSimpleApp() {}
  virtual ~CSimpleApp() {}
  virtual BOOL InitInstance();

private:
  CView m_View;
};

BOOL CSimpleApp::InitInstance()
{
  // This function is called by Run

  m_View.Create(); // Create the Window
  return TRUE;
}

//////////////////////////////////////////////
// The entry point for our windows application
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
  // Start Win32++
  CSimpleApp MyApp;

  // Run the application until the window is destroyed
  return MyApp.Run();
}

Summary Information

Header file | wincore.h
Win32/64 support | Yes
WinCE support | Yes


CWindowDC

CWindowDC Class

Description

The class responsible for creating a device context for the entire area of a window, including the non-client area.

CWindowDC Members

Initialization and Assignment

Initialization and Assignment
CWindowDC
CWindowDC(const CWnd* pWnd);
Constructs a CWindowDC object.
Base class Members

For base class members, refer to the members of CDC.

Remarks

Refer to the Graphics Device Interface section of Using Win32++ for additional information on using this class.

Summary Information

Header file | gdi.h
Win32/64 support | Yes
WinCE support | Yes


CWinException

CWinException Class

Description

A class which handles exceptions. Exceptions should only be used to handle errors which might arise from exceptional circumstances. In Win32++, exceptions are typically used to handle the unexpected failure of Windows API functions, like, for example, CreateWindowEx.

It is not normal for a program to routinely throw exceptions. A thrown exception often indicates a programming error, but they could also be thrown when a system is so starved of resources that the operating system cannot successfully allocate the resources needed to complete the task.

CWinException Members

CWinException
CWinException (LPCTSTR msg);
Constructor for CWinException
GetError
DWORD GetError() const throw ();
Retrieves the last error code value.
GetErrorString
LPCTSTR GetErrorString() const;
Retrieves the error string from GetLastError.
what
const char * what () const throw ();
Sends the exception message and error string to the debug window.

Remarks

Exceptions should be caught by constant reference to avoid the creation of a temporary copy of the CWinException object. Since an exception could be thrown when the operating system is already starved of resources, consuming additional resources to create this copy to catch the exception would by very undesirable.

void SomeFunction()
{
  try
  {
    if(IsValid())
    {
      // Do the normal stuff
      .
      .
      .
    }
    else
      throw CWinException(_T("Not Valid"));

  }

  catch (const CWinException &e)
  {
    // Send the exception information to the debug window
    e.what();
  }

}

The what function reports the text message associated with the exception and sends this information to the IDE's debug window. It also reports the text associated with the GetLastError function.

Summary Information

Header file | wincore.h
Win32/64 support | Yes
WinCE support | Yes


CWnd

CWnd Class

Description

The CWnd class represents a window. CWnd handles such things as window creation and window destruction, as well as determining how the window messages are handled. Each window created by Win32++ is a CWnd object, or an object derived from CWnd. Many of the classes in Win32++ are inherited from CWnd, including CFrame, CMDIChild, CMDIFrame, CMenuBar, CReBar, CStatusBar, and CToolBar.

Inherit from this class in your own application to create windows. The WndProc member function is called whenever the window associated with the CWnd object receives a Window message. Override WndProc to handle window messages, and pass all unhandled messages on to WndProcDefault.

CWnd Members:

Construction

CWnd
CWnd();
Constructs a CWnd object

Operations

operator HWND
operator HWND() const;
Converts a CWnd to a window handle (HWND).
Attach
virtual BOOL Attach(HWND hWnd);
Attaches a CWnd object to an existing window.
AttachDlgItem
virtual BOOL AttachDlgItem(UINT nID, CWnd* pParent);
Attaches a CWnd object to a dialog item.
CenterWindow
virtual void CenterWindow() const;
Positions the window over the center of its parent.
Create
virtual HWND Create(CWnd* pParent = NULL);
Creates the window with default parameters. Use PreCreate to set the default parameters.
CreateEx
virtual HWND CreateEx(DWORD dwExStyle, LPCTSTR lpszClassName,
                      LPCTSTR lpszWindowName, DWORD dwStyle,
                      int x, int y, int nWidth, int nHeight,
                      CWnd* pParent, CMenu pMenu, LPVOID lpParam = NULL);
virtual HWND CreateEx(DWORD dwExStyle, LPCTSTR lpszClassName,
                 LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rc,
                 CWnd* pParent, CMenu pMenu, LPVOID lpParam = NULL);
Creates the window by specifying each parameter.
Destroy
virtual void Destroy();
Destroys the window associated with the CWnd, and returns the CWnd to its default state.
Detach
virtual HWND Detach();
Detaches a window from a CWnd object. It reverses an attach.
Invalidate
virtual void Invalidate(BOOL bErase = TRUE) const;
Invalidates the entire window. The window will be redrawn when the next WM_PAINT message is processed.
SetIconLarge
virtual HICON SetIconLarge(int nIcon);
Loads the large icon from the specified resource, and assigns it to the window.
SetIconSmall
virtual HICON SetIconSmall(int nIcon);
Loads the small icon from the specified resource, and assigns it to to the window.
WndProcDefault
virtual LRESULT WndProcDefault(UINT uMsg, WPARAM wParam, LPARAM lParam);
Don't override this function. Pass all unhandled messages to WndProcDefault when overriding WndProc.

Overridables

OnCommand
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
Called when the user selects a command, typically in response to a menu or toolbar button.
OnCreate
virtual void OnCreate();
Called during window creation. Override this function to perform tasks such as creating child windows.
OnDraw
virtual void OnDraw(CDC* pDC);
Called when part of the window is about to be redrawn. Override this function to specify how the window should be drawn.
OnEraseBkGnd
virtual BOOL OnEraseBkgnd(CDC* pDC);
Called when part of the window background is erased. Override this function to specify how the window's background should be drawn.
OnInitialUpdate
virtual void OnInitialUpdate();
Called after the window is created. Override this function to perform tasks once the window is created.
OnMenuUpdate
virtual void OnMenuUpdate(UINT nID);
Called when a popup menu is about to be displayed. Override this function to set or clear the check box or radio button to menu items.
OnMessageReflect
virtual LRESULT OnMessageReflect(UINT uMsg, WPARAM wParam, LPARAM lParam);
Called when a notification message is sent to the parent. Override this function to handle these notification messages in the CWnd that generated them.
OnNotify
virtual LRESULT OnNotify(WPARAM wParam, LPARAM lParam);
Called when a WM_NOTIFY message is received from a child window. Override this function to handle notifications in the parent's CWnd.
OnNotifyReflect
virtual LRESULT OnNotifyReflect(WPARAM wParam, LPARAM lParam);
Called when a WM_NOTIFY message is sent to the parent. Override this function to handle notifications in the CWnd that generated them.
PreCreate
virtual void PreCreate(CREATESTRUCT& cs);
Override this function to set the window creation parameters used by Create.
PreRegisterClass
virtual void PreRegisterClass(WNDCLASS& wc);
Override the function to set the window class parameters used by Create.
PreTranslateMessage
virtual BOOL PreTranslateMessage(MSG* pMsg);
Override this function to filter mouse and keyboard messages prior to being passed to the message loop.
WndProc
virtual LRESULT WndProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
Override this function to specify how the messages for this window are to be handled. Return all unhandled messages to WndProcDefault.

Attributes

FromHandle
static CWnd* FromHandle(HWND hWnd);
Returns a pointer to the CWnd object, given the window handle (HWND).
GetHwnd
HWND GetHwnd() const;
Returns the handle of the window associated with CWnd.
GetPrevWindowProc
WNDPROC GetPrevWindowProc() const;
Pointer to the Window Procedure prior to it being subclassed.

Member Variables

m_hWnd
HWND m_hWnd;
Handle to the CWnd's window.

Wrappers for Window API functions and messages (don't override these).

BeginPaint
CDC* BeginPaint(PAINTSTRUCT& ps) const;
Prepares the specified window for painting and fills a PAINTSTRUCT structure with information about the painting.
BringWindowToTop
BOOL BringWindowToTop() const;
Brings the window to the top of the Z order. If the window is a top-level window, it is activated. If the window is a child window, the top-level parent window associated with the child window is activated.
CallWindowProc
LRESULT CallWindowProc(WNDPROC lpPrevWndFunc, UINT Msg,
                       WPARAM wParam, LPARAM lParam) const;
Passes message information to the specified window procedure.
CheckDlgButton
BOOL CheckDlgButton(int nIDButton, UINT uCheck) const;
Changes the check state of a button control.
CheckRadioButton
BOOL CheckRadioButton(int nIDFirstButton, int nIDLastButton,
                      int nIDCheckButton) const;
Sdds a check mark to (checks) a specified radio button in a group and removes a check mark from (clears) all other radio buttons in the group.
ChildWindowFromPoint
CWnd* ChildWindowFromPoint(POINT pt) const;
Determines which, if any, of the child windows belonging to a parent window contains the specified point. The search is restricted to immediate child windows. Grandchildren, and deeper descendant windows are not searched.
ClientToScreen
BOOL ClientToScreen(POINT& pt) const;
BOOL ClientToScreen(RECT& rc) const;
Converts the client-area coordinates of a specified point to screen coordinates..
CloseWindow
BOOL CloseWindow() const;
Minimizes (but does not destroy) the window. This function is not supported on WinCE.
DefWindowProc
LRESULT DefWindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam) const;
Calls the default window procedure to provide default processing for any window messages that an application does not process.
DeferWindowPos
HDWP DeferWindowPos(HDWP hWinPosInfo, HWND hWndInsertAfter,
                    int x, int y, int cx, int cy, UINT uFlags) const;
HDWP DeferWindowPos(HDWP hWinPosInfo, HWND hWndInsertAfter,
               const RECT& rc, UINT uFlags) const;
Updates the multiple-window – position structure for the window.
DlgDirList
int DlgDirList(LPTSTR lpPathSpec, int nIDListBox,
               int nIDStaticPath, UINT uFileType) const;
Replaces the contents of a list box with the names of the subdirectories and files in a specified directory. You can filter the list of names by specifying a set of file attributes. This function is not supported on WinCE.
DlgDirListComboBox
int DlgDirListComboBox(LPTSTR lpPathSpec, int nIDComboBox,
                       int nIDStaticPath, UINT uFiletype) const;
Replaces the contents of a combo box with the names of the subdirectories and files in a specified directory. You can filter the list of names by specifying a set of file attributes. This function is not supported on WinCE.
DlgDirSelectEx
BOOL DlgDirSelectEx(LPTSTR lpString, int nCount, int nIDListBox) const;
Retrieves the current selection from a single-selection list box. It assumes that the list box has been filled by the DlgDirList function and that the selection is a drive letter, filename, or directory name. This function is not supported on WinCE.
DlgDirSelectComboBoxEx
BOOL DlgDirSelectComboBoxEx(LPTSTR lpString, int nCount,
                            int nIDComboBox) const;
Retrieves the current selection from a combo box filled by using the DlgDirListComboBox function. The selection is interpreted as a drive letter, a file, or a directory name. This function is not supported on WinCE.
DrawAnimatedRects
BOOL DrawAnimatedRects(int idAni, RECT& rcFrom, RECT& rcTo) const;
Draws a wire-frame rectangle and animates it to indicate the opening of an icon or the minimizing or maximizing of a window. This function is not supported on WinCE.
DrawCaption
BOOL DrawCaption(CDC* pDC, RECT& rc, UINT uFlags) const;
Draws a window caption. This function is not supported on WinCE.
DrawMenuBar
BOOL DrawMenuBar() const;
Redraws the menu bar of the window. If the menu bar changes after the system has created the window, this function must be called to draw the changed menu bar.
EnableScrollBar
BOOL EnableScrollBar(UINT uSBflags, UINT uArrows) const;
Enables or disables one or both scroll bar arrows. This function is not supported on WinCE.
EnableWindow
BOOL EnableWindow(BOOL bEnable = TRUE) const;
The EnableWindow function enables or disables mouse and keyboard input to the specified window or control. When input is disabled, the window does not receive input such as mouse clicks and key presses. When input is enabled, the window receives all input.
EndPaint
BOOL EndPaint(PAINTSTRUCT& ps) const;
Marks the end of painting in the specified window. This function is required for each call to the BeginPaint function, but only after painting is complete.
GetActiveWindow
CWnd* GetActiveWindow() const;
Returns the pointer to the active window. This pointer might be temporary, so don't save it for later use.
GetAncestor
CWnd* GetAncestor(UINT gaFlag = 3 /*= GA_ROOTOWNER*/) const;
Returns the pointer to the ancestor window. This pointer might be temporary, so don't save it for later use.
GetCapture
CWnd* GetCapture() const;
Returns the pointer to the window (if any) that has captured the mouse. This pointer might be temporary, so don't save it for later use.
GetClassLongPtr
ULONG_PTR GetClassLongPtr(int nIndex) const;
Retrieves the specified value from the WNDCLASSEX structure associated with the window.
GetClassName
LPCTSTR GetClassName() const;
Returns a pointer to a TCHAR array containing the class name of the window.
GetClientRect
CRect GetClientRect() const;
Retrieves the coordinates of a window's client area. The client coordinates specify the upper-left and lower-right corners of the client area. Because client coordinates are relative to the upper-left corner of a window's client area, the coordinates of the upper-left corner are (0,0).
GetDC
CDC* GetDC() const;
Retrieves a pointer to the display device context (CDC) for the client area of the window.
GetDCEx
CDC* GetDCEx(HRGN hrgnClip, DWORD flags) const;
Retrieves a pointer to a display device context (CDC) for the client area of the window. This function is an extension to the GedDC function, which gives an application more control over how and whether clipping occurs in the client area.
GetDesktopWindow
CWnd* GetDesktopWindow() const;
Retrieves a pointer to the desktop window. This pointer might be temporary, so don't save it for later use.
GetDlgItem
CWnd* GetDlgItem(int nIDDlgItem) const;
Retrieves a pointer to a control in the dialog box. This pointer might be temporary, so don't save it for later use.
GetDlgItemInt
UINT GetDlgItemInt(int nIDDlgItem, BOOL* lpTranslated, BOOL bSigned) const;
Translates the text of a specified control in a dialog box into an integer value.
GetDlgItemText
LPCTSTR GetDlgItemText(int nIDDlgItem) const;
Retrieves the title or text associated with a control in a dialog.
GetFont
CFont* GetFont() const;
Retrieves a handle to the font assigned to the window.
GetIcon
HICON GetIcon(BOOL bBigIcon) const;
Retrieves a handle to the icon assigned to the window.
GetLastActivePopup
CWnd* GetLastActivePopup() const;
Retrieves the pointer to the pop-up window owned by the window which was most recently active. This pointer might be temporary, so don't save it for later use.
GetMenu
CMenu* GetMenu() const;
Retrieves a handle to the menu assigned to the window. This function is not supported on WinCE.
GetNextDlgGroupItem
CWnd* GetNextDlgGroupItem(CWnd* pCtl, BOOL bPrevious) const;
Retrieves a handle to the first control in a group of controls that precedes (or follows) the specified control in a dialog box.
GetNextDlgTabItem
CWnd* GetNextDlgTabItem(CWnd* pCtl, BOOL bPrevious) const;
Retrieves a handle to the first control that has the WS_TABSTOP style that precedes (or follows) the specified control.
GetParent
CWnd* GetParent() const;
Retrieves a pointer to the window's parent or owner (if any). This pointer might be temporary, so don't save it for later use.
GetScrollInfo
BOOL GetScrollInfo(int fnBar, SCROLLINFO& si) const;
Retrieves the parameters of a scroll bar, including the minimum and maximum scrolling positions, the page size, and the position of the scroll box (thumb).
GetScrollPos
int GetScrollPos(int nBar) const;
Retrieves the current position of the scroll box (thumb) in the specified scroll bar. The current position is a relative value that depends on the current scrolling range. For example, if the scrolling range is 0 through 100 and the scroll box is in the middle of the bar, the current position is 50. This function is not supported on WinCE. New applications should use the GetScrollInfo function.
GetScrollRange
BOOL GetScrollRange(int nBar, int& MinPos, int& MaxPos) const;
Retrieves the current minimum and maximum scroll box (thumb) positions for the specified scroll bar. This function is not supported on WinCE. New applications should use the GetScrollInfo function.
GetSystemMenu
CMenu* GetSystemMenu(BOOL bRevert) const;
Allows the application to access the window menu (also known as the system menu or the control menu) for copying and modifying. This function is not supported on WinCE.
GetTopWindow
CWnd* GetTopWindow() const;
Retrieves a pointer to the child window at the top of the Z order. This pointer might be temporary, so don't save it for later use.
GetUpdateRect
CRect GetUpdateRect(BOOL bErase) const;
Retrieves the coordinates of the smallest rectangle that completely encloses the update region of the specified window.
GetUpdateRgn
int GetUpdateRgn(CRgn* pRgn, BOOL bErase) const;
Retrieves the update region of a window by copying it into the specified region.
GetWindow
CWnd* GetWindow(UINT uCmd) const;
Retrieves a pointer to a window that has the specified relationship (Z-Order or owner) to the window. This pointer might be temporary, so don't save it for later use.
GetWindowDC
CDC* GetWindowDC() const;
Retrieves the device context (DC) for the entire window, including title bar, menus, and scroll bars. A window device context permits painting anywhere in a window, because the origin of the device context is the upper-left corner of the window instead of the client area.
GetWindowLongPtr
LONG_PTR GetWindowLongPtr(int nIndex) const;
Retrieves information about the window. The function also retrieves the value at a specified offset into the extra window memory.
GetWindowPlacement
BOOL GetWindowPlacement(WINDOWPLACEMENT& pWndpl) const;
Retrieves the show state and the restored, minimized, and maximized positions of the window. This function is not supported on WinCE.
GetWindowRect
CRect GetWindowRect() const;
Retrieves the dimensions of the bounding rectangle of the specified window. The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
GetWindowText
LPCTSTR GetWindowText() const;
Retrieves the title or text associated with the window.
GetWindowTextLength
int GetWindowTextLength() const;
Retrieves the length, in characters, of the specified window's text.
HiliteMenuItem
BOOL HiliteMenuItem(CMenu* pMenu, UINT uItemHilite, UINT uHilite) const;
Highlights or removes the highlighting from an item in a menu bar. This function is not supported on WinCE.
InvalidateRect
BOOL InvalidateRect(LPCRECT lpRect, BOOL bErase = TRUE) const;
The InvalidateRect function adds a rectangle to the window's update region. The update region represents the portion of the window's client area that must be redrawn.
InvalidateRgn
BOOL InvalidateRgn(CRgn* pRgn, BOOL bErase = TRUE) const;
The InvalidateRgn function invalidates the client area within the specified region by adding it to the current update region of a window. The invalidated region, along with all other areas in the update region, is marked for painting when the next WM_PAINT message occurs.
IsChild
BOOL IsChild(CWnd* pChild) const;
Tests whether a window is a child window or descendant window of a specified parent window. A child window is the direct descendant of a specified parent window if that parent window is in the chain of parent windows; the chain of parent windows leads from the original overlapped or pop-up window to the child window.
IsDialogMessage
BOOL IsDialogMessage(LPMSG lpMsg) const;
Determines whether a message is intended for the specified dialog box and, if it is, processes the message.
IsDlgButtonChecked
UINT IsDlgButtonChecked(int nIDButton) const;
Determines whether a button control has a check mark next to it or whether a three-state button control is grayed, checked, or neither.
IsIconic
BOOL IsIconic() const;
Determines whether the window is minimized (iconic). This function is not supported on WinCE.
IsWindow
BOOL IsWindow() const;
Determines whether the window handle identifies an existing window.
IsWindowEnabled
BOOL IsWindowEnabled() const;
Determines whether the window is enabled for mouse and keyboard input.
IsWindowVisible
BOOL IsWindowVisible() const;
Retrieves the visibility state of the window.
IsZoomed
BOOL IsZoomed() const;
Determines whether the window is maximized. This function is not supported on WinCE.
KillTimer
BOOL KillTimer(UINT_PTR uIDEvent) const;
Destroys the specified timer.
LockWindowUpdate
BOOL LockWindowUpdate() const;
Disables or enables drawing in the window. Only one window can be locked at a time.This function is not supported on WinCE.
MapWindowPoints
void MapWindowPoints(CWnd* pWndTo, POINT& pt) const;
void MapWindowPoints(CWnd* pWndTo, RECT& rc) const;
void MapWindowPoints(CWnd* pWndTo, LPPOINT ptArray, UINT nCount) const;
Converts (maps) a set of points from a coordinate space relative to one window to a coordinate space relative to another window.
MessageBox
int MessageBox(LPCTSTR lpText, LPCTSTR lpCaption, UINT uType) const;
Creates, displays, and operates a message box. The message box contains an application-defined message and title, plus any combination of predefined icons and push buttons.
MoveWindow
BOOL MoveWindow(int x, int y, int nWidth, int nHeight,
                BOOL bRepaint = TRUE) const;
BOOL MoveWindow(const RECT& rc, BOOL bRepaint = TRUE) const;
The MoveWindow function changes the position and dimensions of the window.
OpenIcon
BOOL OpenIcon() const;
Restores a minimized (iconic) window to its previous size and position, and then activates the window.
PostMessage
BOOL PostMessage(UINT uMsg, WPARAM wParam = 0L, LPARAM lParam = 0L) const;
BOOL PostMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) const;
The PostMessage function places (posts) a message in the message queue associated with the thread that created the window and returns without waiting for the thread to process the message.
Print
void Print(CDC* pDC, DWORD dwFlags) const;
Requests that the window draw itself in the specified device context, most commonly in a printer device context. This function is not supported on WinCE.
RedrawWindow
BOOL RedrawWindow(LPCRECT lpRectUpdate = NULL, CRgn* pRgn = NULL,
                  UINT flags = RDW_INVALIDATE | RDW_UPDATENOW |
                  RDW_ERASE | RDW_ALLCHILDREN) const;
This function updates the specified rectangle or region in a window's client area.
ReleaseDC
int ReleaseDC(CDC* pDC) const;
Releases a device context (DC), freeing it for use by other applications.
ScreenToClient
BOOL ScreenToClient(POINT& Point) const;
BOOL ScreenToClient(RECT& rc) const;
Converts the screen coordinates of a specified RECT or points on the screen to client-area coordinates.
ScrollWindow
BOOL ScrollWindow(int XAmount, int YAmount, LPCRECT prcScroll,
                  LPCRECT prcClip) const;
Scrolls the contents of the specified window's client area. This function is not supported on WinCE. New applications should use the ScrollWindowEx function.
ScrollWindowEx
int ScrollWindowEx(int dx, int dy, LPCRECT prcScroll, LPCRECT prcClip,
                   CRgn* prgnUpdate, LPRECT prcUpdate, UINT flags) const;
Scrolls the contents of the specified window's client area. This function is not supported on WinCE.
SendDlgItemMessage
LRESULT SendDlgItemMessage(int nIDDlgItem, UINT Msg,
                           WPARAM wParam, LPARAM lParam) const;
Sends a message to the specified control in a dialog box.
SendMessage
LRESULT SendMessage(UINT uMsg, WPARAM wParam = 0L,
                    LPARAM lParam = 0L) const;
LRESULT SendMessage(HWND hWnd, UINT uMsg, WPARAM wParam,
               LPARAM lParam) const;
The SendMessage function sends the specified message to a window or windows. It calls the window procedure for the window and does not return until the window procedure has processed the message.
SendNotifyMessage
BOOL SendNotifyMessage(UINT Msg, WPARAM wParam, LPARAM lParam) const;
Sends the specified message to a window or windows. If the window was created by the calling thread, SendNotifyMessage calls the window procedure for the window and does not return until the window procedure has processed the message. If the window was created by a different thread, SendNotifyMessage passes the message to the window procedure and returns immediately; it does not wait for the window procedure to finish processing the message.
SetActiveWindow
CWnd* SetActiveWindow() const;
Activates a window. The window will be brought into the foreground (top of Z-Order) if its application is in the foreground when the system activates the window.
SetCapture
CWnd* SetCapture() const;
Sets the mouse capture to the window belonging to the current thread. SetCapture captures mouse input either when the mouse is over the capturing window, or when the mouse button was pressed while the mouse was over the capturing window and the button is still down. Only one window at a time can capture the mouse.
SetClassLongPtr
ULONG_PTR SetClassLongPtr(int nIndex, LONG_PTR dwNewLong) const;
Replaces the specified value at the specified offset in the extra class memory or the WNDCLASSEX structure for the class to which the window belongs.
SetDlgItemInt
BOOL SetDlgItemInt(int nIDDlgItem, UINT uValue, BOOL bSigned) const;
Sets the text of a control in a dialog box to the string representation of a specified integer value.
SetDlgItemText
BOOL SetDlgItemText(int nIDDlgItem, LPCTSTR lpString) const;
Sets the title or text of a control in a dialog box.
SetFocus
CWnd* SetFocus() const;
Sets the keyboard focus to the window.
SetFont
void SetFont(CFont pFont, BOOL bRedraw) const;;
Specifies the font that a window will use when drawing text.
SetForegroundWindow
BOOL SetForegroundWindow() const;
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 system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.
SetIcon
HICON SetIcon(HICON hIcon, BOOL bBigIcon) const;
Associates a new large or small icon with the window..
SetMenu
BOOL SetMenu(CMenu* pMenu) const;
Assigns a new menu to the window. This function is not supported on WinCE.
SetParent
CWnd* SetParent(CWnd* pWndParent) const;
Changes the parent window of the specified child window.
SetRedraw
BOOL SetRedraw(BOOL bRedraw = TRUE) const;
This function allows changes in the window to be redrawn or prevents changes in the window from being redrawn, by sending a WM_SETREDRAW message.
SetScrollInfo
int SetScrollInfo(int fnBar, const SCROLLINFO& si, BOOL fRedraw) const;
Sets the parameters of a scroll bar, including the minimum and maximum scrolling positions, the page size, and the position of the scroll box (thumb). The function also redraws the scroll bar, if requested.
SetScrollPos
int SetScrollPos(int nBar, int nPos, BOOL bRedraw) const;
Sets the position of the scroll box (thumb) in the specified scroll bar and, if requested, redraws the scroll bar to reflect the new position of the scroll box. New applications should use the SetScrollInfo function. This function is not supported on WinCE.
SetScrollRange
BOOL SetScrollRange(int nBar, int nMinPos, int nMaxPos,
                    BOOL bRedraw) const;
Sets the minimum and maximum scroll box positions for the specified scroll bar. New applications should use the SetScrollInfo function. This function is not supported on WinCE.
SetTimer
UINT_PTR SetTimer(UINT_PTR nIDEvent, UINT uElapse,
                  TIMERPROC lpTimerFunc) const;
Creates a timer with the specified time-out value.
SetWindowLongPtr
LONG_PTR SetWindowLongPtr(int nIndex, LONG_PTR dwNewLong) const;
Changes an attribute of the window. The function also sets a value at the specified offset in the extra window memory.
SetWindowPlacement
BOOL SetWindowPlacement(const WINDOWPLACEMENT& wndpl) const;
Sets the show state and the restored, minimized, and maximized positions of the window. This function is not supported on WinCE.
SetWindowPos
BOOL SetWindowPos(const CWnd* pInsertAfter, int x, int y,
                  int cx, int cy, UINT uFlags) const;
BOOL SetWindowPos(const CWnd* pInsertAfter, const RECT& rc,
             UINT uFlags) const;
Changes the size, position, and Z order of a child, pop-up, or top-level window. Child, pop-up, and top-level windows are ordered according to their appearance on the screen. The topmost window receives the highest rank and is the first window in the Z order.
The pInsertAfter can one of: &wndTop, &wndTopMost, &wndBottom, or &wndNoTopMost.
SetWindowRgn
int SetWindowRgn(CRgn* pRgn, BOOL bRedraw = TRUE) const;
Sets the window region of a window. The window region determines the area within the window where the system permits drawing. The system does not display any portion of a window that lies outside of the window region. The system owns the region after a successful call to SetWindowRgn.
SetWindowText
BOOL SetWindowText(LPCTSTR lpString) const;
Changes the text of the window's title bar (if it has one). If the window is a control, the text of the control is changed.
SetWindowTheme
HRESULT SetWindowTheme(LPCWSTR pszSubAppName, LPCWSTR pszSubIdList) const;
Causes a window to use a different set of visual style information (XP Theme) than its class normally uses.
ShowOwnedPopups
BOOL ShowOwnedPopups(BOOL fShow) const;
Shows or hides the all the pop-up windows owned by this window.
ShowScrollBar
BOOL ShowScrollBar(int nBar, BOOL bShow) const;
Shows or hides the specified scroll bar. This function is not supported on WinCE.
ShowWindow
BOOL ShowWindow(int nCmdShow = SW_SHOWNORMAL) const;
Sets the window's show state.
ShowWindowAsync
BOOL ShowWindowAsync(int nCmdShow) const;
The ShowWindow function sets the window's show state created in a different thread.
UpdateWindow
BOOL UpdateWindow() const;
Updates the client area of the window by sending a WM_PAINT message to the window if the window's update region is not empty. If the update region is empty, no message is sent.
ValidateRect
BOOL ValidateRect(LPCRECT prc) const;
Validates the client area within a rectangle by removing the rectangle from the update region of the window.
ValidateRgn
BOOL ValidateRgn(CRgn* pRgn) const;
Validates the client area within a region by removing the region from the current update region of the window.
WindowFromDC
CWnd* WindowFromDC(CDC* pDC) const;
Retrieves a pointer to the window associated with the specified device context. This pointer might be temporary, so don't save it for later use.
WindowFromPoint
static CWnd* WindowFromPoint(POINT pt);
Retrieves the window that contains the specified point (in screen coordinates).

Remarks

Refer to the Simple Window section for information on how to use this class to create a window and handle its messages.

Summary Information

Header file | wincore.h
Win32/64 support | Yes
WinCE support | Yes


Shared_Ptr

Shared_Ptr Class

Description

A Shared_Ptr is a smart pointer that can be used in a STL container, such as vector. It mimics the behaviour of "share_ptr" which will be included in the next standard of C++.

Shared_Ptr Members

Shared_Ptr | Constructor for the Shared_Ptr.
get | Returns the stored pointer.
swap | Exchanges the contents of two smart pointers.
unique | Returns true if the use_count equals 1.
use_count | Returns the number of Shared_Ptr objects.
operator = | Assigns a pointer to the Shared_Ptr.
operator -> | Returns the stored pointer.
operator * | Returns the dereferenced stored pointer.
operator == | Compares the dereferenced stored pointers. Returns true if lhs == rhs.
operator != | Compares the dereferenced stored pointers. Returns true if lhs != rhs.
operator < | Compares the dereferenced stored pointers. Returns true if lhs < rhs.
operator > | Compares the dereferenced stored pointers. Returns true if lhs > rhs.

Remarks

Shared_Ptr wraps a reference-counted smart pointer around a dynamically allocated object. Unlike auto_ptr, the Shared_Ptr can be used as a smart pointer for objects stored in containers like std::vector. Do not use Shared_Ptr (or shared_ptr or auto_ptr) for dynamically allocated arrays. See below for advice on how to wrap dynamically allocated arrays in a vector.

The next standard of C++ will also contain a shared_ptr. Some modern compilers already have a shared_ptr available as std::tr1::shared_ptr. If your compiler already provides a shared_ptr, or if you have Boost, you should use that smart pointer instead. This class has been provided for those users who don't have easy access to an "official" shared_ptr. Note that this class is "Shared_Ptr", a slightly different name to the future "shared_ptr" to avoid naming conflicts.

Advantages of Shared_Ptr (or shared_ptr where available):

  • Shared_Ptr can be safely copied. This makes them suitable for containers.
  • Shared_Ptr automatically calls delete for the wrapped pointer when its last copy goes out of scope.
  • Shared_Ptr simplifies execution safety.

Without smart pointers, it can be quite challenging to ensure that every dynamically allocated pointer (i.e. use of new) is deleted in the event of all possible exceptions. In addition to the exceptions we throw ourselves, "new" itself will throw an exception it it fails, as does the STL (Standard Template Library which includes vector and string). Without smart pointers we often need to resort to additional try/catch blocks simply to avoid memory leaks when exception occur.

Examples of declaring a Shared_Ptr:

Shared_Ptr<CWnd> w1(new CWnd);

Shared_Ptr<CWnd> w1 = new CWnd;
typedef Shared_Ptr<CWnd> CWndPtr;
CWndPtr w1 = new CWnd;
typedef Shared_Ptr<CWnd> CWndPtr;
CWndPtr w1(new CWnd);

Examples using a Shared_Ptr in a vector:

typedef Shared_Ptr<CWnd> CWndPtr;
std::vector<CWndPtr> MyVector;
MyVector.push_back(new CWnd);
typedef Shared_Ptr<CWnd> CWndPtr;
CWnd* pWnd = new CWnd;
std::vector<CWndPtr> MyVector;
MyVector.push_back(pWnd);

Summary Information

Header file | shared_ptr.h
Win32/64 support | Yes
WinCE support | Yes


Scribble Tutorial

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

This set of tutorials will demonstrate how to create a scribble application, capable of drawing on a window using a mouse. It starts with a simple window and ends with a frame based scribble application which supports the loading and saving saving its data to a file, and printing the contents of the window. The code for these tutorials can be found in the tutorials directory.

The application produced by completing the tutorial looks like this.

Choose from the set of links in the Menu of Tutorials to start.


1: The Simplest Window

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 1: The Simplest Window

The following code uses Win32++ to create a window. This is all the code you need (in combination with Win32++) to create and display a simple window. Note that in order to add the Win32++ code to our program, we use an #include statement as shown below.

#include "../Win32++/Wincore.h"

INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
    //Start Win32++
    CWinApp MyApp;

    //Create a CWnd object
    CWnd MyWindow;

    //Create (and display) the window
    MyWindow.Create();

    //Run the application
    return MyApp.Run();
}

This program has four key steps:

  • Start Win32++.  We do this here by creating a CWinApp
  object called MyApp.

  • Create a CWnd object called MyWindow.

  • Create a default window by calling the Create function.

  • Start the message loop, by calling the Run function.

The source code for this tutorial is located within the Tutorial folder of
the software available from SourceForge at

http://sourceforge.net/projects/win32-framework.

If you compile and run this program, you'll find that the application doesn't
end when the window is closed.  This is behaviour is normal.  An
illustration of how to use messages to control the windows behaviour (including
closing the application) will be left until tutorial 3.


2: Using Classes and Inheritance

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 2: Using Classes and Inheritance

The program in the previous tutorial calls the CWinApp and CWnd classes directly. Normally, however, we would inherit from these classes to have more control over the type of CWnd and CWinApp objects we create.

This is an example of how we would derive a class from CWinApp.

class CSimpleApp : public CWinApp
{
public:
    CSimpleApp() {}
    virtual ~CSimpleApp() {}
    virtual BOOL InitInstance();

private:
    CView m_View;
};

BOOL CSimpleApp::InitInstance
{
    //Create the Window
    m_View.Create();

    return TRUE;
}

Notice that we override InitInstance to determine what happens when the application is started. In this instance we create the window for the m_View member variable. The m_View member variable is a CView object inherited from CWnd. The code for CView is shown below

// The directory of the include directory should also be added to project's
//  additional include directories.

#include "wincore.h"

class CView : public CWnd
{
public:
    CView() {}
    virtual ~CView() {}
};

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.

Once again, if you compile and run this program you'll find that it will continue to run after the window is closed. We will demonstrate how to handle the message to close the application in the next section.


3: Using Messages

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 3: Using Messages to create a Scribble Application

Each external event that a window might need to respond to is send to the window by way of a message. Its now time to control the way our window behaves by handling some of these messages. Each CWnd object handles its own messages in the WndProc function. In this example we will create a simple scribble program by handling the left mouse button messages. We will also handle the message to end the application when the window is closed.

The WM_LBUTTONDOWN message is sent to the window when the left button is clicked, and the cursor is over the window's client area. We capture the mouse input and store the current mouse position in the m_OldPt member variable.

The WM_MOUSEMOVE message is posted to a window when the cursor moves. If the mouse is not captured, the message is posted to the window that contains the cursor. Otherwise, the message is posted to the window that has captured the mouse. We check that the left button is also down, and call DrawLine to draw the line in the view window.

The WM_LBUTTTONUP message is sent to the window when the left mouse button changed from down to up during mouse capture.

The WM_DESTROY message is sent when a window is being destroyed.

A window receives messages through its window procedure. We intercept these messages and take our own actions by overriding the WndProc function.

LRESULT CView::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg)
  {
  case WM_LBUTTONDOWN:
    OnLButtonDown(lParam);
    break;

  case WM_MOUSEMOVE:
    OnMouseMove(wParam, lParam);
    break;

  case WM_LBUTTONUP:
    OnLButtonUp(lParam);
    break;

  case WM_DESTROY:
    //End the program when window is destroyed
    ::PostQuitMessage(0);
    break;
  }

  //Use the default message handling for remaining messages
  return WndProcDefault(hWnd, uMsg, wParam, lParam);
}

Here are the definitions of the functions used in WndProc. SetCapture captures mouse input either when the mouse is over the capturing window, or when the mouse button was pressed while the mouse was over the capturing window and the button is still down.

void CView::OnLButtonDown(LPARAM lParam)
{
  // Capture mouse input.
  SetCapture();

  m_OldPt.x = GET_X_LPARAM(lParam);
  m_OldPt.y = GET_Y_LPARAM(lParam);
}

void CView::OnLButtonUp(LPARAM lParam)
{
  {
    //Release the capture on the mouse
    ReleaseCapture();
  }
}

void CView::OnMouseMove(WPARAM wParam, LPARAM lParam)
{
  // hold down the left mouse button and move mouse to draw lines.
  if (wParam & MK_LBUTTON)
  {
    DrawLine(LOWORD(lParam), HIWORD(lParam));
    m_OldPt.x = GET_X_LPARAM(lParam);
    m_OldPt.y = GET_Y_LPARAM(lParam);
  }
}

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.

This time the application ends when the window is closed. We detected when the window was closed by handling the WM_DESTROY message, and used this opportunity to end the application with the PostQuitMessage function.


4: Repainting the Window

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 4: Repainting the Window

The previous example fails to repaint the window. Repainting the window is required whenever the window is resized, or when part of the window is revealed after being covered by another window.

The Windows API handles repainting automatically. When part of a window needs repainting, windows sends a WM_PAINT message to the application. Typically you would respond to this message with the code to redraw the entire client area of the window. You don't need to concern yourself with which parts of the client area need to be redrawn, as windows handles this part for you automatically.

Win32++ already contains the code to handle the WM_PAINT message in CWnd::WndProc. All you need to do is write the OnDraw function. For our application here, we can store the various points in a vector, and have the OnDraw function draw the lines again. The function to store the points looks like this.

void CView::StorePoint(int x, int y, bool PenDown)
{
  PlotPoint P1;
  P1.x = x;
  P1.y = y;
  P1.PenDown = PenDown;

  m_points.push_back(P1); //Add the point to the vector
}

Our OnDraw function looks like this.

void CView::OnDraw(CDC* pDC)
{
  if (m_points.size() > 0)
  {
    bool bDraw = false;  //Start with the pen up

    for (unsigned int i = 0 ; i < m_points.size(); i++)
    {
      if (bDraw)
        pDC->LineTo(m_points[i].x, m_points[i].y);
      else
        pDC->MoveTo(m_points[i].x, m_points[i].y);

      bDraw = m_points[i].PenDown;
    }
  }
}

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.


5: Adding a Frame

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 5: Wrapping a Frame around our Scribble Application

This is the code to produce a simple frame application. We inherit a class called CMainframe from the CFrame class in Win32++. Notice how we use the SetView function to specify the "view" window of our frame. This "view" window happens to be the same code as the simple scribble application shown in the previous tutorial. Hence we have wrapped a frame around our previous scribble application.

The CMainFrame class inherits OnCommand from CFrame. This function responds to input from the frame's menu and toolbar. We haven't implemented many of these inputs yet, so at this stage most of them simply display a simple message box.

CMainFrame::CMainFrame()
{
  //Set m_View as the view window of the frame
  SetView(m_View);
}

BOOL CMainFrame::OnCommand(WPARAM wParam, LPARAM lParam)
{
  // Process the messages from the Menu and Tool Bar
  switch (LOWORD(wParam))
  {
  case IDM_FILE_EXIT:
    // End the application
    ::PostMessage(m_hWnd, WM_CLOSE, 0, 0);
    return TRUE;
  case IDM_HELP_ABOUT:
    // Display the help dialog
    OnHelp();
    return TRUE;
  case IDM_FILE_NEW:
    ::MessageBox(NULL, _T("File New  ... Implemented later"), _T("Menu"), MB_OK);
    return TRUE;
  case IDM_FILE_OPEN:
    ::MessageBox(NULL, _T("File Open  ... Implemented later"), _T("Menu"), MB_OK);
    return TRUE;
  case IDM_FILE_SAVE:
    ::MessageBox(NULL, _T("File Save  ... Implemented later"), _T("Menu"), MB_OK);
    return TRUE;
  case IDM_FILE_SAVEAS:
    ::MessageBox(NULL, _T("File SaveAs  ... Implemented later"), _T("Menu"), MB_OK);
    return TRUE;
  case IDM_FILE_PRINT:
    ::MessageBox(NULL, _T("File Print  ... Implemented later"), _T("Menu"), MB_OK);
    return TRUE;
  }

  return FALSE;
}

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.


6: Customising Window Creation

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 6: Customising Window Creation

Up until now we have used the default parameters supplied by Win32++ to create the view window. Here we use the PreRegisterClass to specify the Window Class (not to be confused with a C++ class) parameters prior to window creation. This will allow us to create a window with a coloured background and set it's cursor. We also use PreCreate to give the window a 3D look by giving it's border a sunken edge.

void CView::PreCreate(CREATESTRUCT &cs)
{
  // Set the extra style to provide a sunken edge
  cs.dwExStyle = WS_EX_CLIENTEDGE;
}
void CView::PreRegisterClass(WNDCLASS &wc)
{
  // Set the background brush and cursor
  wc.hbrBackground = m_Brush;
  wc.lpszClassName = "Scribble Window";
  wc.hCursor = ::LoadCursor(GetApp()->GetInstanceHandle(), MAKEINTRESOURCE(IDC_CURSOR1));
}

Notice that we used GetApp()->GetInstanceHandle() in the LoadCursor function to get the instance handle (or HINSTANCE) of our application. The GetApp function returns a pointer to our CScribbleApp object, and GetInstanceHandle returns the instance handle of our application.

We create the background brush in CView's constructor. The brush is a CBrush object which automatically deletes its brush when its destructor is called. This is how the brush is created.

// Constructor
CView::CView() : m_PenColor(RGB(0,0,0))
{
     m_Brush.CreateSolidBrush(RGB(255,255,230));
}

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.


7: Customising the ToolBar

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 7: Customising the ToolBar

Our frame window has both a menu and a toolbar at the top. Customising the menu is relatively straight forward, since we can use a resource editor to perform that task. Customising the toolbar however is another matter. While its true that the resource editor which ships Microsoft's Visual Studio can edit the toolbar resource, this is not standard, and we so need to come up with a standards compliant way of modifying the toolbar.

To set your own toolbar for your applications, you will need to perform the following steps:

  • Modify the toolbar bitmap.
  • Add the toolbar resource IDs to to the string table.
  • Assign resource IDs to the toolbar buttons, as shown below.
void CMainFrame::SetupToolBar()
{
  // Define the resource IDs for the toolbar
  AddToolBarButton( IDM_FILE_NEW   );
  AddToolBarButton( IDM_FILE_OPEN  );
  AddToolBarButton( IDM_FILE_SAVE  );
  AddToolBarButton( 0 );				// Separator
  AddToolBarButton( IDM_EDIT_CUT,   FALSE );
  AddToolBarButton( IDM_EDIT_COPY,  FALSE );
  AddToolBarButton( IDM_EDIT_PASTE, FALSE );
  AddToolBarButton( 0 );				// Separator
  AddToolBarButton( IDM_FILE_PRINT );
  AddToolBarButton( 0 );				// Separator
  AddToolBarButton( IDM_HELP_ABOUT );
}

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.


8: Loading and Saving Files

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 8: Loading and Saving Files

In this tutorial we will demonstrate how to save our data to a file, and load it back again.

Saving Data

To save the data we perform the following steps:

  • Use CFile::SaveFileDialog to open a dialog and choose the filename to save the data to.
  • Use CFile::Open to open the file for writing.
  • Use CFile::Write to write the data to the file.

This code segment shows how to use the SaveFileDialog function to choose the file to write to.

void CMainFrame::OnFileSaveAs()
{
  CFile File;
  CString str = File.SaveFileDialog(0, OFN_OVERWRITEPROMPT, _T("Scribble Files (*.dat)\0*.dat\0\0"), _T("dat"), this);

  // Store the PlotPoint data in the file
  if (!str.IsEmpty())
  {
    m_PathName = str;

    // Save the file name
    m_View.FileSave(str);
    AddMRUEntry(str);
  }
}
This next code segment demonstrates how to open a file for writing, and write data to it. The data written in this case is the contents of the m_points vector. Error checking has been omitted from the code segment displayed here for clarity, but is included in the code for this tutorial.
BOOL CView::FileSave(LPCTSTR szFilename)
{
  BOOL bResult = TRUE;
  CFile hFile;
  hFile.Open(szFilename, CREATE_ALWAYS))

  // Write the file
  for (size_t i = 0; i < m_points.size(); ++i)
  {
    hFile.Write(&m_points[i], sizeof(PlotPoint));
  }

  return bResult;
}

Loading Data

Reading data back from a file follows a rather similar process. The steps involved are as follows:

  • Use CFile::OpenFileDialog to open a dialog and choose the file to load.
  • Use CFile::Open to open the file for reading.
  • Use CFile::Read to retrieve the data from the file.

The following code segment demonstrates how to use OpenFileDialog to choose the file to load.

void CMainFrame::OnFileOpen()
{
  CFile File;
  CString str = File.OpenFileDialog(0, OFN_FILEMUSTEXIST, _T("Scribble Files (*.dat)\0*.dat\0\0"), this);

  if (!str.IsEmpty())
  {
    // Retrieve the PlotPoint data
    if (m_View.FileOpen(str))
    {
      // Save the filename
      m_PathName = str;
      AddMRUEntry(str);
    }
    else
      m_PathName=_T("");
  }
}

This is the code which loads our PlotPoint vector from the contents of the chosen file. Once again, the error checking has been omitted from the code displayed here for clarity, but is present in the source code.

BOOL CView::FileOpen(LPCTSTR szFilename)
{
  // empty the PlotPoint vector
  m_points.clear();
  DWORD nBytesRead;
  BOOL bResult = FALSE;

  // Create a handle to the file
  CFile File;
  if (File.Open(szFilename, OPEN_EXISTING))
  {
    do
    {
      nBytesRead = 0;
      PlotPoint pp;

      nBytesRead = File.Read(&pp, sizeof(PlotPoint));
      if (nBytesRead == sizeof(PlotPoint))
        m_points.push_back(pp);

    } while (nBytesRead == sizeof(PlotPoint));

    bResult = TRUE;
  }

  Invalidate();
  return bResult;
}

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.


9: Printing

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 9: Printing

In this tutorial we will demonstrate how to send a bitmap to a printer. The bitmap in this case will be the one we've been drawing on in the view window. The resulting printout will be resized to match the size of the original drawing. This task can be broken down into several steps:

  • Extract the bitmap from the view window
  • Choose the printer
  • Start the print job
  • Extract the bitmap image data from the bitmap
  • Copy the resized image data to the printer's device context
  • End the print job

Extract the bitmap from the view window

When we draw on the view window, we are actually drawing on to a bitmap attached to view window's device context. Here we will copy this bitmap to a compatible bitmap.

// Copy the bitmap from the View window
CClientDC dcView(&m_View);
CMemDC MemDC(&dcView);
CBitmap bmView;
bmView.CreateCompatibleBitmap(&dcView, Width, Height);
MemDC.SelectObject(&bmView);
MemDC.BitBlt(0, 0, Width, Height, &dcView, 0, 0, SRCCOPY);

Choose a printer

This step is fairly straight forward. We declare a PRINTDLG struct and use this in the PrintDlg function. The PrintDlg function brings up a dialog, allowing us to choose the printer, and stores its device context in the PRINTDLG struct.

// Bring up a dialog to choose the printer
PRINTDLG pd = {0};
pd.lStructSize = sizeof(pd);
pd.Flags = PD_RETURNDC;
pd.hwndOwner = m_hWnd;

// Retrieve the printer DC
PrintDlg(&pd);

Start the Print Job

The StartDoc function should be called before sending output to a printer. This function ensures that multipage documents are not interspersed with other print jobs. StartPage (and a corresponding EndPage) is then called for each page of printout.

// Zero and then initialize the members of a DOCINFO structure.
DOCINFO di = {0};
di.cbSize = sizeof(DOCINFO);
di.lpszDocName = _T("Scribble Printout");
di.lpszOutput = (LPTSTR) NULL;
di.lpszDatatype = (LPTSTR) NULL;
di.fwType = 0;

// Begin a print job by calling the StartDoc function.
StartDoc(pd.hDC, &di);

// Inform the driver that the application is about to begin sending data.
StartPage(pd.hDC);

Extract the bitmap image data from the bitmap

In order to use StretchDIBits we first need the bitmap image data. This is retrieved by using the GetDIBits. It is called twice in the following code sample, the first time to get the size byte array to hold the data, and the second to fill the byte array.

// Get the dimensions of the View window
RECT rcView;
GetClientRect (m_View.GetHwnd(), &rcView);
int Width = rcView.right - rcView.left;
int Height = rcView.bottom - rcView.top;

// Fill the BITMAPINFOHEADER structure
BITMAPINFOHEADER bi = {0};
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biHeight = Height;
bi.biWidth = Width;
bi.biPlanes = 1;
bi.biBitCount =  24;
bi.biCompression = BI_RGB;

// Note: BITMAPINFO and BITMAPINFOHEADER are the same for 24 bit bitmaps
// Get the size of the image data
MemDC.GetDIBits(&bmView, 0, Height, NULL, (BITMAPINFO*)&bi, DIB_RGB_COLORS);

// Retrieve the image data
byte* pBits = new byte[bi.biSizeImage];
MemDC.GetDIBits(&bmView, 0, Height, pBits, (BITMAPINFO*)&bi, DIB_RGB_COLORS);

Copy the resized bitmap to the printer's device context

StretchDIBits is the function used here to copy the bitmap information to the printer's device context because the bitmap needs to be resized in order to retain the same dimensions on the printed page as the original. The following code segment shows how the scaling factors are calculated and the StretchDIBits function is called.

// Determine the scaling factors required retain the bitmap's original proportions.
float fLogPelsX1 = (float) GetDeviceCaps(ViewDC, LOGPIXELSX);
float fLogPelsY1 = (float) GetDeviceCaps(ViewDC, LOGPIXELSY);
float fLogPelsX2 = (float) GetDeviceCaps(pd.hDC, LOGPIXELSX);
float fLogPelsY2 = (float) GetDeviceCaps(pd.hDC, LOGPIXELSY);
float fScaleX = MAX(fLogPelsX1, fLogPelsX2) / min(fLogPelsX1, fLogPelsX2);
float fScaleY = MAX(fLogPelsY1, fLogPelsY2) / min(fLogPelsY1, fLogPelsY2);

// Compute the coordinates of the upper left corner of the centered bitmap.
int cWidthPels = GetDeviceCaps(pd.hDC, HORZRES);
int xLeft = ((cWidthPels / 2) - ((int) (((float) Width) * fScaleX)) / 2);
int cHeightPels = GetDeviceCaps(pd.hDC, VERTRES);
int yTop = ((cHeightPels / 2) - ((int) (((float) Height) * fScaleY)) / 2);

// Use StretchDIBits to scale the bitmap and maintain its original proportions
StretchDIBits(pd.hDC, xLeft, yTop, (int) ((float) Width * fScaleX),
               (int) ((float) Height * fScaleY), 0, 0, Width, Height, pBits,
               (BITMAPINFO*)&bi, DIB_RGB_COLORS, SRCCOPY);

End the print job

To finish the print job, EndPage is called to indicate that printing to this page is complete, then EndDoc is called the end the print job.

// Inform the driver that the page is finished.
EndPage(pd.hDC);

// Inform the driver that document has ended.
EndDoc(pd.hDC);

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.


10: Finishing Touches

Tutorials

Menu of tutorials

Tutorial 1: The Simplest Window
Tutorial 2: Using Classes and Inheritance
Tutorial 3: Using Messages to Create a Scribble Window
Tutorial 4: Repainting the Window
Tutorial 5: Wrapping a Frame around our Scribble Window
Tutorial 6: Customising Window Creation
Tutorial 7: Customising the ToolBar
Tutorial 8: Loading and Saving Files
Tutorial 9: Printing
Tutorial 10: Finishing Touches

Tutorial 10: Finishing Touches

In this final tutorial we will show how to store the application's settings in the registry, and implement tracing. The code for this final tutorial is the scribble demo application.

Saving the Window Position

Users will expect modern applications to save their settings, such as the position and size of the frame window. These settings are stored in the registry. LoadRegistrySettings is used to set the name of the registry key. Typically the name takes the form of "CompanyName\\ApplicationName" as demonstrated below.

CMainFrame::CMainFrame()
{
  .
  .
  .

  // Set the registry key name, and load the initial window position
  // Use a registry key name like "CompanyName\\Application"
  LoadRegistrySettings(_T("Win32++\\Scribble Sample"));
}

If a registry key name has been set using the LoadRegistrySetting function, the registry settings will be loaded from the registry when the application starts, and stored in the registry when the application ends. Override the LoadRegistrySettings and SaveRegistrySettings functions in CMainFrame if you wish to store other settings in the registry.

Saving the Most Recently Used (MRU) List

Applications which load and store files typically allow the user to choose from a list of recently used file names to load from. This MRU list is also stored in the registry. To add this capability to your Win32++ application, use the LoadRegistryMRUSettings function to specify the number of entries in the MRU list (up to a maximum of 16) as shown below.

CMainFrame::CMainFrame()
{
  .
  .
  .

  // Set the registry key name, and load the initial window position
  // Use a registry key name like "CompanyName\\Application"
  LoadRegistrySettings(_T("Win32++\\Scribble Sample"));

  // Load the settings from the registry with 4 MRU entries
  LoadRegistryMRUSettings(4);
}

Command Line Arguments

Command line arguments are passed to the program when it is started. The GetCommandLine function is used to retrieve the the command line string. The CommandLineToArgvW can parse this string and convert it to an array of LPWSTR pointers.

The following code demonstrates how to load a file when the filename is supplied as a command line argument.

void CMainFrame::OnInitialUpdate()
{
  int argCount = 0;
  LPWSTR* lpArgv = ::CommandLineToArgvW(::GetCommandLineW(), &argCount);

  // The second argument (if any) contains our file name.
  if (argCount >= 2)
  {
    m_View.FileOpen((W2T(lpArgv[1])));
  }
}

This allows the application to start and load the file when it is selected and opened from within Windows Explorer.

Debugging your Application with Tracing

One important debugging technique is to trace what is happening with the application while it is running. The tracing allows you to display messages or the contents of variables in the output pane of Visual Studio (or whichever Integrated Development Environment you use).

In order to take advantage of this, you will need do the following

  • Use Version 6.0 (or later) of Win32++
  • Run your application in debug mode (see below)
  • Use the TRACE function to display the messages.

To run the application in debug mode, you need to have the _DEBUG variable defined. Microsoft's Visual Studio products define this variable for you when you compile in debug mode. For other compilers you should use the appropriate compiler option to set this variable. The source code for this example, as well as the samples in the download section, include project files for debug modes for both DevC++ and CodeBlocks to make this task easier.

If you are not running in debug mode, TRACE statements have no effect. You can leave them in place for Release mode if you wish.

In the sample code for this section we add tracing to our scribble application to display the position of the mouse for the lines we draw.

This is the code added to CView::WndProc for tracing.

char str[80];
::wsprintf(str, "Draw Point: %hd, %hd\n", GET_X_LPARAM(lParam),
             GET_Y_LPARAM(lParam));
TRACE(str);

These are the lines of code added to CMainFrame::WndProc

TRACE("Red pen selected\n");
TRACE("Blue pen selected\n");
TRACE("Green pen selected\n");
TRACE("Black pen selected\n");

The source code for this tutorial is located within the Tutorial folder of the software available from SourceForge at http://sourceforge.net/projects/win32-framework.


Links

Some Useful Links

Free Compilers and Tools

Dev-C++ | Dev-C++ is a Integrated Development Environment (IDE) for C/C++. It includes the MinGW port of GCC as it's compiler.
Code::Blocks | Code::Blocks is an IDE for C/C++. It includes the MinGW port of GCC, and also supports the MS Visual Toolkit, and the free command line compiler from Borland.
Microsoft Visual C++ 2010 Express | A free C++ Win32 compiler and IDE from Microsoft.
Borland C++ Builder | A free C++ Win32 compiler from Borland. You will need to register before downloading.
DJGPP | A free C++ compiler for DOS.
ResEdit | A free Resource Editor for Win32 programs.
GDIView | A utility that displays list a of GDI handles used by each process. It's useful for spotting GDI leaks.

Tutorials and References

MSDN | The Microsoft Developers Network. Microsoft's online reference.
MS Platform SDK | Provides the documentation, samples, header files, libraries, and tools designed to help you develop Windows applications (XP and below).
MS Windows SDK | Provides the documentation, samples, header files, libraries, and tools designed to help you develop Windows applications (Vista and above).
MS DirectX SDK | Contains the additional header files and libraries for DirectX programming.
SourceForge | SourceForge hosts a large collection of open source projects.
Code Project | Forums and Code samples for software developers.
Cfanatic | A forum for C, Win32, C++, MFC, C# developers.
Reliable Software | A Win32 tutorial for advanced C++ users.
the Forger | A Win32 tutorial for C++.
FunctionX | A Win32 programming reference, by FunctionX.
Dev-C++ Resource Site | API references, tutorials, online resources, documentation downloads, etc. about C/C++ and Win32 programming.
Thinking in C++ | Thinking in C++ 2nd Edition. An excellent book on C++ by Bruce Eckel. Available Online.
Google | Internet Search Engine.
Wikipedia | Web based encyclopedia.
C++ FAQ | C++ Frequently Asked Questions


Contact

Contacting the Author

Anyone with a question or comment relating to Win32++ are encouraged to post these in one of the forums here at SourceForge. You will find forums for support requests, feature requests, bug reports and general comments. I monitor the forums regularly, and am normally able to post a reply the next day.

If you would prefer to send me a direct email, you can contact me on dnash@bigpond.net.au