MFC's Simple Adder (ii)

Source: Internet
Author: User
Tags delete key

There are two major steps in creating a dialog, first, creating a dialog resource, which includes creating a new dialog box template, setting dialog properties, and adding various controls for the dialog box, and second, building a dialog class that includes new dialog classes, adding control variables and message handlers for controls, and so on. Chicken Peck Rice In this section, talk about how to create a dialog box template and Set dialog box properties.

Creating a dialog-based application framework

Before the chicken Peck Rice created the HelloWorld program is a single document application, generated a variety of windows, if you use it to talk about creating dialog boxes may be a bit complicated, for everyone to simply understand the dialog box a little influence, so here chicken peck Rice Then create a dialog-based application to implement the function of the addition operation. Creating steps is similar to a single document application, with the following simple steps:

1. Select the menu item File->new->project, and the New Project dialog box pops up.

2. Under Visual C + + installed templated in the left Panel select MFC, select MFC application in the middle window, and then type the project name in the name edit box below, this example is named "Addition", Set the save path for the project in the location edit box. Point "OK".

3. Click "Next" to "Application Type" dialog box, under Application Type Select dialog based, other use default settings, click "Finish".

As we can see in the Solution Explorer view, this project has fewer files than a single document application, there are three main classes in Class View: CAboutDlg, Cadditionapp, and Cadditiondlg. CAboutDlg is the "about" dialog class for the application, Cadditionapp is a class derived from CWinApp, Cadditiondlg is the main dialog class, and the main dialog box is the main interface that is displayed after the application runs.

Note: If you cannot find a view such as Solution Explorer or Class View in VS2010, you can find the corresponding view option in the menu item view. It is already explained in the introduction of VS2010.

In Resource view, you can see the resource tree for the project addition, expand Addition.rc, with four subkeys: Dialog (Dialog), icon (icon), string table (string tables), and version (versions). then expand the DIALOG entry with the following two dialog template IDs: Idd_aboutbox and Idd_addition_dialog, which are templates for the About dialog box, which is the template for the main dialog box. An ID is a unique identifier for a resource, essentially an unsigned integer, and the integer value represented by the general ID is defined by the system and we do not need to interfere.

dialog box Templates

Visible for the main dialog box, the Create New dialog box template in the first step of the Create dialog box has been automatically completed by the system. If you add a dialog box to create a new dialog template, you need to right-click on the "Dialog" node of the Resource View and select "Insert Dialog" in the right-click menu, a new dialog template will be generated and the ID will be automatically assigned.

Double-click an ID in the Resource View's resource tree to display the corresponding resource interface within the middle area. When you double-click Idd_addition_dialog, the Addition dialog box template is displayed in the middle area. Such as:

Setting dialog Box Properties

Right-clicking on the addition dialog template and selecting Properties in the right-click menu displays a list of properties for the dialog box in the right-hand panel. Such as:

Chicken Peck Rice Here is a brief description of several properties that are often used, and a description of the properties of the addition dialog box.

1.ID: The dialog ID, which uniquely identifies the dialog resource, can be modified. Here is Idd_addition_dialog, we do not modify it.

2.Caption: Dialog box title. The default here is addition, which we'll change to "addition Calculator".

3.Border: Border type. There are four types: None, Thin, resizing, and dialog Frame. We use the default dialog Frame.

4.Maximize: Whether to use the Maximize button. We use the default false.

5.Minimize: Whether to use the Minimize button. Likewise we use the default false.

6.Style: Dialog box type. There are three types: Overlapped (overlapping window), popup (pop-up window), and child (sub-window). Pop-up windows are more common. We use the default popup type.

7.System Menu: The System menu with the upper-left corner of the title bar, including the move, close, and other menu items. We use the default true.

8.Title Bar: Whether it has a title bar. We use the default true.

9.Font (size): font type and font size. If you modify it to a non-system font, the use system automatically changes to false. The font (Size) is automatically set to the system font if the use system turns false and it is modified to true. Here we use the default system font.

