1 / 36

C++ Part III (not in the textbook)

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.

yael
Download Presentation

C++ Part III (not in the textbook)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Event-driven Programming (EDP)

  3. 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

  4. 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. Programming Paradigms

  5. Friendliness of Programming Paradigms 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.

  6. #include <iostream> using namespace std; int value; // global int main() { // Initialization char 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 user switch(s){ //event mapper case '+': //event registrationadd(); break; //event handler case '-': //event registration sub(); break;//event handler case 'q': //event registration exit(1); //event handler } } return(1); } Text-Based EDP

  7. // event handlers void 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 handler int in; cout << "Please select an integer: \n"; cin >> in; value -= in; cout << "The current value is: " << value << "\n"; } Text-Based EDP

  8. The six major components of an EDP program • Event generators: keyboard and mouse • Events: system and user defined • Event loop: continuously waits for events • Event handlers: methods to process the events (mostly user defined, some system defined) • Event mapper: dispatches events to their corresponding event handlers • Event registration: inform the event mapper which event an event hander is for. Event-driven Programming EDP: Introduction

  9. App User : UI Object : Event Mapper : Event Handler registers event handler actions fires events EDP: Event Flow Sequence Diagram dispatches events processes events

  10. 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

  11. 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.

  12. GUI-EDP

  13. 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.

  14. 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 Handler • GUI-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.

  15. 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. Implementing GUI-EDP Applications Using Visual Studio

  16. 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 MFC: Microsoft Foundation Classes

  17. 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 GUI-EDP with MS Visual Studio 2005

  18. Start with a dialog application. Dialog GUI-EDP with MS Visual Studio 2005

  19. All the basic files of a do-nothing dialog app are created. Build->Build Solution Debug->Start Without Debugging Or double click: My Documents\Visual Studio 2005\Projects\oop-dialog\debug\oop-dialog.exe Dialog GUI-EDP with MS Visual Studio 2005

  20. 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) MFC-based Dialog App : Understanding the Code

  21. 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.h

  22. // Message Map BEGIN_MESSAGE_MAP(CoopdialogApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // The one and only CoopdialogApp object CoopdialogApp theApp; // CoopdialogApp initialization BOOL CoopdialogApp::InitInstance() { INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); Understanding the Code: oop-dialog.cpp

  23. 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-dialog.cpp

  24. class CoopdialogDlg : public CDialog { // Construction public:CoopdialogDlg(CWnd* pParent = NULL); // Dialog Data enum { IDD = IDD_OOPDIALOG_DIALOG }; // DDX/DDV support protected:virtual void DoDataExchange(CDataExchange* pDX); // Implementation protected: HICON m_hIcon; Understanding the Code: oop-dialogDlg.h

  25. // Generated message map functions • virtual 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.h

  26. CoopdialogDlg::CoopdialogDlg(CWnd* pParent /*=NULL*/) : CDialog(CoopdialogDlg::IDD, pParent) {m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);} // Exchange data between the dialog internal structure and the app void 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

  27. 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

  28. 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

  29. void CoopdialogDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int 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

  30. else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user dragsthe minimized window. HCURSOR CoopdialogDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } Understanding the Code: oop-dialogDlg.cpp

  31. class CAboutDlg : public CDialog { // Dialog Data enum { IDD = IDD_ABOUTBOX }; // DDX/DDV support protected:virtual void DoDataExchange(CDataExchange* pDX); // Implementation protected:DECLARE_MESSAGE_MAP() }; void CAboutDlg::DoDataExchange(CDataExchange* pDX) {CDialog::DoDataExchange(pDX);} BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() Understanding the Code: oop-dialogDlg.cpp

  32. Tools->Cutomize->Toolbars check Dialog Editor Resource View -> oop-dialog -> oop-dialog.rc -> Dialog DD_OOPDIALOG_DIALOG Toolbox->Edit Control Toolbox->Edit Control Draw an Edit Box Toolbox->Button Draw a button Right-click Properties Caption: Button1 => Click here. Double click on the button, an event-handler will be added into existing code. Adding GUI Items and Event Handlers

  33. // CoopdialogDlg dialog class CoopdialogDlg : public CDialog { … afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); // Handlers for system messages are listed above DECLARE_MESSAGE_MAP() // Handlers for application messages are listed below public: afx_msg void OnBnClickedButton1(); }; Code Added to oop-dialogDlg.h

  34. BEGIN_MESSAGE_MAP(CoopdialogDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_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_MAP void CoopdialogDlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here } Code Added to oop-dialogDlg.cpp

  35. 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. Add your own code to handle the event.

  36. 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 Multiple Documents Application with MS Visual Studio 2005

More Related