MFC Tutorial
MFC Tutorial
Audience
This tutorial is designed for all those developers who are keen on developing best-in-class
applications using MFC. The tutorial provides a hands-on approach with step-by-step
program examples, source codes, and illustrations that will assist the developers to learn
and put the acquired knowledge into practice.
Prerequisites
To gain advantage of this tutorial you need to be familiar with programming for Windows.
You also need to know the basics of programming in C++ and understand the
fundamentals of object-oriented programming.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com.
                                                                                              i
                                                                                                               Microsoft Foundation Classes
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience........................................................................................................................................................... i
Prerequisites..................................................................................................................................................... i
Table of Contents............................................................................................................................................. ii
Prerequisites.................................................................................................................................................... 1
                                                                                                                                                                   ii
                                                                                                                 Microsoft Foundation Classes
Identifiers ...................................................................................................................................................... 59
Icons .............................................................................................................................................................. 60
Menus ........................................................................................................................................................... 63
Toolbars......................................................................................................................................................... 68
Accelerators................................................................................................................................................... 75
                                                                                                                                                                    iii
                                                                                                               Microsoft Foundation Classes
                                                                                                                                                                   v
                                                                                                               Microsoft Foundation Classes
                                                                                                                                                                 vi
                                                                                                                 Microsoft Foundation Classes
Arcs.............................................................................................................................................................. 396
Fonts............................................................................................................................................................ 401
                                                                                                                                                                  vii
                         1. MFC - Overview
The Microsoft Foundation Class (MFC) library provides a set of functions, constants, data
types, and classes to simplify creating applications for the Microsoft Windows operating
systems. In this tutorial, you will learn all about how to start and create windows based
applications using MFC.
Prerequisites
We have assumed that you know the following:
What is MFC?
The Microsoft Foundation Class Library (MFC) is an "application framework" for
programming in Microsoft Windows. MFC provides much of the code, which are required
for the following:
      Managing Windows.
      Menus and dialog boxes.
      Performing basic input/output.
      Storing collections of data objects, etc.
You can easily extend or override the basic functionality the MFC framework in you C++
applications by adding your application-specific code into MFC framework.
MFC Framework
      The MFC framework provides a set of reusable classes designed to simplify
       Windows programming.
      MFC provides classes for many basic objects, such as strings, files, and collections
       that are used in everyday programming.
      It also provides classes for common Windows APIs and data structures, such as
       windows, controls, and device contexts.
      The framework also provides a solid foundation for more advanced features, such
       as ActiveX and document view processing.
                                                                                         1
                                                           Microsoft Foundation Classes
Why MFC?
The MFC framework is a powerful approach that lets you build upon the work of expert
programmers for Windows. MFC framework has the following advantages.
      MFC simplifies database programming through Data Access Objects (DAO) and
       Open Database Connectivity (ODBC), and network programming through
       Windows Sockets.
                                                                                     2
               2. MFC - Environment Setup                   Microsoft Foundation Classes
Microsoft Visual C++ is a programming environment used to create applications for the
Microsoft Windows operating systems. To use MFC framework in your C++ application,
you must have installed either Microsoft Visual C++ or Microsoft Visual Studio. Microsoft
Visual Studio also contains the Microsoft Visual C++ environment.
Microsoft provides a free version of visual studio which also contains SQL Server and it
can be downloaded from https://www.visualstudio.com/en-us/downloads/download-
visual-studio-vs.aspx.
Step 1: Once Visual Studio is downloaded, run the installer. The following dialog box will
be displayed.
                                                                                        3
Microsoft Foundation Classes
                          4
                                                              Microsoft Foundation Classes
Step 3: Once Visual Studio is installed successfully, you will see the following dialog box.
Step 4: Close this dialog box and restart your computer if required.
                                                                                          5
                                                            Microsoft Foundation Classes
Step 5: Open Visual studio from the Start menu, which will open the following dialog box.
It will take some time for preparation, while starting for the first time.
                                                                                       6
                                                           Microsoft Foundation Classes
Step 6: Next, you will see the main window of Visual Studio.
                                                                                     7
                    3. MFC - VC++ Projects                     Microsoft Foundation Classes
In this chapter, we will be covering the different types of VC++ projects. Visual Studio
includes several kinds of Visual C++ project templates. These templates help to create
the basic program structure, menus, toolbars, icons, references, and include statements
that are appropriate for the kind of project you want to create. Following are some of the
salient features of the templates.
      It provides wizards for many of these project templates and helps you customize
       your projects as you create them.
 Once the project is created, you can build and run the application.
      You don't have to use a template to create a project, but in most cases it's more
       efficient to use project templates.
      It's easier to modify the provided project files and structure than it is to create
       them from scratch.
Following are some General templates which can also be used to create MFC application:
                                                                                             8
                   4. MFC - Getting Started                 Microsoft Foundation Classes
In this chapter, we will look at a working MFC example. To create an MFC application, you
can use wizards to customize your projects. You can also create an application from
scratch.
Step 1: Open the Visual studio and click on the File -> New -> Project menu option.
Step 2: You can now see that the New Project dialog box is open.
Step 3: From the left pane, select Templates -> Visual C++ -> MFC
Step 4: In the middle pane, select MFC Application.
Step 5: Enter the project name ‘MFCDemo’ in the Name field and click OK to continue.
You will see the following dialog.
                                                                                       9
                      Microsoft Foundation Classes
                                               10
                                                           Microsoft Foundation Classes
Step 7: Select the options which are shown in the dialog box given above and click Next.
                                                                                     11
                                                       Microsoft Foundation Classes
                                                                                12
                                                             Microsoft Foundation Classes
You can now see that the MFC wizard creates this Dialog Box and the project files by
default.
Step 9: Run this application, you will see the following output.
                                                                                       13
                                                           Microsoft Foundation Classes
Step 1: Open the Visual studio and click on the File - > New - > Project menu option.
Step 2: You can now see the New Project dialog box.
                                                                                        14
                                                          Microsoft Foundation Classes
Step 3: From the left pane, select Templates -> Visual C++ -> General.
Step 5: Enter project name ‘MFCDemoFromScratch’ in the Name field and click OK to
continue. You will see that an empty project is created.
                                                                                   15
                                                             Microsoft Foundation Classes
Step 6: To make it an MFC project, right-click on the project and select Properties.
                                                                                       16
                                                              Microsoft Foundation Classes
Step 8: Select the Use MFC in Shared DLL option in Project Defaults section and click OK.
Step 9: As it is an empty project now; we need to add a C++ file. So, right-click on the
project and select Add -> New Item…
Step 10: Select C++ File (.cpp) in the middle pane and enter file name in the Name field
and click Add button.
                                                                                       17
                                                            Microsoft Foundation Classes
Step 11: You can now see the main.cpp file added under the Source Files folder.
Step 12: Let us add the following code in this file.
 #include <iostream>
 using namespace std;
 void main()
 {
       cout << "***************************************\n";
       cout << "MFC Application Tutorial";
       cout << "\n***************************************";
       getchar();
 }
Step 13: When you run this application, you will see the following output on console.
 ***************************************
 MFC Application Tutorial
 ***************************************
                                                                                        18
     5.         MFC - Windows Fundamentals                 Microsoft Foundation Classes
Step 1: Open the Visual studio and click on the File -> New -> Project menu option.
Step 2: You can now see the New Project dialog box.
Step 3: From the left pane, select Templates -> Visual C++ -> Win32.
Step 5: Enter the project name ‘MFCWindowDemo’ in the Name field and click OK to
continue. You will see the following dialog box.
                                                                                      19
                      Microsoft Foundation Classes
                                               20
                                                            Microsoft Foundation Classes
Step 7: Select the options as shown in the dialog box given above and click Finish.
                                                                                      21
                                                             Microsoft Foundation Classes
Step 9: To make it an MFC project, right-click on the project and select Properties.
                                                                                       22
                                                             Microsoft Foundation Classes
Step 10: In the left section, click Configuration Properties -> General.
Step 11: Select the Use MFC in Shared DLL option in Project Defaults section and click
OK.
Step 13: Right-click on your Project and select Add -> New Item...
                                                                                      23
                                                                   Microsoft Foundation Classes
Window Creation
Any application has two main sections:
        Class
        Frame or Window
Step 1: To create an application, we need to derive a class from the MFC's CWinApp.
                                                                                            24
                                                            Microsoft Foundation Classes
Step 3: For this, we need to add another class and derive it from the MFC's CFrameWnd
class and implement its constructor and a call the Create() method, which will create a
frame/window as shown in the following code.
Step 4: As you can see that Create() method needs two parameters, the name of the
class, which should be passed as NULL, and the name of the window, which is the string
that will be shown on the title bar.
Main Window
After creating a window, to let the application use it, you can use a pointer to show the
class used to create the window. In this case, the pointer would be CFrameWnd. To use
the frame window, assign its pointer to the CWinThread::m_pMainWnd member variable.
This is done in the InitInstance() implementation of your application.
              Frame->ShowWindow(SW_NORMAL);
              Frame->UpdateWindow();
              return TRUE;
       }
 };
                                                                                      25
                                                           Microsoft Foundation Classes
#include <afxwin.h>
             Frame->ShowWindow(SW_NORMAL);
             Frame->UpdateWindow();
             return TRUE;
      }
 };
CExample theApp;
                                                                                    26
                                                              Microsoft Foundation Classes
Step 3: When we run the above application, the following window is created.
Windows Styles
Windows styles are characteristics that control features such as window appearance,
borders, minimized or maximized state, or other resizing states, etc. Following is a list of
styles which you can use while creating a Window.
         Style                                      Description
 WS_BORDER                Creates a window that has a border.
                          Creates a window that has a title bar (implies the WS_BORDER
 WS_CAPTION
                          style). Cannot be used with the WS_DLGFRAME style.
                          Creates a child window. Cannot be used with the WS_POPUP
 WS_CHILD
                          style.
 WS_CHILDWINDO
                          Same as the WS_CHILD style.
 W
                          Excludes the area occupied by child windows when you draw
 WS_CLIPCHILDREN          within the parent window. Used when you create the parent
                          window.
                          Clips child windows relative to each other; that is, when a
                          particular child window receives a paint message, the
                          WS_CLIPSIBLINGS style clips all other overlapped child
                          windows out of the region of the child window to be updated.
 WS_CLIPSIBLINGS
                          (If WS_CLIPSIBLINGS is not given and child windows overlap,
                          when you draw within the client area of a child window, it is
                          possible to draw within the client area of a neighboring child
                          window.) For use with the WS_CHILD style only.
 WS_DISABLED              Creates a window that is initially disabled.
 WS_DLGFRAME              Creates a window with a double border but no title.
                          Specifies the first control of a group of controls in which the
 WS_GROUP                 user can move from one control to the next with the arrow
                          keys. All controls defined with the WS_GROUP style FALSE after
                                                                                         27
                                                             Microsoft Foundation Classes
                          the first control belong to the same group. The next control
                          with the WS_GROUP style starts the next group (that is, one
                          group ends where the next begins).
 WS_HSCROLL               Creates a window that has a horizontal scroll bar.
                          Creates a window that is initially minimized. Same as the
 WS_ICONIC
                          WS_MINIMIZE style.
 WS_MAXIMIZE              Creates a window of maximum size.
 WS_MAXIMIZEBOX           Creates a window that has a Maximize button.
                          Creates a window that is initially minimized. For use with the
 WS_MINIMIZE
                          WS_OVERLAPPED style only.
 WS_MINIMIZEBOX           Creates a window that has a Minimize button.
                          Creates an overlapped window. An overlapped window usually
 WS_OVERLAPPED
                          has a caption and a border.
                          Creates an overlapped window with the WS_OVERLAPPED,
 WS_OVERLAPPED
                          WS_CAPTION,           WS_SYSMENU,           WS_THICKFRAME,
 WINDOW
                          WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles.
                          Creates a pop-up window. Cannot be used with the WS_CHILD
 WS_POPUP
                          style.
                          Creates a pop-up window with the WS_BORDER, WS_POPUP,
                          and WS_SYSMENU styles. The WS_CAPTION style must be
 WS_POPUPWINDO
                          combined with the WS_POPUPWINDOW style to make the
 W
                          Control menu visible.
                          Creates a window that has a sizing border. Same as the
 WS_SIZEBOX
                          WS_THICKFRAME style.
                          Creates a window that has a Control-menu box in its title bar.
 WS_SYSMENU
                          Used only for windows with title bars.
                          Specifies one of any number of controls through which the user
 WS_TABSTOP               can move by using the TAB key. The TAB key moves the user
                          to the next control specified by the WS_TABSTOP style.
                          Creates a window with a thick frame that can be used to size
 WS_THICKFRAME
                          the window.
                          Creates an overlapped window. An overlapped window has a
 WS_TILED
                          title bar and a border. Same as the WS_OVERLAPPED style.
                          Creates an overlapped window with the WS_OVERLAPPED,
                          WS_CAPTION,           WS_SYSMENU,           WS_THICKFRAME,
 WS_TILEDWINDOW           WS_MINIMIZEBOX, and WS_MAXIMIZEBOX styles. Same as
                          the WS_OVERLAPPEDWINDOW style.
 WS_VISIBLE               Creates a window that is initially visible.
 WS_VSCROLL               Creates a window that has a vertical scroll bar.
Step 1: Let us look into a simple example in which we will add some styling. After creating
a window, to display it to the user, we can apply the WS_VISIBLE style to it and
additionally, we will also add WS_OVERLAPPED style. Here is an implementation:
                                                                                        28
                                                               Microsoft Foundation Classes
Step 2: When you run this application, the following window is created.
You can now see that the minimize, maximize, and close options do not appear anymore.
Windows Location
To locate things displayed on the monitor, the computer uses a coordinate system similar
to the Cartesian's, but the origin is located on the top left corner of the screen. Using this
coordinate system, any point can be located by its distance from the top left corner of the
screen of the horizontal and the vertical axes.
      The ‘x’ member variable is the distance from the left border of the screen to the
       point.
                                                                                           29
                                                               Microsoft Foundation Classes
        The ‘y’ variable represents the distance from the top border of the screen to the
         point.
        Besides the Win32's POINT structure, the Microsoft Foundation Class (MFC)
         library provides the CPoint class.
        This provides the same functionality as the POINT structure. As a C++ class, it
         adds more functionality needed to locate a point. It provides two constructors.
    CPoint();
    CPoint(int X, int Y);
Windows Size
While a point is used to locate an object on the screen, each window has a size. The size
provides two measures related to an object.
Besides the Win32's SIZE structure, the MFC provides the CSize class. This class has the
same functionality as SIZE but adds features of a C++ class. It provides five constructors
that allow you to create a size variable in any way of your choice.
    CSize();
    CSize(int initCX, int initCY);
    CSize(SIZE initSize);
    CSize(POINT initPt);
    CSize(DWORD dwSize);
                                                                                           30
                                                             Microsoft Foundation Classes
Windows Dimensions
When a Window displays, it can be identified on the screen by its location with regards to
the borders of the monitor. A Window can also be identified by its width and height. These
characteristics are specified or controlled by the rect argument of the Create() method.
This argument is a rectangle that can be created through the Win32 RECT structure.
Besides the Win32's RECT structure, the MFC provides the CRect class which has the
following constructors:
 CRect();
 CRect(int l, int t, int r, int b);
 CRect(const RECT& srcRect);
 CRect(LPCRECT lpSrcRect);
 CRect(POINT point, SIZE size);
 CRect(POINT topLeft, POINT bottomRight);
Let us look into a simple example in which we will specify the location and the size of the
window
When you run this application, the following window is created on the top left corner of
your screen as specified in CRect constructor in the first two parameters. The last two
parameters are the size of the Window.
                                                                                        31
                                                              Microsoft Foundation Classes
Windows Parents
In the real world, many applications are made of different Windows. When an      application
uses various Windows, most of the objects depend on a particular one. It could   be the first
Window that was created or another window that you designated. Such a            Window is
referred to as the Parent Window. All the other windows depend on it             directly or
indirectly.
        If the Window you are creating is dependent of another, you can specify that it
         has a parent.
 If the Window does not have a parent, pass the argument with a NULL value.
Let us look into an example which has only one Window, and there is no parent Window
available, so we will pass the argument with NULL value as shown in the following code:
                                                                                           32
                                                         Microsoft Foundation Classes
When you run the above application, you see the same output.
                                                                                  33
                  6.        MFC - Dialog Boxes              Microsoft Foundation Classes
In this chapter, we will be covering the Dialog boxes. Applications for Windows frequently
communicate with the user through dialog boxes. CDialog class provides an interface for
managing dialog boxes. The Visual C++ dialog editor makes it easy to design dialog boxes
and create their dialog-template resources.
Step 1: Open the Visual studio and click on the File -> New -> Project menu option.
Step 2: You can now see the New Project dialog box.
Step 3: From the left pane, select Templates -> Visual C++ -> Win32.
Step 5: Enter project name ‘MFCDialogDemo’ in the Name field and click OK to continue.
You will see the following dialog.
                                                                                       34
                      Microsoft Foundation Classes
                                               35
                                                            Microsoft Foundation Classes
Step 7: Select the options shown in the dialog box given above and click Finish.
                                                                                     36
                                                             Microsoft Foundation Classes
Step 9: To make it a MFC project, right-click on the project and select Properties.
                                                                                      37
                                                             Microsoft Foundation Classes
Step 10: In the left section, click Configuration Properties -> General.
Step 11: Select the Use MFC in Shared DLL option in Project Defaults section and click
OK.
Step 13: Right-click on your Project and select Add -> New Item.
                                                                                      38
                                                           Microsoft Foundation Classes
Step 16: To create an application, we need to add a class and derive it from the MFC's
CWinApp.
#include <afxwin.h>
                                                                                     39
                                                               Microsoft Foundation Classes
Step 2: In the Add Resource dialog box, select Dialog and click New.
Step 4: A dialog box can first be manually created as a text file (in a resource file).
Step 5: You can now see the MFCDialogDemo.rc file created under Resource Files.
                                                                                          40
                                                              Microsoft Foundation Classes
Step 6: The resource file is open in designer. The same can be opened as a text file. Right-
click on the resource file and select Open With.
                                                                                         41
                                                             Microsoft Foundation Classes
Step 7: Select the Source Code (Text) editor and click Add button.
Step 8: Go back to the designer and right-click on the dialog and select Properties.
                                                                                       42
                                                               Microsoft Foundation Classes
Step 10: Like most other controls, a dialog box must be identified. The identifier (ID) of
a dialog box usually starts with IDD_, Let us change the ID to IDD_EXAMPLE_DLG.
Dialog Location
A dialog box must be “physically” located on an application. Because a dialog box is usually
created as a parent to other controls, its location depends on its relationship to its parent
window or to the desktop.
If you look and the Properties window, you see two fields, X Pos and Y Pos.
                                                                                          43
                                                              Microsoft Foundation Classes
      X is the distance from the left border of the monitor to the left border of the
       dialog box.
      Y is the distance from the top border of the monitor to the top border of the
       dialog box.
By default, these fields are set to zero. You can also change as shown above.
If you specify these two dimensions as 0, the left and top borders of the dialog box would
be set so the object appears in the center-middle of the screen.
                                                                                         44
                                                            Microsoft Foundation Classes
You can see the changes in width and height on the Status Bar.
 CDialog();
 CDialog(UINT nIDTemplate, CWnd* pParentWnd = NULL);
 CDialog(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL);
                                                                                       45
                                                         Microsoft Foundation Classes
Let us create another class CExampleDlg and derive it from CDialog. We will implement
its default constructor destructor as shown in the following code.
      CExampleDlg();
      ~CExampleDlg();
 };
 CExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD)
 {
 }
 CExampleDlg::~CExampleDlg()
 {
 }
 BOOL CExample::InitInstance()
 {
      CExampleDlg myDlg;
      m_pMainWnd = &myDlg;
      return TRUE;
 }
                                                                                  46
                                                                 Microsoft Foundation Classes
        To create a modeless dialog box, call your public constructor and then call the
         dialog object's Create member function to load the dialog resource.
        You can call Create either during or after the constructor call. If the dialog resource
         has the property WS_VISIBLE, the dialog box appears immediately.
Modal Dialog
        To create a modal dialog box, call either of the two public constructors declared in
         CDialog.
        Next, call the dialog object's DoModal member function to display the dialog box
         and manage interaction with it until the user chooses OK or Cancel.
        This management by DoModal is what makes the dialog box modal. For modal
         dialog boxes, DoModal loads the dialog resource.
Step 1: To display the dialog box as modal, in the CExample::InitInstance() event call the
DoModal() method using your dialog variable:
 BOOL CExample::InitInstance()
 {
         CExampleDlg myDlg;
         m_pMainWnd = &myDlg;
         myDlg.DoModal();
         return TRUE;
 }
 #include <afxwin.h>
 #include "resource.h"
                                                                                             47
                                                       Microsoft Foundation Classes
};
     CExampleDlg();
     ~CExampleDlg();
};
CExampleDlg::CExampleDlg():CDialog(CExampleDlg::IDD)
{
}
CExampleDlg::~CExampleDlg()
{
}
BOOL CExample::InitInstance()
{
     CExampleDlg myDlg;
     m_pMainWnd = &myDlg;
     myDlg.DoModal();
     return TRUE;
}
CExample MyApp;
                                                                                48
                                                              Microsoft Foundation Classes
Step 3: When the above code is compiled and executed, you will see the following dialog
box.
Dialog-Based Applications
Microsoft Visual Studio provides an easier way to create an application that is mainly based
on a dialog box. Here are the steps to create a dialog base project using project templates
available in Visual Studio:
Step 1: Open the Visual studio and click on the File -> New -> Project menu option. You
can see the New Project dialog box.
                                                                                         49
                                                         Microsoft Foundation Classes
Step 2: From the left pane, select Templates -> Visual C++ -> MFC.
Step 4: Enter project name ‘MFCModalDemo’ in the Name field and click OK to continue.
You will see the following dialog box.
                                                                                   50
                      Microsoft Foundation Classes
                                               51
                                                           Microsoft Foundation Classes
