CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

follow us on Twitter

Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















Home >> Visual C++ / C++ >> Miscellaneous >> Miscellaneous >> Console Apps


Console app using MFC
Rating: none

Troels Knakkergaard (view profile)
February 3, 1999


This article was contributed by Troels Knakkergaard.

Why not use the familiar init/run/exit "code-sandwich" in Win32 console applications too? And why not use good old CWinApp for this? It is perfectly possible, only it doesn't seem to ever get mentioned.
All it takes is a call to MFC's AfxWinMain in main(). The DECLARE_CONSOLEAPP in the code example below implements main() for you, which leaves you only to implement your own CWinApp-derived application class.


(continued)




As an added benefit, using MFC and CWinApp enables you to use CCommandLineInfo just like in any other MFC app. You almost always want to parse the command line for parameters in a command line application, so CCommandLineInfo is extremely useful here. CCommandLineInfo is easy to derive from and apply - and anyway, deriving from and using a (popular) framework always beats rolling your own code, however trivial, in respect of readability/maintainability etc.

Notes:
- CWinApp doesn't mind you not having a main window (m_pMainWnd == NULL).
- The code compiles with Visual C++ 4.2 or later, with _CONSOLE and _AFXDLL.
- The code below will actually compile 'as is'.

Program example:

#include <afxwin.h>

#if !defined(_CONSOLE)
   #error Make it a console application project
#endif

/////////////////////////////////////////////////////////////////////////////
// DECLARE_CONSOLEAPP - enables MFC-like console app

#ifdef _CONSOLE
   #define DECLARE_CONSOLEAPP \
      extern int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPTSTR lpCmdLine, int nCmdShow);\
      extern "C" int _tmain( int /*argc*/, TCHAR** /*argv*/, TCHAR** /*envp*/)\
      {\
         return AfxWinMain(GetModuleHandle(NULL), NULL, GetCommandLine(), SW_SHOW);\
      }
      // remember to instantiate app class
#endif // _CONSOLE

/////////////////////////////////////////////////////////////////////////////
// Interface of CMyCommandLineInfo

class CMyCommandLineInfo : public CCommandLineInfo
{
// Attributes
public:
   BOOL    m_bHelp;        // /H /? /HELP
   CString m_strParameter;
   BOOL    m_bSuccess;     // all switches ok

// Construction
public:
   CMyCommandLineInfo(void);

// Overrides
public:
   virtual void ParseParam( LPCTSTR lpszParam, BOOL bFlag, BOOL bLast );
};

/////////////////////////////////////////////////////////////////////////////
// Implementation of CMyCommandLineInfo

CMyCommandLineInfo::CMyCommandLineInfo(void) : CCommandLineInfo(), m_bHelp(FALSE), m_bSuccess(TRUE)
{
}

void CMyCommandLineInfo::ParseParam(LPCTSTR lpszParam, BOOL bSwitch, BOOL /*bLast*/)
{
   if (bSwitch)
   {
      if (0 == lstrcmpi(_T("help"), lpszParam))
      {
         m_bHelp = TRUE;
      }
      else
      {
         // the for loop enables 'compound' switches like "/XYZ"
         BOOL bContinue = TRUE;
         for(int i = 0; (i < lstrlen(lpszParam)) && m_bSuccess && bContinue; i++)
         {
            switch(lpszParam[i])
            {
               case _T('?'):
               case _T('h'):
               case _T('H'):
                  m_bHelp = TRUE;
                  break;
               default:
                  m_bSuccess = bContinue = FALSE;
                  break;
            }
         }
      }
   }
   else
   {
      m_strParameter = lpszParam;
   }
}

/////////////////////////////////////////////////////////////////////////////
// Interface of some application class

class CMyApp : public CWinApp
{
// Construction
public:
   CMyApp(void);

// Attributes
public:
   CMyCommandLineInfo m_cmdInfo;

// Overrides
   // ClassWizard generated virtual function overrides
   //{{AFX_VIRTUAL(CMyApp)
   public:
   virtual BOOL InitInstance();
   virtual int Run();
   virtual int ExitInstance();
   //}}AFX_VIRTUAL

// Implementation
public:
   virtual ~CMyApp(void);
};

/////////////////////////////////////////////////////////////////////////////
// Instatiate the application class

DECLARE_CONSOLEAPP

CMyApp theApp;

/////////////////////////////////////////////////////////////////////////////
// Implementation of the application class

CMyApp::CMyApp(void) : CWinApp()
{
}

CMyApp::~CMyApp(void)
{
}

BOOL CMyApp::InitInstance()
{
   if (!CWinApp::InitInstance())
   {
      return FALSE;
   }

   _tprintf(_T("Init\n"));

   SetRegistryKey(_T("Codeguru samples"));

   ParseCommandLine(m_cmdInfo);

   return TRUE;
}

int CMyApp::Run()
{
   if (!m_cmdInfo.m_bSuccess)
   {
      _tprintf(_T("Bad command line\n"));
   }
   if (m_cmdInfo.m_bHelp || (!m_cmdInfo.m_bSuccess))
   {
      _tprintf(_T("usage: [ \"string\" /?]\n"));
   }
   else
   {
      m_cmdInfo.m_strParameter;
      _tprintf(_T("Run\n"));
      // ...
   }
   return CWinApp::Run(); // calls ExitInstance and exits right away when m_pMainWnd=NULL
}

int CMyApp::ExitInstance()
{
   _tprintf(_T("Done\n"));
   return CWinApp::ExitInstance();
}

Date Last Updated: February 3, 1999

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
How to add CAsyncSocket supporting in your project? - Legacy CodeGuru (04/08/2003)
Download demo Project here - Legacy CodeGuru (04/11/2000)
Console App with COM to read Excel - Legacy CodeGuru (02/19/2000)
Can't compile this no matter what ! - Legacy CodeGuru (01/18/2000)
redirecting from console to window - Legacy CodeGuru (01/03/2000)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)