lecture 7 introduction to mfc programming
TRANSCRIPT
1
Lecture 7Introduction to MFC
Programming:
The Application/Window ApproachWindow Message, WM_LBUTTONDOWN, etc..Menu Message, WM_COMMAND
2 /34
Microsoft Foundation Classes
MFC, is a class library that assists programmers in creating Windows-based applications
Perhaps two of the most important aspects of MFC programming are as follows: MFC adds object-oriented programming capabilities to Windows API
programming MFC encapsulates the Windows API into a logically organized class
hierarchy : Encapsulation means that the C++ class CWnd, for example, contains
HWND m_hWnd: a member variable of type HWND, and BOOL ShowWindow (int nCmdShow) : the class's member functions encapsulate
calls to Win32 functions.
The class member functions typically have the same name as the Win32function they encapsulate. :ShowWindow()
3 /34
MFC Class Library
The MFC class library consists of two major sections:
The MFC class hierarchy
Global functions or variables and macros
If a function or variable is not a member of a class, it is a global function or variable
Most of the MFC classes are defined in the afxwin.h file, must include that file in the header files
5 /34
The library’s classes are classified in the following (~10 groups):
Root Class: CObject Most of the classes in the Microsoft Foundation Class (MFC) Library
are derived from a single base class at the root of the class hierarchy.
MFC Application Architecture Classes: CWinApp, CDocument,CView Application and Thread Support Classes Document Classes View Classes Frame Window Classes Document-Template Classes, etc.
Window, Dialog, and Control Classes: CDialog, CEdit, CStatic Dialog Box Classes Control Classes Control Bar Classes, etc.
6 /34
Drawing and Printing Classes: CDC, CBrush, CPen Output (Device Context) Classes Drawing Tool Classes
Simple Data Type Classes: CPoint, CRect Array, List, and Map Classes: CArray, CList, CMap File and Database Classes: CFile, CDatabase
File I/O Classes DAO Classes ODBC Classes OLE DB Classes
The library’s classes are classified in the following: (cont.)
7 /34
The library’s classes are classified in the following: (cont.)
Internet and Networking Classes : CHttpFilter, CSocket ISAPI Classes Windows Sockets Classes Win32 Internet Classes
OLE Classes: COleDocObjectItem (Object Linking and Embedding ) OLE Container Classes OLE Server Classes OLE Drag-and-Drop and Data Transfer Classes OLE Common Dialog Classes OLE Automation Classes OLE Control Classes Active Document Classes OLE-Related Classes
Debugging and Exception Classes: CException Debugging Support Classes Exception Classes
ยกตัวอยาง Word, excelเมนูเปลีย่น
8 /34
2nd Section:MFC Global Functions or Variables and Macros (เรียกใชที่คลาสใดๆ ก็ได) If a function or variable is not a member of a MFC class, it is
Global function : Begin with Afx prefix (Application FrameworKS) or
Global variable : Begin with afx prefix
Macros: all uppercase letters
BEGIN_MESSAGE_MAP() and END_MESSAGE_MAP(), which are used for handling messages
(See Help for more information, เปด MFC reference)
Independent of span MFC class hierarchy
9 /34
The MFC macros and global offer functionality in the following categories:
General MFC: TRY, CATCH, AfxMessageBox() Exception processing CString formatting and message-box display Message maps , etc…
Database:AFX_ODBC_CALL , AfxGetHENV Internet DHTML Event Maps OLE & OLE Controls
10 /34
Some Important Global Functions(2nd Section, cont.)
AfxMessageBox()-- Message boxes are predefined windows
AfxAbort() -- unconditionally terminate an app
AfxBeginThread() -- Create & run a new thread
AfxGetApp() -- Returns a pointer to the application object
AfxGetMainWnd() -- Returns a pointer to application’s main window
AfxGetInstanceHandle() -- Returns handle to applications’s current instance :HINSTANCE
AfxRegisterWndClass() -- Register a custom WNDCLASS for an MFC app
11 /34
To Develop a MFC program
Primary task in writing MFC program— to create Classes: most will be derived from MFC library
classes Member Functions: ShowWindow()--a member of CWnd class TextOut()--a member of CDC LoadBitmap()--a member of CBitmap
data memebers: CWnd::m_hWnd
Apps can also call API functions directly Use Global Scope Resolution Operator(::), for example: ::UpdateWindow(hWnd);
12 /34
MFC Notation
All MFC class names begin with C Additionally, data members of MFC
classes are prefixed with m_
Should begin class names with a C and data members with m_ in order to identify as an MFC program
13 /34
The Application/Window ApproachA Minimal MFC Program
Must contain two classes : An application class derived from CWinApp
encapsulates the initialization, running, and termination of an application
ex. class CApp : public CWinApp {}
A window class usually derived from CFrameWnd Defines the application's main window ex. class CMainWin : public CFrameWnd {}
These & other MFC classes brought in by using#include <afxwin.h>
14 /34
ขั้นตอนการสราง Minimal MFC prog1. สรางคลาส derive จากคลาส CFrameWnd
a) สราง constructor และ destructor ของคลาสที่สรางขึ้นใหมb) ใน constructor ของคลาส ให implement ฟงกชัน Create() เพื่อสราง main
window
2. สรางคลาส derive จากคลาส CWinAppa) สราง constructor และ destructor ของคลาสที่สรางขึ้นใหมb) Override ฟงกชัน InitInstance() และภายใน body ของฟงกชันนี้ตองประกอบดวย
ขั้นตอนดังนี้
i. เซ็ตคา pointer ชี้ไปยังอ็อปเจ็คของคลาสในขอ 1 ใหกับ m_pMainWndii. สั่งแสดง main window ดวยคําสั่ง m_pMainWnd->ShowWindow(m_nCmdShow);
iii. สั่ง update main window ดวยคําสั่ง m_pMainWnd->UpdateWindow();
3. สรางออ็ปเจ็คจากคลาสในขอ 2a) Each application that uses the Microsoft Foundation classes
can only contain one object derived from CWinAppb) Global level
วาด UML
15 /34
// file of prog1.h#include <afxwin.h>class CMainWin : public CFrameWnd{public:
CMainWin(); virtual ~CMainWin();
};
// file of prog1.cpp#include "prog1.h" //declarations
CMainWin::~CMainWin(){}CMainWin::CMainWin(){
Create(NULL, "An MFC pplication Skeleton");
}class CApp : public CWinApp{public:
CApp();virtual ~CApp();virtual BOOL InitInstance();
//must override this fn. };
// Our CApp class function definitionsCApp::CApp(){}CApp::~CApp(){}// Initialize the applicationBOOL CApp::InitInstance(){
m_pMainWnd = new CMainWin(); m_pMainWnd->ShowWindow(m_nCmdShow);m_pMainWnd->UpdateWindow();return TRUE;
}// Instantiate the applicationCApp App;// create a CApp object and // begin execution
CWnd* m_pMainWndเปน inherited data member จากคลาส CWinThread:Holds a pointer to the application’s main window.
CWinApp::m_nCmdShow corresponds to the nCmdShow parameter passed by Windows to WinMain.
16 /34
Sequence of Execution
WinMainCalls
InitInstance
Standard function supplied by framework application
Initializes current instance of the application
Calls
Run Runs the message loop
Calls
ExitInstance Cleans up after the application close
InitInstance, Run, ExitInstance เปน member fns. ของ CWinApp
17 /34
Global functions to access your CWinApp object In addition to the CWinApp member functions, the
Microsoft Foundation Class Library provides the following global functions AfxGetApp Obtains a pointer to the CWinApp object
:CWinApp * (return type) AfxGetInstanceHandle Obtains a handle to the
current application instance :HINSTANCE AfxGetResourceHandle Obtains a handle to the
application's resources. Load the menu specifying the module handle where resource is
to be found & resource ID HMENU hMenu = ::LoadMenu(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MENU1));
19 /34
Project|Add new Items...:Header file(.h) & Declaration file (.cpp)
Visual C++|Code|C++ File(.cpp) or Header File (.h)
20 /34
Enable MFC support in win 32 AppProject|…properties
Use MFC in a Shared DLL
•By default, Win32 Application projects do not support MFC programming•In order to enable MFC support in a Win32 Application project,
•Set “Use MFC in a Shared DLL” or “Use MFC in a Static Library”•If no, compile error•Character set : not set
21 /34
Build|Run
The CFrameWnd class creates a simple window with a frame,title bar, system menu, and control buttons
23 /34
Message Processing under MFC
Like API programs, MFC programs must handle messages from Windows
API mechanism: big switch/case statement
Handle notification messages from child windows.
Child Window Notification Message Handlers
Handles WM_COMMAND messages generated by user menu selections or menu access keys.
WM_COMMAND Message Handlers
Handle WM_ messages, such as WM_LBUTTONDOWN, WM_PAINT.
WM_ Message Handler( Application|Window Approach)
DescriptionMessage Categories
MFC mechanism: "message maps" (lookup tables)
24 /34
Message Handling between Win 32 API & MFC
คลาสที่สามารถจะดักจับเมสเสจไดจะตองเปนคลาสที่ derive มาจากคลาส CCmdTarget ซึ่ง CFrameWnd ก็ derive มาจากคลาสนี้
• Encapsulates the messaging features of the Windows API
CCmdTarget
CFrameWnd
CWnd
CView
CDialog
25 /34
Implement a Message MapTo have your class do something in response to a message:1. Add DECLARE_MESSAGE_MAP statement to the class definition
(header file, *.h). & prototype of function handler2. In implementation file ( *.cpp)
2.1 Identifying the messages between BEGIN_MESSAGE_MAPmacro and END_MESSAGE_MAP macro
• Need to tell it the class name and the superclass name2.2 Add Member Functions to handle the messages
Example: ตองการให app รับเมสเสจจากการกดเมาสปุมซาย- function prototype ใน .h ไฟล:DECLARE_MESSAGE_MAP;afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
- Define message macros ใน .cpp ไฟล:BEGIN_MESSAGE_MAP(CMainWin, CFrameWnd)
ON_WM_LBUTTONDOWN()//ใชชื่ออื่นไมไดเปน Macro มาตรฐานEND_MESSAGE_MAP()void CMainWin::OnLButtonDown(UINT nFlags,CPoint point){…}
ถาตองการให detect การกดเมาสปุมขวาดวยทําอยางไร?
26 /34
Window messaes : WM_ Message Handlers
afx_msg void OnLButtonDown(UINT, CPoint);afx_msg void OnLButtonDblClk( UINT, CPoint );afx_msg void OnMouseMove(UINT, CPoint);afx_msg void OnClose( );afx_msg void OnLButtonUp( UINT, CPoint );etc,...
ON_WM_LBUTTONDOWN()ON_WM_LBUTTONDBLCLK( )ON_WM_MOUSEMOVE()ON_WM_CLOSE()ON_WM_LBUTTONUP( )etc,...
Function prototype member functions of CWndMab Entry
•WM window message
•เปน member function ของคลาส CWnd•CWndCFrameWnd
UINT nFlagsMK_CONTROL Set if CTRL key is down.MK_LBUTTON Set if left mouse button is down.MK_MBUTTON Set if middle mouse button is down.MK_RBUTTON Set if right mouse button is down.MK_SHIFT Set if SHIFT key is down.
CPoint point :
Specifies the x and y coordinates of the cursor.
void CMainWin::OnLButtonDown (UINT nFlags,CPoint point){…}
27 /34
Creating a Message Mapping for a Class Derived from CFrameWnd
// file of prog1.h#include <afxwin.h>class CMainWin : public CFrameWnd{public:CMainWin(); virtual ~CMainWin();
afx_msg void OnLButtonDown(UINT nFlags,CPoint point);DECLARE_MESSAGE_MAP()};
class CApp : public CWinApp{public:
CApp();virtual ~CApp();virtual BOOL InitInstance();
};
// file of prog1.cpp#include "prog1.h" //declarationsCMainWin::~CMainWin(){}CMainWin::CMainWin(){
Create(NULL, "An MFC pplication Skeleton");}// CMainWin's message mapBEGIN_MESSAGE_MAP (CMainWin, CFrameWnd)
ON_WM_LBUTTONDOWN()END_MESSAGE_MAP();void CMainWin::OnLButtonDown(UINT nFlags,
CPoint point){
CDC *pDC = GetDC();pDC->TextOut(point.x, point.y,"Hello");
}// Our CApp class function definitionsCApp::CApp(){}CApp::~CApp(){}// Initialize the applicationBOOL CApp::InitInstance(){
m_pMainWnd = new CMainWin(); m_pMainWnd->ShowWindow(m_nCmdShow);m_pMainWnd->UpdateWindow();return TRUE;
}
// Instantiate the applicationCApp App;
Demo project ;Prog1
if (nFlags & MK_CONTROL) {pDC->TextOut(200, 200,"Bye ");
}
28 /34
WM_COMMAND
Handle notification messages from child windows.
Child Window Notification Message Handlers
Handles WM_COMMAND messages generated by user menu selections or menu access keys.
WM_COMMAND Message Handlers
Handle WM_ messages, such as WM_LBUTTONDOWN, WM_PAINT.
WM_ Message Handler(Application|Window Approach)
DescriptionMessage Categories
Menu• Design• Load• Process
29 /34
Resources A resource is a graphical user interface element that allows a user
to interact with an application
Resources are defined in special files called resource scripts
Resource scripts have an extension of .rc and are written in C preprocessor language
A resource ID is a constant declared with the #define preprocessor directive and is used for programmatically referring to a resource
#include “resource.h”
เนื่องจากสรางภายใต Win 32 Project ดังนั้นการสราง resource ใหกบั Application &window Approach เหมือนใน Win 32 Project
Project|Add Resource…
สมมุติเราจะสรางเมนูให attach กับ main window ทีส่รางขึ้นในสไลดที่ 21
30 /34
Project|Add resource:Design Menu
เกิดไฟลนามสกุล .rc และไฟล resource.h ใหอัตโนมัติ แลวเลือกเมนู เพื่อออกแบบเมนู
31 /34
Attach a menu to the Application:Load Menu
เปลี่ยนแปลงรูปแบบการเรียกใชฟงกชัน Create() ใน Constructor ของคลาสที่ derive จากคลาส CFrameWnd ตัวอยาง:
ใน .cpp ไฟล ตองทําการ #include “resource.h”
สราง message mapping แตละเมนู หรือ resource เพื่อ response เมื่อ user เลือกเมนูนั้นๆ
CMainWin::CMainWin(){
Create(NULL, “Using Menus”, WS_OVERLAPPEDWINDOW, rectDefault, NULL, (LPCTSTR)IDR_MENU1);
}
Demo project ;Prog1
•Create(NULL, "Using Menus", WS_OVERLAPPEDWINDOW, rectDefault, NULL, MAKEINTRESOURCE(IDR_MENU1));
33 /34
afx_msg void memberFxn( );
ParametersId : The control ID.memberFxn: The name of the message-handler function towhich the command is mapped.
ON_COMMAND( id, memberFxn)Menu, toolbar,Accelerator key
Control type Function prototypeMap Entry
Message from :Menu, Toolbar, Accelerator key
อยูใน .cpp ไฟล อยูระหวางmacro:BEGIN_MESSAGE_MAP & END_MESSAGE_MAP
Prototype ในไฟล .hสวน implement ในไฟล .cpp
สวนประกาศของฟงกชนั memberFxn() อยูในไฟล .cppวาจะให response อะไรตอ userDemo Project: Prog1
34 /34
Including a Menu & Responding to Menu SelectionsCMainWin::CMainWin()
{ Create(NULL, “Using Menus”, WS_OVERLAPPEDWINDOW, rectDefault, NULL, (LPCTSTR)IDR_MENU1);
}
BEGIN_MESSAGE_MAP(CMainWin, CFrameWnd)…
ON_COMMAND (ID_SHOW_MESSAGEBOX, OnShowMsg)END_MESSAGE_MAP()
void CMainWin::OnShowMsg(){ AfxMessageBox(200,200, “Bye”);}
.cpp
afx_msg void OnShowMsg(); in .h file