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

Ahm*_*med 21 c# process batch-file

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

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

process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
Run Code Online (Sandbox Code Playgroud)

Joe*_*win 40

如果proc.StartInfo.UseShellExecute为false,那么您正在启动该进程并可以使用:

proc.StartInfo.CreateNoWindow = true;
Run Code Online (Sandbox Code Playgroud)

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

proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Run Code Online (Sandbox Code Playgroud)

但是,被叫应用程序可能会忽略后一个请求.

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

proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
Run Code Online (Sandbox Code Playgroud)

并且具有类似的功能

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

MSDN博客CreateNoWindow上有一个很好的页面.

Windows中还有一个错误,CreateNoWindow如果您传递用户名/密码,可能会抛出一个对话框并失败.详情

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


Von*_*onC 8

根据Process属性,您有一个:

属性: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.
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用:process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;