How do I process command line arguments?
If you want to parse the command line arguments to an MFC program, the
recommended way is to write a class to do it. Part of the reasoning here is that MFC
will automatically parse command line options like loading or printing a file. The code
you want to look for is in the InitInstance of your application class (it has the same .cpp
filename as your project). Here you will find:
CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE;
This is the code that handles the file open or print for you. The way it works, is that
MFC will call the ParseParam function of the CCommandInfo object for each word on
the command line, inside the ParseCommandLine function.
What you want to do is:
1. Create a new class, derived from CCommandLineInfo
2. In your new class, add any data members needed to reflect the command line
arguments.
3. Write your own ParseParam function inside this class. You'll want to make sure that
you still call the original CCommandLineInfo::ParseParam function, to handle the normal
parameters that you won't be handling.
So, your new class might look something like:
class CMyCmd : public CCommandLineInfo
{
public:
BOOL JustTerminate;
void ParseParam( LPCSTR lpszParam, BOOL bFlag, BOOL bLast )
{
if( bFlag && strcmp( lpszParam, "exit" )==0 ) // handle "/exit"
JustTerminate=1;
else
{
JustTerminate=0;
CCommandLineInfo::ParseParam( lpszParam, bFlag, bLast );
}
}
CMyCmd();
virtual ~CMyCmd();
};
4. In your InitInstance, make sure you use your new class instead of the
CComandLineInfo: // Parse command line for standard shell commands, DDE, file open // CCommandLineInfo cmdInfo; - Removed, so we use our new class CMyCmd cmdInfo; ParseCommandLine(cmdInfo); if( cmdInfo.JustTerminate ) // Use our custom data members return( FALSE );
5. After ParseCommandLine, add whatever code you need to work with the data
members that were set by ParseParam, as demonstrated by JustTerminate above.
--------------------------------
courtesy openroad.org