Creating a window in VC++ using MFC

Abhisek
Posted by Abhisek under Others category on | Views : 6391
The following code will create a simple window displaying a message in MessageBox. It is developed using MFC in VC++.

#include "afxwin.h"
/*Crating window class inheratig the CFrameWnd class*/
Class MsgWin:public CFrameWnd
{
public:
MsgWin()
{
/*It will create the window with title*/
Create(0,"DotNetSpider");
}
/*Defining event handlers*/
int OnCreate(
{
/*On the creation of window the message will be displayed*/
MessageBox(0,"Welcome To DotNetSpider","DNS");
}
DECLARE_MESSAGE_MAP();/*Declaring event handlers*/
};
/*implementing message loop*/
BEGIN_MESSAGE_MAP(CFrameWnd,MsgWin);
ON_WM_CREATE();/*It is the event handler for OnCreate function*/
END_MESSAGE_MAP();
Class MsgApp:public CWinApp
{
public:
/*This method will initialize the window.*/
int InitInstance()
{
MsgWin mw;
mw = new MsgWin();
mw->ShowWindow(3);/*It will show the window in maximize mode.*/
m_pMainWnd = mw;
return 0;
}
};
MsgApp msg;/*Creating object of Application class*/


DESCRIPTION:-


For creating an application in MFC first we have to include the header file"afxwin.h"

Then we have to create a subclass of CFrameWnd and inside this subclass create a constructor. In side the constructor we have to implement the Create() function which is responsible for creating the window.

In the MsgWin subclass we are declaring the event handler function,i.e, OnCreate() function. It is called when the window is invoked. Inside this OnCreate() function we have to do all the event handling operations. In our program it is displaying of message.

As we are dealing with event handling by displaying message on the window creation we have to specify the message map after the MsgWin class.

BEGIN_MESSAGE_MAP(CFrameWnd,MsgWin);
ON_WM_CREATE();//It is the event handler for OnCreate function
END_MESSAGE_MAP();


The message loop is implemented using BEGIN_MESSAGE_MAP(CFrameWnd,MsgWin) and END_MESSAGE_MAP().

After the message map we have to define subclass of CWinApp class,i.e, MsgApp. Inside this class we have to define InitInstance() method which is responsible for instantiating window application. Inside it we are creating object of MsgWin class and assigning it to a global variable m_pMainWnd.

After the InitInstance() the MsgApp class ends. After that we have to create an object of MsgApp class which will invoke the InitInstance(). InitInstance() in turn will call the MsgWin() constructor and it then take care of events and the window will be created.

Comments or Responses

Login to post response