views:

387

answers:

4

Hi,

I just wanna ask your opinion/suggestion on how to 'terminate' a running application/process is C#

Right now, I do have the following codes:

    Process myProcess;
    private void btnOpen_Click(object sender, RoutedEventArgs e)
    {
        DirectoryInfo di = new DirectoryInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.Programs));
        myProcess = Process.Start(di + @"\Wosk\Wosk.appref-ms"); // opening a file coming for Startup Menu
    }

    private void btnClose_Click(object sender, RoutedEventArgs e)
    {
        myProcess.Kill(); // not working - Cannot process request because the process has exited
    }

I also tried myProcess.Close(); but nothing's happening.

+3  A: 

You should have a look at

Process.HasExited Property

A process can terminate independently of your code. If you started the process using this component, the system updates the value of HasExited automatically, even if the associated process exits independently.

astander
This is the wrong approach because immediately after returning false the process could exit. So a check to `if ( !myProcess.HasExited ) { myProcess.Kill(); }` could still throw an exception. Much better to just call `Kill` and deal with the resulting exception.
JaredPar
+2  A: 

First please replace:

di + @"\Wosk\Wosk.appref-ms" 

with:

Path.Combine(di.FullName, @"Wosk\Wosk.appref-ms")

Now to the point: I don't know what Wosk.appref-ms is or how this process is started. If this is a file it will be opened with the default program associated with this file extension. The problem could be related to the fact that the process you start only starts another process and terminates immediately. That's why when you try to kill it it says that it has already exited, but the actual process it spawned is still running. In this case you will have to enumerate through the running processes with Process.GetProcesses(), find the process and stop it.

Darin Dimitrov
I don't get your Path.Combine, but mine's pretty fine right now.
eibhrum
+1  A: 

Based on your comment it looks like the Process instance has already exited when you hit the close button. This can happen at any time and it's something you need to guard against. The easiest way is to simply catch the exception that results from calling Kill on an already exited process.

try {
  myProcess.Kill();
} catch ( InvalidOperationException ) {
  // Process is already finished so nothing to do
}
JaredPar
+2  A: 

You are starting a program that was installed with ClickOnce. The .appref-ms is executed by a helper program, rundll32.exe, that starts the process and quickly exits. To terminate the started process, you'll need to find the actual running .exe with Process.GetProcessesByName() and use the Kill method.

We can't tell you what the process name is, that's contained in the .appref-ms file. But it is easy for you to see with TaskMgr.exe.

Hans Passant