MFC: Getting Started with Visual C++ III

Author: Ronald S. Holland
at
Total Application Works






To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


To contact us

© 2002 - 2017 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)

  • <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/GettingStarted_III.html">
    MFC: Getting Started with Visual C++ </a>
    </table>
    </body>
    </html>
    Download Source and see a screen shot


Introduction

This tutorial relies heavily on the lessons presented in

  1. Getting Started I
  2. Getting Started II
In this tutorial, we will add a menu to the example we created in Getting Started I. Remember that in the Getting Started I example, we used the following template:

  
// define our window based on the MFC frame window 
class MyApp : public CFrameWnd 
{
public:
   MyApp();          // MyApp constructor
   virtual ~MyApp(); // free-up resources
 
private:

};
  

Figure 1: Template


We will use this template and the concept of a resource file to build the application in this example. The requirements for this example follows in the next section.

Requirements

We will define the following requirements that should be applied to the application we will build in this tutorial.

  1. Create a class MyHelloWorld, which is derived from class CWinApp.
    • In class MyHelloWorld, instantiate class MyApp.
  2. Create a class MyApp, which is derived from class CFrameWnd.
  3. In class MyApp, create the following methods:
    1. MyApp() - constructor
    2. ~MyApp() - destructor
    3. OnHello() - event handler code that is called when the "Hello" button is clicked
    4. OnGoodBye() - event handler code that is called when the "GoodBye" button is clicked
    5. OnExit() - event handler code that is called when the "Clear" button is clicked
  4. Create a menu bar.
    • Use a resource file.
  5. On the event handlers, use the logic from Getting Started II
  6. Create a CStatic window in the MyApp constructor.
We will do a heavy cut-and-paste from the previous two tutorials to get the logic for this example. The only code that is new will be the code in the resource file that will used to build the menu bar.

MFC Application Template

In the Getting Started I tutorial, the header looked like:

  

// define our window based on the MFC frame window 
class MyApp : public CFrameWnd 
{
public:
   MyApp();          // MyApp constructor
   virtual ~MyApp(); // free-up resources
 
private:

};
 

Figure 2: MFC Application Template


We will modify that header file for this example to look like:

  
class MyApp : public CFrameWnd 
{
public:
   MyApp();          // MyApp constructor
   virtual ~MyApp(); // free-up resources
 
   afx_msg void OnHello();         // clicked the "Hello" button
   afx_msg void OnGoodBye();       // clicked the "GoodBye" button
   afx_msg void OnExit();       // clicked the "Clear" button

private:

   DECLARE_MESSAGE_MAP() 

};
  
Figure 3: MyApp Header File



We will modify the .cpp template to look like:

  

/*************************************************************
 * File: MyApp_III.cpp
 *************************************************************/

// include application framework windows class definitions:
#include 
#include "MyApp_III.h"
#include "MyApp_III_ids.h"


/****************************************
 * MyApp_III constructor initializes frame
 * 1- Create a Cframe window
 * 2- Instantiate the pHello pointer based on a CStatic control
 * 3- Create a CStatic child window
 ****************************************/
MyApp::MyApp()
{
   // Create Window with Title Bar
   Create( 0,                       // default CFrameWnd class
           "Hello World",           // window title
           WS_OVERLAPPEDWINDOW,     // full-featured window
            CRect( 100, 100,        // initial position and
                 600, 400 ),        // frame size
			NULL, 
            "MYAPP_III");           // Name of menu 

 
 
    pHello = new CStatic();      // create a static control

    pHello->Create(              // create Windows control
       "This is a slight modification of the Hello World. "
	   "\n \n"
	   "Hello world from Ron Holland" 	   , // text
       WS_CHILD | WS_VISIBLE | WS_BORDER  // window styles
       | SS_CENTER,                 // static object styles
       CRect( 50, 50, 450, 150 ),   // window coordinates
       this );                      // context
}

/****************************************
 * destructor frees resources
  ***************************************/
MyApp::~MyApp()   
{ 
   //delete pHello;          // only object owned by window 
}

afx_msg void MyApp::OnHello()
{
    MessageBox("Hello World",
		       "Hello World\n from\nRon Holland",
			   MB_ICONEXCLAMATION ); 
}

/****************************************
 *
 ***************************************/
afx_msg void MyApp::OnGoodBye()
{
    MessageBox("GoodBye World",
		       "GoodBye World from Ron Holland",
			   MB_ICONEXCLAMATION ); 

	OnExit() ;

}

/****************************************
 *
 ***************************************/
afx_msg void MyApp::OnExit()
{
   // Exit the app
   SendMessage( WM_CLOSE ) ;
}


BEGIN_MESSAGE_MAP( MyApp, CFrameWnd )
   ON_COMMAND( IDC_HELLO, OnHello )
   ON_COMMAND( IDC_GOODBYE, OnGoodBye )
   ON_COMMAND( IDC_EXIT, OnExit )
END_MESSAGE_MAP()
 
/*************************************************
 * Derive our application class CHelloApp based on 
 * CWinApp
 * 1- Overwrite InitInstance() method
 * 2- Make main frame window visiable
 * 3- Make the main frame window visiable
 *************************************************/
class MyHelloWorld : public CWinApp 
{
public:
   virtual BOOL InitInstance()   // override default method
   {
     m_pMainWnd = new MyApp();    // instantiate MyApp
     m_pMainWnd->ShowWindow( m_nCmdShow ) ;   
	 m_pMainWnd->UpdateWindow() ;

     return true;                          // report success
   }

} helloWorldApp;     


  
Figure 4: MyApp.cpp File


Where do we go from here? We need the means to describe the menu bar we will use in this example. To do this, we will define the resource file.

Resource File

In this section we will describe the use of resource script files (.rc). It is through the use of resource files that many applications define the graphical elements of their user interface: dialogs, menus, text strings (static/labels), bitmaps, toolbars, and other types of resources. In the Getting Started II, we used a resource file to declare labels/text and push buttons. In this example, our code will look like:

  
#include "afxres.h"
#include "myapp_III_ids.h"


MYAPP_III MENU
{
   POPUP "File"
   {
      MENUITEM "Exit", IDC_EXIT
   }

   POPUP "Hello"
   {
      MENUITEM "Say Hello", IDC_HELLO 
   }

   POPUP "Goodbye"
   {
      MENUITEM "Goodbye", IDC_GOODBYE 
   }

}
  
Figure 5: Resource Script File


