VC ++MFC Tutorial 6 & 7 (English)

zhaozj2021-02-08  299

Lesson 6: SDI and MDI Applications

We are getting to some advanced stuff now. In this lesson I am not going to go in depth at all. I will just give you a flavor of the structure of a SDI (single document interface) and a MDI (multiple document interface) application .................

The SDI application is typically used when you intend work with only one data set at a time. For instance, the program notepad.exe is a SDI application. Netscape is also an SDI application. At any one time, there is only one document to open at a time. Word for Windows and the VC developer studio are MDI applications. In these you can have several documents opened at once. This is particularly useful when you want to cut and paste between documents. Another use for MDI applications is to have one document, but several different views open that view the data differently. A graphing application comes to mind where in one window you have a spreadsheet-like data list, and in another window you have a plot of the data. For small applications, a SDI Application Will Usually Be All You NEED. After You Master IT, The Jump To MDI Is A Snap. Let's Go Over The Structure of A SDI APP.

Remember that in a dialog app, we had just two main classes CWinApp and CDialog Here again we have a CWinApp which serves the same purpose as it did in lesson 5. The CDialog class however is replaced by 3 other classes:.. CMainFrame, CDocument And CView.

CDocument is a class that has no display, and typically does not react much with the messaging system of windows. It is used as a class to manage your data. MFC will create the code automatically which handles the event of File-> Save, File-> SaveAs, File-> Close, and File-> Open. All you need to do is to fill in the blank functions in the CDocument class.Next is the CView. Most likely you will spend more time writing code to display and interact with the document's data then you will writing any other code. This is where the CView comes in. The CView is a class derived from CWnd, which is used for displaying your CDocument in some way. It is also one of the places where you Can Handle Events Like Mouse Click and what Not. The Heart of the CView Is Usually a call to get a pointer to your document Followed by Some Drawing routines to display the data in your document.

