Command Line Arguments Processing in Win32 Application

By Akbar

It’s common for Windows executable to get and process the additional parameters from the command line. This way you can pass any custom actions when launching an application i.e. open a particular file, print a file, control the application visibility state, etc.

If you are working on C/C++ console application, then you can easily get all the passed command line parameters as the main function arguments. Something like:

1
2
3
4
int main (int argc, char *argv[])
{
    return 0;
}

Here is a nice tutorial for arguments processing for console application:
http://www.crasseux.com/books/ctutorial/argc-and-argv.html

But if you are working in Win32 Windows application, your main entry point may look like this:

1
2
3
4
5
6
7
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
    // Windows initialization code goes here
}

As you can see that in this case, you get a third command line parameter which contains command line string. One straight forward option is to parse all the parameters in lpCmdLine parameter and then use these. This is a bit hassale, but does the job. The good news is that in WinMain function, you can also access two global variables named __argc and __argv which works exactly like argc and argv in console application i.e. __argc contains the count of the parameters passed, and __argv is string array containing those parameters string values.

There is one small catch though (I wasted half an hour to figure this out), and that’s if you are running in Unicode mode, then the __argv will always be NULL, and instead you should use the __wargv for the command lines parameter. Here is the conditional code I used for command line processing:

1
2
3
4
5
6
// Process any command line arguments
#if (UNICODE)
   bool bContinue = ProcessCommandLineArg (__argc, __wargv);
#else
    bool bContinue = ProcessCommandLineArg (__argc, __argv);
#endif

Spent few hours in figuring and making all this works, but in the end it was a fun learning and coding.

Tags: , ,