Q How can I parse the command line in an MFC app? My program has several command line options (such as -l, -x, -help). I see there's m_lpCmdLine that points to the command line, but do I have to parse it myself? It seems like there should be some way to make CCommandLineInfo do it, but I can't figure out how. Amy Brechstler
A You're on the right track. CCommandLineInfo is the class MFC uses to parse command-line options; the generic MFC app starts out with the following lines in InitInstance: CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
ParseCommandLine is a CWinApp member function that calls CCommandLineInfo to do the work. CCommandLineInfo has a virtual function, ParseParam, that parses a single parameter. void ParseParam(const TCHAR*
pszParam, // text param, sans / or -
BOOL bFlag, // TRUE if / or -
BOOL bLast); // TRUE if last
CWinApp::ParseCommandLine calls this function repeatedly for each command-line token. Unfortunately, ParseParam is hardcoded to recognize only certain common switches like -Embedding, -Automation, -pt (PrintTo), and so on (see Figure 5). For example, if ParseParam sees -p, it sets m_nShellCommand = CCommandLineInfo::FilePrintTo, and if it sees -Embedding or -Automation, MFC sets m_bRunEmbedded or m_bRunAutomated = TRUE. There can be other effects as well. In the last two cases, MFC sets m_bShowSplash = FALSE and calls AfxOleSetUserCtrl(FALSE) to kill the UI.
CCommandLineInfo is all very fine and dandy, but there's no easy provision to add your own options, other than to derive a new class and override ParseParam. That's a lot of typing for such a simple feature. What you really want is to call some function that will get the value of any options the user may have typed. CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
if (cmdinfo.GetOption("mumble")) {
// handle mumble option
}
Naturally, I wrote a new class, CCommandLineInfoEx, that does this (see Figure 6). It has two overloaded GetOption functions: one to get a boolean option as in the previous case, and another to get a string value: if (cmdinfo.GetOption("baz", m_sBaz)) {
// handle it
}
In this case, m_sBaz is a CString that's filled with whatever the user typed after -baz. For example, if the user typed "MyApp -baz mumble" then m_sBaz will be "mumble." CCommandLineInfoEx has far fewer lines of code than the MFC version with all its hardwired if/then/else statements, and it's totally generic. Why didn't the Redmondtonians give us this? It could be their heads got stuck in assembler mode that day; it happens to the best of us.
How does CCommandLineInfoEx work? Simple. It uses a string hash (CMapStringToString) to store all the options as it parses them. For a string option, it sets the value of the option to the typed string; for a nonstring option, it stores the value "TRUE". The CSplash class I created for the previous question uses CCommandLineInfoEx to parse the -nologo switch.
from: http://www.microsoft.com/msj/1099/C/c1099.aspx
没有评论:
发表评论