creat MFC applications with Microsoft Visual C++
- 格式:doc
- 大小:164.00 KB
- 文档页数:10
Creating MFC Applications with Microsoft Visual C++Programming for the graphical Windows platform is much more demanding than programming for text based platforms such as Windows NT console or DOS, since straightforward I/O is replaced with a graphical user interface. To make matters worse, Windows programs must use and obey the Windows messaging system, absent from text based applications. As a result, Windows programming involves a great deal of tedious and repetitive coding. For this reason it is common practice to use a graphical development tool to perform most of the tedious chores and set up the framework and graphical user interface of the application. Most modem compilers are equipped with such a tool.Visual C++’s graphical user interface dev elopment tool for Windows NT and Windows 95 applications has much in common with other development tools, such as Visual Basic. It relies heavily on a tool referred to as the AppWizard.The following sample application is intended to familiarize you with some of the features of the development environment of Visual C++. The documentation for Visual C++ adheres to the lofty standards of the software industry: It is inadequate and incomprehensible, unless you already know how to use the software. Therefore, rather than using their convoluted sample applications, we will design our own sample application, Our sample app1ication does not pretend to be a real application, rather the intent will be to demonstrate the characteristics and features of important contro1s in a very direct and straightforward manner.Visual C++ generates C++ code based on Microsoft Foundation Classes (MFC). These are classes that implement various controls and elements of a graphical Windows environment. Another popular set of Windows classes is Borland’s Object Windows Libraries or OWL. We will only have time for MFC in this course, but this does not mean we endorse Microsoft's clumsy implementation of C++ over Borland’s aw ful implementation!Application generation software such as Visual C++ can generate code for implementing the graphical user interface (CUI) of the application. The resulting code wil1 be able to start the application, invoke dialogboxes, display and implement controls, and even perform standard tasks such as opening and closing files. However the code to perform the actual task for which the program was written in the first place, must be written by you.The Sample ApplicationWe will design a Windows NT application. From the menu bar of the application a dialogbox can be and a button. When the button is pressed, the contents of the editbox will be displayed in a message box.Step 1) Creating the Skeleton of the ApplicationIn this step the name, location, target platform and overall features of the application must be specified. Since you are new to Windows programming, this first step is a bit intimidating. Follow the instructions very carefully! Start Visual C++. From it’s File menu select New….. In the New dialogbox select MFC AppWizard (exe). Specify D:\TEMP for the location in the Location editbox. Name the project winproj. This creates a new folder named winproj that will hold the files that belong to this application. Up to here the process is similar to creating a console based application, from here on everything is different!Press the OK button to move to the MFC AppWizard - Step 1 dialogbox. This is the first of six dialogboxes that AppWizard will preset you with. In each you will specify something about your application. Press the Single document radio button. Press Next to move to the MFC AppWizard - Step 2 of 6 dialogbox. Keep pressing the Next button until you arrive at the MFC AppWizard - Step 4 of 6 dialogbox. Make sure only the 3d controls checkbox is checked. Every time you unselect a checkbox, watch carefully to see what feature is removed from the application. Press Nex t to move to the MFC AppWizard-Step 5 of 6 dialogbox. Under the How would you like to use the MFC library? Select As a Statically Linked Library. Press Next and note the name of the classes that are created. Your application’s main class is called CWinprojApp. Press the Finish button. Press the OK button to finish generating a skeleton application and the C++ code for it .We will now start modifying this skeleton.Step 2) Modifying the Default Menu BarThe menu bar is located immediately below the title bar of an application. From the menu bar, all the features of the application can be viewed and selected. Relevant or related features are collected under the same menu and presented as items. Clicking on a menu causes all the items that are related to that menu to be displayed in what is down as a menu list .Usually when an item from a menu list is selected, a dialogbox appears that asks for more information and guides the user further along.Our menu bar will have two menus and each menu will display a list. The first menu will be named Dialogs. The second menu is the Help menu that is automatically created when the application is generated by AppWizard. The Dialogs menu will display two items namedDemobox…and YuHu. We will first create the Dialogs menuand it’s two items; later a dialogbox will be linked to theDemobox… item. The YuHu item will be left doing nothing. Youcan use it for practice on your own.In the Project Workplace (left) window of the MicrosoftDeveloper Studio select the Recourses tabto view the resources of your project.Resources are “things”like menus, dialogboxes and icons.Expand the winproj resources folder. Open the Menu folderand double click on the only menu bar currently in theapplication, IDR_MAINFRAME. The application’s main menu bar appears in design view in the client area of the Microsoft Developer Studio. The default menu bar contains more items than weneed eliminate two to reduce the size of the application .Select and delete the File, Edit and View menus from the menu bar by clicking on them and pressing the delete key .grab the Help menu with your mouse and pull it to the right of the empty box .Help should always be the rightmost menu.Right click in the empty box in the menu bar. The menu is shown on the right pops up. This menu will be encountered very often! Select Propert1es from the popup menu to invoke the Menu Item Properties dialogbox. In it, type &Dialogs for the name of the new menu in the Captions editbox and close the dialogbox. Notice that an empty box for the next new menu appears to the right of the Help menu.To add the Demobox…item to the Dialogs menu, right click in the empty box located below the Dialoqs menu and select Properties from the popup menu. Type &Demobox... in the Captions editbox of the Menu Item Properties dialogbox. Now comes an important step: Specifying the ID of the menu item. Type IDM_DIALOGS_DEMO in the ID combobox, This id will be used to identify the Demobox. . . menu item. Close the Menu Item Properties dialogbox.Practice some more byadding a second itemnamed Yuhu to the Dialogsmenu. It.s id should beIDM_DIALOGS_YUHU.Modif1cation of the menubar is complete. At thisstage it appears as shownbelow. Select File |Save form Microsoft Developer Studio's menu or click on the diskette icon to save your work.Select File | Close to close the menu design view. The next step is the design of a dialogbox that will be linked to the Demobox. . . item of the Dialogs menu.Step 3) Creating a DialogboxMost interactions with users take placethrough dialogboxes. We will now design adialogbox, and later attach it to theDemobox. . .menu item. Start designing thedialogbox by selecting Insert |Resource…from the Developer Stud1o'smain menu. A dialogbox pops up to askwhat type of resource you want. SelectDialoq and press New. The dialog designscreen with a dialogbox under construction appears. Notice that the new dialogbox already has an OK and a Cancel button in it. Move them to the approximate location shown on the right.The first step in constructing a dialogbox is to specify it’s id and title. To do this, ri ght click on the dialogbox that is under construction. From the by now familiar popup menu select Propertiesto bring up the dialogbox on the right. Type IDD_DEMO in the ID: combobox.This id will be used to identify the dialogbox. Remember it!Next set the title of the dia1ogbox to Demonstration, by typing Demonstration in the Capt1on: editbox. The title has no relation to the id and has functional purpose. Close the Dialog Properties dialogbox. Once more right click on the dialogbox and in the popup menu click on ClassWizard…. A dialogbox pops up and asks for confirmation to create a new class for the dialogbox. Ask for a new class. The New Class dialogbox appears. This is an important step, since here you specify the name of the class and source file in which the code for your dialogbox will be placed. Get used to a logical naming convention; the dialog's id was IDD_DEMO, the class name will be CDemoDlg, resulting in two files named DemoDlg.cpp and DemoDlg.h. The second file does not appear in the File name: editbox. Note that the filename isautomatically selectedbased on the classname. This is logicaland in this instanceMicrosoft hasimplemented goodcoding practice. As amatter of fact thenaming conventionfollowed by VisualC++ is remarkablyconsistent and if youfollow it, it becomeseasy to locate a pieceof code among themany components of aprojectTo finish specifying the preliminary class information, click on OK and notice that the MFC ClassWizard dialogbox is lurking behind. Dismiss it for now, by clicking on OK; we will use it later. Step 4) Adding and Declaring Control ObjectsGrab the bottom of your dialogbox with the mouse and stretch it a bit, to make room for some controls that will be placed in it. All active controls in a dialogbox are members of the dialogbox'sclass. They are themselves C++ objects, based on MFC classes, and thus their contents or status can be easily set and retrieved, using member functions of their class. We will not declare the controls as objects directly; instead we will use the ClassWizard to declare variables that will be connected to these controls. ClassWizard not only places the variables in the Class declaration for the dialogbox, but also handles the transfer of information between the controls and the variables. This is an advanced topic and referred to in Microsoft jargon as Dialog Data eXchange and Validation. So welcome to DDX/DDV!We will put a few controls in the newly created dialogbox and later use theClassWizard to incorporate the controls into the dialogbox’s class declaration.To place a control in a dialogbox use the mouse to drag it out of the controlstoolbox,shown on the right,and place it in the desired location in the dialogbox.The toolbox contains a11 the available controls: items such as editbox, listboxand static text.Now let us add a static text to the dialogbox. Press on in the toolboxand drag it to the top center area of the dialogbox. Right click on the new statictext select Properties from the popup menu. In the Text Propertiesdialogbox, set the caption to Enter something. This text appears in thedialogbox and directs the user of your application to enter some text into theeditbox that will be created in the following paragraph.To create an editbox,press on in the toolbox andplace it below the EnterSomething text, as shown onthe right. Right click on theeditbox and select Propertiesm the popup menu. In the Editpropert1ies dialogbox,change the id to IDEB_TEXT.This id will be used to identifythis editbox. The IDEB prefix isa reminder that this is the id ofan editbox object. Close the Edit properties dialogbox.ClassWizard will now be used to declare a member variable for the CDemoDlq class and associate it with the IDEB_TEXT editbox. As explained earlier, at run time this variable receives the contents of the editbox and vice versa, through the magic of DDX. Right click on the dialogbox and select CLassWizard. . . from the popup menu. The MFC CLassWizard dialogbox, shown on the next page, appears. ClassWizard is a powerful too1 that is capable of performing many tasks. We will use it selectively, because it is often easier to type in the required code directly, rather than going through the many layers of the ClassWizard. Furthermore, ClassWizard tends to hide the structure of the application this is a dangerous trap, even for experienced programmers!Select the Member Variables tab in the MFC ClassWizard. Making sure IDEB_TEXT ishighlighted in the list of Control IDs: press the Add Variable. . button. The Add Member Variable Dialogbox appears. In it you must specify the name and type of the variable.In the Member variable name:editbox enter m_IDEB_TEXT. Usethe following convention fornaming variables that are linked tocontrol objects: Prefix the id of thecontrol object with m_. This is whythe variable associated withIDEB_TEXT should be namedm_IDEB_TEXT. Make sure theCategory: is set to Value and theVariable typ e: to CString, thenpress the OK button to close thedialogbox.In the editbox in the bottom part of the MFC C1assWizard dialogbox, enter 80 for the maximum number of characters allowed, to limit user input to 80 characters. Press OK to close the MFC ClassWizard and complete the declaration of the variable.Now we are going to add a push button that when pressed, causes the text entered into theeditbox to be displayed in a MessageBox. Drag the from the toolbox and place it direct1y below the IDEB_TEXT editbox. Right click on it with the mouse and select Properties from the popup menu. In the Push Button Properties dialogbox, change the id to IDPB_SHOWTEXT. This id will be used to identify this push button. The IDPB prefix is a reminder that this is the id of a push button object. Next, set the title of the push button to Push Me, by typing Push Me in the Caption: editbox.The title is not the same as the id and has no functional purpose. Close the Push Button Properties dialogboxStep 5) Assigning an Event Procedure to a ControlIn ourapplication,the pushbutton is theonly controlthat requiresan eventprocedure.An eventprocedure is afunction that iscalledwhenever acontrol sends asignal toWindows. Abutton sends aBN_CLICKEDevent toWindows, whenever it is pushed once. We will now assign a function to the click event of IDPB_SHOWTEXT.Right click on the button and select Events... from the popup menu. The New Windows Message and Even Handler for class CDemoDlg dialogbox shows up! Study it very carefully and notice that it is dealing with the BN_CLICKED event. Press the Add and Edit button. AppWizard is going to ask you to specify a name for the event handler function, by presenting you with a dialogbox named Add Member Function. Make sure the function name in the Member function name: editbox is OnShowtext. This name should be in the editbox by default, since AppWizard picks names very logically. Press OK. AppWizard starts the editor and shows exactly where to write your code! Notice that a function named CDemoDlg::OnShowtext() has been created! The code to retrieve the content of the IDEB_TEXT editbox and display it in a MessageBox must be written in this function. Add the following two lines of code to the CDemoDlg::OnShowtext( )function:UpdateData ( TRUE );MessageBox ( m_IDEB_TEXT, “Echo!”, MB_OK );The UpdateData() member function of class CDemoDlg transfers the content of the controls to the associated data members of the class. In our example there is only one data member that is associated with a control: m_lDEB_TEXT is associated with IDEB_TEXT.Select File |Save or the diskette icon to save your work. This completes the design of the dialogbox. All that is left to do is to link the dialogbox to the Dialogs | Demobox. . . menu item.Step 6) Assigning Functionality to a Menu ItemWe are going to attach the IDD_DEMO dialogbox to the Demobox. . . menu item. This requires some coding that can be accomplished either manually or by using the AppWizard. We will write the code manually, since this is not only easy, but also gives a great deal of insight into the structure of the application. Let's review the steps before diving into the details.6.1. Place the id of Demobox… in the message queue of the application, along with the name of afunction that will be called every time Demobox… is selected. These types of functions arereferred to as message handler functions. Windows calls the message handler function, every time the Demobox…menu item is selected.6.2. Declare an object of type CDemoDlg in the declaration of the application's class. This createsthe IDD_DEMO dialogbox, but does not display it.6.3. Define and dec1are the message handler function mentioned in step 6.1. in the message handlerfunction, the DoModal ( ) function must be called for the object created in the previous step, to display the IDD_DEMO dialogbox.Step 6.lIn the Project Workplace (left) window of the Microsoft Developer Studio select the Files tab. Edit the source file winproj.cpp and locate the following code segment:BEGIN_MESSAGE_MAP(CWinprojApp, CWinApp)//{{AFX_MSG_MAP(CWinpojApp)ON_COMMAND(ID_APP_ABOUT, OnAppAbout〉// NOTE — the C1assWinzard will add and remove mapping macros here.// DO NOT EXIT what You see in these blocks of generated code!//}}AFX_ MSG_ MAP// Standard file based document commandsON_C○MMAND(ID_FILE_NEW, CWinApp::OnFileNew)ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)END_ MESSAGE_ MAP()This is the message queue of class CWinprojApp. Insert the following line of code immediately before END_MESSAGE_MAP ();ON_COMMAND(IDM_DIALOGS_DEMO, CWinprojApp::OnDialogsDemo)What you just did was to tell Windows to call the message handler function OnDialogsDemo() (which you will create shortly as a member function of the class CWinprojApp) when it receives the IDM_DIALOGS_DEMO message. This message is generated whenever the Demobox... menu item is selected. The message handler function must be a member function of the application's class; that is why OnDialoqsDemo() must be a member of CWinprojApp.Step 6.2In this step the dialogbox will be declared as an object. Declaring a control object such as a dialogbox, creates. The control without displaying it. This is an important point. A control object, no matter how complicated, is created by simply declaring it!Edit the source fi1e winproj.h and add the following declaration to the public section of the declaration of class CWinprojApp:CDemoDlg demoDlg;Since CDemoDlg is used in winproj.h, it's declaration must be #included in winproj.h. Add the followiÿÿ statement to the beginning of winproj.h iÿÿediately af ter all other #included directives: #i nclude “demoDlg.h”Step 6.3Now that the message queue has been updated and the dialogbox object declared, the message handler function that displays the diaiogbox in response to the IDM_DIALOGS_DEMO event generated by selecting the Dialogs | Demobox. . . menu item can be defined and declared.Again edit the source file winproj.cpp and write the definition for the message handler function OnDialogsDemo(), by adding the following code to the very end of the file:void CWinprojApp::OnDialogsDemo( void ){demoDlg.DoModal();return;}Note that in the above function, the line demoDlg.DoModal(); displays the dialogbox on the screen! It should be obvious that DoModal( ) is a member function of the CDemoDld class. Remember this class was created by ClassWizard in step 4.All that is left to do is to add the declaration of the message handler function OnDialogsDemo( ) to the declaration of class CWinprojApp. This is done by opening winproj.h and adding the following dec1aration immediately following the declaration for the constructor for CWinprojApp: void OnDialogsDemo( void ) ;Step 7) DrawingIn C1assView of Workspace window, find a pure virtual function ”OnDraw”,and add your MFCGDI object class and codes as below∶/////////////////////////////////////////////////////////////////////////////////////////////////CWinprojView drawingV oid CWinprojView∷○nDraw(CDC*pDC)//OnDraw 函数{CWinprojDoc*pDoc=GetDocumcnt():ASSERT_V ALID(pDOC):// TODO∶add draw code for native data here// add your班级号and你的姓名as bellow:pDC->TextOut(300,50,"信03班0号"); // 调用TextOut 函数输出字符pDC->TextOut(400,50,"石若明");//add a blue line under your name:CPen pen1(PS_SOLID,3,RGB(0,0,255));CPen *pOldPen; //使用CgdiObject的派生类Cpen建立画笔对象CPen*pOldPen;pOldPen=pDC->SelectObject(&pen1);pDC->MoveTo(280,75); // 用画笔画线pDC->LineTo(470,75);pDC->SelectObject(pOldPen) ;pen1.DeleteObject();}Step 8) Compiling and LinkingCongratulations, you are done! Select the Build|Build winproj.exe menu item to compile and link. Then run your application. After you recover from the shock of finding out how much code is needed to perform such a trivial task, review the steps one more time. If you want to save the project, select File | Save Workspace from Microsoft Developer Studio’s menu. The result is a figure as below.。