Repository navigation
Expand file tree
/
Copy pathSwitchPowerTray.cs
More file actions
3413 lines (2983 loc) · 140 KB
/
Copy pathSwitchPowerTray.cs
File metadata and controls
3413 lines (2983 loc) · 140 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Win32;
static class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr FindWindow(string cls, string title);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childAfter, string cls, string title);
private static bool IsTrayReady()
{
IntPtr taskbar = FindWindow("Shell_TrayWnd", null);
if (taskbar == IntPtr.Zero) return false;
IntPtr tray = FindWindowEx(taskbar, IntPtr.Zero, "TrayNotifyWnd", null);
return tray != IntPtr.Zero;
}
private const string ElevatedTaskName = "SwitchPowerTray Elevated";
internal static bool IsRunningElevated()
{
try
{
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
catch
{
return false;
}
}
private static bool IsElevatedTaskInstalled()
{
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = Path.Combine(Environment.SystemDirectory, "schtasks.exe"),
Arguments = "/Query /TN \"" + ElevatedTaskName + "\" /XML",
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using (Process p = Process.Start(psi))
{
if (p == null) return false;
string xml = p.StandardOutput.ReadToEnd();
p.WaitForExit(5000);
if (p.ExitCode != 0 || string.IsNullOrWhiteSpace(xml)) return false;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode commandNode = doc.SelectSingleNode("//*[local-name()='Command']");
XmlNode argumentsNode = doc.SelectSingleNode("//*[local-name()='Arguments']");
string command = commandNode != null ? (commandNode.InnerText ?? "").Trim() : "";
string arguments = argumentsNode != null ? (argumentsNode.InnerText ?? "").Trim() : "";
string expected = Path.GetFullPath(Application.ExecutablePath).TrimEnd('\\');
string actual = command.Trim().Trim('\"');
bool pointsToThisExe = string.Equals(
Path.GetFullPath(actual).TrimEnd('\\'),
expected,
StringComparison.OrdinalIgnoreCase);
bool launchesElevatedTray =
arguments.IndexOf("/elevated-tray", StringComparison.OrdinalIgnoreCase) >= 0;
// Older builds used a one-time 20-year task. Treat that task
// as stale so the next launch asks once more and upgrades it
// to the permanent ONLOGON task.
bool isLogonTask =
xml.IndexOf("<LogonTrigger", StringComparison.OrdinalIgnoreCase) >= 0;
// The elevated tray task must be explicitly allowed to run on
// battery power and must not stop when AC power is removed.
// Older test registrations can inherit Task Scheduler battery
// conditions that stop the tray exactly when the laptop is
// unplugged. Require the corrected values before trusting the
// persisted task.
XmlNode disallowBatteryNode =
doc.SelectSingleNode("//*[local-name()='DisallowStartIfOnBatteries']");
XmlNode stopOnBatteryNode =
doc.SelectSingleNode("//*[local-name()='StopIfGoingOnBatteries']");
bool disallowStartOnBatteries =
disallowBatteryNode != null &&
string.Equals((disallowBatteryNode.InnerText ?? "").Trim(), "true", StringComparison.OrdinalIgnoreCase);
bool stopIfGoingOnBatteries =
stopOnBatteryNode != null &&
string.Equals((stopOnBatteryNode.InnerText ?? "").Trim(), "true", StringComparison.OrdinalIgnoreCase);
bool batterySafe = !disallowStartOnBatteries && !stopIfGoingOnBatteries;
return pointsToThisExe && launchesElevatedTray && isLogonTask && batterySafe;
}
}
catch
{
return false;
}
}
private static bool DeleteElevatedTask()
{
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = Path.Combine(Environment.SystemDirectory, "schtasks.exe"),
Arguments = "/Delete /TN \"" + ElevatedTaskName + "\" /F",
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using (Process p = Process.Start(psi))
{
if (p == null) return false;
p.WaitForExit(5000);
return p.ExitCode == 0;
}
}
catch
{
return false;
}
}
private static bool RunElevatedTask()
{
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = Path.Combine(Environment.SystemDirectory, "schtasks.exe"),
Arguments = "/Run /TN \"" + ElevatedTaskName + "\"",
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using (Process p = Process.Start(psi))
{
if (p == null) return false;
p.WaitForExit(3000);
return p.ExitCode == 0;
}
}
catch
{
return false;
}
}
private static bool InstallElevatedTask()
{
string exePath = Application.ExecutablePath;
string escapedExe = System.Security.SecurityElement.Escape(exePath);
string workingDirectory = Application.StartupPath;
string escapedWorkingDirectory = System.Security.SecurityElement.Escape(workingDirectory);
try
{
// Register the persistent elevated tray task from explicit XML so
// the task has no AC/battery restrictions. This is important on
// laptops: the tray must continue running when AC is unplugged and
// it must also remain launchable while already on battery power.
string taskXml =
"<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
"<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">" +
"<RegistrationInfo><Description>SwitchPowerTray elevated tray task.</Description></RegistrationInfo>" +
"<Triggers><LogonTrigger><Enabled>true</Enabled></LogonTrigger></Triggers>" +
"<Principals><Principal id=\"Author\">" +
"<UserId>" + System.Security.SecurityElement.Escape(WindowsIdentity.GetCurrent().Name) + "</UserId>" +
"<LogonType>InteractiveToken</LogonType>" +
"<RunLevel>HighestAvailable</RunLevel>" +
"</Principal></Principals>" +
"<Settings>" +
"<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>" +
"<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>" +
"<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>" +
"<AllowHardTerminate>true</AllowHardTerminate>" +
"<StartWhenAvailable>true</StartWhenAvailable>" +
"<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>" +
"<IdleSettings><StopOnIdleEnd>false</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings>" +
"<AllowStartOnDemand>true</AllowStartOnDemand>" +
"<Enabled>true</Enabled>" +
"<Hidden>true</Hidden>" +
"<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>" +
"<Priority>7</Priority>" +
"</Settings>" +
"<Actions Context=\"Author\"><Exec>" +
"<Command>" + escapedExe + "</Command>" +
"<Arguments>/elevated-tray</Arguments>" +
"<WorkingDirectory>" + escapedWorkingDirectory + "</WorkingDirectory>" +
"</Exec></Actions>" +
"</Task>";
string xmlPath = Path.Combine(Path.GetTempPath(), "SwitchPowerTray_ElevatedTask.xml");
File.WriteAllText(xmlPath, taskXml, new UnicodeEncoding(false, true));
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = Path.Combine(Environment.SystemDirectory, "schtasks.exe"),
Arguments =
"/Create" +
" /TN \"" + ElevatedTaskName + "\"" +
" /XML \"" + xmlPath.Replace("\"", "\\\"") + "\"" +
" /F",
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = true,
RedirectStandardError = true
};
using (Process p = Process.Start(psi))
{
if (p == null) return false;
string stdout = p.StandardOutput.ReadToEnd();
string stderr = p.StandardError.ReadToEnd();
p.WaitForExit(5000);
if (p.ExitCode != 0)
{
try
{
File.AppendAllText(
Path.Combine(Path.GetTempPath(), "SwitchPowerTray.log"),
DateTime.Now.ToString("s") +
" ElevationTaskInstall failed: " +
p.ExitCode + " " + stdout + " " + stderr +
Environment.NewLine);
}
catch { }
return false;
}
}
}
finally
{
try { if (File.Exists(xmlPath)) File.Delete(xmlPath); } catch { }
}
return IsElevatedTaskInstalled();
}
catch
{
return false;
}
}
private static void StartElevatedTaskSoon()
{
ThreadPool.QueueUserWorkItem(delegate
{
Thread.Sleep(150);
RunElevatedTask();
});
}
internal static int ApplyEnergySaverPolicyAsElevated(bool enable)
{
const string policyPath = @"SOFTWARE\Policies\Microsoft\Power\EnergySaver";
const string policyValue = "EnableEnergySaver";
try
{
if (enable)
{
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(policyPath, true))
{
if (key == null) return 10;
key.SetValue(policyValue, 1, RegistryValueKind.DWord);
}
}
else
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(policyPath, true))
{
if (key != null)
{
try { key.DeleteValue(policyValue, false); } catch { }
}
}
}
string gpupdate = Path.Combine(Environment.SystemDirectory, "gpupdate.exe");
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = gpupdate,
Arguments = "/target:computer /force /wait:0",
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
};
using (Process p = Process.Start(psi))
{
if (p == null) return 11;
// /wait:0 intentionally means we do not block the tray or the
// special-mode worker while Windows refreshes policy. The
// registry policy write above is already complete, and the
// latest requested mode will be reconciled independently.
return 0;
}
}
catch (UnauthorizedAccessException) { return 5; }
catch (Exception) { return 1; }
}
private static void WaitForExplorerAndTray(int timeoutMs)
{
int start = Environment.TickCount;
while (Process.GetProcessesByName("explorer").Length == 0)
{
if (Environment.TickCount - start > timeoutMs) break;
Thread.Sleep(300);
}
while (!IsTrayReady())
{
if (Environment.TickCount - start > timeoutMs) break;
Thread.Sleep(300);
}
}
private static void ManageLogFile()
{
try
{
string logPath = Path.Combine(Path.GetTempPath(), "SwitchPowerTray.log");
if (File.Exists(logPath))
{
long length = new FileInfo(logPath).Length;
if (length > 1024 * 1024) // If larger than 1 MB
{
File.Copy(logPath, logPath + ".old", true);
File.Delete(logPath);
}
}
}
catch { }
}
[STAThread]
static void Main(string[] args)
{
// This executable also acts as a tiny elevated helper. The normal tray
// process stays unelevated; only the machine-level Energy Saver policy
// change is relaunched with the UAC "runas" verb.
if (args != null && args.Length >= 1 &&
string.Equals(args[0], "/install-elevated", StringComparison.OrdinalIgnoreCase))
{
bool installed = InstallElevatedTask();
if (installed)
{
// We are already elevated because this branch was launched
// through UAC. Start the tray directly from this elevated
// process instead of asking Task Scheduler to launch it and
// then exiting. This guarantees the very first launch shows
// the tray immediately and avoids a second UAC prompt.
try
{
ProcessStartInfo trayPsi = new ProcessStartInfo
{
FileName = Application.ExecutablePath,
Arguments = "/elevated-tray",
UseShellExecute = false,
WorkingDirectory = Application.StartupPath
};
Process.Start(trayPsi);
}
catch { }
}
Environment.ExitCode = installed ? 0 : 1;
return;
}
if (args != null && args.Length >= 2 &&
string.Equals(args[0], "/elevated-energy-policy", StringComparison.OrdinalIgnoreCase))
{
int rc = ApplyEnergySaverPolicyAsElevated(
string.Equals(args[1], "enable", StringComparison.OrdinalIgnoreCase));
Environment.ExitCode = rc;
return;
}
bool elevated = IsRunningElevated();
if (args == null || args.Length == 0 ||
(!string.Equals(args[0], "/elevated-tray", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(args[0], "/elevated-energy-policy", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(args[0], "/install-elevated", StringComparison.OrdinalIgnoreCase)))
{
if (!elevated)
{
bool taskInstalledForThisExe = IsElevatedTaskInstalled();
if (taskInstalledForThisExe)
{
// The persisted task must point to THIS executable.
// Older test builds may have left a task pointing at a
// previous EXE, which otherwise makes the launcher exit
// without ever showing the tray.
if (RunElevatedTask())
return;
DeleteElevatedTask();
}
DialogResult answer = MessageBox.Show(
"Switch Power Plan Tray can be configured to run with administrator privileges automatically on future launches.\r\n\r\n" +
"This requires one administrator approval now. After approval, Windows Task Scheduler will start the app elevated without asking every time.\r\n\r\n" +
"Install this one-time elevated startup?",
"Switch Power Plan Tray",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (answer == DialogResult.Yes)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = Application.ExecutablePath,
Arguments = "/install-elevated",
UseShellExecute = true,
Verb = "runas",
WorkingDirectory = Application.StartupPath
};
using (Process p = Process.Start(psi))
{
if (p != null)
p.WaitForExit(20000);
}
}
catch
{
// UAC canceled or elevation failed. Continue below
// in normal mode so the tray remains usable.
}
if (IsElevatedTaskInstalled())
{
StartElevatedTaskSoon();
return;
}
}
}
}
bool createdNew;
using (Mutex mutex = new Mutex(true, "Global\\SwitchPowerTray_SingleInstanceMutex", out createdNew))
{
if (!createdNew)
{
// App is already running, exit silently
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ManageLogFile();
// Global shutdown guards
SystemEvents.SessionEnding += (s, e) => TrayContext.BeginShutdown("Program.SessionEnding");
SystemEvents.SessionEnded += (s, e) => TrayContext.BeginShutdown("Program.SessionEnded");
AppDomain.CurrentDomain.ProcessExit += (s, e) => TrayContext.BeginShutdown("Program.ProcessExit");
Application.ThreadException += (s, e) => TrayContext.LogAndShow("ThreadException", e.Exception);
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
TrayContext.LogAndShow("UnhandledException", e.ExceptionObject as Exception);
try
{
WaitForExplorerAndTray(7000);
bool debug = (args.Length > 0 && string.Equals(args[0], "/debug", StringComparison.OrdinalIgnoreCase));
Application.Run(new TrayContext(debug));
}
catch (Exception ex)
{
TrayContext.LogAndShow("MainCatch", ex);
}
}
}
}
public sealed class TrayContext : ApplicationContext
{
// === PowrProf interop ===
private const uint ACCESS_SCHEME = 16;
private const uint ERROR_NO_MORE_ITEMS = 259;
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerEnumerate(IntPtr RootPowerKey, IntPtr SchemeGuid, IntPtr SubGroupOfPowerSettingsGuid, uint AccessFlags, uint Index, IntPtr Buffer, ref uint BufferSize);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerReadFriendlyName(IntPtr RootPowerKey, ref Guid SchemeGuid, IntPtr SubGroupOfPowerSettingsGuid, IntPtr PowerSettingGuid, IntPtr Buffer, ref uint BufferSize);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerGetActiveScheme(IntPtr UserRootPowerKey, out IntPtr ActivePolicyGuid);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerSetActiveScheme(IntPtr UserRootPowerKey, ref Guid SchemeGuid);
[DllImport("powrprof.dll")]
private static extern uint PowerRegisterForEffectivePowerModeNotifications(uint Version, EffectivePowerModeCallback Callback, IntPtr Context, out IntPtr RegistrationHandle);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerSetUserConfiguredACPowerMode(ref Guid PowerModeGuid);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerSetUserConfiguredDCPowerMode(ref Guid PowerModeGuid);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerGetUserConfiguredACPowerMode(out Guid PowerModeGuid);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerGetUserConfiguredDCPowerMode(out Guid PowerModeGuid);
[DllImport("powrprof.dll")]
private static extern uint PowerUnregisterFromEffectivePowerModeNotifications(IntPtr RegistrationHandle);
private delegate void EffectivePowerModeCallback(int Mode, IntPtr Context);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerReadACValueIndex(IntPtr RootPowerKey, ref Guid SchemeGuid, ref Guid SubGroupOfPowerSettingsGuid, ref Guid PowerSettingGuid, out uint AcValueIndex);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerReadDCValueIndex(IntPtr RootPowerKey, ref Guid SchemeGuid, ref Guid SubGroupOfPowerSettingsGuid, ref Guid PowerSettingGuid, out uint DcValueIndex);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerWriteACValueIndex(IntPtr RootPowerKey, ref Guid SchemeGuid, ref Guid SubGroupOfPowerSettingsGuid, ref Guid PowerSettingGuid, uint AcValueIndex);
[DllImport("powrprof.dll", SetLastError = true)]
private static extern uint PowerWriteDCValueIndex(IntPtr RootPowerKey, ref Guid SchemeGuid, ref Guid SubGroupOfPowerSettingsGuid, ref Guid PowerSettingGuid, uint DcValueIndex);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr hMem);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool DestroyIcon(IntPtr hIcon);
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll") ]
private static extern bool IsWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool LockWorkStation();
[DllImport("powrprof.dll", SetLastError = true)]
private static extern bool SetSuspendState(bool Hibernate, bool ForceCritical, bool DisableWakeEvent);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessageTimeout(
IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam,
uint flags, uint timeout, out UIntPtr result);
// Subgroup + setting GUIDs
private static readonly Guid SUB_BUTTONS = new Guid("4f971e89-eebd-4455-a8de-9e59040e7347");
private static readonly Guid SET_PBUTTON = new Guid("7648efa3-dd9c-4e3e-b566-50f929386280");
private static readonly Guid SET_SBUTTON = new Guid("96996bc0-ad50-47ec-923b-6f41874dd9eb");
private static readonly Guid SET_LID = new Guid("5ca83367-6e45-459f-a27b-476b1d01c936");
private static readonly Guid SUB_VIDEO = new Guid("7516b95f-f776-4464-8c53-06167f40cc99");
private static readonly Guid SUB_SLEEP = new Guid("238c9fa8-0aad-41ed-83f4-97be242c8f20");
private static readonly Guid SET_VIDEOIDLE = new Guid("3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e");
private static readonly Guid SET_VIDEOCONLOCK = new Guid("8ec4b3a5-6868-48c2-be75-4f3044be88a7");
private static readonly Guid SET_SLEEPIDLE = new Guid("29f6c1db-86da-48c5-9fdb-f2b67b1f44da");
private static readonly Guid SET_HIBERNATEIDLE = new Guid("9d7815a6-7ee4-497e-8888-515a05f02364");
private static readonly Guid SET_UNATTENDSLEEP = new Guid("7bc4a2f9-d8fc-4469-b07b-33eb785aaca0");
// Managed built-in power schemes created by SwitchPowerTray when missing.
// These GUIDs are deterministic for the app so re-launches never create duplicates.
private static readonly Guid MANAGED_ALWAYS_ON = new Guid("03b25512-e812-45ae-b15f-f3d257f19bd6");
private static readonly Guid MANAGED_DESKTOP_DOCK = new Guid("a30c6ddc-23dc-43cb-9a36-90a07ae999e8");
private static readonly Guid MANAGED_LAPTOP = new Guid("c9500eed-7461-4557-ac04-efda065f31b0");
private static readonly Guid MANAGED_ENERGY_SAVING = new Guid("9e437415-0f01-4df6-8e22-ed7575fac4b3");
private static readonly Guid MANAGED_BALANCED = new Guid("8ff9a948-64f6-4079-ad16-189978fb39f2");
private static readonly Guid MANAGED_MOON = new Guid("14a99604-09ee-4ad7-9e04-6839239ac89d");
private static readonly Guid WINDOWS_BALANCED_TEMPLATE = new Guid("381b4222-f694-41f0-9685-ff5bb260df2e");
private static readonly Guid POWER_MODE_BEST_EFFICIENCY = new Guid("961cc777-2547-4f9d-8174-7d86181b8a7a");
private static readonly Guid POWER_MODE_BALANCED = Guid.Empty;
private enum ButtonLidAction : uint { DoNothing = 0, Sleep = 1, Hibernate = 2, Shutdown = 3 }
private enum UiLanguage { English, Spanish }
private UiLanguage uiLanguage = UiLanguage.English;
private bool languageLoadedFromConfig = false;
private string L(string en, string es) { return (uiLanguage == UiLanguage.Spanish ? es : en); }
private const string RES_DESKTOP_DARK = "Icon.Desktop.Dark.ico";
private const string RES_DESKTOP_LIGHT = "Icon.Desktop.Light.ico";
private const string RES_LAPTOP_DARK = "Icon.Laptop.Dark.ico";
private const string RES_LAPTOP_LIGHT = "Icon.Laptop.Light.ico";
private const string RES_BOLT_DARK = "Icon.Bolt.Dark.ico";
private const string RES_BOLT_LIGHT = "Icon.Bolt.Light.ico";
private const string RES_BOLT_ACTIVE_DARK = "Icon.BoltActive.Dark.ico";
private const string RES_BOLT_ACTIVE_LIGHT = "Icon.BoltActive.Light.ico";
private const string RES_MOON_DARK = "Icon.Moon.Dark.ico";
private const string RES_MOON_LIGHT = "Icon.Moon.Light.ico";
private const string RES_BALANCED_DARK = "Icon.Balanced.Dark.ico";
private const string RES_BALANCED_LIGHT = "Icon.Balanced.Light.ico";
private const string RES_ENERGYSAVE_DARK = "Icon.EnergySave.Dark.ico";
private const string RES_ENERGYSAVE_LIGHT = "Icon.EnergySave.Light.ico";
internal const string AppId = "SwitchPowerTray";
internal const string ShortcutName = "Switch Power Plan Tray.lnk";
private static readonly string ConfigDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SwitchPowerTray");
private static readonly string ConfigPath = Path.Combine(ConfigDir, "config.txt");
private static readonly string LogPath = Path.Combine(Path.GetTempPath(), "SwitchPowerTray.log");
private readonly NotifyIcon tray;
private readonly bool debug;
private static volatile bool _blockLaunch = false;
private enum IconSet { Auto, Light, Dark }
private IconSet iconSetPref = IconSet.Auto;
private sealed class SlotConfig
{
public char Key;
public string Guid = "";
public string LightIconPath = "";
public string DarkIconPath = "";
// Whether this slot participates in left-click Toggle cycling.
// Legacy configurations default to true to preserve existing behavior.
public bool CycleEnabled = true;
}
private readonly SortedDictionary<char, SlotConfig> slots = new SortedDictionary<char, SlotConfig>();
private Icon exeIcon, lastIcon;
private readonly Dictionary<string, Icon> icons = new Dictionary<string, Icon>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, Icon> fileIcons = new Dictionary<string, Icon>(StringComparer.OrdinalIgnoreCase);
private enum TemporaryAlwaysOnTrigger { Window, Process }
private enum TemporaryEndAction { ReturnToSlot, Lock, Sleep, Hibernate, ShutDown, Restart, Nothing }
private sealed class WindowTarget
{
public IntPtr Handle;
public int ProcessId;
public string Title;
public string ProcessName;
public string Display;
public override string ToString() { return Display; }
}
private sealed class ProcessTarget
{
public int ProcessId;
public string ProcessName;
public string Display;
public override string ToString() { return Display; }
}
private bool _temporaryAlwaysOnActive;
private TemporaryAlwaysOnTrigger _temporaryTrigger;
private IntPtr _temporaryWindowHandle = IntPtr.Zero;
private int _temporaryProcessId;
private string _temporaryReturnGuid = "";
private char _temporaryReturnSlot = '\0';
private TemporaryEndAction _temporaryEndAction = TemporaryEndAction.ReturnToSlot;
private string _temporaryTriggerDescription = "";
private System.Windows.Forms.Timer _temporaryAlwaysOnTimer;
private string activeGuid = "";
private List<Plan> plans = new List<Plan>();
private sealed class Plan
{
public string Guid;
public string Name;
public bool IsActive;
public override string ToString() { return Name + " (" + Guid + (IsActive ? ", Active" : "") + ")"; }
}
private struct AssignTagDynamic
{
public char SlotKey;
public string Guid;
public AssignTagDynamic(char s, string g) { SlotKey = s; Guid = g; }
}
private bool _busy;
private ContextMenuStrip _openContextMenu;
// User-configured Windows 11 Power Mode values saved when entering
// Energy Saving, so leaving the mode can restore the previous user choice.
private Guid _savedAcPowerMode = Guid.Empty;
private Guid _savedDcPowerMode = Guid.Empty;
private bool _savedPowerModesForEnergyMode;
private readonly object _specialModeLock = new object();
private bool _specialModeWorkerRunning;
private bool _specialModeRequestPending;
private bool _nightLightEnabledByApp;
private IntPtr powerNotifyHandle = IntPtr.Zero;
private EffectivePowerModeCallback _powerModeCallback;
private readonly Control _syncControl;
// === Event Watchers ===
private sealed class SystemEventWatcher : NativeWindow, IDisposable
{
private const int WM_SETTINGCHANGE = 0x001A;
private readonly Action _onThemeChange;
private readonly Action _onTaskbarCreated;
private readonly uint _wmTaskbarCreated;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern uint RegisterWindowMessage(string lpString);
public SystemEventWatcher(Action onThemeChange, Action onTaskbarCreated)
{
CreateHandle(new CreateParams());
_onThemeChange = onThemeChange;
_onTaskbarCreated = onTaskbarCreated;
_wmTaskbarCreated = RegisterWindowMessage("TaskbarCreated");
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_SETTINGCHANGE && m.LParam != IntPtr.Zero)
{
string area = Marshal.PtrToStringUni(m.LParam);
if (area == "ImmersiveColorSet" && _onThemeChange != null) _onThemeChange();
}
else if (m.Msg == _wmTaskbarCreated && _wmTaskbarCreated != 0)
{
if (_onTaskbarCreated != null) _onTaskbarCreated();
}
base.WndProc(ref m);
}
public void Dispose()
{
if (Handle != IntPtr.Zero) DestroyHandle();
}
}
private sealed class EndSessionWatcher : NativeWindow, IDisposable
{
private const int WM_QUERYENDSESSION = 0x0011;
private const int WM_ENDSESSION = 0x0016;
public EndSessionWatcher() { CreateHandle(new CreateParams()); }
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_QUERYENDSESSION || m.Msg == WM_ENDSESSION) TrayContext.BeginShutdown("WM_ENDSESSION");
base.WndProc(ref m);
}
public void Dispose() { try { if (this.Handle != IntPtr.Zero) this.DestroyHandle(); } catch { } }
}
private SystemEventWatcher themeWatcher;
private EndSessionWatcher endWatcher;
public TrayContext(bool debugMode)
{
debug = debugMode;
try { exeIcon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); }
catch { exeIcon = SystemIcons.Application; }
LoadAllIcons();
LoadConfig();
EnsureDefaultSlots();
EnsureBuiltInPowerSchemes();
DetectLanguageIfNotSet();
tray = new NotifyIcon();
tray.Visible = false;
tray.Text = L("Switch Power Plan", "Cambiar plan de energía");
tray.ContextMenuStrip = BuildMenu();
tray.MouseClick += OnTrayMouseClick;
endWatcher = new EndSessionWatcher();
themeWatcher = new SystemEventWatcher(
() => { if (iconSetPref == IconSet.Auto) UpdateTrayIcon(); },
() => { try { if (tray != null) { tray.Visible = false; tray.Visible = true; UpdateTrayIcon(); } } catch { } }
);
// Create an invisible dummy control to handle thread marshalling
_syncControl = new Control();
IntPtr forceHandle = _syncControl.Handle; // Force the OS handle to be created
// Store the delegate in the class variable to prevent Garbage Collection
_powerModeCallback = delegate (int mode, IntPtr ctx)
{
try
{
// Safely marshal the background notification to the main UI thread
_syncControl.BeginInvoke(new Action(delegate ()
{
activeGuid = GetActiveSchemeGuid();
RefreshPlansAndIcon();
QueueSpecialModeReconcile();
}));
}
catch { }
};
// Register the safe callback
PowerRegisterForEffectivePowerModeNotifications(1, _powerModeCallback, IntPtr.Zero, out powerNotifyHandle);
for (int i = 0; i < 5; i++)
{
RefreshPlansAndIcon();
if (!string.IsNullOrEmpty(activeGuid)) break;
Thread.Sleep(250);
}
// Reconcile special Windows integrations in the background so startup
// cannot be blocked by UAC, gpupdate, or CloudStore work.
QueueSpecialModeReconcile();
tray.Visible = true;
SystemEvents.SessionEnding += (s, e) => { BeginShutdown("Context.SessionEnding"); };
SystemEvents.SessionEnded += (s, e) => { BeginShutdown("Context.SessionEnded"); };
Application.ApplicationExit += (s, e) => { BeginShutdown("Context.ApplicationExit"); };
}
private void EnsureDefaultSlots()
{
if (!slots.ContainsKey('A')) slots['A'] = new SlotConfig { Key = 'A' };
if (!slots.ContainsKey('B')) slots['B'] = new SlotConfig { Key = 'B' };
if (!slots.ContainsKey('C')) slots['C'] = new SlotConfig { Key = 'C' };
if (!slots.ContainsKey('D')) slots['D'] = new SlotConfig { Key = 'D' };
if (!slots.ContainsKey('E')) slots['E'] = new SlotConfig { Key = 'E' };
if (!slots.ContainsKey('F')) slots['F'] = new SlotConfig { Key = 'F' };
}
private void EnsureBuiltInPowerSchemes()
{
try
{
// Balanced is the first template. If Windows' standard Balanced scheme
// is missing, create a replacement Balanced scheme from any available
// scheme and keep its generated/fixed GUID under our control.
plans = ListPlans();
string balancedGuid = EnsureManagedPlan(
"Balanced",
MANAGED_BALANCED,
WINDOWS_BALANCED_TEMPLATE,
"Balanced power plan managed by SwitchPowerTray.",
null);
if (string.IsNullOrEmpty(balancedGuid))
return;
// Create/locate the five companion modes. Existing plans with the
// requested names are never reconfigured; only newly created plans
// receive the layouts below.
string alwaysOn = EnsureManagedPlan(
"Always On",
MANAGED_ALWAYS_ON,
Guid.Parse(balancedGuid),
"Keeps the computer and display on until the user changes power settings.",
ConfigureAlwaysOnPlan);
string dock = EnsureManagedPlan(
"Desktop Docking Station",
MANAGED_DESKTOP_DOCK,
Guid.Parse(balancedGuid),
"Docked desktop-style mode: closing the lid does not sleep or hibernate.",
ConfigureDesktopDockPlan);
string laptop = EnsureManagedPlan(
"Laptop On The Go",
MANAGED_LAPTOP,
Guid.Parse(balancedGuid),
"Portable laptop mode with hibernation-oriented lid and power behavior.",
ConfigureLaptopPlan);
string energy = EnsureManagedPlan(
"Energy Saving",
MANAGED_ENERGY_SAVING,
Guid.Parse(balancedGuid),
"Power-saving mode with shorter idle timers and energy saver behavior.",
ConfigureEnergySavingPlan);
string moon = EnsureManagedPlan(
"Night",
MANAGED_MOON,
Guid.Parse(balancedGuid),
"Night mode: turns off the display after 2.5 minutes of inactivity and enables Night light when supported.",
ConfigureMoonPlan);
AssignManagedSchemeToSlot('A', dock);
AssignManagedSchemeToSlot('B', laptop);
AssignManagedSchemeToSlot('C', alwaysOn);
AssignManagedSchemeToSlot('D', moon);
AssignManagedSchemeToSlot('E', balancedGuid);
AssignManagedSchemeToSlot('F', energy);
SaveConfig();
EnsurePlanList();
}
catch (Exception ex)
{
try { File.AppendAllText(LogPath, DateTime.Now.ToString("s") + " EnsureBuiltInPowerSchemes: " + ex + Environment.NewLine); } catch { }
}
}
private delegate void NewPlanConfigurator(Guid scheme);
private string EnsureManagedPlan(string desiredName, Guid managedGuid, Guid preferredTemplate,
string description, NewPlanConfigurator configurator)
{
List<Plan> currentPlans = ListPlans();
foreach (Plan p in currentPlans)
{
if (string.Equals(p.Name, desiredName, StringComparison.OrdinalIgnoreCase))
return p.Guid;
}
Guid template = preferredTemplate;
bool templateExists = false;
foreach (Plan p in currentPlans)
{
if (string.Equals(p.Guid, template.ToString(), StringComparison.OrdinalIgnoreCase))
{
templateExists = true;
break;
}
}
if (!templateExists)
{
// For Balanced only, the Windows standard GUID may be unavailable.
// Fall back to the first scheme that exists.
if (string.Equals(desiredName, "Balanced", StringComparison.OrdinalIgnoreCase) && currentPlans.Count > 0)
{
template = Guid.Parse(currentPlans[0].Guid);
templateExists = true;
}
}
if (!templateExists)
return "";
// If our managed GUID already exists, use it as-is. This is useful after
// an interrupted startup where duplication completed but naming did not.
foreach (Plan p in currentPlans)