94
THE HISTORY OF WINDOWS..........................1 THE MICROSOFT FOUNDATION CLASSES................3 Document Class……………………………………………………………………8 View Class…………………………………………………………………………8 MESSAGE & MESSAGE MAP..........................11 OTHER MFC FEATURES.............................14 Collection Class……………………………………………………………..……14 Serialization………………………………..……………………………………..15 DIALOGUES...................................... 16 SDI…………………………………………………………….…………………16 MDI………………………………………………………………………………22 Dialog…………………………………………………………………………….25 SCROLLER & SPLITTING...........................30 Scrolling………………………………………………………………………….30 Splitting…………………………………………………………………………..35 GRAPHICS & TEXT & PRINTING....................36 CPen……………………………………………………………………………...37 CBrush………………………....………………………………………………...40 CFont…………………………..………………………………………………...43 CBitmap……………………..……………………………………………….......47 LITTLE OBJECTS & SYNCHRONIZATION...............48 THE DATABASE................................... 54 DAO Class………………………………………………………………………..55 ODBC Class……………………………………………………………………...55 MULTITASKING................................... 61

Visual c++ and mfc windows programming

Embed Size (px)

Citation preview

Page 1: Visual c++ and mfc windows programming

THE HISTORY OF WINDOWS............................................................1

THE MICROSOFT FOUNDATION CLASSES...................................3 Document Class……………………………………………………………………8 View Class…………………………………………………………………………8

MESSAGE & MESSAGE MAP...........................................................11

OTHER MFC FEATURES...................................................................14 Collection Class……………………………………………………………..……14 Serialization………………………………..……………………………………..15

DIALOGUES..........................................................................................16 SDI…………………………………………………………….…………………16 MDI………………………………………………………………………………22 Dialog…………………………………………………………………………….25

SCROLLER & SPLITTING.................................................................30 Scrolling………………………………………………………………………….30 Splitting…………………………………………………………………………..35

GRAPHICS & TEXT & PRINTING..................................................36 CPen……………………………………………………………………………...37 CBrush………………………....………………………………………………...40 CFont…………………………..………………………………………………...43 CBitmap……………………..……………………………………………….......47

LITTLE OBJECTS & SYNCHRONIZATION..................................48

THE DATABASE...................................................................................54 DAO Class………………………………………………………………………..55 ODBC Class……………………………………………………………………...55

MULTITASKING..................................................................................61

Page 2: Visual c++ and mfc windows programming

THE HISTORY OF WINDOWS

Windows 95, released in August of 1995. A 32-bit system providing full pre-emptive multitasking, advanced file systems, threading, networking and more. Includes MS-DOS 7.0, but takes over from DOS completely after starting. Also includes a completely revised user interface.

Windows 95/98

Windows 98, released in June of 1998. Integrated Web Browsing gives your desktop a browser-like interface. You will 'browse' everything, including stuff on your local computer. Active Desktop allows you to setup your desktop to be your personal web page, complete with links and any web content. Internet Explorer 5.0 New browser that supports HTML 4.0 and has an enhanced user interface. FAT32 with Conversion utility Enhanced & Efficient support for larger hard drives. Includes a utility to convert your FAT16 to a FAT32 partition. Multiple Display Support can expand your desktop onto up to 8 connected monitors. New Hardware support will support the latest technology such as DVD, Firewire, USB, and AGP. Win32 Driver model Uses same driver model as Windows NT 5.0 Disk Defragmentor Wizard  Enhanced hard drive defragmentor to speed up access to files and applications. 

1

Page 3: Visual c++ and mfc windows programming

WINDOWS XP Microsoft officially launches it on October 25th. 2001.

XP is a whole new kind of Windows for consumers. Under the hood, it contains the 32-bit kernel and driver set from Windows NT and Windows 2000. Naturally it has tons of new features that no previous version of Windows has, but it also doesn't ignore the past--old DOS and Windows programs will still run, and may even run better.

WINDOWS XP

<<Back to the top

2

Page 4: Visual c++ and mfc windows programming

THE MICROSOFT FOUNDATION CLASSES

As we can see in the following picture if run up Visual C++, like Figure 1.1 .

Figure 1.1 the environment of Visual C++

When developing Visual C++ programming, usually we need to use leader (Wizard). During this chapter, we will use Visual C++ AppWizard. After AppWizard produce code, we will modify this code as we need for making this programming to conform to our requests.

Here is a small example. Displaying “Welcome to Visual C++”. In fact, the program is just to display one short message, but it will involve much knowledge of Visual C++. For doing this programming, Visual C++ has already created both menu and tools for us, even these kind of object haven’t done anything yet. Ok! Anyway, let’s start to program (example1).

1. Open Visual C++. Click New in the File menu, it will display New message box, like Figure 1.2.

2. Choose MFC AppWizard (exe) in this New dialog frame.

3. Type a new program name “Welcome” in the Project name frame.

3

Page 5: Visual c++ and mfc windows programming

Figure1.2 Use MFC AppWizard to edit a new programming

4. Hit button “OK” to run up Visual C++ AppWizard, like Figure 1.3.

5. AppWizard will edit much code in the program.

6. As showing in Figure 1.3. It exists Step 1, the first step of the whole six steps in AppWizard.

Figure 1.3 MFC AppWizard edit Visual C++ programming for us

7. Hit Single Document item in the AppWizard, like figure 1.3. Hit button Next to the second step of AppWizard, show in the figure 1.4.

4

Page 6: Visual c++ and mfc windows programming

8. In the Figure 1.4, AppWizard asking what kind of database will support. Here we don’t need any database, so just choose None item.

9. Continuing to hit button Next until it get into the sixth step of AppWizard, show in the Figure 1.5.

Figure 1.4 the second step of MFC AppWizard

Figure 1.5 the sixth step of MFC AppWizard12. Here, AppWizard will explain, what kind of classes are create in this new

program: CWelcomeApp, CmainFrame, CwelcomeDoc and CwelcomeView.

5

Page 7: Visual c++ and mfc windows programming

13. After hit the button Finish of AppWizard, it will display New Project information box, show in the Figure 1.6.

14. Hit the button OK of the New Project information box, it created program.

Figure 1.6 the New Project information box of MFC AppWizard These are all the things we need to do before coding the program. As it mentioned above that there are 4 portions of Visual C++ program (Show in Figure 1.7).

Figure 1.7 the structure of 4 portions of Visuall C++ Right now, we can modify this program to make it that can display the message “Welcome to Visual C++”. For doing such kind of things, we need to add code to OnDraw( ) which is in CWelcomeView Class.

1. Hit the label ClassView in Workspace. 2. Find CWelcomeView Class, show in Figure 1.8.

6

Page 8: Visual c++ and mfc windows programming

3. Find function which named OnDraw( ),it will display editor of OnDraw( ) function after you double click. Show in Figure 1.8.

4. To display one message, we need to add extra code to OnDraw( ) function:

void CWelcomeView::OnDraw(CDC* pDC){

CWelcomeDoc* pDoc = GetDocument();ASSERT_VALID (pDoc);CString welcome_string = "Welcome to Visual C++";pDC->TextOut (0,0,welcome_string);// TODO: add draw code for native data here

}

Figure 1.8 edit function OnDraw()

5. Now, we have finished editing code. To run the program, we need to compile

the code first, find the button in the tool bar. You will see the result in the output after you click it. If there is no error or warning, we can start to execute

the program by click the button . Finally, you will get the result (Show in Figure 1.9).

7

Page 9: Visual c++ and mfc windows programming

Figure 1.9 the result for the program