Step 7: Select the options shown in the above dialog box and click Next.
                                                                                    52
                                                          Microsoft Foundation Classes
Step 8: Check all the options that you choose to have on your dialog box like Maximize
and Minimize Boxes and click Next.
                                                                                   53
                      Microsoft Foundation Classes
                                               54
                                                           Microsoft Foundation Classes
Step 10: It will generate these two classes. You can change the name of the classes and
click Finish.
Step 11: You can now see that the MFC wizard creates this Dialog Box and the project
files by default.
                                                                                    55
                                                            Microsoft Foundation Classes
Step 12: When you run this application, you will see the following output.
                                                                                     56
Microsoft Foundation Classes
                         57
             7. MFC - Windows Resources                      Microsoft Foundation Classes
A resource is a text file that allows the compiler to manage objects such as pictures,
sounds, mouse cursors, dialog boxes, etc. Microsoft Visual Studio makes creating a
resource file particularly easy by providing the necessary tools in the same environment
used to program. This means, you usually do not have to use an external application to
create or configure a resource file. Following are some important features related to
resources.
      Most resources are created by selecting the desired one from the Add Resource
       dialog box.
                                                                                          58
                                                             Microsoft Foundation Classes
      The Add Resource dialog box provides an extensive list of resources which can be
       used as per requirements, but if you need something which is not available then
       you can add it manually to the *.rc file before executing the program.
Identifiers
An identifier is a symbol which is a constant integer whose name usually starts with ID.
It consists of two parts — a text string (symbol name) mapped to an integer value (symbol
value).
      When you create a new resource or resource object, the resource editors
       provide a default name for the resource, for example, IDC_DIALOG1, and assign
       a value to it.
Step 1: Let us look into our CMFCDialogDemo example from the last chapter in which
we have created a dialog box and its ID is IDD_EXAMPLE_DLG.
Step 2: Go to the Solution Explorer, you will see the resource.h file under Header Files.
Continue by opening this file in editor and you will see the dialog box identifier and its
integer value as well.
                                                                                        59
                                                            Microsoft Foundation Classes
Icons
An icon is a small picture used on a window which represents an application. It is used in
two main scenarios.
      On a Window's frame, it is displayed on the left side of the Window name on the
       title bar.
If you look at our MFCModalDemo example, you will see that Visual studio was using a
default icon for the title bar as shown in the following snapshot.
                                                                                       60
                                                            Microsoft Foundation Classes
You can create your own icon by following the steps given below:
Step 1: Right-click on your project and select Add -> Resources, you will see the Add
Resources dialog box.
Step 2: Select Icon and click New button and you will see the following icon.
                                                                                     61
                                                            Microsoft Foundation Classes
Step 3: In Solution Explorer, go to Resource View and expand MFCModalDemo > Icon.
You will see two icons. The IDR_MAINFRAME is the default one and IDI_ICON1 is the newly
created icon.
Step 5: IDI_ICON1 is the ID of this icon, now Let us change this ID to IDR_MYICON.
Step 6: You can now change this icon in the designer as per your requirements. We will
use the same icon.
                                                                                     62
                                                            Microsoft Foundation Classes
Step 9: You can now see that the default icon is loaded in the constructor. Let us change
it to IDR_ MYICON as shown in the following code.
Step 10: When the above code is compiled and executed, you will see the new icon is
displayed on the dialog box.
Menus
Menus allow you to arrange commands in a logical and easy-to-find fashion. With the
Menu editor, you can create and edit menus by working directly with a menu bar that
closely resembles the one in your finished application. To create a menu, follow the steps
given below:
Step 1: Right-click on your project and select Add -> Resources. You will see the Add
Resources dialog box.
                                                                                       63
                                                          Microsoft Foundation Classes
Step 2: Select Menu and click New. You will see the rectangle that contains "Type Here"
on the menu bar.
                                                                                    64
                                                            Microsoft Foundation Classes
Step 3: Write some menu options like File, Edit, etc. as shown in the following snapshot.
                                                                                      65
                                                           Microsoft Foundation Classes
Step 4: If you expand the Menu folder in Resource View, you will see the Menu identifier
IDR_MENU1. Right-click on this identifier and change it to IDM_MAINMENU.
                                                                                     66
                                                            Microsoft Foundation Classes
Step 6: We need to attach this menu to our dialog box. Expand your Dialog folder in
Solution Explorer and double click on the dialog box identifier.
Step 7: You will see the menu field in the Properties. Select the Menu identifier from the
dropdown as shown above.
Step 8: Run this application and you will see the following dialog box which also contains
menu options.
                                                                                       67
                                                             Microsoft Foundation Classes
Toolbars
A toolbar is a Windows control that allows the user to perform some actions on a form by
clicking a button instead of using a menu.
      A toolbar provides a convenient group of buttons that simplifies the user's job by
       bringing the most accessible actions as buttons.
      They can be equipped with buttons but sometimes their buttons or some of their
       buttons have a caption.
Step 1: Right-click on your project and select Add -> Resources. You will see the Add
Resources dialog box.
                                                                                       68
                                                            Microsoft Foundation Classes
Step 2: Select Toolbar and click New. You will see the following screen.
                                                                                     69
Microsoft Foundation Classes
                         70
                                                           Microsoft Foundation Classes
Step 3: Design your toolbar in the designer as shown in the following screenshot and
specify the IDs as well.
      CToolBar m_wndToolBar;
      BOOL          butD;
 // Dialog Data
                                                                                    71
                                                          Microsoft Foundation Classes
 #ifdef AFX_DESIGN_TIME
      enum { IDD = IDD_MFCMODALDEMO_DIALOG };
 #endif
      protected:
      virtual void DoDataExchange(CDataExchange* pDX);       // DDX/DDV support
 // Implementation
 protected:
      HICON m_hIcon;
      CToolBar m_wndToolBar;
      BOOL            butD;
 BOOL CMFCModalDemoDlg::OnInitDialog()
 {
      CDialogEx::OnInitDialog();
      // Set the icon for this dialog.     The framework does this automatically
      //     when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                   // Set big icon
      SetIcon(m_hIcon, FALSE);           // Set small icon
      if (!m_wndToolBar.Create(this)
               || !m_wndToolBar.LoadToolBar(IDR_TOOLBAR1))
               //if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD |
                                                                                   72
                                                          Microsoft Foundation Classes
              GetClientRect(rcClientOld);
              RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST,
0,
                    reposQuery, rcClientNew);
              CRect rcChild;
              CWnd* pwndChild = GetWindow(GW_CHILD);     //Handle to the Dialog
Controls
              while (pwndChild) // Cycle through all child controls
              {
                    pwndChild->GetWindowRect(rcChild); //    Get the child control
RECT
                    ScreenToClient(rcChild);
                    // Changes the Child Rect by the values of the claculated
offset
                                                                                     73
                                                             Microsoft Foundation Classes
                      rcChild.OffsetRect(ptOffset);
                      pwndChild->MoveWindow(rcChild, FALSE); // Move the Child
 Control
                      pwndChild = pwndChild->GetNextWindow();
              }
              CRect rcWindow;
              // Get the RECT of the Dialog
              GetWindowRect(rcWindow);
       return TRUE;   // return TRUE    unless you set the focus to a control
 }
Step 7: Run this application. You will see the following dialog box which also contains the
toolbar.
                                                                                        74
                                                            Microsoft Foundation Classes
Accelerators
An access key is a letter that allows the user to perform a menu action faster by using
the keyboard instead of the mouse. This is usually faster because the user would not need
to position the mouse anywhere, which reduces the time it takes to perform the action.
Step 1: To create an access key, type an ampersand "&" on the left of the menu item.
                                                                                       75
                                                             Microsoft Foundation Classes
Step 2: Repeat this step for all menu options. Run this application and press Alt. You will
see that the first letter of all menu options are underlined.
                                                                                        76
                                                            Microsoft Foundation Classes
Shortcut Key
A shortcut key is a key or a combination of keys used by advanced users to perform an
action that would otherwise be done on a menu item. Most shortcuts are a combination
of the Ctrl key simultaneously pressed with a letter key. For example, Ctrl + N, Ctrl + O,
or Ctrl + D.
To create a shortcut, on the right side of the string that makes up a menu caption, right-
click on the menu item and select properties.
In the Caption field type \t followed by the desired combination as shown below for the
New menu option. Repeat the step for all menu options.
                                                                                       77
                                                               Microsoft Foundation Classes
Accelerator Table
An Accelerator Table is a list of items where each item of the table combines an identifier,
a shortcut key, and a constant number that specifies the kind of accelerator key. Just like
the other resources, an accelerator table can be created manually in a .rc file. Following
are the steps to create an accelerator table.
Step 1: To create an accelerator table, right-click on *.rc file in the solution explorer.
                                                                                             78
                                            Microsoft Foundation Classes
                                                                     79
                                                         Microsoft Foundation Classes
Step 3: Click the arrow of the ID combo box and select menu Items.
                                                                                  80
                                                          Microsoft Foundation Classes
Step 5: Click the Key box and type the respective Keys for both menu options.
We will also add New menu item event handler to testing. Right-click on the New menu
option.
                                                                                   81
                                                           Microsoft Foundation Classes
Step 6: You can specify a class, message type and handler name. For now, let us leave it
as it is and click Add and Edit button.
                                                                                     82
                                                          Microsoft Foundation Classes
Step 8: You will now see the event added at the end of the CMFCModalDemoDlg.cpp file.
 void CMFCModalDemoDlg::OnFileNew()
 {
      // TODO: Add your command handler code here
      MessageBox(L"File > New menu option");
 }
Step 9: Now Let us add a message box that will display the simple menu option message.
To start accelerator table in working add the HACCEL variable and ProcessMessageFilter
as shown in the following CMFCModalDemoApp.
                                                                                   83
                                                            Microsoft Foundation Classes
 // Overrides
 public:
       virtual BOOL InitInstance();
       HACCEL m_hAccelTable;
// Implementation
       DECLARE_MESSAGE_MAP()
       virtual BOOL ProcessMessageFilter(int code, LPMSG lpMsg);
 };
 m_hAccelTable = LoadAccelerators(AfxGetInstanceHandle(),
 MAKEINTRESOURCE(IDR_ACCELERATOR1));
Step 12: When the above code is compiled and executed, you will see the following output.
                                                                                      84
                                                           Microsoft Foundation Classes
Step 13: Press Alt button followed by F key and then N key or Ctrl + N. You will see the
following message.
                                                                                     85
                  8. MFC - Property Sheets                  Microsoft Foundation Classes
A property sheet, also known as a tab dialog box, is a dialog box that contains property
pages. Each property page is based on a dialog template resource and contains controls.
It is enclosed on a page with a tab on top. The tab names the page and indicates its
purpose. Users click a tab in the property sheet to select a set of controls.
To create property pages, let us look into a simple example by creating a dialog based
MFC project.
Visual Studio makes it easy to create resources for property pages by displaying the Add
Resource dialog box, expanding the Dialog node and selecting one of the
IDD_PROPPAGE_X items.
Step 1: Right-click on your project in solution explorer and select Add -> Resources.
                                                                                        86
                                                       Microsoft Foundation Classes
                                                                                87
                                                           Microsoft Foundation Classes
Step 3: Let us change ID and Caption of this property page to IDD_PROPPAGE_1 and
Property Page 1 respectively as shown above.
                                                                                    88
                                       Microsoft Foundation Classes
                                                                89
                                                            Microsoft Foundation Classes
Step 6: Enter the class name and select CPropertyPage from base class dropdown list.
Step 8: Add one more property page with ID IDD_PROPPAGE_2 and Caption Property
Page 2 by following the above mentioned steps.
Step 9: You can now see two property pages created. To implement its functionality, we
need a property sheet.
The Property Sheet groups the property pages together and keeps it as entity.
Step 1: Right-click on your project and select Add > Class menu options
                                                                                       90
                                                          Microsoft Foundation Classes
Step 2: Select Visual C++ -> MFC from the left pane and MFC Class in the template pane
and click Add.
                                                                                   91
                                                           Microsoft Foundation Classes
Step 3: Enter the class name and select CPropertySheet from base class dropdown list.
Step 5: To launch this property sheet, we need the following changes in our main project
class.
 #include "MySheet.h"
 #include "PropPage1.h"
 #include "PropPage2.h"
 mySheet.AddPage(&page1);
                                                                                     92
                                                        Microsoft Foundation Classes
mySheet.AddPage(&page2);
 m_pMainWnd = &mySheet;
 INT_PTR nResponse = mySheet.DoModal();
 #include "stdafx.h"
 #include "MFCPropSheetDemo.h"
 #include "MFCPropSheetDemoDlg.h"
 #include "MySheet.h"
 #include "PropPage1.h"
 #include "PropPage2.h"
 #ifdef _DEBUG
 #define new DEBUG_NEW
 #endif
// CMFCPropSheetDemoApp
 BEGIN_MESSAGE_MAP(CMFCPropSheetDemoApp, CWinApp)
      ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
 END_MESSAGE_MAP()