1. Add a static text box (static) for the dialog box to display the string-"Summand".

The resource template that was generated in the previous lecture is automatically added with a title of "Todo:place dialog controls here." The static text box, we can modify its title to continue to use, you can also delete it. To explain the process of adding a static text box from scratch, delete it and continue adding a new static text box.

When you delete a control, you can click to select it with the left mouse button, and a dashed box appears around the control when you select it, and then press the DELETE key to delete it. Open the dialog template created in the previous lecture in the resource view of the addition project Idd_addition_dialog, and the automatically added static text box can be removed using this method.

Before adding a new static text box, check to see if the Toolbox view is displayed, or click View->toolbox on the menu bar if it is not displayed. Toolbox views such as:

Some common controls are listed in Toolbox, one of which is static Text, which is the control we want to add. In toolbox, the static text on the left mouse button is not released, and dragged to the Idd_addition_dialog dialog template, a dashed box appears on the template, we find the right place to release the left mouse button down it.

When you select a control with the left mouse button, a dashed box appears around the border, and the position of several black dots on the dotted box becomes a two-headed arrow shape, so you can press the left mouse button and drag to change the size of the control. We can change the size of the newly added static text box control to better display the caption. Of course, the entire dialog box template can also change size in this way.

You should then modify the text of the static text box. Right click on the static text box, select "Properties" in the right-click menu, the Properties panel will be displayed, modify the Caption property on the panel is "Summand", the ID is modified to idc_summand_static. At this point the template is as follows:

2. Add an edit Control to the dialog box to enter Summand.

The process of adding an edit box is similar to a static text box, in Toolbox, by selecting the edit control to drag onto the dialog template and aligning it horizontally with the previous static text box (for aesthetics), and then resizing it to fit the input of the summand.

Right-click on the edit box and still select "Properties" in the right-click menu to display the property panel and modify its ID to idc_summand_edit. At this point the template is as follows:

3. Add a static text box titled "Addend" in the 1 method to display the string-"Addend". and change its ID to idc_addend_static.

4. Add an edit box with ID Idc_addend_edit in the 2 method to enter Addend.

5. Add a static text box titled "and" in the 1 method to display the text--"and". and modify its ID to idc_sum_static.

6. Add an edit box with ID Idc_sum_edit in the 2 method to display the final sums.

7. A similar Add button control to a dialog template that triggers an addition calculation after being clicked. modify its title to "calculate" with ID Idc_add_button.

To this, the dialog box template

8. Remove the OK button. Open the Properties panel of the Cancel button, change the caption to exit, and align it horizontally with the Calculate button.

9. Depending on the layout of the control, adjust the size of the entire dialog box template appropriately, making it appropriate for the layout of the control and pleasing to the interface.

This adds up the controls we need to use in this example in the dialog box template. The final effect is as follows:

At this point, our dialog resources are basically created.

Addition is a dialog-based program, so the program automatically creates a dialog template Idd_addition_dialog and automatically generates a dialog class Cadditiondlg, which is derived from the CDialogEx class. We have used VC + + 6.0 may remember that we define the dialog box class are derived from the CDialog class, but in VS2010, the General dialog box class is inherited from the CDialogEx class.

Create a dialog box class

How do you create a dialog class for a new dialog template that you add yourself?

1. First the chicken peck rice just as the sixth Lecture: Create a dialog template and modify the dialog box Properties said, in the resource view of the "Dialog" node right-click, and then select "Insert Dialog" in the right-click menu to create a new dialog box template, the ID will use the default Idd_ DIALOG1.

2. In the middle area, a new dialog template is displayed, then select the dialog template, right-click, and select Add Class from the context menu.

3. After selecting "Add Class", a dialog will pop up and a custom class name can be written in the edit box under "Class name" in the dialog box, for example CMyDialog.

4. The final point "finish" is complete.

