Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close an external application using c#

Tags:

c#

process

Im trying to be close the calculator when the user press's a key on the key board. But p.kill and p.CloseMainWindow doesn't kill the calculator, only the shell which is executed.

Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.Arguments = "/c calc ";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.Start();
Console.WriteLine("Press any key to kill Calc");
Console.ReadKey();
p.CloseMainWindow();

p.Kill();
like image 940
Craig Allan Avatar asked Dec 31 '25 14:12

Craig Allan


2 Answers

Don't use the shell (cmd) but run the calc process directly. Setting Process.StartInfo.FileName to "calc" should do it (assuming calc.exe is on the system path).

like image 81
Polyfun Avatar answered Jan 02 '26 04:01

Polyfun


You need to find the Calculator process and kill it. There are actually two processes created: one for the cmd and the other for Calculator. You are killing only the first one.

The other solution is to start the Calculator directly, without using cmd.

like image 36
Jakub Konecki Avatar answered Jan 02 '26 04:01

Jakub Konecki