Author : Prof Devi
Page : 1 Next >>
The Microsoft Foundation Class Library(MFC Library) is a C++ class library released with Microsoft Visual C++ to support application development on Microsoft Windows. Although MFC is most often used in GUI applications, it can be used to develop any type of application. The MFC Library consists of numerous classes that are thin wrappers for high level Application Programming Interfaces(APIs) such as WinSock and ODBC. All the Win32 Kernel, GDI, and User Objects have associated MFC classes. The MFC library is called a vertical library, as it uses class inheritance heavily with very little C++ templates. When the MFC 1.0 library was first released in 1992(with Microsoft C++ 7.0), back when Microsoft was touting their 16 bit Windows 3.1, the class library did not have templates. Today's current version MFC 4.2 does contain template based classes. If you do use MFC, your applications will not have to be modified much when moving between different platforms. For instance, many MFC applications written for Windows 3.1(Win16) were simply recompiled for Win32 platforms such Windows 95 and NT. When Win64 comes out, you do not have to rewrite your whole MFC again. You will just
The MFC library can either be linked statically or dynamically into your application. If it is linked dynamically, then your application is very small. At runtime, your application uses MFC classes through the MFC dynamic link libraries. These DLLs are usually found in the SYSTEM subdirectory. If many applications are MFC based and use MFC dynamically, you can save a tremendous amount of hard drive space. Also, if the library is already loaded when one application is running, then the next application that uses MFC dynamically loads faster.
The following chapters are meant to introduce laymen to MFC programming. Although MFC seems simple, it does require one to have a background in Win32 and C++ programming. If you do not have this background, these notes will not help. Due to the high learning curve for knowing Win32 and C++, very few programmers know how to be proficient in MFC. It does take a long time of study. If you just want to write simple GUI applications, then study VB instead.
There are many Visual Basic Programmers who develop for windows. Every day, more are born via simple 8 week VB courses. There is not much expertise required for clicking and dragging controls on to a Visual Basic form. This can be seen by the number of varied backgrounds of VB programmers in the market place. One certainly does not require a Computer Science Degree for writing a simple VB program. Visual Basic offers only access to those facilities of windows that are used in most applications. For instance, a scroll bar in Visual Basic is simple enough. But, a scroll bar that changes its color is not to be found in Visual Basic. If one needs to have such a control, you will need to create an ActiveX control with with either raw C++ with Win32 calls, Active Template Library(ATL), or using MFC. For this problem, because of its simplicity, ATL would be the fastest most reliable method of development. After the control is built, it can then be used by a VB programmer on his forms. Many Window programmers who used straight Win32 API to develop window applications have been pushed aside by VB programmers. Although Microsoft does support Visual Basic for developing complicated data structures, Visual Basic is meant for Simple GUI development.
If MFC was used to develop a simple windows application with standard UI elements, it would probable take hours to develop. In Visual Basic, it would take only a couple of minutes. MFC does not sparkle here. It sparkles when one is confronted with a complex application with a lot of Win32 programming. For instance, you need to write an application with Multi threading, sockets, and database interactions. You could write your program in straight C using Win32, WinSock and ODBC. But this type of code tends to very error prone. (In a convoluted way, you can declare and call win32 api functions in Visual Basic. Socket support can be achieved through special controls. Databases can be reached using ADO. But, these VB apps tend not to be unmaintainable). MFC would be the best bet for this type of application.
All the MFC Classes have a capital C prefix. For instance, CString, CFile, CSocket, CMutex are classes found in the MFC library. The standard MFC classes are declared in the header file afxwin.h. If you do not use the App Wizard, you will have to turn on the MFC by modifying the project settings in Visual C++ to either static or dynamic MFC linking. All the code in the following pages use Visual C++ 6.0. As we will be using MFC in a console application, we will need to manually initialize the MFC run-time support with a call to the function AfxWinInit. If you do not initialize the MFC run time, your code may terminate unexpectedly. The beginning chapters teach MFC from non-GUI perspective.
Declaration: BOOL AFXAPI AfxWinInit( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
Info: Funcion initalizes the MFC run time environment. The return value is TRUE on success.
The Box #1 program demonstrates a simple main which just initializes the MFC runtime environment.
// BOX #1: Initialize the MFC Runtime Environment.
#include <afxwin.h>
int main(void)
{
if(AfxWinInit(GetModuleHandle(NULL),NULL,GetCommandLine(),0)==FALSE)
{ cout<<"Unable to initialize MFC"<<endl; return 1; }
/*
Use MFC Classes Here !!!
*/
return 0;
}
The CString class is a member of the MFC library. The class offers an easy to manipulate strings without resorting to using the C string library. The CString class has several overloaded operators to access and modify strings. CString instances can either hold standard C strings or Unicode strings. A CString object can be used any where a const char * or a const wchar_t * types are used. There is even a specialized Format method works much like the sprintf function.
The following Box #1 program demonstrates usage of a CString object. The _T( ) is a C macro that will either translate into a blank for normal single byte C strings or to an L for Unicode strings. Notice how easily standard and Unicode strings can be intermixed together.
// Box #1: CString Class
#include <afxwin.h>
#include <stdio.h>
int main(void)
{
if(AfxWinInit(::GetModuleHandle(NULL),NULL,::GetCommandLine(),0)==FALSE)
{ perror("Unable to initialize string\n"); return 1; }
CString str;
str="Hello"; // Assign a standard C string into str
str=str + _T(" World"); // Append "World" to str
str=str + " and " + str + L" Again"; // mix standard and Unicode strings
printf("Output:%s\n",(const char *)str); // Cast to get correct output
return 0;
}
The next Box #2 program demonstrates the Format method.
// Box #2: Format Method
#include <afxwin.h>
#include <stdio.h>
int main(void)
{
if(AfxWinInit(::GetModuleHandle(NULL),NULL,::GetCommandLine(),0)==FALSE)
{ AfxMessageBox(_T("Unable to initialize Library")); return 1; }
CString str;
str.Format(_T("Sum of %d and %d is %d"),10,20,30);
printf("Output:%s\n",(const char *)str);
return 0;
}
The next Box #3 program demonstrates several functions often used on string manipulations.
// Box #3: Some more String operations
#include <afxwin.h>
#include <stdio.h>
int main(void)
{
if(AfxWinInit(::GetModuleHandle(NULL),NULL,::GetCommandLine(),0)==FALSE)
{ AfxMessageBox(_T("Unable to initialize Library")); return 1; }
CString str;
str="\t\t\r\n Hello World \t\t\t\t";
str.TrimLeft(); // Remove all non printable characters on left side
str.TrimRight(); // Remove all non printable character on Right side
str.MakeUpper(); // Convert the string to upper case (lower case is MakeLower())
str.MakeReverse(); // Reverse the string
int len=str.GetLength(); // Get Length of string.
printf(" <<< %s >>> Length=%d\n",(const char *)str,len);
str="The city of New York is very old";
str.Replace("New York","Boston"); // Replace all occurrences of "New York" with "Boston"
printf("Info: %s\n",(const char *)str);
CString word1="first"; CString word2="second";
if(word1.Compare(word2)<0) // Compare strings togather
{ printf("<%s> comes first in the dictionary\n",(const char *)word1); }
else
{ printf("<%s> comes second in the dictionary\n",(const char *)word2); }
str="Hello World";
CString left=str.Left(5); // Get the Left 5 characters (ie "Hello")
CString right=str.Right(5); //Get the Right 5 Characters(ie "World" )
CString mid=str.Mid(5,1); // Get the mid for position 5 of length 1 (ie " ")
str=left+mid+right; // "Hello World"
printf("%s\n",(const char *)str);
return 0;
}
The CString object can even load string resources from the executable using the method LoadString. The Box #4 program has a string resource identified by the integer constant ID_MYSTRING. The value of ID_MYSTRING is defined in the header file resource.h.
// Box #4 : LoadString Method
#include <afxwin.h>
#include <stdio.h>
#include "resource.h"
int main(void)
{
if(AfxWinInit(::GetModuleHandle(NULL),NULL,::GetCommandLine(),0)==FALSE)
{ AfxMessageBox(_T("Unable to initialize Library")); return 1; }
CString str;
str.LoadString(ID_MYSTRING); // Load string identified by integer ID_MYSTRING
printf("String: %s\n",(const char *)str);
return 0;
}
The MFC class library has an extensive arsenal of preprocessing macros and runtime classes for tracking and eliminating run time errors. In large applications, memory leaks are
Page : 1 Next >>