diff --git a/EnergyStar/EnergyManager.cs b/EnergyStar/EnergyManager.cs index 0b93002..62666c2 100644 --- a/EnergyStar/EnergyManager.cs +++ b/EnergyStar/EnergyManager.cs @@ -184,5 +184,19 @@ public static void ThrottleAllUserBackgroundProcesses() Win32Api.CloseHandle(hProcess); } } + public static void RecoverAllUserProcesses() + { + var runningProcesses = Process.GetProcesses(); + var currentSessionID = Process.GetCurrentProcess().SessionId; + + var sameAsThisSession = runningProcesses.Where(p => p.SessionId == currentSessionID); + foreach (var proc in sameAsThisSession) + { + if (BypassProcessList.Contains($"{proc.ProcessName}.exe".ToLowerInvariant())) continue; + var hProcess = Win32Api.OpenProcess((uint)Win32Api.ProcessAccessFlags.SetInformation, false, (uint) proc.Id); + ToggleEfficiencyMode(hProcess, false); + Win32Api.CloseHandle(hProcess); + } + } } } diff --git a/EnergyStar/Program.cs b/EnergyStar/Program.cs index 6f791a4..14508cb 100644 --- a/EnergyStar/Program.cs +++ b/EnergyStar/Program.cs @@ -1,9 +1,21 @@ -using EnergyStar.Interop; +using EnergyStar.Interop; +using System.Runtime.InteropServices; namespace EnergyStar { internal class Program { + public delegate bool ConsoleCtrlDelegate(int CtrlType); + [DllImport("kernel32.dll")] + private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate handlerRoutine, bool add); + static bool HandlerRoutine(int ctrlType) + { + cts.Cancel(); + HookManager.UnsubscribeWindowEvents(); + EnergyManager.RecoverAllUserProcesses(); + return false; + } + static CancellationTokenSource cts = new CancellationTokenSource(); static async void HouseKeepingThreadProc() @@ -17,7 +29,7 @@ static async void HouseKeepingThreadProc() await houseKeepingTimer.WaitForNextTickAsync(cts.Token); EnergyManager.ThrottleAllUserBackgroundProcesses(); } - catch (TaskCanceledException) + catch (OperationCanceledException) { break; } @@ -26,6 +38,8 @@ static async void HouseKeepingThreadProc() static void Main(string[] args) { + SetConsoleCtrlHandler(new ConsoleCtrlDelegate(HandlerRoutine), true); + // Well, this program only works for Windows Version starting with Cobalt... // Nickel or higher will be better, but at least it works in Cobalt // @@ -48,19 +62,10 @@ static void Main(string[] args) { if (Event.GetMessage(out Win32WindowForegroundMessage msg, IntPtr.Zero, 0, 0)) { - if (msg.Message == Event.WM_QUIT) - { - cts.Cancel(); - break; - } - Event.TranslateMessage(ref msg); Event.DispatchMessage(ref msg); } } - - cts.Cancel(); - HookManager.UnsubscribeWindowEvents(); } } }