[C ++ entry reprinted Note 1] Detailed description of the MFC Dialog Box program

Source: Internet
Author: User
Tags response code vc9

Preface
If you are already an MFC expert, this article is not suitable for you. If you have written an MFC program, this article may be of little significance to you, this article is suitable for you. This article describes how to use MFC to develop applications through examples. The Development Environment selected by the author is Visual C ++ 2008 (VC9) in Visual Studio 2008 (VS9) Professional Edition ), the main content in this article also applies to readers who use Visual C ++ 6.0. If you ask why I want to choose Microsoft (MS) This product, because I think the biggest advantage of the MS tool in detail design is very good, the user is very comfortable, the specific advantages will be mentioned later. Since this is the first time I have written a tutorial, I would like to apologize for your understanding.
The author's e-mail is: lightning_0721@163.com.
Introduction
The MFC Dialog Box program is a Windows form program based on MFC. The development of the MFC dialog box belongs to WIN32 development. The development of WIN32 is different from that of the 16-bit program, except for the source file, resource files are also required. during compilation, the source files and resource files will be compiled *. obj and *. res files, which are linked together. The resource file describes the application icons, versions, images, strings, and other information. The resource file usually contains the resource. h file. Some macros are defined in this header file, such as the control ID value.
Let's first look at the dialog box:

Http://baike.baidu.com/view/119316.htm

