VC++ Book

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 92

Contents

About Visual C++

Programs
1. Create A window
2. Window Class
3. PaintDC
4. Mouse Presence
5. Drawing a Line
6. Line Drawing Example 2
7. Free Hand Drawing
8. Different Shapes
9. Metafile DC
10. Menu
11. Context Menu
12. Checked Menu Items
13. Button Creation
14. Checkbox and Radio Button
15. List box and combo box
16. Font
17. Keyboard
18. Modal Dialog Box with validation
19. Modeless Dialog box
20. File Dialog
21. Font Dialog and color dialog
22. Scroll bar
23. Toolbar
24. Toolbar with button creation
25. Slider
26. Status Bar
27. Notepad
28. SDI
29. Worker Thread
30. User Interface Thread with Synchronization
31. Database
Features of Visual C++ are:

• Code reusability

• Application wizards for MFC applications, DLLs, ActiveX controls, ATL Projects

• ATL COM Objects and ISAPI extensions

• Integrated development environment

• Components and Controls Gallery to store and access reusable controls and components

• Portability across platforms

In addition to conventional graphical user-interface applications, Visual C++ enables developers


to build Web applications, smart-client Windows-based applications, and solutions for thin-client
and smart-client mobile devices. C++ is the world's most popular
systems- level language, and Visual C++ gives developers a world-class tool with which to build
soft

Visual C++ 6.0

Visual C++ 6.0 in particular provides lot of new features, some of which are mentioned below.
. Visual C++ 6.0 provides a whole new set of wizards to build the skeleton applications.
. It provides easier application coding and building and a greater support for ActiveX1 and Internet
Technologies.

. Visual C++ 6.0 components:


The Gallery can contain tools that let you add features to your project. Such a tool could insert
new classes, functions, data members, and resources into an existing project. Some component
modules are supplied by Microsoft (Idle time processing, Palette support, and Splash screen, for
example) as part of Visual C++. Others will be supplied by third-party software firms.

VC++ Developer Studio - An integrated application, which provides a set of programming-tools.


VC++ Runtime Libraries – These are the libraries that provide standard functions like strlen and
strcpy etc. that can be called from a standard C or C++ functions.
MFC and Template Libraries – The extensive C++ class library especially designed for creating
GUI programs.
VC++ Build Tools – It comprises of C/C++ Compiler, the Linker, resource compiler especially
designed for compiling the resources and some other tools required for generating a 32-bit
Windows programs.
ActiveX
Data Access Components – This includes Database drivers, controls and other tools required by
VC++ to interact with Databases.
Enterprise Tools – These are the advanced level Tools like Application Performance explorer or
Visual Studio Analyzer.2
Graphics – Consist of Bitmaps, Metafiles, Cursors and icons available for inclusion in the
application

Parts of Visual C++

The fundamental parts of Visual C++ , provided as part of the IDE, are the editor, the compiler,
the linker, and the libraries. These are the basic tools that are essential to writing and executing a
C++ program. Their functions are as follows.

The Editor

The editor provides an interactive environment in which to create and edit C++ source code. As
well as the usual facilities, such as cut and paste, which you are certainly already familiar with, the
editor also provides color cues to differentiate between various language elements. The editor
automatically recognizes fundamental words in the C++ language and assigns a color to them
according to what they are. This not only helps to make your code more readable, but also provides
a clear indicator of when you make errors in keying such words.

The Compiler

The compiler converts your source code into object code, and detects and reports errors in the
compilation process. The compiler can detect a wide range of errors caused by invalid or
unrecognized program code, as well as structural errors, such as parts of a program that can never
be executed. The object code output from the compiler is stored in files called object files that have
names with the extension .obj.

The Linker

The linker combines the various modules generated by the compiler from source code files, adds
required code modules from program libraries supplied as part of C++, and welds everything into
an executable whole. The linker can also detect and report errors — for example, if part of your
program is missing, or a nonexistent library component is referenced.

The Libraries
A library is simply a collection of prewritten routines that supports and extends the C++ language
by providing standard professionally-produced code units that you can incorporate into your
programs to carry out common operations. The operations implemented by routines in the various
libraries provided by Visual C++ greatly enhance productivity by saving you the effort of writing
and testing the code for such operations yourself. I have already mentioned the .NET Framework
library, and there are a number of others — too many to enumerate here — but I’ll identify the
most important ones.

The Project Workspace

Working with the Developer Studio is based on working with Project workspaces. These
workspaces represent a particular set of projects, which can be anything from a single application,
to a function library, to an entire suite of applications. Each workspace may include any number
of different projects that you want to group into a single workspace so that you can work closely
with each separate project at the same time.

The project workspace (.dsw) file is responsible for maintaining all of the information that defines
your workspace and the projects that you have included in it. Each workspace contains one or more
projects, with each project using a project (.dsp) file. Previ ously, you might have used make (.mak)
files to maintain projects and the processes involved in creating your applications. Developer
Studio 6.0 does not create .mak files by default anymore, although you can force Developer Studio
to create a makefile based on current project settings by using the Export Makefile command from
the Project menu. This is useful if you are using .mak files to automate your builds outside of
Developer Studio.

In addition to makefile-type information about your projects, the project workspace file includes
information about the settings you have chosen for Developer Studio itself. This means that
whenever you open a project workspace, all of the Developer Studio settings that you had when
you last worked with this workspace will be restored. All of the windows that were open before
will also be opened and returned to their previous position in the workspace.

Project Files and Makefiles

PROJNAME.DSW

This is the workspace file used within the development environment. It organizes all the projects
into a single workspace.

PROJNAME.OPT
This is the workspace options file used within the development environment. It stores all the user
options you create for your workspace, so that each time you open the project workspace it has the
look and feel you want and includes any customizations you have made.

PROJNAME.DSP

This is the project file used within the development environment. In previous versions of Visual
C++ this file extension was .MAK. It stores the information specific to your project. There will be
a separate .DSP file for each project you create. .DSP files are not compatible with NMAKE. You
must export a makefile to build with NMAKE.

PROJNAME.CLW

This file is used by ClassWizard to store information about the classes in your project

PROJNAME.ODL

This file contains the Object Description Language source code for a control type library. This file
is used by Visual C++ to generate a type library. The generated library exposes the control’s
interface to other Automation clients.

PROJNAME.NCB This is the No compile Browser file. It contains information generated by the
parser which is used by ClassView, WizardBar, and Component Gallery. If the file is accidentally
or deliberately deleted, it is automatically regenerated.

README.TXT A file (located in the parent directory of the project) that describes each file in
your project using the actual filenames created by AppWizard or ControlWizard.

Program or Control Source and Header Files

PROJNAME.H

This is the main include file for the program or DLL. It contains all global symbols and #include
directives for other header files. It derives the CPrjnameApp class from CWinApp and declares
an InitInstance member function. For a control, the CPrjnameApp class is derived from
COleControlModule.

PROJNAME.CPP

This file is the main program source file. It creates one object of the class CPrjnameApp (which is
derived from CWinApp) and overrides the InitInstance member function.

For executables, CPrjnameApp::InitInstance does several things. It registers document templates,


which serve as a connection between documents and views, creates a main frame window, and
creates an empty document (or opens a document if one is specified as a command-line argument
to the application).
For DLLs and ActiveX (formerly OLE) controls, CProjNameApp::InitInstance registers the
control’s object factory with OLE by calling COleObjectFactory::RegisterAll and makes a call
to AfxOLEControlInit. In addition, the member function CProjNameApp::ExitInstance is used
to unload the control from memory with a call to AfxOleControlTerm.

This file also registers and unregisters the control in the Windows registration database by
implementing the DllRegisterServer and DllUnregisterServer functions.

PROJNAMECTL.H, PROJNAMECTL.CPP

These files declare and implement the CProjnameCtrl class. CProjnameCtrl is derived from
COleControl, and skeleton implementations of some member functions are defined that initialize,
draw, and serialize (load and save) the control. Message, event, and dispatch maps are also defined.

PROJNAMEDLG.CPP, PROJNAMEDLG.H

These files are created if you choose a dialog-based application. The files derive and implement
the dialog class, named CProjnameDlg, and include skeleton member functions to initialize a
dialog and perform dialog data exchange (DDX). Your About dialog class is also placed in these
files instead of in PROJNAME.CPP.

MFC ( Microsoft Foundation’s Class)

The C++ class library that Microsoft provides with its C++ compiler to assist programmers in
creating Windows -based applications. MFC hides the fundamental Windows API in class
hierarchies, so that, programmers can write Windows-based applications without needing to know
the details of the native Windows API.

The MFC classes are coded in C++. It provides the necessary code for managing windows, menus
and dialog-boxes. It also helps in carrying out basic tasks like performing basic input-output,
storing the collection of data objects etc. It provides the basic framework for the application on
which the programmer can build the rest of the customized code.
MFC Library is a collection of classes in hierarchical form, where classes are derived from some
base class. For most of the classes provided by MFC, base class is CObject from which most of
the classes are inherited. The rest few classes are independent classes. The classes in MFC Library
can be categorized as:

• Root Class: CObject

• MFC Application Architecture Classes

• Window, Dialog, and Control Classes


• Drawing and Printing Classes

• Simple Data Type Classes

• Array, List, and Map Classes

• File and Database Classes

• Internet and Networking Classes

• OLE Classes

• Debugging and Exception Classes

In addition to these classes, the Microsoft Foundation Class Library contains a number of global
functions, global variables, and macros.

The Microsoft Foundation Class Library (MFC) supplies full source code. The full source code is
supplied in the form of Header files (.H) that are in the MFC\Include directory and implementation
files (.Cpp) that are in the MFC\Src directory

MFC Library was especially designed to provide an object oriented interface to Windows,
simultaneously providing the compatibility with the windows programs written in C language. The
compatibility with C language was required as the Windows was developed long before MFC
came into existence and hence all the applications for Windows were initially written in C, a large
number of which is still in use.

MFC Library provides the following features:

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

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

• Minimum code size overhead.

• Ability to call any Windows C function directly.

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


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

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

• Easier-to-use yet powerful abstractions of complicated features such as ActiveX, database


support, printing, toolbars, and status bars.

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

Advantages of MFC

Microsoft Foundation Class Library greatly reduces the development time, makes the code more
portable, provides support without reducing the programming freedom and flexibility and provides
easy access to user interface elements and technologies like ActiveX and Internet programming
which are otherwise very hard to program.
By using MFC, developers can add many capabilities to their applications in an easy, object-
oriented manner. MFC simplifies database programming by providing Data Access Objects
(DAO) and Open Database Connectivity (ODBC) and network programming through Windows
Sockets.
MFC offers many advantages like:

• Application Framework

• Largest base of reusable C++ source code

• Integration with Visual C++

• Flexible and fast database access

• Support for Internet and ActiveX technology

• Support for messaging API

• Support for multithreading

MFC is not only library of classes. MFC is also an application framework.MFC helps to define the
structure of an application and handles many routine chores on the application’s behalf.

Starting with CWinApp, the class that represents that represents the application itself, MFC
encapsulates virtually every aspect of a program’s operation. The framework supplies the
WinMain() function, and WinMain() in turn calls the application object’s member functions to
make the program go. One of the CWinApp member functions
.called by WinMain()- Run() – encapsulates the message loop that literally runs the program.
Parts of Application

The application source code generated for you by AppWizard actually consists of 4 major classes.
All these classes can be seen by expanding the class listing in the Class View tab. For each of these
classes corresponding header file (.h) and an implementation file (.cpp) is generated.

Application framework

The application framework is a collection of classes and the structure of an application which
handles many routine chores on the application’s behalf. The framework also provides
abstractions that go above and beyond what the Windows API has to offer.

MFC is an application framework – it acts as object oriented wrapper around the Windows API.

The MainFrame Window Class

This class is named CMainFrame and is derived from the MFC class CFrameWnd. This class
manages the main window of the application that contains the window frame, Menu bar, Toolbar,
Status bar, System menu and Minimise, Maximise and Close boxes and also contains the view
window of the application.

The Application Class

This class named C ProjectNameApp is derived from the MFC class CWinApp. It manages the
application as a whole by managing the tasks, like initialising the application instance, managing
the message loop and performing final cleanup of the program.

The Document Class

This class named C ProjectNameDoc is derived from the MFC class CDocument. It is responsible
for storing the program data as a single string and reading and writing this data to disk files.

The View Class

The class named C projectNameView is derived from CView class from the MFC classes.It
manages the view window, which is used to display program data on the screen and also used in
processing the input from the user.
MFC and AppWizard use the Document/View architecture to organize programs written for
Windows.
Debug and Release version

Visual Studio projects have separate release and debug configurations for your program. As the
names imply, you build the debug version for debugging and the release version for the final
release distribution.

The debug configuration of your program is compiled with full symbolic debug information and
no optimization. Optimization complicates debugging, because the relationship between source
code and generated instructions is more complex.

The release configuration of your program contains no symbolic debug information and is fully
optimized. Debug information can be generated in PDB Files, depending on the compiler options
that are used. Creating PDB files can be very useful if you later have to debug your release version.

You can set a range of options for a project through the Project | Ex1_01 Properties menu item.
These options determine how your source code is processed during the compile and link stages.
The set of options that produces a particular executable version of your program is called a
configuration. When you create a new project workspace, Visual C++ 2010 automatically creates
configurations for producing two versions of your application. One version, called the Debug
version, includes additional information that helps you debug the program. With the Debug version
of your program, you can step through the code when things go wrong, checking on the data values
in the program. The other, called the Release version, has no debug information included and has
the code-optimization options for the compiler turned on to provide you with the most efficient
executable module. These two configurations are sufficient for your needs throughout this book,
but when you need to add other configurations for an application you can do so through the Build
| Configuration Manager menu.

Cleaning up

The RegMaid utility is designed to clean up invalid registry entries that are caused by deleting
OLE projects that are created with Visual C++ and Microsoft Foundation Classes (MFC).

MFC based Windows program execution Sequence

Global Application Object Created

Execution Begins with WinMain() which has been linked by MFC into other application

AfxGetApp() gets a pointer to an application object

AfxWinInit() copies hInstance, nCmdShow, etc to data members of the application object

InitApplication() is executed

InitInsatnce() is executed
Run() implements the message loop

On Encountering WM_QUIT the message loop is terminated

ExitInstance() performs cleanup operations if any

AfxWinTerm() terminates the application

MFC AppWizard

The AppWizard is a "template generator .The AppWizard gives you a number of different options
as you are creating the template, and you choose among these options depending on what type of
application you are planning to create. You will use the AppWizard exactly once for each
application you create. After it has generated the template, the AppWizard is finished

MFC AppWizard is really a collection of different Application Wizards that help to do different
sorts of projects. Each of the AppWizards will guide you through the process of creating a new
project, prompting for various option selections along the way.

When you have made all of your choices, MFC will create your project for you. For some types
of projects, this can be a tremendous time-saver. For MFC applications, this means creating all of
the source, header, resource, help, and project files necessary to create a skeleton for your
application. The project created by the MFC AppWizard (exe) will build without any further
modifications and has all of the setup for the application features you selected. This can easily
reduce half a day's hunting, cutting, and pasting to just a few seconds.

AppWizard is a tool that based on user specifications, writes a minimal Windows application using
MFC

ClassWizard

ClassWizard helps you create handler functions for Windows messages and commands, create and
manage classes, create class member variables, create Automation methods and properties, create
database classes, and more. ClassWizard also helps you to override virtual functions in the MFC
classes. Select the class and the virtual function to override. The rest of the process is similar to
message handling, as described in the following paragraphs.
Class Wizard is a tool that assists programmer write classes, add members to classes and write
event-handlers

Device Context

A data structure in Windows programming that is used to define the attributes of text and images
that are output to the screen or printer. The device context (DC) is maintained by GDI. A DC,
which is a handle to the structure, is obtained before output is written and released after the
elements have been written

All drawing calls are made through a device-context object, which encapsulates the Windows APIs
for drawing lines, shapes, and text. Device contexts allow device-independent drawing in
Windows. Device contexts can be used to draw to the screen, to the printer, or to a metafile.

CDC

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

CPaintDC

A display context used in OnPaint member functions of windows. Automatically calls


BeginPaint on construction and EndPaint on destruction.

CClientDC

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

CWindowDC

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

CMetaFileDC

A device context for Windows metafiles. A Windows metafile contains a sequence of


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

Resource editors
Use the Visual C++ resource editors to create and edit menus, dialog boxes, custom controls,
accelerator keys, bitmaps, icons, cursors, strings, and version resources. ClassWizard works with
the editors: for example, when you create a dialog-template resource, you can run ClassWizard to
connect the resource to a dialog class. Resources are user interface objects that you can create with
visual resource editors. Resources include bitmaps, cursors, dialogs, icons, menus and their
accelerator table, string tables and version information.

Message Loop

Once the window is created, the window will interact with the rest of the system by way of
messages. The system sends messages to the window, and the window sends messages back. Most
programs in fact don't do anything but read messages and respond to them. The parts of a Windows
application, such as the forms, buttons, and scroll bars, communicate with each other, with other
applications, and with the system by passing messages.

In Window programming Message is the main communication. The messages are stored in
message queue. The way you retrieve messages from the Message Queue is by creating a Message
Loop. A Message Loop is a loop that checks for messages in the Message Queue. Once a message
is received, the Message Loop dispatches the message by calling a Message Handler, a function
designed to help the Message Loop at processing the message.

In the world of Windows programming, a message is a small packet of data that is sent to a
component to tell it some event has happened. These events could include a timer going off, a key
being pressed on the keyboard, or the user clicking a button. A message is a structure that describes
an event, and Windows delivers the message to the appropriate application, placing it in the
application's message queue. Message loop ends when WM_QUIT message is retrieved

The message map functionality in an MFC application works by the support of 3 Macros,
DECLARE_MESSAGE_MAP, BEGIN_MESSAGE_MAP, and END_MESSAGE_MAP and the
WindowProc function implementation. MFC’s DECLARE_MESSAGE_MAP macro adds three
members to the class declaration: a private array of AFX_MSGMAP_ENTRY structures named
message Entries that contains information correlating messages and message handlers; a static
AFX_MSGMAP structure named messageMap that contains a pointer to the class’s message
Entries array and a pointer to the base class’s messageMap structure; and a virtual function named
GetMessageMap that returns messageMap’s address. BEGIN_MESSAGE_MAP contains the
implementation for the GetMessageMap function and code to initialize the messageMap structure.
The macros that appear between BEGIN_MESSAGE_MAP and END_MESSAGE_MAP fill in
the _messageEntries array, and END_MESSAGE_MAP marks the end of the array with a NULL
entry.

Thus corresponding to each message a class can traverse through it’s and base classes message
map entries to find a handler till it to reach the DefWindowProc.
Application Object

The Application object represents Developer Studio and is the topmost object in the Developer
Studio object hierarchy. From the Application object, you can directly access other Developer
Studio objects by using the Application object's properties and methods, or you can indirectly
access objects through other objects obtained by these properties and methods.

The application object is the object that is loaded first and it interact with the windows to get things
started. Next this object loads in the main window and displays it. The program’s data is stored in
the document object and displaying that data is the view objects job.

Application object job is to start and initialize the program and then show the main window.
Application object is what windows actually runs first by calling the WinMain() method to get the
program started. This object has three tasks. Starting the program, placing main window on the
screen and passing window messages from the operating system to the main window.

Document object

The Document object represents an open document.

Each open document in Developer Studio is represented by a Document object. This object has
members (properties, methods, and events) that you can use to manipulate the document. The
document object is where the program’s data is storedIn a document/view application, data is
stored in a document object. The document object is created when the framework instantiates a
class derived from CDocument. It is an abstract representation of a program’s data that draws a
clear boundary between how the data is stored and how it is presented to the user. That means the
sole purpose of a document object is to manage an application’s data.

Window object

The window object is an object of the C++ CWnd class (or a derived class) that your program
creates directly. It comes and goes in response to your program's constructor and destructor calls.
The main window object is responsible for the title bar, menu bar, toolbar and status bar.
Window object is the object the user uses to interact with the computer.

View Object

The view object displays data in the client area of the window. The OnDraw() method in the .cpp
file allows us to display messages and other objects on the screen. View objects exist for two
purposes: to render visual representations of a document on the screen and to translate the user’s
input—particularly mouse and keyboard messages—into commands that operate on the
document’s data. Thus, documents and views are tightly interrelated, and information flows
between them in both directions
Handle

A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea
is that they provide an abstraction of a resource, so you don't need to know much about the resource
itself to use it. A handle is a number used by Microsoft Windows to keep track of resources (like
windows and memory and files, etc.

Inside the kernel, Windows maintains a table of all the different objects that the kernel is
responsible for. Windows, buttons, icons, mouse pointers, menus, and so on, all get an entry in the
table, and each entry is assigned a unique identifier known as a HANDLE. If you want to pick a
particular entry out of that table, you need to give Windows the HANDLE value, and Windows
will return the corresponding table entry.

HANDLEs are defined as being unsigned 32-bit quantities in <windows.h>, but HANDLEs should
never be used like integers. They are unique identifiers, and if you edit them, or use them in
arithmetic, then they can never be used to get the table entry that they correspond to. In other
words, HANDLEs should be stored, but they should never be changed by the programmer.

HANDLEs are generally prefixed with an "h". BHandles are unsigned integers that Windows uses
internally to keep track of objects in memory. Windows moves objects like memory blocks in
memory to make room, if the object is moved in memory, the handles table is updated.

Example.

HWND Handles to a Window

HINSTANCE variables are handles to a program instance

Client Area

Total area of a window is divided in two parts client area and non-client area. Client area of a

window is the square area of window below title bar where user can place child widgets.

Non-Client Area

Not client area is the area of a window where operating system constructs borders, title bar, menu
bar, minimize/maximize button and exit button etc. Non client area is generally under control of
operating system and depending on the themes selected by user it changes its appearance.
Modal and Modeless Dialog Boxes.

Modal dialog box is the dialog box in which user response is required before continuing with the
program

Modeless dialog box is the dialog box in which the screen remain stable and available to all the
user for use at any time but it doesn’t stop their and allow other user work to be carried out without
any interference.

Modal captures the message loop and doesn’t move on to other objects until the current object is
closed but modeless doesn’t capture it. Modal doesn’t allow its parents window to be accessed
until all other windows are closed but it is allowed in modeless.

Example of Modal is Save and Save As in Microsoft word until they are opened you can not do
anything until you close the window whereas Find and Replace can simultaneously be executed
together.

The MFC framework provides an efficient mechanism for transferring and validating data in a
dialog box through the DDX and DDV routines. Dialog Data Exchange (DDX) is an easy way to
initialize the controls in a dialog box and gather data input by the user. Dialog Data Validation
(DDV) is an easy way to validate data entry in a dialog box.

The framework calls CWnd::DoDataExchange to exchange and validate dialog data. When a class
is derived from CDialog, you need to override this member function if you wish to utilize the
framework's automatic data exchange and validation. An implementation of DoDataExchange is
shown below:

void CDataExchangeDlg::DoDataExchange(CDataExchange* pDX)

CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_strEdit);
DDX_Check(pDX, IDC_CHECK1, m_bCheck);

It's to be noted that DoDataExchange is never called directly, it's called by the CWnd::UpdateData
member function.

BOOL UpdateData( BOOL bSaveAndValidate = TRUE );


UpdateData is called to initialize data in a dialog box, or to retrieve and validate dialog data. The
bSaveAndValidate flag indicates whether a dialog box is being initialized (set bSaveAndValidate
= FALSE) or data is being retrieved (set bSaveAndValidate = TRUE).

Dialog Data Exchange (DDX) A convenient way to expose the input from a dialog, is to map the
control to a public member variable. MFC’sDoDataExchange()uses DDX macros to transfer data
between dialog’s controls and data members.

void CMyDialog::DoDataExchange( CDataExchange* pDX)

DDX_Text (pDX, IDC_NAME, m_strName);

DDX_Text (pDX, IDC_PHONE, m_strPhone);

Linking two CStringdata members to edit controls.

DDX Functions

DDX_CBIndex Initializes or retrieves the index of the current selection of a combo box
control.
DDX_CBString Initializes or retrieves the current contents of the edit field of a combo box
control.
DDX_CBStringExact Initializes or retrieves the current contents of the edit field of a combo box
control.
DDX_Check Initializes or retrieves the current state of a check box control.
DDX_Control Subclasses a given control within a dialog box.
DDX_DateTimeCtrl Initializes or retrieves date and/or time data of a date and time picker
control.
DDX_IPAddress Initializes or retrieves the current value of an IP address control.
DDX_LBIndex Initializes or retrieves the index of the current selection of a list box control.

DDX_LBString Initializes or retrieves the current selection within a list box control.
DDX_LBStringExact Initializes or retrieves the current selection within a list box control.
DDX_MonthCalCtrl Initializes or retrieves the current value of a month calendar control.
DDX_Radio Initializes or retrieves the 0-based index of the radio control that is currently
checked within a radio control group.
The Document/View Architecture

When you create an SDI application, more classes are created for an SDI application than for a
dialog-style application. Each of these classes serves a specific purpose in how SDI applications
operate. Ignoring the About window dialog class, four specific classes make up an SDI application:

 The CWinApp-derived class


 The CFrameView-derived class
 The CDocument-derived class
 The CView-derived class

The CWinApp class creates all the other components in the application. It is the class that receives
all the event messages and then passes the messages to the CFrameView and CView classes.

The CFrameView class is the window frame. It holds the menu, toolbar, scrollbars, and any other
visible objects attached to the frame. This class determines how much of the document is visible
at any time. Very little (if any) of your programming efforts on SDI applications will require
making any modifications or additions to either of these first two classes.

The CDocument class houses your document. This class is where you will build the data structures
necessary to house and manipulate the data that makes up your document. This class receives input
from the CView class and passes display information to the CView class. This class is also
responsible for saving and retrieving the document data from files.

The CView class is the class that displays the visual representation of your document for the user.
This class passes input information to the CDocument class and receives display information from
the CDocument class. Most of the coding that you will do for this class consists of drawing the
document for the user and handling the input from the user. The CView class has several
descendent classes that can be used as the ancestor for the view class. These descendent classes
are listed in the following table

. THE CView DESCENDENT CLASSES.


Class Description

CEditView Provides the functionality of a edit box control. Can be used to implement
simple text-editor functionality.

CFormView The base class for views containing controls. Can be used to provide form-based
documents in applications.

CHtmlView Provides the functionality of a Web browser. This view directly handles the
URL navigation, hyperlinking, and so on. Maintains a history list for browsing
forward and back.
CListView Provides list-control functionality in the Document/View architecture.

CRichEditView Provides character and paragraph formatting functionality. Can be used to


implement a word-processor application.

CScrollView Provides scrolling capabilities to a CView class.

CTreeView Provides tree-control functionality in the Document/View architecture.

MFC not only provides a set of classes to help you work with document objects, but it provides a
complete architecture that ties the various classes together.

The Document / View Architecture is a part of MFC framework that provide logical separation
between application’s data and representation of data.

A document is an object that act as a container of application’s data and view is window object,
usually associated with the client area of screen window through which the user interacts with
the data contained in the document.

Advantages

1) Multiple views---Single document can have multiple views


2) Serialization support
3) Intelligent command routing---Menus, toolbars, status bars
4) Support of Print and Print preview

Compare Document/View Architecture with Dialog-Based Architecture

The MFC document/view architecture includes a combination of a document, in which data is


stored, and a view, which has privileged access to the data. The document/view architecture
separates the storage and maintenance of data from the display of data. This separation facilitates
development of applications that display multiple views of a single set of data simultaneously.
When the application user changes the data in one view, the architecture handles the task of
notifying the other views that they must update to display the modified data

The following table compares the architectures.


Architecture Menus Toolbars Benefits

Document/View · System menu · Fully developed With the fully


similar to the one in toolbar that includes developed menu and
dialog-based buttons for all default toolbar in the
architecture. menu options. document/view
· Application menu architecture, you can
that includes the provide users with an
following options. · Option to add easy-to-use, intuitive
custom toolbar application. These
-New buttons and organize expanded menus and
-Open the buttons. toolbars make it easy
-Save for users to navigate
-Save As a complex
- Print · Includes a status
bar at the bottom of application.
- Print Preview
- Print Setup the frame.
- Undo
- Cut
- Copy
- Paste

Dialog-Based Minimal system No integrated tools With the dialog-


menu that includes or status bars. based architecture,
options for moving you can provide
the dialog box, users with a simple,
viewing the About clean interface for
information, and less complex
exiting the applications.
application.

Creating an SDI Application

To get a good idea of how the Document/View architecture works, and of how you can use it to
build applications, you will build a new version of the drawing application you created on Day 3,
"Allowing User Interaction--Integrating the Mouse and Keyboard in Your Application." In this
version, the user's drawing will be persistent, which means it is not erased each time another
window is placed in front of the application. This version will also be able to save and restore
drawings.
Building the Application Shell

To create the application shell for today's application, follow these steps:

1. Create a new AppWizard project. Name the project

2. On the first step of the AppWizard, select Single Document.

3. Use the default values on the second step of the AppWizard.

4. On the third step of the AppWizard, uncheck the support for ActiveX Controls.

5. On the fourth step of the AppWizard, leave all the default values. Click the Advanced
button.

6. In the Advanced Options dialog, enter a three-letter file extension for the files that your
application will generate (for example, dhc or dvp). Click the Close button to close the
dialog and then click Next to move to the next step of the AppWizard.

7. Use the default settings on the fifth step of the AppWizard.

8. On the sixth and final AppWizard step, you can choose the base class on which your
view class will be based. Leave the base class as CView and click Finish. The AppWizard
will generate the application shell.

Multithreading

MFC distinguishes between two types of threads, Worker Thread and user Interface Thread.
Worker threads are intended to be used as secondary threads which perform some unit of work
without inputs prom the user. Worker thread do not have their own message loop defined nor do
they have an associated window, so there is no direct interaction between a worker thread and
the user. Worker threads are typically used to perform lengthy procedures which can be
processed asynchronously.

user interface threads have an associated message loop and window and can therefore interact
directly with the user. To create a user interface thread one must derive a new class from
CWinThread and override the IniInstance() function to initialize the window that is to be
associated with the thread.
Worker Threads are intended to be used as secondary thread which perform some unit of work
without input from the user. Worker thread do not have their own message loop defined nor do
they have an associated window, so there is no direct interaction between a worker thread and
the user.

Worker thread are typically used to perform lengthy procedures which can be processed
asynchronously

CWinThread *t = AfxBeginThread(function name, parameter , priority ,stacksize ,flags ,


securityattributes )

Example
CWinThread *t=AfxBeginThread(doit,i)

UINT doit(LPVOID param)

Return 0

UI Thread

User Interface threads have an associated message loop and window and can therefor interact
directly with the user.To create a UI thread , one must derive a new class from CWinThread and
override the InitInstance() function to initialize the window that is to be associated with the
thread.

To create a user-interface thread, you use a slightly different version of the AfxBeginThread()
function. The version used to create user-interface threads takes a pointer to a CRuntimeClass
object for your thread class. MFC creates this for you with the RUNTIME_CLASS macro:

AfxBeginThread(RUNTIME_CLASS(CMyThread));

If you want to keep track of the MFC object for your thread, use this:

(CMyThread*) pMyThread = (CMyThread*)


AfxBeginThread(RUNTIME_CLASS(CMyThread));
Keeping a pointer to the MFC thread object enables you to access the member data and functions
of your thread class from other threads.

Thread Synchronization

CcriticalSection

the critical section allows synchronization within the same process.

CcriticalSection cs;

cs.Lock();

StringArray.DoSomething();

cs.Unlock()

CMutex

Mutex is the thread synchronization object which allows to access the resource only one thread
at a time

mutex are used to synchronize the resource with different processes

Cmutex m_mutex(false,”mymutex”)

First parameter– initially lock or not

Second parameter- identifier of mutex and can be accessed from two different process

If you lock critical section in a thread and then the thread exits without unlocking it, then any
other thread waiting on it will be forever blocked.

Mutexes will unlock automatically if the thread exits. Mutex can have time out values.

m_mutex.Lock(600000)

String.Array.Dosomething()

m_mutex.Unlock();

CSemaphore

A semaphore is used to limit simultaneous access to a certain number of threads.

CSemaphore m_semaphore(10,10)

First parameter is the initial reference count


Second parameter is the maximum reference count

Each time we lock the semaphore, it will decrement the reference count by 1, until it reaches
zero.

m_semaphore.Lock(60000);

stringArray.DoSomething();

m_semaphore.UnLock(60000);

Programs

1) Creating a Window

2) Window Class

#include<afxwin.h>
class mframe : public CFrameWnd
{
public:
mframe()
{

CString mwindowclass;
HBRUSH mbrsh;
mbrsh=(HBRUSH)::GetStockObject(LTGRAY_BRUSH);
//mbrsh=CreateSolidBrush(RGB(100,200,50));
//mwindowclass=AfxRegisterWndClass(CS_HREDRAW,AfxGetApp()-
>LoadStandardCursor(IDC_CROSS),mbrsh,AfxGetApp()-
>LoadStandardIcon(IDI_EXCLAMATION));
mwindowclass=AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW,AfxGetApp()-
>LoadStandardCursor(IDC_CROSS),mbrsh,AfxGetApp()-
>LoadStandardIcon(IDI_EXCLAMATION));
Create(mwindowclass,"Hello
MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,CRect(20,20,300,300));
}
};
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(1);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
3) PaintDC

#include<afxwin.h>
class mframe : public CFrameWnd
{
public:
mframe()
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,CRect(20,20,400,400));
}
void OnPaint()
{
//CFrameWnd::OnPaint();

CPaintDC d(this);

CPen mpen(PS_SOLID,5,RGB(100,200,50));
d.SelectObject(&mpen);
CBrush mbrsh(RGB(40,40,140));
d.SelectObject(&mbrsh);

d.MoveTo(50,100);
d.LineTo(250,100);
d.Rectangle(50,120,250,200);

MessageBox("Paint Message","Paint Caption");


}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(1);
m_pMainWnd=p;
return 1;
}
};
map a;

4) Mouse Presence

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
myframe()
{
Create(0,"HELLLO");
}

void test()
{
int value,num;
char str[5];
value=::GetSystemMetrics(SM_MOUSEPRESENT);
if(value==1)
{
MessageBox("Mouse Present","OK");
num=::GetSystemMetrics(SM_CMOUSEBUTTONS);
sprintf(str,"%d",num);
MessageBox(str,"number of buttons");
}
else
MessageBox("Mouse not present","dd");
}

void OnLButtonDown(UINT flag, CPoint pt)


{
MessageBox("Left Button Clicked","LLLBBB");
}

void OnRButtonDown(UINT flag, CPoint pt)


{
MessageBox("Right Button Clicked","RRRBBB");
}

void OnRButtonUp(UINT flag, CPoint pt)


{
MessageBox("Right Button Released","RRBBUP");
}

void OnLButtonUp(UINT flag, CPoint pt)


{
MessageBox("Left Button Released","LLBBDOWN");
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_RBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_RBUTTONUP()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
int InitInstance()
{
myframe *p;
p=new myframe;
p->ShowWindow(3);
p->test();
m_pMainWnd=p;
return 1;
}
};
myapp app;
Output

5) Drawing a Line

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
int x1,y1,x2,y2;
CPen mpen;
myframe()
{
Create(0,"Line Drawing");
mpen.CreatePen(PS_SOLID,2,RGB(255,0,0));
}

void OnLButtonDown(UINT flag, CPoint pt)


{
x1=pt.x;
y1=pt.y;
x2=pt.x;
y2=pt.y;

void OnMouseMove(UINT flag, CPoint pt)


{

CClientDC d(this);
d.SelectObject(&mpen);
if(flag)
{

d.SetROP2(R2_NOTXORPEN);
d.MoveTo(x1,y1);
d.LineTo(x2,y2);
d.MoveTo(x1,y1);
d.LineTo(pt.x,pt.y);
x2=pt.x;
y2=pt.y;
}
}

DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()

class myapp:public CWinApp


{
int InitInstance()
{
myframe *p;
p=new myframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
myapp app;

Output

6) Line Drawing Example 2

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
CPoint pnt;
CPen mpen;
CRect r;
myframe()
{
Create(0,"HELLLO");
mpen.CreatePen(PS_SOLID,2,RGB(255,0,0));
}
void OnLButtonDown(UINT flag, CPoint pt)
{
pnt=pt;
}

void OnLButtonUp(UINT flag, CPoint pt)


{
CClientDC d(this);
GetClientRect(r);
ValidateRect(r);
d.SelectObject(&mpen);
d.MoveTo(pnt);
d.LineTo(pt);

}
void OnPaint()
{
InvalidateRect(r,1);
}

DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_PAINT()
END_MESSAGE_MAP()

class myapp:public CWinApp


{
int InitInstance()
{
myframe *p;
p=new myframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
myapp app;

Output
7) Free Hand Drawing

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:
int x1,y1,x2,y2;

myframe()
{
Create(0,"Free Hand Drwaing");

void OnLButtonDown(UINT flag, CPoint pt)


{
x1=pt.x;
y1=pt.y;

void OnMouseMove(UINT flag, CPoint pt)


{
CClientDC d(this);
if(flag)
{
d.MoveTo(x1,y1);
d.LineTo(pt.x,pt.y);
x1=pt.x;
y1=pt.y;
}
}

DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()

class myapp:public CWinApp


{
int InitInstance()
{
myframe *p;
p=new myframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
myapp app;

Output
8) Different Shapes

#include<afxwin.h>
class mframe : public CFrameWnd
{
public:
mframe()
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,CRect(20,20,550,590));
}
void OnPaint()
{

CPaintDC d(this);

CPen mpen(PS_DOT,1,RGB(0,0,250));
d.SelectObject(&mpen);
CBrush mbrsh(RGB(40,40,140));
d.SelectObject(&mbrsh);
d.MoveTo(50,100);
d.LineTo(230,100);
d.Rectangle(50,120,230,200);
CBrush redbrsh(RGB(255,0,0));
d.SelectObject(&redbrsh);
CPen dashpen(PS_DASH,1,RGB(0,0,250));
d.SelectObject(&dashpen);
int k=d.SaveDC();
d.RoundRect(50,220,230,300,20,20);
CBrush greenbrsh(RGB(0,255,0));
d.SelectObject(&greenbrsh);
d.Ellipse(50,380,430,540);
d.Pie(250,10,350,110,350,110,350,10);
d.RestoreDC(-1);
//d.RestoreDC(k);
POINT pt[5]={250,150,250,300,300,350,400,300,320,190};
d.Polygon(pt,5);
d.TextOut(50,5,"SNGCE",strlen("SNGCE"));
d.DrawText("KOLENCHER EKM KER IND",10,CRect(50,20,150,150),DT_LEFT);
//d.DrawText("SNGCE EKM KER IND",-1,CRect(250,590,450,750),DT_LEFT);

}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
9) Metafile DC

#include<afxwin.h>
#include<afxext.h>
class mframe : public CFrameWnd
{
private:

CMetaFileDC mdc;
HMETAFILE hm;
int flag;
int h;
public:

mframe()
{
Create(0,"Hello MFC",WS_OVERLAPPEDWINDOW,CRect(10,10,500,500));
h=100;
flag=1;
}
void OnPaint()
{
//CFrameWnd::OnPaint();
CPaintDC d(this);
if(flag==1)
{

mdc.Create("mfile");
d.MoveTo(100,100);
d.LineTo(300,400);
mdc.MoveTo(300,100);
mdc.LineTo(100,400);
hm= mdc.Close();
flag=2;
}
else
{
d.PlayMetaFile(hm);
}

}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(1);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
10. Creating a Menu

#include<afxwin.h>
#include "resource.h"

class mframe : public CFrameWnd


{
public:
CMenu men;
mframe()
{
Create(0,"Hello MFC",WS_OVERLAPPED|WS_DLGFRAME,CRect(20,20,400,400));
//,0,MAKEINTRESOURCE(mca));
}
void file()
{
MessageBox("Save as clicked","aa");
}
void exit()
{
DestroyWindow();
}
int OnCreate(LPCREATESTRUCT i)
{
CFrameWnd::OnCreate(i);
men.LoadMenu(mca);
SetMenu(&men);
return 0;

}
void red()
{
CClientDC d(this);
d.SetTextColor(RGB(255,0,0));
d.TextOut(300,300,"SNGCE in Red Color",18);

}
void green()
{
CClientDC d(this);
d.SetTextColor(RGB(0,255,0));
d.TextOut(300,300,"SNGCE in Green Color",20);

}
void ENB(CCmdUI *item)
{
//item->Enable(FALSE);
}
void add()
{

men.GetSubMenu(2)->AppendMenu(MF_STRING,304,"sngce");

}
void remove()
{
men.RemoveMenu(304,MF_BYCOMMAND);
}
void mod()
{
men.ModifyMenu(304,MF_STRING|MF_BYCOMMAND,304,"GURUKULAM");
}

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)

ON_WM_CREATE()
ON_COMMAND(1,file)
ON_COMMAND(ID_EXIT,exit)
ON_COMMAND(201,red)
ON_COMMAND(202,green)
ON_COMMAND(301,add)
ON_COMMAND(302,remove)
ON_COMMAND(303,mod)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

11. Creating Context Menu

#include<afxwin.h>
class mframe : public CFrameWnd
{
public:
CMenu men;
mframe()
{
Create(0,"Hello MFC");
}
void OnContextMenu(CWnd *p,CPoint pt)
{
CRect r;
GetClientRect(r);
ClientToScreen(r);
if(r.PtInRect(pt))
{
CMenu sngce;
CMenu branch;

branch.CreateMenu();
branch.AppendMenu(MF_STRING,202,"CSE");
branch.AppendMenu(MF_STRING,203,"CE");
branch.AppendMenu(MF_STRING,204,"ME");
branch.AppendMenu(MF_STRING,205,"ECE");

sngce.CreatePopupMenu();
sngce.AppendMenu(MF_STRING,101,"MCA");
sngce.AppendMenu(MF_STRING,102,"MBA");
sngce.AppendMenu(MF_STRING,103,"B.Tech");
sngce.AppendMenu(MF_SEPARATOR);

sngce.AppendMenu(MF_POPUP,(unsigned int )branch.m_hMenu,"M.Tech");

sngce.TrackPopupMenu(TPM_CENTERALIGN|TPM_RIGHTBUTTON,pt.x,pt.y,this,0)
;
//CRect(10,10,500,500));

}
else
{
CFrameWnd::OnContextMenu(p,pt);
}
}
void line()
{
MessageBox("Context M","aa");
}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_CONTEXTMENU()
ON_COMMAND(101,line)

END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
12. Menu Item Checking

#include<afxwin.h>
#include "resource.h"

class mframe : public CFrameWnd


{
public:
int check1,check2,check3;
mframe()
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,rectDefault,0,MAKEINTRESOURCE
(IDR_MENU1));
check1=check2=check3=0;
}

void exit()
{
DestroyWindow();
}
void col1()
{
check1=!check1;
//check2=0;
//check3=0;
//check1=1;

}
void col2()
{
check2=!check2;
//check2=1;
//check3=0;
//check1=0;

}
void col3()
{
check3=!check3;
//check2=0;
//check3=1;
//check1=0;
}
void setcheckmark(CCmdUI *item)
{
if(item->m_nID==1)
{
item->SetCheck(check1);
//item->SetRadio(check1);
}
if(item->m_nID==2)
{
item->SetCheck(check2);
//item->SetRadio(check2);
}
if(item->m_nID==3)
{
item->SetCheck(check3);
//item->SetRadio(check3);
}
}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_COMMAND(1,col1)
ON_COMMAND(2,col2)
ON_COMMAND(3,col3)
ON_COMMAND(e1,exit)
ON_UPDATE_COMMAND_UI_RANGE(1,3,setcheckmark)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
13. Button Creation

#include<afxwin.h>
#include"resource.h"
class mframe : public CFrameWnd
{
public:
CButton b1,b2,b3;
CBitmap m1,m2;
mframe()
{
Create(0,"Hello MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME);
}
int OnCreate(LPCREATESTRUCT i)
{
CFrameWnd::OnCreate(i);
m1.LoadBitmap(IDB_BITMAP1);
m2.LoadBitmap(IDB_BITMAP2);
b1.Create("",BS_BITMAP|BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE|BS_CENTE
R,CRect(250,400,300,450),this,101);
b2.Create("",BS_BITMAP|BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE|BS_CENTE
R,CRect(350,400,400,450),this,201);
b3.Create("Clear",BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE,CRect(450,400,500,4
50),this,301);
b1.SetBitmap((HBITMAP)m1.m_hObject);
b2.SetBitmap((HBITMAP)m2.m_hObject);
b1.SetFocus();
return 0;

}
void line()
{
CClientDC d(this);
CPen mpen;
mpen.CreatePen(PS_SOLID,2,RGB(255,0,0));
d.SelectObject(mpen);
d.MoveTo(250,255);
d.LineTo(300,255);
b2.SetFocus();
}
void rectangle()
{
CClientDC d(this);
CPen mpen;
mpen.CreatePen(PS_SOLID,2,RGB(0,255,0));
d.SelectObject(mpen);
d.RoundRect(350,255,400,300,20,20);
b1.SetFocus();
}
void cls()
{
CRect rect;
GetClientRect(rect);
InvalidateRect(rect,1);
}

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_CREATE()
ON_COMMAND(101,line)
ON_COMMAND(201,rectangle)
ON_COMMAND(301,cls)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output

14. Checkbox and Radio Button

#include<afxwin.h>
class mframe : public CFrameWnd
{
public:
CButton checkb[4];
CButton radiob[4];
CButton gr[2];
CButton ck,rd;
CButton set;
CButton rd1,rd2;
mframe()
{
Create(0,"Hello MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME);
}
int OnCreate(LPCREATESTRUCT i)
{
CFrameWnd::OnCreate(i);
checkb[0].Create("MCA",BS_AUTOCHECKBOX|WS_CHILD|WS_VISIBLE,CRect(20
0,110,340,160),this,1);
checkb[1].Create("MBA",BS_AUTOCHECKBOX|WS_CHILD|WS_VISIBLE,CRect(20
0,170,340,220),this,2);
checkb[2].Create("M.Tech",BS_AUTOCHECKBOX|WS_CHILD|WS_VISIBLE,CRect(
200,230,340,280),this,3);
checkb[3].Create("B.Tech",BS_AUTOCHECKBOX|WS_CHILD|WS_VISIBLE,CRect(
200,290,340,340),this,4);
gr[0].Create("Programmes",BS_GROUPBOX|WS_CHILD|WS_VISIBLE,CRect(190,75,
390,390),this,5);
radiob[0].Create("Lateral",BS_AUTORADIOBUTTON|WS_CHILD|WS_VISIBLE|WS
_GROUP,CRect(450,110,550,150),this,6);
radiob[1].Create("Regular",BS_AUTORADIOBUTTON|WS_CHILD|WS_VISIBLE,CR
ect(450,170,550,210),this,7);

gr[1].Create("Type",BS_GROUPBOX|WS_CHILD|WS_VISIBLE,CRect(440,75,590,39
0),this,8);
ck.Create("Check",BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE,CRect(220,450,300,
480),this,10);
rd.Create("Radio",BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE,CRect(320,450,380,4
80),this,11);
set.Create("RESET",BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE,CRect(420,450,50
0,480),this,12);

return 0;
}
void CHECK()
{
char str[120];
str[0]='\0';
if(checkb[0].GetCheck())
{
strcat(str," MCA ");

}
if(checkb[1].GetCheck())
{
strcat(str," MBA ");
}
if(checkb[2].GetCheck())
{
strcat(str," M.Tech ");
}
if(checkb[3].GetCheck())
{
strcat(str," B.Tech ");
}
MessageBox(str,"SNGCE");

}
void RADIO()
{
char str[20];
str[0]='\0';
if(radiob[0].GetCheck())
{
strcpy(str," LATERAL ");
}
if(radiob[1].GetCheck())
{
strcpy(str," Regular ");
}
MessageBox(str,"SNGCE");

}
void RESET()
{
checkb[0].SetCheck(0);
checkb[1].SetCheck(0);
checkb[2].SetCheck(0);
checkb[3].SetCheck(0);
radiob[0].SetCheck(0);
radiob[1].SetCheck(0);

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_CREATE()
ON_COMMAND(10,CHECK)
ON_COMMAND(11,RADIO)
ON_COMMAND(12,RESET)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output

15 List box and combo box


#include<afxwin.h>

class mframe : public CFrameWnd


{
public:
CButton b1,b2;
CListBox lb;
CComboBox cb;
CEdit eb;
CStatic s1,s2;

mframe()
{
Create(0,"Hello MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME);
}
int OnCreate(LPCREATESTRUCT i)
{
CFrameWnd::OnCreate(i);
b1.Create("List",BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE|BS_CENTER,CRect(2
50,400,300,450),this,101);
b2.Create("Combo",BS_PUSHBUTTON|WS_CHILD|WS_VISIBLE|BS_CENTER,CRe
ct(350,400,400,450),this,201);
lb.CreateEx(WS_EX_CLIENTEDGE,"LISTBOX",NULL,WS_CHILD|WS_VISIBLE|L
BS_STANDARD|LBS_DISABLENOSCROLL,CRect(240,80,350,250),this,1);
lb.AddString("MCA");
lb.AddString("MBA");
lb.AddString("MTECH");
lb.AddString("BTECH");
s1.Create("List and Combo
Box",WS_CHILD|WS_VISIBLE,CRect(100,20,300,40),this,5);
eb.CreateEx(WS_EX_CLIENTEDGE,"EDIT","",WS_CHILD|WS_VISIBLE|ES_AUTO
HSCROLL|ES_AUTOVSCROLL|ES_MULTILINE,CRect(240,20,400,45),this,2);
cb.CreateEx(WS_EX_CLIENTEDGE,"COMBOBOX",NULL,WS_CHILD|WS_VISIBL
E|WS_VSCROLL|CBS_DROPDOWNLIST|CBS_SORT,CRect(450,80,580,280),this,3);
cb.AddString("Lateral");
cb.AddString("Reglar");
cb.SetCurSel(0);

return 0;
}
void selectlist()
{
CString str;
int index=lb.GetCurSel();
lb.GetText(index,str);
eb.SetWindowText(str);
}
void selectcombo()
{

int in=cb.GetCurSel();
if(in==0)
{
eb.SetWindowText("Lateral");
}
else
{
eb.SetWindowText("Reglar");
}

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_CREATE()
ON_COMMAND(101,selectlist)
ON_COMMAND(201,selectcombo)
//ON_COMMAND(301,cls)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
16. Font

#include<afxwin.h>
class mframe : public CFrameWnd
{
public:
int i,ht,t;
int k;
char str[15];
TEXTMETRIC tm;
CFont font;
mframe()
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,CRect(20,20,400,400));
t=30;
}
void OnPaint()
{
//CFrameWnd::OnPaint();

CPaintDC d(this);
font.CreateFont(40,10,10,10,FW_BOLD,0,0,0,DEFAULT_CHARSET,0,0,0,0,"Ebrima")
;
//Arial");
//height , width , escapement , orientation , weight , italic , underline , strikeout ,
//charset , outprecision , clipprecision ,quality , pitchandfamily ,facename

d.SelectObject(&font);
d.GetTextMetrics(&tm);
ht=tm.tmHeight+tm.tmExternalLeading;
for(i=0;i<=20;i++)
{
sprintf(str,"%d.SNGCE",i);
d.TextOut(20,t,str,strlen(str));
t=t+ht;
}

}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
17 Keyboard

#include<afxwin.h>
class myframe:public CFrameWnd
{
public:

char str[100];
int k;
CPoint p,st;

myframe()
{
Create(0,"HELLLO");

k=0;
}
void OnKeyDown(UINT ascii,UINT rept,UINT scan)
{
if(ascii==VK_BACK)
MessageBox("backspace","keboard");
if(ascii==VK_F1)
MessageBox("F1","keboard");
}

void OnChar(UINT ascii,UINT rept,UINT scan)


{

CClientDC d(this);
str[k]=ascii;
CSize s=d.GetTextExtent(str,k);
HideCaret();
p.x=s.cx+st.x;
d.TextOut(p.x,p.y,&str[k],1);
CPoint pp=p;
pp.x=p.x+8;
SetCaretPos(pp);
ShowCaret();
k++;
}
void OnLButtonDown(UINT flag, CPoint pt)
{
p=pt;
st=pt;
k=0;
str[100]=NULL;
CreateSolidCaret(2,20);
SetCaretPos(pt);
ShowCaret();

DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_KEYDOWN()
ON_WM_KEYUP()
ON_WM_SYSKEYDOWN()
ON_WM_SYSKEYDOWN()
ON_WM_CHAR()
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

class myapp:public CWinApp


{
int InitInstance()
{
myframe *p;
p=new myframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
myapp app;

Output

18. Modal Dialog Box with validation

#include<afxwin.h>
#include "resource.h"
class mdialog : public CDialog
{
public:
CString sname;
CString sclass;
int rollno;
mdialog(int n):CDialog(n)
{
}
int OnInitDialog()
{
sname="Enter std name";
sclass="Enter Class name";
rollno=0;
return CDialog::OnInitDialog();

}
void DoDataExchange(CDataExchange *pdx)
{
CDialog::DoDataExchange(pdx);
DDX_Text(pdx,IDC_EDIT1,sname);
DDV_MaxChars(pdx,sname,10);
DDX_Text(pdx,IDC_EDIT2,sclass);
DDV_MaxChars(pdx,sname,10);
DDX_Text(pdx,IDC_EDIT3,rollno);
DDV_MinMaxInt(pdx,rollno,1,58);
}
void OnOK()
{
CDialog::OnOK();
char str[100];
sprintf(str," %s %s %d",sname,sclass,rollno);
MessageBox(str,"OK Btton");

}
void OnCancel()
{
CDialog::OnCancel();
MessageBox("Pressed Cancel Btton","Cancel");
}
};

class mframe : public CFrameWnd


{
public:

mframe()
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,rectDefault,0,MAKEINTRESOURCE
(IDR_MENU1));
}

void add()
{
mdialog d(IDD_DIALOG1);
d.DoModal();
}

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_COMMAND(101,add)

END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
19 Modeless Dialog box

#include<afxwin.h>
#include "resource.h"
class mdialog : public CDialog
{
public:
CString sname;
CString sclass;
int rollno;
CString str;
int OnInitDialog()
{
sname="Student Name";
sclass="Enter Class name";
rollno=1;
return CDialog::OnInitDialog();
}
void DoDataExchange(CDataExchange *pdx)
{
CDialog::DoDataExchange(pdx);
DDX_Text(pdx,IDC_EDIT1,sname);
DDX_Text(pdx,IDC_EDIT2,sclass);
DDX_Text(pdx,IDC_EDIT3,rollno);
}
virtual void OnOK();
virtual void OnCancel();
virtual void PostNcDestroy();
};
class mframe : public CFrameWnd
{
public:
mdialog *d;
CString str1;
mframe()
{
Create(0,"Modeless Dialog
Box",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,rectDefault,0,MAKEINTRESOURCE(
IDR_MENU1));
d=NULL;
str1="SNGCE";
}
void OnPaint()
{
CPaintDC p(this);
disp(&p);
}
void disp(CDC *pdc)
{
CRect r;
GetClientRect(&r);
pdc->FillRect(&r,&CBrush(RGB(255,255,255)));
pdc->TextOut(100,100,str1,strlen(str1));
}
void record()
{
//if(d==NULL)
//{
d=new mdialog;
d->Create(mca,this);
d->ShowWindow(1);
//}
//else
//d->ShowWindow(1);
}
void show()
{
CClientDC pp(this);
pp.TextOut(100,100,"Now in Main Window",18);
}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_PAINT()
ON_COMMAND(101,record)
ON_COMMAND(102,show)
END_MESSAGE_MAP()
void mdialog::OnOK()
{
UpdateData(TRUE);
char s[100];
str=sname;
sprintf(s,"%s %d",sclass,rollno);
((mframe*)AfxGetMainWnd())->str1=str;
DestroyWindow();
CClientDC p((mframe*)AfxGetMainWnd());
((mframe*)AfxGetMainWnd())->disp(&p);
}
void mdialog::OnCancel()
{
((mframe*)AfxGetMainWnd())->str1="No records";
DestroyWindow();
CClientDC p((mframe*)AfxGetMainWnd());
((mframe*)AfxGetMainWnd())->disp(&p);
}
void mdialog::PostNcDestroy()
{
delete this;
((mframe*)AfxGetMainWnd())->d=NULL;
}
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
20 File Dialog

#include<afxwin.h>
class mframe :
public CFrameWnd
{
public:
mframe(void);
~mframe(void);
void filereport(void);
DECLARE_MESSAGE_MAP()
afx_msg void OnAppCommand(CWnd* pWnd, UINT nCmd, UINT nDevice, UINT
nKey);
afx_msg void OnIdrMenu1();
};

#include "mapp.h"
#include "mframe.h"

mapp::mapp(void)
{
}
mapp::~mapp(void)
{
}

int mapp::InitInstance(void)
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
#include "mframe.h"
#include "resource.h"
#include<afxdlgs.h>
mframe::mframe(void)
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1));
}

mframe::~mframe(void)
{
}

void mframe::filereport(void)
{
CString str,temp;
CFileDialog fd(1,0,0,0,"Text|*.txt|All Files|*.*|Word Files|*.docx||");
fd.m_ofn.lpstrTitle="SNGCE Browse";
if(fd.DoModal()==IDOK)
{
temp=fd.GetPathName();
str="Fll Path";
str+=temp;

temp=fd.GetFileName();
str+="\nFile Name";
str+=temp;

temp=fd.GetFileExt();
str+="\n File EXT";
str+=temp;
temp=fd.GetFileTitle();
str+="\n File Title";
str+=temp;

MessageBox(str,"File Details");
}

}
BEGIN_MESSAGE_MAP(mframe, CFrameWnd)
ON_COMMAND(101,filereport)

END_MESSAGE_MAP()

#include "afxwin.h"
class mapp :
public CWinApp
{
public:
mapp(void);
~mapp(void);
int InitInstance(void);
};
mapp a;

Output
21 Font Dialog and color dialog

#include<afxwin.h>
#include<afxdlgs.h>
#include "resource.h"

class mframe : public CFrameWnd


{
public:

mframe()
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(men));
}
void font()
{
CClientDC d(this);
CFontDialog f;
CString facename,stname;
CFont mfont;
COLORREF rgb;
int size,wt;
CColorDialog cd;
BOOL strike, line, bold,italics;
Invalidate();
if(f.DoModal()==IDOK)
{
facename=f.GetFaceName();
size=f.GetSize();
rgb=f.GetColor();
wt=f.GetWeight();
strike=f.IsStrikeOut();
line=f.IsBold();
italics=f.IsItalic();
}
if(cd.DoModal()==IDOK)
{
rgb=cd.GetColor();
}
mfont.CreateFont(size,15,0,0,wt,italics,line,strike,0,0,0,0,0,facename);

//mfont.CreateFont(hight,width,escapment,orientation,weight,italic,line,strikeot,charset,ot
precision,cliprecion,qalit,pitchfamil,facenam);

d.SelectObject(&mfont);
d.SetTextColor(rgb);
d.TextOut(50,50,"SNGCE",5);

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_COMMAND(101,font)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output

22 Scroll Bar
#include<afxwin.h>
class mframe : public CFrameWnd
{
public:
CScrollBar scrred,scrgreen,scrbl;
int red,green,bl;
CStatic box;
CClientDC *stdc;
CRect rr;
mframe()
{
Create(0,"Hello MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME);
}
int OnCreate(LPCREATESTRUCT i)
{
CFrameWnd::OnCreate(i);

scrred.Create(SBS_VERT|WS_CHILD|WS_VISIBLE,CRect(170,55,190,260),this,1);
scrgreen.Create(SBS_VERT|WS_CHILD|WS_VISIBLE,CRect(200,55,220,260),this,2);
scrbl.Create(SBS_VERT|WS_CHILD|WS_VISIBLE,CRect(230,55,250,260),this,3);
scrred.SetScrollRange(0,255);
scrred.SetScrollPos(0);
scrgreen.SetScrollRange(0,255);
scrgreen.SetScrollPos(0);
scrbl.SetScrollRange(0,255);
scrbl.SetScrollPos(0);
box.Create("",WS_CHILD|WS_VISIBLE,CRect(262,102,358,198),this,4);
stdc=new CClientDC(&box);
box.GetClientRect(&rr);
red=green=bl=0;
return 0;
}
void OnVScroll(UINT code,UINT pos,CScrollBar *scroll)
{

if(scroll==&scrred)
{
if(code==SB_THUMBTRACK)
red=(int)pos;
if(code==SB_LINEDOWN)
if(red<255)
red++;
if(code==SB_LINEUP)
if(red>0)
red--;
scrred.SetScrollPos(red,1);
}

if(scroll==&scrgreen)
{
if(code==SB_THUMBTRACK)
green=(int)pos;
if(code==SB_LINEDOWN)
if(green<255)
green++;
if(code==SB_LINEUP)
if(green>0)
green--;
scrgreen.SetScrollPos(green,1);
}

if(scroll==&scrbl)
{
if(code==SB_THUMBTRACK)
bl=(int)pos;
if(code==SB_LINEDOWN)
if(bl<255)
bl++;
if(code==SB_LINEUP)
{
if(bl>0)
bl--;
}
scrbl.SetScrollPos(bl,1);
}

CBrush t(RGB(red,green,bl));
stdc->FillRect(&rr,&t);
}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_CREATE()
ON_WM_VSCROLL()
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
23 Toolbar

#include<afxwin.h>
#include<afxext.h>
#include "resource.h"
class mframe : public CFrameWnd
{
public:
CToolBar t;
mframe()
{
Create(0,"Hello MFC");
}
int OnCreate(LPCREATESTRUCT I)
{
t.Create(this,WS_CHILD|WS_VISIBLE|CBRS_TOP|CBRS_BORDER_LEFT|CBRS_B
ORDER_BOTTOM|CBRS_BORDER_RIGHT|CBRS_BORDER_TOP);
t.LoadToolBar(IDR_TOOLBAR1);
return 0;
}
void col1()
{
MessageBox("First tool","toolbar");
}
void col2()
{
MessageBox("Second tool","toolbar");
}
void col3()
{
MessageBox("Third tool","toolbar");
}

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_COMMAND(101,col1)
ON_COMMAND(102,col2)
ON_COMMAND(103,col3)
ON_WM_CREATE()

END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
24 Toolbar with button creation

#include<afxwin.h>
#include<afxext.h>

class mframe : public CFrameWnd


{
public:
CToolBar t;
mframe()
{
Create(0,"Hello MFC");
}
int OnCreate(LPCREATESTRUCT I)
{
unsigned int bttarra[4];
t.Create(this,WS_CHILD|WS_VISIBLE|CBRS_TOP|CBRS_BORDER_LEFT|CBRS_B
ORDER_BOTTOM|CBRS_BORDER_RIGHT|CBRS_BORDER_TOP);
int i;
for(i=0;i<4;i++)
bttarra[i]=101+i;
t.SetButtons(bttarra,4);
t.SetButtonText(0,"Line");
t.SetButtonText(1,"Rec");
t.SetButtonText(2,"Cir");
t.SetButtonText(3,"Hide");
t.SetSizes(CSize(58,50),CSize(26,15));
t.EnableDocking(CBRS_ALIGN_TOP|CBRS_ALIGN_BOTTOM);
t.SetWindowText("Shapes");

EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&t,AFX_IDW_DOCKBAR_TOP);
return 0;
}
void col1()
{
MessageBox("Line","toolbar");

}
void col4()
{

ShowControlBar(&t,FALSE,FALSE);

void col2()
{
MessageBox("Rectangle","toolbar");
}
void col3()
{
MessageBox("circle","toolbar");
}

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_COMMAND(101,col1)
ON_COMMAND(104,col4)
ON_COMMAND(102,col2)
ON_COMMAND(103,col3)
ON_WM_CREATE()

END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output

25 Slider
26 Status Bar
#include<afxwin.h>
#include<afxext.h>
#include "resource.h"

class mframe : public CFrameWnd


{
public:

CStatusBar s;
unsigned int indicators[4];
CRect r;

mframe()
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,rectDefault,0,MAKEINTRESOURCE
(color));
}
int OnCreate(LPCREATESTRUCT i)
{
CFrameWnd::OnCreate(i);
s.Create(this);
indicators[0]=0;
indicators[1]=0;
indicators[2]=0;
indicators[3]=ID_INDICATOR_CAPS;
//indicators[5]=ID_INDICATOR_NUM;
//indicators[6]=ID_INDICATOR_SCRL;
s.SetIndicators(indicators,4);
SetTimer(1,100,NULL);
return 0;
}
void OnSize(UINT type, int cx, int cy)
{
CFrameWnd::OnSize(type,cx,cy);
GetClientRect(&r);
}
void OnMouseMove(UINT flag, CPoint pt)
{

char str[20];
SetCapture();
if(pt.x<r.right && pt.x> r.left && pt.y <r.bottom && pt.y > r.top)
{
sprintf(str,"x=%d y=%d",pt.x,pt.y);
s.SetPaneText(0,str);
}
else
{
s.SetPaneText(0," ");
ReleaseCapture();
}
}

void OnTimer(UINT n)
{
CTime t;
int h,m,sec;
int dd,mm,yy;
t=CTime::GetCurrentTime();
char tm[20];
h=t.GetHour();
m=t.GetMinute();
sec=t.GetSecond();
sprintf(tm,"%d:%d:%d",h,m,sec);
s.SetPaneText(2,tm);
dd=t.GetDay();
mm=t.GetMonth();
yy=t.GetYear();
sprintf(tm,"%d:%d:%d",dd,mm,yy);
s.SetPaneText(1,tm);
}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_MOUSEMOVE()
ON_WM_TIMER()
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
27 Notepad

#include<afxwin.h>
#include "resource.h"
class mframe : public CFrameWnd
{
private:
CEdit e;
public:
mframe()
{
Create(0,"SNGCE
Notepad",WS_OVERLAPPEDWINDOW,rectDefault,0,MAKEINTRESOURCE(IDR_MENU1)
);
}
int OnCreate(LPCREATESTRUCT i)
{
CFrameWnd::OnCreate(i);
e.Create(WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_HSCROLL|ES_MULTILINE|
ES_AUTOVSCROLL,CRect(0,0,0,0),this,1);
e.SetMargins(10,10);
return 0;
}
void OnSize(UINT n,int cx, int cy)
{
CFrameWnd::OnSize(n,cx,cy);
e.MoveWindow(0,0,cx,cy);
}
void SetFocus(CWnd *old)
{
e.SetFocus();
}
void filenew()
{
e.SetWindowText("");
}
void fileload()
{
CString str="";
CString t="";
char temp[100];

CFile fp("notepad.txt",CFile::modeRead);
/* while(fp.Read(temp,100)!=0)
{
str +=temp;
}*/
BYTE buffer[0x400];
DWORD rem=fp.GetLength();
buffer[rem]=0;
while(rem)
{
UINT bread=fp.Read(buffer,sizeof(buffer));
rem=bread;
}
str=(char*)buffer;
SetDlgItemText(1,str);
fp.Close();
}
void filesave()
{
CString str;
GetDlgItemText(1,str);
//str+="\0";
CFile fp("notepad.txt",CFile::modeCreate|CFile::modeReadWrite);
fp.Write(str,str.GetLength());
fp.Close();
}
void fileexit()
{
DestroyWindow();
}
void editcut()
{
e.Cut();
}
void editcopy()
{
e.Copy();
}
void editpaste()
{
e.Paste();
}
void editdelete()
{
e.Clear();
}
void editundo()
{
e.Undo();
}
void onupdateundo(CCmdUI *cm)
{
cm->Enable(e.CanUndo());
}
void onupdatecut(CCmdUI *cm)
{
cm->Enable(istextselected());
}
void onupdatecopy(CCmdUI *cm)
{
cm->Enable(istextselected());

}
void onupdatepaste(CCmdUI *cm)
{

cm->Enable(::IsClipboardFormatAvailable(CF_TEXT));

}
void onupdatedelete(CCmdUI *cm)
{
cm->Enable(istextselected());

}
int istextselected()
{
int start,end;
e.GetSel(start,end);
return (start!=end);
}
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_SETFOCUS()
ON_COMMAND(101,filenew)
ON_COMMAND(102,fileload)
ON_COMMAND(103,filesave)
ON_COMMAND(301,fileexit)
ON_COMMAND(201,editcopy)
ON_COMMAND(202,editpaste)
ON_COMMAND(203,editcut)
ON_COMMAND(204,editdelete)
ON_COMMAND(205,editundo)
ON_UPDATE_COMMAND_UI(201,onupdatecopy)
ON_UPDATE_COMMAND_UI(202,onupdatepaste)
ON_UPDATE_COMMAND_UI(203,onupdatecut)
ON_UPDATE_COMMAND_UI(204,onupdatedelete)
ON_UPDATE_COMMAND_UI(205,onupdateundo)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
28 Single Document Interface example 1

Create a Document View Architecture using Application wizard.

Add the following code in the Doc.h


public:
CString str;
CString read(void);

Add the following code in the Doc.cpp


Csdiexm2Doc::Csdiexm2Doc()
{
// TODO: add one-time construction code here

str = _T("");
}

BOOL Csdiexm2Doc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;

// TODO: add reinitialization code here


// (SDI documents will reuse this document)
str="VC++ SDI";
return TRUE;
}
CString Csdiexm2Doc::read(void)
{
return str;
}

Modify the OnDraw function in the View.cpp

void Csdiexm2View::OnDraw(CDC* pDC)


{
Csdiexm2Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;

CString temp=pDoc->read();

pDC->TextOut(20,20,temp,5);
}
29 Worker Thread

#include<afxwin.h>
#include "resource.h"
class CThreadDlg : public CDialog
{
public:
CThreadDlg(int n):CDialog(n)
{
}
void OnBnClickedStop();
void OnBnClickedStart();
VOID OnTimer(UINT_PTR nIDEvent);
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(CThreadDlg,CDialog)
ON_COMMAND(101,OnBnClickedStart)
ON_COMMAND(201,OnBnClickedStop)
ON_WM_TIMER()
END_MESSAGE_MAP()

int gnCurValue;
int gnMaxValue;
BOOL gfStopNow;
UINT MyThreadProc( LPVOID pParam )
{
while ( !gfStopNow && (gnCurValue < gnMaxValue) ) {
gnCurValue++;
Sleep( 50 );
}
return(1);
}
void CThreadDlg::OnBnClickedStart()
{
gnCurValue= 0;
gnMaxValue= 5000;
gfStopNow= 0;

SetTimer(1234,100,0);

AfxBeginThread( MyThreadProc, 0 );
}

void CThreadDlg::OnBnClickedStop()
{
gfStopNow= TRUE;
KillTimer(1234 );
}

void CThreadDlg::OnTimer(UINT_PTR nIDEvent)


{
CString sStatusMsg;
sStatusMsg.Format("Running: %d", gnCurValue );
SetDlgItemText(IDC_EDIT1,sStatusMsg);
CDialog::OnTimer(nIDEvent);
}

class mframe : public CFrameWnd


{
public:

mframe()
{
Create(0,"Thread
Example",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,rectDefault,0,MAKEINTRESOU
RCE(MCA));
}

void thrd()
{
CThreadDlg d(IDD_DIALOG1);
d.DoModal();
}
void EXIT()
{
DestroyWindow();
}

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)
ON_COMMAND(301,thrd)
ON_COMMAND(401,EXIT)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output
30 User Interface Thread with Synchronization

MyUIThread.h

#pragma once
#include "afxwin.h"
class CMyUIThread :
public CWinThread
{

DECLARE_DYNCREATE(CMyUIThread)
public:
virtual BOOL InitInstance();
};

MyUIThread.cpp

#include "MyUIThread.h"
#include<afxmt.h>
CMutex mt(0,"mtx");
class myframe1:public CFrameWnd
{
public:
int x1,y1,x2,y2;

myframe1()
{

Create(0,"Thread
Example",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,CRect(120,120,400,400));

void OnLButtonDown(UINT flag, CPoint pt)


{
x1=pt.x;
y1=pt.y;

void OnMouseMove(UINT flag, CPoint pt)


{
mt.Lock(1000);
CClientDC d(this);
if(flag)
{
d.MoveTo(x1,y1);
d.LineTo(pt.x,pt.y);
x1=pt.x;
y1=pt.y;
}
mt.Unlock();
}

DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe1,CFrameWnd)
ON_WM_LBUTTONDOWN()
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()

IMPLEMENT_DYNCREATE(CMyUIThread,CWinThread)
BOOL CMyUIThread::InitInstance()
{
myframe1 *p;
p=new myframe1;
p->ShowWindow(1);
m_pMainWnd=p;

return TRUE;
}

Source.cpp

#include<afxwin.h>
#include "resource.h"
#include "MyUIThread.h";
class mframe : public CFrameWnd
{
public:
CMenu men;
CEdit e1,e2;
mframe()
{
Create(0,"Hello
MFC",WS_OVERLAPPEDWINDOW|WS_DLGFRAME,CRect(20,20,400,400),0,MAKEINTR
ESOURCE(mca));
}

void exit()
{
DestroyWindow();
}
int OnCreate(LPCREATESTRUCT i)
{
CFrameWnd::OnCreate(i);
e1.Create(WS_CHILD|WS_VISIBLE,CRect(50,50,70,70),this,1);
e2.Create(WS_CHILD|WS_VISIBLE,CRect(150,150,170,170),this,2);
return 0;

}
void one(void)
{
CWinThread *p=::AfxBeginThread(RUNTIME_CLASS(CMyUIThread));
}
void two(void)
{
CMyUIThread *p=new CMyUIThread;
p->CreateThread();
}

DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(mframe,CFrameWnd)

ON_WM_CREATE()
ON_COMMAND(101,one)
ON_COMMAND(102,two)
ON_COMMAND(ID_EXIT,exit)
END_MESSAGE_MAP()
class map : public CWinApp
{
public:
int InitInstance()
{
mframe *p;
p=new mframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
map a;

Output

You might also like