C++ Part III (not in the textbook)
description
Transcript of C++ Part III (not in the textbook)
C++Part III
(not in the textbook)
Yingcai Xiao
10/01/2008
Event-driven Programming (EDP)
Programming Paradigms Sequential:• Program statements are executed one at a time.• The order of execution is predetermined by the programmer.• The user has no or little control of the order.• Not user friendly.
Event-driven:• Program idles after initialization, waits for events.• When an event is generated by the user, it will be sent to the program to be processed.• The event is first send to the event-mapper, which dispatches the event to its handler.• The event-handler process the event.• The program goes to idle mode again.• The order of events is not predetermined by the programmer.• The user can select what the program should do next. • User friendly.
Programming Paradigms Text-based:• Users issue commands as texts.• Users have to remember the texts of the commands and their format.• Not user friendly.
GUI-based:• Users issue commands by point-and-click on GUI (Graphical User Interface) objects.• Users do not have to remember the texts of the commands (but have to remember
where the GUI items are). WYSIWYG (What you see is what you get).• User friendly.
Friendliness of Programming Paradigms
Sequential EDP
Text least modest
GUI no use most
EDP: The application continuously waits until interrupted by some input events to respond. The application has an event-handler for each event it wants to handle. The event-handler is invoked when the corresponding event occurs.
GUI-EDP: Application waits (idles) until the user generates an event trough an input device (keyboard, mouse, …). The OS dispatches the event to the application who owns the window. The corresponding event handler(s) of the application is invoked to process the event.
Text-Based EDP #include <iostream>using namespace std;int value; // globalint main() {
// Initializationchar s = '+';value = 0;while(1) { // event loop
cout << "Please select an operation (+,-,q): \n";cin >> s; //wait for an event to be generated by the userswitch(s){ //event mapper
case '+': //event registration add(); break; //event handler
case '-': //event registration sub(); break; //event handler
case 'q': //event registration exit(1); //event handler
}}return(1);
}
Text-Based EDP
// event handlersvoid add () { // "+" event handler
int in;cout << "Please select an integer: \n";cin >> in;value += in;cout << "The current value is: " << value << "\n";
}
void sub () { // "-" event handlerint in;cout << "Please select an integer: \n";cin >> in;value -= in;cout << "The current value is: " << value << "\n";
}
Event-driven Programming
EDP: Introduction
The six major components of an EDP program1. Event generators: keyboard and mouse
2. Events: system and user defined
3. Event loop: continuously waits for events
4. Event handlers: methods to process the events (mostly user defined, some system defined)
5. Event mapper: dispatches events to their corresponding event handlers
6. Event registration: inform the event mapper which event an event hander is for.
EDP: Event Flow Sequence Diagram
App
User
: Event
Handler
: Event
Mapper
: UI
Object
actions
fires events
dispatches events
registers eventhandler
processes events
Event-driven Programming
The major task of EDP is to write the event handlers.
event loop and event mapper are usually implemented by the system applications only implement handlers as desired handlers need to follow the standard “interfaces” handlers need to be registered
EDP: Benefits Promotes code reuse.
Event loop and event mapper can be shared by all applications.
Event handlers have standardized interfaces and can be shared by different applications. Some are built by the system.
OOP makes it easier to implement EDP:
Events are defined as classes, easier to pass around and easier to modify.
Java and C# have EDP components (loop, mapper, system events, event generators) built in
C# defines event as a built-in type and provides delegate for type-safe registration of event handlers.
GUI-EDP
Key Components of GUI-EDP:(1) GUI items (buttons, menus, …). (2) Events / Messages (Mouse Enter, Key Down,
…)(3) Event Loop (an infinite loop constantly waits
for events) (4) Event Handlers (methods for processing the
events: OnMouseEnter(), …)(5) Event Mapper (dispatches events to
corresponding event handlers)(6) Event Registration: inform event mapper which
event an event hander is for.
GUI-EDP
Design of GUI-EDP Apps Designing GUI-based Applications: Look & Feel
Look => Appearance (Layout Design), related code are called resources.Feel => Response (Event Handling), related code are called source code.User => Button Click => Event => Event HandlerGUI-based application => Event-driven programming
Keys for a good GUI:• Elegant: simple but powerful (google.com)• Guide the user but don’t force the user to think the way you
think.• Give hints if the user hesitates.• Use hierarchy interfaces if there are too many GUI items.• Allow the user to make mistakes.
Implementing GUI-EDP Applications Using Visual Studio
C++ has no language-level support for GUI or EDP. MS Visual Studio: GUI-based IDE (Integrated Development Environment). IDE - Integrated Development Environment includes:
editor, compiler, linker, loader, debugger, profiler, context-sensitive help, form designer. MS Visual Studio supports the development of text, text-EDP and GUI-EDP applications. GDI (Graphical Device Interface): API to the graphics hardware.
MFC: Microsoft Foundation Classes
Introduced in 1992. Was called "Application Framework Extensions" and abbreviated "AFX". Provides the basic framework for building windows applications. Contains wrapping classes for Windows API and GDI. Contains many useful classes (e.g. container classes) MFC 8.0 was released with Visual Studio 2005. An alternative is Windows Template Library (WTL). WTL not MFC is included in the free Visual C++ Express. All replaced by FCL (Framework Class Library) in Visual Studio .NET
GUI-EDP with MS Visual Studio 2005
Start->Program Files-> MS Visual Studio 2005-> MS Visual Studio 2005
File->New->Project->Visual C++>MFC->MFC Application
Name: oop-dialog
Application Types:
Dialog based (e.g. calculator)
Single document (e.g. Notepad)
Multiple documents (e.g. MS Word)
Pick a type and follow the instructions or just pick “Finish”.
MFC-defined class CWinApp is the parent of all applications. It contains:
• main
• event loop
• event mapper/dispatcher
Dialog GUI-EDP with MS Visual Studio 2005
Start with a dialog application.
Dialog GUI-EDP with MS Visual Studio 2005
All the basic files of a do-nothing dialog app are created.Build->Build SolutionDebug->Start Without DebuggingOr double click:My Documents\Visual Studio 2005\Projects\oop-dialog\debug\oop-dialog.exe
MFC-based Dialog App : Understanding the Code
• Source Files (Class Implementation Files)
• oop-dialog.cpp (the app)
• oop-dialogDlg.cpp (the dialog)
• sdtafx.cpp (the standard AFX file for precompiled headers)
• Resource Files (for GUI)
• oop-dialog.ico (the app icon)
• oop-dialog.rc(2) (the app resource files containing specifications of GUI items.)
• Header Files (Class Declaration Files)
• oop-dialog.h (the app class definition)
• oop-dialogDlg.h (the dialog class definition)
• sdtafx.h (the standard AFX precompiled header)
• Resource.h (define GUI item IDs)
Understanding the Code: oop-dialog.h
class CoopdialogApp : public CWinApp{public: CoopdialogApp();// Overrides
public: virtual BOOL InitInstance();// Implementation
DECLARE_MESSAGE_MAP() // message map declaration};
extern CoopdialogApp theApp; // the application object
Understanding the Code: oop-dialog.cpp
// Message Map BEGIN_MESSAGE_MAP(CoopdialogApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)END_MESSAGE_MAP()
// The one and only CoopdialogApp objectCoopdialogApp theApp;
// CoopdialogApp initializationBOOL CoopdialogApp::InitInstance(){
INITCOMMONCONTROLSEX InitCtrls;InitCtrls.dwSize = sizeof(InitCtrls);InitCtrls.dwICC = ICC_WIN95_CLASSES;InitCommonControlsEx(&InitCtrls);
Understanding the Code: oop-dialog.cpp
CWinApp::InitInstance();AfxEnableControlContainer();SetRegistryKey(_T("Local AppWizard-Generated
Applications"));
CoopdialogDlg dlg;m_pMainWnd = &dlg;INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK){ /* TODO: Place code here to handle OK */ }else if (nResponse == IDCANCEL){ /* TODO: Place code here to handle Cancel */ }return FALSE;
}
Understanding the Code: oop-dialogDlg.h
class CoopdialogDlg : public CDialog{// Constructionpublic: CoopdialogDlg(CWnd* pParent = NULL);// Dialog Dataenum { IDD = IDD_OOPDIALOG_DIALOG }; // DDX/DDV supportprotected: virtual void DoDataExchange(CDataExchange* pDX); // Implementationprotected:
HICON m_hIcon;
Understanding the Code: oop-dialogDlg.h
// Generated message map functionsvirtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();DECLARE_MESSAGE_MAP()
};
• MFC generated event handlers have predefined headers.• They must be named as OnMessage, e.g. OnPaint is the handler for the PAINT message.• Other app specific event handlers are declared in DECLARE_MESSAGE_MAP()• All application event handlers are implemented in oop-dialogDlg.h.
Understanding the Code: oop-dialogDlg.cpp
CoopdialogDlg::CoopdialogDlg(CWnd* pParent /*=NULL*/): CDialog(CoopdialogDlg::IDD, pParent)
{ m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); }
// Exchange data between the dialog internal structure and the appvoid CoopdialogDlg::DoDataExchange(CDataExchange* pDX){ CDialog::DoDataExchange(pDX); }
BEGIN_MESSAGE_MAP(CoopdialogDlg, CDialog)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()//}}AFX_MSG_MAP
END_MESSAGE_MAP()
Understanding the Code: oop-dialogDlg.cpp
BOOL CoopdialogDlg::OnInitDialog(){
CDialog::OnInitDialog();CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){
CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){
pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING,
IDM_ABOUTBOX, strAboutMenu);}
}return TRUE; }
Understanding the Code: oop-dialogDlg.cpp
void CoopdialogDlg::OnSysCommand(UINT nID, LPARAM lParam){
if ((nID & 0xFFF0) == IDM_ABOUTBOX){
CAboutDlg dlgAbout;dlgAbout.DoModal();
}else{
CDialog::OnSysCommand(nID, lParam);}
}
Understanding the Code: oop-dialogDlg.cpp
void CoopdialogDlg::OnPaint(){
if (IsIconic()){
CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;dc.DrawIcon(x, y, m_hIcon);
}
Understanding the Code: oop-dialogDlg.cpp
else{
CDialog::OnPaint();}
}
// The system calls this function to obtain the cursor to display while the user drags the minimized window.HCURSOR CoopdialogDlg::OnQueryDragIcon(){
return static_cast<HCURSOR>(m_hIcon);}
Understanding the Code: oop-dialogDlg.cpp
class CAboutDlg : public CDialog{// Dialog Dataenum { IDD = IDD_ABOUTBOX };// DDX/DDV supportprotected: virtual void DoDataExchange(CDataExchange* pDX); // Implementationprotected: DECLARE_MESSAGE_MAP()};
void CAboutDlg::DoDataExchange(CDataExchange* pDX){ CDialog::DoDataExchange(pDX); }
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()
Adding GUI Items and Event Handlers
Tools->Cutomize->Toolbarscheck Dialog Editor
Resource View -> oop-dialog -> oop-dialog.rc -> Dialog DD_OOPDIALOG_DIALOG
Toolbox->Edit ControlToolbox->Edit Control
Draw an Edit BoxToolbox->Button
Draw a buttonRight-click
PropertiesCaption: Button1 => Click here.
Double click on the button, an event-handler will be added into existing code.
Code Added to oop-dialogDlg.h
// CoopdialogDlg dialogclass CoopdialogDlg : public CDialog{
…afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();// Handlers for system messages are listed aboveDECLARE_MESSAGE_MAP()// Handlers for application messages are listed below
public: afx_msg void OnBnClickedButton1();
};
Code Added to oop-dialogDlg.cpp
BEGIN_MESSAGE_MAP(CoopdialogDlg, CDialog)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()//}}AFX_MSG_MAPON_BN_CLICKED(IDC_BUTTON1,
&CoopdialogDlg::OnBnClickedButton1)END_MESSAGE_MAP()// Handlers for system messages are before //}}AFX_MSG_MAP// Handlers for application messages are after //}}AFX_MSG_MAPvoid CoopdialogDlg::OnBnClickedButton1(){
// TODO: Add your control notification handler code here}
Add your own code to handle the event.
void CoopdialogDlg::OnBnClickedButton1(){
CString s;s = "Hi, there.";SetDlgItemText(IDC_EDIT1,s);GetDlgItem(IDC_EDIT1)->EnableWindow(false);
}
Congratulations, you just created a complete GUI-EDP application.
Multiple Documents Application with MS Visual Studio 2005
Start->Program Files-> MS Visual Studio 2005-> MS Visual Studio 2005
File->New->Project->Other Languages->MFC->MFC Application
Name: oop-md
Application Types: Multiple documents (e.g. MS Word)
Pick a type and follow the instructions or just pick “Finish”.
MFC-defined class CWinApp is the parent of all applications. It contains:
• main
• event loop
• event mapper/dispatcher
This is an example of Application Framework / Template Method