Vous êtes sur la page 1sur 76

THE HISTORY OF WINDOWS............................................................1 THE MICROSOFT FOUNDATION CLASSES...................................

3
DOCUMENT CLASS................................................................................................9 VIEW CLASS (ARCHITECTURE)..........................................................................9

MESSAGE & MESSAGE MAP............................................................12 OTHER MFC FEATURES...................................................................15


COLLECTION CLASSES.......................................................................................15 SERIALIZATION....................................................................................................16

DIALOGUES..........................................................................................17
SDI...........................................................................................................................17 MDI..........................................................................................................................23 Dialog.......................................................................................................................26

SCROLLER & SPLITTING.................................................................31


Scrolling ................................................................................................................31 Splitting....................................................................................................................33

GRAPHICS & TEXT & PRINTING..................................................37


Pen............................................................................................................................38 Brush........................................................................................................................41 Fonts.........................................................................................................................44 Bitmap......................................................................................................................47

LITTLE OBJECTS & SYNCHRONIZATION.................................49 THE DATABASE...................................................................................54


DAO CLASS............................................................................................................55 ODBC CLASS.........................................................................................................55

MULTITASKING..................................................................................62

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. 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

THE MICROSOFT FOUNDATION CLASSES

4 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 havent done anything yet. Ok! Anyway, lets 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.

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

6 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. 8. In the Figure 1.4, AppWizard asking what kind of database will support. Here we dont 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 AppWizard

7 12. Here, AppWizard will explain, what kind of classes are create in this new program: CWelcomeApp, CmainFrame, CwelcomeDoc and CwelcomeView. 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++

8 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. 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 Figure 1.9). . Finally, you will get the result (Show in

Figure 1.9 the result for the program

DOCUMENT CLASS Document class objects, created by document-template objects, manage the applications 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 documents 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) 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 documenttemplate object. CView : The base class for application-specific views of a documents data. Views display data and accept user input to edit or select the data. Derive your view class(es) from CView. We havent store any data in the preceding example, excluding the variable welcome_string. Its easy to put the variable in the View Class. But, as a matter of fact it should put in the Document Class. Lets try another way by declare the variable welcome_string in welcomeDoc.h :

10

Storing program data; saving and loading program data from disk

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

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

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

To give the value to the variable welcome_string.

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( ) :

11

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

To display the variable welcome_string at the position (0,0) in the window . Displaying program data; processing user input; managing view window

Window, 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.

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

<<Back to the top

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

12

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.

13

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. Lets see more clearly about the Message & Message Map are working in each item. First, lets see how to edit the menu in Visual C++(Show in Figure 2.1).

14
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.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.

Figure 2.2 The window of Visual C++ ClassWizard

<<Back to the top

15

OTHER MFC FEATURES


COLLECTION 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:

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:

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. Its 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 lists ends.
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 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.

16 SERIALIZATION 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 CObjects 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 objects 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 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

17

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. SDI 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. Lets 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).

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

Figure 4.1 Add handler OnChar() to the member function

18

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).

To declare the variable in CCaretView.h

Use boolean type to declare caretCreated & CPoint to declare cretPosition 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).

To create caret in the client area. 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).

19

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. Figure 4.4 Add code to OnChar() for receive characters

4. The only thing we havent 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.

20 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).

Use CSize function to get the length of the viriable StringData

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( ).

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.

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.

21

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 wont be any caret anywhere in the client area. Because of we havent initialized for the position of the caret. Lets go to CCaretView()::CCaretView() (the constructor of View Class, and it is also the Initialization of the View Class). Add following codes:

No new caret will created just in the initialized position.

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

22 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 characters 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

23

MDI 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. Lets 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

24 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( ).

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.

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.

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

Refresh the data all the time

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

25

Refresh the data in all the View

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

Ok, as we have finished coding it, just compile & run it if there are not any errors & warnings exists. Lets 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

26 Dialog 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).

27

Figure 6.1 Create the project which is base on Dialog

Figure 6.2 Design the interface of the Dialog

28

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.

29 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

30

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 its 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( ).

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

Now, we finished coding this program, lets 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 its main window

Figure 6.7 Message displaying in the TextBox after clicked the button

<<Back to the top

31

SCROLLER & SPLITTING


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

Now, lets 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

32

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 lets initialize to (1000,1000) arbitrarily.

To declare mSize by the function calling CSize Use CSize function to get the document size, and to return the variable size to mSize.

To initialized mSize with CSize function

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.

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

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).

33

Figure 7.2 Scroll View in the SDI

Splitting
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, its has a Scroll View class. And split is one of the member functions there. Lets 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.

34 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).

Place for new item

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

35

4. Embed a CSplitterWnd member variable in the applications CChildFrame Class.

CSplitterWnd is the function for create split variable

5. Lets add code to CChildFrame::OnCreateClient to set the initialization of the splitter.

Different style configuration of the splitter

6. Till now, we finish almost the steps of this program. Lets 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

36

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

37

GRAPHICS & TEXT & PRINTING


Graphic Object Classes and the Handles They Encapsulate MFC Class Cbitmap Cbrush Graphic Object Handle HBITMAP HBRUSH Graphic Object Purpose Bitmap in memory. Brush characteristics when filling a shape, the color and pattern to be used. Font characteristics when writing text, the font to be used. Palette colors. Pen characteristics when drawing an outline, the line thickness to be used. A regions characteristics including the points that define it.

Cfont

HFONT

Cpalette Cpen

HPALETTE HPEN

CRgn

HRGN

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

38

(2) Construct by two sections: constructor is completed by the constructor the function which is not carrying parameters. And, initialization is completed by initializing 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.

Pen
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.

39

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).
Use CPen to declare variable pen A to writes with thin black dotted line

Figure 8.1 to create CPen object

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

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.

MoveTo declare the initial position of the line, and LineTo declare the final position of the line. 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.

40

(5050)

(70050)

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).
The initial position (50,100) of the rectangle

The final position (700,200) of the rectangle

The initial position (50,250) of The ellipse Figure 8.4 Drawing rectangle and ellipse

7. Finally, we finish this program. Lets compile and run it. See the result like Figure 8.5.
The final position (700,350) of the ellipse

41

Figure 8.5 The result for drawing line & rectangle & ellipse

Brush
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.

42

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, lets compile the program. After running it, you can get the result like Figure 8.8.

43

Figure 8.8 A green brush rectangle with HS_BDIAGONAL style

Now, lets 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.

44

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

Figure 8.9 Other extra way for create CBrush object

Use delete function to cancel CBrush variable pblueBrush.

Fonts
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 objects 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.

45 To creating a Font, because there are so many font characteristics, there is no constructor function for directly creating fully defined CFont object. Lets 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; Specifies the output precision. The output precision defines how closely LONG lfWidth; the output must match the requested font's height, width, character orientation, escapement, pitch, and font type. LONG lfEscapement; LONG lfOrientation; LONG lfWeight; Specifies the clipping precision. The clipping precision defines how BYTE lfItalic; to clip characters that are partially outside the clipping region. BYTE lfUnderline; BYTE lfStrikeOut; Specifies the output quality. The output quality defines how BYTE lfCharSet; carefully the graphics device interface (GDI) must attempt to BYTE lfOutPrecision; match the logical-font attributes to those of an actual physical font. BYTE lfClipPrecision; BYTE lfQuality; BYTE lfPitchAndFamily; Specifies the pitch and family of the font. The two low-order bits specify the pitch of the font. TCHAR lfFaceName[LF_FACESIZE]; } LOGFONT, *PLOGFONT;
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. Figure 8.10 The structure of LOGFONT Specifies the character

lfHeight :
Value >0 0 <0 Description The font mapper transforms this value into device units and matches it against the cell height of the available fonts. The font mapper uses a default height value when it searches for a match. 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_CHARSET CHINESEBIG5_CHARSET DEFAULT_CHARSET EASTEUROPE_CHARSET GB2312_CHARSET GREEK_CHARSET HANGUL_CHARSET MAC_CHARSET OEM_CHARSET RUSSIAN_CHARSET SHIFTJIS_CHARSET SYMBOL_CHARSET TURKISH_CHARSET