The CMainFrame acts as a way to bridge the gap between your document / view classes and the rest of the application. Do you see that frame which goes all around applications boarders? That is the Main Frame window of the application. The title bar, the menu, the scroll bars, the status bar, and the tool bars are all part of the main frame window in an SDI application. You typically put the code to handle these objects in the CMainFrame class. The CMainFrame class is the main window of the application. The CView class is typically a child window of the CMainFrame. (For the most part, the child / parent window relations just tell windows what windows are 'stuck' to what other windows. If you move a parent window, all of the Children Will Move Also. if you destroy a pent window, all of the children will be destroyed. etc.

You should have a pretty good idea now of how SDI applications are constructed. MDI applications are similar, but there can be several CDocument classes in existence at the same time and there is an added class called CChildFrame which acts as a connection between the CView and The cmainframe.lesson 7: Data Viewer

The moment you have been waiting for, we finally will make a useful application. If you have just skipped the last 6 lessons, then you will probably be able to follow along, but you may not really understand what you are doing. (But since You are the Type of Person That Skips Ahead, you are all probably used to this.)

I have decided to make this example a data viewing application that takes a text file of data, reads it in, and then displays it. If that is not enough, we are then going to use the timer to animate the data. Let's first assume that we are doing an experiment tracking the random motion of a drunken bug on a table. Every second we measure its distance from two adjacent sides of the table. These are what we will call the bug's x, y coordinates. Our data file looks LIKE THIS:

390.789362.245386.032366.429386.559369.289385.557370.483384.841372.370385.785371.975389.348371.005377.266379.550376.916382.096373.959384.111373.109384.387370.598382.973370.067383.667369.099377.171366.549379.162368.245383.977366.427385.877364.343388.575365.326389.769368.751389.556369.598386.514389.381384.817387.311381.979388.205382.978386.632387. 414385.150388.393384.099390.620382.926394.712385.771396.611375.693393.622376.697392.655394.063397.035391.727401.327379.119400.460381.912407.491384.119407.505383.090406.474384.888408.943386.664409.806386.207409.759388.031411.599387.911411.545

Go cut and paste this to a file named BugPosition.dat if you want to follow along. We first fire up Visual C Developers Studio and create a new project. In this case I called the project 'BugTracks'. For the app wizard options select SDI application. Keep the default settings for the rest of the choices, EXCEPT deselect printing preview and docking toolbar.First lets figure out how to get our data into the program. Go to the ClassView and double click on your document class. It should be called CBugTracksDoc if you named your project 'BugTracks'. When you double click on the class name, the .h file will be opened in the editor. Right before the declaration of the class, lets declare a structure to hold the data.

Struct sbugdata

{

Float x;

Float y;

}

Also I want to use one of microsoft's template classes Templates are C things that allow you to write a function for an arbitrary data type The one I like to use is the CArray class Include the afxtempl.h before your structure declaration...:

#include

And the in a public area of ​​Your Class Declare A Carray Template Class As Follows:

Carray m_bugdataaarray;

Yea, it looks funny, but that is the way you want to type it. This is sort of like declaring a data type of CArray but we have to tell the template class what type of data we want to store in the array. That is Done Between The Brackets <,>. The first Thing in the brackets is the type of data we want to put in the array. The second thing... Since to the carray class. since w have a list of data points, it is obvious that we want to have an array of SBugData. The second parameter is also SBugData meaning we will just pass the data to the array. (Alternatively we could have passed a 'reference' to the data , but that is another lesson) .Let's go to the .cpp file for the document and add the code now. Expand the CBugTracksDoc in the ClassView. You should see the member functions for the document. Double click on OnNewDocument (). You will Jump to the function in .cpp file. this function is called every Time a new document (file) is opened. a Ll we want to do here is to clear out the array so it will be ready for the new data:

m_bugdataaarray.removeall ();

Now to fill up the array, jump to the Serialize () function. This is a function called when a new file is opened or saved. Instead of the good old FILE pointers you use in C with fopen, we are going to use microsoft's CArchive .

Void Cbugtracksdoc :: Serialize (CARCHIVE & A)

{

// if not storing the data, read it

IF (! ar.isstoring ())

{

Sbugdata data;

Cstring strone;

// Read Data IN, One Line At a Time

While (Ar.Readstring (Stroneline))

{

// Convert the text to floats

SSCANF (Stroneline, "% G / N", & Data.x, & Data.y);

// address the data to the array

m_bugdataaarray.add (data);

}

}

}

For the very basic display, we just need to add some code to draw the data. Go to the function OnDraw () in the view class CBugTracksView. This is the function that is called every time the window needs refreshed. All drawing is done through ................

Void CbugtracksView :: OnDraw (CDC * PDC)

{

// Get a Pointer to the Document Class

Cbugtracksdoc * pdoc = getDocument ();

// Get the Total Number of Data Points

INT n = pdoc-> m_bugdataarray.getsize ();

// Draw All of the Connecting Lines

For (int i = 0; i

{

PDC-> MoveTo (pdoc-> m_bugdataaarray [i] .x, pdoc-> m_bugdataaarray [i] .y);

PDC-> LineTo (PDOC-> M_BugDataArray [i 1] .x, pdoc-> m_bugdataaarray [i 1] .y);

}

}

Well that is it! Compile and run the program. You will get a few warnings since our data is float, but screen coordinates are int, but that is harmless in this case. Once the program is running, go to File, Open and select IT SHOULD DISPLAY THE TRACK IN The Lower-Middle Part of The Window. We Could Call It Quits Here, But Let's Add A Couple Of More Features.

First, I hate the File, Open menu Lets make our application accept files that are dropped on the main window Go to the InitInstance () function in our CWinApp class CBugTracksApp Near the end of the function add this line...:

// enable DRAG / DROP OPEN

m_pmainwnd-> DragacceptFiles ();

Now let's take advantage of the status bar and put some useful text in it. The status bar is managed by the CStatusBar class, which is a protected member of CMainFrame. This means that we can not touch it from other classes. We can either move its declaration to a public part of the class or just a public member function to CMainFrame to change the status bar text. We will do the later. Right click on CMainFrame in the class view and select 'Add Member function'. A dialog will pop up to help add the member function Type in "void" (without the quotes) for the function type -. this is the return value of the function, and type in "ChangeStatusText (LPCTSTR text)" as the function declaration Make. sure that the 'access' is set to public. Press OK. This will automagically add the declaration to the .h file and a blank function to the .cpp file of CMainFrame. The LPCTSTR is one of many microsoft defines for data types. We Could Have Alternately Have Typed "ChangeStatustext (const char * text)". LPCTSTR stands for Long Pointer to a Constant T STRing. A T-string is just a string that will work on computers with different character sets (like Japanese). On computers in the US, a T-string is just the same as a char *.

Jump to the new function in the CMainFrame .cpp file and add the code to change the text on the status bar. To do this we'll just use the CWnd function SetWindowText. CStatusBar is derived from CWnd so we can always use any of the CWnd functions with it. A hint on how to find out about all of these strange new functions ... use the help and look at the 'class members' for the class, and then look at the class members for all of the base classes From Which It Was Derived. Your Function Should Now Look Like this: Void CMAINFRAME :: ChangeSTATUSTEXT (LPCTSTR TEX)

{

M_WndStatusBar.SetWindowText (Text);

}

We have to call this function from somewhere, and I'll do it from the document. Go to the 'File View' which is the view I use most. Under 'Source Files' double-click on your document file "BugTracksDoc.cpp ". Go to the top of this file and include the header for cmainframe Right After the rest of the new function we just name.

#include "mainfrm.cpp"

Next go to our Serialize () function and modify the reading code to spit some text out to the status bar. We first get a pointer to the main window, which is the CMainFrame window in SDI applications. Since the function AfxGetMainWnd () returns a .

Void Cbugtracksdoc :: Serialize (CARCHIVE & A)

{

IF (! ar.isstoring ())

{

Sbugdata data;

CSTRING LINE;

Cstring strstatus;

// Get a Pointer to the main window

// (Which is the mainframe for sdi applications)

CMAINFRAME * PMAIN = (CMAINFRAME *) AFXGETMAINWND ();

While (Ar.Readstring (line)) {

SSCANF (Line, "% G / N", & Data.x, & data.y);

// Tell the user ready

Strstatus.Format ("Reading Point% D", M_BugDataArray.getsize ());

PMain-> ChangeStatustext (strStatus);

m_bugdataaarray.add (data);

}

// Tell The User The Total Number of Points

Strstatus.Format ("Loaded% D Points.", M_BugDataArray.getsize ());

PMain-> ChangeStatustext (strStatus);

}

}

If you run the app, you'll notice all of the default menu items. We don't need name. Let's clean up the menus and add an item for animating the bug track Which We'll Code Later.

Go to the Resource View. Under the Menu resource, double click on IDR_MAINFRAME. This is the menu resource for the main window. In the edit window, click on File. Then delete the menu entries for New, Save, and Save As. Also delete the main menu headings for Edit and View. Next, go to the empty box at the end of the menu and Add a new heading called 'Track' by selecting the empty box and typing 'Track'. Drag the Track menu heading so that IT IS Between File and Help. Click on the TRACK MENU AND THEN CLICK ON The Empty Sub Menu Box. Type in '& Animate / Talt-a'. The & underlines The 'A' In Animate So That It Is The Menu Hot Key. THE / T I Just The Scan Code for a Tab and The Alt-a Will Be Our Hot Key To Start The Animation. For the ID, Type In `Id_Track_animate ', Thought this will be filled in automaticly if you esr forget.

In ORDER TO Make Alt-a Our Hot Key, Go To The Accelerator Resources and Double-Click ON IDR_MAINFRAME. IN The Edit Window, Double-Click on The Empty Box at the end of the list. From the drop list for the id, select the ID of your new menu item (ID_TRACK_ANIMATE). Press the `Next Key Typed 'button and then press Alt-A. Hit enter to close the dialog.Before we are done with resources, you should modify the icons to something more suitable For this app. I'm Sure You CAN Figure Out How To Do this. The Only Hints Here Are To Make User And Modify THE 32X32 Size Icon and The 16x16 Size Icon. If You Want Part of The icon to Be Transparent, Use That Greenish Color with The Two Border Around It on The Color Palette.

Now we can get back to coding. It's time to add fancier drawing and animating. We will animate the bug track by drawing more and more segments of the path in red as time increases. The rest of the path will be drawn in black.

In order to keep track of the last segment in the path that is to be drawn in red, we have to add a member variable to our document. Go to the Class View, right click on the document class, and select Add Member Variable. .

Jump to the onnewdocument () in the document class. Add this line to itialize the new variable to -1. We will use the value -1 to designate That The TRACK IS Not Being Animated.

m_nbugposition = -1;

Next let's add the message handler for our 'Animate' hot key and menu. Press Ctrl-W to bring up the class wizard. In the class name drop box select the view class (CBugTracksView) and in the Object ID list, select the ID of our new menu and hot key command (ID_TRACK_ANIMATE). You'll see the two possible choices in the Messages list. Double-click on COMMAND to add a function to handle our new command. You will be prompted for a function name. Just accept the default one OnTrackAnimate () and press OK. You will see the function appear in the Member function list near the bottom of the dialog. Double-click on the function to jump directly to the code. We set m_nBugPosition to zero and start a Timer That Will Redraw the bug tracks in interval of 0.2 seconds.void cbugtracksview :: Ontrackanimate ()

{

// Get the document

Cbugtracksdoc * pdoc = getDocument ();

// set the position to the first data point

PDOC-> m_nbugposition = 0;

// Create a Timer with id = 1 and delay of 200 milliseconds

Settimer (1,200, null);

Next we need to handle the timer message. Ctrl-W back to the class view. Make sure you are looking at the view class, select the class as the Object ID, then double-click WM_TIMER in the message list to handle the timer message . Again, double-click on the function name to jump to the code. In the OnTimer function we will first check the ID of the timer to make sure we are responding to the correct timer. In this case we set the timer ID to 1 ..................

Void Cbugtracksview :: Ontimer (uint nidevent)

{

IF (nidevent == 1)

{

// Tell Windows The View Needs RedRawn

// Note: The Last Parameter Is The Erase Flag.

// if it is true, things will flicker like crazy.invalidateect (null, false);

}

CView :: ONTIMER (Nidevent);

}

All that is left now is to fix up the OnDraw () function in the view class. We need to first draw the red tracks, then the blue ones, then increment the position m_nBugPosition. If m_nBugPosition is larger than the number of positions we will Set it to -1 and kill the time.

One of the new things in this code is the CPen class that is needed to change the color of the line. The way these graphical objects work is that you 'select' the object in to the CDC class. When you are done with it, You Select The old one what at there is one you just ready.

Void CbugtracksView :: OnDraw (CDC * PDC)

{

Cbugtracksdoc * pdoc = getDocument ();

Ask_VALID (PDOC);

// make Pens for Solid Lines of Thickness 2

CPEN Redpen (PS_SOLID, 2, RGB (255, 0, 0));

CPEN Bluepen (PS_SOLID, 2, RGB (0, 0, 255));

CPEN * POLDPEN = PDC-> SelectObject (& redpen);

INT i, n = pdoc-> m_bugdataaarray.getsize ();

// Draw Any TRACKS Which Need Animated

For (i = 0; i m_nbugposition-1; i )

{

PDC-> Moveto (pdoc-> m_bugdataaarray [i] .x,) pdoc-> m_bugdataArray [i] .y);

PDC-> LineTo (PDOC-> M_BugDataArray [i 1] .x, pdoc-> m_bugdataaarray [i 1] .y);

}

// Change Pens

PDC-> SELECTOBJECT (& Bluepen);

// Start Drawing Non Animated TRACks, But Need to Check for A

// Valid Starting Postion

INT Start = pdoc-> m_nbugposition;

IF (start <0) st = 0;

For (i = start; i

{

PDC-> Moveto (pdoc-> m_bugdataaarray [i] .x,) pdoc-> m_bugdataArray [i] .y);

PDC-> LineTo (PDOC-> M_BugDataArray [i 1] .x, pdoc-> m_bugdataaarray [i 1] .y);

}

// deselect Pens and delete thempdc-> selectObject (PoldPen);

Redpen.deleteObject ();

Bluepen.deleteObject ();

//move to next position or quit animating

IF (pdoc-> m_nbugposition! = - 1) PDOC-> M_NBugPosition ;

IF (pdoc-> m_nbugposition> = n)

{

PDOC-> m_nbugposition = -1;

// stop Timer 1

Killtimer (1);

// Redraw and Erase SO All Lines Are in Initial State (Blue)

INVALIDATERECT (NULL);

}

}

Ctrl-f5 the program to build and run it. Fix, bugs and you are done! Of course many ilversion THINK you have enough to go on. Good luck! (AND Don't Be Afraid of That F1 Key)

转载请注明原文地址:https://www.9cbs.com/read-2800.html

New Post(0)