Finally you can see the newly generated dialog class CMyDialog in Class View and have the corresponding MyDialog.h header file and MyDialog.cpp source file generated in the Solution Explorer. The CMyDialog class is also derived from the CDialogEx class.

Note that the general class names begin with C, and for example, Ctestdlg.

to add a variable to a control in a dialog box

Added several controls to the dialog box in the previous lecture, including three static text boxes, three edit boxes, and one button control. The Cancel button, which is automatically generated by the program, is retained as an exit button and the OK button is removed.

The static text box is just to illustrate the meaning of the data in the edit box immediately following it, is it addend, addend, and so they don't change, and we don't add variables for them. Button controls are used for manipulation, and no variables are added to them here. The data in the edit box may change frequently, and it is necessary to associate a variable for each of them.

First add a variable for the summand edit box Idc_summand_edit.

1. Right click on the edit box and select "Add Variable" in the right-click menu. The wizard dialog box for adding member variables pops up.

2. We want to add a value variable instead of a control variable for it, so select value in the combo box under Category in the dialog box.

3. The combo box under "Variable type" is now selected by default as "CString", CString is a string class and obviously cannot be additive. We can choose double, float, int, and so on. Here we select Double, which is the edit box to associate a variable of type double.

4. Write the custom variable name in "Variable name". The chicken pecked the rice for its name M_editsummand.

5. Click "Finish" to complete.

Note that the member variable name of a class is typically preceded by m_ to identify that it is a member variable.

Refer to this method, and then add the double type variable m_editaddend to the edit box for Addend, Idd_addend_edit, and the edit box for the double type variable m_editsum.

data Exchange and Validation for dialog classes

In the program run interface, the user tends to change the properties of the control, for example, to enter a string in the edit box, or to change the selection of the combo box, or to change the check box selection status. After the control's properties have changed, MFC modifies the value of the control's associated variable accordingly. This kind of synchronization change is implemented by MFC's member function DoDataExchange (), which is automatically generated by the dialog class, which is also called the data exchange and inspection mechanism of the dialog box.

After we have added variables for three edit boxes, we have three more ddx_text call statements in the function body of the DoDataExchange () function Cadditiondlg in AdditionDlg.cpp. Here is the function body code and the note added by the Chicken peck rice

void Cadditiondlg::D odataexchange (cdataexchange* pdx)   {       //handles MFC default data Exchange       CDialogEx::D odataexchange (PDX );       Handles data exchange between control Idc_summand_edit and variable M_editsummand       ddx_text (PDX, Idc_summand_edit, M_editsummand);       Handles data exchange between control Idc_addend_edit and variable m_editaddend       ddx_text (PDX, Idc_addend_edit, m_editaddend);       Handles data exchange between control Idc_sum_edit and variable m_editsum       ddx_text (PDX, Idc_sum_edit, m_editsum);   }  

  Then take the addition procedure as an example to briefly say the data exchange mechanism. If we enter Summand in the program runtime interface, the input value can be saved to the M_editsummand variable through the caddition's DoDataExchange () function, or vice versa if the value of the variable M_editsummand is modified in the program's run. The caddition DoDataExchange () function can also display the new variable values in the Summand edit box.

But in this data exchange mechanism, DoDataExchange () is not called automatically, but requires us to call the Cdialogex::updatedata () function in the program, by UpdateData () The function then goes to automatically call DoDataExchange ().

The prototype of the Cdialogex::updatedata () function is:

BOOL UpdateData (bool bsaveandvalidate = TRUE);

Parameters: bSaveAndValidate is used to indicate the direction of the data transfer, true to pass from the control to the variable, false to pass from the variable to the control. The default value is True, which is passed from the control to the variable.

Return value: The return value of the Cdialogex::updatedata () function indicates whether the operation was successful, returns true if successful, or false otherwise.

MFC defines a number of messages for dialog boxes and controls, and we trigger messages when they are manipulated, which are ultimately handled by the message handler function. For example, when we click on the button will generate bn_clicked message, modify the contents of the edit box will produce En_change messages. In general, in order for an operation to be effective, we only need to implement the message handler for a message.

I. Adding a message-handler function

Still using the previous addition calculator's program as an example, how to add a message handler function for the Calculate button control. The Add method lists 4 kinds:

1. Adding a message handler function using the Class Wizard

The use of VC + + 6.0 friends should be familiar with the Class wizard, add classes, message processing functions, etc. often used to it, can be said to be a very core function. But from the beginning of VS2002 to see the Class wizard, most of the functions are integrated into the properties of dialog boxes and controls, and easy to use. To VS2010, the long-lost Class wizard came back. But chicken peck rice has been used to the use of properties in the function, for from VC + + 6.0 direct to VS2010 friends may feel or use the Class Wizard to compare habits.

You should remember that the "Calculate" button has the ID of Idc_add_button, the commands tag in the Oject IDs list has this ID, because we want to implement the message processing function after the click button, so select Bn_clicked message in the Messages list , and then click Add Handler on the top right of the BN_CLICKED message handler function to Onclickedaddbutton. Of course you can also change the name, but the general use of the default can be.

2. Add Message handler function via "Add Event Handler ..."

Right-click on the Calculate button and select menu item "ADD event Handler ..." In the right-click menu to bring up the "Event Handler Wizard" dialog box, such as:

It is visible that the bn_clicked message is selected by default in the "Message type", and the function name and class are given automatically, just click "Add and Edit".

3. Add a message handler function in the Properties view of the button

As stated above, the message handlers are added from the Properties view primarily from the VS2002. We right-click on the "Calculate" button, select "Properties" in the right-click menu, and the button's property view will be displayed in the right panel.

We can point to the Control Events button in the Properties view (similar to the lightning bolt) as in, and the following lists all the messages for the Calculate button. We have to deal with the bn_clicked message, click on its right blank list item, a button with the arrow next to it, click this button will appear "<Add> onbnclickedaddbutton" option, and finally Select this option will automatically add Bn_ Clicked the processing function.

4. Double-click the button to add the message handler function

The most straightforward and straightforward approach is to double-click the Calculate button, and MFC will automatically add a handler function Onbnclickedaddbutton () for the bn_clicked message to it in the Cadditiondlg class.

two. Adding custom features to message handlers

After we have added the message handler function in either method, we can only get an empty function body of the Onbnclickedaddbutton () function, we need to add the custom function code in the function body to implement the function we want.

In the addition Calculator program, we want the "calculate" button to implement the function is to get the values of Summand and Addend, and then calculate their sum and display to the and the edit box. Then, the function Body of Onbnclickedaddbutton () should be modified to:

void Cadditiondlg::onbnclickedaddbutton ()   {       //Todo:add your control notification handler code here       // Save the data in each control to the appropriate variable       updatedata (TRUE);         will be addend and addend add and assign value to m_editsum       m_editsum = M_editsummand + m_editaddend;         Updates the corresponding control based on the values of each variable. And the edit box will display the value of M_editsum       updatedata (FALSE);   }  

  

Comments have been added to the code above, and you should be very easy to understand. The description of the UpdateData () function has been described in the previous lecture, and if you forget, you can go back to the previous section to learn more.

Next we run this application. In the Run results interface, enter Summand 5.1, addend 2.3, then click "Calculate":

As you can see, after clicking the "Calculate" button, the correct result is displayed in the edit box: 7.4.

Simple analysis of the running process: Enter Summand and Addend, click the "Calculate" button to generate a hit message, thereby calling the Onbnclickedaddbutton () function. After entering this function, first by the UpdateData (TRUE) function will be Addend value 5.1 and Addend value 2.3 respectively saved to the variable M_editsummand and m_editaddend, and then through the statement m_editsum = M_editsummand + M _editaddend, calculate the Summand and Addend and the 7.4, and assign 7.4 to m_editsum. Finally call UpdateData (FALSE) to update the display values of the three edit boxes based on the values of Summand, Addend, and, and the results are obtained.

In this respect, an addition calculator application with a simple addition function is basically done. If you want to implement additional functionality, you can modify the control resources and message handler functions to practice.

How the tab order of controls on the dialog box is adjusted .

The addition calculator has been able to add operations to floating-point numbers after adding a message handler function for the Calculate button. But there is a small problem left, that is, the dialog Box control tab order problem.

Run the addition Calculator program, display the dialog box without any action, press ENTER directly, you can see the dialog box exited. This is because the Exit button is a control that has a tab order of 1, which is the first control that accepts user input. But according to our input habits, should be addend edit box first accept the user input, then the Addend edit box, and then the "Calculate" button, and finally the "exit" button.

Let's take a visual look at the tab order of each control. Open Resource View, and then locate the dialog box in the resource Idd_addition_dialog, double-click the ID and the intermediate customer area appears with its template view. in the main menu, choose Format, tab order, or press the shortcut key to Ctrl+d, and the dialog box template displays the tab number of each control. such as:

has a number in the upper-left corner of each control, which is its tab response order. When the dialog box just opens, the input focus is on the Exit button with tab order 1, the TAB key is pressed without any action, and the input focus is transferred to the "Summand" Static text box with Tab order 2, but because the static text box does not accept any input, So the input focus continues to be automatically transferred to the tab order 3 Summand edit box, and then the TAB key, the input focus will be transferred to the tab order 4 of the "Addend" Static text box, also because it is a static text box, the input focus does not stop to continue to transfer to the Addend edit box, the same as the following controls.

We think that this order is unreasonable, how to change it? It's easy to start by clicking on the control that you think the tab order should be 1 , and as you click Done, the tab response order for each control is set as we thought.

For example, in this example we can click the Summand edit box, the Summand static text box, the Addend edit box, the Addend static text box, and the edit box, the and static text box, the calculation button, and the Exit button. After the setup is complete, such as:

Finally press the ESC key to confirm the setting and exit the dialog template's tab order setting state.

Now we run the program, we can see the dialog box opened after the initial input focus on the Addend edit box, and we press the TAB key, the input focus moves to the Addend edit box, continue to press the TAB key more than once, the input focus will press the "and edit box-" calculation "button--' Exit ' button--summand edit box--addend edit box--and edit box ... "in the order of the loop transfer. That's what we're going to achieve.

A. modal dialogs and non-modal dialog boxes

The Windows dialog is divided into two categories: modal dialogs and non-modal dialog boxes.

Modal dialog box is a dialog box, when it pops up, the other windows of the application will no longer accept user input, only the dialog box in response to user input, after the corresponding action to exit, other windows can continue to interact with the user.

The non-modal dialog box is that when it pops up, the other windows of the program can still respond to user input. The non-modal dialog box is typically used to display informational messages and so on.

You know the Windows system very well, I believe both of these dialog boxes should have encountered. The previous Add Calculator dialog is a modal dialog box.

two. How the modal dialog box pops up

After all, the addition Calculator program is mostly MFC automatically generated, the dialog box how to pop out of the people may not be very clear. Chicken Peck Rice below simply say where it is to play out, and then re-build a new dialog box and pop it, so that we will be more flexible to use the modal dialog box.

You open the Addition.cpp file, you can see the Cadditionapp class has a InitInstance () function, in the MFC application framework analysis mentioned this function, but that is the single document application class, the function body is not the same, However, it is the initialization of an instance of the App class.

The second part of the InitInstance () function has a piece of code that defines the dialog object and pops up the dialog box, and the Chicken Peck meter gives the code and notes it:

Cadditiondlg Dlg;        Defining objects for Dialog Class Cadditiondlg dlg   m_pMainWnd = &dlg;       The DLG is set as the main window   int_ptr nresponse = dlg. DoModal ();   The dialog box appears dlg and assigns the return value of the DoModal function (the ID of the click button on exit) to Nresponse   if (nresponse = = IDOK)               //To determine if the return value is an OK button (its ID is IDOK, Chicken Peck Rice has removed it)   {       //Todo:place code here to handle when the dialog is       /dismissed with  OK   }   Else if (Nresponse = = IDCANCEL)      //Determine if the return value is the Cancel button (whose ID is IDCANCEL, the chicken pecked the rice and changed its caption to "Exit")   {       //Todo:place Code here to handle when the dialog are       //  dismissed with Cancel   }  

  

Pop-up dialog a key function is the DoModal () function of the dialog class. CDialog: The prototype of the:D Omodal () function is:

Virtual INT_PTR DoModal ();

Return value: An integer value that specifies the value of the Nresult parameter passed to Cdialog::enddialog, which is used to close the dialog box. Returns 1 if the function cannot create a dialog box, or returns Idabort if there are other errors.

The call to the dialog pops up and the return value is the ID of the button that was clicked when the dialog was exited, for example, when we clicked the "Exit" button, then the DoModal return value was idcancel.

three. Add a new dialog box and pop it

Chicken Peck Rice Then add a dialog box to the addition Calculator program to ask the user if they are sure they want to calculate before calculating. You can take a complete look at the dialog box to add and pop-up process.

1. Based on the method described in "Creating a dialog template and Modifying dialog Box Properties", in Resource View, right-click on "Dialog" and select "Insert Dialog", create a new dialog template, modify its ID to Idd_tip_dialog, Caption change to prompt, and then refer to add Control for dialog box, add a static text box on the dialog template (static text), caption to "Are you sure you want to do the addition calculation?" , then modify the OK button's caption to OK, the Cancel button's caption to cancel, and finally adjust the position of each control and the size of the dialog box. The final dialog box template is as follows:

2. Based on the method of creating the dialog class in "Create dialog class and add control variable", right-click on the dialog template to select "Add Class ...", Pop up the Add Class dialog box, set "class name" to Ctipdlg, click "OK". In Solution Explorer, you can see the header file TipDlg.h and source file TipDlg.cpp that generated the Ctipdlg class.

3. In order to access the Ctipdlg class, we need to access the prompt dialog class in the Message handler function Onbnclickedaddbutton () of the Calculate button after the point "Calculate" button. Include the Ctipdlg header file in the AdditionDlg.cpp: #include "TipDlg.h".

4. Modify the function body of the Onbnclickedaddbutton (), before all the code, construct the object Tipdlg of the Ctipdlg class, and pass the statement tipdlg.domodal (); pop-up dialog, finally Judge DoModal () The return value of the function is IDOK or idcancel to determine whether to proceed with the calculation. The Onbnclickedaddbutton () function is modified as follows:

void Cadditiondlg::onbnclickedaddbutton ()   {       //Todo:add your control notification handler code here       Int_ PTR nres;             Used to save the return value of the DoModal function         Ctipdlg tipdlg;           Constructs a dialog box class Ctipdlg instance       nres = Tipdlg.domodal ();  Pop-Up dialog if       (IDCANCEL = = nres)     //Determine if the return value of the dialog box is IDCANCEL, or return if it is, otherwise continue to execute           return;         Save the data in each control to the appropriate variable       updatedata (TRUE);         will be addend and addend add and assign value to m_editsum       m_editsum = M_editsummand + m_editaddend;         Updates the corresponding control based on the values of each variable. And the edit box will display the value of M_editsum       updatedata (FALSE);   }  

  

5. Test. After compiling the program, enter Summand and Addend on the dialog, click "Calculate", the popup prompt dialog asks whether the calculation is done, if "OK" is selected, the prompt dialog box exits, and the Summand and Addend are displayed on the main dialog box, and if "Cancel" is selected, the prompt dialog box exits. However, the main dialog box is displayed and unchanged, that is, there is no addition calculation.

In this case, you should master the basic use of modal dialog box. I hope you continue to pay attention to the chicken Peck of the MFC tutorial, we progress together.

MFC's Simple Adder (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.