0

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Nate R.
  • 1
  • 1
  • Everything with a parent process that was launched from the "shell" (explorer.exe) and having the same user as the current user and session. You might also filter by the window type to pick up what we call apps. I would not use kill - I would use p.CloseMainWindow. For further thought.. How does the "minimize all windows" action work when you click the far right side of the taskbar? I wonder if the Shell API can give you a desktop widnow list. – Sql Surfer Mar 28 '17 at 21:52
  • I am using p.CloseMainWindow first, but often I get errors because programs don't support it or don't have a 'main window' so in case that errors out I just call kill, unless I'm missing something. Thanks for the advice, I'll look into the shell API to see if I can find something about the list of processes that have my current user and session – Nate R. Mar 31 '17 at 16:44

1 Answers1

0

In Windows 10 (Maybe 8 has this too, I can't remember), the task manager has a "Processes" tab which splits processes in at least 3 categories, Apps / Background processes / Windows processes. My guess is that you would like to kill the Apps.

It seems that the way this work is by having the task manager check if each process has a top level window. I'm not very familiar with how to do this, but it would seem that Process.MainWindowHandle could be a place to start.

Eric
  • 19,525
  • 19
  • 84
  • 147