如果只知道其名称,如何使用CreateProcess打开程序?

Shy*_*ani 0 c c++ windows winapi

如下例所示,我尝试使用Windows API函数CreateProcess从Windows应用程序启动Googles Chrome浏览器.

我遇到的问题是我不知道Chrome应用程序(或程序路径中的任何其他应用程序)的路径.我怎么能得到这个?

在下面的代码中,我评论了三个不同的例子.如果我开始"计算",计算器将在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);
}
Run Code Online (Sandbox Code Playgroud)

注意:如果我在Windows运行命令窗口中输入"chrome"(不带引号),则Chrome也会启动.我正在寻找的是相同的功能.但是,我的应用程序可以驻留在任何位置,并且不一定与Chrome位于同一驱动器上.

Dav*_*nan 5

如果你真的必须使用CreateProcess那么你需要找出它的安装位置并传递可执行文件的完整路径.这将需要一些注册表黑客攻击.

但是,我觉得有一种更简单,更健壮的方式.Chrome在AppPaths注册表中注册,因此ShellExecuteEx指定的文件L"chrome"和默认动词将完成工作.

  • @ShyRobbiani"PROCESS_INFORMATION"给你的唯一信息是进程id +句柄和线程id +句柄.如果使用`SEE_MASK_NOCLOSEPROCESS`,`ShellExecuteEx`可以为您提供进程句柄.其他值可以使用`GetProcessId()`,`CreateToolhelp32Snapshot()`/`Thread32First()`从进程句柄中获取(参见[枚举进程中的线程](https://blogs.msdn.microsoft.com/) oldnewthing/20060223-14 /?p = 32173))和`OpenThread()`. (2认同)