// CMFCPropSheetDemoApp construction
 CMFCPropSheetDemoApp::CMFCPropSheetDemoApp()
 {
      // support Restart Manager
      m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;
                                                                                 93
                                                           Microsoft Foundation Classes
CMFCPropSheetDemoApp theApp;
// CMFCPropSheetDemoApp initialization
BOOL CMFCPropSheetDemoApp::InitInstance()
{
       // InitCommonControlsEx() is required on Windows XP if an application
       // manifest specifies use of ComCtl32.dll version 6 or later to enable
       // visual styles.   Otherwise, any window creation will fail.
       INITCOMMONCONTROLSEX InitCtrls;
       InitCtrls.dwSize = sizeof(InitCtrls);
       // Set this to include all the common control classes you want to use
       // in your application.
       InitCtrls.dwICC = ICC_WIN95_CLASSES;
       InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
                                                                                    94
                                                      Microsoft Foundation Classes
     // Standard initialization
     // If you are not using these features and wish to reduce the size
     // of your final executable, you should remove from the following
     // the specific initialization routines you do not need
     // Change the registry key under which our settings are stored
     // TODO: You should modify this string to be something appropriate
     // such as the name of your company or organization
     SetRegistryKey(_T("Local AppWizard-Generated Applications"));
     mySheet.AddPage(&page1);
     mySheet.AddPage(&page2);
     m_pMainWnd = &mySheet;
     INT_PTR nResponse = mySheet.DoModal();
     if (nResponse == IDOK)
     {
           // TODO: Place code here to handle when the dialog is
           //   dismissed with OK
     }
     else if (nResponse == IDCANCEL)
     {
           // TODO: Place code here to handle when the dialog is
           //   dismissed with Cancel
     }
     else if (nResponse == -1)
     {            TRACE(traceAppMsg, 0, "Warning: dialog creation failed, so
application is terminating unexpectedly.\n");
            TRACE(traceAppMsg, 0, "Warning: if you are using MFC controls on
the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS.\n");
     }
                                                                               95
                                                          Microsoft Foundation Classes
             delete pShellManager;
      }
      // Since the dialog has been closed, return FALSE so that we exit the
      //   application, rather than start the application's message pump.
      return FALSE;}
Step 9: When the above code is compiled and executed, you will see the following dialog
box. This dialog box contains two property pages.
                                                                                    96
                 9. MFC - Windows Layout                     Microsoft Foundation Classes
Layout of controls is very important and critical for application usability. It is used to
arrange a group of GUI elements in your application. There are certain important things
to consider while selecting layout:
Adding controls
Let us create new Dialog based MFC Project MFCLayoutDemo.
Step 1: Once the project is created, you will see the following screen.
Step 3: Drag some controls from the Toolbox which you can see on the left side.
(We will drag one Static Text and one Edit Control as shown in the following snapshot).
                                                                                       97
                                                         Microsoft Foundation Classes
                                                                                  98
                                                              Microsoft Foundation Classes
Control Grid
Control grid is the guiding grid dots, which can help in positioning of the controls you are
adding at the time of designing.
To enable the control grid, you need to click the Toggle Grid button in the toolbar as shown
in the following snapshot.
                                                                                         99
                                                              Microsoft Foundation Classes
Controls Resizing
After you have added a control to a dialog box, it assumes either its default size or the
size you drew it with. To help with the sizes of controls on the form or dialog box, Visual
Studio provides a visual grid made of black points.
To resize a control, that is, to give it a particular width or height, position the mouse on
one of the handles and drag it in the desired direction.
                                                                                        100
                                                             Microsoft Foundation Classes
You can now resize the controls with the help of this dotted grid.
Controls Positions
The controls you position on a dialog box or a form assume their given place. Most of the
time, these positions are not practical. You can move them around to any position of your
choice.
                                                                                     101
                                                              Microsoft Foundation Classes
Step 1: To move a control, click and drag it in the desired direction until it reaches the
intended position.
Step 2: To move a group of controls, first select them. Then drag the selection to the
desired location. Let us select the Static Texts and Edit Controls.
                                                                                        102
                                                         Microsoft Foundation Classes
                                                                                 103
Microsoft Foundation Classes
                        104
                                                            Microsoft Foundation Classes
To help with positioning the controls, Visual Studio provides the Dialog toolbar with the
following buttons.
Step 1: Let us align the Check box and Static Text controls to the left by selecting all
these controls.
                                                                                     105
                                               Microsoft Foundation Classes
                                                                       106
                                                              Microsoft Foundation Classes
Step 3: You can now see all these controls are aligned to the left.
Tab Ordering
The controls you add to a form or a dialog box are positioned in a sequence that follows
the order they were added. When you add control(s) regardless of the section or area you
place the new control, it is sequentially positioned at the end of the existing controls. If
you do not fix it, the user would have a hard time navigating the controls. The sequence
of controls navigation is also known as the tab order.
To change the tab, you can either use the Format -> Tab Order menu option or you can
also use the Ctrl + D shortcut. Let us press Ctrl + D.
                                                                                        107
                                                           Microsoft Foundation Classes
You can now see the order in which all these controls are added to this dialog box. To
Change the order or sequence of controls, click on all the controls in sequence in which
you want to navigate.
In this example, we will first click on the checkbox followed by Name and Address Edit
controls. Then click OK and Cancel as shown in the following snapshot.
                                                                                    108
                                                              Microsoft Foundation Classes
Let us run this application and you will see the following output.
                                                                                      109
Microsoft Foundation Classes
                        110
           10. MFC - Controls Management                       Microsoft Foundation Classes
In MFC applications, after visually adding a control to your application, if you want to refer
to it in your code, you can declare a variable based on, or associated with that control.
The MFC library allows you to declare two types of variables for some of the controls used
in an application a value or a control variable.
      One variable is used for the information stored in the control, which is also known
       as Control Variable/Instance.
      The other variable is known as Control Value Variable. A user can perform
       some sort of actions on that control with this variable.
Control Variable/Instance
A control variable is a variable based on the class that manages the control. For example,
a button control is based on the CButton class.
To see these concepts in real programming, let us create an MFC dialog based project
MFCControlManagement.
Once the project is created, you will see the following dialog box in designer window.
                                                                                          111
                                                          Microsoft Foundation Classes
Step 1: Delete the TODO line and drag one checkbox and one Edit control as shown in the
following snapshot. Change the caption of checkbox to Enable Control.
                                                                                   112
                                       Microsoft Foundation Classes
                                                               113
                                                          Microsoft Foundation Classes
Step 4: You can now see the Add Member Variable Wizard.
                                                                                  114
                                                             Microsoft Foundation Classes
You can select different options on this dialog box. For checkbox, the variable type is
CButton. It is selected by default in this dialog box.
Similarly, the control ID is also selected by default now we need to select Control in the
Category combo box, and type m_enableDisableCheck in the Variable Name edit box and
click finish.
Step 5: Similarly, add Control Variable of Edit control with the settings as shown in the
following snapshot.
                                                                                      115
                                                               Microsoft Foundation Classes
Observe the header file of the dialog class. You can see that the new variables have been
added now.
 CButton m_enableDisableCheck;
 CEdit m_myEditControl;
      The value variable must be able to handle the type of value stored in the control
       it is intended to refer to.
      For example, because a text based control is used to handle text, you can declare
       a text-based data type for it. This would usually be a CString variable.
                                                                                          116
                                                              Microsoft Foundation Classes
Let us look into this type of variable for checkbox and edit control.
Step 2: The Variable type is BOOL. Select Value from the Category dropdown list.
Step 4: Similarly, add value Variable for Edit control with the settings as shown in the
following snapshot.
                                                                                      117
                                                              Microsoft Foundation Classes
Step 5: Type CString in variable type and m_editControlVal in the variable name field.
Step 6: You can now see these variables added in the Header file.
 bool m_enableDisableVal;
 CString m_editControlVal;
      For project dialog boxes that are already associated with a class, you can take
       advantage of some shortcuts when you create event handlers.
      You can quickly create a handler either for the default control notification event or
       for any applicable Windows message.
                                                                                         118
                                                             Microsoft Foundation Classes
Let us look into the same example in which we added event handler for checkbox.
Step 1: Right-click the control for which you want to handle the notification event.
Step 2: On the shortcut menu, click Add Event Handler to display the Event Handler
Wizard.
                                                                                       119
                                                               Microsoft Foundation Classes
Step 3: Select the event in the Message type box to add to the class selected in the Class
list box.
Step 4: Accept the default name in the Function handler name box, or provide the name
of your choice.
Step 6: You can now see the                following   event    added    at   the   end    of
CMFCControlManagementDlg.cpp file.
 void CMFCControlManagementDlg::OnBnClickedCheck1()
 {
       // TODO: Add your control notification handler code here
 }
                                                                                          120
                                                               Microsoft Foundation Classes
Controls Management
So far, we have seen how to add controls to an application. We will now see how to manage
these controls as per user requirement. We can use the control variable/instance in a
particular event handler.
Step 1: Let us look into the following example. Here, we will enable/disable the edit control
when the checkbox is checked/unchecked.
Step 2: We have now added the checkbox click event handler. Here is the implementation:
 void CMFCControlManagementDlg::OnBnClickedCheck1()
 {
        // TODO: Add your control notification handler code here
        UpdateData(TRUE);
        if (m_enableDisableVal)
               m_myEditControl.EnableWindow(TRUE);
        else
               m_myEditControl.EnableWindow(FALSE);
 }
Step 3: When the dialog is created, we need to add the following code to
CMFCControlManagementDlg::OnInitDialog(). This will manage these controls.
 UpdateData(TRUE);
 if (m_enableDisableVal)
        m_myEditControl.EnableWindow(TRUE);
 else
        m_myEditControl.EnableWindow(FALSE);
 #include "stdafx.h"
 #include "MFCControlManagement.h"
 #include "MFCControlManagementDlg.h"
 #include "afxdialogex.h"
#ifdef _DEBUG
                                                                                         121
                                                        Microsoft Foundation Classes
// Dialog Data
#ifdef AFX_DESIGN_TIME
     enum { IDD = IDD_ABOUTBOX };
#endif
     protected:
     virtual void DoDataExchange(CDataExchange* pDX);      // DDX/DDV support
// Implementation
protected:
     DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
                                                                                122
                                                         Microsoft Foundation Classes
// CMFCControlManagementDlg dialog
BEGIN_MESSAGE_MAP(CMFCControlManagementDlg, CDialogEx)
     ON_WM_SYSCOMMAND()
     ON_WM_PAINT()
     ON_WM_QUERYDRAGICON()
     ON_BN_CLICKED(IDC_CHECK1, &CMFCControlManagementDlg::OnBnClickedCheck1)
END_MESSAGE_MAP()
BOOL CMFCControlManagementDlg::OnInitDialog()
{
     CDialogEx::OnInitDialog();
                                                                                 123
                                                           Microsoft Foundation Classes
     // Set the icon for this dialog.     The framework does this automatically
     //     when the application's main window is not a dialog
     SetIcon(m_hIcon, TRUE);                   // Set big icon
     SetIcon(m_hIcon, FALSE);           // Set small icon
     return TRUE;    // return TRUE   unless you set the focus to a control
}
                                                                                   124
                                                          Microsoft Foundation Classes
             CAboutDlg dlgAbout;
             dlgAbout.DoModal();
      }
      else
      {
             CDialogEx::OnSysCommand(nID, lParam);
      }
}
// If you add a minimize button to your dialog, you will need the code below
//   to draw the icon.     For MFC applications using the document/view model,
//   this is automatically done for you by the framework.
void CMFCControlManagementDlg::OnPaint()
{
      if (IsIconic())
      {
             CPaintDC dc(this); // device context for painting
            SendMessage(WM_ICONERASEBKGND,
reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
 // The system calls this function to obtain the cursor to display while the
 user drags
 //   the minimized window.
 HCURSOR CMFCControlManagementDlg::OnQueryDragIcon()
 {
       return static_cast<HCURSOR>(m_hIcon);
 }
 void CMFCControlManagementDlg::OnBnClickedCheck1()
 {
       // TODO: Add your control notification handler code here
       UpdateData(TRUE);
       if (m_enableDisableVal)
              m_myEditControl.EnableWindow(TRUE);
       else
              m_myEditControl.EnableWindow(FALSE);
 }
Step 5: When the above code is compiled and executed, you will see the following output.
The checkbox is unchecked by default. This disables the edit control too.
                                                                                    126
                                                             Microsoft Foundation Classes
Step 6: Check the Enable Control checkbox. This will automatically enable the edit control.
                                                                                       127
                 11. MFC - Windows Controls                    Microsoft Foundation Classes
Windows controls are objects that users can interact with to enter or manipulate data.
They commonly appear in dialog boxes or on toolbars. There are various types of controls:
      A text based control which is used to display text to the user or request text
       from the user.
      A static control can be used to show colors, a picture or something that does
       not regularly fit in the above categories.
Static Control
A static control is an object that displays information to the user without his or her direct
intervention. It can be used to show colors, a geometric shape, or a picture such as an
icon, a bitmap, or an animation. Following are the static controls:
      Static Text
      Picture Control
      Group Box
Animation Control
An animation control is a window that displays an Audio clip in AVI format. An AVI clip is
a series of bitmap frames, like a movie. Animation controls can only play simple AVI clips,
and they do not support sound. It is represented by the CAnimateCtrl class.
        Name                                        Description
        Close            Closes the AVI clip.
                         Creates an animation control and attaches it to a CAnimateCtrl
        Create
                         object.
                         Creates an animation control with the specified Windows
       CreateEx
                         extended styles and attaches it to a CAnimateCtrl object.
                         Indicates whether an Audio-Video Interleaved (AVI) clip is
       IsPlaying
                         playing.
                         Opens an AVI clip from a file or resource and displays the first
         Open
                         frame.
         Play            Plays the AVI clip without sound.
         Seek            Displays a selected single frame of the AVI clip.
         Stop            Stops playing the AVI clip.
                                                                                         128
                                                              Microsoft Foundation Classes
                                                                                      129
                                                           Microsoft Foundation Classes
Step 2: Once the project is created, remove the TODO line and click on Animation Control
in Toolbox and draw a rectangle as shown in the following snapshot.
                                                                                    130
                                                               Microsoft Foundation Classes
Step 3: To add a control variable for animation control, right-click and select Add Variable.
Step 4: Enter the variable name and variable type, which is CAnimateCtrl for animation.
                                                                                         131
                                                              Microsoft Foundation Classes
Step 5: Using the Properties window, set the Border value to False, Set the Auto Play, the
Center, and the transparent values to True.
Step 6: Here we have *.avi file in res folder, which is the default folder for any resources
used in the project
Step 7: To start the animation, we need to call the Open method CAnimateCtrl class.
Add the following line of code in CMFCAnimationDemoDlg::OnInitDialog()
m_animationCtrl.Open(L"res\\copyfile.avi");
 BOOL CMFCAnimationDemoDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
                                                                                        132
                                                            Microsoft Foundation Classes
       // Set the icon for this dialog.    The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                   // Set big icon
       SetIcon(m_hIcon, FALSE);           // Set small icon
       return TRUE;   // return TRUE   unless you set the focus to a control
 }
Step 9: When the above code is compiled and executed, you will see the following output.
                                                                                    133
                                                                Microsoft Foundation Classes
Button
A button is an object that the user clicks to initiate an action. Button control is represented
by CButton class.
              Name                                        Description
                                     Creates the Windows button control and attaches it to
              Create
                                     the CButton object.
            DrawItem                 Override to draw an owner-drawn CButton object.
                                     Retrieves the handle of the bitmap previously set with
            GetBitmap
                                     SetBitmap.
         GetButtonStyle              Retrieves information about the button control style.
           GetCheck                  Retrieves the check state of a button control.
                                     Retrieves the handle of the cursor image previously
            GetCursor
                                     set with SetCursor.
                                     Retrieves the handle of the icon previously set with
             GetIcon
                                     SetIcon.
          GetIdealSize               Retrieves the ideal size of the button control.
          GetImageList               Retrieves the image list of the button control.
                                     Retrieves the note component of the current
             GetNote
                                     command link control.
                                     Retrieves the length of the note text for the current
         GetNoteLength
                                     command link control.
                                     Retrieves the glyph associated with the current split
          GetSplitGlyph
                                     button control.
                                     Retrieves the image list for the current split button
       GetSplitImageList
                                     control.
                                     Retrieves information that defines the current split
           GetSplitInfo
                                     button control.
                                     Retrieves the bounding rectangle of the drop-down
           GetSplitSize
                                     component of the current split button control.
                                     Retrieves the split button styles that define the
          GetSplitStyle
                                     current split button control.
                                     Retrieves the check state, highlight state, and focus
             GetState
                                     state of a button control.
         GetTextMargin               Retrieves the text margin of the button control.
           SetBitmap                 Specifies a bitmap to be displayed on the button.
                                                                                           134
                                                              Microsoft Foundation Classes
Let us look into a simple example by dragging two buttons from the Toolbox.
                                                                                      135
                                                           Microsoft Foundation Classes
Step 3: Here is an implementation of both events in which we will start and stop
animation.
 void CMFCAnimationDemoDlg::OnBnClickedButtonStart()
 {
       // TODO: Add your control notification handler code here
       m_animationCtrl.Open(L"res\\copyfile.avi");
 }
 void CMFCAnimationDemoDlg::OnBnClickedButtonStop()
 {
       // TODO: Add your control notification handler code here
       m_animationCtrl.Stop();
 }
Step 4: When the above code is compiled and executed, you will see the following output.
                                                                                    136
                                                              Microsoft Foundation Classes
Step 5: When you click the Stop button, the animation stops and when you press the
Start button, it starts again.
Bitmap Button
A bitmap button displays a picture or a picture and text on its face. This is usually
intended to make the button a little explicit. A bitmap button is created using the
CBitmapButton class, which is derived from CButton.
             Name                                        Description
                                   Associates a button in a dialog box with an object of
           AutoLoad                the CBitmapButton class, loads the bitmap(s) by
                                   name, and sizes the button to fit the bitmap.
                                   Initializes the object by loading one or more named
         LoadBitmaps               bitmap resources from the application's resource file
                                   and attaching the bitmaps to the object.
        SizeToContent              It resizes the button to the size of the bitmaps.
                                                                                      137
                                                               Microsoft Foundation Classes
Step 3: Design your bitmap and change its ID to IDB_BITMAP_START as shown above.
                                                                                       138
                                                               Microsoft Foundation Classes
Step 4: Add a button to your dialog box and also add a control Variable m_buttonStart
for that button.
Step 5: Add a bitmap variable in your header file. You can now see the following two
variables.
 CBitmap m_bitmapStart;
 CButton m_buttonStart;
 m_bitmapStart.LoadBitmap(IDB_BITMAP_START);
 HBITMAP hBitmap = (HBITMAP)m_bitmapStart.GetSafeHandle();
 m_buttonStart.SetBitmap(hBitmap);
Step 7: When the above code is compiled and executed, you will see the following output.
Command Button
A command button is an enhanced version of the regular button. It displays a green
arrow icon on the left, followed by a caption in regular size. Under the main caption, it can
display another smaller caption that serves as a hint to provide more information.
                                                                                         139
                                                           Microsoft Foundation Classes
            Name                                      Description
                                Creates the Windows button control and attaches it to
            Create
                                the CButton object.
          DrawItem              Override to draw an owner-drawn CButton object.
                                Retrieves the handle of the bitmap previously set with
          GetBitmap
                                SetBitmap.
       GetButtonStyle           Retrieves information about the button control style.
         GetCheck               Retrieves the check state of a button control.
                                Retrieves the handle of the cursor image previously set
          GetCursor
                                with SetCursor.
                                Retrieves the handle of the icon previously set with
           GetIcon
                                SetIcon.
        GetIdealSize            Retrieves the ideal size of the button control.
        GetImageList            Retrieves the image list of the button control.
                                Retrieves the note component of the current command
           GetNote
                                link control.
                                Retrieves the length of the note text for the current
        GetNoteLength
                                command link control.
                                Retrieves the glyph associated with the current split
        GetSplitGlyph
                                button control.
                                Retrieves the image list for the current split button
      GetSplitImageList
                                control.
                                Retrieves information that defines the current split
         GetSplitInfo
                                button control.
                                Retrieves the bounding rectangle of the drop-down
         GetSplitSize
                                component of the current split button control.
                                Retrieves the split button styles that define the current
         GetSplitStyle
                                split button control.
                                Retrieves the check state, highlight state, and focus
           GetState
                                state of a button control.
        GetTextMargin           Retrieves the text margin of the button control.
          SetBitmap             Specifies a bitmap to be displayed on the button.
        SetButtonStyle          Changes the style of a button.
           SetCheck             Sets the check state of a button control.
          SetCursor             Specifies a cursor image to be displayed on the button.
                                Sets the drop-down state of the current split button
     SetDropDownState
                                control.
           SetIcon              Specifies an icon to be displayed on the button.
         SetImageList           Sets the image list of the button control.
           SetNote              Sets the note on the current command link control.
                                Associates a specified glyph with the current split
        SetSplitGlyph
                                button control.
                                Associates an image list with the current split button
      SetSplitImageList
                                control.
                                Specifies information that defines the current split
         SetSplitInfo
                                button control.
                                Sets the bounding rectangle of the drop-down
         SetSplitSize
                                component of the current split button control.
         SetSplitStyle          Sets the style of the current split button control.
           SetState             Sets the highlighting state of a button control.
        SetTextMargin           Sets the text margin of the button control.
                                                                                      140
                                                          Microsoft Foundation Classes
Let us look into a simple example of command button by creating a new MFC dialog based
project MFCCommandButton
                                                                                  141
                                                             Microsoft Foundation Classes
Step 3: Add the event handler for this button and add the following message in the event
handler.
 void CMFCCommandButtonDlg::OnBnClickedCommand1()
 {
        // TODO: Add your control notification handler code here
        MessageBox(L"My Command Button Clicked");
 }
Step 4: When the above code is compiled and executed, you will see the following output.
Step 5: When the My Command Button is clicked; the following message will be displayed.
Static Text
A static control displays a text string, box, rectangle, icon, cursor, bitmap, or enhanced
metafile. It is represented by CStatic class. It can be used to label, box, or separate
other controls. A static control normally takes no input and provides no output.
                                                                                      142
                                                              Microsoft Foundation Classes
               Name                                        Description
                                       Creates the Windows static control and attaches it
               Create
                                       to the CStatic object.
             DrawItem                  Override to draw an owner-drawn static control.
                                       Retrieves the handle of the bitmap previously set
            GetBitmap
                                       with SetBitmap.
                                       Retrieves the handle of the cursor image previously
             GetCursor
                                       set with SetCursor.
                                       Retrieves the handle of the enhanced metafile
          GetEnhMetaFile
                                       previously set with SetEnhMetaFile.
                                       Retrieves the handle of the icon previously set with
              GetIcon
                                       SetIcon.
                                       Specifies a bitmap to be displayed in the static
             SetBitmap
                                       control.
                                       Specifies a cursor image to be displayed in the
             SetCursor
                                       static control.
                                       Specifies an enhanced metafile to be displayed in
          SetEnhMetaFile
                                       the static control.
                                       Specifies an icon to be displayed in the static
              SetIcon
                                       control.
                                                                                        143
                                                              Microsoft Foundation Classes
Step 2: Change the Caption to It is Static Text Control and run your application you
will see the following dialog box, which now contains the Static Text control as well.
List Box
A list box displays a list of items, such as filenames, that the user can view and select. A
List box is represented by CListBox class. In a single-selection list box, the user can
select only one item. In a multiple-selection list box, a range of items can be selected.
When the user selects an item, it is highlighted and the list box sends a notification
message to the parent window.
                    Name                                        Description
                  AddString                      Adds a string to a list box.
                 CharToItem                      Override to provide custom WM_CHAR
                                                 handling for owner-draw list boxes which
                                                 don't have strings.
                CompareItem                      Called by the framework to determine
                                                 the position of a new item in a sorted
                                                 owner-draw list box.
                    Create                       Creates the Windows list box and
                                                 attaches it to the CListBox object.
                 DeleteItem                      Called by the framework when the user
                                                 deletes an item from an owner-draw list
                                                 box.
                 DeleteString                    Deletes a string from a list box.
                     Dir                         Adds filenames, drives, or both from the
                                                 current directory to a list box.
                                                                                        144
                                   Microsoft Foundation Classes
                                                              145
                                                           Microsoft Foundation Classes
Let us look into a simple example of List box by creating a new MFC dialog based
application.
Step 1: Once the project is created, you will see the TODO line which is the Caption of
Text Control. Remove the Caption and set its ID to IDC_STATIC_TXT.
                                                                                     146
Microsoft Foundation Classes
                        147
                                                         Microsoft Foundation Classes
                                                                                 148
Microsoft Foundation Classes
                        149
                                                             Microsoft Foundation Classes
Step 5: Add the control variable for the List Box control.
                                                                                     150
                                                          Microsoft Foundation Classes
Step 6: Add the event handler for the List Box control.
Step 7: Select the LBN_SELCHANGE from the message type and enter name for the event
handler.
Step 8: Add one function, which will load the list box.
 void CMFCListBoxDlg::LoadListBox()
 {
       CString str = _T("");
       for (int i = 0; i<10; i++)
       {
              str.Format(_T("Item %d"), i);
              m_listBox.AddString(str);
       }
 }
                                                                                  151
                                                            Microsoft Foundation Classes
 BOOL CMFCListBoxDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.      The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                    // Set big icon
       SetIcon(m_hIcon, FALSE);            // Set small icon
Step 10: Here is the event handler implementation. This will display the current selected
item from the List Box.
 void CMFCListBoxDlg::OnLbnSelchangeList1()
 {
       // TODO: Add your control notification handler code here
       m_listBox.GetText(m_listBox.GetCurSel(),m_strItemSelected);
       UpdateData(FALSE);
Step 11: When the above code is compiled and executed, you will see the following output.
                                                                                     152
                                                              Microsoft Foundation Classes
Step 12: When you select any item, it will be displayed on the Text Control.
Combo Boxes
A combo box consists of a list box combined with either a static control or edit control. it
is represented by CComboBox class. The list-box portion of the control may be displayed
at all times or may only drop down when the user selects the drop-down arrow next to the
control.
                        Name                                          Description
                      AddString                          Adds a string to the end of the
                                                         list in the list box of a combo box,
                                                         or at the sorted position for list
                                                         boxes with the CBS_SORT style.
                         Clear                           Deletes (clears) the current
                                                         selection, if any, in the edit
                                                         control.
                    CompareItem                          Called by the framework to
                                                         determine the relative position of
                                                         a new list item in a sorted owner-
                                                         drawn combo box.
                         Copy                            Copies the current selection, if
                                                         any, onto the Clipboard in
                                                         CF_TEXT format.
                        Create                           Creates the combo box and
                                                         attaches it to the CComboBox
                                                         object.
                                                                                         153
                             Microsoft Foundation Classes
                                                         154
                       Microsoft Foundation Classes
                                                 155
                                                             Microsoft Foundation Classes
                                                                                      156
                                                            Microsoft Foundation Classes
Let us look into an example of Radio button by creating a new MFC dialog based
application.
Step 1: Drag a Combo box and remove the Caption of Static Text control.
Step 2: Add a control variable m_comboBoxCtrl for combobox and value variable
m_strTextCtrl for Static Text control.
                                                                                    157
                                                           Microsoft Foundation Classes
Step 4: Add the following code in OnInitDialog() to load the combo box.
                                                                                   158
                                                            Microsoft Foundation Classes
 void CMFCComboBoxDlg::OnCbnSelchangeCombo1()
 {
       // TODO: Add your control notification handler code here
       m_comboBoxCtrl.GetLBText(m_comboBoxCtrl.GetCurSel(), m_strTextCtrl);
       UpdateData(FALSE);
 }
Step 6: When the above code is compiled and executed, you will see the following output.
Step 7: When you select any item then it will be displayed on the Text Control.
Radio Buttons
A radio button is a control that appears as a dot surrounded by a round box. In reality,
a radio button is accompanied by one or more other radio buttons that appear and behave
as a group.
             Name                                     Description
                                  Creates the Windows button control and attaches it to
             Create
                                  the CButton object.
           DrawItem               Override to draw an owner-drawn CButton object.
                                                                                    159
                                                             Microsoft Foundation Classes
                                                                                       160
                                                             Microsoft Foundation Classes
Let us look into an example of Radio button by creating a new MFC dialog based application
Step 1: Drag a group box and three radio buttons and remove the Caption of Static Text
control.
Step 2: Add event handler for all the three radio buttons.
                                                                                      161
                                                              Microsoft Foundation Classes
Step 3: Add the Value variable for the Static Text control.
                                                                                      162
                                                              Microsoft Foundation Classes
 void CMFCRadioButtonDlg::OnBnClickedRadio1()
 {
      // TODO: Add your control notification handler code here
      m_strTextControl = _T("Radio Button 1 Clicked");
      UpdateData(FALSE);
 }
 void CMFCRadioButtonDlg::OnBnClickedRadio2()
 {
      // TODO: Add your control notification handler code here
      m_strTextControl = _T("Radio Button 2 Clicked");
      UpdateData(FALSE);
 }
 void CMFCRadioButtonDlg::OnBnClickedRadio3()
 {
                                                                                      163
                                                             Microsoft Foundation Classes
Step 5: When the above code is compiled and executed, you will see the following output.
When you select any radio button, the message is displayed on Static Text control.
Checkboxes
A checkbox is a Windows control that allows the user to set or change the value of an item
as true or false.
              Name                 Description
                                   Creates the Windows button control and attaches it to
             Create
                                   the CButton object.
           DrawItem                Override to draw an owner-drawn CButton object.
                                   Retrieves the handle of the bitmap previously set with
           GetBitmap
                                   SetBitmap.
         GetButtonStyle            Retrieves information about the button control style.
           GetCheck                Retrieves the check state of a button control.
                                   Retrieves the handle of the cursor image previously
           GetCursor
                                   set with SetCursor.
                                   Retrieves the handle of the icon previously set with
             GetIcon
                                   SetIcon.
                                                                                      164
                                             Microsoft Foundation Classes
                                                                      165
                                                             Microsoft Foundation Classes
Once the project is created, you will see the following dialog box in designer window.
Step 1: Delete the TODO line and drag one checkbox and one Edit control as shown in the
following snapshot. Also change the caption of checkbox to Enable Control.
                                                                                         166
                                                              Microsoft Foundation Classes
Step 3: You can select different options on this dialog box. For checkbox, the CButton
variable type is selected by default.
Step 4: Similarly, the control ID is also selected by default. We now need to select Control
in the Category combo box, and type m_enableDisableCheck in the Variable Name edit
box and click Finish.
Step 5: Add Control Variable of Edit control with the settings as shown in the following
snapshot.
                                                                                        167
                                                            Microsoft Foundation Classes
Step 6: Observe the header file of the dialog class. You can see that these two variables
have been added now.
 CButton m_enableDisableCheck;
 CEdit m_myEditControl;
                                                                                     168
                                    Microsoft Foundation Classes
                                                            169
                                                             Microsoft Foundation Classes
Step 9: Add value Variable for Edit control with the settings as shown in the following
snapshot.
Step 10: Observe the header file. You can see that the new variables have been added
now.
 bool m_enableDisableVal;
 CString m_editControlVal;
Step 12: Right-click the control for which you want to handle the notification event.
                                                                                        170
                                                                Microsoft Foundation Classes
Step 13: Select the event in the Message type box to add to the class selected in the
Class list box.
Step 14: Accept the default name in the Function handler name box, or provide a name
of your choice.
Step 15: Click Add and Edit to add the event handler.
Step 16: You can now see the              following     event     added   at   the   end    of
CMFCControlManagementDlg.cpp file.
 void CMFCControlManagementDlg::OnBnClickedCheck1()
 {
      // TODO: Add your control notification handler code here
 }
Step 17: This enables/disables the edit control when the checkbox is checked/unchecked.
                                                                                           171
                                                         Microsoft Foundation Classes
Step 18: We have now added the checkbox click event handler. Here is the
implementation of event handler for checkbox.
 void CMFCControlManagementDlg::OnBnClickedCheck1()
 {
        // TODO: Add your control notification handler code here
        UpdateData(TRUE);
        if (m_enableDisableVal)
               m_myEditControl.EnableWindow(TRUE);
        else
               m_myEditControl.EnableWindow(FALSE);
 }
 UpdateData(TRUE);
 if (m_enableDisableVal)
        m_myEditControl.EnableWindow(TRUE);
 else
        m_myEditControl.EnableWindow(FALSE);
 #include "stdafx.h"
 #include "MFCControlManagement.h"
 #include "MFCControlManagementDlg.h"
 #include "afxdialogex.h"
 #ifdef _DEBUG
 #define new DEBUG_NEW
 #endif
                                                                                 172
                                                        Microsoft Foundation Classes
// Dialog Data
#ifdef AFX_DESIGN_TIME
     enum { IDD = IDD_ABOUTBOX };
#endif
     protected:
     virtual void DoDataExchange(CDataExchange* pDX);      // DDX/DDV support
// Implementation
protected:
     DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
                                                                                173
                                                         Microsoft Foundation Classes
     m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
BEGIN_MESSAGE_MAP(CMFCControlManagementDlg, CDialogEx)
     ON_WM_SYSCOMMAND()
     ON_WM_PAINT()
     ON_WM_QUERYDRAGICON()
     ON_BN_CLICKED(IDC_CHECK1, &CMFCControlManagementDlg::OnBnClickedCheck1)
END_MESSAGE_MAP()
BOOL CMFCControlManagementDlg::OnInitDialog()
{
     CDialogEx::OnInitDialog();
                                                                                 174
                                                           Microsoft Foundation Classes
              bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
              ASSERT(bNameValid);
              if (!strAboutMenu.IsEmpty())
              {
                     pSysMenu->AppendMenu(MF_SEPARATOR);
                     pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
              }
     }
     // Set the icon for this dialog.     The framework does this automatically
     //     when the application's main window is not a dialog
     SetIcon(m_hIcon, TRUE);                   // Set big icon
     SetIcon(m_hIcon, FALSE);           // Set small icon
     return TRUE;    // return TRUE   unless you set the focus to a control
}
                                                                                   175
                                                          Microsoft Foundation Classes
// If you add a minimize button to your dialog, you will need the code below
//   to draw the icon.     For MFC applications using the document/view model,
//   this is automatically done for you by the framework.
void CMFCControlManagementDlg::OnPaint()
{
      if (IsIconic())
      {
             CPaintDC dc(this); // device context for painting
            SendMessage(WM_ICONERASEBKGND,
reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// The system calls this function to obtain the cursor to display while the
user drags
//   the minimized window.
HCURSOR CMFCControlManagementDlg::OnQueryDragIcon()
{
      return static_cast<HCURSOR>(m_hIcon);
}
                                                                                  176
                                                            Microsoft Foundation Classes
 void CMFCControlManagementDlg::OnBnClickedCheck1()
 {
       // TODO: Add your control notification handler code here
       UpdateData(TRUE);
       if (m_enableDisableVal)
              m_myEditControl.EnableWindow(TRUE);
       else
              m_myEditControl.EnableWindow(FALSE);
 }
Step 21: When the above code is compiled and executed, you will see the following output.
You can now see the checkbox is unchecked by default. This disables the edit control.
Step 22: Now when you check the checkbox, the edit control is enabled.
                                                                                     177
                                                           Microsoft Foundation Classes
Image Lists
An Image List is a collection of same-sized images, each of which can be referred to by
its zero-based index. Image lists are used to efficiently manage large sets of icons or
bitmaps. Image lists are represented by CImageList class.
                       Name                                      Description
                                                     Adds an image or images to an
                        Add
                                                     image list.
                                                     Attaches an image list to a
                       Attach
                                                     CImageList object.
                     BeginDrag                       Begins dragging an image.
                                                     Copies an image within a
                        Copy
                                                     CImageList object.
                                                     Initializes an image list and
                       Create
                                                     attaches it to a CImageList object.
                 DeleteImageList                     Deletes an image list.
                                                     Called by the CWinApp idle-time
                                                     handler to delete any temporary
                 DeleteTempMap
                                                     CImageList object created by
                                                     FromHandle.
                                                     Detaches an image list object from
                       Detach                        a CImageList object and returns a
                                                     handle to an image list.
                                                     Locks updates during a drag
                     DragEnter                       operation and displays the drag
                                                     image at a specified position.
                                                                                     178
                            Microsoft Foundation Classes
                                                     179
                                                            Microsoft Foundation Classes
Let us create a new MFC Application MFCImageListDemo with the following settings.
Step 2: In header file of CMFCImageListDemoView class, add the following two variables.
 CImageList ImageList;
 int nImage;
 CMFCImageListDemoView::CMFCImageListDemoView()
 {
       // TODO: add construction code here
       ImageList.Create(800, 800, ILC_COLOR, 4, 1);
       CBitmap bmp;
                                                                                      180
                                                            Microsoft Foundation Classes
       bmp.LoadBitmap(IDB_BITMAP1);
       ImageList.Add(&bmp, RGB(0, 0, 0));
       nImage = 0;
       ImageList.Draw(pDC , nImage, CPoint(0,0), ILD_NORMAL);
       Invalidate();
       if (!pDoc)
              return;
Step 5: When you run this application, you will see the following output.
                                                                                    181
                                                              Microsoft Foundation Classes
Edit Box
An Edit Box is a rectangular child window in which the user can enter text. It is
represented by CEdit class.
                   Name                                        Description
                                              Determines      whether     an    edit-control
                 CanUndo
                                              operation can be undone.
                                              Retrieves the line and character indexes for
               CharFromPos
                                              the character closest to a specified position.
                                              Deletes (clears) the current selection (if
                   Clear
                                              any) in the edit control.
                                              Copies the current selection (if any) in the
                   Copy                       edit control to the Clipboard in CF_TEXT
                                              format.
                                              Creates the Windows edit control and
                   Create
                                              attaches it to the CEdit object.
                                              Deletes (cuts) the current selection (if any)
                    Cut                       in the edit control and copies the deleted
                                              text to the Clipboard in CF_TEXT format.
                                                                                        182
                                      Microsoft Foundation Classes
Let us into a simple example by creating a new MFC dialog based project.
Step 1: Remove the caption of Static Text control and drag one button and one Edit
control.
Step 2: Add a control variable m_editCtrl for edit control and value variable m_strTextCtrl
for Static text control.
                                                                                        185
                                                            Microsoft Foundation Classes
Step 4: Here is the implementation of event handler for button click event.
 void CMFCEditDlg::OnBnClickedButton1()
 {
       // TODO: Add your control notification handler code here
       CString str = _T("");
       m_editCtrl.GetWindowTextW(str);
       if (!str.IsEmpty())
              m_strTextCtrl = str;
       else
              m_strTextCtrl = _T("Write Something");
       UpdateData(FALSE);
 }
                                                                                    186
                                                             Microsoft Foundation Classes
Step 5: When the above code is compiled and executed, you will see the following.
Step 6: When you write text in the edit control and click Display, it will update that text
on Static Text Control.
Rich Edit
A Rich Edit Control is a window in which the user can enter and edit text. The text can be
assigned character and paragraph formatting, and can include embedded OLE objects. It
is represented by CRichEditCtrl class.
                        Name                                         Description
                       CanPaste                           Determines if the contents of
                                                          the Clipboard can be pasted
                                                          into this rich edit control.
                        CanRedo                           Determines whether there are
                                                          any actions in the controls redo
                                                          queue.
                        CanUndo                           Determines      if   an    editing
                                                          operation can be undone.
                                                                                        187
                          Microsoft Foundation Classes
                       in Asian-language versions of
                       the operating system.
   HideSelection       Shows or hides the current
                       selection.
     LimitText         Limits the amount of text a
                       user can enter into the
                       CRichEditCtrl object.
   LineFromChar        Determines which line contains
                       the given character.
     LineIndex         Retrieves the character index
                       of a given line in this
                       CRichEditCtrl object.
     LineLength        Retrieves the length of a given
                       line in this CRichEditCtrl object.
     LineScroll        Scrolls    the     text  in    this
                       CRichEditCtrl object.
       Paste           Inserts the contents of the
                       Clipboard into this rich edit
                       control.
    PasteSpecial       Inserts the contents of the
                       Clipboard into this rich edit
                       control in the specified data
                       format.
    PosFromChar        Retrieves     the client area
                       coordinates of a specified
                       character in an edit control.
       Redo            Redoes the next action in the
                       control's redo queue.
     ReplaceSel        Replaces the current selection
                       in this CRichEditCtrl object with
                       specified text.
   RequestResize       Forces this CRichEditCtrl object
                       to     send      request    resize
                       notifications.
 SetAutoURLDetect      Indicates if the auto URL
                       detection is active in a rich edit
                       control.
SetBackgroundColor     Sets the background color in
                       this CRichEditCtrl object.
SetDefaultCharFormat   Sets     the    current    default
                       character formatting attributes
                       in this CRichEditCtrl object.
   SetEventMask        Sets the event mask for this
                       CRichEditCtrl object.
     SetModify         Sets or clears the modification
                       flag for this CRichEditCtrl
                       object.
   SetOLECallback      Sets                            the
                       IRichEditOleCallback         COM
                       object for this rich edit control.
     SetOptions        Sets the options for this
                       CRichEditCtrl object.
   SetParaFormat       Sets the paragraph formatting
                       attributes     in    the   current
                                                      190
                                                              Microsoft Foundation Classes
                                                                                       191
                                                            Microsoft Foundation Classes
Let us into a simple example by creating a new MFC dialog based application.
Step 1: Delete the TODO line and drag one Rich Edit Control and three buttons from the
Toolbox.
                                                                                       192
                                                              Microsoft Foundation Classes
Step 2: Change the Caption of these three buttons from Bold, Italic and Under Line to
IDC_BUTTON_BOLD, IDC_BUTTON_ITALIC and IDC_BUTTON_UNDERLINE respectively.
Step 3: Set the following properties to True: Multiline, Want Return, Vertical Scroll.
Step 4: Add the control variable m_richEdit for Rich Edit Control.
                                                                                         193
                                                        Microsoft Foundation Classes
 BOOL CMFCRichEditApp::InitInstance()
 {
 //TODO: call AfxInitRichEdit2() to initialize richedit2 library.
      // InitCommonControlsEx() is required on Windows XP if an application
      // manifest specifies use of ComCtl32.dll version 6 or later to enable
      // visual styles.   Otherwise, any window creation will fail.
      INITCOMMONCONTROLSEX InitCtrls;
      InitCtrls.dwSize = sizeof(InitCtrls);
      // Set this to include all the common control classes you want to use
      // in your application.
      InitCtrls.dwICC = ICC_WIN95_CLASSES;
      InitCommonControlsEx(&InitCtrls);
::AfxInitRichEdit2();
                                                                                194
                                                           Microsoft Foundation Classes
CWinApp::InitInstance();
AfxEnableControlContainer();
       // Standard initialization
       // If you are not using these features and wish to reduce the size
       // of your final executable, you should remove from the following
       // the specific initialization routines you do not need
       // Change the registry key under which our settings are stored
       // TODO: You should modify this string to be something appropriate
       // such as the name of your company or organization
       SetRegistryKey(_T("Local AppWizard-Generated Applications"));
       CMFCRichEditDlg dlg;
       m_pMainWnd = &dlg;
       INT_PTR nResponse = dlg.DoModal();
       if (nResponse == IDOK)
       {
             // TODO: Place code here to handle when the dialog is
             //   dismissed with OK
       }
       else if (nResponse == IDCANCEL)
       {
             // TODO: Place code here to handle when the dialog is
             //   dismissed with Cancel
       }
       else if (nResponse == -1)
       {
                                                                                   195
                                                            Microsoft Foundation Classes
       // Since the dialog has been closed, return FALSE so that we exit the
       //   application, rather than start the application's message pump.
       return FALSE;
 }
Step 6: Add the Click event handler for all the three buttons. Here is the implementation
for these events.
 void CMFCRichEditDlg::OnBnClickedButtonBold()
 {
       // TODO: Add your control notification handler code here
       CHARFORMAT Cfm;
m_richEdit.GetSelectionCharFormat(Cfm);
       Cfm.cbSize = sizeof(CHARFORMAT);
       Cfm.dwMask = CFM_BOLD;
       Cfm.dwEffects ^= CFE_BOLD;
       m_richEdit.SetSelectionCharFormat(Cfm);
       m_richEdit.SetFocus();
 }
 void CMFCRichEditDlg::OnBnClickedButtonItalic()
 {
       // TODO: Add your control notification handler code here
                                                                                     196
                                                           Microsoft Foundation Classes
CHARFORMAT Cfm;
m_richEdit.GetSelectionCharFormat(Cfm);
       Cfm.cbSize = sizeof(CHARFORMAT);
       Cfm.dwMask = CFM_ITALIC;
       Cfm.dwEffects ^= CFE_ITALIC;
       m_richEdit.SetSelectionCharFormat(Cfm);
       m_richEdit.SetFocus();
 }
 void CMFCRichEditDlg::OnBnClickedButtonUnderline()
 {
       // TODO: Add your control notification handler code here
       CHARFORMAT Cfm;
m_richEdit.GetSelectionCharFormat(Cfm);
       Cfm.cbSize = sizeof(CHARFORMAT);
       Cfm.dwMask = CFM_UNDERLINE;
       Cfm.dwEffects ^= CFE_UNDERLINE;
       m_richEdit.SetSelectionCharFormat(Cfm);
       m_richEdit.SetFocus();
 }
Step 7: When the above code is compiled and executed, you will see the following output.
Now enter text and change its formatting by selecting the text and then click on any of
the three buttons.
                                                                                    197
                                                           Microsoft Foundation Classes
Group Box
A group box is a static control used to set a visible or programmatic group of controls.
The control is a rectangle that groups other controls together. The controls are grouped
by drawing a border around them and displaying the given text in the upper-left corner.
                                                                                    198
                                                             Microsoft Foundation Classes
In the following dialog box, the Group box contains three radio buttons inside.
Spin Button
A Spin Button Control (also known as an up-down control) is a pair of arrow buttons that
the user can click to increment or decrement a value, such as a scroll position or a number
displayed in a companion control. it is represented by CSpinButtonCtrl class.
        Name                                       Description
                         Creates a spin button control and attaches it to a
        Create
                         CSpinButtonCtrl object.
                         Creates a spin button control with the specified Windows
      CreateEx
                         extended styles and attaches it to a CSpinButtonCtrl object.
      GetAccel           Retrieves acceleration information for a spin button control.
       GetBase           Retrieves the current base for a spin button control.
      GetBuddy           Retrieves a pointer to the current buddy window.
       GetPos            Retrieves the current position of a spin button control.
                         Retrieves the upper and lower limits (range) for a spin button
      GetRange
                         control.
      SetAccel           Sets the acceleration for a spin button control.
       SetBase           Sets the base for a spin button control.
      SetBuddy           Sets the buddy window for a spin button control.
       SetPos            Sets the current position for the control.
                                                                                       199
                                                             Microsoft Foundation Classes
SetRange Sets the upper and lower limits (range) for a spin button control.
                                                                                       200
                                                           Microsoft Foundation Classes
Let us look into a simple example of Spin button by creating a new MFC dialog based
application.
Step 1: Add one Spin Control and one Edit control from the Toolbox.
Step 2: Go to the Properties of Spin Control and set the values of Auto Buddy and Set
Buddy Integer to True.
                                                                                    201
                                                             Microsoft Foundation Classes
                                                                                     202
                                                         Microsoft Foundation Classes
Step 3: Add the event handler for UDN_DELTAPOS event for the spin button.
                                                                                 203
                                                           Microsoft Foundation Classes
 BOOL CMFCSpinButtonDlg::OnInitDialog()
 {
      CDialogEx::OnInitDialog();
      // Set the icon for this dialog.     The framework does this automatically
      //   when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                   // Set big icon
      SetIcon(m_hIcon, FALSE);           // Set small icon
      // TODO: Add extra initialization here
      m_spinControl.SetRange(0, 100);
      m_spinControl.SetPos(50);
      m_editControl.SetWindowText(L"50");
      return TRUE;   // return TRUE   unless you set the focus to a control
 }
                                                                                   204
                                                            Microsoft Foundation Classes
              CString str;
              str.Format(L"%d", CurPos);
              // Display the value into the accompanying edit box
              m_editControl.SetWindowText(str);
       }
       *pResult = 0;
 }
Step 6: When the above code is compiled and executed, you will see the following output.
                                                                                    205
                                                                 Microsoft Foundation Classes
Progress Control
A progress bar control is a window that an application can use to indicate the progress
of a lengthy operation. It consists of a rectangle that is gradually filled, from left to right,
with the system highlight color as an operation progresses. It is represented by
CProgressCtrl class.
           Name                                         Description
           Create               Creates a progress bar control and attaches it to a
                                CProgressCtrl object.
          CreateEx              Creates a progress control with the specified Windows
                                extended styles and attaches it to a CProgressCtrl object.
        GetBarColor             Gets the color of the progress indicator bar for the current
                                progress bar control.
        GetBkColor              Gets the background color of the current progress bar.
          GetPos                Gets the current position of the progress bar.
         GetRange               Gets the lower and upper limits of the range of the progress
                                bar control.
          GetState              Gets the state of the current progress bar control.
          GetStep               Retrieves the step increment for the progress bar of the
                                current progress bar control.
                                                                                           206
                                                            Microsoft Foundation Classes
Step 1: Change the ID of the Text control to and remove the caption.
                                                                                      207
                                                          Microsoft Foundation Classes
 BOOL CMFCProgressControlDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
           bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
           ASSERT(bNameValid);
           if (!strAboutMenu.IsEmpty())
           {
                   pSysMenu->AppendMenu(MF_SEPARATOR);
                   pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
           }
    }
    // Set the icon for this dialog.    The framework does this automatically
    //   when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);                  // Set big icon
    SetIcon(m_hIcon, FALSE);           // Set small icon
    return TRUE;   // return TRUE   unless you set the focus to a control
}
                                                                                 209
                                                              Microsoft Foundation Classes
Step 6: When the above code is compiled and executed, you will see the following output.
Progress Bars
Besides the Progress control, Visual C++ provides two other progress-oriented controls:
                                                                                      210
                                                            Microsoft Foundation Classes
                                                                                    211
                                                            Microsoft Foundation Classes
Step 3: Select the Microsoft ProgressBar Control 6.0 and click OK.
Step 4: Select the progress bar and set its Orientation in the Properties Window to 1 –
ccOrientationVertical.
 m_progBarCtrl.SetScrollRange(0,100,TRUE);
 m_progBarCtrl.put_Value(53);
                                                                                    212
                                                               Microsoft Foundation Classes
Step 7: Run this application again and you will see the progress bar in Vertical direction
as well.
Timer
A timer is a non-spatial object that uses recurring lapses of time from a computer or from
your application. To work, every lapse of period, the control sends a message to the
operating system. Unlike most other controls, the MFC timer has neither a button to
represent it nor a class. To create a timer, you simply call the CWnd::SetTimer() method.
This function call creates a timer for your application. Like the other controls, a timer uses
an identifier.
                                                                                          213
                                                           Microsoft Foundation Classes
                                                                                   214
                                                        Microsoft Foundation Classes
Step 6: Click the WM_TIMER field and click the arrow of its combo box. Select <Add>
OnTimer and implement the event.
              strMinutes.Format(_T("0%d"), iMinutes);
       else
              strMinutes.Format(_T("%d"), iMinutes);
       UpdateData(FALSE);
       CDialogEx::OnTimer(nIDEvent);
 }
Step 7: When the above code is compiled and executed, you will see the following output.
                                                                                    216
                                                               Microsoft Foundation Classes
                        Name                                        Description
                                                         Closes the current date and time
                   CloseMonthCal
                                                         picker control.
                                                         Creates the date and time picker
                        Create                           control and attaches it to the
                                                         CDateTimeCtrl object.
                                                         Retrieves information about the
              GetDateTimePickerInfo                      current date and time picker
                                                         control.
                                                         Returns the ideal size of the date
                                                         and time picker control that is
                    GetIdealSize
                                                         required to display the current
                                                         date or time.
                                                         Retrieves the color for a given
                                                         portion of the month calendar
                 GetMonthCalColor
                                                         within the date and time picker
                                                         control.
                                                         Retrieves the CMonthCalCtrl
                  GetMonthCalCtrl                        object associated with the date
                                                         and time picker control.
                                                         Retrieves the font currently used
                                                         by the date and time picker
                  GetMonthCalFont
                                                         control's child month calendar
                                                         control.
                                                         Gets the style of the current date
                 GetMonthCalStyle
                                                         and time picker control.
                                                         Retrieves the current minimum
                                                         and maximum allowed system
                      GetRange
                                                         times for a date and time picker
                                                         control.
                                                         Retrieves the currently selected
                                                         time from a date and time picker
                       GetTime
                                                         control and puts it in a specified
                                                         SYSTEMTIME structure.
                                                         Sets the display of a date and
                      SetFormat                          time picker control in accordance
                                                         with a given format string.
                                                         Sets the color for a given portion
                 SetMonthCalColor                        of the month calendar within a
                                                         date and time picker control.
                                                         Sets the font that the date and
                  SetMonthCalFont                        time picker control's child month
                                                         calendar control will use.
                                                                                         217
                                                           Microsoft Foundation Classes
                                                                                    218
                                             Microsoft Foundation Classes
                                                                     219
                                                       Microsoft Foundation Classes
                                                                               220
                                                         Microsoft Foundation Classes
 void CMFCDateAndTimePickerDlg::OnDtnDatetimechangeDatetimepicker1(NMHDR
 *pNMHDR, LRESULT *pResult)
 {    LPNMDATETIMECHANGE pDTChange =
 reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
      // TODO: Add your control notification handler code here
      GetDlgItemText(IDC_DATETIMEPICKER1, m_strValue);
      UpdateData(FALSE);
      *pResult = 0;
 }
                                                                                 221
                                                              Microsoft Foundation Classes
Step 7: When you run the above application, you see the following output. Select any
date, it will display on the Static Text Control.
Picture
If you need to display a picture for your application, Visual C++ provides a special control
for that purpose.
Let us look into a simple example by creating a new MFC dialog based application.
                                                                                        222
                                                             Microsoft Foundation Classes
Step 1: Right-click on the dialog in the designer window and select Insert ActiveX Control.
Step 2: Select the Microsoft Picture Click Control and click OK.
                                                                                       223
                                                              Microsoft Foundation Classes
Step 3: Resize the Picture control and in the Properties window, click the Picture field.
Step 4: Browse the folder that contains Pictures. Select any picture.
Step 5: Run this application and you will see the following output.
                                                                                        224
                                                               Microsoft Foundation Classes
Image Editor
The Image editor has an extensive set of tools for creating and editing images, as well
as features to help you create toolbar bitmaps. In addition to bitmaps, icons, and cursors,
you can edit images in GIF or JPEG format using commands on the Image menu and tools
on the Image Editor Toolbar.
                                                                                       225
                                                            Microsoft Foundation Classes
Step 2: Select Bitmap and click New. It will open the Image editor.
                                                                                    226
                                                           Microsoft Foundation Classes
Step 3: Design your bitmap image          in   Image   editor   and   change   its   ID    to
IDB_BITMAP_START as shown above.
Step 4: Add a button to your dialog box and also add a control Variable m_buttonStart
for that button.
Step 5: Add a bitmap variable to your header file. You will now see the following two
variables.
 CBitmap m_bitmapStart;
 CButton m_buttonStart;
 m_bitmapStart.LoadBitmap(IDB_BITMAP_START);
 HBITMAP hBitmap = (HBITMAP)m_bitmapStart.GetSafeHandle();
 m_buttonStart.SetBitmap(hBitmap);
Step 7: When the above code is compiled and executed, you will see the following output.
                                                                                          227
                                                              Microsoft Foundation Classes
Slider Controls
A Slider Control (also known as a trackbar) is a window containing a slider and optional
tick marks. When the user moves the slider, using either the mouse or the direction keys,
the control sends notification messages to indicate the change. There are two types of
sliders — horizontal and vertical. It is represented by CSliderCtrl class.
                 Name                                        Description
               ClearSel                    Clears the current selection in a slider control.
               ClearTics                   Removes the current tick marks from a slider
                                           control.
                 Create                    Creates a slider control and attaches it to a
                                           CSliderCtrl object.
               CreateEx                    Creates a slider control with the specified
                                           Windows extended styles and attaches it to a
                                           CSliderCtrl object.
               GetBuddy                    Retrieves the handle to a slider control buddy
                                           window at a given location.
           GetChannelRect                  Retrieves the size of the slider control's
                                           channel.
              GetLineSize                  Retrieves the line size of a slider control.
              GetNumTics                   Retrieves the number of tick marks in a slider
                                           control.
                                                                                         228
                                                             Microsoft Foundation Classes
Let us look into a simple example by creating a new MFC dialog based project.
Step 1: Once the project is created you will see the TODO line which is the Caption of Text
Control. Remove the Caption and set its ID to IDC_STATIC_TXT.
Step 2: Add a value variable m_strSliderVal for the Static Text control.
                                                                                        229
Microsoft Foundation Classes
                        230
                                                    Microsoft Foundation Classes
                                                                            231
                                                          Microsoft Foundation Classes
                                                                                  232
                                                               Microsoft Foundation Classes
Step 8: Scroll down to "WM_HSCROLL" and click on the drop-down menu. Click "<Add>
OnHScroll".
Step 9: Initialize the Slider and Static Text control inside the OnInitDialog() function.
 BOOL CMFCSliderControlDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.      The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                     // Set big icon
       SetIcon(m_hIcon, FALSE);             // Set small icon
       m_sliderCtrl.SetPos(0);
       m_strSliderVal.Format(_T("%d"), 0);
       return TRUE;    // return TRUE   unless you set the focus to a control
 }
Step 10: Add the following code inside the function code block for OnVScroll()
Step 11: When the above code is compiled and executed, you will see the following output.
                                                                                     234
                                                               Microsoft Foundation Classes
Scrollbars
A scrollbar is a graphical control element with which continuous text, pictures or anything
else can be scrolled in two directions along a control by clicking an arrow. This control can
assume one of two directions — horizontal or vertical. It is represented by CScrollBar
class.
                Name                                        Description
                Create                   Creates the Windows scroll bar and attaches it to
                                         the CScrollBar object.
           EnableScrollBar               Enables or disables one or both arrows of a scroll
                                         bar.
          GetScrollBarInfo               Retrieves information about the scroll bar using
                                         a SCROLLBARINFO structure.
            GetScrollInfo                Retrieves information about the scroll bar.
           GetScrollLimit                Retrieves the limit of the scroll bar
            GetScrollPos                 Retrieves the current position of a scroll box.
           GetScrollRange                Retrieves the current minimum and maximum
                                         scroll-bar positions for the given scroll bar.
            SetScrollInfo                Sets information about the scroll bar.
            SetScrollPos                 Sets the current position of a scroll box.
           SetScrollRange                Sets minimum and maximum position values for
                                         the given scroll bar.
           ShowScrollBar                 Shows or hides a scroll bar.
                                                                                         235
                                                         Microsoft Foundation Classes
Step 1: To add either horizontal or vertical scrollbar, you need to set the following
highlighted properties of the dialog box to True.
                                                                                 236
                                                              Microsoft Foundation Classes
Step 2: When you run the above application, you will see that both horizontal and vertical
scrollbars have been added.
Tree Control
A Tree View Control is a window that displays a hierarchical list of items, such as the
headings in a document, the entries in an index, or the files and directories on a disk. Each
item consists of a label and an optional bitmapped image, and each item can have a list
of subitems associated with it. By clicking an item, the user can expand and collapse the
associated list of subitems. It is represented by CTreeCtrl class.
             Name                                        Description
Create                             Creates a tree view control and attaches it to a
                                   CTreeCtrl object.
CreateDragIm                       Creates a dragging bitmap for the specified tree view
age                                item.
CreateEx                           Creates a tree control with the specified Windows
                                   extended styles and attaches it to a CTreeCtrl object.
DeleteAllItem                      Deletes all items in a tree view control.
s
DeleteItem                         Deletes a new item in a tree view control.
EditLabel                          Edits a specified tree view item in-place.
                                                                                         237
                                              Microsoft Foundation Classes
                                                                         238
                                            Microsoft Foundation Classes
                                                                      239
                                                             Microsoft Foundation Classes
Let us look into a simple example by creating a new MFC dialog based project.
Step 1: Once the project is created you will see the TODO line, which is the Caption of
Text Control. Remove the Caption and set its ID to IDC_STATIC_TXT.
Step 2: Add a value variable m_strTree for the Static Text control.
                                                                                        240
Microsoft Foundation Classes
                        241
                                                            Microsoft Foundation Classes
Step 4: On the dialog box, click the Tree Control to select it. On the Properties window,
set the Has Buttons, the Has Lines, the Lines At Root, the Client Edge and the Modal Frame
properties to True.
                                                                                      242
                                                                   Microsoft Foundation Classes
 BOOL CMFCTreeControlDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.       The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                      // Set big icon
       SetIcon(m_hIcon, FALSE);              // Set small icon
                                                                                           243
                                                        Microsoft Foundation Classes
    m_treeCtrl.InsertItem(L"SD-397", hCar);
    m_treeCtrl.InsertItem(L"JU-538", hCar);
    m_treeCtrl.InsertItem(L"DI-285", hCar);
    m_treeCtrl.InsertItem(L"AK-830", hCar);
    hCar = m_treeCtrl.InsertItem(L"Compact", hItem);
    m_treeCtrl.InsertItem(L"HG-490", hCar);
    m_treeCtrl.InsertItem(L"PE-473", hCar);
    hCar = m_treeCtrl.InsertItem(L"Standard", hItem);
    m_treeCtrl.InsertItem(L"SO-398", hCar);
    m_treeCtrl.InsertItem(L"DF-438", hCar);
    m_treeCtrl.InsertItem(L"IS-833", hCar);
    hCar = m_treeCtrl.InsertItem(L"Full Size", hItem);
    m_treeCtrl.InsertItem(L"PD-304", hCar);
    hCar = m_treeCtrl.InsertItem(L"Mini Van", hItem);
    m_treeCtrl.InsertItem(L"ID-497", hCar);
    m_treeCtrl.InsertItem(L"RU-304", hCar);
    m_treeCtrl.InsertItem(L"DK-905", hCar);
    hCar = m_treeCtrl.InsertItem(L"SUV", hItem);
    m_treeCtrl.InsertItem(L"FE-948", hCar);
    m_treeCtrl.InsertItem(L"AD-940", hCar);
    hCar = m_treeCtrl.InsertItem(L"Truck", hItem);
    m_treeCtrl.InsertItem(L"HD-394", hCar);
    return TRUE;   // return TRUE   unless you set the focus to a control
}
                                                                                244
                                                              Microsoft Foundation Classes
Step 7: When the above code is compiled and executed, you will see the following output.
List Control
Encapsulates the functionality of a List View Control, which displays a collection of items
each consisting of an icon (from an image list) and a label. It is represented by CListCtrl
class. A list control consists of using one of four views to display a list of items.
       Icons
       Small Icons
       List
       Report
                 Name                                       Description
                                      Determines the width and height required to display
       ApproximateViewRect
                                      the items of a list view control.
             Arrange                  Aligns items on a grid.
          CancelEditLabel             Cancels item text editing operation.
                                      Creates a list control and attaches it to a CListCtrl
                 Create
                                      object.
        CreateDragImage               Creates a drag image list for a specified item.
                                      Creates a list control with the specified Windows
                CreateEx
                                      extended styles and attaches it to a CListCtrl object.
                                                                                        245
                                                        Microsoft Foundation Classes
                                                                                   246
                                                Microsoft Foundation Classes
                                                                           247
                                               Microsoft Foundation Classes
                                                                         248
                                                               Microsoft Foundation Classes
Let us look into a simple example by creating a new MFC dialog based application.
Step 1: Delete the TODO line and drag one List Control.
Step 2: In the Properties Window, you will see the different options in View dropdown list.
                                                                                          249
                                                            Microsoft Foundation Classes
                                                                                    250
                                                             Microsoft Foundation Classes
 BOOL CMFCListControlDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.       The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                      // Set big icon
       SetIcon(m_hIcon, FALSE);             // Set small icon
int nItem;
    return TRUE;   // return TRUE   unless you set the focus to a control
}
                                                                               252
                                                           Microsoft Foundation Classes
