简体   繁体   English

如何在后台启动批处理文件并重定向其输出?

[英]How do you start a batch file in the background and redirect its output?

I am trying to call a batch file from an application, but I want the command window to be hidden and the standard output to be redirected to one or more locations (as it is produced by the batch file). 我试图从应用程序中调用批处理文件,但是我希望命令窗口被隐藏,并且标准输出将重定向到一个或多个位置(因为它是由批处理文件产生的)。

My issue is that when the batch file is running the console is up and nothing displays; 我的问题是,当批处理文件运行时,控制台已启动,并且什么也没有显示。 it's just up. 它只是。 When the task completes, the console closes. 任务完成后,控制台将关闭。 I want to get rid of the console (perhaps have it run in the back ground). 我想摆脱控制台(也许让它在后台运行)。

The other issue is that I am redirecting the output to a richtext box. 另一个问题是我将输出重定向到RTF框。 If i redirect it to the console or text box, it just spits out all the results at once. 如果我将其重定向到控制台或文本框,它将立即吐出所有结果。 I would like it to spit out line by line as it happens. 我希望它在发生时逐行吐出。 Make sense? 说得通?

The code is below: 代码如下:

    //Declare and instantiate a new process component.
    System.Diagnostics.Process process1;
    process1 = new System.Diagnostics.Process();
    process1.StartInfo.UseShellExecute = false;
    process1.StartInfo.RedirectStandardOutput = true;
    process1.StartInfo.FileName = "cmd.exe";
    process1.StartInfo.Arguments = "<BATCHfILE>";
    process1.Start();

    string output = process1.StandardOutput.ReadToEnd();
    rchsdtOut.Text = output;

    Console.WriteLine(process1.StandardOutput.ReadToEnd());

    process1.WaitForExit();
    process1.Close();

This is how I would have done it. 这就是我要做的。 Hope I understood your question correctly: 希望我能正确理解您的问题:

Add: 加:

process1.CreateNoWindow = true,
process1.OutputDataReceived += (s, e) => myMethod(e);
process1.BeginOutputReadLine(); 

And then a method 然后是方法

private void myMethod(DataReceivedEventArgs e)
{
    //Do something with e.Data
}

To solve the Cross-thread operation issue mentioned in the comments. 解决注释中提到的跨线程操作问题。 You will need to add this to your form class (before the functions begin): 您需要将其添加到表单类中(在函数开始之前):

private delegate void updateText(string str);

Then you need to add this: 然后,您需要添加以下内容:

private void update_richTextBox1(string value)
{
    richTextBox1.Text += value;
}

And then in the myMethod function add: 然后在myMethod函数中添加:

richTextBox1.Invoke(new updateText(update_richTextBox1), new object[] { e.Data.ToString() });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM