I have this loop that runs continuously as a process to check if the mstsc.exe
is running.
for (; ; )
{
System.Diagnostics.Process[] pname = System.Diagnostics.Process.GetProcessesByName("mstsc");
if (pname.Length != 0)
{
}
else
{
System.Diagnostics.Process.Start(@"mstsc.exe");
}
System.Threading.Thread.Sleep(3000);
}
The problem is that on logoff, reboot, or shutdown I get this.
I tried to end the process on Form_Closing or with
Microsoft.Win32.SystemEvents.SessionEnded +=
new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
and I still get this...
How could I force this process to kill correctly?
That happends when process has child processes. You have to kill whole process tree.
Kill process tree programmatically in C#
Code from link above (provided by Gravitas):
/// <summary>
/// Kill a process, and all of its children.
/// </summary>
/// <param name="pid">Process ID.</param>
private static void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With