如何在运行批处理文件时隐藏cmd窗口?

22

如何在运行批处理文件时隐藏cmd窗口?

我使用以下代码来运行批处理文件:

process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
5个回答

44

如果 proc.StartInfo.UseShellExecute 为false,则表示您正在启动该进程并可以使用以下代码:

proc.StartInfo.CreateNoWindow = true;

如果 proc.StartInfo.UseShellExecute 为true,则操作系统将启动该进程,并且您必须通过以下方式向进程提供“提示”:

proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

然而,被调用的应用程序可能会忽略这个后续请求。

如果使用UseShellExecute = false,您可能需要考虑重定向标准输出/错误,以捕获生成的任何日志:

proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);

并且有一个像这样的函数

private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
   if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}

这个MSDN博客页面提供了关于CreateNoWindow的详细介绍。

同时,在Windows中也存在一个bug,如果你传递了用户名和密码,可能会弹出对话框并阻止CreateNoWindow的功能。有关详细信息,请参见:

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476 http://support.microsoft.com/?kbid=818858


有时候可以工作,有时候不行。这取决于批处理文件命令吗? - Ahmed Atia
Ahmed,我已经将答案更全面化,并为您提供了两种不同的隐藏窗口选项。此外,根据应用程序的不同,我认为即使您尽最大努力,它仍然可能会弹出一些窗口。 - Joel Goodwin

8
根据进程属性,您可以使用以下功能:

属性:CreateNoWindow
说明:允许您静默运行命令行程序。 它不会闪烁控制台窗口。

以及:

属性:WindowStyle
说明:使用此选项设置窗口为隐藏状态。 作者经常使用ProcessWindowStyle.Hidden作为示例!

static void LaunchCommandLineApp()
{
    // For the example
    const string ex1 = "C:\\";
    const string ex2 = "C:\\Dir";

    // Use ProcessStartInfo class
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = false;
    startInfo.FileName = "dcm2jpg.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

    try
    {
        // Start the process with the info we specified.
        // Call WaitForExit and then the using statement will close.
        using (Process exeProcess = Process.Start(startInfo))
        {
            exeProcess.WaitForExit();
        }
    }
    catch
    {
        // Log error.
    }
}

1
有时候可以工作,有时候不行。这取决于批处理文件的命令吗? - Ahmed Atia

5
使用方法: process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

1
有时候能正常工作,有时候就不能。这是由bat文件命令决定的吗? - Ahmed Atia

1
这是我所做的, 当你重定向所有的输入和输出,并将窗口隐藏,它应该可以工作。
            Process p = new Process();
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

0

尝试使用thisthis,其中C#代码嵌入到批处理文件中:

@echo off

echo self minimizing
call getCmdPid.bat
call windowMode.bat -pid %errorlevel% -mode minimized

echo --other commands--
pause

虽然可能不太容易取消隐藏窗口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接