C++: Parse command line arguments

First off, you should not use lpCmdLine which is given by the main function of your application.

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)

Be aware that lpCmdLine will only support ASCII characters. If you are creating a project which works with wide characters or multibyte strings, it will be horrible to deal with.

Not to mention you have to parse the string yourself, which means you also have to manage "strings within quotes" yourself as well.


Instead, you should be using CommandLineToArgvW() with GetCommandLine(). They will retrieve the arguments for your program, in the correct character set.

You can also use this anywhere, so there is no need to complicate your code and cause hell by passing lpCmdLine down the initialisation function chain.

The magic code:

// Parse command line arguments
LPTSTR *szArgList;
int argCount;

szArgList = CommandLineToArgvW(GetCommandLine(), &argCount);

if (szArgList) {
for (int i = 0; i < argCount; i++) {
//MessageBox(NULL, szArgList[i], L"Arglist contents", MB_OK);

if (!_tcscmp(L"--no-icon", szArgList[i])) {
bShowTrayIcon = false;


LocalFree() is required to unallocate the memory, which is set by CommandLineToArgvW().

Other than that, this is fairly straight forward.

[ Source ]

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog