Search code examples
c++windowsvisual-studio-2015parametersshellexecuteex

C++ ShellExecuteEx does not execute exe with parameter by not generating output from that exe


for the last few days or weeks. In Visual Studio C++, I am having hard time with ShellExecuteEx() trying to run an exe with a paramter inside an exe. The way it happens is that I run the debug program in Visual Studio (even outside too). The program would start the other program and it sucessfully run, but it does not generate an .txt file output. I wasn't sure if I used the parameter correctly. Here's the steps I am trying to achieve:

  1. Start MainTest.exe (the exe that will open ScreenCapture.exe)
  2. Cmd screen - MainTest.exe started and prepares to start ScreenCapture.exe using ShellExecuteEx
  3. UAC pops up, run as admin
  4. New cmd screen - ScreenCapture.exe started with parameters and directories
  5. ScreenCapture.exe completes command and closes
  6. CaptureText.txt generated by ScreenCapture.exe placed into same directroy as ScreenCapture.exe .

The problem is that I am not getting CaptureText.txt in my directory or any proof that the parameters are working in this program.

Now, if I run the ScreenCapture.exe without using Test.exe with the parameters, it works and generates the .txt file.

Here's the Code:

#include "stdafx.h"
#include <isostream>
#include <fstream>
#include <string>
#include <Windows.h>

int main()

{

    auto str = _T("C:\\Users\Engrsky\Pictures\Screenshot.png ScreenCapture -l eng")

    SHELLEXECUTEINFO shExInfo = {0};
    shExInfo.cbSize = sizeof(shExInfo);
    shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
    shExInfo.hwnd = 0;
    shExInfo.lpVerb = _T("runas");                
    shExInfo.lpFile = _T("C:/Program File (x86)/Test/ScreenCapture.exe");           
    shExInfo.lpParameters = str;                  
    shExInfo.lpDirectory = 0;
    shExInfo.nShow = SW_SHOW;
    shExInfo.hInstApp = 0;  

}

EXAMPLE: Using just Command Prompt, ScreenCapture.exe works perfectly with the parameter. I entered it like this:

Adminstrator: Command Prompt

C:\Program File (x86)\Test> ScreenCapture "C:\\Users\Engrsky\Pictures\Screenshot.png ScreenCapture -l eng"

Then it would sucessfully run and write an output file called ScreenCapture.txt

However, when I tried to do run it using the exe I made(this file). I couldn't get an output generated.


Solution

  • From the MSDN doc for the ShellExecuteEx function, you first need to initialize COM. The example there is to use:

        CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);