的System.Diagnostics.Process

时间:2013-06-19 19:00:53

标签: winforms system.diagnostics

我有.NET窗体和按钮。当点击按钮我开始蝙蝠文件:

        //execute batch
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = "test.bat";
        proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(path);
        proc.Start();
        proc.WaitForExit();

我希望能够再次点击按钮并停止执行bat。现在Windows窗体失去焦点,我无法点击按钮。如何从Windows窗体中停止该过程?

由于

2 个答案:

答案 0 :(得分:0)

this.Focus(); 

 proc.Start();

答案 1 :(得分:0)

不能更精确,因为我需要知道在蝙蝠内部运行的是什么,但可能你可以使用Process.Kill方法。

为了能够使用它,你应该在Start之后删除WaitForExit并将proc变量保存为表单级变量。然后,当您需要关闭该过程时,您可以尝试使用

if(!proc.HasExited)
{
    proc.Kill();
    proc.WaitForExit();
}
proc.Dispose();
proc = null;

请注意,以这种方式关闭进程可能会对计算机的稳定性造成危险,具体取决于bat文件正在执行的操作....

对于Focus问题,假设这是一个批处理文件,您可以使用CreateNoWindow选项阻止窗口出现

    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo.FileName = "cmd.exe";
    proc.StartInfo.Arguments = "/C test.bat";
    proc.StartInfo.WorkingDirectory = @"c:\temp";
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.UseShellExecute = false;
    proc.Start();