DOCUMENT CLASSDOCUMENT CLASS Document class objects, created by document-template objects, manage the application’s data. You will derive a class for your documents from one of these classes. Document class objects interact with view objects. View objects represent the client area of a window, display a document’s data, and allow users to interact with it. Documents and views are created by a document-template object.

CDocument: The base class for application-specific documents. Derive your document class(es) from CDocument.

VIEW CLASS (ARCHITECTURE)VIEW CLASS (ARCHITECTURE)

CView and its derived classes are child windows that represent the client area of a frame window. Views show data and accept input for a document. A view class is associated with a document class and a frame window class using a document-template object.

CView : The base class for application-specific views of a document’s data. Views display data and accept user input to edit or select the data. Derive your view class(es) from CView.

We haven’t store any data in the preceding example, excluding the variable welcome_string. It’s easy to put the variable in the View Class. But, as a matter of fact it should put in the Document Class. Let’s try another way by declare the variable welcome_string in welcomeDoc.h :

8

Page 10: Visual c++ and mfc windows programming

The next step is to initialize the variable welcome_string in the constructer of Document Class:

Now, the data is stored in the function of Document Class. Right now, we need to load it by using View Class. For using the variable welcome_string which is in the Document Class, we can do it like pDOC->welcome_string; Therefore, we put the code into OnDraw( ) :

9

Storing program data; saving and loading program data from disk

CString is one function of Document Class which can declare string variable.

CWelcomeDoc.cpp is the virtual function which is processing the data.

To give the value to the variable welcome_string.

Page 11: Visual c++ and mfc windows programming

Window, Dialog, and Control ClassesWindow, Dialog, and Control Classes

Class CWnd and its derived classes encapsulate an HWND, a handle to a Windows window. CWnd can be used by itself or as a base for deriving new classes. The derived classes supplied by the class library represent various kinds of windows.

CWnd: The base class is for all windows. You can use one of the classes derived from CWnd or derive your own classes directly from it.

The CWnd class provides the base functionality of all window classes in the Microsoft Foundation Class Library.

<<Back to the top

10

Displaying program data; processing user input; managing view window

To display the variable welcome_string at the position (0,0) in the window .

Use function GetDocument( ) in the View Class to get one point which is point to the Document Class, AppWizard named this point pDoc.

This is the class for Dialog base doing the constructor, initialization, etc, of Dialog

Using CWnd Class point here is to make the standard constructor of the dialog base

Page 12: Visual c++ and mfc windows programming

MESSAGE & MESSAGE MAP

Message Handling

In MFC the message pump and WndProc are hidden by a set of macros. To add message routing put the following line in the class declaration, DECLARE_MESSAGE_MAP( ). For every message you want to handle you have to add an entry to message

map. The architecture of a basic Windows application will in 99% of cases perform

screen out put in the WM_PAINT message handler. With graphical input via MOUSE EVENTS we have to modify this and perform out put as required.

11

Page 13: Visual c++ and mfc windows programming

The diagram above is showing that how one message is sending to the message loop. Anyway, just following the direction line, then you can see the processing that one message start from event and after return to windows.

Right now, we just use the preceding exercise as an example. Let’s see more clearly about the Message & Message Map are working in each item. First, let’s see how to edit the menu in Visual C++(Show in Figure 2.1).

12

Page 14: Visual c++ and mfc windows programming

Figure 2.1 the menu editor of Visual C++

Mouse click by the right button, it will display a new message box (Show in right picture). Choose ClassWizard to get Message Maps & Message of Visual C++ MFC. Now you have to open the ClassWizard, Show in Figure 2.2.

<<Back to the top

13

Support to set the hot key of the window

Dialog box

Support to set the item of the menu

Support to set the item of the toolbar

Figure 2.2 The window of Visual C++ ClassWizard

Page 15: Visual c++ and mfc windows programming

OTHER MFC FEATURES

COLLECTION CLASSESCOLLECTION CLASSES The collection classes are including Array, List, and Map Classes. For handling aggregates of data, the class library provides a group of collection classes — arrays, lists, and “maps” — that can hold a variety of object and predefined types. The collections are dynamically sized. These classes can be used in any program, whether written for Windows or not. However, they are most useful for implementing the data structures that define your document classes in the application framework.

ARRAY CLASSES:ARRAY CLASSES: Arrays are one-dimensional data structures that are stored contiguously in memory. They support very fast random access since the memory address of any given element can be calculated by multiplying the index of the element by the size of an element and adding the result to the base address of the array. But arrays are very expensive if you have to insert elements into the array, since the entire array past the element inserted has to be moved to make room for the element to be inserted. Arrays can grow and shrink as necessary.

LIST CLASSES:LIST CLASSES: Lists are similar to arrays but are stored very differently. Each element in a list also includes a pointer to the previous and next elements, making it a doubly-linked list. It’s very fast to add or delete items because doing so only involves changing a few pointers. However, searching a list can be expensive since all searches need to start at one of the list’s ends.

MAP CLASSES:MAP CLASSES: Maps relate a key value to a data value. For instance, the key of a map could be a string and the data a pointer into a list. You would ask the map to give you the pointer associated with a particular string. Map lookups are fast because maps use hash tables for key lookups. Adding and deleting items is also fast. Maps are often used with other data structures as auxiliary indices. MFC uses a special kind of map called a “ message map” to map Windows messages to a pointer to the handler function for that message.

DRAWING & PRINTING CLASS DRAWING & PRINTING CLASS

In Windows, all graphical output is drawn on a virtual drawing area called a device context (or DC). MFC provides classes to encapsulate the various types of DCs, as well as encapsulations for Windows drawing tools such as bitmaps, brushes, palettes, and pens.

14

Page 16: Visual c++ and mfc windows programming

SERIALIZATIONSERIALIZATION “Serialization” is the process of writing or reading an object to or from a persistent storage medium, such as a disk file. MFC supplies built-in support for serialization in the class CObject. Thus, all classes derived from CObject can take advantage of CObject’s serialization protocol. The basic idea of serialization is that an object should be able to write its current state, usually indicated by the value of its member variables, to persistent storage. Later, the object can be re-created by reading, or deserializing, the object’s state from the storage. Serialization handles all the details of object pointers and circular references to objects that are used when you serialize an object. A key point is that the object itself is responsible for reading and writing its own state. Thus, for a class to be serializable, it must implement the basic serialization operations. As shown in the Serialization group of articles, it is easy to add this functionality to a class. MFC uses an object of the CArchive class as an intermediary between the object to be serialized and the storage medium. This object is always associated with a CFile object, from which it obtains the necessary information for serialization, including the file name and whether the requested operation is a read or write. The object that performs a serialization operation can use the CArchive object without regard to the nature of the storage medium. A CArchive object uses overloaded insertion (<<) and extraction (>>) operators to perform writing and reading operations.

SIMPLE DATA TYPE CLASSSIMPLE DATA TYPE CLASS The following classes encapsulate drawing coordinates, character strings, and time and date information, allowing convenient use of C++ syntax. These objects are used widely as parameters to the member functions of Windows classes in the class library. Because CPoint, CSize, and CRect correspond to the POINT, SIZE, and RECT structures, respectively, in the Win32 SDK, you can use objects of these C++ classes wherever you can use these C-language structures. The classes provide useful interfaces through their member functions. CString provides very flexible dynamic character strings. CTime, COleDateTime, CTimeSpan, and COleTimeSpan represent time and date values.

CString Holds character strings.

CPoint Holds coordinate (x, y) pairs.

CSize Holds distance, relative positions, or paired values.

CRect Holds coordinates of rectangular areas.

CTime Holds absolute time and date values.

<<Back to the top

15

Page 17: Visual c++ and mfc windows programming

DIALOGUES Now, we know the basic idea of Visual C++ MFC and how to make it running the program. Here we go on, to get more about this aspect by the following three examples, which are based on SDI, MDI, Dialog interface. SDISDI SDI (Single Document Interface) applications allow only one open document frame window at a time.

The basic model for doing SDI program is show in example1. Let’s do another program that the user clicks the left button of the mouse anywhere in the client area. This will cause a caret (or insertion point) to be inserted at that position and subsequent text to appear starting there. A caret is slightly tricky because its size should be the same as that of the current text font. Also, it should disappear when the window gets out of focus and reappear when the window gets back into focus.

1. We create a new project caret and set up an empty string in the document (To declare StringData in CCaretDoc.h, then to initialize it as an empty string, show like following). Add handler OnChar( )(show in Figure 4.1 ).

Figure 4.1 Add handler OnChar() to the member function

16

Use “ ” here means an empty string for the initial value of this string variable.

Page 18: Visual c++ and mfc windows programming

Since we need to create the caret only once on the first call of OnDraw ( ), we set up a Boolean variable caretCreated in the View and initialize it to false. We also set up a variable caretPosition of type Cpoint, which is to hold the coordinates of the caret, and initialize the coordinates to zero (Show in Figure 4.2).

Figure 4.2 To declare variable by type Boolean & CPoint

2. In OnDraw(), we set up a conditional staement if (!caretCreated) {…}. In it, we set up a structure textmetric of type TEXTMETRIC and fill it with a call to the Device Context method GetTextMetrics( ). The members tmAveCharWidth and tmHeight give us the necessary information and we call the function CreateSolidCaret( ) giving it 1/8 of the average character width as well as the text eight as the dimensions of the caret(Show in Figure 4.3).

Figure 4.3 Add code to OnDraw() for display one caret in the client area

3. Following the if statement, for ever call of OnChar( ), we need to do following things: a) Display the string. b) Find out the width of the string. c) Display the caret at that position. We do a) and b) as before using the DC methods TextOut( ) and GetTextExtent( ). For c) we first need to call HideCaret( ),then we call SetCarePosition( ) with the right coordinates, and finally ShowCaret( ) (Show in Figure 4.4).

17

To declare the variable in CCaretView.h

Use boolean type to declare caretCreated & CPoint to declare cretPosition

To create caret in the client area.

Page 19: Visual c++ and mfc windows programming

Figure 4.4 Add code to OnChar() for receive characters

4. The only thing we haven’t done is to adding the mouse control. To start coding the function, we first to add message WM_LBUTTONDOWN in the View (Show in Figure 4.5).

Figure 4.5 Add handler OnLButtonDown() to the member function

Create 2 int variables mouseX and mouse Y for coordinates of mouse click.

18

To get document from the Document Class

Save what the user type (number of characters) into the variable StringData.

Here use Invalidate( ) to retype the characters. Refresh the data.

Page 20: Visual c++ and mfc windows programming

Now, we initialize the mouse position (mouseX, mouseY) to original point (0,0), to create a caret by using an if statement in OnDraw( ). Next, we need to take the next position of the caret for the next character. To obtain the extent of the text in the variable size and show the caret at the position we use (mouseX+size.cx, mouseY).

Here, we start to coding the handler OnLButtonDown(). In this handler, the mouse coordinates are copy to (mouseX, mouseY). And the string is cleared by calling the method pDoc->StringData.Empty() . Finally, a redraw of the Vie is forced by a call to Invalidate( ).

5. At last, we need to handle the messages WM_KILLFOCUS and WM_SETFOCUS to hide the caret after type and to display the caret before the next input. So, we first add those message to View (Show in Figure 4.6).As we have add the function OnKillFocus( ) & OnSetFocus( ) to the member function. And now, we need to add the statement HideCare( ) in OnKillFocus( ). By the same way to add the statement ShowCaret( ) in OnSetFocus( ). Show in Figure 4.7.

19

Use CSize function to get the length of the viriable StringData

point.x & point.y are using here to get the coordinate of the

To assert GetDocument( ) for load the variable StringData from the Document Class to View Class.

Page 21: Visual c++ and mfc windows programming

Figure 4.6 Add handlers OnKillFocus and OnSetFocus to member function

Figure 4.7 Edit OnKillFocus() & OnSetFocus() Finally, seems we finished the coding this example, just compile it and run it if there are “no errors & no warnings”. But there won’t be any caret anywhere in the client area. Because of we haven’t initialized for the position of the caret. Let’s go to CCaretView()::CCaretView() (the constructor of View Class, and it is also the Initialization of the View Class). Add following codes:

20

No new caret will created just in the initialized position.

Initialize both the positions of caret and mouse to be (0,0) .

Page 22: Visual c++ and mfc windows programming

Now, we compile and link this program. Run it after get none errors and warnings.You will see a caret on the left top of the client area (Show in Figure 4.8). If you click the left button of the mouse in client area arbitrarily, the caret will display at the position where you mouse down. And the caret will move to the next character’s position after you type word on the client area (Show in Figure 4.9).

Figure 4.8 Caret displaying at the initialized position on the client area

Figure 4.8 Caret displaying at position after typying

21

Page 23: Visual c++ and mfc windows programming

MDIMDI MDI (Multiply Document Interface) applications allow multiple document frame windows to be open in the same instance of an application. An MDI application has a window within which multiple MDI child windows, which are frame windows themselves, can be opened, each containing a separate document.

Let’s look multiple views and multiple documents. Several documents may be open simultaneously, each holding its own data, independent of data in the other documents. If a document is viewed through different views, each change to the document must simultaneously affect all the views. Views must be scrollable and cutting, copying and pasting must be possible between the views. Now, we take a simple example for MDI. The similar one like example1, but an extra action is for saving the data of each displaying.

1. To create a new project named Multiview. Choose Multiple Document as the base interface (Show in Figure 5.1). No need to change other settings, just make other 5 steps to default till finish creating the project. Visual C++ will create the classes automatically. After checking all the default classes are OK! Then, we can go on with coding in each class, which are needed for the request.

Figure 5.1 the first step for create a MDI project

22

Page 24: Visual c++ and mfc windows programming

2. In the Document, we set up and initialize a CString variable StringData, which is to hold some text. We also include the familiar two lines for serialization in the if statement of Serialize( ).

3. In the View, we modify OnDraw( ), to call pDC->TextOut( ). Then we modify OnChar( ) so that each new key board character is added to the string and the View is invalidated. Otherwise, we call UpdateAllViews( ) to update any other views of the Document as well. Finally we call SetModifiedFlag( ) so that the user, when exiting the application, is asked to save a document if it has changed since the last Save.

23

Declare Cstring variable StringData

To initialize the variable StringData as a empty string.

Save the data which is in the variable StringData to ar

Reload the data from ar to the variable StringData.

Display the string at the position (0,0) on the client area

Page 25: Visual c++ and mfc windows programming

Ok, as we have finished coding it, just compile & run it if there are not any errors & warnings exists. Let’s see how it happens after running the program. Show in following step.

The environment of Multiview application

When you close the application it will ask for saving

24Support user to continue type, count the number of character.

Refresh the data all the time

Refresh the data in all the View

Support the user can save the file while user want to quit out of this project.

Page 26: Visual c++ and mfc windows programming

DialogDialog

The Dialog Box is one of the most important mechanism the application has, after the view, to retrieve information from the user.

Sometimes, your program may have many ActiveX events. You will probably think the main window is showing such ActiveX events to the users. One easy way to do that, you can program it with a Dialog base as the main window. And now, we take a example for Dialog which have one Button “Click Me” & one Textbox:

When the user click the Button “Click Me”, the Textbox will display one message “Dialog box Windows!” :

Now, we create a new project named “buttons”.

1. In the Step 1 of AppWizard, Click “Dialog based” make the new project to base on CDialog Class, show in figure 6.1.

2. Click Finish to create new project.

3. To the next, click “Resources” label, open the “Dialog” file folder, and click the item IDD_BUTTONS_DIALOG to open the editor of Dialog interface (Show in figure 6.2).

4. Add a new button, to name it “Click Me”(To click the right button of the mouse, choose Properties, to change the name in the Caption box, show in figure 6.3), also by the same way to add one new Textbox (Show in figure 6.2).

25

Page 27: Visual c++ and mfc windows programming

Figure 6.1 Create the project which is base on Dialog

Figure 6.2 Design the interface of the Dialog

26

Page 28: Visual c++ and mfc windows programming

Figure 6.3 to change the name of the button

5. Open ClassWizard, link the button to the handler OnButton1( ) (Show in Figure 6.4). Double click IDC_BUTTON in the Object IDs box, and double click BN-CLICKED in the Messages box to create OnButton( ) :

void CButtonsDlg::OnButton1() {

// TODO: Add your control notification handler code here}

Figure 6.4 Add handler OnButton1() to member function

6. As we need to display one message “Dialog box Windows!” in the Textbox after the user click the button “Click Me”. We need declare a member variable for the Textbox named m_text.

27

Page 29: Visual c++ and mfc windows programming

7. Open ClassWizard, to choose IDC_EDIT1 in the Control IDs box after click Member Variable. To be sure that the Class name is CbuttonDlg. Then, click Add Variable to open Add Member Variables box, show in Figure 6.5. After that, we input m_text in Member Name Variable box, and to be sure that “Control” is display in the Category box, and “CEdit” is display in Variable type box. Just click OK after all. Show in Figure 6.6.

Figure 6.5 Create the member object

Figure 6.6 Create a new variable m_edit

28

Page 30: Visual c++ and mfc windows programming

From the above picture we can see that in the Category it has two choice one is Value, another is Control. The difference is that Value is only saving the data in that member variable. But, if it’s setting to Control, so it needs condition to act this member variable. Like preceding program, it need click button “Click Me”, then display the message.

8. Add code to OnButton1( ) for display the message after click the button. Here we use the function SetWindowText( ).

Now, we finished coding this program, let’s compile and link it. And just run it after got “0 errors & 0 warnings”. After you click the button “Click Me” it will display the message in the Textbox (Show in Figure 6.7).

This program use Dialog base as it’s main window

Figure 6.7 Message displaying in the TextBox after clicked the button

<<Back to the top

29

The function, which can support display the string in the Window TextBox.

Page 31: Visual c++ and mfc windows programming

SCROLLER & SPLITTING Scrolling Scrolling A scroll is the one bar, which can automatically change orientation of any position in the view.

Now, let’s take an example that how to add a scroll in the SDI. Following next steps:

1. Create a new project, and give the name “scroll”.

2. Choose Single Document as the base interface.

3. To the last step of creating the application using the AppWizard, select CScrollview in the base class combo box. After that, click on Finish (Show in Figure 7.1).

Figure 7.1 Creating project with Base class CscrollView

30

Scrollbars

Page 32: Visual c++ and mfc windows programming

4. The next step is to set up a CSize variable sizeTotal, which comprise an x- and a y- coordinate. This variable is to contain the total size of the View (not just the visible area) and let’s initialize to (1000,1000) arbitrarily.

5. Then, to make the views scrollable, we need to set the total size of the view, using a call to the View method SetScrollsizes( ). The second parameter is sizeTotal as just defined and the first parameter is a constant MM_TEXT, which indicates that the unit of measurement is screen pixels.

6. Well, as we finished coding the program. Just compile & run it. You will see the two scrollbars display at the right and the bottom (Show in Figure 7.2).

31

Use CSize function to get the document size, and to return the variable size to mSize.

To initialized mSize with CSize function

To declare mSize by the function calling CSize

To give the variable size to sizeTotal by the function GetdocSize() which is in the document Class

Page 33: Visual c++ and mfc windows programming

Figure 7.2 Scroll View in the SDI

SplittingSplitting The splitting means to cut up the document to different size of parts. Now, we are doing a program to get the following requests:

To split a source window

1. Switch to the source window.

If there are multiple windows open on the source file, select one of them.

2. From the Window menu, choose Split.

The split bar appears.

3. Drag the split bar to the location you want.

Because as we did in the previous programming, it’s has a Scroll View class. And split is one of the member functions there. Let’s follow next steps to see how to do splitting in MDI.

1. Create a new project and name it split, select MDI as the base interface. To choose “CScrollView” for the “base class:” at the 6th step.

32

Page 34: Visual c++ and mfc windows programming

2. Go to ResourceView to modify IDR_SPLITTYPE in the Menu item (Show Figure 7.3). To add “split” in “window” tools. “ID_WINDOW_SPLIT” is one member in ID resource, and it has default prompt (Show in Figure 7.4).

Figure 7.3 IDR_SPLITYPE item in the Menu item

Figure 7.4 Add split to Menu Item

3. Add message handler OnCreateClient to Member function in CChildFrame Class (Show in Figure 7.5).

Figure 7.5 Add OnCreateClient in ClassWizard

33

Place for new item

Page 35: Visual c++ and mfc windows programming

4. Embed a CSplitterWnd member variable in the application’s CChildFrame Class.

5. Let’s add code to CChildFrame::OnCreateClient to set the initialization of the splitter.

6. Till now, we finish almost the steps of this program. Let’s run it after compile with no error & warning. Then you will get the window show like Figure 7.6 (a,b).

Figure 7.6.a the boot key for start splitter

34

CSplitterWnd is the function for create split variable

Different style configuration of the splitter

Page 36: Visual c++ and mfc windows programming

Figure 7.6.b after decide on the position for splitting

You can also split by vertical side by change the value of row and column (Like following show).

Well, after that you can get the splitting show like Figure 7.7.

Figure 7.7 the result for vertical split

<<Back to the top

35

Page 37: Visual c++ and mfc windows programming

GRAPHICS & TEXT & PRINTING

Graphic Object Classes and the Handles They Encapsulate

MFC Class Graphic Object Handle Graphic Object Purpose

Cbitmap HBITMAP Bitmap in memory.

Cbrush HBRUSH Brush characteristics – when filling a shape, the color and pattern to be used.

Cfont HFONT Font characteristics – when writing text, the font to be used.

Cpalette HPALETTE Palette colors.

Cpen HPEN Pen characteristics – when drawing an outline, the line thickness to be used.

CRgn HRGN A region’s characteristics including the points that define it.

Using a Device Context

Suppose that you want to send output to a particularly windows. Here is the basic sequence of activities that will take place: Provided you have pWnd, a pointer to a window object (i.e., the white part) of that window can be acquired by creating a CclientDC object, i.e.,

CClientDC dc(pWnd);

The characteristics of that device context (e.g. , current font, attached drawing objects) can then be modified, as desired. e.g. ,

Normally, there are two ways to construct GDI object:(1) Construct by one section: both of the constructor and the initialization are

completed by the constructor function, which is carrying parameters.

For example: Cpen myPen(PS_SOLID,2,RGB(0,0,0)); // double thickness of the black solid line. Cbrush myBrush(RGB(0,0,255)); // blue color of the brush

36

Page 38: Visual c++ and mfc windows programming

(2) Construct by two sections: constructor is completed by the constructor the function which is not carrying parameters. And, initialization is completed byinitializing the function :

For example: Cpen myPen; MyPen.CreatePen(PS_SOLID,2,RGB(0,0,0)); //double thickness of the black solid line Cbrush myBrush; MyBrush.CreateSolidBrush(RGB(0,0,255)); //blue color of the solid brush

Drawing functions, all of which are members of the CDC object, can then be called. e.g. ,

dc.MoveTo(45,50); // the initialized position of the line dc.LineTo(40,90); // the final position of the line

Characteristics of a Device Context

Every device context has certain characteristics associated with it, many of which can be modified by the user: Coordinate System: There are three relevant aspects of a window coordinate system: - Mapping mode: the coordinates are fixed in size(e.g. , 10 dots per mm.) or they depend on the size of the window. - Window coordinates and origin: Determines the X and Y range of the coordinates of logical window(not all of which may appear on the screen).

- Viewport coordinates and origin: Determines the range of coordinates appearing on the screen of variable mapping modes.

Drawing tools: The specific drawing tools that are currently selected. Some of these include: - Pen: The color and width of which determine how lines will appear. - Brush: The color and pattern used to fill areas. - Font: The size and style that is used to draw text.

PenPen

The pen associated with a given device context determines how lines, rectangles, circles, etc. will look when they are drawn on the screen. Key characteristics include:

Style: How the line will look (e.g., PS_SOLID, PS_DASH, PS_DOT) Width: The width of the line in pixels. Styles only apply to lines of width 1. Color: The color of the line, specified as an RGB(red, green, blue) value, where measured from 0 to 255 respectively.

37

Page 39: Visual c++ and mfc windows programming

Now, we take an example for drawing line, rectangle and circle by different kind of styles, widths, colors.

1. Create a new project named “Pen”, and select SDI as the based interface.

2. Create a Cpen object in function OnDraw( ) of the View Class( Show in Figure 8.1).

Figure 8.1 to create CPen object

3. Use function MoveTo & LineTo to drawing lines (Show in Figure 8.2).

SelectObject is the function of Device Context, here we use it to reload CPen variable penA.

Figure 8.2 drawing line

4. To compile it, see if there is any errors or warnings. Then, just run it. And you will get the dotted line like Show in Figure 8.3.

38

Use CPen to declare variable pen A to writes with thin black dotted line

Use point of Device Context to point to the function “SelectObject” to load pen A

MoveTo declare the initial position of the line, and LineTo declare the final position of the line.

Page 40: Visual c++ and mfc windows programming

Figure 8.3 The red dotted line in SDI

5. To create other two pens (penB & penC) by the same way like penA.

6. Use function Rectangle to drawing rectangles, and function Ellipse for drawing ellipses. Both functions are the members of CDC(Show in Figure 8.4).

Figure 8.4 Drawing rectangle and ellipse

7. Finally, we finish this program. Let’s compile and run it. See the result like Figure 8.5.

39

The initial position (50,100) of the rectangle

The final position (700,200) of the rectangle

The initial position (50,250) of The ellipse

The final position (700,350) of the ellipse

(50,50)

(700,50)

Page 41: Visual c++ and mfc windows programming

Figure 8.5 The result for drawing line & rectangle & ellipse

BrushBrush

The CBrush class encapsulates a Windows graphics device interface (GDI) brush. To use a CBrush object, construct a CBrush object and pass it to any CDC member function that requires a brush.

The brush associated with a given device context determines how fill commands will appear. Key characteristics include:

Color: The color of the line, specified as an RGB(r,g,b)value. Hatch Style: How the fill pattern will appear (e.g., HS_BDIAGONAL, HS_CROSS, HS_VERTICAL). Bitmap: Allows the fill pattern to be set by an 8x8 pixel bitmap (used instead of color and style).

Here, we create a new project named Brush and to choose SDI as the base interface. The same step as preceding program, we add codes to OnDraw().

1. Declare a CBrush variable “BrushA” to create CBrush object. Then, we draw a rectangle by red solid brush (Show in Figure 8.6). As well as we have written the code, just run it after getting “0 errors and 0 warnings”. You can see the result like Figure 8.7.

40

Page 42: Visual c++ and mfc windows programming

Figure 8.6 Create a CBrush object to brush the rectangle

Figure 8.7 The result for drawing a red solid rectangle

2. Use the same way as preceding program to create CBrush object (by name this variable brushB ). And, to create a ellipse by HS_BDIAGONAL brush Show in following way.

3. Till now, let’s compile the program. After running it, you can get the result like Figure 8.8.

41

Page 43: Visual c++ and mfc windows programming

Figure 8.8 A green brush rectangle with HS_BDIAGONAL style

Now, let’s try to drawing 3 ellipses with 3 different way. Make the result like following picture:

Here is code for it, if have some problem with programming this example. Just take look at Figure 8.9.

42

Page 44: Visual c++ and mfc windows programming

Figure 8.9 Other extra way for create CBrush object

FontsFonts

The CFont class encapsulates a Windows graphics device interface (GDI) font and provides member functions for manipulating the font. To use a CFont object, construct a CFont object and attach a Windows font to it with Create Font, CreateFontIndirect, CreatePointFont, or CreatePointFontIndirect, and then use the object’s member functions to manipulate the font.

The CreatePointFont and CreatePointFontIndirect functions are often easier to use than CreateFont or CreateFontIndirect since they do the conversion for the height of the font from a point size to logical units automatically.

Fonts are a bit more complicated than pens or brushes because they have many more attributes. For example:

Height: height of font in logical units. Width: average width of a character in the font, in logical units. In proportional font, actual width may vary significantly. Escapement: Angle of text strings, in 0.1 degree units, measured counterclockwise from the X axis. Orientation: Angle of individual characters, in 0.1 degree units, measured counterclockwise from the X axis. Used to create effects, such a vertical text strings. Weight: The thickness of the typeface. Italic, Underline, Strikout: Style of font. Typeface name: A string indicating the name of the font.

43

Use CBrush object point to *oldBrush to

By the same way as the preceding code.Here we use “= new CBrush()” to create a new CBrush object

Use delete function to cancel CBrush variable pblueBrush.

Page 45: Visual c++ and mfc windows programming

To creating a Font, because there are so many font characteristics, there is no constructor function for directly creating fully defined CFont object. Let’s now, take example for how to create it.

1. Create a new project and name it “Font”, select SDI as the base interface.2. Create a CFont variable “myFont” .3. Use CreateFont( ) function to create font of variable myFont. The parameters

are the same with LOGFONT structure (Show in Figure 8.10).4. Use SetTextColor( ) & TextOut( ) to create the color and the text for display

(Show in Figure 8.11).

typedef struct tag LOGFONT {LONG lfHeight;LONG lfWidth;LONG lfEscapement;LONG lfOrientation;LONG lfWeight;BYTE lfItalic;BYTE lfUnderline;BYTE lfStrikeOut;BYTE lfCharSet;BYTE lfOutPrecision;BYTE lfClipPrecision;BYTE lfQuality;BYTE lfPitchAndFamily;TCHAR lfFaceName[LF_FACESIZE];} LOGFONT, *PLOGFONT;

Figure 8.10 The structure of LOGFONT

lfHeight :Value Description

> 0 The font mapper transforms this value into device units and matches it against the cell height of the available fonts.

0 The font mapper uses a default height value when it searches for a match.< 0 The font mapper transforms this value into device units and matches its absolute

value against the character height of the available fonts.

LfCharSet: The following values are predefined

ANSI_CHARSET BALTIC_CHARSETCHINESEBIG5_CHARSET DEFAULT_CHARSETEASTEUROPE_CHARSET GB2312_CHARSETGREEK_CHARSET HANGUL_CHARSETMAC_CHARSET OEM_CHARSETRUSSIAN_CHARSET SHIFTJIS_CHARSETSYMBOL_CHARSET TURKISH_CHARSET

44

Specifies the character

Specifies the output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, pitch, and font type.

Specifies the clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region.

Specifies the output quality. The output quality defines how carefully the graphics device interface (GDI) must attempt to match the logical-font attributes to those of an actual physical font.

Specifies the pitch and family of the font. The two low-order bits specify the pitch of the font.

A null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 32 characters, including the null terminator. The EnumFontFamiliesEx function can be used to enumerate the typeface names of all currently available fonts. If lfFaceName is an empty string, GDI uses the first font that matches the other specified attributes.

Page 46: Visual c++ and mfc windows programming

Figure 8.11 Create font for the text

5. Right now, we completed this program. Let’s run it after compiling without error & warning (Show in Figure 8.12).

Figure 8.11 the final text displaying with special font

45

Both the angle of text strings and the angle of individual characters are 45 degree units.

-30 here means the height of the characters.

Page 47: Visual c++ and mfc windows programming

BitmapBitmap

The CBitmap class encapsulates a Windows graphics device interface (GDI) bitmap and provides member functions to manipulate the bitmap. To use a CBitmap object, construct the object, attach a bitmap handle to it with one of the initialization member functions, and then call the object’s member functions.

The easiest way to use a bitmap is to load it from a resource. Now, we make an example for how to make it in SDI.

1. Create a new project and name it “MyBitmap”.2. Go to Resource and insert a new Bitmap (Show in Figure 8.12).3. After finish drawing the picture, it will give it a default name: Bitmap1 (Show

in Figure 8.13).4. Use CBitmap to create a new bitmap. The CDC loadBitmap function converts

a resource-basedDIB to a GDI bitmap. Below is the simplest possible self- contained OnDraw function that displays the BITMAP1 bitmap.

Figure 8.12 Insert new Bitmap into Resource

46

Create a new CDC

Load the bitmap by the ID number

Creates a memory device context

Use CBitmap* to create pOldBitmap which is point to IDB_BITMAP1

Copies a bitmap from the source device context to this current device context.

Page 48: Visual c++ and mfc windows programming

Figure 8.13 the property of new Bitmap

5. After compile with none errors & warnings, just run it with F5. You will see the result like Figure 8.14.

Figure 8.14 Bitmap1 is display in the client area

<<Back to the top

47

Page 49: Visual c++ and mfc windows programming

LITTLE OBJECTS & SYNCHRONIZATION

As we mentioned in MFC FEATURE, serialization is a CArchive object uses overloaded insertion (<<) and extraction (>>) operators to perform writing and reading operations. We know that the easiest way to do it is to code it in Document Class. And, there is a Serialize function for that. Here, we learn how to use it in our own class. Just follow the steps to get the main idea of how to do that.

Create a new project, and name it “Writer”. Select SDI as the base interface. Then, do the program as preceding one like Multiview project. User can type, and can do both save and load data. If have some problem just consider following codes:

……

……

……

48

Use CString function to declare CString variable StringData.

To initialize the variable StringData as an empty string.

“+= nChar” support user can continue on typing characters.

Use SetModifiedFlag ( ) function to inform the user to save the document before quit.

Display the data at the position

Page 50: Visual c++ and mfc windows programming

……

…… It’s the same codes like we did in MultiView task. Now, we see how to do the serialization in your own class. And, start from the beginning step by step:

1. Create a new project which name is “Serialize”, select SDI as the base interface.

2. After we created a new project, we need to add our own class to the project. The most easiest way to do that is go to file label, and choose “C/C++ Header File”. Be sure that “Add to project” has been clicked, and the project name is “Serialize”. Give the file name as “CData.h”. (Show in Figure 9.1)

Figure 9.1 Add own class to a exist project

49

To save the data

To reload the data

If open a new document the client area will be empty.

Page 51: Visual c++ and mfc windows programming

3. Use the following way to store the string “data” in this class, and use three different function to initialize the string:

4. Otherwise, if we want to load the CString variable data in the Document class, it’s better to including CData class in the Document class. Create a new object of CData class, and name it DataObject.

5. Now, we add code to OnChar( ) function to get the characters which users type. By the same way as the previous program, but to use AddText( ) function to add the characters into the CString variable data which only can load by the new object DataObject.

50

Initialize the CString variable data to be an empty string

Declare the AddText() function for doing action like add characters to the end of the string.“data += text” is the same way as the preceding program, like “StringData += nChar”

Delcare the DrawText() function to output the string on the position of client area which declare in TextOut() function.

The ClearText() function is to refresh the string to an empty string

Include the CData Class

Create a project by CData Class

As we declare the variable in AddText() function is “text”. So, here we use “CString(nChar)” to reload to text.

Page 52: Visual c++ and mfc windows programming

6. To be the same, we can use the DrawText( ) function which is from OnDraw( ) function in View Class. Following way to output the string through the object DataObject.

7. If you want to serialize the CData Class. Make sure that CData Class is public from MFC CObject Class (the base of all MFC Classes). Secondly, you may define DECLARE_SERIAL in declaration of CData class. At last, we need to declare a Serialize() function of CObject. Show in Figure 9.2.

You can choose from four levels of functionality when deriving a class from CObject:

Basic functionality: No support for run-time class information or serialization but includes diagnostic memory management.

Basic functionality plus support for run-time class information. Basic functionality plus support for run-time class information and

dynamic creation. Basic functionality plus support for run-time class information, dynamic

creation, and serialization.

51

As we declare the DrawText( ) function. Here just give the type (CDC* pDC) for DrawText().

Here, we can’t do the serialization as the preceding program. Not just straightly serialize DataObject in Document Class. All because of it didn’t define any serialization in CData Class. So, we should create our own serialization to CData Class.

DECLARE_SERIAL generates the C++ header code necessary for a CObject-derived class that can be serialized. Serialization is the process of writing or reading the contents of an object to and from a file. Use the DECLARE_SERIAL macro in a .H module, then include that module in all .CPP modules that need access to objects of this class. If DECLARE_SERIAL is included in the class declaration, then IMPLEMENT_SERIAL must be included in the class implementation.

Page 53: Visual c++ and mfc windows programming

Macros Used for Serialization and Run-Time Information

Macro used CObject::IsKindOf

CRuntimeClass::CreateObject

CArchive::operator>>CArchive::operator<<

Basic CObject functionality No No No

DECLARE_DYNAMIC Yes No No

DECLARE_DYNCREATE

Yes Yes No

DECLARE_SERIAL Yes Yes Yes

Figure 9.2 Create serialize function in own class

8. By the same way for create CData.h, we add a new file “CData.cpp” to project. Let’s open it, and define Serialize( ). First, construct Serialize( ) function from base class(CObject). Secondly, use << & >> to serialize the CString variable data. Finally, use the declaration IMPLEMENT_SERIAL to do the implementation of the class.

52

Define that CData Class as the base class of MFC

To create a own serialize() function for CData class

Assert CData support serial base

Store the string to variable data

Reload the string to variable data

Construct serialization of own class

Page 54: Visual c++ and mfc windows programming

9. Now, we can serialize our own class (CData Class). The last step is to serialize the object DataObject. Use the following way to load it in serialize( ) function of Document Class.

Finally, we finish this program. Compile it and run it, if you get none errors and warnings. We can have a test for this program. Just type some thing on the client area. Save the file and give the name “serialize.txt”. And, run the program again. Open the file that you saved just now. You will see the same data which u typed just now in the client area (Show in Figure 9.3). Also the name if the file will display at the title of the document window.

Figure 9.3 Saving & Loading the file of own serialization

Well, it seems to be the same processing as the preceding program. Only difference is by this program, we use our own serialize of own class.

<<Back to the top

53

IMPLEMENT_SERIAL( class_name, base_class_name, wSchema )<Parameters>class_name: The actual name of the class (not enclosed in quotation marks).base_class_name: The name of the base class (not enclosed in quotation marks).WSchema: A UINT “version number” that will be encoded in the archive to enable a de-serializing program to identify and handle data created by earlier program versions. The class schema number must not be –1.

The file is belong to the project name

Page 55: Visual c++ and mfc windows programming

THE DATABASE

FILE & DATABASE CLASSFILE & DATABASE CLASS

These classes allow you to store information to a database or a disk file. There are two sets of database classes — DAO and ODBC — which provide similar functionality. The DAO group is implemented using the Data Access Object, while the ODBC group is implemented using Open Database Connectivity. There are also a set of classes for manipulating standard files, Active streams, and HTML streams.

DAO CLASSDAO CLASS

These classes work with the other application framework classes to give easy access to DAO (Data Access Object) databases, which use the same database engine as Microsoft Visual Basic® and Microsoft Access. The DAO classes can also access a wide variety of databases for which ODBC (Open Database Connectivity) drivers are available.

Programs that use DAO databases will have at least a CDaoDatabase object and a CDaoRecordset object.

CDaoDatabase: A connection to a database through which you can operate on the data.

CDaoRecordset: Represents a set of records selected from a data source.

ODBC CLASSODBC CLASS

These classes work with the other application framework classes to give easy access to a wide variety of databases for which ODBC drivers are available. Programs that use ODBC databases will have at least a CDatabase object and a CRecordset object.

CDatabase: Encapsulates a connection to a data source, through which you can operate on the data source.

CRecordset: Encapsulates a set of records selected from a data source. Record-sets enable scrolling from record to record, updating records (adding, editing, and deleting records), qualifying the selection with a filter, sorting the selection, and parameterize the selection with information obtained or calculated at run time.

There are many other classes in Database classes. Here, we concentrate on DAO and make an example. As we had a database already which named “Student.mdb” (It’s made by Microsoft Access.)

54

Page 56: Visual c++ and mfc windows programming

1. Create a new project, name it “StudentDB”. Choose SDI as the base interface. As the “Step 2 of 6”, you may select “Database view with file support”(Show in Figure 10.1).

Figure 10.1 Step 2 of MFC AppWizard about database support

1. After selected the database support, click the button “Data Source…” . It will display a Database Options window (Show in Figure 10.2).

Figure 10.2 Configuration of Database Option

55

Nowadays, people use Office2000 or OfficeXP. And maybe the version can’t be supported by DAO. So, the best way is to change the version of the Access file. Go to Tools >> Database Utilities >> Convert Database >> To prior Database version… And the Version of this Access file may change to Access 97. After you save to a new file. Then it can be supported by DAO.

Click this button to get the Database Options selection

Find the correct path of Access file, which you want to add to the Datasource.

A snapshot is a record-set that reflects a static view of the data as it existed at the time the snapshot was created.

A “dynaset” is a record-set with dynamic properties.

A table is a record-set with columns & fields properties.

Page 57: Visual c++ and mfc windows programming

2. You need to select correct Database Table after click the button OK in Database Options (Show in Figure 10.3).

Figure 10.3 Selection the Database tables which is load by Access file

3. Just make the default setting of other steps till to the Step 6. Be sure that CDaoRecordView Class is the Base class. Because of the DAO type is the data source type right now. So, there should be a CDaoRecordView Class in the Base class automatically (Show in Figure 10.4).

Figure 10.4 Step 6 of creating the database project

4. Till now, we have finished all the creating of this project. Firstly, we check if there is any class, which is new in the StudentDB Classes. As you can see in the following picture, there is a new class, which named CStudentDBSet.

56

This table is the Access file, which added to data source with the same name of the file.

CDaoRecordView Class is the class which holding the data base.

Page 58: Visual c++ and mfc windows programming

5. And there is a new Dialog box in the ResourceView, and the ID is IDD_STUDENTDB_FORM. Let’s make an interface of this dialog like show in Figure 10.5.

Figure 10.5 Add controllers to the dialog

6. Give the member variable m_StudentName & m_StrudentGrade to those two TextBox in AppWizard (Show in Figure 10.6). And, give the message handler to Button as BN_CLICKED (Show in Figure 10.7). As we have done such kind of action in the preceding programs. So, just skip those steps for doing add member variable& message handler.

Figure 10.6 Add message handler to OnButton1

57

These two member variables are the default string variables. It came from that Access file which you add to data source.

CStudentDBSet is the class which saving the data of the Access file and the default setting of the database of that file.

Static box

Text box

Button

Here we choose “Value” instead of “Control”. Because of it just output the string no any return value

Page 59: Visual c++ and mfc windows programming

Figure 10.7 Add variable to both IDC_EDIT1 & IDC_EDIT2

7. Let’s go back to code area. You will find there is a new member variable m_pSet, which is already in the View Class. It is use to loading the data from CStudentDBSet class. As you can see in the following codes, it get the document from m_studentDBSet. And it create a new constructor about CDaoRecordView by OnInitialUpdate( ) function.

58

CFrameWnd* GetParentFrame( ) const;Return Value A pointer to a frame window if successful; otherwise NULL.Remarks Call this member function to retrieve the parent frame window. The member function searches up the parent chain until a CFrameWnd (or derived class) object is found.

virtual void RecalcLayout( BOOL bNotify = TRUE );Parameters bNotify Determines whether the active in-place item for the frame window receives notification of the layout change. If TRUE, the item is notified, otherwise FALSE.Remarks Called by the framework when the standard control bars are toggled on or off or when the frame window is resized.

Resize the frame window

Dictate the view size of the size of frame window

Page 60: Visual c++ and mfc windows programming

8. Now, time for edit code for Button1. If the user click the button, in each TextBox will display the student’s name & student’s grade. Here we may add some new functions of CStudentDBSet class. IsEOF( ) , MoveNext( ) , MoveFirst( ). Add following codes to OnButton1( ), let’s see what will happened.

59

void ResizeParentToFit( BOOL bShrinkOnly = TRUE );Parameters bShrinkOnly The kind of resizing to perform. The default value, TRUE, shrinks the frame window if appropriate. A value of FALSE causes the view always to resize the frame window exactly. Remarks Call ResizeParentToFit to let the size of your view dictate the size of its frame window. This is recommended only for views in MDI child frame windows.

Load the data from the member variable of the database to the member variable of Text box

Refresh the data

BOOL IsEOF( ) const;Return Value Nonzero if the recordset contains no records or if you have scrolled beyond the last record; otherwise 0.Remarks Call this member function as you scroll from record to record to learn whether you have gone beyond the last record of the recordset.

Read the next record in the recordset the current

Read the first record in the recordset (if any) the current

Page 61: Visual c++ and mfc windows programming

9. After all the things are ready, let’s compile and run the program if without any errors and warnings. You will get the window like Figure 10.8.

Figure 10.8 Displaying the data from the database to SDI

<<Back to the topMULTITASKING

Till now, you can start to plan your own project. First, be sure that what the main idea of your project. Secondly, plan your classes and variables carefully. Make a graphic if it’s possible. Now we start to program one virtual library task. Let’s see how the use of threads and processes in applications works.

Create a new project, and name it “library”. Select SDI as the base interface. And you need to have a database of books before you start to program wish this project. After finish creating the project, choose the correct database. Let’s following the steps:

1. Select the “bookdatabase.mdb” as the database support (Show in Figure 11.1). Choose the right table show in Figure 11.2.

60

Page 62: Visual c++ and mfc windows programming

Figure 11.1 Open one database to support the data for this program

Figure 11.2 Select the table of the Database

2. Make sure that CDaoRecordView Class is chosen in the base class. As the preceding program, it need load the data from the database file. Check the 6th step of creating project (Show in Figure 11.3).

61

Page 63: Visual c++ and mfc windows programming

Figure 11.3 MFC support base class for database

3. Insert a new Dialog for PASSWORD typing. And set the ID as IDC_PASSWORD, also use “Password” for the title (Show in Figure 11.4). Add a) Static Picture Controller, set type to be “Icon”, and choose the one icon which for KEY frame. b) One StatitText for topic is “Password”. c) One TextBox, which support user to type password, give the ID as IDC_PASSWORDEDIT. After all, choose both “Tab order”& “Password” command in the Layout menu, and you can make the sequence like Figure 11.5.

Figure 11.4 load icon into one static picture controller

Figure 11.5 Password Dialog and Tab sequence

62

Page 64: Visual c++ and mfc windows programming

4. Get into ClassWizard, it will ask you to create a new class. Just give the class name as CpasswordDlg. Select Cdialog as the base class (Show in Figure 11.6).

Figure 11.6 Create one new class for new dialog

5. Give the name of member variable to TextBox as “m_Password”, and select CString for the type of it. Go to CPasswordDlg.h to declare two CBitmapButton variable button1& button2.

6. Create OnInitDialog( ) function in PasswordDlg.cpp . Using the following way to create the border of the button.

63

Use the CBitmapButton class to create push-button controls labeled with bitmapped images instead of text.

Using SizeToContect( ) function here to resize a bitmap button to the size of the bitmap.

Here use SubclassDlgItem( ) function is to determine if OK button was clicked.

Page 65: Visual c++ and mfc windows programming

7. Find InitInstance( ) function which is in CLibraryApp Class. Let’s add codes to the function, which can check if the user typed correct password or not (Here we set the password as “gyx801213”).

8. Now, you can test it, and see if anything problem with these codes. Compile and run it, you can get the dialog like Figure 11.7.

64

VERIFY( booleanExpression )ParametersbooleanExpressionSpecifies an expression (including pointer values) that evaluates to nonzero or 0.RemarksIn the debug version of MFC, the VERIFY macro evaluates its argument. If the result is 0, the macro prints a diagnostic message and halts the program. If the condition is nonzero, it does nothing.

Use strcmp() function to compare the password which user typed with the correct password

MessageBox( ) function here to set the form of display on the message box.To assume quit out of program if still

wrong password for the third typing

Page 66: Visual c++ and mfc windows programming

Figure 11.7 Message box will display if the password is wrong

9. Seems checking password is ok. Now, let’s try to make the management of library. As you are a manager of this library you can check all the information about how books are in and out. Firstly, make the dialog surface like Figure 11.8. And after that, give member variable for each item (Show in Figure 11.9).

Figure 11.8 Design the interface of library system

Figure 11.9 Add variable to each member of library item

65

Page 67: Visual c++ and mfc windows programming

10. Add function for ID_RECORD_FIRST, ID_RECORD_LAST, ID_RECORD_NEXT, ID_RECORD_PREV (Show in Figure 11.10).

Figure 11.10 Creating message handler to record command

11. Now add code to each function like following way (just like preceding program that user click the button to load the data from the database). And the system will inform the message if something wrong with the operating.

66

Reach the first record of the database

Reach the last record of the database

Page 68: Visual c++ and mfc windows programming

12. Finally, we finish this small project. Compile and run it if without any errors and warnings. If successfully, you can see like Figure 11.11.

Figure 11.11 Section 1) Ask user to type password

Figure 11.11 Situation 1) Message to inform the user after wrong type for 3 times

