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 , TCHAR** , TCHAR** )\
{\
return AfxWinMain(GetModuleHandle(NULL), NULL, GetCommandLine(), SW_SHOW);\
}
#endif