Introducing MFC
Programming Windows with MFC, Second Edition. Jeff Prosise
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
Hello, MFC
Many Years Ago Windows Applications written in C:
Knowing the ins and outs of a new operating system
Knowing hundreds of different API functions
Today C++ has become the professional Windows
programmers language of choice.
MFC is a class library that:
Abstracts the Windows API
Encapsulates the basic behavior of Windows
Windows uses the Win32 API.
Acronyms
SDK Software Development Kit
API Application Programming Interface
MFC Microsoft Foundation Classes
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
The Windows Programming Model
Traditional Programs: Procedural programming model.
Programs execute top-to-bottom.
The path varies depending on the input and conditions.
Windows programs: Event-driven programming model.
Applications respond to events, by processing
messages sent by the operating system to the application
(and by the application to itself !!!).
events keystroke, mouse click, command for windows repaint
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
The Message Handler
can call local function, or
API functions.
API functions such as
creating a window,
drawing a line,
performing file I/O and
much more.
API functions are
contained in DLLs.
DLL
Dynamic Link Libraries
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
Messages, Messages
Message
WM_CHAR
WM_COMMAND
WM_CREATE
WM_DESTROY
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_MOUSEMOVE
WM_PAINT
WM_QUIT
WM_SIZE
Sent When
A character is input from the
keyboard.
The user selects an item from a menu,
or a control sends a notification to its
parent.
A window is created.
A window is destroyed.
The left mouse button is pressed.
The left mouse button is released.
The mouse pointer is moved.
A window needs repainting.
The application is about to terminate.
A window is resized.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
Messages, Messages (Cont.)
The MSG structure contains message information from the
message queue.
typedef struct tagMSG
{
HWND hwnd;
//
UINT message; //
WPARAM wParam;//
LPARAM lParam;//
} MSG;
Uniquely identifies a window.
Specifies the message type.
Additional information
about the message.
For wParam and lParam, the exact meaning depends on the value
of the message member. For WM_LBUTTONDOWN it is the
state of the Ctrl or Shift keys, and the mouse coordinates.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
Hungarian Notation
Prefix
b
c or ch
clr
cx, cy
dw
h
l
n
p
sz
w
wnd
str
m_
Data Type
BOOL
char
COLORREF
Horizontal or vertical distance
DWORD
Handle
LONG
int
Pointer
Zero-terminated string
WORD
CWnd
CString
class member variable
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
Note:
Prefixes can be
combined:
pszName
m_nAge
Introducing MFC
MFC is the C++ library Microsoft provides to place an
object-oriented wrapper around the Windows API.
No need to call the Windows API directly.
Create objects from MFC classes and call member
functions (some functions are thin wrappers around the
API).
Visual C++ Wizards.
MFC is also an application framework.
Helps define the structure of an application and handles
many routine chores.
Document / View architecture.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
The First MFC Application
Hello.h
class CMyApp : public CWinApp {
public:
virtual BOOL InitInstance ();
};
class CMainWindow : public CFrameWnd {
public:
CMainWindow ();
// ctor
protected:
afx_msg void OnPaint ();
DECLARE_MESSAGE_MAP ()
};
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
Hello.cpp
#include <afxwin.h>
#include "Hello.h"
CMyApp myApp;
// The one and only application
// CMyApp member functions
BOOL CMyApp::InitInstance () {
m_pMainWnd = new CMainWindow; // create app window
m_pMainWnd->ShowWindow (m_nCmdShow);
m_pMainWnd->UpdateWindow (); // force repaint
return TRUE;
// otherwise application shutdown
}
// CMainWindow message map and member functions
BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
ON_WM_PAINT ()
END_MESSAGE_MAP ()
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
10
Hello.cpp (cont.)
CMainWindow::CMainWindow () {
Create (NULL, _T ("The Hello Application"));
}
void CMainWindow::OnPaint () {
CPaintDC dc (this);
// Device context
CRect rect;
// Client rectangle
GetClientRect (&rect); //
area
dc.DrawText (_T ("Hello, MFC"), -1, &rect,
DT_SINGLELINE DT_CENTER DT_VCENTER);
}
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
11
The Hello Application
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
12
The Application Object
The heart of an MFC application is an application object based
on the CWinApp class.
CWinApp class
provides the message loop that retrieves messages.
dispatches them to the applications window.
An application can have one, and only one, application object.
CMyApp declares no data members and overrides one inherited
function.
InitInstance is called early.
InitInstance is where a window is created.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
13
The InitInstance Function
CWinAp::InitInsance is a virtual function.
Its purpose is to provide the application with the opportunity to
initialize itself.
At the very least, this means creating the window that will
represent the application on the screen.
m_pMainWnd is a CMainWindow object data member
variable.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
14
The Frame Window Object
Hellos window class, CMainWindow, is derived from MFCs
CFrameWnd class.
A Frame window is a top level window that serves as an
applications primary interface to the outside world.
The window seen on the screen is created in CMainWindows
constructor.
Creates first argument, NULL, creates the default frame
window.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
15
Painting the Window
Hellos window class get painted on WM_PAINT messages.
In Hello, these are processed by OnPaint().
All graphical output is preformed through device context
objects that abstract the physical destinations for output.
Default font and text color are used.
CPaintDC is a special case that is used only in WM_PAINT.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
16
The Message Map
How did a WM_PAINT message turn to a call to OnPaint() ?
A message map is a table that correlates messages and member
functions. Some complex macros by MFC.
How to create a message map:
1. Declare it by adding DECLARE_MESSAGE_MAP.
2. Implement it by placing macros identifying messages
between BEGIN_MESSAGE MAP and
END_MESSAGE_MAP.
3. Add member function to handle the messages.
Any class derived from CCmdTarget can contain a
message map.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
17
Message Map (Cont.)
Usage of other generic macros:
ON_MESSAGE(WM_SETTEXT, OnSetText)
With the declaration:
afx_msg LRESULT OnSetText(WPARAM wParam,
LPARAM lParam);
Or command macros provided by
ON_COMMAND(ID_FILE_OPEN, OnFileOpen)
For the File Open command.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
18
Drawing in a Window
The part of Windows responsible for graphics output is the GDI.
Windows created a Device Independent output model, allowing
identical code for all graphics adapters, printers and other
devices.
The Device Context object:
Serves as the key that unlocks the door to output devices.
Encapsulates the GDI functions used for output.
CPaintDC* pDC = new CPaintDC(this);
// Do some drawing
delete pDC;
GDI Graphics Device Interface
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
19
Windows Coordinate System
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
20
Device Context Classes
Class Name
Description
CPaintDC
For drawing in a window's client area (OnPaint()
handlers only)
CClientDC
For drawing in a window's client area (anywhere but
OnPaint())
CWindowDC
For drawing anywhere in a window, including the
nonclient area
All devices have the same functions.
Each classs ctor and dtor call the appropriate
functions to get and release the Device Context.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
21
Drawing With the GDI
Function
Description
MoveTo
Sets the current position in preparation for drawing
LineTo
Draws a line from the current position to a specified position
and moves the current position to the end of the line
SetPixel
Draws a single pixel
Polyline
Connects a set of points with line segments
Ellipse
Draws a circle or an ellipse
Rectangle
Draws a rectangle with square corners
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
22
GDI Pens
Windows uses the pen that is currently selected into the device
context to draw lines and borders.
MFC represents GDI pens with the class CPen.
CPen pen(PS_SOLID, 1, RGB(255, 0, 0));
CPen* pOldPen = dc.SelectObject(&pen);
// drawing using 1-pixel width solid red pen
dc.SelectObject(pOldPen); // dtor will be
called for the local pen
CPen uses three defining characteristics: style, width and color.
Note: the GDI object was deselected at the end of its usage.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
23
The Mouse and the Keyboard
The two most common input devices are the mouse and the
keyboard.
Their input comes in the form of messages.
The WM_ messages, require further processing before being
sent to the application.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
24
Getting Input from the Mouse
Reported mouse events are:
WM_xBUTTONaction
where x[L|M|R] and action[DOWN|UP|DBLCLK]
for left/middle/right button press/release/doubleclick.
// WM_MBUTTONDBLCLK on a middle button double click.
WM_MOUSEMOVE
for cursor movement.
A left double click creates the following messages:
WM_LBUTTONDOWN
WM_LBUTTONUP
WM_LBUTTONDBLCLK
WM_LBUTTONUP
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
25
Mouse Message Map
Message map macros and message handlers:
Message
Message Map Macro
Function
WM_LBUTTONDOWN
ON_WM_LBUTTONDOWN
OnLButtonDown
WM_MOUSEMOVE
ON_WM_MOUSEMOVE
OnMouseMove
Prototyped as follows:
afx_msg void OnMsgName(UINT nFlags,
CPoint point);
Where point is the mouse location at the action and nFlags is the state of the
mouse buttons, Shift and Ctrl keys.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
26
Message Box
A useful tool to display messages:
int AfxMessageBox (LPCTSTR lpszText,UINT nType=IDOK,
UINT nIDHelp = 0 );
For example:
AfxMessageBox(_T("X
wins),MB_OK);
Which returns with a IDOK code.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
27
Getting Input from the Keyboard
A windows application learns of keyboard events just like the
mouse, through messages.
For printable characters, a program receives a message
whenever the key is pressed.
Just process the WM_CHAR message and check for key codes.
This message is mapped with an ON_WM_CHAR entry to
OnChar().
afx_msg void OnChar(UINT nChar,
UINT nRepCnt, UINT nFlags);
Other virtual keys (Alt, ESC, PgUp, Left Arrow )
are handled differently.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
28
Menus
Drop down menus are the most widely recognized GUI.
Menus contribute to programs ease of use.
Windows handles menus graphically, and MFC routes menu
item commands to designated class members.
Menus resources can be placed in the resource file, and loaded
on run time. The menu editing is done in Visual C++ resource
editor.
A resource file (.rc) defines the applications resources,
such as binary objects, menu, icons etc
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
29
Menu Commands
WM_COMMAND messages are sent when selecting menu
items (for example with an ID_FILE_NEW identifier).
An ON_COMMAND statement in the message map links this
messages to a class member function.
ON_COMMAND(ID_FILE_NEW, OnFileNew)
Prototyped as
afx_msg void OnFileNew();
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
30
Updating the Items in a Menu
MFC provides a convenient mechanism for keeping menu
items updated.
ON_UPDATE_COMMAND_UI macros in the message map
link selected member functions to serve as update handlers.
ON_UPDATE_COMMAND_UI(ID_COLOR_RED,OnUpdateColorRed)
void CMainWindow::OnUpdateColorRed(CCmdUI* pCmdUI){
pCmdUI->SetCheck (m_nCurrentColor == 0);
}
Other CCmdUI methods are Enable(), SetCheck(), SetRadio()
and SetText().
ON_UPDATE_COMMAND_UI connects menu items to update handlers.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
31
Add Windows Message Handlers
Visual Studios ClassWizard can be used to add command
handlers and update handlers.
See .net class wizard tutorial on the course web site
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
32
Controls
A control is a special kind of window designed to convey information to the
user or to acquire input.
The classic controls are:
Control Type
WNDCLASS
MFC Class
Buttons
"BUTTON"
CButton
List boxes
"LISTBOX"
CListBox
Edit controls
"EDIT"
CEdit
Combo boxes
"COMBOBOX"
CComboBox
Scroll bars
"SCROLLBAR"
CScrollBar
Static controls
"STATIC"
CStatic
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
33
The Classic Controls
MFC uses message maps to link control notifications to class
member functions.
ON_BN_CLICKED(IDC_BUTTON, OnButtonClicked)
There are ON_EN macros for edit controls and ON_LBN
macros for list box controls.
The generic ON_CONTROL macro handles all notifications
and all control types.
Controls are windows! Some useful inherited CWnd member
functions are SetWindowText, SetFont, EnableWindow etc
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
34
Dialog Boxes
A dialog box is a window that pops up to obtain input from the
user.
A modal dialog box disables its parent window until dismissed
(like file open dialog)
A modeless dialog box acts as a conventional window. It does
not disable its parent (like floating toolbar).
Both are encapsulated in MFCs CDialog class.
Use & to place an underline in the caption of a control.
Save &As Save As
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
35
Creating a Modal Dialog Box
Create a new dialog using VC++ Insert Dialog command, from
the Resource Tab.
Modify the dialog by adding desired controls.
Double Clicking the dialog opens the ClassWizard which
guides to the addition of a new class, inherited from CDialog.
VC++ creates the new class, and places it in the project, linking
it to the dialog box.
Activation of the new dialog class is done simple by:
CMyDialog dlg;
if ( dlg.DoModal() == IDOK ) {
// The user clicked OK; do something !
}
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
36
Dialog Data Exchange (DDX)
A convenient way to expose the input from a dialog, is to map
the control to a public member variable.
MFCs DoDataExchange() uses DDX macros to transfer data
between dialogs 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 CString data members to edit controls.
The pDX argument is a pointer to a CDataExchange object.
Note: The linkage is only during entry and exit of the dialog.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
37
DDX Functions
DDX Function
Description
DDX_Text
Associates a BYTE, an int, a short, a UINT, a
long, a DWORD, a CString, a string, a float, a
double, a COleDateTime, or a COleCurrency
variable with an edit control.
DDX_Check
Associates an int variable with a check box
control.
DDX_Radio
Associates an int variable with a group of radio
buttons.
DDX_LBString
Associates a CString variable with a list box.
DDX_LBStringExact
Associates a CString variable with a list box.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
38
Dialog Data Validation (DDV)
DDV allows MFC to validate the values entered into a dialogs
control before the dialog is dismissed.
The validation falls into two categories:
Validate numeric variables so they fall within specified limits.
Validate CString variable length to a certain limit.
void CMyDialog::DoDataExchange(
CDataExchange* pDX){
DDX_Text (pDX, IDC_COUNT, m_nCount);
DDV_MinMaxInt (pDX, m_nCount, 0, 100);
}
The DDV function call should immediately follow the DDX.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
39
DDX and DDV from ClassWizard
ClassWizard can help in the addition of DDX and DDVs.
To add a DDX or DDV to a dialog box:
Show the dialog in the resource view.
Right click the selected control and choose Add Variable.
Type the member variable name and select the varibale type
in the Add Member Variable dialog box.
For numeric and string variables limiting, just add restrictions.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
40
Interacting with other controls
It is possible to get a CWnd pointer to any control in a dialog
box.
MFCs DDX_Control function offers this capability.
DDX_Control(pDX, IDC_LIST, m_wndListBox);
Now adding strings to the list box is a simple:
m_wndListBox.AddString(_T(One));
Using ClassWizard to add DDX_Control is similar, with the
difference of choosing Control instead of Value in the Add
Member Variable dialog box.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
41
Common Dialogs
Windows provides standard implementation of several common dialog
boxes. MFC provides C++ interface to these classes.
Class
Dialog Type(s)
CFileDialog
Open and Save As dialog boxes.
CPrintDialog
Print and Print Setup dialog boxes.
CPageSetupDialog
Page Setup dialog boxes.
CFindReplaceDialog
Find and Replace dialog boxes.
CColorDialog
Color dialog boxes.
CFontDialog
Font dialog boxes.
Introducing MFC - Center for Graphics and Geometric Computing,
Technion
42