0

I have .NET windows form and button. When click on button I start bat file:

        //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();

I want to be able to click on button again and stop executing bat. Right now Windows form lose focus and I can't click the button. How can I stop the process from Windows Form?

Thanks

Steve
  • 213,761
  • 22
  • 232
  • 286

2 Answers2

0

try

this.Focus(); 

after

 proc.Start();
Moondustt
  • 864
  • 1
  • 11
  • 30
  • Well, the question is not very clear, you need to get the focus on the form to be able to click the STOP button, or you need to create a stop button? – Moondustt Jun 19 '13 at 19:12
0

Can't be more precise because I need to know what is running inside the bat but probably you could use the Process.Kill method.

To be able to use it you should remove the WaitForExit after the Start and save the proc variable in as a form level variable. Then when you need to close the process you could try with

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

Beware that closing a process in this manner could be Dangerous for the stability of your computer depending on what the bat file is doing....

For the Focus problem, given that this is a batch file you could use the CreateNoWindow option to stop the window from appearing

    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();
Steve
  • 213,761
  • 22
  • 232
  • 286