【问题标题】:Can't hide CMD window while running .bat file using C#使用 C# 运行 .bat 文件时无法隐藏 CMD 窗口
【发布时间】:2022-11-22 05:12:28
【问题描述】:
private void button1_Click_1(object sender, EventArgs e)
        {

            lbl_startingTest.Text = "Flashing DUT..";
            lbl_Result.Text = "Flash";
            
            Process fls1 = new Process();
            fls1.StartInfo.UseShellExecute = false;
            fls1.StartInfo.FileName = "C:\\test\\test\\bin\\Debug\\flash.bat";
            fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            fls1.Start();
            fls1.WaitForExit();
        }

我尝试使用 fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;查看它是否隐藏了 CMD 窗口。但是当我运行应用程序软件时,当我单击应用程序上的按钮时,它会弹出 CMD 窗口。如何隐藏 CMD 窗口并仍然在后台运行 .bat 文件?

【问题讨论】:

  • 在使用 fls1.StartInfo.CreateNoWindow = true; 时还应考虑批处理文件不是可执行文件,它是需要解释器的脚本(文本)文件。要运行的可执行文件实际上是 Windows 系统目录中的cmd.exe,参数字符串为"/D /C C:\\test\\test\\bin\\Debug\\flash.bat"。使用 Environment.SystemDirectory 并将返回的字符串与 "\\cmd.exe" 连接起来,以获得 Windows 命令处理器的完全限定文件名。
  • 顺便说一句:cmd.exe 使用 Windows 库函数来处理批处理文件(主要来自 Windows 内核)。 C# 编码的应用程序可以直接使用完全相同的库函数来执行与 cmd.exe 处理批处理文件完全相同的操作。出于这个原因,执行 cmd.exe 来处理批处理文件是设计错误的。 C# 代码可用于执行与cmd.exe 相同的处理批处理文件的操作,不同之处在于执行速度比cmd.exe 快。

标签: c# batch-file cmd


【解决方案1】:

在没有 UseShellExecute = false 的情况下尝试它;也许将其更改为 UseShellExecute 为真。

 private void button1_Click_1(object sender, EventArgs e)
    {

        lbl_startingTest.Text = "Flashing DUT..";
        lbl_Result.Text = "Flash";
        fls1.StartInfo.UseShellExecute = true;
        Process fls1 = new Process();
        fls1.StartInfo.FileName = "C:\test\test\bin\Debug\flash.bat";
        fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        fls1.Start();
        fls1.WaitForExit();
    }

【讨论】:

    【解决方案2】:

    CreateNoWindow 属性可能就是您要查找的内容。

    fls1.StartInfo.CreateNoWindow = true;

    【讨论】:

    • 像这样极其简短的答案通常会被否决并经常被删除。考虑在你的建议背后加上一些背景和推理来充实它。
    猜你喜欢
    • 2022-01-22
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多