0

I want to close running exe on button click in C#..But I got

Process has exited, so the requested information is not available.

my code:

Process nynprocess = new Process();
private void button2_Click(object sender, EventArgs e)
{
    string str = @"C:\Program Files\ShareX\ShareX";
    nynprocess.StartInfo.FileName = str;
    nynprocess.Start();
}

private void button3_Click(object sender, EventArgs e)
{
    nynprocess.CloseMainWindow();
    nynprocess.Kill();
    nynprocess.WaitForExit();
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Nayan
  • 43
  • 1
  • 8
  • 4
    Possible duplicate of [How to kill a process without getting a "process has exited" exception?](http://stackoverflow.com/questions/13564645/how-to-kill-a-process-without-getting-a-process-has-exited-exception) – Gilad Green Jul 18 '16 at 10:24
  • 1
    So you've kinda answered your own question. if the process has already finished, button 3 cant kill it – BugFinder Jul 18 '16 at 10:24
  • You can use a Process object just once. After the process has exited it is no longer usable. Adding nynprocess = null; to the button3_Click() method is a sensible thing to do, helps you get to a point where you fix button2_Click() and create a new Process object. Or help the user avoid clicking that button multiple times. – Hans Passant Jul 18 '16 at 10:39
  • 1
    Are you sure the process is still running when you click `button3`? You could wrap the lines in `button3_Click` in `if (!nynprocess.HasExited) { ... }` so they only apply if the process is still running when the button is clicked.. – Thorsten Dittmar Jul 18 '16 at 11:15

1 Answers1

0

try using this

        // Close process by sending a close message to its main window.
        nynprocess.CloseMainWindow();
        // Free resources associated with process.
        nynprocess.Close();