Vc++ Mfc Example - Custom Ccommandlineinfo to Parse Command Line Parameters

Updated on August 20, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.

1. Introduction

We know that functions will sometimes take parameters and process it. Similarly, executable applications also take parameters and switches and it behaves based on the parameters passed to it. In this article, we will see how do we pass command line parameters to an MFC Dialog based applications. The approach is same for other applications like single document and multi-document applications.

2. Creating a dialog based application

First, we will create a dialog-based application and name it as CommandLineDlg. That is the name we had chosen but we are not restricting one to keep the same name.

Creating Dialog Based MFC Application
Creating Dialog Based MFC Application | Source

Once the application is created, using the class view add a class to the solution. We are naming the class as CCommandParse. Make this class derived from CCommandLineInfo. This class declaration is shown below:

class CCommandParse : public CCommandLineInfo

Creating the dialog based application is shown in the below video (No Audio):

Creating MFC Dialog Based Application (No Audio)

3. The CCommandLineInfo Derived class

We have two MFC string Arrays declared in this class. One will hold command line data and another one will hold command line switches. Switches will tell how the application should behave based on the information passed for processing. The Get functions will receive reference parameters and copies the String Array values from the class’s member variable.

We override the ParseParam function of the base class CCommandLineInfo. Because of this, we will get the opportunity to process every param passed from the command line.

Below is the Full Class definition:

class CCommandParse : public CCommandLineInfo
	virtual ~CCommandParse(void);

	//Sample 03: Get functions for 
	//params and switches
	void GetParams(CStringArray& params);
	void GetSwitches(CStringArray& switches);

	//Sample 01: Private Members
	CStringArray m_params;
	CStringArray m_switches;

	//Sample 02: Override for Base class virtual
	void ParseParam(const TCHAR *pszParam, 
		BOOL bFlag, BOOL bLast);

The application calls ParseParam function for each command line parameters (data and switches) and this function will store the command line arguments to m_params or m_switches flags, which is the second parameter to the function. Below is the overridden function:

//Sample 04: Implement the Parse Param
void CCommandParse::ParseParam(
	const TCHAR *pszParam, 
	BOOL bFlag, BOOL bLast) 
	//Sample 04_1: Collect the parameters 
	//	and switches in a separate Array
	CString param_or_switch(pszParam);
	if (bFlag)

AS already told, the get functions will copy the command line arguments to the corresponding local member variables. The code is straightforward, and it is given below:

//Sample 05: Get Functions. 
void CCommandParse::GetParams(CStringArray& params) 
	int size = m_params.GetCount();
	for (int i = 0; i<size; i++)
		params.Add( m_params.GetAt(i)); 

void CCommandParse::GetSwitches(CStringArray& switches)
	int size = m_switches.GetCount();
	for (int i = 0; i<size; i++)
		switches.Add( m_switches.GetAt(i)); 

That all the changes we need for the CCommandParse class. Now, we will move to the Application Instance and make the changes. We will use the class which we defined just now.

4. Application Instance Parsing Params & Switches

We discussed about the custom parser in In the previous section. In the application class, we use it to parse the command-line arguments. We declare the GetCommandLinePasrser in the CWinApp class to receive the command line parameters. It takes references to the CStringArray instances to know the command-line parameters and parameter switches. Finally, we declare our custom parser written in the previous section as the member variable. The entire header file is shown below:

//Sample 06: Include the Custom Parse
#include "CommandParse.h"

// CCmdLineDlgApp:
// See CmdLineDlg.cpp for the implementation 
// of this class

class CCmdLineDlgApp : public CWinApp

// Overrides
	virtual BOOL InitInstance();
//Sample 07: Fill the passed in array structures.
	void GetCommandLinePasrser(
		CStringArray& params, 
		CStringArray& switches);

//Sample 08: To pasrse command line arguments
	CCommandParse m_cmdParse;

// Implementation


The Application calls the InitInstance function when it initializes the application and other resources. From InitInstance, we call the ParseCommandLine function and pass our custom parser to it as an argument.

Now, the MFC Framework is aware of the extended functionality offered by our Custom Parser. For each command line arguments passed, MFC will now call our overridden ParseParam member function CCommandParse. Note that we derived it from the class CCommandLineInfo. Below is the piece of code:

//Sample 09: Use the Custom Command Line Parser
if (ProcessShellCommand(m_cmdParse))
	return FALSE;

We will make a call to GetCommandLineParser from OnInitDialog handler of our dialog class. We have not written the call so for. First, let is write what the GetCommandLineParser of the dialog class do.

The GetCommandLineParser which is implemented in the Application class will copy the Parameters and switches to the internal members of our Custom Parser. This is done through the Getter Functions. Below is the code:

//Sample 10: The command Line parser will do the copy
void CCmdLineDlgApp::GetCommandLinePasrser(
	CStringArray& params, 
	CStringArray& switches) 

5. The Dialog class

In the dialog, we just have two list boxes. The dialog template edited by IDE is shown below:

The MFC Dialog Template for this Example
The MFC Dialog Template for this Example | Source

The dialog will get the application instance and passes two string arrays by reference to the member function exposed by it. The application instance will make a call to our custom command line parser to copy the parameters and switches to its member variables. Once the dialog knows the parameters and switches, it will display it in the corresponding list boxes.

All the above said stuff is done in the OnInitDialog member function of the dialog. Look at the below piece of code:

// TODO: Add extra initialization here 
//Sample 11: Add the Command Line Arguments 
//to List controls.
CStringArray params, switches;
 ((CCmdLineDlgApp *) 
	 params, switches);

 for (int i = 0; i<params.GetCount(); i++)

 for (int i = 0; i<switches.GetCount(); i++)

First, we make a call to the GetCommandLinePasrser of Application instance. The function will fill the passed CStringArray with parameters and switches. Once the dialog has the information, it displays those by adding it to the corresponding m_lst_params, m_lst_switches by iterating through the CStringArray instances.

After the call, our dialog has the command line information in the CStringArray instances. Using a for loops, we iterate through each CStringArray and display the content in the CListBox instances. The AddString function of the CListBox instance is used to display the Parameters and Switches.

6. Testing the Example

The attached sample can be tested in two different ways. The first way is going to the command prompt and executing the exe by passing the command line argument. The second way is passing the static parameters by setting the debug property of the project. The second method is useful when we want to debug the sample.

Below video shows passing the command line argument (with switches) from the command prompt.

Video: Testing the Example from Command Line Window (No Audio)

Below video shows perform debugging with command line arguments.

Video: Debugging the MFC Example with Command-Line Arguments (No Audio)

Source Code: DownLoad

© 2018 sirama


    0 of 8192 characters used
    Post Comment
    • profile image

      Andrew Truckle 

      3 months ago

      Hi. Thanks for the article. What about where you want to support both? Eg:

      Exe /flag=xyz


      In other words, extracts all command line flags and any file passed. See:


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)