Step 6: When the above code is compiled and executed, you will see the following output.
                                                                                    253
              12. MFC - Messages and Events                 Microsoft Foundation Classes
An application is made of various objects. Most of the time, more than one application is
running on the computer and the operating system is constantly asked to perform some
assignments. Because there can be so many requests presented unpredictably, the
operating system leaves it up to the objects to specify what they want, when they want
it, and what behavior or result they expect.
Overview
      The Microsoft Windows operating system cannot predict what kinds of requests
       one object would need to be taken care of and what type of assignment another
       object would need.
 To manage all these assignments and requests, the objects send messages.
 Each object has the responsibility to decided what message to send and when.
      To make a distinction between the two, a message's name usually starts with
       WM_ which stands for Window Message.
Map of Messages
Since Windows is a message-oriented operating system, a large portion of programming
for the Windows environment involves message handling. Each time an event such as a
keystroke or mouse click occurs, a message is sent to the application, which must then
handle the event.
      For the compiler to manage messages, they should be included in the class
       definition.
      The DECLARE_MESSAGE_MAP macro should be provided at the end of the class
       definition as shown in the following code.
                                                                                     254
                                                           Microsoft Foundation Classes
#include <afxwin.h>
class CMainFrame : public CFrameWnd
{
public:
        CMainFrame();
protected:
        DECLARE_MESSAGE_MAP()
};
CMainFrame::CMainFrame()
{
        // Create the window's frame
        Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW,
              CRect(120, 100, 700, 480), NULL);
}
class CMessagesApp : public CWinApp
{
public:
        BOOL InitInstance();
};
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
END_MESSAGE_MAP()
BOOL CMessagesApp::InitInstance()
{
        m_pMainWnd = new CMainFrame;
        m_pMainWnd->ShowWindow(SW_SHOW);
        m_pMainWnd->UpdateWindow();
        return TRUE;
}
CMessagesApp theApp;
                                                                                   255
                                                              Microsoft Foundation Classes
Step 1: To create an MFC project, right-click on the project and select Properties.
Step 3: Select the ‘Use MFC in Shared DLL’ option in Project Defaults section and click
OK.
Step 5: Right-click on your Project and select Add -> New Item.
                                                                                      256
                                                         Microsoft Foundation Classes
 #include <afxwin.h>
 class CMainFrame : public CFrameWnd
 {
 public:
       CMainFrame();
 protected:
       DECLARE_MESSAGE_MAP()
 };
 CMainFrame::CMainFrame()
 {
       // Create the window's frame
       Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW,
              CRect(120, 100, 700, 480), NULL);
 }
 class CMessagesApp : public CWinApp
 {
 public:
                                                                                 257
                                                           Microsoft Foundation Classes
        BOOL InitInstance();
 };
 BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
 END_MESSAGE_MAP()
 BOOL CMessagesApp::InitInstance()
 {
        m_pMainWnd = new CMainFrame;
        m_pMainWnd->ShowWindow(SW_SHOW);
        m_pMainWnd->UpdateWindow();
        return TRUE;
 }
 CMessagesApp theApp;
Windows Messages
There are different types of Windows messages like creating a window, showing a window
etc. Here are some of the commonly used windows messages.
                                                                            259
                                                  Microsoft Foundation Classes
                                                                            260
                                                        Microsoft Foundation Classes
WM_CREATE: When an object, called a window, is created, the frame that creates the
objects sends a message identified as ON_WM_CREATE.
 BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
       ON_WM_CREATE()
 END_MESSAGE_MAP()
                                                                                261
                                                             Microsoft Foundation Classes
Step 4: Now your *.cpp file will look like as shown in the following code.
 #include <afxwin.h>
 class CMainFrame : public CFrameWnd
 {
 public:
       CMainFrame();
 protected:
       afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
       DECLARE_MESSAGE_MAP()
 };
 CMainFrame::CMainFrame()
 {
       // Create the window's frame
       Create(NULL, L"MFC Messages Demo", WS_OVERLAPPEDWINDOW,
              CRect(120, 100, 700, 480), NULL);
 }
 class CMessagesApp : public CWinApp
 {
 public:
       BOOL InitInstance();
 };
 BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
       ON_WM_CREATE()
 END_MESSAGE_MAP()
 int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
 {
       // Call the base class to create the window
       if (CFrameWnd::OnCreate(lpCreateStruct) == 0)
       {
              // If the window was successfully created, let the user know
              MessageBox(L"The window has been created!!!");
              // Since the window was successfully created, return 0
              return 0;
       }
       // Otherwise, return -1
       return -1;
 }
                                                                                     262
                                                              Microsoft Foundation Classes
 BOOL CMessagesApp::InitInstance()
 {     m_pMainWnd = new CMainFrame;
       m_pMainWnd->ShowWindow(SW_SHOW);
       m_pMainWnd->UpdateWindow();
       return TRUE;
 }
 CMessagesApp theApp;
Step 5: When the above code is compiled and executed, you will see the following output.
Step 6: When you click OK, it will display the main window.
                                                                                      263
                                                             Microsoft Foundation Classes
Command Messages
One of the main features of a graphical application is to present Windows controls and
resources that allow the user to interact with the machine. Examples of controls that we
will learn are buttons, list boxes, combo boxes, etc.
One type of resource we introduced in the previous lesson is the menu. Such controls and
resources can initiate their own messages when the user clicks them. A message that
emanates from a Windows control or a resource is called a command message.
To provide your application the ability to create a new document, the CWinApp class
provides the OnFileNew() method.
 BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
       ON_COMMAND(ID_FILE_NEW, CMainFrame::OnFileNew)
 END_MESSAGE_MAP()
 void CMainFrame::OnFileNew()
 {
       // Create New file
 }
Keyboard Messages
A keyboard is a hardware object attached to the computer. By default, it is used to enter
recognizable symbols, letters, and other characters on a control. Each key on the keyboard
displays a symbol, a letter, or a combination of those, to give an indication of what the
key could be used for. The user typically presses a key, which sends a signal to a program.
Each key has a code that the operating system can recognize. This code is known as the
virtual key code. The virtual key codes are as follows:
     Constant/value                                Description
      VK_LBUTTON            Left mouse button
      VK_RBUTTON            Right mouse button
       VK_CANCEL            Control-break processing
      VK_MBUTTON            Middle mouse button (three-button mouse)
        VK_BACK             BACKSPACE key
         VK_TAB             TAB key
        VK_CLEAR            CLEAR key
                                                                                       264
                                      Microsoft Foundation Classes
                                                              265
                                                        Microsoft Foundation Classes
 BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
       ON_WM_CREATE()
       ON_WM_KEYDOWN()
 END_MESSAGE_MAP()
                                                                                266
                                                             Microsoft Foundation Classes
Step 3: When the above code is compiled and executed, you will see the following output.
Step 4: When you press Enter, it will display the following message.
Mouse Messages
The mouse is another object that is attached to the computer allowing the user to interact
with the machine.
                                                                                      267
                                                           Microsoft Foundation Classes
Step 1: Add the following two functions in CMainFrame class definition as shown in the
following code.
 BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
         ON_WM_KEYDOWN()
         ON_WM_LBUTTONDOWN()
         ON_WM_RBUTTONUP()
 END_MESSAGE_MAP()
                                                                                   268
                                                            Microsoft Foundation Classes
Step 4: When you run this application, you will see the following output.
Step 5: When you click OK, you will see the following message.
Step 6: Right-click on this window. Now, when you release the right button of the mouse,
it will display the following message.
                                                                                    269
                   13. MFC - ActiveX Control                 Microsoft Foundation Classes
An ActiveX control container is a parent program that supplies the environment for an
ActiveX (formerly OLE) control to run.
      ActiveX is not a programming language, but rather a set of rules for how
       applications should share information.
Let us look into simple example of add ActiveX controls in your MFC dialog based
application.
Step 1: Right-click on the dialog in the designer window and select Insert ActiveX Control.
Step 2: Select the Microsoft Picture Clip Control and click OK.
                                                                                       270
                                                              Microsoft Foundation Classes
Step 3: Resize the Picture control and in the Properties window, click the Picture field.
Step 4: Browse the folder that contains Pictures. Select any picture.
Step 5: When you run this application, you will see the following output.
                                                                                        271
                                                            Microsoft Foundation Classes
                                                                                    272
                                                            Microsoft Foundation Classes
                                                                                    273
                                                          Microsoft Foundation Classes
Step 4: Select the progress bar and set its Orientation in the Properties Window to 1 –
ccOrientationVertical.
 m_progBarCtrl.SetScrollRange(0,100,TRUE);
 m_progBarCtrl.put_Value(53);
                                                                                   274
                                                          Microsoft Foundation Classes
Step 7: When you run this application again, you will see the progress bar in Vertical
direction as well.
                                                                                  275
                       14. MFC - File System                   Microsoft Foundation Classes
In this chapter, we will discuss the various components of the file system.
Drives
A drive is a physical device attached to a computer so it can store information. A logical
disk, logical volume or virtual disk (VD or vdisk for short) is a virtual device that provides
an area of usable storage capacity on one or more physical disk drive(s) in a computer
system. A drive can be a hard disk, a CD ROM, a DVD ROM, a flash (USB) drive, a memory
card, etc.
One of the primary operations you will want to perform is to get a list of drives on the
computer.
Let us look into a simple example by creating a new MFC dialog based application.
Step 1: Drag one button from the toolbox, change its Caption to Get Drives Info.
Step 2: Remove the Caption of Static control (TODO line) and change its ID to
IDC_STATIC_TEXT.
                                                                                          276
                                                           Microsoft Foundation Classes
Step 4: Select the BN_CLICKED message type and click the Add and Edit button.
                                                                                   277
                                                                Microsoft Foundation Classes
Step 5: Add the value variable m_strDrives for Static Text control.
                                                                                           278
                                                           Microsoft Foundation Classes
Step 6: When the above code is compiled and executed, you will see the following output.
Step 7: When you click the button, you can see all the drives on your computer.
                                                                                    279
                                                               Microsoft Foundation Classes
Directories
In computing, a directory is a file system cataloging structure which contains references
to other computer files, and possibly other directories. Directory is a physical location. It
can handle operations not available on a drive.
Let us look into a simple example by creating a new MFC dialog based application
Step 1: Drag three buttons from the toolbox. Change their Captions to Create Directory,
Delete Directory and Move Directory.
Step 5: To create a directory, you can call the CreateDirectory() method of the Win32
library.
Step 6: Here is the Create button event handler implementation in which we will create
one directory and then two more sub directories.
                                                                                         280
                                                            Microsoft Foundation Classes
 void CMFCDirectoriesDemoDlg::OnBnClickedButtonCreate()
 {
       // TODO: Add your control notification handler code here
       SECURITY_ATTRIBUTES saPermissions;
       saPermissions.nLength = sizeof(SECURITY_ATTRIBUTES);
       saPermissions.lpSecurityDescriptor = NULL;
       saPermissions.bInheritHandle = TRUE;
Step 7: To get rid of a directory, you can call the RemoveDirectory() function of the
Win32 library. Here is the implementation of delete button event handler.
 void CMFCDirectoriesDemoDlg::OnBnClickedButtonDelete()
 {
       // TODO: Add your control notification handler code here
       if (RemoveDirectory(L"D:\\MFCDirectoryDEMO\\Dir1") == TRUE)
              AfxMessageBox(L"The directory has been     deleted");
 }
Step 8: If you want to move a directory, you can also call the same MoveFile() function.
Here is the implementation of move button event handler in which we will create first new
directory and then move the Dir2 to that directory.
 void CMFCDirectoriesDemoDlg::OnBnClickedButtonMove()
 {
       // TODO: Add your control notification handler code here
       CreateDirectory(L"D:\\MFCDirectory", NULL)
       if (MoveFile(L"D:\\MFCDirectoryDEMO\\Dir1",
              L"D:\\MFCDirectory\\Dir1") == TRUE)
              AfxMessageBox(L"The directory has been moved");
 }
                                                                                     281
                                                             Microsoft Foundation Classes
Step 9: When the above code is compiled and executed, you will see the following output.
Step 10: When you click the Create Directory button, it will create these directories.
                                                                                         282
                                                             Microsoft Foundation Classes
Step 11: When you click on Delete Directory button, it will delete the Dir1.
                                                                                     283
                                                              Microsoft Foundation Classes
File Processing
Most of the file processing in an MFC application is performed in conjunction with a class
named CArchive. The CArchive class serves as a relay between the application and the
medium used to either store data or make it available. It allows you to save a complex
network of objects in a permanent binary form (usually disk storage) that persists after
those objects are deleted.
                 Name                                        Description
                                           Closes an archive without throwing an
                  Abort
                                           exception.
                                           Flushes unwritten data and disconnects from
                  Close
                                           the CFile.
                                           Flushes unwritten data from the archive
                  Flush
                                           buffer.
                 GetFile                   Gets the CFile object pointer for this archive.
                                           Called from the Serialize function to
           GetObjectSchema                 determine the version of the object that is
                                           being deserialized.
                                           Determines whether the buffer has been
            IsBufferEmpty                  emptied during a Windows Sockets receive
                                           process.
               IsLoading                   Determines whether the archive is loading.
               IsStoring                   Determines whether the archive is storing.
                                           Places objects in the map that are not
               MapObject                   serialized to the file, but that are available for
                                           subobjects to reference.
                  Read                     Reads raw bytes.
                                           Reads a class reference previously stored with
               ReadClass
                                           WriteClass.
              ReadObject                   Calls an object's Serialize function for loading.
              ReadString                   Reads a single line of text.
                                           Reads or writes the class reference to the
             SerializeClass                CArchive object depending on the direction of
                                           the CArchive.
                                           Sets the size to which the load array grows.
            SetLoadParams                  Must be called before any object is loaded or
                                           before MapObject or ReadObject is called.
                                           Sets the object schema stored in the archive
           SetObjectSchema
                                           object.
                                           Sets the hash table size and the block size of
            SetStoreParams                 the map used to identify unique objects during
                                           the serialization process.
                  Write                    Writes raw bytes.
                                           Writes a reference to the CRuntimeClass to
               WriteClass
                                           the CArchive.
              WriteObject                  Calls an object's Serialize function for storing.
              WriteString                  Writes a single line of text.
                                                                                         284
                                                                 Microsoft Foundation Classes
            Name                                       Description
         operator <<              Stores objects and primitive types to the archive.
         operator >>              Loads objects and primitive types from the archive.
Let us look into a simple example by creating a new MFC dialog based application.
Step 1: Drag one edit control and two buttons as shown in the following snapshot.
Step 2: Add control variable m_edtiCtrl and value variable m_strEdit for edit control.
Step 3: Add click event handler for Open and Save buttons.
 void CMFCFileProcessingDlg::OnBnClickedButtonOpen()
 {
       // TODO: Add your control notification handler code here
       UpdateData(TRUE);
CFile file;
       file.Open(L"ArchiveText.rpr", CFile::modeRead);
       if(file)
       CArchive ar(&file, CArchive::load);
                                                                                         285
                                                      Microsoft Foundation Classes
ar >> m_strEdit;
     ar.Close();
     file.Close();
     UpdateData(FALSE);
}
void CMFCFileProcessingDlg::OnBnClickedButtonSave()
{
     // TODO: Add your control notification handler code here
     UpdateData(TRUE);
     if (m_strEdit.GetLength() == 0)
     {
           AfxMessageBox(L"You must enter the name of the text.");
           return;
     }
CFile file;
ar << m_strEdit;
     ar.Close();
     file.Close();
}
                                                                              286
                                                            Microsoft Foundation Classes
Step 5: When the above code is compiled and executed, you will see the following output.
Step 6: Write something and click Save. It will save the data in binary format.
Step 7: Remove the test from edit control. As you click Open, observe that the same text
is loaded again.
                                                                                    287
                      15. MFC - Standard I/O                    Microsoft Foundation Classes
The MFC library provides its own version of file processing. This is done through a class
named CStdioFile. The CStdioFile class is derived from CFile. It can handle the reading and
writing of Unicode text files as well as ordinary multi-byte text files.
 CStdioFile();
 CStdioFile(CAtlTransactionManager* pTM);
 CStdioFile(FILE* pOpenStream);
 CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags);
 CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM);
           Name                                        Description
                              Overloaded. Open is designed for use with the default
           Open
                              CStdioFile constructor (Overrides CFile::Open).
       ReadString             Reads a single line of text.
          Seek                Positions the current file pointer.
       WriteString            Writes a single line of text.
Let us look into a simple example again by creating a new MFC dialog based application.
Step 1: Drag one edit control and two buttons as shown in the following snapshot.
                                                                                        288
                                                             Microsoft Foundation Classes
                                                                                     289
                                                             Microsoft Foundation Classes
Step 3: Add click event handler for Open and Save buttons.
 void CMFCStandardIODlg::OnBnClickedButtonOpen()
 {
      // TODO: Add your control notification handler code here
      UpdateData(TRUE);
      CStdioFile file;
      file.Open(L"D:\\MFCDirectoryDEMO\\test.txt", CFile::modeRead |
 CFile::typeText);
      file.ReadString(m_strEditCtrl);
      file.Close();
      UpdateData(FALSE);
 }
void CMFCStandardIODlg::OnBnClickedButtonSave()
                                                                                     290
                                                           Microsoft Foundation Classes
 {
       // TODO: Add your control notification handler code here
       UpdateData(TRUE);
       CStdioFile file;
       if (m_strEditCtrl.GetLength() == 0)
       {
              AfxMessageBox(L"You must specify the text.");
              return;
       }
      file.Open(L"D:\\MFCDirectoryDEMO\\test.txt", CFile::modeCreate |
 CFile::modeWrite | CFile::typeText);
       file.WriteString(m_strEditCtrl);
       file.Close();
 }
Step 5: When the above code is compiled and executed, you will see the following output.
                                                                                    291
                                                              Microsoft Foundation Classes
Step 6: Write something and click Save. It will save the data in *.txt file.
                                                                                      292
                                                                 Microsoft Foundation Classes
Step 7: If you look at the location of the file, you will see that it contains the test.txt file.
Step 8: Now, close the application. Run the same application. When you click Open, the
same text loads again.
Step 9: It starts by opening the file, reading the file, followed by updating the Edit Control.
                                                                                            293
                  16. MFC - Document View                   Microsoft Foundation Classes
The parts that compose the Document/View architecture are a frame, one or more
documents, and the view. Put together, these entities make up a usable application.
View
A view is the platform the user is working on to do his or her job. To let the user do
anything on an application, you must provide a view, which is an object based on the
CView class. You can either directly use one of the classes derivedfrom CView or you can
derive your own custom class from CView or one of its child classes.
Document
A document is similar to a bucket. For a computer application, a document holds the
user's data. To create the document part of this architecture, you must derive an object
from the CDocument class.
Frame
As the name suggests, a frame is a combination of the building blocks, the structure, and
the borders of an item. A frame gives "physical" presence to a window. It also defines the
location of an object with regards to the Windows desktop.
                                                                                      294
                                                          Microsoft Foundation Classes
Let us look into a simple example of single document interface or SDI by creating a new
MFC dialog based application.
Step 1: Let us create a new MFC Application MFCSDIDemo with below mentioned
settings.
Step 2: Select Single document from the Application type and MFC standard from Project
Style.
                                                                                   295
                                                            Microsoft Foundation Classes
Step 4: Once the project is created, run the application and you will see the following
output.
Let us look into a simple example of single document interface or SDI by creating a new
MFC dialog based application.
                                                                                      296
                                                          Microsoft Foundation Classes
Step 1: Let us create a new MFC Application MFCMDIDemo with below mentioned
settings.
Step 2: Select Single document from the Application type and MFC standard from Project
Style.
                                                                                  297
                                                           Microsoft Foundation Classes
Step 4: Once the project is created, run the application and you will see the following
output.
Step 5: When you click on File -> New menu option, it will create another child window
as shown in the following snapshot.
                                                                                   298
                                                          Microsoft Foundation Classes
Step 6: In Multiple Document Interface (MDI) applications, there is one main frame per
application. In this case, a CMDIFrameWnd, and one CMDIChildWnd derived child frame
for each document.
                                                                                  299
                             17. MFC - Strings               Microsoft Foundation Classes
Strings are objects that represent sequences of characters. The C-style character string
originated within the C language and continues to be supported within C++.
      A null-terminated string contains the characters that comprise the string followed
       by a null.
 char word[12] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'
 };
Microsoft Foundation Class (MFC) library provides a class to manipulate string called
CString. Following are some important features of CString.
 CString provides functions and operators using a syntax similar to that of Basic.
                   Method                                   Description
                   CString                    Constructs CString objects in various ways
        Method                                     Description
       GetLength          Returns the number of characters in a CString object.
        IsEmpty           Tests whether a CString object contains no characters.
         Empty            Forces a string to have 0 length.
         GetAt            Returns the character at a specified position.
         SetAt            Sets a character at a specified position.
                                                                                      300
                                                                 Microsoft Foundation Classes
               Method                                      Description
              Compare                      Compares two strings (case sensitive).
           CompareNoCase                   Compares two strings (case insensitive).
             Method                                         Description
                                       Extracts the middle part of a string (like the Basic
               Mid
                                       MID$ function).
                                       Extracts the left part of a string (like the Basic LEFT$
               Left
                                       function).
                                       Extracts the right part of a string (like the Basic
              Right
                                       RIGHT$ function).
                                       Extracts a substring that contains only the characters
         SpanIncluding
                                       in a set.
                                       Extracts a substring that contains only the characters
         SpanExcluding
                                       not in a set.
            Method                                      Description
                                  Converts all the characters in this string to uppercase
          MakeUpper
                                  characters.
                                  Converts all the characters in this string to lowercase
          MakeLower
                                  characters.
         MakeReverse              Reverses the characters in this string.
            Format                Format the string as sprintf does.
           TrimLeft               Trim leading white-space characters from the string.
          TrimRight               Trim trailing white-space characters from the string.
          Method                                       Description
           Find                 Finds a character or substring inside a larger string.
        ReverseFind             Finds a character inside a larger string; starts from the
                                end.
         FindOneOf              Finds the first matching character from a set.
                      Method                                     Description
                                                   Returns a pointer to the characters in
                  GetBuffer
                                                   the CString.
                                                   Returns a pointer to the characters in
             GetBufferSetLength                    the CString, truncating to the specified
                                                   length.
                                                   Releases control of the buffer returned
                ReleaseBuffer
                                                   by GetBuffer.
                                                                                           301
                                                             Microsoft Foundation Classes
                Method                                  Description
            AllocSysString          Allocates a BSTR from CString data.
                                    Sets an existing BSTR object with data from a
            SetSysString
                                    CString object.
                                    Loads an existing CString object from a Windows CE
             LoadString
                                    resource.
Create String
You can create a string by either using a string literal or creating an instance of CString
class.
 BOOL CMFCStringDemoDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.       The framework does this automatically
       //    when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                     // Set big icon
       SetIcon(m_hIcon, FALSE);            // Set small icon
       m_strText.Append(string1 + L"\n");
       m_strText.Append(string2);
UpdateData(FALSE);
       return TRUE;    // return TRUE   unless you set the focus to a control
 }
                                                                                       302
                                                           Microsoft Foundation Classes
When the above code is compiled and executed, you will see the following output.
Empty String
You can create an empty string by either using an empty string literal or by using
CString::Empty() method. You can also check whether a string is empty or not using
Boolean property isEmpty.
 BOOL CMFCStringDemoDlg::OnInitDialog()
 {
      CDialogEx::OnInitDialog();
      // Set the icon for this dialog.     The framework does this automatically
      //   when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                   // Set big icon
      SetIcon(m_hIcon, FALSE);           // Set small icon
                                                                                   303
                                                          Microsoft Foundation Classes
string2.Empty();
      if(string1.IsEmpty())
             m_strText.Append(L"String1 is empty\n");
      else
             m_strText.Append(string1 + L"\n");
      if(string2.IsEmpty())
             m_strText.Append(L"String2 is empty");
      else
             m_strText.Append(string2);
UpdateData(FALSE);
      return TRUE;   // return TRUE   unless you set the focus to a control
 }
When the above code is compiled and executed you will see the following output.
                                                                                  304
                                                           Microsoft Foundation Classes
String Concatenation
To concatenate two or more strings, you can use + operator to concatenate two strings or
a CString::Append() method.
 BOOL CMFCStringDemoDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.    The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                   // Set big icon
       SetIcon(m_hIcon, FALSE);           // Set small icon
UpdateData(FALSE);
       return TRUE;   // return TRUE   unless you set the focus to a control
 }
                                                                                    305
                                                          Microsoft Foundation Classes
When the above code is compiled and executed you will see the following output.
String Length
To find the length of the string you can use the CString::GetLength() method, which
returns the number of characters in a CString object.
 BOOL CMFCStringDemoDlg::OnInitDialog()
 {
      CDialogEx::OnInitDialog();
      // Set the icon for this dialog.     The framework does this automatically
      //   when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                   // Set big icon
      SetIcon(m_hIcon, FALSE);           // Set small icon
UpdateData(FALSE);
      return TRUE;   // return TRUE   unless you set the focus to a control
 }
When the above code is compiled and executed you will see the following output.
                                                                                  307
                                                           Microsoft Foundation Classes
String Comparison
To compare two strings variables you can use == operator
 BOOL CMFCStringDemoDlg::OnInitDialog()
 {
      CDialogEx::OnInitDialog();
      // Set the icon for this dialog.      The framework does this automatically
      //     when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                    // Set big icon
      SetIcon(m_hIcon, FALSE);            // Set small icon
      if (string1 == string2)
               m_strText = "string1 and string1 are same\n";
      else
               m_strText = "string1 and string1 are not same\n";
      if (string3 == string4)
               m_strText += "string3 and string4 are same";
      else
               m_strText += "string3 and string4 are not same";
UpdateData(FALSE);
      return TRUE;     // return TRUE   unless you set the focus to a control
 }
                                                                                    308
                                                          Microsoft Foundation Classes
When the above code is compiled and executed you will see the following output.
                                                                                  309
                            18. MFC - CArray                    Microsoft Foundation Classes
CArray is a collection that is best used for data that is to be accessed in a random or non
sequential manner. CArray class supports arrays that are like C arrays, but can
dynamically shrink and grow as necessary.
      You can decide whether to fix the upper bound or enable the array to expand
       when you add elements past the current bound.
      Memory is allocated contiguously to the upper bound, even if some elements are
       null.
               Name                                           Description
                                          Adds an element to the end of the array; grows the
                Add
                                          array if necessary.
                                          Appends another array to the array; grows the
              Append
                                          array if necessary
                                          Copies another array to the array; grows the array
                Copy
                                          if necessary.
                                          Returns a temporary reference to the element
             ElementAt
                                          pointer within the array.
                                          Frees all unused memory above the current upper
             FreeExtra
                                          bound.
              GetAt                       Returns the value at a given index.
             GetCount                     Gets the number of elements in this array.
                                          Allows access to elements in the array. Can be
              GetData
                                          NULL.
            GetSize                       Gets the number of elements in this array.
         GetUpperBound                    Returns the largest valid index.
                                          Inserts an element (or all the elements in another
              InsertAt
                                          array) at a specified index.
             IsEmpty                      Determines whether the array is empty.
            RemoveAll                     Removes all the elements from this array.
            RemoveAt                      Removes an element at a specific index.
                                          Sets the value for a given index; array not allowed
               SetAt
                                          to grow.
                                          Sets the value for a given index; grows the array
            SetAtGrow
                                          if necessary.
                                          Sets the number of elements to be contained in
              SetSize
                                          this array.
                                                                                          310
                                                               Microsoft Foundation Classes
Add items
To add an item you can use CArray::Add() function. It adds an item at the end of the
array. In the OnInitDialog(), CArray object is created and three names are added as shown
in the following code.
Retrieve Items
To retrieve any item, you can use the CArray::GetAt() function. This function takes one
integer parameter as an index of the array.
Step 1: Let us look at a simple example, which will retrieve all the names.
 BOOL CMFCCArrayDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
                                                                                         311
                                                        Microsoft Foundation Classes
    // Set the icon for this dialog.     The framework does this automatically
    //   when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);                   // Set big icon
    SetIcon(m_hIcon, FALSE);           // Set small icon
    UpdateData(FALSE);
    return TRUE;   // return TRUE   unless you set the focus to a control
}
                                                                                 312
                                                            Microsoft Foundation Classes
Step 3: When the above code is compiled and executed, you will see the following output.
 BOOL CMFCCArrayDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.     The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                    // Set big icon
       SetIcon(m_hIcon, FALSE);           // Set small icon
                                                                                     313
                                                       Microsoft Foundation Classes
strArray.InsertAt(1, L"Allan");
    UpdateData(FALSE);
    return TRUE;   // return TRUE   unless you set the focus to a control
}
                                                                               314
                                                            Microsoft Foundation Classes
When the above code is compiled and executed, you will see the following output. You can
now see the name Allan dded as the second index.
Let us update the third element in the array as shown in the following code.
 BOOL CMFCCArrayDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.     The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                   // Set big icon
       SetIcon(m_hIcon, FALSE);           // Set small icon
                                                                                     315
                                                           Microsoft Foundation Classes
strArray.InsertAt(1, L"Allan");
strArray.SetAt(2, L"Salman");
       UpdateData(FALSE);
       return TRUE;   // return TRUE   unless you set the focus to a control
 }
When the above code is compiled and executed, you will see the following output. You can
now see that the value of third element is updated.
                                                                                    316
                                                            Microsoft Foundation Classes
Copy Array
To copy the entire array into another CArray object, you can use CArray::Copy() function.
Step 1: Let us create another array and copy all the elements from first array as shown
in the following code.
 BOOL CMFCCArrayDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
           bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
           ASSERT(bNameValid);
           if (!strAboutMenu.IsEmpty())
           {
                   pSysMenu->AppendMenu(MF_SEPARATOR);
                   pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
           }
    }
    // Set the icon for this dialog.     The framework does this automatically
    //   when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);                   // Set big icon
    SetIcon(m_hIcon, FALSE);           // Set small icon
strArray.InsertAt(1, L"Allan");
strArray.SetAt(2, L"Salman");
    UpdateData(FALSE);
    return TRUE;   // return TRUE   unless you set the focus to a control
}
                                                                                 318
                                                           Microsoft Foundation Classes
You can now see that we have retrieved element from the 2nd array and the output is the
same because we have used the copy function.
Remove Items
To remove any particular item, you can use CArray::RemoveAt() function. To remove all
the element from the list, CArray::RemoveAll() function can be used.
 BOOL CMFCCArrayDlg::OnInitDialog()
 {
      CDialogEx::OnInitDialog();
                                                                                   319
                                                       Microsoft Foundation Classes
    strArray.Add(L"Ali");
    strArray.Add(L"Ahmed");
    strArray.Add(L"Mark");
strArray.InsertAt(1, L"Allan");
strArray.SetAt(2, L"Salman");
strArray2.RemoveAt(1);
    UpdateData(FALSE);
    return TRUE;   // return TRUE   unless you set the focus to a control
}
                                                                               320
                                                           Microsoft Foundation Classes
When the above code is compiled and executed, you will see the following output. You can
now see that the name Allan is no longer part of the array.
                                                                                    321
                        19. MFC - Linked Lists                   Microsoft Foundation Classes
A linked list is a linear data structure where each element is a separate object. Each
element (we will call it a node) of a list comprises two items — the data and a reference
to the next node. The last node has a reference to null.
A linked list is a data structure consisting of a group of nodes which together represent a
sequence. It is a way to store data with structures so that the programmer can
automatically create a new place to store data whenever necessary. Some of its salient
features are:
      If the list contains at least one node, then a new node is positioned as the last
       element in the list.
 If the list has only one node, that node represents the first and the last item.
                                                                                           322
                                                                Microsoft Foundation Classes
CList Class
MFC provides a class CList which is a template linked list implementation and works
perfectly. CList lists behave like doubly-linked lists. A variable of type POSITION is a key
for the list. You can use a POSITION variable as an iterator to traverse a list sequentially
and as a bookmark to hold a place.
                 Name                                           Description
                                          Adds an element (or all the elements in another
               AddHead
                                          list) to the head of the list (makes a new head).
                                          Adds an element (or all the elements in another
                AddTail
                                          list) to the tail of the list (makes a new tail).
                                          Gets the position of an element specified by
                  Find
                                          pointer value.
                                          Gets the position of an element specified by a
              FindIndex
                                          zero-based index.
                GetAt                     Gets the element at a given position.
               GetCount                   Returns the number of elements in this list.
                                          Returns the head element of the list (cannot be
               GetHead
                                          empty).
                                          Returns the position of the head element of the
          GetHeadPosition
                                          list.
               GetNext                    Gets the next element for iterating.
               GetPrev                    Gets the previous element for iterating.
               GetSize                    Returns the number of elements in this list.
                                          Returns the tail element of the list (cannot be
                GetTail
                                          empty).
           GetTailPosition                Returns the position of the tail element of the list.
             InsertAfter                  Inserts a new element after a given position.
            InsertBefore                  Inserts a new element before a given position.
              IsEmpty                     Tests for the empty list condition (no elements).
             RemoveAll                    Removes all the elements from this list.
                                          Removes an element from this list, specified by
              RemoveAt
                                          position.
            RemoveHead                    Removes the element from the head of the list.
             RemoveTail                   Removes the element from the tail of the list.
               SetAt                      Sets the element at a given position.
                                                                                           323
                                                               Microsoft Foundation Classes
Add items
To add an item, you can use CList::AddTail() function. It adds an item at the end of the
list. To add an element at the start of the list, you can use the CList::AddHead() function.
In the OnInitDialog() CList, object is created and four values are added as shown in the
following code.
Retrieve Items
A variable of type POSITION is a key for the list. You can use a POSITION variable as an
iterator to traverse a list sequentially.
Step 1: To retrieve the element from the list, we can use the following code which will
retrieve all the values.
                                                                                         324
                                                         Microsoft Foundation Classes
 BOOL CMFCCListDemoDlg::OnInitDialog()
 {
      CDialogEx::OnInitDialog();
      // Set the icon for this dialog.    The framework does this automatically
      //   when the application's main window is not a dialog
      SetIcon(m_hIcon, TRUE);                  // Set big icon
      SetIcon(m_hIcon, FALSE);           // Set small icon
      return TRUE;   // return TRUE   unless you set the focus to a control
 }
                                                                                  325
                                                            Microsoft Foundation Classes
Step 3: When the above code is compiled and executed, you will see the following output.
 BOOL CMFCCListDemoDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.     The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                    // Set big icon
       SetIcon(m_hIcon, FALSE);            // Set small icon
                                                                                      326
                                                           Microsoft Foundation Classes
       return TRUE;   // return TRUE   unless you set the focus to a control
 }
Step 2: You can now see see that we first retrieved the position of value 85.26 and then
inserted one element before and one element after that value.
                                                                                    327
                                                             Microsoft Foundation Classes
Step 3: When the above code is compiled and executed, you will see the following output.
Let us update the 300.00 to 400 in the list as shown in the following code.
 BOOL CMFCCListDemoDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.     The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                    // Set big icon
       SetIcon(m_hIcon, FALSE);            // Set small icon
                                                                                      328
                                                       Microsoft Foundation Classes
    position = m_list.Find(300.00);
    m_list.SetAt(position, 400.00);
    return TRUE;   // return TRUE   unless you set the focus to a control
}
                                                                               329
                                                           Microsoft Foundation Classes
When the above code is compiled and executed, you will see the following output. You can
now see that the value of 300.00 is updated to 400.00.
Remove Items
To remove any particular item, you can use CList::RemoveAt() function. To remove all the
element from the list, CList::RemoveAll() function can be used.
 BOOL CMFCCListDemoDlg::OnInitDialog()
 {
       CDialogEx::OnInitDialog();
       // Set the icon for this dialog.    The framework does this automatically
       //   when the application's main window is not a dialog
       SetIcon(m_hIcon, TRUE);                   // Set big icon
       SetIcon(m_hIcon, FALSE);           // Set small icon
       position = m_list.Find(300.00);
       m_list.SetAt(position, 400.00);
       position = m_list.Find(95.78);
       m_list.RemoveAt(position);
       return TRUE;   // return TRUE   unless you set the focus to a control
 }
When the above code is compiled and executed, you will see the following output. You can
now see that the value of 95.78 is no longer part of the list.
                                                                                    331
Microsoft Foundation Classes
                        332
                  20. MFC - Database Classes                   Microsoft Foundation Classes
You do not have to write special-case code to handle different database management
systems (DBMSs). As long as your users have an appropriate ODBC driver for the data
they want to access, they can use your program to manipulate data in tables stored there.
A data source is a specific instance of data hosted by some database management system
(DBMS). Examples include Microsoft SQL Server, Microsoft Access, etc.
CDatabase
MFC provides a class CDatabase which represents a connection to a data source, through
which you can operate on the data source. You can have one or more CDatabase objects
active at a time in your application.
         Name                                         Description
                            Starts a "transaction" — a series of reversible calls to the
                            AddNew, Edit, Delete, and Update member functions of class
      BeginTrans
                            CRecordset — on the connected data source. The data source
                            must support transactions for BeginTrans to have any effect.
    BindParameters          Allows you to bind parameters before calling ExecuteSQL.
                            Cancels an asynchronous operation or a process from a second
         Cancel
                            thread.
      CanTransact           Returns nonzero if the data source supports transactions.
                            Returns nonzero if the CDatabase object is updatable (not
       CanUpdate
                            read-only).
          Close             Closes the data source connection.
                            Completes a transaction begun by BeginTrans. Commands in
     CommitTrans
                            the transaction that alter the data source are carried out.
     ExecuteSQL             Executes a SQL statement. No data records are returned.
 GetBookmarkPersist         Identifies the operations through which bookmarks persist on
        ence                recordset objects.
                            Returns the ODBC connection string used to connect the
      GetConnect
                            CDatabase object to a data source.
 GetCursorCommitBe          Identifies the effect of committing a transaction on an open
       havior               recordset object.
 GetCursorRollbackBe        Identifies the effect of rolling back a transaction on an open
       havior               recordset object.
  GetDatabaseName           Returns the name of the database currently in use.
                            Returns nonzero if the CDatabase object is currently
         IsOpen
                            connected to a data source.
                                                                                          333
                                                           Microsoft Foundation Classes
Let us look into a simple example by creating a new MFC dialog based application.
Step 1: Change the caption of TODO line to Retrieve Data from Database and drag one
button and one List control as shown in the following snapshot.
Step 2: Add click event handler for button and control variable m_ListControl for List
Control.
                                                                                    334
                                                            Microsoft Foundation Classes
Step 3: We have simple database which contains one Employees table with some records
as shown in the following snapshot.
Step 4: We need to include the following headers file so that we can use CDatabase class.
 #include "odbcinst.h"
 #include "afxdb.h"
Insert Query
The SQL INSERT INTO Statement is used to add new rows of data to a table in the
database.
To add new records, we will use the ExecuteSQL() function of CDatabase class as shown
in the following code.
 CDatabase database;
 CString SqlString;
 CString strID, strName, strAge;
 CString sDriver = L"MICROSOFT ACCESS DRIVER (*.mdb)";
 CString sDsn;
 CString sFile = L"D:\\Test.mdb";
                                                                                     335
                                                       Microsoft Foundation Classes
                                                                               336
                                                            Microsoft Foundation Classes
Step 2: When the above code is compiled and executed, you will see that a new record is
added in your database.
Retrieve Record
To retrieve the above table in MFC application, we implement the database related
operations in the button event handler as shown in the following steps.
Step 1: To use CDatabase, construct a CDatabase object and call its Open() function. This
will open the connection.
Step 2: Construct CRecordset objects for operating on the connected data source, pass
the recordset constructor a pointer to your CDatabase object.
Step 3: After using the connection, call the Close function and destroy the CDatabase
object.
 void CMFCDatabaseDemoDlg::OnBnClickedButtonRead()
 {
       // TODO: Add your control notification handler code here
       CDatabase database;
       CString SqlString;
       CString strID, strName, strAge;
       CString sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)";
                                                                                     337
                                                   Microsoft Foundation Classes
CString sDsn;
CString sFile = L"D:\\Test.mdb";
// You must change above path if it's different
int iRec = 0;
recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);
      // Reset List control if there is any data
      ResetListControl();
      // populate Grids
      ListView_SetExtendedListViewStyle(m_ListControl,LVS_EX_GRIDLINES);
                                                                                  339
                                                          Microsoft Foundation Classes
 #pragma once
 #include "afxcmn.h"
 // CMFCDatabaseDemoDlg dialog
 class CMFCDatabaseDemoDlg : public CDialogEx
 {
 // Construction
 public:
       CMFCDatabaseDemoDlg(CWnd* pParent = NULL);   // standard constructor
 // Dialog Data
 #ifdef AFX_DESIGN_TIME
       enum { IDD = IDD_MFCDATABASEDEMO_DIALOG };
 #endif
       protected:
       virtual void DoDataExchange(CDataExchange* pDX);      // DDX/DDV support
       void ResetListControl();
 // Implementation
 protected:
       HICON m_hIcon;
                                                                                  340
                                                           Microsoft Foundation Classes
Step 5: When the above code is compiled and executed, you will see the following output.
Step 6: Press the Read button to execute the database operations. It will retrieve the
Employees table.
                                                                                    341
                                                           Microsoft Foundation Classes
Update Record
The SQL UPDATE Query is used to modify the existing records in a table. You can use
WHERE clause with UPDATE query to update selected rows otherwise all the rows would
be affected.
Step 1: Let us look into a simple example by updating the Age where ID is equal to 5.
 void CMFCDatabaseDemoDlg::OnBnClickedButtonRead()
 {
       // TODO: Add your control notification handler code here
       CDatabase database;
       CString SqlString;
       CString strID, strName, strAge;
       CString sDriver = L"MICROSOFT ACCESS DRIVER (*.mdb)";
       CString sDsn;
      CString sFile =
 L"C:\\Users\\Muhammad.Waqas\\Downloads\\Compressed\\ReadDB_demo\\Test.mdb";
       // You must change above path if it's different
                                                                                    342
                                                   Microsoft Foundation Classes
int iRec = 0;
database.ExecuteSQL(SqlString);
recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);
m_listCtrl.SetColumnWidth(2, 200);
Step 3: When the above code is compiled and executed, you will see the following output.
                                                                                    344
                                                          Microsoft Foundation Classes
Step 4: Press the Read button to execute the database operations. It will retrieve the
following Employees table.
                                                                                  345
                                                             Microsoft Foundation Classes
Step 5: You can now see that age is updated from 69 to 59.
Delete Record
The SQL DELETE Query is used to delete the existing records from a table. You can use
WHERE clause with DELETE query to delete selected rows, otherwise all the records would
be deleted.
Step 1: Let us look into a simple example by deleting the record where ID is equal to 3.
database.ExecuteSQL(SqlString);
 void CMFCDatabaseDemoDlg::OnBnClickedButtonRead()
 {
       // TODO: Add your control notification handler code here
       CDatabase database;
       CString SqlString;
                                                                                     346
                                                        Microsoft Foundation Classes
database.ExecuteSQL(SqlString);
recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);
                                                                                347
                                                       Microsoft Foundation Classes
                                                                               348
                                                           Microsoft Foundation Classes
Step 3: When the above code is compiled and executed, you will see the following output.
Step 4: Press the Read button to execute the database operations. It will retrieve the
Employees table.
                                                                                    349
Microsoft Foundation Classes
                        350
                      21. MFC - Serialization                   Microsoft Foundation Classes
When performing file processing, the values are typically of primitive types (char, short,
int, float, or double). In the same way, we can individually save many values, one at a
time. This technique doesn't include an object created from (as a variable of) a class
The MFC library has a high level of support for serialization. It starts with the CObject class
that is the ancestor to most MFC classes, which is equipped with a Serialize() member
function.
Step 1: Remove the TODO line and design your dialog box as shown in the following
snapshot.
                                                                                          351
                                                           Microsoft Foundation Classes
Step 2: Add value variables for all the edit controls. For Emp ID and Age mentioned, the
value type is an integer as shown in the following snapshot.
Step 4: Let us now add a simple Employee class, which we need to serialize. Here is the
declaration of Employee class in header file.
 public:
       void Serialize(CArchive& ar);
       DECLARE_SERIAL(CEmployee);};
                                                                                    352
                                                             Microsoft Foundation Classes
 IMPLEMENT_SERIAL(CEmployee, CObject, 0)
 CEmployee::CEmployee(void)
 {
 }
 CEmployee::~CEmployee(void)
 {
 }
      if (ar.IsStoring())
             ar << empID << empName << age;
      else
             ar >> empID >> empName >> age;
 }
 void CMFCSerializationDlg::OnBnClickedButtonSave()
 {
      // TODO: Add your control notification handler code here
      UpdateData(TRUE);
      CEmployee employee;
      CFile file;
      file.Open(L"EmployeeInfo.hse", CFile::modeCreate | CFile::modeWrite);
      CArchive ar(&file, CArchive::store);
      employee.empID = m_id;
      employee.empName = m_strName;
      employee.age = m_age;
      employee.Serialize(ar);
      ar.Close();
 }
                                                                                     353
                                                          Microsoft Foundation Classes
 void CMFCSerializationDlg::OnBnClickedButtonOpen()
 {
      // TODO: Add your control notification handler code here
      UpdateData(TRUE);
CFile file;
      file.Open(L"EmployeeInfo.hse", CFile::modeRead);
      CArchive ar(&file, CArchive::load);
      CEmployee employee;
employee.Serialize(ar);
      m_id = employee.empID;
      m_strName = employee.empName;
      m_age = employee.age;
      ar.Close();
      file.Close();
      UpdateData(FALSE);
 }
                                                                                  354
                                                              Microsoft Foundation Classes
Step 8: When the above code is compiled and executed, you will see the following output.
Step 9: Enter the info in all the fields and click Save and close this program.
                                                                                      355
                                                             Microsoft Foundation Classes
Step 10: It will save the data. Run the application again and click open. It will load the
Employee information.
                                                                                      356
Microsoft Foundation Classes
                        357
                   22. MFC - Multithreading                Microsoft Foundation Classes
The Microsoft Foundation Class (MFC) library provides support for multithreaded
applications. A thread is a path of execution within a process. When you start Notepad,
the operating system creates a process and begins executing the primary thread of that
process. When this thread terminates, so does the process.
You can create additional threads in your application if you want. All threads in MFC
applications are represented by CWinThread objects. In most situations, you do not even
have to explicitly create these objects; instead call the framework helper function
AfxBeginThread, which creates the CWinThread object for you.
Let us look into a simple example by creating a new MFC dialog based application.
Step 1: Change the Caption and ID of Static control to Click on Start Thread button
and IDC_STATIC_TEXT respectively.
Step 2: Drag two buttons and add click event handlers for these buttons.
                                                                                    358
                                                            Microsoft Foundation Classes
Step 4: Now add the following             three   global   variables   at   the   start    of
CMFCMultithreadingDlg.cpp file
 int currValue;
 int maxValue;
 BOOL stopNow;
      CDialogEx::OnTimer(nIDEvent);
 }
      return TRUE;
 }
Step 7: Here is the implementation of event handler for Start Thread button, which will
start the thread.
void CMFCMultithreadingDlg::OnBnClickedButtonStart()
                                                                                          359
                                                          Microsoft Foundation Classes
 {
       // TODO: Add your control notification handler code here
       currValue = 0;
       maxValue = 5000;
       stopNow = 0;
       m_ctrlStatus.SetWindowText(L"Starting...");
       SetTimer(1234, 333, 0); // 3 times per second
Step 8: Here is the implementation of event handler for Stop Thread button, which will
stop the thread.
 void CMFCMultithreadingDlg::OnBnClickedButtonStop()
 {
       // TODO: Add your control notification handler code here
       stopNow = TRUE;
       KillTimer(1234);
       m_ctrlStatus.SetWindowText(L"Stopped");
 }
 #include "stdafx.h"
 #include "MFCMultithreading.h"
 #include "MFCMultithreadingDlg.h"
 #include "afxdialogex.h"
 #ifdef _DEBUG
 #define new DEBUG_NEW
 #endif
                                                                                  360
                                                        Microsoft Foundation Classes
// CMFCMultithreadingDlg dialog
int currValue;
int maxValue;
BOOL stopNow;
BEGIN_MESSAGE_MAP(CMFCMultithreadingDlg, CDialogEx)
     ON_WM_PAINT()
     ON_WM_QUERYDRAGICON()
     ON_BN_CLICKED(IDC_BUTTON_START,
&CMFCMultithreadingDlg::OnBnClickedButtonStart)
     ON_WM_TIMER()
     ON_BN_CLICKED(IDC_BUTTON_STOP,
&CMFCMultithreadingDlg::OnBnClickedButtonStop)
END_MESSAGE_MAP()
BOOL CMFCMultithreadingDlg::OnInitDialog()
{
     CDialogEx::OnInitDialog();
     // Set the icon for this dialog.   The framework does this automatically
     //   when the application's main window is not a dialog
     SetIcon(m_hIcon, TRUE);                 // Set big icon
                                                                                361
                                                          Microsoft Foundation Classes
      return TRUE;   // return TRUE    unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
//   to draw the icon.     For MFC applications using the document/view model,
//   this is automatically done for you by the framework.
void CMFCMultithreadingDlg::OnPaint()
{
      if (IsIconic())
      {
             CPaintDC dc(this); // device context for painting
            SendMessage(WM_ICONERASEBKGND,
reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
                                                                                  362
                                                         Microsoft Foundation Classes
// The system calls this function to obtain the cursor to display while the
user drags
//   the minimized window.
HCURSOR CMFCMultithreadingDlg::OnQueryDragIcon()
{
      return static_cast<HCURSOR>(m_hIcon);
}
      return TRUE;
}
void CMFCMultithreadingDlg::OnBnClickedButtonStart()
{
      // TODO: Add your control notification handler code here
      currValue = 0;
      maxValue = 5000;
      stopNow = 0;
      m_ctrlStatus.SetWindowText(L"Starting...");
      SetTimer(1234, 333, 0); // 3 times per second
                                                                                 363
                                                            Microsoft Foundation Classes
m_ctrlStatus.SetWindowText(sStatusMsg);
       CDialogEx::OnTimer(nIDEvent);
 }
 void CMFCMultithreadingDlg::OnBnClickedButtonStop()
 {
       // TODO: Add your control notification handler code here
       stopNow = TRUE;
       KillTimer(1234);
       m_ctrlStatus.SetWindowText(L"Stopped");
 }
Step 10: When the above code is compiled and executed, you will see the following output.
                                                                                     364
                                                             Microsoft Foundation Classes
Step 12: Click the Stop Thread button. It will stop the thread.
                                                                                     365
Microsoft Foundation Classes
                        366
           23. MFC - Internet Programming                    Microsoft Foundation Classes
Microsoft provides many APIs for programming both client and server applications. Many
new applications are being written for the Internet, and as technologies, browser
capabilities, and security options change, new types of applications will be written. Your
custom application can retrieve information and provide data on the Internet.
MFC provides a class CSocket for writing network communications programs with
Windows Sockets.
                   Name                                      Description
                                              Attaches a SOCKET handle to a CSocket
                  Attach
                                              object.
                                              Cancels a blocking call that is currently in
           CancelBlockingCall
                                              progress.
                  Create                      Creates a socket.
                                              Returns a pointer to a CSocket object, given
               FromHandle
                                              a SOCKET handle.
                                              Determines whether a blocking call is in
                IsBlocking
                                              progress.
                                                                                       367
                                                          Microsoft Foundation Classes
Step 3: Once the project is created, add a new MFC class CServerSocket.
                                                                                  368
                                                             Microsoft Foundation Classes
                                                                                     369
                                                             Microsoft Foundation Classes
 #include "ServerSocket.h"
 #include "MFCServerView.h"
 CServerSocket m_serverSocket;
 CMFCServerView m_pServerView;
Step 8: In CMFCServerApp::InitInstance() method, create the socket and specify the port
and then call the Listen method as shown below.
 m_serverSocket.Create(6666);
 m_serverSocket.Listen();
                                                                                     370
                                                             Microsoft Foundation Classes
#include "MFCServerDoc.h"
Step 11: Select CServerSocket in class view and the highlighted icon in Properties window.
Now, Add OnAccept. Here is the implementation of OnAccept function.
                                                                                      371
                                                           Microsoft Foundation Classes
 {    // TODO: Add your specialized code here and/or call the base class
      AfxMessageBox(L"Data Received");
      CSocket::OnReceive(nErrorCode);}
Right-click on the CMFCServerView class in solution explorer and select Add -> Add
Function.
Step 14: Enter the above mentioned information and click finish.
Step 15: Add the following CStringArray variable in CMFCServerView header file.
CStringArray m_msgArray;
                                                                                   372
                                                            Microsoft Foundation Classes
 CMFCServerView::CMFCServerView()
 {
      ((CMFCServerApp*)AfxGetApp())->m_pServerView = this;
Step 18: Here is the implementation of OnDraw() function, which display messages.
                                                                                    373
                                                             Microsoft Foundation Classes
Step 19: The server side is now complete. It will receive message from the client.
                                                                                        374
                                                        Microsoft Foundation Classes
Step 2: On Advanced Features tab, check the Windows sockets option as shown above.
                                                                                375
                                                           Microsoft Foundation Classes
Step 3: Once the project is created, design your dialog box as shown in the following
snapshot.
                                                                                   376
                                                               Microsoft Foundation Classes
Step 5: Add value variables for all the three edit controls. For port edit control, select the
variable type UINT.
                                                                                          377
                                                           Microsoft Foundation Classes
Step 7: Include the header file of CClientSocket class in the header file
CMFCClientDemoApp class and add the class variable. Similarly, add the class variable in
CMFCClientDemoDlg header file as well.
CClientSocket m_clientSocket;
 void CMFCClientDemoDlg::OnBnClickedButtonConnect()
 {
       // TODO: Add your control notification handler code here
       UpdateData(TRUE);
       m_clientSocket.Create();
       if (m_clientSocket.Connect(m_ipAddress, m_port))
       {
              AfxMessageBox(L"Connection Successfull");
       }
       else
                                                                                    378
                                                            Microsoft Foundation Classes
       {
              AfxMessageBox(L"Connection Failed");
       }
       DWORD error = GetLastError();
 }
 void CMFCClientDemoDlg::OnBnClickedButtonSend()
 {
       // TODO: Add your control notification handler code here
       UpdateData(TRUE);
      if (m_clientSocket.Send(m_message.GetBuffer(m_message.GetLength()),
 m_message.GetLength()))
       {
       }
       else
       {
              AfxMessageBox(L"Failed to send message");
       }
 }
Step 10: First run the Server application and then the client application. Enter the local
host ip and port and click Connect.
                                                                                      379
                                                           Microsoft Foundation Classes
Step 11: You will now see the message on Server side as shown in the following snapshot.
                                                                                    380
                              24. MFC - GDI                   Microsoft Foundation Classes
Windows provides a variety of drawing tools to use in device contexts. It provides pens to
draw lines, brushes to fill interiors, and fonts to draw text. MFC provides graphic-object
classes equivalent to the drawing tools in Windows.
Drawing
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.
CDC is the most fundamental class to draw in MFC. The CDC object provides member
functions to perform the basic drawing steps, as well as members for working with a
display context associated with the client area of a window.
           Name                                         Description
                               Terminates the current print job, erasing everything the
         AbortDoc              application has written to the device since the last call of
                               the StartDoc member function.
         AbortPath             Closes and discards any paths in the device context.
                               Copies the comment from a buffer into a specified
  AddMetaFileComment
                               enhanced-format metafile.
                               Displays bitmaps that have transparent or semitransparent
        AlphaBlend
                               pixels.
                               Draws a line segment and an arc, and moves the current
         AngleArc
                               position to the ending point of the arc.
            Arc                Draws an elliptical arc.
                               Draws an elliptical arc. This function is similar to Arc,
           ArcTo
                               except that the current position is updated.
          Attach               Attaches a Windows device context to this CDC object.
         BeginPath             Opens a path bracket in the device context.
           BitBlt              Copies a bitmap from a specified device context.
                               Draws a chord (a closed figure bounded by the intersection
           Chord
                               of an ellipse and a line segment).
        CloseFigure            Closes an open figure in a path.
                               Creates a memory-device context that is compatible with
   CreateCompatibleDC          another device context. You can use it to prepare images
                               in memory.
         CreateDC              Creates a device context for a specific device.
                               Creates an information context for a specific device. This
         CreateIC              provides a fast way to get information about the device
                               without creating a device context.
                                                                                        381
                                                   Microsoft Foundation Classes
                                                                             382
                                                        Microsoft Foundation Classes
                                                                                  383
                                                         Microsoft Foundation Classes
                                                                                    384
                                                      Microsoft Foundation Classes
                                                                                385
                                                    Microsoft Foundation Classes
                                                                              386
                                                            Microsoft Foundation Classes
                            Sets the limit for the length of miter joins for the device
      SetMiterLimit
                            context.
        SetOutputDC         Sets m_hDC, the output device context.
                            Sets the pixel at the specified point to the closest
          SetPixel
                            approximation of the specified color.
                            Sets the pixel at the specified coordinates to the closest
                            approximation of the specified color. SetPixelV is faster
         SetPixelV
                            than SetPixel because it does not need to return the color
                            value of the point actually painted.
    SetPolyFillMode         Sets the polygon-filling mode.
        SetROP2             Sets the current drawing mode.
   SetStretchBltMode        Sets the bitmap-stretching mode.
      SetTextAlign          Sets the text-alignment flags.
 SetTextCharacterExtra      Sets the amount of intercharacter spacing.
      SetTextColor          Sets the text color.
  SetTextJustification      Adds space to the break characters in a string.
    SetViewportExt          Sets the x- and y-extents of the viewport.
    SetViewportOrg          Sets the viewport origin.
     SetWindowExt           Sets the x- and y-extents of the associated window.
    SetWindowOrg            Sets the window origin of the device context.
                            Sets     the    current     world-space     to    page-space
   SetWorldTransform
                            transformation.
         StartDoc           Informs the device driver that a new print job is starting.
         StartPage          Informs the device driver that a new page is starting.
                            Moves a bitmap from a source rectangle and device into a
                            destination rectangle, stretching or compressing the
         StretchBlt
                            bitmap if necessary to fit the dimensions of the destination
                            rectangle.
                            Closes any open figures in a path, strikes the outline of the
    StrokeAndFillPath       path by using the current pen, and fills its interior by using
                            the current brush.
        StrokePath          Renders the specified path by using the current pen.
                            Writes a character string at a specified location, expanding
     TabbedTextOut          tabs to the values specified in an array of tab-stop
                            positions.
                            Writes a character string at a specified location using the
          TextOut
                            currently selected font.
                            Transfers a bit-block of color data from the specified source
     TransparentBlt         device context into a destination device context, rendering
                            a specified color transparent in the transfer.
                            Updates the client area of the device context by matching
      UpdateColors          the current colors in the client area to the system palette
                            on a pixel-by-pixel basis.
                            Redefines the current path as the area that would be
        WidenPath           painted if the path were stroked using the pen currently
                            selected into the device context.
Lines
Step 1: Let us look into a simple example by creating a new MFC based single document
project with MFCGDIDemo name.
                                                                                      387
                                                         Microsoft Foundation Classes
Step 2: Once the project is created, go the Solution Explorer and double click on the
MFCGDIDemoView.cpp file under the Source Files folder.
                                                                                 388
                                                             Microsoft Foundation Classes
Step 4: Run this application. You will see the following output.
Step 5: The CDC::MoveTo() method is used to set the starting position of a line.
When using LineTo(), the program starts from the MoveTo() point to the LineTo() end.
After LineTo() when you do not call MoveTo(), and call again LineTo() with other point
value, the program will draw a line from the previous LineTo() to the new LineTo() point.
Step 6: To draw different lines, you can use this property as shown in the following code.
                                                                                      389
                                                             Microsoft Foundation Classes
Step 7: Run this application. You will see the following output.
Polylines
A polyline is a series of connected lines. The lines are stored in an array of POINT or
CPoint values. To draw a polyline, you use the CDC::Polyline() method. To draw a polyline,
at least two points are required. If you define more than two points, each line after the
first would be drawn from the previous point to the next point until all points have been
included.
                                                                                      390
                                                            Microsoft Foundation Classes
pDC->Polyline(Pt, 3);
Step 2: When you run this application, you will see the following output.
Rectangles
A rectangle is a geometric figure made of four sides that compose four right angles. Like
the line, to draw a rectangle, you must define where it starts and where it ends. To draw
a rectangle, you can use the CDC::Rectangle() method.
                                                                                     391
                                                            Microsoft Foundation Classes
Step 2: When you run this application, you will see the following output.
                                                                                    392
                                                             Microsoft Foundation Classes
Squares
A square is a geometric figure made of four sides that compose four right angles, but
each side must be equal in length.
When you run this application, you will see the following output.
                                                                                     393
                                                                 Microsoft Foundation Classes
Pies
A pie is a fraction of an ellipse delimited by two lines that span from the center of the
ellipse to one side each. To draw a pie, you can use the CDC::Pie() method as shown
below:
BOOL Pie(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);
      The (x1, y1) point determines the upper-left corner of the rectangle in which the
       ellipse that represents the pie fits. The (x2, y2) point is the bottom-right corner
       of the rectangle.
                                                                                         394
                                                                 Microsoft Foundation Classes
        The (x3, y3) point specifies the starting corner of the pie in a default
         counterclockwise direction.
        The (x4, y4) point species the end point of the pie.
                                                                                         395
                                                                 Microsoft Foundation Classes
Step 2: When you run this application, you will see the following output.
Arcs
An arc is a portion or segment of an ellipse, meaning an arc is a non-complete ellipse. To
draw an arc, you can use the CDC::Arc() method.
BOOL Arc(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);
                                                                                         396
                                                            Microsoft Foundation Classes
                Value                                    Orientation
 AD_CLOCKWISE                          The figure is drawn clockwise
 AD_COUNTERCLOCKWISE                   The figure is drawn counterclockwise
Step 2: When you run this application, you will see the following output.
                                                                                    397
                                                                Microsoft Foundation Classes
Chords
The arcs we have drawn so far are considered open figures because they are made of a
line that has a beginning and an end (unlike a circle or a rectangle that do not). A chord
is an arc whose two ends are connected by a straight line.
BOOL Chord(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);
When you run the above application, you will see the following output.
Colors
The color is one the most fundamental objects that enhances the aesthetic appearance of
an object. The color is a non-spatial object that is added to an object to modify some of
its visual aspects. The MFC library, combined with the Win32 API, provides various actions
you can use to take advantage of the various aspects of colors.
                                                                                      399
                                                             Microsoft Foundation Classes
The RGB macro behaves like a function and allows you to pass three numeric values
separated by a comma. Each value must be between 0 and 255 as shown in the following
code.
When you run this application, you will see the following output.
                                                                                     400
                                                             Microsoft Foundation Classes
Fonts
CFont encapsulates a Windows graphics device interface (GDI) font and provides member
functions for manipulating the font. To use a CFont object, construct a CFont object and
attach a Windows font to it, and then use the object's member functions to manipulate
the font.
             Name                                        Description
           CreateFont               Initializes a CFont with the specified characteristics.
                                    Initializes a CFont object with the characteristics
      CreateFontIndirect
                                    given in a LOGFONT structure.
                                    Initializes a CFont with the specified height,
        CreatePointFont
                                    measured in tenths of a point, and typeface.
                                    Same as CreateFontIndirect except that the font
   CreatePointFontIndirect          height is measured in tenths of a point rather than
                                    logical units.
                                    Returns a pointer to a CFont object when given a
          FromHandle
                                    Windows HFONT.
                                    Fills a LOGFONT with information about the logical
           GetLogFont
                                    font attached to the CFont object.
                                                                                        401
                                                            Microsoft Foundation Classes
When you run the above application, you will see the following output.
                                                                                    402
                                                              Microsoft Foundation Classes
Pens
A pen is a tool used to draw lines and curves on a device context. In the graphics
programming, a pen is also used to draw the borders of a geometric closed shape such as
a rectangle or a polygon. Microsoft Windows considers two types of pens — cosmetic and
geometric.
A pen is referred to as cosmetic when it can be used to draw only simple lines of a fixed
width, less than or equal to 1 pixel. A pen is geometric when it can assume different widths
and various ends. MFC provides a class CPen which encapsulates a Windows graphics
device interface (GDI) pen.
                   Name                                      Description
                                             Creates a logical cosmetic or geometric pen
                CreatePen                    with the specified style, width, and brush
                                             attributes, and attaches it to the CPen object.
                                             Creates a pen with the style, width, and color
           CreatePenIndirect                 given in a LOGPEN structure, and attaches it
                                             to the CPen object.
                                             Returns a pointer to a CPen object when
              FromHandle
                                             given a Windows HPEN.
             GetExtLogPen                    Gets an EXTLOGPEN underlying structure.
              GetLogPen                      Gets a LOGPEN underlying structure.
               Value                               Description
             PS_SOLID          A continuous solid line.
             PS_DASH           A continuous line with dashed interruptions.
              PS_DOT           A line with a dot interruption at every other pixel.
                               A combination of alternating dashed and dotted
           PS_DASHDOT
                               points.
                               A combination of dash and double dotted
        PS_DASHDOTDOT
                               interruptions.
             PS_NULL           No visible line.
                               A line drawn just inside of the border of a closed
        PS_INSIDEFRAME
                               shape.
                                                                                        403
                                                             Microsoft Foundation Classes
When you run the above application, you will see the following output.
Brushes
A brush is a drawing tool used to fill out closed shaped or the interior of lines. A brush
behaves like picking up a bucket of paint and pouring it somewhere. MFC provides a class
CBrush which encapsulates a Windows graphics device interface (GDI) brush.
                                                                                      404
                                                              Microsoft Foundation Classes
              Name                                        Description
                                     Initializes a brush with the style, color, and pattern
      CreateBrushIndirect
                                     specified in a LOGBRUSH structure.
                                     Initializes a brush with a pattern specified by a
     CreateDIBPatternBrush
                                     device-independent bitmap (DIB).
                                     Initializes a brush with the specified hatched pattern
       CreateHatchBrush
                                     and color.
                                     Initializes a brush with a pattern specified by a
      CreatePatternBrush
                                     bitmap.
        CreateSolidBrush             Initializes a brush with the specified solid color.
      CreateSysColorBrush            Creates a brush that is the default system color.
                                     Returns a pointer to a CBrush object when given a
           FromHandle
                                     handle to a Windows HBRUSH object.
          GetLogBrush                Gets a LOGBRUSH structure.
                                                                                        405
                                                             Microsoft Foundation Classes
When you run this application, you will see the following output.
                                                                                     406
                           25. MFC - Libraries                 Microsoft Foundation Classes
A library is a group of functions, classes, or other resources that can be made available
to programs that need already implemented entities without the need to know how these
functions, classes, or resources were created or how they function. A library makes it easy
for a programmer to use functions, classes, and resources etc. created by another person
or company and trust that this external source is reliable and efficient. Some unique
features related to libraries are:
      A library is created and functions like a normal regular program, using functions
       or other resources and communicating with other programs.
      At the same time, a library may use some functions that other programs would
       not need.
 The program that uses the library, are also called the clients of the library.
There are two types of functions you will create or include in your libraries:
      An internal function is one used only by the library itself and clients of the library
       will not need access to these functions.
 External functions are those that can be accessed by the clients of the library.
There are two broad categories of libraries you will deal with in your programs:
      Static libraries
      Dynamic libraries
Static Library
A static library is a file that contains functions, classes, or resources that an external
program can use to complement its functionality. To use a library, the programmer has to
create a link to it. The project can be a console application, a Win32 or an MFC application.
The library file has the lib extension.
                                                                                          407
                                                              Microsoft Foundation Classes
Step 1: Let us look into a simple example of static library by creating a new Win32 Project.
                                                                                        408
                                                            Microsoft Foundation Classes
Step 2: On Application Wizard dialog box, choose the Static Library option.
                                                                                    409
                                                            Microsoft Foundation Classes
Step 4: Right-click on the project in solution explorer and add a header file from Add ->
New Item…menu option.
                                                                                     410
                                                              Microsoft Foundation Classes
 #pragma once
 #ifndef _CALCULATOR_H_
 #define _CALCULATOR_H_
 double Min(const double *Numbers, const int Count);
 double Max(const double *Numbers, const int Count);
 double Sum(const double *Numbers, const int Count);
 double Average(const double *Numbers, const int Count);
 long GreatestCommonDivisor(long Nbr1, long Nbr2);
 #endif // _CALCULATOR_H_
                                                                                      411
                                                            Microsoft Foundation Classes
 #include "StdAfx.h"
 #include "Calculator.h"
 double Min(const double *Nbr, const int Total)
 {     double Minimum = Nbr[0];
       for (int i = 0; i < Total; i++)
              if (Minimum > Nbr[i])
                     Minimum = Nbr[i];
       return Minimum;
 }
 double Max(const double *Nbr, const int Total)
 {
       double Maximum = Nbr[0];
       for (int i = 0; i < Total; i++)
              if (Maximum < Nbr[i])
                     Maximum = Nbr[i];
       return Maximum;
                                                                                    412
                                                          Microsoft Foundation Classes
 }
 double Sum(const double *Nbr, const int Total)
 {
      double S = 0;
      for (int i = 0; i < Total; i++)
             S += Nbr[i];
      return S;
 }
 double Average(const double *Nbr, const int Total)
 {
      double avg, S = 0;
      for (int i = 0; i < Total; i++)
             S += Nbr[i];
      avg = S / Total;
      return avg;
 }
 long GreatestCommonDivisor(long Nbr1, long Nbr2)
 {    while (true)
      {
             Nbr1 = Nbr1 % Nbr2;
             if (Nbr1 == 0)
                      return Nbr2;
             Nbr2 = Nbr2 % Nbr1;
             if (Nbr2 == 0)
                      return Nbr1;
      }}
Step 9: Build this library from the main menu, by clicking Build -> Build MFCLib.
                                                                                    413
                                                             Microsoft Foundation Classes
Step 10: When library is built successfully, it will display the above message.
Step 11: To use these functions from the library, let us add another MFC dialog application
based from File -> New -> Project.
                                                                                       414
                                                          Microsoft Foundation Classes
Step 12: Go to the MFCLib\Debug folder and copy the header file and *.lib files to the
MFCLibTest project as shown in the following snapshot.
                                                                                  415
                                                            Microsoft Foundation Classes
Step 13: To add the library to the current project, on the main menu, click Project -> Add
Existing Item and select MFCLib.lib.
Step 14: Design your dialog box as shown in the following snapshot.
                                                                                      416
                                                            Microsoft Foundation Classes
Step 15: Add value variable for both edit controls of value type double.
                                                                                    417
                                                             Microsoft Foundation Classes
Step 16: Add value variable for Static text control, which is at the end of the dialog box.
                                                                                       418
                                                          Microsoft Foundation Classes
To add functionality from the library, we need to include the header file in
CMFCLibTestDlg.cpp file.
 #include "stdafx.h"
 #include "MFCLibTest.h"
 #include "MFCLibTestDlg.h"
 #include "afxdialogex.h"
 #include "Calculator.h"
 void CMFCLibTestDlg::OnBnClickedButtonCal()
 {
      // TODO: Add your control notification handler code here
      UpdateData(TRUE);
CString strTemp;
                                                                                  419
                                                            Microsoft Foundation Classes
       double numbers[2];
       numbers[0] = m_Num1;
       numbers[1] = m_Num2;
       strTemp.Format(L"%.2f", Max(numbers,2));
       m_strText.Append(L"Max is:\t" + strTemp);
       UpdateData(FALSE);
 }
Step 19: When the above code is compiled and executed, you will see the following output.
                                                                                     420
                                                              Microsoft Foundation Classes
Step 20: Enter two values in the edit field and click Calculate. You will now see the result
after calculating from the library.
Dynamic Library
A Win32 DLL is a library that can be made available to programs that run on a Microsoft
Windows computer. As a normal library, it is made of functions and/or other resources
grouped in a file.
The DLL abbreviation stands for Dynamic Link Library. This means that, as opposed to a
static library, a DLL allows the programmer to decide on when and how other applications
will be linked to this type of library.
For example, a DLL allows difference applications to use its library as they see fit and as
necessary. In fact, applications created on different programming environments can use
functions or resources stored in one particular DLL. For this reason, an application
dynamically links to the library.
                                                                                        421
                                                           Microsoft Foundation Classes
Step 1: Let us look into a simple example by creating a new Win32 Project.
                                                                                   422
                                                             Microsoft Foundation Classes
Step 2: In the Application Type section, click the DLL radio button.
Step 4: Add the following functions in MFCDynamicLib.cpp file and expose its definitions
by using:
Step 5: Use the _declspec(dllexport) modifier for each function that will be accessed
outside the DLL.
#include "stdafx.h"
                                                                                     423
                                                      Microsoft Foundation Classes
                                                                              424
                                                         Microsoft Foundation Classes
Step 6: To create the DLL, on the main menu, click Build > Build MFCDynamicLib from
the main menu.
Step 7: Once the DLL is successfully created, you will see amessage display in output
window.
                                                                                 425
                                                            Microsoft Foundation Classes
Step 8: Open Windows Explorer and then the Debug folder of the current project.
Step 9: Notice that a file with dll extension and another file with lib extension has been
created.
Step 10: To test this file with dll extension, we need to create a new MFC dialog based
application from File -> New --> Project.
                                                                                      426
                                                          Microsoft Foundation Classes
Step 11: Go to the MFCDynamicLib\Debug folder and copy the *.dll and *.lib files to the
MFCLibTest project as shown in the following snapshot.
                                                                                   427
                                                          Microsoft Foundation Classes
Step 12: To add the DLL to the current project, on the main menu, click Project -> Add
Existing Item and then, select MFCDynamicLib.lib file.
Step 13: Design your dialog box as shown in the following snapshot.
                                                                                  428
                                                            Microsoft Foundation Classes
Step 14: Add value variable for both edit controls of value type double.
                                                                                    429
                                                             Microsoft Foundation Classes
Step 15: Add value variable for Static text control, which is at the end of the dialog box.
Step 17: In the project that is using the DLL, each function that will be accessed must be
declared using the _declspec(dllimport) modifier.
                                                                                       430
                                                          Microsoft Foundation Classes
 void CMFCLibTestDlg::OnBnClickedButtonCal()
 {
      // TODO: Add your control notification handler code here
      UpdateData(TRUE);
      CString strTemp;
      double numbers[2];
      numbers[0] = m_Num1;
      numbers[1] = m_Num2;
      strTemp.Format(L"%.2f", Max(numbers,2));
      m_strText.Append(L"Max is:\t" + strTemp);
      UpdateData(FALSE);
 }
                                                                                  431
                                                              Microsoft Foundation Classes
Step 20: When the above code is compiled and executed, you will see the following output.
Step 21: Enter two values in the edit field and click Calculate. You will now see the result
after calculating from the DLL.
                                                                                        432
Microsoft Foundation Classes
433