windows 阻止新cmd窗口关闭

lnxxn5zx  于 2023-11-21  发布在  Windows
关注(0)|答案(1)|浏览(309)

我的问题是:我怎样才能防止我在cmd中执行的程序在不改变原始源代码的情况下打开和关闭第二个cmd窗口?(我只有.exe文件)还有:有没有办法让程序在同一个cmd窗口中打印输出,而不是打开第二个窗口?
我正在使用Windows 11并执行程序这个程序打开第二个cmd窗口,打印一些东西,然后立即关闭。我不是这个程序的所有者,所以我没有办法改变它的源代码,使它暂停cmd窗口后,它完成执行。我看到类似的问题,人们建议添加/k在cmd提示符中的代码末尾,以防止它关闭,但问题是程序打开第二个cmd窗口,而/k命令不适用于它,所以它不工作。

cig3rfwq

cig3rfwq1#

听起来你的程序 * 显式地 * 创建了一个 * 新的控制台窗口 *。
因此,任何常规调用机制(直接调用、通过Start-Process调用)都不会有什么不同。
你有两个基本的选择:

  • 检查目标可执行文件是否有某种 * 配置机制 *,使其保持显式创建的控制台窗口打开 *,直到用户决定关闭它 *,例如通过命令行选项或环境变量。
  • 如果没有-假设cmd.exe用于启动新的控制台窗口-您可以cmd.exe创建一个 * 代理 * 可执行文件,使窗口保持打开状态,直到用户按下一个键-见下文。
  • 注意事项:原则上,该技术也可以应用于其他可执行程序,只要你知道程序的可执行文件名,并且只要它不是用 * 固定路径 * 调用的(即使这样,你也可以 * 临时 * 替换它,但这显然是一个次优的解决方案)。

要使用cmd.exe的代理可执行文件,请执行以下操作:

  • Windows PowerShell 编译代理cmd.exe可执行文件,如下所示。
  • 假设代理cmd.exe是在 current 目录中创建的(根据需要进行调整):
  1. $prevPath = $env:PATH; $prevComSpec = $env:ComSpec
  2. # *Temporarily* replace cmd.exe with the proxy program.
  3. $env:ComSpec = Convert-Path .\cmd.exe
  4. $env:Path = (Split-Path -Parent $env:ComSpec) + ';' + $env:PATH
  5. # Now invoke your program - synchronously
  6. Start-Process -Wait yourProgram.exe
  7. # Restore the original environment.
  8. $env:Path = $prevPath
  9. $env:ComSpec = $prevComSpec

字符串

编译代理cmd.exe可执行文件

注意事项:必须在 Windows PowerShell 中运行(在撰写本文时,不支持从PowerShell (Core) 7+创建.exe文件(PowerShell 7.3.x)-请参阅GitHub issue #13344)。

  1. # Create a proxy for `cmd.exe` in the current directory
  2. # that invokes the real `cmd.exe` behind the scenes and
  3. # then waits for the user to press a key before exiting,
  4. # which keeps the console window open.
  5. Add-Type -OutputAssembly .\cmd.exe @'
  6. using System;
  7. using System.Text.RegularExpressions;
  8. using System.Diagnostics;
  9. static class Program
  10. {
  11. static int Main()
  12. {
  13. // Get cmd.exe's full path.
  14. var cmdExePath = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\System32\cmd.exe");
  15. // Strip this exe's own name/path from the original command line.
  16. var passThruArgs = Regex.Replace(Environment.CommandLine, @"^.+\.exe""? ", "");
  17. // Synchronously run cmd.exe with the pass-through arguments
  18. var psi = new ProcessStartInfo {
  19. FileName = cmdExePath,
  20. Arguments = passThruArgs,
  21. UseShellExecute = false
  22. };
  23. var ps = Process.Start(psi);
  24. ps.WaitForExit();
  25. // Prompt for a keypress to prevent the window from closing.
  26. Console.Write("Press any key to continue . . . ");
  27. Console.ReadKey(true);
  28. // Pass cmd.exe's exit code through.
  29. return ps.ExitCode;
  30. }
  31. }
  32. '@

展开查看全部

相关问题