就像在下面的例子中,我試圖從使用Windows API函數CreateProcess的Windows應用程序啓動Google Googles Chrome瀏覽器。如果只知道其名稱,如何使用CreateProcess打開程序?
我遇到的問題是我不知道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的內容 – VolAnd
當您鍵入'calc'並鍵入'chrome'時,在cmd控制檯中會發生什麼? –
我只是需要類似的東西,通過在調用'CreateProcess'前調用'PathFindOnPath'來查找完整路徑來解決問題。但在這個特定的情況下,因爲想要推出Chrome瀏覽器,我認爲David Heffernan的回答更好。我還要求你重新考慮明確啓動Chrome的想法。如果用戶喜歡使用不同的瀏覽器,比如Firefox或Opera,該怎麼辦?只需使用ShellExecuteEx啓動網頁或HTML文檔,即可允許用戶的默認瀏覽器打開它。 –