Search code examples
c++winapisystemcreateprocess

CreateProcess function instead of system


I have created a code which using windows forms application in order to construct a gui. I am using system command in my code in order to call an external .exe. However this approach creates a command line terminal. I found that I can replace system with CreateProcess function here. How should I use this function? What parameters should I specify in order to run? My code now is:

 string run_template = "a.exe -i " + s1 + " -r 10 -f image2  filename%03d.jpg";
 system(run_template.c_str());

EDIT:

 #include <tchar.h>

 string workPath = "";
 string args = "-i " + s1 + " -r 10 -f image2  vid/frames/filename%03d.jpg";

 HINSTANCE hRet = ShellExecute(NULL, _T("open"), _T("a.exe"), _T(args.c_str()), _T(workPath.c_str()), SW_HIDE);
 DWORD errNum = GetLastError();

I got the following error:

1>c\projects\first_api\first_api\Form1.h(229): error  C2065: 'Largs' : undeclared identifier
1>c:\projects\first_api\first_api\Form1.h(229): error C2228: left of '.c_str' must have class/struct/union
1>          type is ''unknown-type'' 
1>c:\projects\first_api\first_api\Form1.h(229): error C2065: 'LworkPath' : undeclared identifier
1>c:\projects\first_api\first_api\Form1.h(229): error C2228: left of '.c_str' must have class/struct/union

EDIT2:

string run_template = "a.exe -i " + s1 + " -r 1 -f image2 /filename%03d.jpg";
//system(run_template.c_str());

STARTUPINFOA si = {sizeof(STARTUPINFOA), 0};
PROCESS_INFORMATION pi = {0};

if (CreateProcessA(NULL, const_cast<char*>(run_template.c_str()), NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))   {
     CloseHandle(pi.hThread);
     CloseHandle(pi.hProcess);
}

The command prompt still exists when using the above code.


Solution

  • string run_template = "a.exe -i " + s1 + " -r 10 -f image2  filename%03d.jpg";
    
    STARTUPINFOA si = {sizeof(STARTUPINFOA), 0};
    si.dwFlags = STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE;
    
    PROCESS_INFORMATION pi = {0};
    
    vector<char> cmdline(run_template.begin(), run_template.end());
    if (CreateProcessA(NULL, &cmdline[0], NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
    {
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
    }