0

I tried to execute a batch file which is in same directory as in the application is and hide the batch file window as in hidden but the code doesn't work for some reason.

Please help me what is wrong in the code. Below is the code.

STARTUPINFO StartupInfo;
PROCESS_INFORMATION ProcessInfo;


memset(&StartupInfo, 0, sizeof(StartupInfo));
StartupInfo.cb = sizeof(STARTUPINFO);
StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow = SW_HIDE;

CreateProcess(NULL, _T("Testfile.bat"), NULL, NULL, FALSE,CREATE_NEW_CONSOLE, NULL, NULL,&StartupInfo,&ProcessInfo);

The application crashes when the control comes to this portion of the code.

Maloser
  • 35
  • 7
  • 1
    Quoting [the documentation](https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx) ‘*To run a batch file, you must start the command interpreter; set lpApplicationName to cmd.exe and set lpCommandLine to the following arguments: /c plus the name of the batch file.*’ – Biffen Feb 12 '16 at 12:53
  • @Biffen Well how to know whee the application is placed? i mean should i give proper dir of the batch file? – Maloser Feb 12 '16 at 13:13
  • Not sure what you mean by the application, but yes, the path to the batch file will have to be correct. – Biffen Feb 12 '16 at 13:14
  • @Biffen I want to run the batch file hidden also i don't where is the batch file like i create a batch file where ever the current process is running. – Maloser Feb 12 '16 at 13:17
  • I don't know what ‘*hidden*’ means in this context. If *you* created the file, then just use the same path again, be it absolute or relative to the working directory. – Biffen Feb 12 '16 at 13:20
  • may be [link](http://stackoverflow.com/a/25919674/2135548) – Mandar Feb 12 '16 at 13:22

1 Answers1

0

Below is a pseudo code for running bat in background.

 //... Prepare
 //
 // Get Current Dir  
 #define BUFSIZE MAX_PATH             
 TCHAR myBat[BUFSIZE];
 DWORD dwRet;    
 dwRet = GetCurrentDirectory(BUFSIZE, myBat);

 // Append .bat name
 myBat += "this_one.bat"


//... Execute
//
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;

wchar_t cmdline[] = L"cmd.exe /C "+ myBat ;
wchar_t cmdline2[] = L"start /MIN /B \"\" \""+ myBat +"\"";

// For kiosk windows
//wchar_t cmdline[] = L"%systemroot%\\system32\\cmd.exe /C "+ myBat ;

if (!CreateProcess(NULL, cmdline, NULL, NULL, false, CREATE_UNICODE_ENVIRONMENT,
   NULL, NULL, &si, &pi))
{
    std::cout << GetLastError();
    abort();
}

CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
Mandar
  • 1,006
  • 11
  • 28
  • @Maloser you can replace it by [wcscat](http://www.cplusplus.com/reference/cwchar/wcscat/). something like wcscat_s(myBat, L"\\this_one.bat"); – Mandar Feb 13 '16 at 04:55