Search code examples
c++mfcshellexecuteshellexecuteex

Why are the ShellExecuteEx() parameters not working?


Let say I want the program "C:\MyProgram.exe" to run with parameters that are two variables. The problem that occurs is that MyProgram only receives 2 parameters, while I clearly pass 3 parameters.

My code:

SHELLEXECUTEINFO    ShExecInfo = { 0 };
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;

ShExecInfo.lpFile = T("\"C:\\MyProgram.exe\"");
ShExecInfo.lpParameters = _T("\"\"") _T(" ") + dir + file[i] + _T(" ") + dir + outputfile + _T(".TIFF");
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess, 1500);
if(GetExitCodeProcess(ShExecInfo.hProcess, &exitCode)){
    MessageBox(_T("Conversion ") + file[i] + _T(" unsuccesful."), _T("TEST!"), MB_OK);
    succes = 0;
}

Because there isn't much info on the internet on variable parameters with ShellExecuteEx, I could not find a proper explanation for this.

Does any of you maybe know how to solve this issue? Thanks in advance!


Solution

  • Simply because your construct yields into a temporary object and the pointer to it (a CString I guess) is stored but the temporary object is already destroyed when you launch the program.

    auto str = _T("\"\"") _T(" ") + dir + file[i] + _T(" ") + dir + outputfile + _T(".TIFF");
    ShExecInfo.lpParameters = str;
    ShellExecuteEx(&ShExecInfo);