【发布时间】:2016-07-02 08:45:18
【问题描述】:
如下例所示,我尝试使用 Windows API 函数 CreateProcess 从 Windows 应用程序启动 Google 的 Chrome 浏览器。
我遇到的问题是我不知道 Chrome 应用程序(或程序路径中的任何其他应用程序)的路径。我怎样才能得到这个?
在下面的代码中,我注释了三个不同的示例。如果我启动“calc”,计算器会在 Windows/System32 路径中启动。如果我用它运行的应用程序的完整路径启动 Chrome。但是,如果我省略了路径并尝试启动“chrome”,则会收到错误 #2。
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain()
{
char* cmd = "calc"; // works... calc.exe is in windows/system32
// char* cmd = "chrome"; // doesn't work... how can I add the path if it's not known (e.g. windows installed on D:\)
// char* cmd = "c:/program files (x86)/google/chrome/application/chrome"; // works (even without extension .exe)
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Start the child process.
if (!CreateProcess(NULL, // No module name (use command line)
cmd, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
注意:如果我在 Windows 运行命令窗口中输入“chrome”(不带引号),Chrome 也会启动。我正在寻找的是相同的功能。但是,我的应用程序可以驻留在任何地方,并且不一定位于与 Chrome 相同的驱动器上。
【问题讨论】:
-
尝试
system("path")在您的应用程序运行时查看 PATH env.variable 的内容 -
当您输入
calc和当您输入chrome时,cmd 控制台会发生什么? -
我只是需要类似的东西,并通过在调用
CreateProcess之前调用PathFindOnPath找到完整路径来解决问题。但在这种特定情况下,对于想要启动 Chrome 浏览器,我认为 David Heffernan 的回答更好。我还要求您重新考虑明确启动 Chrome 的想法。如果用户喜欢不同的浏览器,比如 Firefox 或 Opera,该怎么办?只需使用 ShellExecuteEx 启动网页或 HTML 文档,允许用户的默认浏览器打开它,无论是什么。