简体   繁体   中英

Small issue with creating a process ( CreateProcess or ShellExecuteEx) with parameters

Related question: CreateProcess doesn't pass command line arguments .

Is there a difference between passing an argument vs. passing a parameter to an EXE when using CreateProcess (and/or ShellExecuteEx)?

I'm trying to call something like:

myExe.exe /myparam

with the code like :

TCHAR Buffer[MAX_PATH];
 DWORD dwRet;
 dwRet = GetCurrentDirectory(MAX_PATH, Buffer);

 CString sCmd;
 sCmd.Format ( "%s\\%s", Buffer, command);
 CString sParam( "/myparam" );
 sCmd += " " + sParam;

 STARTUPINFO si;
 PROCESS_INFORMATION pi;

 ZeroMemory( &si, sizeof(si) );
 si.cb = sizeof(si);
 ZeroMemory( &pi, sizeof(pi) );


 if (CreateProcess( NULL, sCmd.GetBuffer() , NULL, NULL, TRUE, 0, NULL, Buffer, &si, &pi))
 {
  ::WaitForSingleObject(pi.hProcess, INFINITE);
  CloseHandle(pi.hProcess);
  CloseHandle(pi.hThread);
 }
 else
 {
  LPVOID lpMsgBuf = NULL;
  DWORD dw = GetLastError(); 

  FormatMessage(
   FORMAT_MESSAGE_ALLOCATE_BUFFER | 
   FORMAT_MESSAGE_FROM_SYSTEM |
   FORMAT_MESSAGE_IGNORE_INSERTS,
   NULL,
   dw,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   (LPTSTR) &lpMsgBuf,
   0, NULL );

  CString msg;
  msg.Format("Failed to start command line (error: %s) : %s\n",lpMsgBuf,sCmd);

  AfxMessageBox(msg); 

  LocalFree(lpMsgBuf);
 }

From what I understand from the other thread and MSDN is that it should be working properly and call the EXE with the parameter; doing the above code without adding the "/myparam" works like it should.

I've tried the EXE from the command line and from Explorer (by creating a shortcut and adding /myparam to the target name) and it's working alright.

Try this in case there are spaces in the path:

CString sCmd;
sCmd.Format ( "\"%s\\%s\"", Buffer, command);

Or else pass the parameters via the parameters argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM