C++ Part III (not in the textbook)

36
C++ Part III (not in the textbook) Yingcai Xiao 10/01/2008

description

C++ Part III (not in the textbook). Yingcai Xiao 10/01/2008. Event-driven Programming (EDP). 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. - PowerPoint PPT Presentation

Transcript of C++ Part III (not in the textbook)

Page 1: C++ Part III (not in the textbook)

C++Part III

(not in the textbook)

Yingcai Xiao

10/01/2008

Page 2: C++ Part III (not in the textbook)

Event-driven Programming (EDP)

Page 3: C++ Part III (not in the textbook)

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.

Page 4: C++ Part III (not in the textbook)

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.

Page 5: C++ Part III (not in the textbook)

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.

Page 6: C++ Part III (not in the textbook)

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);

}

Page 7: C++ Part III (not in the textbook)

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";

}

Page 8: C++ Part III (not in the textbook)

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.

Page 9: C++ Part III (not in the textbook)

EDP: Event Flow Sequence Diagram

App

User

: Event

Handler

: Event

Mapper

: UI

Object

actions

fires events

dispatches events

registers eventhandler

processes events

Page 10: C++ Part III (not in the textbook)

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

Page 11: C++ Part III (not in the textbook)

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.

Page 12: C++ Part III (not in the textbook)

GUI-EDP

Page 13: C++ Part III (not in the textbook)

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

Page 14: C++ Part III (not in the textbook)

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.

Page 15: C++ Part III (not in the textbook)

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.

Page 16: C++ Part III (not in the textbook)

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

Page 17: C++ Part III (not in the textbook)

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

Page 18: C++ Part III (not in the textbook)

Dialog GUI-EDP with MS Visual Studio 2005

Start with a dialog application.

Page 19: C++ Part III (not in the textbook)

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

Page 20: C++ Part III (not in the textbook)

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)

Page 21: C++ Part III (not in the textbook)

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

Page 22: C++ Part III (not in the textbook)

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);

Page 23: C++ Part III (not in the textbook)

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;

}

Page 24: C++ Part III (not in the textbook)

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;

Page 25: C++ Part III (not in the textbook)

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.

Page 26: C++ Part III (not in the textbook)

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()

Page 27: C++ Part III (not in the textbook)

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; }

Page 28: C++ Part III (not in the textbook)

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);}

}

Page 29: C++ Part III (not in the textbook)

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);

}

Page 30: C++ Part III (not in the textbook)

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);}

Page 31: C++ Part III (not in the textbook)

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()

Page 32: C++ Part III (not in the textbook)

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.

Page 33: C++ Part III (not in the textbook)

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();

};

Page 34: C++ Part III (not in the textbook)

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}

Page 35: C++ Part III (not in the textbook)

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.

Page 36: C++ Part III (not in the textbook)

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