Programming with Microsoft Foundation Classes allows you to quickly create programs that are smaller than they would have been if you had created a full-fledged application using the Windows API, but still accomplish the same goals. It also allows you to separate the user interface of your program from the processing logic; this flexibility can come in very handy when you need to make modifications. Read on to learn the basics.
The support file for this article is availablehere.
In this article we’ll try to grasp the basics of Windows programming with MFC and how to use Visual Studio to write MFC applications. We’ll observe how programs behave the way they do from the perspective of a Visual C++ programmer. Most beginners to Visual C++ and MFC dive straight into the code that the Visual C++ AppWizard generates and then are clueless about what they see. This happens simply because it is not only hard to follow the generated MFC code, but also because most people don’t know what they get from the AppWizard. You need to have a fundamental understanding of MFC code structure; without that, you can’t write even a single line of code. Yes, that’s the truth!
Beginning with this article, we’ll cover in a simple but effective manner the fundamental concepts that animate any MFC program. Once you have covered the basics we’ll move on to more advanced topics that will surely make you a better Win32 MFC programmer. Here in the first article of this series we shall take a look at the basics, and you’ll see that the MFC and the App Wizard generated output does make your life as a programmer easier.
Visual Studio and Visual C++ together are much more than an IDE with a compiler. They are a full fledged application development environment for Windows that, when used correctly, lets you exercise the object oriented nature of C++ to create robust and scalable 32-bit Windows applications. To get the most out of this powerful environment, one must be well versed in the C++ programming language and a few other language features. To write code in MFC using C++, you need to know C++ well, conceptually at least.
You must also be familiar with the Microsoft Foundation Classes’ hierarchy. This class hierarchy does the fabulous job of encapsulating the user-interface-related APIs, and makes it conceptually easier to create Windows applications in an object-oriented way -- because now you think in terms of the application logic, rather than where to handle message and where to put the code! This hierarchy is well defined and exposes only the APIs which a specific version of Windows supports by magical use of #ifdefs, thus covering all versions of Windows. Hence the code you write using MFC is a lot more portable than old fashioned C/SDK code.
In this article we’re going to learn the essentials needed to begin with MFC programming, and then talk about event driven programming. You need to do that kind of programming anyway when you program for Windows. We will also write a plain MFC "Hello World" application just to see how well we understood the basics. In future articles we’ll also discuss the details of the MFC library so that you may appreciate the way MFC was written and used now.
So let’s talk about MFC. Why do we need MFC when we can create a full fledged Windows application using the Windows API? One reason is that, when doing the latter, you have to write a lot of boilerplate code. Another reason is that, once your code exceeds a few thousand lines, it is difficult if not impossible to manage.
The focus of developing applications is to fulfill client needs in most cases -- and you have to develop them without asking a lot of questions if the client is a non-techie guy. So both of you have a very different perspective about the same problem. Say you need to write a program that allows fast searching and viewing of very large image files on a number of disks that also lets the user edit them. "Where do I begin?" is the first question that comes to your mind.
Yes, it is quite a pain to isolate the application logic from the code that you use to make the application, but with MFC you have a solution. Using Object-oriented programming concepts that wrap up the Windows API in a well defined manner makes this possible. Imagine one class that wraps up the User Interface of your application and another that encapsulates the processing logic of your application. Now you can be sure what goes where. This is much simpler than the structured way. We shall shortly see this in action!
Another advantage is that if you have the User Interface separated from logic, you can play with the user interface elements without affecting the application logic as you do in Visual Basic. But you may have this capability with the raw power of C++ using the MFC classes that encapsulate almost all of the Windows API.
The MFC library that comes straight from Microsoft is essentially a C++ class library that wraps most of the raw Windows APIs to let us write programs in a better, managed way. The biggest benefit that we get by using this library is efficiency. It greatly reduces the amount of code that must be written to create a Windows program. It also allows us to design our solutions using object oriented methodologies and some other features that come bundled with C++ like RTTI.
As we discussed earlier, the code we write using MFC is portable. By this I mean that code written under Windows 3.1 can be moved to Windows NT or Windows 95 very easily, perhaps just with a recompile, but I don’t believe that it is done nowadays. Anyway, now we can surely conclude that MFC is a preferred way for developing Windows applications.
From a developer's point of view, it lets you capture the client's requirements and design an appropriate User Interface. If you find that it does not have a user interface (as in the case of a Windows service), you can still use MFC to write code or use the Dialog Editor to create the designed user interface and other controls (like menus, buttons, toolbars, and so forth) and customize their appearance. You then begin with writing code that responds to user interactions with these controls. For example, if the user clicks a menu item, you might want to load a large image file. In this way you essentially are writing event handlers that will form the logic of any application. Once the application behaves properly to all possible user requests, you may begin with testing and deployment.
From the above discussion you’ll find that the creation of a Windows program is a very simple process when we code using MFC.
When we use MFC we’re provided with placeholders, in the form of member functions of a class. These are invoked when an event occurs, and they are essentially the Event Handlers we’re just talking about.
Say you made a Dialog and created a button for it. How do you handle the clicking of this button? When using C/SDK you’ll have to find a place in the big switch statement under the WM_COMMAND switch to write the handler after checking the wParams and the lParams. But in the MFC world you can make an entry in the MessageMap and implement your handler as a function of the class in which the control (Button) is created.
If you’re not following everything, don’t worry. It will be clear in a little while.
Understanding MFC Code
The best way to see MFC in action is to understand the structure and style of a typical MFC program and see it running. I assume that you have a copy of Visual Studio or Visual Studio .NET to write MFC programs. The code listing below is a simple "hello world" program for MFC. If you’ve never seen any MFC code before it may seem cryptic to you, but you will find it very logical once you understand why is it that way.
//helloworld.cpp #include <afxwin.h>
// Declare the main application class derived from CWinApp class CHelloWorldApp : public CWinApp { public: virtual BOOL InitInstance(); };
// Create a Global instance of the application class CHelloWorldApp HelloWorldApp;
// Declare the main window class derived from CFrameWnd class CMainWindow : public CFrameWnd { CStatic* cs; public: // Constructor CMainWindow (); };
// The InitInstance function is called each // time the application first executes. BOOL CHelloWorldApp::InitInstance() { m_pMainWnd = new CMainWindow (); m_pMainWnd->ShowWindow(m_nCmdShow); m_pMainWnd->UpdateWindow(); return TRUE; }
// The constructor for the main window class CMainWindow:: CMainWindow () { // Create the window itself Create(NULL, "Hello World App", WS_OVERLAPPEDWINDOW, CRect(0,0,200,200));
// Create a static label cs = new CStatic(); cs->Create("Hello, World", WS_CHILD|WS_VISIBLE|SS_CENTER, CRect(50,50,150,75), this); }
This 15-20 line program does three things visibly:
It creates an "application object." Each MFC program needs this in order to handle the initialization details of MFC and Windows.
The application creates a single window on the screen to act as the main application window for the rest of the application session. If your application does not need user interface elements you may choose a different path, but you’ll do the processing in the constructor itself as shown above.
Finally, on the main window created in step 2, the application also creates a single static control (like a label in Visual Basic) containing the text "Hello, World."
In the next article we’ll explore these CWinApp and CFrameWnd in great detail -- details that you should know to become a good MFC programmer. But for now we must discuss how to compile and run this little application.
Just fire up VC++ and to create a new project; choose the File | New option in the File menu. Next, under the Projects tab, highlight Win32 Application. In the Location field type an appropriate path name or click the Browse button. Type in the word "HelloWorld" for the project name, and you will see that word echoed in the Location field as well. Click the OK button to get to the next window. Here, use the default selection "An empty project" and click "Finish" to see an info Dialog. Finally click "OK" to generate the workspace for the application code. You may copy and paste the above code or type it in yourself in a Cpp file that you create by selecting File | New and C/C++ source file on the Files tab. You can name the file whatever you want it to be.
Also, you must now tell the compiler to use the MFC library. If you forget this step the project will not compile and link properly, and error messages will pop up. Choose the Settings option in the Project menu. Next on the General tab, in the Microsoft Foundation Classes combo box, choose the third option: "Use MFC in a Shared DLL" as shown below and then close the dialog by clicking OK.
Figure 1: Telling the compiler to use MFC
Now, to run the application press F5 or Ctrl + F5 and you shall see a window like the one below.
Figure 2: Our First Application
Conclusion
In this tutorial you looked at what MFC is and what benefits it provides over C/SDK programming. We also successfully compiled and executed our first “Hello World” program. In next part we’ll get into understanding structure of MFC programs and how the user interface is separated from the application’s business logic.