67

Reach the next record to the current record

Reach the previous record to the current record

Page 69: Visual c++ and mfc windows programming

Figure 11.11 Section 2) User interface after typed correct password

Figure 11.11 Section 3) User can find the information of borrowing by click the button ->

68

This is the button, which can load the first record

This is the button, which can load the previous record from current one

This is the button, which can load the last record

This is the button, which can load the next record from current one

Page 70: Visual c++ and mfc windows programming

Figure 11.11 Situation 2) Message informing the user that end of the record

Figure 11.11 Situation 3) Message informing the user that initial of the record

Now, we continue on and to make an extra thing here. Add one button to the IDD_LIBRARY_FORM like Figure 11.12. Give ID as IDC_BUTTONBROWSE.

Figure 11.12 new button was added

69

This button is supported by special style

Page 71: Visual c++ and mfc windows programming

Add new one dialog, give it’s ID as “IDD_WebBrower”. Delete CANCEL button, change the caption of IDOK to “E&xit”. Here, we need to add one ActiveX controller for Microsoft WebBrowser. Click right button of the mouse, choose “Insert ActiveX contrl…” . Select “Microsoft WebBrowser” in the list box.

It will display a webBrowser window in the dialog after click OK button (Show in Figure 11.13). And it will give ID like IDC_EXPLORER1.

Figure 11.13 Create the window of webbrowser in dialog base

It will ask you to create a new class for dialog later you want to get into AppWizard. Just give the name “WebBrowserDlg” (Show in Figure 11.14)

70

Page 72: Visual c++ and mfc windows programming

Figure 11.14 Creating new class for new dialog

Add one button to dialog, give it’s ID as “IDC_BUTTONYAHOO” and caption as “Yahoo!” . Give the message BN_CLICKED to this button like Figure 11.15.

Figure 11.15 send message handler to Button click

71

Page 73: Visual c++ and mfc windows programming

It needs to give the member variable to IDC_EXPLORER1. If you click “Add variable…”, it will inform you to insert the this ActiveX controller into project. You see such kind of dialog frame show in following:

You can add variable to this web browser after confirm the class of CWebBrowser2. Just give the name as “m_webBrowser”(Show in Figure 11.16)

Figure 11.16 Add member variable to ActiveX controller

Go to OnButtonyahoo( ) function in WebBrowserDlg Class. Add following code to display the website of yahoo in window web Browser.

72

Page 74: Visual c++ and mfc windows programming

Now, we need to add one message BN_CLICKED to Button Browser to load browser dialog (Show in Figure 11.17).

Figure 11.17 Add message handler to Button

Add following codes to OnButtonbrowse( ) function.

73

void Navigate( LPCTSTR URL, DWORD dwFlags = 0, LPCTSTR lpszTargetFrameName = NULL, LPCTSTR lpszHeaders = NULL, LPVOID lpvPostData = NULL, DWORD dwPostDataLen = 0 );ParametersURL A caller-allocated string that contains the URL to navigate to, or the full path of the file to display.

Remarks Call this member function to navigate to the resource identified by a URL.

Load the webbrowser dialog by clicked the button

Page 75: Visual c++ and mfc windows programming

And don’t forget to put into LibraryView.cpp.

Compile and run it if there are no errors and warnings. After you click the button “Browse the Internet”, you will get the web browser dialog. And click the button “Yahoo!” you will see such dialog like Figure 11.18.

Figure 11.18 Browse the website through dialog base

<<Back to the top

74