Your First MFC Application
It's time to build your first MFC application. And what better place to start than with one that displays "Hello, MFC" in a window? Based on the classic "Hello, world" program immortalized in Brian Kernighan and Dennis Ritchie's The C Programming Language (1988, Prentice-Hall), this very minimal program, which I'll call Hello, demonstrates the fundamental principles involved in using MFC to write a Windows application. Among other things, you'll get a close-up look at MFC's CWinApp and CFrameWnd classes and see firsthand how classes are derived from them and plugged into the application. You'll also learn about the all-important CPaintDC class, which serves as the conduit through which text and graphics are drawn in a window in response to WM_PAINT .
Figure 1-3 lists the source code for Hello. Hello.h contains the declarations for two derived classes. Hello.cpp contains the implementations of those classes. Among C programmers, it's traditional to put class definitions in .h files and source code in .cpp files. We'll honor that tradition here and throughout the rest of this book. for large applications containing tens or perhaps hundreds of classes, it's also beneficial to put class declarations and implementations in separate source code files. that's overkill for the programs In The First Few Chapters of this Book, But Later ON, WHEN WEB WORKING WITH CLASS ITS OWN .H AND .CPP FILES ON The cd in the back of the book, in the folder Named Chap01, You'll Find A Folder with Copies of Hello.h and hello.cpp as well as a folder containing a copy of the compiled executable (Hello.exe) .figure 1-3. The Hello Application.
Hello.hclass CMYAPP: Public CWINAPP
{
PUBLIC:
Virtual Bool InitInstance ();
}
Class CMainWindow: Public CFrameWnd
{
PUBLIC:
CMAINWINDOW ();
protected:
AFX_MSG void onpaint ();
Declare_message_map ()
}
Hello.cpp # include
#include "hello.h"
CMYAPP myApp;
/
// CMYAPP Member Functions
Bool CmyApp :: InitInstance ()
{
m_pmainwnd = new cmainwindow;
m_pmainwnd-> showwindow (m_ncmdshow);
m_pmainwnd-> UpdateWindow ();
Return True;
}
/
// CMainWindow Message Map and Member Functions
Begin_MESSAGE_MAP (CMainWindow, CFrameWnd)
ON_WM_PAINT ()
END_MESSAGE_MAP ()
CMAINWINDOW :: CMAINWINDOW ()
{
Create (NULL, _T ("The Hello Application");
}
Void cmainwindow :: onpaint ()
{
CPAINTDC DC (this);
CRECT RECT;
GetClientRect (& Re); DC.Drawtext (_T ("Hello, MFC"), -1, & review,
DT_SINGLINE | DT_CENTER | DT_VCENTER);
}
. Figure 1-4 shows the output from Hello When you run the application, notice that the window is entirely functional; you can move it, resize it, minimize it, maximize it, and close it And when the window is resized, ". Hello, MFC "Is RedRawn in the center of the window.
. Most of Hello's functionality comes from Windows Windows, for example, draws the exterior, or nonclient area, of the window:. The title bar, the buttons on the title bar, and the window's border It's your responsibility to create the window and process .
Figure 1-4. The hello window.
The Application Object
The heart of an MFC application is an application object based on the CWinApp class. CWinApp provides the message loop that retrieves messages and dispatches them to the application's window. It also includes key virtual functions that can be overridden to customize the application's behavior. CWinApp and other MFC classes are brought into your application when you include the header file afxwin.h. An MFC application can have one-and only one-application object, and that object must be declared with global scope so that it will be instantiated in memory at The Very OutSet of The Program.
Hello's Application Class Is Named CmyApp. It is instantiated in Hello.cpp with the statement
CMYAPP myApp;
CMYAPP's Class Declaration Appears in Hello.h:
Class CMYAPP: Public CWINAPP
{
PUBLIC:
Virtual Bool InitInstance ();
}
CMyApp declares no data members and overrides just one function inherited from CWinApp. InitInstance is called early in the application's lifetime, right after the application starts running but before the window is created. In fact, unless InitInstance creates a window, the application does not Have a window. That's why even a minimal mfc Application Must Derive a class from cwinapp and override cwinapp :: InitInstance.The InitInstance function
CWINAPP :: InitInstance Is A Virtual Function Whose Default IMPLEMENT CONTAINS JUST One Statement:
Return True;
The purpose of InitInstance is to provide the application with the opportunity to initialize itself. The value returned by InitInstance determines what the framework does next. Returning FALSE from InitInstance shuts down the application. If initialization goes as planned, InitInstance should return TRUE in order to allow the program to proceed. InitInstance is the perfect place to perform initializations that need to be done each time the program starts. At the very least, this means creating the window that will represent the application on the screen.
CMYAP's Implementation of InitInstance, Which Appears in Hello.cpp, Creates The Hello Window by Instantiating Hello's CMainWindow Class. The Statement
m_pmainwnd = new cmainwindow;
constructs a CMainWindow object and copies its address to the application object's m_pMainWnd data member. After the window is created, InitInstance displays it-remember, a window is not initially visible unless it is created with a WS_VISIBLE attribute-by calling ShowWindow and UpdateWindow through the CMAINWINDOW POINTER:
m_pmainwnd-> showwindow (m_ncmdshow);
m_pmainwnd-> UpdateWindow ();
ShowWindow and UpdateWindow are CWnd member functions common to all window objects, including objects of the CFrameWnd class from which CMainWindow is derived. These functions are little more than wrappers around the API functions of the same name. To call a regular Windows API function from an MFC Program
This notation will ensure that the API function is called even if the object that makes the call has a member function with the same name. In the remainder of this book, Windows API functions will be prefaced with :: to distinguish them from MFC member functions .
ShowWindow accepts just one parameter:. An integer that specifies whether the window should initially be shown minimized, maximized, or neither minimized nor maximized In accordance with Windows programming protocol, Hello passes ShowWindow the value stored in the application object's m_nCmdShow variable, which holds the nCmdShow parameter passed to WinMain. The m_nCmdShow value is usually SW_SHOWNORMAL, indicating that the window should be displayed in its normal unmaximized and unminimized state. However, depending on how the user starts an application, Windows will occasionally slip in a value such as SW_SHOWMAXIMIZED or SW_SHOWMINIMIZED. UNSHOWMINIMIFIC REASON for It to do Otherwise, InitInstance Should Always Pass The M_ncmdshow Variable Instead of a Hardcoded SW_ Value To ShowWindow.
UpdateWindow Completes The Job That ShowWindow Started by Forcing An Immediate Repaint. Its Work Done, InitInstance Returns True To Allow The Application To Proceed.
Other CWINAPP OVERRIDABLES
InitInstance is just one of several virtual CWinApp member functions you can override to customize the behavior of the application object. Look up the CWinApp overridables in your MFC documentation and you'll see a list of more than a dozen others with names such as WinHelp and ProcessWndProcException. Many of these functions are seldom overridden, but they're handy to have around nonetheless. For example, you can use ExitInstance to clean up when an application terminates. If you use InitInstance to allocate memory or other resources, ExitInstance is the perfect place to free those resources. The default implementation of ExitInstance performs some routine cleanup chores required by the framework, so you should be sure to call the base class version if you've overridden ExitInstance. Ultimately, the value returned by ExitInstance is the exit code Returned by Winmain.other Interesting CWINAPP Overridables include OnIdle, Run, And PretranslateMessage. Onidle is Handy for Performing Back ground processing chores such as garbage collection. Because OnIdle is called when an application is "idle" -that is, when there are no messages waiting to be processed-it provides an excellent mechanism for performing low-priority background tasks without spawning a separate thread of execution. OnIdle is discussed at length in Chapter 14. you can override Run to customize the message loop, replacing it with a message loop of your own. If you just want to perform some specialized preprocessing on certain messages before they are dispatched, you Can Override PretranslateMessage and Save Yourself The Trouble of Writing a Whole New Message Loop.
How mfc buy the application object
To someone who has never seen an MFC application's source code, one of the more remarkable aspects of Hello will be that it contains no executable code outside of the classes it defines It has no main or WinMain function, for example;. The only statement in the entire program that has global scope is the statement that instantiates the application object. So what actually starts the program running, and when does the application object come into the picture? The best way to understand what goes on under the hood is to look at . the framework's source code One of the source code files provided with MFC-winmain.cpp-contains an AfxWinMain function that is MFC's equivalent of WinMain (that's right:. when you purchase Visual C , you get the source code for MFC, too. ) AfxWinMain makes extensive use of the application object, which is why the application object must be declared globally. Global variables and objects are created before any code is executed, and the application object must be ex Tant In Memory Before Afxwinmain Starts.
Right after starting, AfxWinMain calls a function named AfxWinInit to initialize the framework and copy hInstance, nCmdShow, and other AfxWinMain function parameters to data members of the application object. Then it calls InitApplication and InitInstance. In 16-bit versions of MFC, InitApplication is called only if the hPrevInstance parameter passed to AfxWinMain is NULL, indicating that this is the only instance of the application currently running. In the Win32 environment, hPrevInstance is always NULL, so the framework does not bother to check it. A 32-bit application could just as easily use InitApplication to initialize itself as InitInstance, but InitApplication is provided for compatibility with previous versions of MFC and should not be used in 32-bit Windows applications. If AfxWinInit, InitApplication, or InitInstance returns 0, AfxWinMain terminates instead of Procepting further and the application is shut down.only if all of the aforementioned functions return nonzero value S Does Afxwinmain Perform The next critical step. The statement
Pthread-> run ();
calls the application object's Run function, which executes the message loop and begins pumping messages to the application's window. The message loop repeats until a WM_QUIT message is retrieved from the message queue, at which point Run breaks out of the loop, calls ExitInstance, and Returns to Afxwinmain. After doing Some Last-Minute Cleaning Up, AfxwinMain Executes a return to end the application.