0
votes

I created a new Win32 Console Application. It has this main entry point:

int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)

I am parsing parameters in lpCmdLine:

LPWSTR *szArglist;
int nArgs;
szArglist = CommandLineToArgvW(lpCmdLine, &nArgs);
if (nArgs >= 1 && wcslen(szArglist[0]) > 0)
    productName = szArglist[0];
if (nArgs >= 2 && wcslen(szArglist[1]) > 0 && PathFileExists(szArglist[1]))
    installPath = szArglist[1];

I want to parse the first parameter as productName and the second parameter as installPath. However, if I launch this program from explorer, it sets the first parameter as the full path to the executable.

Is there any way to handle this behavior? Under what situations does Windows pass arguments to my application? How can I ignore these, and have my application accept command line arguments as follows:

application.exe "Product Name" "C:\Program Files\Product Name"
1
The 1st parameter is just what was used when creating the process. If you type "calc.exe" in console, the 1st parameter of the calc process will be just that. - zett42
Obligatory OldNewThing link. And this. - zett42

1 Answers

1
votes

Looks like I just need to change my approach by parsing for named arguments:

LPWSTR *szArglist;
int nArgs;
szArglist = CommandLineToArgvW(lpCmdLine, &nArgs);
BOOL skipNext = false;
for (int i = 0; i < nArgs; i++) {
    if (skipNext) {
        skipNext = false;
        continue;
    }
    if (wcscmp(szArglist[i], L"/path") == 0 && i + 1 < nArgs && wcslen(szArglist[i + 1]) > 0 && PathFileExists(szArglist[i + 1])) {
        installPath = szArglist[i + 1];
        skipNext = true;
    }
    if (wcscmp(szArglist[i], L"/product") == 0 && i + 1 < nArgs && wcslen(szArglist[i + 1]) > 0) {
        productName = szArglist[i + 1];
        skipNext = true;
    }
}