I'm making a 'simple' program to close down all active applications on Windows 10 that I have running i.e. Chrome, Outlook, Notepadd++, etc.. After doing a lot of searching I came across this code:
foreach (Process p in Process.GetProcesses(Environment.MachineName))
{
if ((p.Id != CurrentProcess.Id && p.MainWindowHandle != IntPtr.Zero))
{
p.kill();
}
}
First it asks the process to close nicely with p.CloseMainWindow(), then kills the process if exceptions are returned. I know it's not ideal, but this works for the most part.
When running my program it closes all of my applications and some underlying Windows applications/processes because the screen, taskbar, and desktop go black for a second and refresh.
My problem is that more than half the time I run this program I get a Win32Exception and the program won't finish closing anything left open.
I'm making a guess here that it's because I don't have sufficient permissions to close Windows background processes even running as administrator and that's why I'm getting the exception.
After each kill call, I put my program to sleep for a short amount of time to give the process time to close to avoid calling kill on a terminating process which will also throw the exception. Perhaps it isn't enough time, I'm using 250ms intervals.
TL;DR Is there a way to close everything that I, the user, have opened (or everything in the taskbar) and leave the main Windows processes alone?