.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh

Home >> Code Snippets >> Visual Studio >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Creating a window in VC++ using MFC

Posted By:Abhisek Panda       Posted Date: November 14, 2009    Points: 10    Category: Visual Studio    URL: http://www.dotnetspark.com  

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
/*It will create the window with title*/
/*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*/
ON_WM_CREATE();/*It is the event handler for OnCreate function*/
Class MsgApp:public CWinApp
/*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*/


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.
ON_WM_CREATE();//It is the event handler for OnCreate function

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.


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend