如何等待ShellExecute运行?

时间:2013-07-14 10:45:03

标签: visual-c++ shellexecute

我已经设法在VC ++中使用ShellExecute来启动文档。 现在我希望运行一个接收一些参数的命令行工具,并在后台运行(隐藏,而不是最小化)并让它阻止我的程序流程,以便我能够等待它完成。 如何更改命令行:

ShellExecute(NULL,"open",FULL_PATH_TO_CMD_LINE_TOOL,ARGUMENTS,NULL,SW_HIDE);

问题是,我有将html转换为pdf的工具,我希望一旦工具完成,也就是pdf准备就绪,让另一个ShellExecute来查看它。

3 个答案:

答案 0 :(得分:49)

有一个CodeProject article通过ShellExecuteEx代替ShellExecute来说明如何:

SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = "c:\\MyProgram.exe";        
ShExecInfo.lpParameters = "";   
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL; 
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
CloseHandle(ShExecInfo.hProcess);

关键点是标志SEE_MASK_NOCLOSEPROCESSas MSDN says

  

用于表示 hProcess 成员收到进程句柄。此句柄通常用于允许应用程序查找使用ShellExecuteEx创建的进程何时终止

另外,请注意:

  

调用应用程序负责在不再需要时关闭句柄。

答案 1 :(得分:1)

您也可以使用CreateProcess而不是ShellExecute / ShellExecuteEx。此函数包括cmd.exe包装选项,返回退出代码,并返回stdout。 (包括可能不完美)。

注意:在我的使用中,我知道必须有stdout结果,但PeekedNamePipe函数在第一次尝试时不会总是返回字节数,因此循环就在那里。也许,有人能想出来并发布修订版?另外,也许应该生成另一个版本,它会单独返回stderr?

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <Shellapi.h>


/*
Note: 
    The exitCode for a "Cmd Process" is not the exitCode
    for a sub process launched from it!  That can be retrieved
    via the errorlevel variable in the command line like so:
    set errorlevel=&[launch command]&echo.&echo exitCode=%errorlevel%&echo.
    The stdOut vector will then contain the exitCode on a seperate line
*/
BOOL executeCommandLine( const CStringW &command,
                         DWORD &exitCode,
                         const BOOL asCmdProcess=FALSE,
                         std::vector<CStringW> *stdOutLines=NULL )
{
    // Init return values
    BOOL bSuccess = FALSE;
    exitCode = 0;
    if( stdOutLines ) stdOutLines->clear();

    // Optionally prepend cmd.exe to command line to execute
    CStringW cmdLine( (asCmdProcess ? L"cmd.exe /C " : L"" ) +
                      command );

    // Create a pipe for the redirection of the STDOUT 
    // of a child process. 
    HANDLE g_hChildStd_OUT_Rd = NULL;
    HANDLE g_hChildStd_OUT_Wr = NULL;
    SECURITY_ATTRIBUTES saAttr; 
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    saAttr.bInheritHandle = TRUE; 
    saAttr.lpSecurityDescriptor = NULL; 
    bSuccess = CreatePipe( &g_hChildStd_OUT_Rd, 
                           &g_hChildStd_OUT_Wr, &saAttr, 0);
    if( !bSuccess ) return bSuccess;         
    bSuccess = SetHandleInformation( g_hChildStd_OUT_Rd, 
                                     HANDLE_FLAG_INHERIT, 0 );
    if( !bSuccess ) return bSuccess;         

    // Setup the child process to use the STDOUT redirection
    PROCESS_INFORMATION piProcInfo; 
    STARTUPINFO siStartInfo;    
    ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
    ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
    siStartInfo.cb = sizeof(STARTUPINFO); 
    siStartInfo.hStdError = g_hChildStd_OUT_Wr;
    siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
    siStartInfo.dwFlags |= STARTF_USESTDHANDLES;

    // Execute a synchronous child process & get exit code
    bSuccess = CreateProcess( NULL, 
      cmdLine.GetBuffer(),  // command line 
      NULL,                 // process security attributes 
      NULL,                 // primary thread security attributes 
      TRUE,                 // handles are inherited 
      0,                    // creation flags 
      NULL,                 // use parent's environment 
      NULL,                 // use parent's current directory 
      &siStartInfo,         // STARTUPINFO pointer 
      &piProcInfo );        // receives PROCESS_INFORMATION    
    if( !bSuccess ) return bSuccess;         
    WaitForSingleObject( piProcInfo.hProcess, (DWORD)(-1L) );
    GetExitCodeProcess( piProcInfo.hProcess, &exitCode );   
    CloseHandle( piProcInfo.hProcess );
    CloseHandle( piProcInfo.hThread );

    // Return if the caller is not requesting the stdout results
    if( !stdOutLines ) return TRUE;

    // Read the data written to the pipe
    DWORD bytesInPipe = 0;
    while( bytesInPipe==0 ){
        bSuccess = PeekNamedPipe( g_hChildStd_OUT_Rd, NULL, 0, NULL, 
                                  &bytesInPipe, NULL );
        if( !bSuccess ) return bSuccess;
    }
    if( bytesInPipe == 0 ) return TRUE; 
    DWORD dwRead; 
    CHAR *pipeContents = new CHAR[ bytesInPipe ];    
    bSuccess = ReadFile( g_hChildStd_OUT_Rd, pipeContents, 
                         bytesInPipe, &dwRead, NULL);
    if( !bSuccess || dwRead == 0 ) return FALSE; 

    // Split the data into lines and add them to the return vector
    std::stringstream stream( pipeContents );
    std::string str;
    while( getline( stream, str ) ) 
        stdOutLines->push_back( CStringW( str.c_str() ) );

    return TRUE;
}

答案 2 :(得分:0)

如果使用COM,有时无法使用ShellExecuteEx,因此必须考虑以下注意事项。

因为ShellExecuteEx可以将执行委派给Shell扩展 (数据源,上下文菜单处理程序,动词实现)是 使用组件对象模型(COM)激活,COM应该是 在调用ShellExecuteEx之前初始化。一些Shell扩展 需要COM单线程单元(STA)类型。在这种情况下, COM应该按如下所示初始化:

CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)

在某些情况下,ShellExecuteEx不使用其中之一 类型的Shell扩展名和那些实例将不需要COM 完全被初始化。但是,始终保持良好的习惯 在使用此功能之前先初始化COM。

更多来自MSDN的信息 https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecuteexa