Console app using MFC


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.

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