46

-30 here means the height of the characters.

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

Figure 8.11 Create font for the text

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

Figure 8.11 the final text displaying with special font

47

Bitmap
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 objects 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 selfcontained OnDraw function that displays the BITMAP1 bitmap. 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.

Figure 8.12 Insert new Bitmap into Resource

48

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

49

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:

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

50

To save the data

To reload the data

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

Its 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

51 3. Use the following way to store the string data in this class, and use three different function to initialize the 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

Initialize the CString variable data to be an empty string

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

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

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

Create a project by CData Class

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.

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

52 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.

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

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

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.

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. 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.

53

Macros Used for Serialization and Run-Time Information

Macro used Basic CObject functionality DECLARE_DYNAMIC

CRuntimeClass:: CArchive::operator>> CObject::IsKindOf CreateObject CArchive::operator<< No Yes No No Yes Yes No No No Yes

DECLARE_DYNCREATE Yes DECLARE_SERIAL Yes

Define that CData Class as the base class of MFC

Assert CData support serial base

To create a own serialize() function for CData class 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. Lets 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.
Construct serialization of own class

Store the string to variable data

Reload the string to variable data

54

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 deserializing program to identify and handle data created by earlier program versions. The class schema number must not be 1. 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.

The file is belong to the project name

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

THE DATABASE

55

FILE & 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 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 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 (Its made by Microsoft Access.)

Nowadays, people use Office2000 or OfficeXP. And maybe the version cant 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.

56

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).

Click this button to get the Database Options selection

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).

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.

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

A table is a record-set with columns & fields properties. Figure 10.2 Configuration of Database Option

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

57

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

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).

CDaoRecordView Class is the class which holding the data base. 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.
CStudentDBSet is the class which saving the data of the Access file and the default setting of the database of that file.

58

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

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

Static box Text box

Button

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.

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

59

Figure 10.6 Add message handler to OnButton1

Figure 10.7 Add variable to both IDC_EDIT1 & IDC_EDIT2

7. Lets 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.

60

Resize the frame window

Dictate the view size of the size of frame window

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.

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.

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

61
Load the data from the member variable of the database to the member variable of Text box Refresh the data Read the next record in the recordset the current Read the first record in the recordset (if any) the current

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. 9. After all the things are ready, lets 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 top

62

MULTITASKING
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 its possible. Now we start to program one virtual library task. Lets 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. Lets 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.

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

Figure 11.2 Select the table of the Database

63 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).

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

64

Figure 11.5 Password Dialog and Tab sequence

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.

Use the CBitmapButton class to create pushbutton controls labeled with bitmapped images instead of text.

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

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

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

VERIFY( booleanExpression ) Parameters booleanExpression Specifies an expression (including pointer values) that evaluates to nonzero or 0. Remarks In 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. 7. Find InitInstance( ) function which is in CLibraryApp Class. Lets add codes to the function, which can check if the user typed correct password or not (Here we set the password as gyx801213).

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

To assume quit out of program if still wrong password for the third typing

MessageBox( ) function here to set the form of display on the message box.

66 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.

Figure 11.7 Message box will display if the password is wrong

9. Seems checking password is ok. Now, lets 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

67

Figure 11.9 Add variable to each member of library item

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

68 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.

Reach the first record of the database

Reach the last record of the database

Reach the next record to the current record

Reach the previous record to the current record

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.

69

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

Figure 11.11 Section 2) User interface after typed correct password

70

This is the button, which can load the first record

This is the button, which can load the last record

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

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

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

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.

71

This button is supported by special style Figure 11.12 new button was added

Add new one dialog, give its 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.

72

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)

73
Figure 11.14 Creating new class for new dialog

Add one button to dialog, give its 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

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:

74

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.

75

void Navigate( LPCTSTR URL, DWORD dwFlags = 0, LPCTSTR lpszTargetFrameName = NULL, LPCTSTR lpszHeaders = NULL, LPVOID lpvPostData = NULL, DWORD dwPostDataLen = 0 ); Parameters URL 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. 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.


Load the webbrowser dialog by clicked the button

76

And dont 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

Vous aimerez peut-être aussi