|
3 | 3 | using System.Diagnostics; |
4 | 4 | using System.IO; |
5 | 5 | using System.Linq; |
| 6 | +using System.Runtime.InteropServices; |
6 | 7 | using System.Threading.Tasks; |
7 | 8 | using System.Windows; |
8 | 9 | using System.Windows.Input; |
|
19 | 20 | using LenovoLegionToolkit.WPF.Utils; |
20 | 21 | using LenovoLegionToolkit.WPF.Windows.Utils; |
21 | 22 | using Microsoft.Xaml.Behaviors.Core; |
| 23 | +using Windows.Win32; |
| 24 | +using Windows.Win32.System.Threading; |
22 | 25 | using Wpf.Ui.Controls; |
23 | 26 | #if !DEBUG |
24 | 27 | using System.Reflection; |
25 | 28 | using LenovoLegionToolkit.Lib.Extensions; |
26 | 29 | #endif |
27 | 30 |
|
| 31 | +#pragma warning disable CA1416 |
| 32 | + |
28 | 33 | namespace LenovoLegionToolkit.WPF.Windows; |
29 | 34 |
|
30 | 35 | public partial class MainWindow |
@@ -146,9 +151,11 @@ private void MainWindow_StateChanged(object? sender, EventArgs e) |
146 | 151 | switch (WindowState) |
147 | 152 | { |
148 | 153 | case WindowState.Minimized: |
| 154 | + SetEfficiencyMode(true); |
149 | 155 | SendToTray(); |
150 | 156 | break; |
151 | 157 | case WindowState.Normal: |
| 158 | + SetEfficiencyMode(false); |
152 | 159 | BringToForeground(); |
153 | 160 | break; |
154 | 161 | } |
@@ -327,7 +334,41 @@ public void SendToTray() |
327 | 334 | if (!_applicationSettings.Store.MinimizeToTray) |
328 | 335 | return; |
329 | 336 |
|
| 337 | + SetEfficiencyMode(true); |
330 | 338 | Hide(); |
331 | 339 | ShowInTaskbar = true; |
332 | 340 | } |
| 341 | + |
| 342 | + private static unsafe void SetEfficiencyMode(bool enabled) |
| 343 | + { |
| 344 | + var ptr = IntPtr.Zero; |
| 345 | + |
| 346 | + try |
| 347 | + { |
| 348 | + var priorityClass = enabled |
| 349 | + ? PROCESS_CREATION_FLAGS.IDLE_PRIORITY_CLASS |
| 350 | + : PROCESS_CREATION_FLAGS.NORMAL_PRIORITY_CLASS; |
| 351 | + PInvoke.SetPriorityClass(PInvoke.GetCurrentProcess(), priorityClass); |
| 352 | + |
| 353 | + var state = new PROCESS_POWER_THROTTLING_STATE |
| 354 | + { |
| 355 | + Version = PInvoke.PROCESS_POWER_THROTTLING_CURRENT_VERSION, |
| 356 | + ControlMask = PInvoke.PROCESS_POWER_THROTTLING_EXECUTION_SPEED, |
| 357 | + StateMask = enabled ? PInvoke.PROCESS_POWER_THROTTLING_EXECUTION_SPEED : 0, |
| 358 | + }; |
| 359 | + |
| 360 | + var size = Marshal.SizeOf<PROCESS_POWER_THROTTLING_STATE>(); |
| 361 | + ptr = Marshal.AllocHGlobal(size); |
| 362 | + Marshal.StructureToPtr(state, ptr, false); |
| 363 | + |
| 364 | + PInvoke.SetProcessInformation(PInvoke.GetCurrentProcess(), |
| 365 | + PROCESS_INFORMATION_CLASS.ProcessPowerThrottling, |
| 366 | + ptr.ToPointer(), |
| 367 | + (uint)size); |
| 368 | + } |
| 369 | + finally |
| 370 | + { |
| 371 | + Marshal.FreeHGlobal(ptr); |
| 372 | + } |
| 373 | + } |
333 | 374 | } |
0 commit comments