C#/.NET: Closing another process outside the main window

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.

Answer1:

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.

Answer2:

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 }

Answer3:

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.

Answer4:

Process[] islemler = Process.GetProcessesByName("osk"); foreach (Process islem in islemler) islem.Kill();

Answer5:

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.

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:C#/.NET: Closing another process outside the main window