我正在尝试启动一个应用程序,然后对其进行监视,直到它关闭。我正在使用ShellExecuteEX和GetExitCodeProcess并遇到几个问题。

调用GetExitCodeProcess时,以下代码导致分段错误。如果更改shellInfo.fMask = NULL,它将不会出现段错误,但会收到一条错误消息,指出“无效句柄”。

Notepad.exe会启动。

QString executeFile("notepad.exe");

// Conversion QString to LPCTSTR
wchar_t* tempEF = new wchar_t[executeFile.size()+1];
int tempEFTerminator = executeFile.toWCharArray(tempEF);
tempEF[tempEFTerminator] = 0;


LPDWORD exitCode = 0;
SHELLEXECUTEINFO shellInfo;

shellInfo.cbSize = sizeof(SHELLEXECUTEINFO);

shellInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
shellInfo.hwnd = NULL;
shellInfo.lpVerb = NULL;

shellInfo.lpFile = tempEF;

shellInfo.lpParameters = NULL;
shellInfo.lpDirectory = NULL;
shellInfo.nShow = SW_MAXIMIZE;
shellInfo.hInstApp = NULL;

if(ShellExecuteEx(&shellInfo))
{
        if(!GetExitCodeProcess(shellInfo.hProcess, exitCode))
        {
            DWORD lastError = GetLastError();

            LPTSTR lpMsgBuf;

            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL);
            QString errorText = ("failed with error: " + QString::number(lastError) + QString::fromWCharArray(lpMsgBuf));
        }
}

最佳答案

我认为问题出在exitCode参数中。

MSND将其指定为LPDWORD的指针DWORD。您应该将有效的指针传递给该函数,以便可以取消引用它以在此处保存退出代码:

DWORD exitCode;
//....
if(!GetExitCodeProcess(shellInfo.hProcess, &exitCode))

09-30 12:45
查看更多