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



Comments

  • How to add CAsyncSocket supporting in your project?

    Posted by Legacy on 04/08/2003 12:00am

    Originally posted by: happycoding

    I include CAsyncSocket class in your project,compiles OK.
    But OnReceive() never been called!
    Any suggestions are appreciated!

    Best Regards,
    Xie Bo
    Email:happpycoding@msn.com

    Reply
  • Download demo Project here

    Posted by Legacy on 04/11/2000 12:00am

    Originally posted by: cdf

    Download demo Project here:
    http://members.tripod.com/~cdf2000/MyConsole.zip

    Thanks.

    Reply
  • Can't compile this no matter what !

    Posted by Legacy on 01/18/2000 12:00am

    Originally posted by: Hans Wedemeyer

    Tried all the suggestions, but I get gobs of errors...
    Wish the author would post a project for VC5 or 6 and or
    the command line switches..

    Reply
  • Hiding the console window

    Posted by Legacy on 07/02/1999 12:00am

    Originally posted by: David Orr

    I would greatly appreciate any suggestions on how I might be able to hide the console window. If have tried defining AfxWinMain with SW_HIDE and even setting m_nCmdShow to SH_HIDE, but the damn window still appears.

    Thanks in advance

    Reply
  • This choked my compiler (internal error)

    Posted by Legacy on 04/20/1999 12:00am

    Originally posted by: Chris A

    I put this into a h file and it killed VC6 (it said pls contact MS, like they care!), what can I be doing wrong.

    Reply
  • Please help...

    Posted by Legacy on 01/21/1999 12:00am

    Originally posted by: Jason Hattingh

    I can't compile the (nearly) useful article becuase I am getting unresolved external errors referencing _beginthreadex, etc.

    Anything I'm missing?

    Thanks

    Reply
  • Visual C++ 6 appwizard prepare Console Application that support MFC

    Posted by Legacy on 12/25/1998 12:00am

    Originally posted by: kwangd devman

    VC6 appwizard support create console application with support MFC Class
    it make console application feel cool , and make me can call DoModal() from command-line application :) cool!!

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • A modern mobile IT strategy is no longer an option, it is an absolute business necessity. Today's most productive employees are not tied to a desk, an office, or a location. They are mobile. And your company's IT strategy has to be ready to support them with easy, reliable, 24/7 access to the business information they need, from anywhere in the world, across a broad range of communication devices. Here's how some of the nation's most progressive corporations are meeting the many needs of their mobile workers …

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds