Reputation: 903
I am working on a c# winforms application. I am trying to close a running process by its process ID.
try
{
//Find process & Kill
foreach (Process Proc in (from p in Process.GetProcesses()
where p.ProcessName == "taskmgr" || p.ProcessName == "explorer"
select p))
{
Microsoft.VisualBasic.Interaction.Shell("TASKKILL /F /IM " + Proc.ProcessName + ".exe");
}
}
catch (Exception ex)
{
ErrorLogging.WriteErrorLog(ex);
}
return null;
This code is not working on windows 2003 SP 2. I have googled and found that 2003 does not have the taskkill
command. What would be a substitute for that?
Upvotes: 3
Views: 5072
Reputation: 12834
If you don't want to see the cmd windows anymore you can use:
proc.Kill();
proc.CloseMainWindow();
of course this is useful when you have used:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo();
procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
proc.StartInfo = procStartInfo;
proc.Start();
Upvotes: 0
Reputation: 60556
Use the Process.Kill
method. If you have the required permission it will work.
Process.Kill Method Immediately stops the associated process.
try
{
//Find process
foreach (Process Proc in (from p in Process.GetProcesses()
where p.ProcessName == "taskmgr" ||
p.ProcessName == "explorer"
select p))
{
// "Kill" the process
Proc.Kill();
}
}
catch (Win32Exception ex)
{
// The associated process could not be terminated.
// or The process is terminating.
// or The associated process is a Win16 executable.
ErrorLogging.WriteErrorLog(ex);
}
catch (NotSupportedException ex)
{
// You are attempting to call Kill for a process that is running on a remote computer.
// The method is available only for processes running on the local computer.
ErrorLogging.WriteErrorLog(ex);
}
catch (InvalidOperationException ex)
{
// The process has already exited.
// or There is no process associated with this Process object.
ErrorLogging.WriteErrorLog(ex);
}
return null;
Upvotes: 4
Reputation: 1377
Find the window associated with the process & send WM_CLOSE message to it.
Upvotes: 0
Reputation: 370
Get the current process and use: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx Process.Kill to kill the corresponding process.
Upvotes: 0