where the MENU parameters, in Figure 5, are defined as

 
menuID MENU  [[optional-statements]]  { 
  - menuID   A number that identifies the menu. This value is 
              either a unique string or a unique 16-bit unsigned 
              integer value in the range of 1 to 65,535.       
              are the upper left-hand coordinates
In this example, the menuID is MYAPP_III
  - optional-statements  This parameter can be zero of more of the 
              following statements: 
              
 
where the POPUP parameters are defined as
         
POPUP text, [[optionlist]]    {       
               item-definitions      .      .      .  } 
  - text      A string that contains the name of the menu. This 
                string must be enclosed in double quotation marks ("). 
  - optionlist This parameter specifies redefined menu options 
                that specify the appearance of the menu item

 
where the MENUITEM parameters are defined as
  
MENUITEM text, result, [[optionlist]]  MENUITEM SEPARATOR
  - text      A string that indicates the name of the menu item. 
  - result    A number that specifies the result generated when 
                the user selects the menu item.
  - optionlist  This parameter specifies the appearance of the 
                  menu item. 
 

Figure 6: File


In Figure 6,

  • A MenuBar control contains top level Menu controls. In the case of the Notepad text editor, the following items represent menus that the user can select.
    File Edit Format View Help
  • A Menu control is made up of a hierarchy of menu items represented by MenuItem objects. For example,
    File
      New
      Open...
      Save
      Save As...
      ___________
      Page Setup
      Print
      ___________
      Exit
  • A MenuItem represents an individual item that is displayed within a Menu object. In the example above, New is a MenuItem.
  • The control used to display the Menu File is called a Popup. In Figure 5, we show how to define our menus that resembles the following figure when displayed.
    File Hello Goodbye
    Exit/td>
At this point, we have built our program in our Getting Started III tutorial.

Conclusion

From this tutorial, you should know

  1. How to build a basic hello world template.
  2. The definition of a resource file.
  3. How to define the graphical elements in the resource file.
  4. The definition of an event.
  5. The definition of an event handler.
  6. How associate the graphical elements with the event handlers.

Definitions

AFXWIN - This is a header for the Microsoft Foundation Classes C++ library. It must be included in all MFC applications.

BEGIN_MESSAGE_MAP - Use the BEGIN_MESSAGE_MAP macro to begin the definition of your message map. In the implementation (.CPP) file that defines the member functions for your class, start the message map with the BEGIN_MESSAGE_MAP macro, then add macro entries for each of your message-handler functions, and complete the message map with the END_MESSAGE_MAP macro.

CFrameWnd - The CFrameWnd class encapsulates the functionality of a Windows single document interface (SDI) frame window. A frame window is a window that frames an application.

CWinApp - The CWinApp class is the base class from which you derive a Windows application object. An application object provides member functions for initializing your application (and each instance of it) and for running the application.

CStatic - The CStatic class provides the functionality of a Windows static control. A static control is a control used to display text, to draw frames or lines separating other controls, or to display icons. A static control doesn't accept user input, but it can notify its parent of stylus taps if it's created with SS_NOTIFY style.

CDialog - The CDialog class encapsulates the functionality of a Windows dialog box.

dialog-based - applications that are derived from the CDialog class. The CDialog class encapsulates the functionality of a Windows dialog box.

DEFPUSHBUTTON - The DEFPUSHBUTTON resource-definition statement creates a default push-button control. The control is a small rectangle with a bold outline that represents the default response for the user. This means that if the user presses the enter button while this button has the focus, the program will executes this button's response. The given text is displayed inside the button. The control highlights the button in the usual way when the user clicks the mouse in it and sends a message to its parent window.

DIALOG - The DIALOG resource-definition statement specifies a window that an application can use to create dialog boxes. The statement defines the position and dimensions of the dialog box on the screen as well as the dialog box style.

DECLARE_MESSAGE_MAP() - in the .h file, this indcates that there will be event handlers. The event handlers are defined in the .cpp file.

event handler - an event occurs when a mouse is clicked, double clicked, a button is clicked, a key pressed, etc. Event handler is the code that is called to respond to the event, as a result of a graphical object being clicked.

GUI - graphical user interface is a program interface that uses a computer's graphics functionality to improve the program's ease to use for the end user.

inheritance - is the ability to create a class that derives properties from one or more base classes.

initinstance - Override InitInstance to initialize each new instance of your application running under Windows. Typically, you override InitInstance to construct your main window object and set the CWinThread::m_pMainWnd data member to point to that window.

message box - A message box is a special kind of modal dialog box that an application uses to display messages and prompt for simple input. A message box typically contains a text message and one or more predefined buttons.

MENU - The MENU resource-definition statement specifies the contents of a menu resource.

MENUITEM - The MENUITEM resource-definition statement creates a menu item.

m_pMainWnd - Holds a pointer to the application’s main window.

PUSHBUTTON - resource-definition statement creates a push-button control. The control is a round-cornered rectangle containing the given text. The text is centered in the control. The control sends a message to its parent whenever the user chooses the control.

POPUP - The POPUP resource-definition statement creates a menu item that can contain menu items and submenus.

resource files - contains graphical window layouts.

SS_CENTER - Designates a simple rectangle and displays the given text centered in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next centered line.

Template - is a unique class or pattern that can be used to build other software code.

WS_BORDER - Creates a window that has a border.

WS_CAPTION - Creates a window that has a title bar (implies the WS_BORDER style). Cannot be used with the WS_DLGFRAME style.

WS_CHILD - Creates a child window. Cannot be used with the WS_POPUP style.

WS_MAXIMIZEBOX - Creates a window that has a Maximize button.

WS_MINIMIZEBOX - Creates a window that has a Minimize button.

WS_MINIMIZE - Creates a window that is initially minimized. For use with the WS_OVERLAPPED style only.

WS_POPUP - Creates a pop-up window. Cannot be used with the WS_CHILD style.

WS_SYSMENU - Creates a window that has a Control-menu box in its title bar. Used only for windows with title bars.

WS_THICKFRAME - Creates a window with a thick frame that can be used to size the window.

WS_VISIBLE - Creates a window that is initially visible.




HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2017 All Rights Reserved Total Application Works

##################################################### #####################################################