Question

i want to close an executable file (.EXE) runing on my PC programatically using WPF, I have succed to start this .EXE file by :

if (_MyPath != "")
{
   Process StartApp = new Process();
   string str = @_MyPath;
   StartApp.StartInfo.FileName = str;
   StartApp.Start();
}
else
{
   MessageBox.Show("Path Empty", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

now my purpose is to close process of this .EXE file by clicking on a button?

Was it helpful?

Solution

Store the process instance in a field and call either Process.CloseMainWindow or Process.Kill on it.

CloseMainWindow sends a window close message to the application, which lets it ask the user, perform any required operations before closing or even decide to ignore the request.

Kill on the other hand, asks the OS to kill the target process immediatelly, probably causing data loss. It is also an asynchronous call, which means you have to call Process.WaitForExit to wait for the process to end.

In both cases, you'll need to handle exceptions that may be thrown if the target process terminates before you call Kill or CloseMainWindow, is in the process of terminating, or the OS can't kill it at all (probably due to security restrictions)

To avoid some exceptions, you can simply check whether the child application has finished before trying to kill it, by calling Process.HasExited

You could try something like this:

Process  _childApp;

private void SpawnProcess()
{
...
    if (_MyPath != "")
    {
       _childApp= new Process();
       string str = @_MyPath;
       _childApp.StartInfo.FileName = str;
       _childApp.Start();
    }
    else
    {
       MessageBox.Show("Path Empty", "Error", MessageBoxButton.OK,
                                              MessageBoxImage.Error);
    }
...
}

private void StopProcess()
{
    if (_childApp.HasExited)
        return;
    try
    {
        _childApp.Kill();
        if (!_childApp.WaitForExit(5000))
        {
          MessageBox.Show("Closing the app takes too long","Warning",
                                              MessageBoxButton.OK,
                                              MessageBoxImage.Error);
        }
    }
    catch(Exception exc)
    {
          MessageBox.Show(exc.ToString(),"Failed to close app",
                                              MessageBoxButton.OK,
                                              MessageBoxImage.Error);
    }
}

OTHER TIPS

Save a reference of the process and when you want to stop it, call the Kill method:

StartApp.Kill();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top