简体   繁体   English

使用参数创建进程(CreateProcess或ShellExecuteEx)的小问题

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

Related question: CreateProcess doesn't pass command line arguments . 相关问题: CreateProcess不传递命令行参数

Is there a difference between passing an argument vs. passing a parameter to an EXE when using CreateProcess (and/or ShellExecuteEx)? 使用CreateProcess(和/或ShellExecuteEx)时,传递参数与传递参数到EXE有区别吗?

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; 据我从其他线程和MSDN了解到的是,它应该可以正常工作,并使用参数调用EXE。 doing the above code without adding the "/myparam" works like it should. 在不添加“ / myparam”的情况下执行上面的代码,其工作方式应该是应该的。

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. 我已经从命令行和资源管理器中尝试了EXE(通过创建快捷方式并将/ myparam添加到目标名称),并且可以正常工作。

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. 否则通过parameters参数传递参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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