【问题标题】:Explorer passing the full executable path name in its command line argumentsExplorer 在其命令行参数中传递完整的可执行路径名
【发布时间】:2017-10-07 23:27:50
【问题描述】:

我创建了一个新的 Win32 控制台应用程序。它有这个主要入口点:

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

我正在解析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];

我想将第一个参数解析为productName,将第二个参数解析为installPath。但是,如果我从explorer 启动这个程序,它会将第一个参数设置为可执行文件的完整路径。

有没有办法处理这种行为? Windows 在什么情况下将参数传递给我的应用程序?如何忽略这些,并让我的应用程序接受如下命令行参数:

application.exe "Product Name" "C:\Program Files\Product Name"

【问题讨论】:

  • 第一个参数就是创建进程时使用的参数。如果你在控制台输入“calc.exe”,那么计算过程的第一个参数就是这个。
  • 必填OldNewThing link。还有this.

标签: windows winapi visual-c++ explorer


【解决方案1】:

看起来我只需要通过解析命名参数来改变我的方法:

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;
    }
}

【讨论】:

  • 是的,解析命名参数是通常的方法。但请注意Raymond Chen writes: CommandLineToArgvW 的第一个参数应该是 GetCommandLineW 返回的值
  • @zett42 你知道 Raymond 实际上在这个网站上非常活跃吗?他为我的一些问题发布了一些有用的答案。
  • @zett42 等等,你是 Raymond Chen 伪装的吗?
猜你喜欢
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多