The above text selects the "dialog box" entry of Baidu encyclopedia.
1. Create a project
As mentioned above, readers who have just studied Windows program development may be confused, but it does not matter. Next I will learn the MFC dialog box through an instance.
When using VS9 to develop a Windows application, the first step is to create a VC project (in fact, a development unit of VS9 is a solution, which is called the work zone in VC ++ 6.0 and later versions ), the system automatically generates a solution with the same name as the new project.
Select "new" from the File menu to create a new project. In the new project dialog box that appears, select the MFC Application and enter a name for the project, helloworld (if you are in the same directory, if you already have a project with the same name as the one you want to create, the creation will fail.) Click OK.
Next, the MFC Application Wizard appears. VC will automatically generate an application framework based on the programmer's settings in the Wizard. The first thing that appears is an overview. We don't have to worry about it. Next step.
In this step, set the type of the MFC program to be created and select "based on the dialog box". At the bottom, there is a Unicode library. For this Unicode, we will mention in future discussions that we should leave it alone and keep it selected by default. Set the usage of MFC on the right. "use MFC in shared DLL" allows your compiled program to run the MFC program by calling the dynamic link library, if the target machine does not have vs9 installed or does not have the MFC Runtime Library file of vc9, the generated program cannot run on this machine. Therefore, the programmer should choose based on the actual situation. Because we are learning, we can keep the default status of this item. Next step.
In this step, the wizard requires us to set the user interface (UI) function. Ignore it and keep the default value. Next step.
In this step, you need to set up advanced functions. Here, we will only explain the meaning of the windows socket option: If a programmer wants to develop a network application, after selecting this option, the system automatically adds the socket initialization Statement (socket is a model used to develop network applications. For more information, visit the Internet ). Continue to the next step.
This is the last step in the Application Wizard. In this step, the wizard asks us to list the classes to be generated (the class name can be modified ). OK. Click "finish" to complete the Application Wizard settings.
After the Wizard is running, the development interface appears. The solution file Resource Tree (including a project and the files belonging to the project) is on the left, and a uidesign window is on the right, in vs9, the components that need to be designed by programmers are in the form of tabs by default.
The dialog box on this uidesigner is our program interface. At this time, you can press F5 or click the green arrow button on the toolbar to start debugging this MFC program, as we have already said, the framework of the MFC program has been built for us by the system. This framework is the source code that can be compiled and executed. We only need to modify and expand it based on it. After the program starts, the interface of this program appears in front of us. Click "cancel" or "OK" to end the dialog box program. You can also press the Esc or Enter key on the disk to achieve the same effect. If the program cannot respond due to a problem in the Code Compiled by the programmer, you can click "Stop debugging" on the VS9 debugging toolbar to terminate the program debugging.
If the programmer only wants to test the program UI, click "test dialog box" in the "dialog box Editor" toolbar ".
Note that there is a list box next to the "Green Arrow" button to start debugging (default Debug). If this program is under development, we recommend that you maintain Debug. If you want to Release it, select Release, the reader can compile the program in Debug and Release modes respectively. We can find that the program generated in Release is much smaller than the program generated in Debug, this is because the program generated by the system in Debug mode must contain all the information required for debugging.
Next we will design the UI of this program. First, select "toolbox" in the "View" menu. In this Toolbox window, lists many commonly used Windows controls (such as buttons, check boxes, edit boxes, and labels). When you click a control, the mouse changes to the cross type, you can draw the widget on the designer just like using a drawing tool. You can drag the widget directly to the dialog box in the uidesigner, or double-click the widget in the toolbar.
The static tag "Todo: place the dialog box control here" on the uidesigner ." You can delete it. Follow these steps to draw a button control in the dialog box, right-click the control, and select "properties" to display the Properties window. In this window, the left side is a property of the control, the right side is the current value of the property, and the lower end of the property window is the specific meaning of the property. For the button control, we now focus on the caption attribute, that is, the text displayed on the button. We set it to "Hello World", and press enter to confirm. The button on the uidesigner has changed to "Hello World. Take a look at the ID attribute of the button. This ID indicates the unique identifier of each control in the dialog box (note that the control with ID idc_static indicates that the control is static, you cannot dynamically change the properties of a widget, such as a tag control, when running the program. However, we can also change the tag ID to a non-idc_static value, so that the control is converted to a dynamic control. This control can be identified using idc_static, and idc_static has no unique restrictions ,), we generally need to change this attribute value to something more meaningful, such as idc_helloworld.
Next we will write the event response code for the button control, right-click the hello World button, and select "add event handler". A wizard dialog box is displayed, in the message type, select the message to be responded to by the button. In this program, we need to respond to the click event (in fact, in general, the button is used to click ), therefore, keep the default value "bn_clicked". In the class list, the response code is used as a member function of the class. By default, the class ending with "DLG" is selected, this class is a derived class that inherits from the cdialog class. Programmers can set their own "function handler name ". Click the "add and edit" button to go to the code editor to edit the Code. (For simple controls such as the button, we need to add the response code, generally, double-click the control in the uidesigner to directly go to the code editor to edit the function that responds to the default message ).
The system automatically adds the onbnclickedhelloworld () function to the chelloworlddlg class. The declaration part of this function is in helloworlddlg. in the H file, double-click the file in Solution Explorer on the right side of the vs9 development environment, or in helloworlddlg. right-click the CPP file and select "go to header file" in the pop-up menu ". Let's take a look at how this MFC framework is made up.
There is a line "# pragma once" in the header of this header file. This is a compilation command that enables the header file to be compiled only once, because the same header file may be included multiple times. The chelloworld class is defined in this header file. In this class, a m_hicon member variable of the hicon type is declared, which is a variable describing the application icon. If you do not know the hicon non-standard type, you can right-click the hicon of the code and select "go to Declaration" or "go to definition ", this is why vs9 automatically positions the cursor to the declaration or definition code of hicon. I think this is a very considerate function and provides great convenience for team development.
Here, by the way, we will briefly talk about the "Hungarian identifier name method" adopted by MFC, which is an agreement to increase the readability of the Code. If you declare or define a class, this class can be prefixed with "C" (class), such as the chelloworlddlg class. If you want to define an unsigned local variable, you can use "U" (unsigned) as the prefix, such as uint uport; ulong uflags; if it is an int or long type, it is prefixed with "N, DWORD variables are prefixed with "DW", character arrays are prefixed with "SZ", and cstring objects are prefixed with "str, pointer to "LP" or "p" (long
Pointer or pointer, there is no difference between the two pointers in Win32 environment) as the prefix, reference with "R" as the prefix, Boolean variables with "B" as the prefix, the variable of the handle type uses "H" (handle) as the prefix. If the variable is global, it starts with "g _" (global), for example, bool g_bflags. If it is a member variable of the class, it starts with "M _" (member, for example, hicon m_hicon ;.
After discussing the naming rules of MFC, let's continue to look at this header file and declare a standard constructor chelloworlddlg (cwnd * pparent = NULL) in this class ); optional parameter cwnd * pparent specifies the parent window of this dialog box.
Code Enum {IDD = idd_helloworld_dialog}; it means that MFC cleverly binds the resources of the idd_helloworld_diworlddialog box with the chelloworlddlg class.
All these except member functions are overloaded with member functions in the parent class cdialog.
The member functions virtual void dodataexchange (cdataexchange * PDX) are used to support DDX (dialog box data exchange, DDX for binding a variable to a control) and DDV (dialog box data validation, check whether the control uses DDV as needed.
The member function virtual bool oninitdialog (); is a function that is executed immediately after the dialog is created (create). Therefore, you can add the custom code required for dialog box initialization.
The member function afx_msg void onsyscommand (uint NID, lparam) is a function for processing wm_syscommand messages in the dialog box. A wm_syscommand message is a message about system control, such as an operation performed by the mouse on the title bar.
The member function afx_msg void onpaint (); is a function used to process wm_paint in the dialog box. When the form of the dialog box is repainted, The wm_paint message arrives at the program.
The member function afx_msg hcursor onquerydragicon (). The system calls this function to display the cursor when you drag the smallest window.
Next is a declare_message_map () Macro, which is used for message processing by MFC. For details, refer to msdn.
The next line afx_msg void onbnclickedhelloworld () is the processing function for clicking the automatically generated processing button.
The reader may have noticed afx_msg. In MFC, as long as it is a response function for processing messages, afx_msg must be added during declaration. By looking for its definition, I think this does not have any functional significance, but it is only a placeholder or a descriptive identifier.
After analyzing the HelloWorldDlg. h file, let's take a look at the HelloWorldDlg. cpp file. The include part of the file contains stdafx. h file, readers can go to "stdafx. h "right-click the header file and open it. The header file contains the necessary files of the MFC program. If the programmer wants to add a custom class, if the class still needs the support of MFC, this header file must be included. The HelloWorld. h file defines the ChelloWorldApp class (inherited from CWinApp), which is the application class of MFC. An MFC WIN32 application must be built on a CWinApp object. In the definition of the InitInstance () member function in the CHelloWorldApp class, there is a code (CHelloWorldDlg
Dlg; followed by the Code ).
Then there is a set of macro definitions # ifdef _ DEBUG # define new DEBUG_NEW # endif, _ DEBUG macros correspond to the Debug mode mentioned above.
Next, we define another dialog box class CAboutDlg, which is a class for displaying program copyright information.
Let's see BEGIN_MESSAGE_MAP ()...... END_MESSAGE_MAP () is a macro definition. The code in the middle is that MFC is used to specify which member function is used to respond to a message. For those that do not need to be specified, MFC is not explicitly specified. For example, ON_WM_PAINT () specifies that the member function for processing the WM_PAINT message is OnPaint (), but this user will not change it, therefore, it is not explicitly specified here. However, in ON_BN_CLICKED (), a specific member function is specified: The BN_CLICKED message of the control whose ID value is IDC_HELLOWORLD is processed by the OnBnClickedHelloworld () member function of the CHelloWorldDlg class.
Let's take a look at the definition of the OnInitDialog () function. First, the initialization function of the parent class is called. Then, before SetIcon, "about" is loaded into the system menu, in this way, when you click the icon in the upper left corner of the program form, right-click the title bar, or right-click the bar icon in the taskbar, the pop-up menu will contain the "about" menu item.
The following notes are added to SetIcon (): "set large icon" and "Set small icon ".
The OnSysCommand () function processes events on the title bar. The Code (nID & 0xFFF0) = IDM_ABOUTBOX indicates that, if you click "about" in the System menu of the title bar, the "about" dialog box is displayed.
The code in the OnPaint () function is used for re-painting.
The methods for retrieving/setting the text in the editing box, setting its available status, and setting its visible status are similar to those for the operation button.
We know that we use the GetDlgItem () function to obtain the text content. If you want to obtain the value, you can use the int nValue = _ ttoi (strInput); Method to convert it. Here we will introduce a DDX method to bind a member variable to a target control so that the value of the variable can be used to reflect the value of the control. Similarly, you can also set the value of this variable to control the value of the control. Next let's take a look at the specific steps: in the toolbox, drag an edit box to the dialog box and set the ID to IDC_INPUT. Right-click the control and select the "add variable" menu item. In the "add member variable wizard" dialog box that appears, set its access attribute (protected is recommended ); select Value (Control by default) in the category list box. Select a variable type in the variable type combo box. Select int here. Enter the variable name m_nValue; the minimum value, maximum value, maximum number of characters, and comments are optional based on the actual situation (skipped here). Click the finish button. After the "add variable" Wizard is complete, the system automatically adds a statement DDX_Text (pDX,
IDC_INPUT, m_nValue); this statement means to bind the control with ID IDC_INPUT to the m_nValue member variable. When the program executes UpdateData (), data is exchanged. The data exchange direction is determined by the UpdateData parameter.
Draw a button in the dialog box, set Caption to "judgment", and double-click to write the message response code:
Void chelloworlddlg: onbnclickedbutton1 ()
{
// Todo: add the control notification handler code here
Updatedata (true );
If (m_nvalue> = 0) MessageBox (_ T ("greater than or equal to zero "));
Else MessageBox (_ T ("Less Than Zero "));
}
Here, updatedata (true) is to update the value of the text box to m_nvalue. If it is updatedata (false), it is to return the data in the variable to the text box. During the initialization of the dialog box, MFC calls updatedata (false) by default to initialize the display content in the control. At the end of the dialog box, MFC calls updatedata (true );, used to update control data to member variables.
You can also add control variables for controls, that is, select control in the variable category list in the Add variable wizard, then, the system will add an MFC control class object as a member variable of the change dialog box, and bind this control object with the Response Control, in this way, the control object is equivalent to the corresponding control.
Check and radio controls. Take the controls with ID idc_check1 and idc_radio1 as examples:
GET/set the selected status:
Member function prototype:
Int GetCheck () const;
Void SetCheck (int nCheck );
Both functions are member functions of the CButton class. Therefore, after obtaining the CWnd pointer using GetDlgItem (), you must forcibly convert it to the CButton pointer type.
Example:
BOOL bState;
BState = (CButton *) GetDlgItem (IDC_CHECK1)-> GetCheck (); // obtain the check box status
(CButton *) GetDlgItem (IDC_RADIO1)-> SetCheck (1); // set the single-worker status to selected
Note: When the Tri-State attribute of the check box is True, the check box can be in three states. When SetCheck () is used, the status can be set by passing to 0, 1, or 2.
You can also use the DDX method to add a member variable of the int type to bind the check box and the status of a single worker to the control.
List and Combo. Only the member function prototype is described here:
List box common member functions:
Void ResetContent (); // clear the list
Int AddString (LPCTSTR lpszItem); // append a list item
Int DeleteString (UINT nIndex); // delete a specified item
Int SetSel (int nIndex, BOOL bSelect = TRUE); // set the selection status of the specified item
Int setcursel (INT nselect); // sets the currently selected item
Int getcursel () const; // gets the currently selected item
Int getselitems (INT nmaxitems, lpint rgindex) const; // obtain all selected items
Int GetSelCount () const; // gets the total number of selected items
Int GetTextLen (int nIndex) const; // gets the text length of a specified item.
Int GetText (int nIndex, LPTSTR lpszBuffer) const; // gets the specified item text
Void GetText (int nIndex, CString & rString) const;
Int FindString (int nStartAfter, LPCTSTR lpszItem) const; // you can call this operation to search for a specified item.
For a combo box, it can be understood as a composite control composed of an editing box and a list box. Therefore, the member functions in its MFC can also refer to the member functions in the editing box and the list box control class.

Related Article

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.