CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
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
















RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

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)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES