【问题标题】:Run a console app and close the window only if it succeeds运行控制台应用程序并仅在成功时关闭窗口
【发布时间】:2022-01-08 11:30:45
【问题描述】:

我想从我的 GUI 应用程序中执行一个控制台应用程序,并且只有在成功完成后才关闭控制台窗口。我尝试了这段代码,但是当我调用该函数时,一个控制台窗口出现并很快消失,我什至看不到那里发生了什么......我试图注释掉CreateProcess之后的所有内容,但它仍然消失了。我做错了什么?

function RunDosApp(const AppName, Params, WorkDir: String): Boolean;
var
  SInfo: TStartupInfo;
  PInfo: TProcessInformation;
  CmdLine: String;
  Code: Cardinal;
begin
  FillChar(SInfo, SizeOf(SInfo), 0);
  SInfo.cb:= SizeOf(SInfo);
  SInfo.dwFlags:= STARTF_USESHOWWINDOW;
  SInfo.wShowWindow:= SW_SHOWNORMAL;
  CmdLine:= Params;
  if CreateProcess(PChar(AppName), PChar(CmdLine), nil, nil, True, 0, nil, PChar(WorkDir), SInfo, PInfo) then begin
   WaitForSingleObject(PInfo.hProcess, INFINITE);
   GetExitCodeProcess(PInfo.hProcess, Code);
   if Code = 0 then begin
    CloseHandle(PInfo.hThread);
    CloseHandle(PInfo.hProcess);
   end;
  end
  else MainForm.Caption:= SysErrorMessage(GetLastError);
end;

RunDosApp('c:\windows\ffmpeg.exe', '-i "'+InFile+'" -ss 00:00:10 -to 00:00:40 -c copy "'+OutFile+'"', Folder);

【问题讨论】:

  • "completed" 表示进程结束。一个仍然存在的进程和它的退出代码是互斥的。为什么不执行cmd.exe /K /S w:\hatever.exe -i "file"...
  • @AmigoJack 如果我使用“/S”参数,我会得到“'/S' 不是内部或外部命令、可运行程序或批处理文件。”...没有“/ S" 它可以工作,但是如果成功终止,我如何读取控制台应用程序退出代码并关闭寡妇?
  • 您的函数RunDosApp 无法运行实际的MS-DOS 应用程序。考虑将其命名为 RunCliApp 或类似名称。
  • 我敢打赌,包括函数名在内的大部分代码都是copied from ancient code——甚至函数的结果都没有设置在任何地方。
  • 这只是一段测试代码...不是最终版本。此时我不在乎名称或结果...... :)

标签: delphi console exit-code createprocess delphi-10.3-rio


【解决方案1】:

我找到了解决办法:

Cmd1:= '@echo off';
Cmd2:= '...'; // your console app and its parameters here
Cmd3:= 'if errorlevel 1 pause';
ShellExecute(0, 'open', 'cmd', PChar('/c "'+Cmd1+'&'+Cmd2+'&'+Cmd3+'"'), PChar(Folder), SW_SHOWNORMAL);

【讨论】:

  • 这不够灵活:除了0 之外的任何东西都必须被视为失败,not only 1
  • @AmigoJack 这是我第一次想到的,但errorlevel 1 的意思是“大于或等于1”。看到这个:computerhope.com/jargon/e/erroleve.htm
  • 谢谢,我宁愿只执行IF /? 而不是阅读任意网站。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 2011-09-23
  • 2010-12-19
相关资源
最近更新 更多