Midterm Exam 3 Evening Class 2 Midterm Exam
- Slides: 73
Midterm Exam (3) - Evening Class 2
Midterm Exam (3) - Evening Class 3
Chapter 18 Working with Dialogs and Controls 4
More Ways to Get Input from Users Dialogs and controls are basic tools for user communication. p In the previous chapter, you have seen how On. Context. Menu() invokes Show. Popup. Menu() to display pop-up menus when the user clicks the right mouse button. p 5
Controls in a Dialog Box File > Open > File 6
Common Controls (P. 1060) p p p Static Controls Button Controls Scrollbars List Boxes Edit Controls Combo boxes 7
Dialogs p p A dialog box is actually a window which pops up when you click a menu item. Each controls in a dialog is also a specialized window. n p They are derived from CWnd. To create and display a dialog box in an MFC program: 1. 2. Define the physical appearance in a resource file Use a dialog class (CDialog) object to manage the operation of the dialog and its controls. 8
Creating a Dialog Resource p Resource View n n Right-click the Dialog folder Insert Dialog The dialog has OK and Cancel button controls already in place. p Adding new controls is easy. p n n n You can drag the control from the toolbox. You can click the control and then click in the dialog. You can double-click the control. 9
Properties of a Dialog p Change the ID from IDD_DIALOG 1 to IDD_PENWIDTH_DLG n D stands for Dialog. p Change the Caption property value to Set Pen Width. p Ex 18 -1: Press Ctrl+T to display the dialog window. n n Only one radio button in the group can be selected at a time. You may click OK or Cancel buttons to close the dialog. 10
Radio Buttons in a Group Box p p Only one member of the group can be checked at any given time. However, enclosing radio buttons within two group boxes does not make them to join two separate groups. n n n The tab order of the dialog, and the Group property completely dictates which radio buttons belong to which groups. Each radio button belongs to the group of the previous main radio button in the tab order. The main radio button has the Group property set to True. You can set the tab order by going to the dialog editor and pressing Ctrl+D. You then click on each control from 11 1 to N in the order you want the tabbing to go.
Dialog Editor (Ctrl-D) main radio button 12
Adding a Dialog Class p Right-click the dialog in the Editor pane n Select Add Class name: CPen. Dialog Base class: CDialog n p Figure 18 -2 (P. 1063) 13
Displaying a Dialog (1) p Modal n n p All other windows are suspended until the dialog box is closed. Example: Class wizard Modeless n n You can move the focus back and forth between the dialog box and other windows Example: the Properties window 14
Displaying a Dialog (2) p p p Rename the Color menu as Pen. Insert Separator (Figure 18 -3 on P. 1065) Add a menu item “Width …” to display CPen. Dialog as a modal dialog. n An ellipsis (three period) indicates that this menu item will display a dialog. p p This is a standard Windows convention. Both the menu item and the toolbar button have their IDs as ID_PEN_WIDTH. 15
Code to Display the Dialog p p Right-click the Width menu item Add Event Handler to the CSketcher. Doc class. void CSketcher. Doc: : On. Pen. Width() { CPen. Dialog a. Dlg; // Create a local dialog object } p // Dispaly the dialog as modal a. Dlg. Do. Modal(); #include "Pen. Dialog. h" at the beginning of Sketcher. Doc. cpp Ex 18 -2: Build Sketcher and see the dialog appears when you click the Width menu item or pen-width toolbar button. 16
Class CPen. Dialog p Store the pen width in a data member, m_Pen. Width (of the CPen. Dialog class) class CPen. Dialog : public CDialog { public: CPen. Dialog(CWnd* p. Parent = NULL); virtual ~CPen. Dialog(); // standard constructor // Dialog Data enum { IDD = IDD_PENWIDTH_DLG }; public: // Record the pen width int m_Pen. Width; }; 17
Overrides the On. Init. Dialog() function overrides messages 18
On. Init. Dialog() BOOL CPen. Dialog: : On. Init. Dialog() { CDialog: : On. Init. Dialog(); } Inherited indirectly from CWnd through CDialog. switch (m_Pen. Width) { case 1: Check. Dlg. Button(IDC_PENWIDTH 1, 1); break; case 2: Check. Dlg. Button(IDC_PENWIDTH 2, 1); break; case 3: Check. Dlg. Button(IDC_PENWIDTH 3, 1); break; case 4: Check. Dlg. Button(IDC_PENWIDTH 4, 1); break; case 5: Check. Dlg. Button(IDC_PENWIDTH 5, 1); break; default: Check. Dlg. Button(IDC_PENWIDTH 0, 1); break; } return TRUE; // return TRUE unless you set the focus to a control 19
Add Event Handler to Radio Buttons 20
Pen. Dialog. cpp void CPen. Dialog: : On. Penwidth 0() { m_Pen. Width = 0; } void CPen. Dialog: : On. Penwidth 1() { m_Pen. Width = 1; } void CPen. Dialog: : On. Penwidth 2() { m_Pen. Width = 2; } 21
On. Pen. Width() handler in CSketcher. Doc void CSketcher. Doc: : On. Pen. Width() { CPen. Dialog a. Dlg; // Create a local dialog object // Set the pen wdith in the dialog to that stored in the document a. Dlg. m_Pen. Width = m_Pen. Width; // Dispaly the dialog as modal if (a. Dlg. Do. Modal() == IDOK) m_Pen. Width = a. Dlg. m_Pen. Width; } 22
Adding Pen Widths to the Document class CSketcher. Doc : public CDocument { // Operations public: unsigned int Get. Element. Type() { return m_Element; } COLORREF Get. Element. Color() { return m_Color; } int Get. Pen. Width() { return m_Pen. Width; } protected: // Current element type unsigned int m_Element; COLORREF m_Color; // Current drawing color int m_Pen. Width; // Current pen width }; 23
Constructor of CSketcher. Doc: : CSketcher. Doc() : m_Element(LINE) , m_Color(BLACK) , m_Pen. Width(0) // 1 pixel pen { // TODO: add one-time construction code here } 24
Modify Get. Bound. Rect() to deal with a pen width of zero CRect CElement: : Get. Bound. Rect() { CRect Bounding. Rect; Bounding. Rect = m_Enclosing. Rect; Bounding. Rect. Inflate. Rect(m_Pen. Width, m_Pen. Width); return Bounding. Rect; } P. 976 25
Modify Get. Bound. Rect() to deal with a pen width of zero CRect CElement: : Get. Bound. Rect() { CRect Bounding. Rect; Bounding. Rect = m_Enclosing. Rect; int Offset = (m_Pen. Width == 0) ? 1 : m_Pen. Width; Bounding. Rect. Inflate. Rect(Offset, Offset); return Bounding. Rect; } 26
Constructor declaration of CLine(CPoint Start, CPoint End, COLORREF a. Color, int pen. Width); And the implementation CLine: : CLine(const CPoint& start, const CPoint& end, COLORREF a. Color, int pen. Width) { m_Start. Point = start; m_End. Point = end; m_Color = a. Color; m_Pen. Width = pen. Width; // Set pen width 27
Create. Element() in CSketcher. View CElement* CSketcher. View: : Create. Element(void) { // Get a pointer to the document for this view CSketcher. Doc* p. Doc = Get. Document(); // Now select the element using the type stored in the document switch(p. Doc->Get. Element. Type()) { case LINE: return new CLine(m_First. Point, m_Second. Point, p. Doc->Get. Element. Color(), p. Doc->Get. Pen. Width()); } default: // Something's gone wrong Afx. Message. Box(_T("Bad Element code"), MB_OK); Afx. Abort(); return NULL; } P. 1072 28
Exercising the Dialog 29
Change the Button Caption
On. Bn. Clicked. Button 1() void Cch 18 puzzle 1 View: : On. Bn. Clicked. Button 1() { CClient. DC a. DC(this); a. DC. Set. ROP 2(R 2_NOTXORPEN); static bool shown = false; a. DC. Ellipse(50, 150, 150); CWnd* p. Btn = Get. Dlg. Item(IDC_BUTTON 1); if (shown) p. Btn->Set. Window. Text("&Show"); else p. Btn->Set. Window. Text("H&ide"); shown = !shown; } 32
Get Mouse Position
P. 834 34
Message from the Mouse p WM_LBUTTONDOWN n p WM_LBUTTONUP n p Left mouse button is pressed Left mouse button is released WM_MOUSEMOVE n The mouse is moved. 35
Mouse Message Handlers p p Create a handler by clicking on the ID of a mouse message. Then select the down arrow in its right column. n n For example, select <add> On. LButton. Up for the WM_LBUTTONUP message. The wizard generates the WM_LBUTTONUP message handler: void CSketcher. View: : On. LButton. Up(UINT n. Flags, CPoint point) { // TODO: Add your message handler code here and/or call default CView: : On. LButton. Up(n. Flags, point); } 36
Exercise: p Add a message handler for WM_LBUTTONDOWN to display the coordinate where you click the left mouse button. n You may compose a string containing the coordinate and some explaining text (e. g. “X: 120 Y: 150”, and then use the function Text. Out. A() or Text. Out. W() to display the string. 37
n. Flags p MK_CONTROL n p MK_LBUTTON n p Right mouse button being down MK_SHIFT n p Middle mouse button being down MK_RBUTTON n p Left mouse button being down MK_MBUTTON n p Ctrl key being pressed Shift key being pressed To test for the Ctrl key being pressed if (n. Flags & MK_CONTROL) // Do something bitwise AND operator (P. 80) 38
On. Mouse. Move() void CSketcher. View: : On. Mouse. Move(UINT n. Flags, CPoint point) { // TODO: Add your message handler code here and/or call default if (n. Flags & MK_LBUTTON) { Verify the left mouse button is down } } 39
Mouse. Down Inside the rectangle 1. Remember the mouse pointer 2. m_Drag. Mode = true END Mouse. Up m_Drag. Mode 1. Erase the previous position 2. Draw bitmap at the new position 3. m_Drag. Mode = false END
Mouse. Move 1. Erase the previous position 2. Draw bitmap at the new position 3. Previous position new position END 41
Using an Edit Box Control (P. 1096) p Mouse clicks are convenient for users to make choices, however, when the programs need more detailed information, you’ll need to get text input from the user. 42
Set the Contents of an Edit Box p Create an MFC application based on the CForm. View class. Create an edit box control for input. p Double-click the button control to create a message handler p void Cch 18 text 1 View: : On. Bn. Clicked. Button 1() { Get. Dlg. Item(IDC_EDIT 1)->Set. Window. Text. A("Hello"); } 43
Get the Contents of an Edit Box void Cch 18 text 1 View: : On. Bn. Clicked. Button 2() { CString str; Get. Dlg. Item(IDC_EDIT 1)->Get. Window. Text. A(str); int i = atoi(str); str. Format("The value is %d", i); Get. Dlg. Item(IDC_STATIC)->Set. Window. Text. A(str); } Similar to sprintf(str, "%d", i); 44
HW 24: Currency Converter Design an application to convert US dollars to NT dollars (assume 1 USD = 30 NT dollars), and vice versa. p Note that the input may not always be integers. p n Hint: Use atof(). 45
Initial Contents of an Edit. Box p Put the following code in CView: : On. Initial. Update() CWnd* p. Edit. Box = static_cast<CWnd*>(Get. Dlg. Item(IDC_EDIT 1)); p. Edit. Box->Set. Window. Text( _T("Please type a string here") ); 46
Properties of an Edit Box Control p Multiline n p Align text n p The text you enter can span more than one line. Left/Center/Right Want return n n Insert a RETURN character into the text string. If False, pressing enter will select the default control (generally the OK button). Auto HScroll p Auto VScroll p 47
HW 25: Multiline Edit Box p Design an application which will convert all the English alphabets (a-z) from lowercase to uppercase. n Hint: Use CString member function Make. Upper() and Make. Lower(). 48
HW 26: Moving More Bitmaps p p p Extend your HW 23 so that when the program starts, there are 8 squares. You can use the mouse to move each square to a new location. Hint: You need an array in CDocument to remember the location of each bitmap. 49
Using a List Box (P. 1093) Create a List Box Control on your form. p The default value of the Sort property is True. p n Set it to False if you want to keep the sequence as items are appended to the list. p e. g. "Jan", "Feb", "Mar“ 50
Initialize a List Box p Put the initialization in On. Initial. Update() instead of the constructor of CView. void CQuiz 13 View: : On. Initial. Update() { CForm. View: : On. Initial. Update(); Get. Parent. Frame()->Recalc. Layout(); Resize. Parent. To. Fit(); CList. Box* p. List. Box = static_cast<CList. Box*>(Get. Dlg. Item(IDC_LIST 1)); CString str; for (int i=0; i<3; i++) { str. Format(_T("Month %d"), i); p. List. Box->Add. String(str); } p. List. Box->Set. Cur. Sel(0); } 51
Get the Index of the Selected Item void Cch 18 list. View: : On. Bn. Clicked. Button 1() { CList. Box* p. List. Box = static_cast<CList. Box*>(Get. Dlg. Item(IDC_LIST 1)); int i = p. List. Box->Get. Cur. Sel(); CString str; str. Format("You selected Month %d", i); Get. Dlg. Item(IDC_STATIC_RESULT)->Set. Window. Text. A(str); } Get. Cur. Sel() returns the index of your selection, based on zero. 52
HW 27: List Box Controls Use three list boxes to represent Month, Day, and Year, respectively. p When the user click the button, show the date chosen by the year. p 53
CList. Box Member Functions p Get. Count n p Get. Text. Len n p Returns the number of strings in a list box. Returns the length in bytes of a list-box item. Delete. String n Deletes a string from a list box. 54
HW 28: Dynamically Change a List p Modify your HW 27, so that n When the user selects a month, your program will automatically adjust the list for days. January – 31 days p April – 30 days p June – 30 days p etc. p n When the user click the button, your program will calculate what day the selected day is, and show a sentence like “ 2013 -06 -04 is Tuesday”. 55
Enable a Button p p We want to design an application which requires the user to input his/her ID number for validation. When the application starts, it shows a message in the edit box to prompt the user typing an ID number. Initially, the button was disabled. When the user types a 10 -character string, the button will be enabled. When the button was clicked, following this rule to validate the ID number. n n If it is valid, change the static text control to show “Correct”. If it is invalid, change the static text control to show “Incorrect!” 56
CView: : On. Initial. Update() p Initialize an Edit Box control n n p CWnd* p. Edit. Box = static_cast<CWnd*>(Get. Dlg. Item(IDC_EDIT 1)); p. Edit. Box->Set. Window. Text( _T("Please type your ID here") ); Disable a Button n Get. Dlg. Item(IDC_BUTTON 1)->Enable. Window(FALSE); 57
Check the Input String Length p Create a handler for the message EN_CHANGE. CView: : On. En. Change. Edit 1() { int len = Get. Dlg. Item(IDC_EDIT 1)->Get. Window. Text. Length(); if (len == 10) Get. Dlg. Item(IDC_BUTTON 1)->Enable. Window(TRUE); else Get. Dlg. Item(IDC_BUTTON 1)->Enable. Window(FALSE); } 58
Change the Color of Edit Box /Static Text Create a handler for the message WM_CTLCOLOR. p Add the following code in CView: : On. Ctl. Color() p if( p. Wnd->Get. Dlg. Ctrl. ID() == IDC_STATIC && m_Wrong. ID) p. DC->Set. Text. Color( RGB(255, 0, 0) ); 59
HW 29: ID Number Validation p p Complete the message handler On. Bn. Clicked. Button 1(). If the user inputs lowercase letter like “a 123456789”, convert it to uppercase by the Make. Upper() member function of CString. If the first character is not an English alphabet, or the other nine characters are not digits, the string is certainly not a valid ID number. If the second character is not 1 or 2, it is also invalid. 60
Using Radio Buttons (P. 1062) p Sometime you want to enclose a few radio buttons in a group box, so that only one member of a group can be checked at any given time. 61
I have 3 groups of radio buttons, but 框起來只是美觀,實際運作上所有 radio button 還是屬於同一個 group. p 你得把每個 group 的第一個(由 tab order決定) radio button的 Group property設為 True. p n n Ctrl-D可以看 tab order. 再按一次則取消. Ctrl-T 可以測試這個 form 是否介面設計好了。 62
On. Bn. Clicked. Radio 1() p When a radio button is checked, do the following : void CView: : On. Bn. Clicked. Radio 1() { m_str[0] = 'H'; Get. Dlg. Item(IDC_EDIT 1)->Set. Window. Text( CString(m_str) ); } p Your CView class may declare a private data member with initial value _T("000"). 63
Check/Uncheck Radio Buttons in Your Program p You may have a RESET button to uncheck all radio buttons void CHW 31 View: : On. Bn. Clicked. Button 2() { // Reset all radio buttons Check. Dlg. Button(IDC_RADIO 1, 0); Check. Dlg. Button(IDC_RADIO 2, 0); Check. Dlg. Button(IDC_RADIO 3, 0); 1 to check the radio Check. Dlg. Button(IDC_RADIO 4, 0); button; 0 to uncheck. Check. Dlg. Button(IDC_RADIO 5, 0); Check. Dlg. Button(IDC_RADIO 6, 0); Check. Dlg. Button(IDC_RADIO 7, 0); Check. Dlg. Button(IDC_RADIO 8, 0); Check. Dlg. Button(IDC_RADIO 9, 0); Check. Dlg. Button(IDC_RADIO 10, 0); } 64
Append Data to a File void CView: : On. Bn. Clicked. Save() { ofstream Log("log. txt", ios: : app); Log << m_str << 'n'; In CView. h #include <fstream> Log. close(); using std: : ofstream; using std: : ios; strcpy(m_str, "000"); Get. Dlg. Item(IDC_EDIT 1)->Set. Window. Text(_T(" ")); On. Bn. Clicked. Reset (); // Reset all radio buttons } p You may find the file “log. txt” in the same directory as your cpp files. 65
Terminate an MFC Application p You may have an Exit button so that your MFC application can terminate itself. void Exit. MFCApp() { ASSERT(Afx. Get. Main. Wnd() != NULL); Afx. Get. Main. Wnd()->Send. Message( WM_CLOSE ); } void CView: : On. Bn. Clicked. Button. End() { Exit. MFCApp(); } 66
Displaying a BITMAP Image 67
A Quick Demonstration Create an SDI application. p In the Resource View, right-click to Add Resource, and create a new Bitmap image. p n n The default name should be IDB_BITMAP 1. Draw something in the bitmap. 68
Sample Code p In the On. Draw() function inf the View class, add the following code: n n n p p CBitmap; Bitmap. Load. Bitmap. W(IDB_BITMAP 1); CDC mem. DC; mem. DC. Create. Compatible. DC( p. DC ); mem. DC. Select. Object( &Bitmap ); p. DC->Bit. Blt( 0, 0, 48, &mem. DC, 0, 0, SRCCOPY ); If Intelli-sense warns you that it does not recognize IDB_BITMAP 1 (yet), just ignore the warning. Build and execute the program. 69
The meaning of each line of code p p A CBitmap object must be declared. The CBitmap object must be initialized by calling its Load. Bitmap() function. A CDC object must be declared. The CDC object must be initialized by calling its Create. Compatible. DC() member function. n This DC is referred to as a “memory device context”. p Select the CBitmap object into the CDC object, by calling the CDC’s Select. Object() function. p Copy the member. DC to an on-screen windows, by calling the screen CDC’s Bit. Blt() function. screen CDC memory DC Bitmap 70
Can I Load an External Bitmap File? CString sz. Filename ("Y: \Waste\micky. bmp"); HBITMAP h. Bmp = (HBITMAP): : Load. Image. W(NULL, sz. Filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION); CBitmap; // Bitmap. Load. Bitmap. W(IDB_BITMAP 2); Bitmap. Attach(h. Bmp); CDC mem. DC; mem. DC. Create. Compatible. DC( p. DC ); CBitmap *p. Oldbmp = mem. DC. Select. Object( &Bitmap ); BITMAP bi; // Get the BMP Height and Width Bitmap. Get. Bitmap(&bi); p. DC->Bit. Blt( 0, 0, bi. bm. Width, bi. bm. Height, &mem. DC, 0, 0, SRCCOPY ); 71 mem. DC. Select. Object( p. Oldbmp );
Add a Button to Trigger the Action Create an SDI (single document interface) application. p Select CForm. View as the base class. p In the Resource View, expand the Dialog resource and double-click the form. p Drag a button control to the form. p Double-click the button to add a handler. p n Insert the code for displaying a BITMAP file. 72
HW 21 Design an application with 3 buttons. Each button will display a different bitmap file when it is pushed. p Bonus: Design your button so that it will show/hide the corresponding bitmap as a toggle switch. p 73
- Nlp midterm exam
- Data mining exam
- Html midterm exam
- English midterm test
- Business law midterm
- Research methodology midterm exam
- English 9 midterm exam
- Introduction to computer science midterm exam
- Introduction to computer science midterm exam test
- Ap english language and composition midterm exam
- Algebra 2 midterm practice test
- Grva midterm exam
- Midterm exam format
- American literature midterm exam
- World history semester 2 final exam review
- English 11 midterm exam
- Database systems midterm exam
- Apes midterm practice test
- Whats a midterm exam
- Bisexts
- Exam midterm
- Ap chemistry midterm review
- Algebra 1 midterm exam
- Midterm exam announcement
- Web development midterm exam
- Operating system midterm exam
- Xiao comp
- Should old acquaintance be forgot
- Wednesday evening prayer
- Evening prayer
- Sunday night prayer
- Monday evening word
- Boat stealing william wordsworth analysis
- Wordsworth boat stealing
- I am poem macbeth
- Shadows are _______ in the evening than they are at midday.
- Stopping by woods on a snowy evening diction
- Shire oak academy uniform
- Direct speech into reported speech
- Assalamualaikum and a very good morning
- Good morning lady and gentleman
- What is internet awareness
- Ts eliot let us go then you and i
- Hi good morning too.(1)
- Good afternoon everyone
- Teacher good afternoon
- Good afternoon to everybody
- Good evening ladies and gentlemen we are now
- Evening hawk by robert penn warren
- One evening there was a murderer answer
- Rendezvous political cartoon meaning
- In the afternoon i stay home
- Hello teacher good afternoon
- Shop assistant good morning
- Good mythical morning writers
- Winchmore sixth form entry requirements
- Evening star eminescu
- 7 lies of success
- University b.t. & evening college
- The sixth form college colchester
- Evening star edgar allan poe meaning
- Xxx good evening
- Shenfield high school open evening
- Saturday evening prayer
- Act 2 romeo and juliet timeline
- Receptionist good morning
- A rainbow in the morning is the sailor's warning
- They .... football yesterday
- Paraphrase. it
- Good evening conversation
- Little heath sixth form
- Kesgrave 6th form
- Parkside school open evening
- Good evening have a seat