-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1292 lines (1154 loc) · 44.1 KB
/
Copy pathProgram.cs
File metadata and controls
1292 lines (1154 loc) · 44.1 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
// LEDder - ThinkPad LED control (.NET 8 WinForms port)
//
// BUILD: dotnet build -c Release
// SILENT: LEDder.exe --silent (or config SilentOnLaunch=true)
//
// WinRing0x64.dll AND WinRing0x64.sys must be next to the .exe.
// App self-elevates via UAC on first launch.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;
namespace LEDder;
// ============================================================
// Entry point
// ============================================================
internal static class Program
{
public const string AppTitle = "LEDder \u2013 ThinkPad LED control";
[STAThread]
static void Main(string[] args)
{
bool cliSilent = args.Any(a =>
a.Equals("--silent", StringComparison.OrdinalIgnoreCase) ||
a.Equals("-s", StringComparison.OrdinalIgnoreCase) ||
a.Equals("/silent", StringComparison.OrdinalIgnoreCase));
if (!IsAdmin())
{
try
{
var psi = new ProcessStartInfo
{
FileName = Environment.ProcessPath ?? Application.ExecutablePath,
UseShellExecute = true,
Verb = "runas",
Arguments = cliSilent ? "--silent" : "",
};
Process.Start(psi);
}
catch
{
MessageBox.Show("This app must run as Administrator.",
AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var exeDir = Path.GetDirectoryName(Environment.ProcessPath ?? "")!;
if (!File.Exists(Path.Combine(exeDir, "WinRing0x64.dll")) ||
!File.Exists(Path.Combine(exeDir, "WinRing0x64.sys")))
{
MessageBox.Show(
$"WinRing0x64.dll and WinRing0x64.sys must be in:\n\n{exeDir}\n\n" +
"Copy both files there and retry.",
AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try { Ec.Initialize(); }
catch (Exception e)
{
MessageBox.Show(
$"WinRing0 driver failed to load:\n\n{e.Message}\n\n" +
"Common causes:\n" +
" \u2022 HVCI / Memory Integrity enabled\n" +
" \u2022 Defender blocked the driver\n" +
" \u2022 Unsigned / old WinRing0 build",
AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AudioMute.Initialize();
try
{
var form = new MainForm { StartHidden = cliSilent };
Application.Run(form);
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), AppTitle,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally { Ec.Shutdown(); }
}
static bool IsAdmin()
{
using var identity = WindowsIdentity.GetCurrent();
return new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator);
}
}
// ============================================================
// Style palette
// ============================================================
internal static class Style
{
// palette
public static readonly Color Bg = Color.FromArgb(244, 245, 247);
public static readonly Color Panel = Color.White;
public static readonly Color Border = Color.FromArgb(224, 226, 230);
public static readonly Color BorderHover = Color.FromArgb(180, 183, 188);
public static readonly Color TextPrimary = Color.FromArgb(28, 28, 32);
public static readonly Color TextMuted = Color.FromArgb(120, 120, 128);
public static readonly Color Accent = Color.FromArgb(0, 113, 227);
public static readonly Color StatusOn = Color.FromArgb(48, 164, 80);
public static readonly Color StatusAlert = Color.FromArgb(220, 52, 50);
public static readonly Color BtnBg = Color.FromArgb(250, 250, 252);
public static readonly Color BtnHover = Color.FromArgb(235, 236, 240);
public static readonly Color BtnPressed = Color.FromArgb(220, 222, 227);
// typography
public static readonly Font Body = new("Segoe UI", 9f);
public static readonly Font Header = new("Segoe UI Semibold", 10f);
public static readonly Font Mono = new("Consolas", 9f);
public static readonly Font AppName = new("Segoe UI Semibold", 11f);
/// <summary>Creates a bordered white panel with a header label at top.</summary>
public static Panel MakeSection(string title, out int contentTopY)
{
const int HEADER_H = 34;
contentTopY = HEADER_H;
var p = new Panel
{
BackColor = Panel,
};
p.Paint += (_, e) =>
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using var pen = new Pen(Border, 1);
e.Graphics.DrawRectangle(pen, 0, 0, p.Width - 1, p.Height - 1);
};
var hdr = new Label
{
Text = title,
Location = new Point(12, 9),
AutoSize = true,
Font = Header,
ForeColor = TextPrimary,
BackColor = Color.Transparent,
};
p.Controls.Add(hdr);
// subtle separator under header
var sep = new Label
{
BackColor = Border,
Location = new Point(1, HEADER_H - 1),
Size = new Size(1, 1), // will be resized in Layout event
};
p.Controls.Add(sep);
p.Layout += (_, _) => sep.Size = new Size(p.Width - 2, 1);
return p;
}
public static Button FlatButton(string text, int x, int y, int w, int h, Action click)
{
var b = new Button
{
Text = text,
Location = new Point(x, y),
Size = new Size(w, h),
FlatStyle = FlatStyle.Flat,
BackColor = BtnBg,
ForeColor = TextPrimary,
Font = Body,
Cursor = Cursors.Hand,
UseVisualStyleBackColor = false,
};
b.FlatAppearance.BorderColor = Border;
b.FlatAppearance.BorderSize = 1;
b.FlatAppearance.MouseOverBackColor = BtnHover;
b.FlatAppearance.MouseDownBackColor = BtnPressed;
b.Click += (_, _) => click();
return b;
}
}
// ============================================================
// EC protocol via WinRing0
// ============================================================
internal static class Ec
{
const ushort EC_DATAPORT = 0x62;
const ushort EC_CTRLPORT = 0x66;
const byte EC_STAT_OBF = 0x01;
const byte EC_STAT_IBF = 0x02;
const byte EC_CTRLPORT_READ = 0x80;
const byte EC_CTRLPORT_WRITE = 0x81;
public const byte TP_LED_OFFSET = 0x0C;
public const byte KBD_LIGHT_OFFSET = 0x0D;
public const byte POWER_ON = 0x80;
public const byte POWER_OFF = 0x00;
public const byte POWER_BLINK = 0xC0;
public const byte KBD_OFF = 0x00;
public const byte KBD_LOW = 0x40;
public const byte KBD_HIGH = 0x80;
[DllImport("WinRing0x64.dll")] static extern bool InitializeOls();
[DllImport("WinRing0x64.dll")] static extern uint GetDllStatus();
[DllImport("WinRing0x64.dll")] static extern void DeinitializeOls();
[DllImport("WinRing0x64.dll")] static extern byte ReadIoPortByte(ushort port);
[DllImport("WinRing0x64.dll")] static extern void WriteIoPortByte(ushort port, byte value);
static bool initialized;
public static void Initialize()
{
if (initialized) return;
bool ok = InitializeOls();
uint status = GetDllStatus();
if (!ok || status != 0)
throw new InvalidOperationException(
$"InitializeOls={ok}, GetDllStatus={status}");
initialized = true;
}
public static void Shutdown()
{
if (!initialized) return;
try { DeinitializeOls(); } catch { }
initialized = false;
}
static void WaitPort(byte bits, bool wantSet, int timeoutMs = 1000)
{
int elapsed = 0;
while (elapsed < timeoutMs)
{
byte data = ReadIoPortByte(EC_CTRLPORT);
if (((data & bits) != 0) == wantSet) return;
System.Threading.Thread.Sleep(10);
elapsed += 10;
}
}
public static void WriteByte(byte offset, byte value)
{
WaitPort((byte)(EC_STAT_IBF | EC_STAT_OBF), false);
WriteIoPortByte(EC_CTRLPORT, EC_CTRLPORT_WRITE);
WaitPort(EC_STAT_IBF, false);
WriteIoPortByte(EC_DATAPORT, offset);
WaitPort(EC_STAT_IBF, false);
WriteIoPortByte(EC_DATAPORT, value);
WaitPort(EC_STAT_IBF, false);
}
public static byte ReadByte(byte offset)
{
WaitPort((byte)(EC_STAT_IBF | EC_STAT_OBF), false);
WriteIoPortByte(EC_CTRLPORT, EC_CTRLPORT_READ);
WaitPort(EC_STAT_IBF, false);
WriteIoPortByte(EC_DATAPORT, offset);
WaitPort(EC_STAT_IBF, false);
return ReadIoPortByte(EC_DATAPORT);
}
public static void SetLed(byte ledId, byte powerBits)
=> WriteByte(TP_LED_OFFSET, (byte)(ledId | powerBits));
public static void SetKbdLight(byte level) => WriteByte(KBD_LIGHT_OFFSET, level);
public static byte GetKbdLightRaw() => ReadByte(KBD_LIGHT_OFFSET);
public static byte KbdRawToLevel(byte raw)
{
if (raw < 50) return KBD_OFF;
if (raw < 100) return KBD_LOW;
if (raw < 150) return KBD_HIGH;
return KBD_OFF;
}
public static string KbdLevelName(byte level) => level switch
{
KBD_OFF => "Off",
KBD_LOW => "Low",
KBD_HIGH => "High",
_ => $"0x{level:X2}",
};
}
// ============================================================
// Win32 interop
// ============================================================
internal static class Win32
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT { public int Left, Top, Right, Bottom; }
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
[DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")] public static extern short GetKeyState(int vKey);
const int SM_CXSCREEN = 0;
const int SM_CYSCREEN = 1;
const int VK_CAPITAL = 0x14;
const int VK_NUMLOCK = 0x90;
public static bool IsCapsLockOn() => (GetKeyState(VK_CAPITAL) & 0x0001) != 0;
public static bool IsNumLockOn() => (GetKeyState(VK_NUMLOCK) & 0x0001) != 0;
public static string GetForegroundTitle()
{
var hwnd = GetForegroundWindow();
if (hwnd == IntPtr.Zero) return "";
int len = GetWindowTextLength(hwnd);
var sb = new StringBuilder(len + 1);
GetWindowText(hwnd, sb, sb.Capacity);
return sb.ToString();
}
public static bool IsForegroundFullscreen()
{
var hwnd = GetForegroundWindow();
if (hwnd == IntPtr.Zero) return false;
var title = GetForegroundTitle();
if (title is "" or "Windows Default Lock Screen" or "Program Manager")
return false;
if (!GetWindowRect(hwnd, out RECT rect)) return false;
int w = GetSystemMetrics(SM_CXSCREEN);
int h = GetSystemMetrics(SM_CYSCREEN);
return rect.Left <= 0 && rect.Top <= 0
&& rect.Right >= w && rect.Bottom >= h;
}
}
// ============================================================
// Core Audio COM interop
// ============================================================
internal static class AudioMute
{
static IAudioEndpointVolume? speakerVol;
static IAudioEndpointVolume? micVol;
public static string? InitError { get; private set; }
public static void Initialize()
{
try
{
var enumType = Type.GetTypeFromCLSID(
new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"));
if (enumType == null) { InitError = "MMDeviceEnumerator CLSID not registered"; return; }
var enumObj = Activator.CreateInstance(enumType);
if (enumObj is not IMMDeviceEnumerator enumerator)
{ InitError = "CoCreateInstance returned null"; return; }
var iid = typeof(IAudioEndpointVolume).GUID;
try
{
int hr = enumerator.GetDefaultAudioEndpoint(
EDataFlow.eRender, ERole.eMultimedia, out var dev);
if (hr == 0 && dev != null)
{
hr = dev.Activate(ref iid, 0x17, IntPtr.Zero, out object obj);
if (hr == 0) speakerVol = (IAudioEndpointVolume)obj;
}
}
catch (Exception e) { InitError = $"speaker: {e.Message}"; }
try
{
int hr = enumerator.GetDefaultAudioEndpoint(
EDataFlow.eCapture, ERole.eMultimedia, out var dev);
if (hr == 0 && dev != null)
{
hr = dev.Activate(ref iid, 0x17, IntPtr.Zero, out object obj);
if (hr == 0) micVol = (IAudioEndpointVolume)obj;
}
}
catch (Exception e) { InitError ??= $"mic: {e.Message}"; }
}
catch (Exception e) { InitError = $"COM init: {e.Message}"; }
}
public static bool? SpeakerMuted()
{
if (speakerVol == null) return null;
try { speakerVol.GetMute(out bool m); return m; } catch { return null; }
}
public static bool? MicMuted()
{
if (micVol == null) return null;
try { micVol.GetMute(out bool m); return m; } catch { return null; }
}
enum EDataFlow { eRender, eCapture, eAll, EDataFlow_enum_count }
enum ERole { eConsole, eMultimedia, eCommunications, ERole_enum_count }
[ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
int EnumAudioEndpoints(EDataFlow dataFlow, uint dwStateMask, out IntPtr ppDevices);
int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppEndpoint);
int GetDevice([MarshalAs(UnmanagedType.LPWStr)] string pwstrId, out IMMDevice ppDevice);
int RegisterEndpointNotificationCallback(IntPtr pClient);
int UnregisterEndpointNotificationCallback(IntPtr pClient);
}
[ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
int Activate(ref Guid iid, uint dwClsCtx, IntPtr pActivationParams,
[MarshalAs(UnmanagedType.IUnknown)] out object ppInterface);
int OpenPropertyStore(uint stgmAccess, out IntPtr ppProperties);
int GetId([MarshalAs(UnmanagedType.LPWStr)] out string ppstrId);
int GetState(out uint pdwState);
}
[ComImport, Guid("5CDF2C82-841E-4546-9722-0CF74078229A"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
int RegisterControlChangeNotify(IntPtr pNotify);
int UnregisterControlChangeNotify(IntPtr pNotify);
int GetChannelCount(out uint pnChannelCount);
int SetMasterVolumeLevel(float fLevelDB, ref Guid pguidEventContext);
int SetMasterVolumeLevelScalar(float fLevel, ref Guid pguidEventContext);
int GetMasterVolumeLevel(out float pfLevelDB);
int GetMasterVolumeLevelScalar(out float pfLevel);
int SetChannelVolumeLevel(uint nChannel, float fLevelDB, ref Guid pguidEventContext);
int SetChannelVolumeLevelScalar(uint nChannel, float fLevel, ref Guid pguidEventContext);
int GetChannelVolumeLevel(uint nChannel, out float pfLevelDB);
int GetChannelVolumeLevelScalar(uint nChannel, out float pfLevel);
int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, ref Guid pguidEventContext);
int GetMute([MarshalAs(UnmanagedType.Bool)] out bool pbMute);
int GetVolumeStepInfo(out uint pnStep, out uint pnStepCount);
int VolumeStepUp(ref Guid pguidEventContext);
int VolumeStepDown(ref Guid pguidEventContext);
int QueryHardwareSupport(out uint pdwHardwareSupportMask);
int GetVolumeRange(out float pflVolumeMindB, out float pflVolumeMaxdB, out float pflVolumeIncrementdB);
}
}
// ============================================================
// Config
// ============================================================
public class Config
{
public bool MonitorEnabled { get; set; } = false;
public bool SilentOnLaunch { get; set; } = false;
public int PollIntervalMs { get; set; } = 500;
public Dictionary<string, string> Mapping { get; set; } = new()
{
["0x00"] = "always_on",
["0x06"] = "none",
["0x07"] = "speaker_mute",
["0x0A"] = "caps_lock",
["0x0E"] = "mic_mute",
};
static string FilePath => Path.Combine(
Path.GetDirectoryName(Environment.ProcessPath ?? "")!,
"ledder.cfg");
public static Config Load()
{
try
{
if (File.Exists(FilePath))
{
var cfg = JsonSerializer.Deserialize<Config>(File.ReadAllText(FilePath), Opts);
if (cfg != null)
{
foreach (var kv in new Config().Mapping)
if (!cfg.Mapping.ContainsKey(kv.Key))
cfg.Mapping[kv.Key] = kv.Value;
return cfg;
}
}
// also look at legacy name
var legacy = Path.Combine(Path.GetDirectoryName(FilePath)!, "thinkpad_led.cfg");
if (File.Exists(legacy))
{
var cfg = JsonSerializer.Deserialize<Config>(File.ReadAllText(legacy), Opts);
if (cfg != null) { cfg.Save(); return cfg; }
}
}
catch (Exception e) { Debug.WriteLine($"[cfg] load: {e.Message}"); }
return new Config();
}
public void Save()
{
try { File.WriteAllText(FilePath, JsonSerializer.Serialize(this, Opts)); }
catch (Exception e) { Debug.WriteLine($"[cfg] save: {e.Message}"); }
}
static readonly JsonSerializerOptions Opts = new()
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
};
}
// ============================================================
// MainForm
// ============================================================
internal class MainForm : Form
{
// ---- settable before Show ----
public bool StartHidden { get; set; }
static readonly (string Name, byte Id)[] Leds =
{
("Power", 0x00),
("Fn", 0x06),
("Sleep", 0x07),
("RedDot", 0x0A),
("Microphone", 0x0E),
};
static readonly (string Key, string Label)[] Sources =
{
("none", "None"),
("always_on", "Always On"),
("caps_lock", "Caps Lock"),
("num_lock", "Num Lock"),
("mic_mute", "Mic Mute"),
("speaker_mute", "Speaker Mute"),
};
readonly Config cfg;
readonly System.Windows.Forms.Timer timer = new();
NotifyIcon? trayIcon;
ToolStripMenuItem? trayMonitorItem;
ToolStripMenuItem? traySilentItem;
bool exiting;
bool firstShown;
// UI references
CheckBox monitorEnabledCb = null!;
Label monitorStatus = null!;
NumericUpDown pollInterval = null!;
CheckBox silentLaunchCb = null!;
Dictionary<byte, ComboBox> mappingCombos = new();
Dictionary<string, Label> statusLabels = new();
// monitor runtime state
bool inFullscreen = false;
byte? savedKbd = null;
Dictionary<byte, byte> lastTarget = new();
Dictionary<byte, (string Src, bool? Val)> overrides = new();
// --- layout constants ---
const int FORM_W = 380;
const int PAD = 12;
const int SECTION_W = FORM_W - PAD * 2;
const int GAP = 8;
const int ROW_H = 28;
const int NAME_W = 78;
const int HEX_W = 38;
const int HEX_X = 12 + NAME_W + 4;
const int CONTROL_X = HEX_X + HEX_W + 10;
const int BTN_W = 54;
const int BTN_H = 24;
public MainForm()
{
cfg = Config.Load();
Icon = BuildAppIcon();
BuildUi();
BuildTray();
timer.Interval = Math.Max(100, cfg.PollIntervalMs);
timer.Tick += (_, _) => Tick();
timer.Start();
RefreshMonitorStatusLabel();
}
// ============================================================
// Start-hidden mechanism (--silent / SilentOnLaunch)
// ============================================================
protected override void SetVisibleCore(bool value)
{
if (!firstShown)
{
firstShown = true;
bool wantHidden = StartHidden || cfg.SilentOnLaunch;
if (wantHidden)
{
// ensure handle is created so timer/tray run
if (!IsHandleCreated) CreateHandle();
ShowInTaskbar = false;
base.SetVisibleCore(false);
return;
}
}
base.SetVisibleCore(value);
}
// ============================================================
// UI construction
// ============================================================
void BuildUi()
{
Text = Program.AppTitle;
FormBorderStyle = FormBorderStyle.FixedSingle;
MaximizeBox = false;
StartPosition = FormStartPosition.CenterScreen;
Font = Style.Body;
AutoScaleMode = AutoScaleMode.Font;
BackColor = Style.Bg;
ForeColor = Style.TextPrimary;
int y = PAD;
var sMonitor = BuildMonitorSection();
sMonitor.SetBounds(PAD, y, SECTION_W, 120);
Controls.Add(sMonitor);
y += sMonitor.Height + GAP;
var sMapping = BuildMappingSection();
sMapping.SetBounds(PAD, y, SECTION_W, 34 + Leds.Length * ROW_H + 8);
Controls.Add(sMapping);
y += sMapping.Height + GAP;
var sManual = BuildManualSection();
int manualH = 34 + Leds.Length * ROW_H + 10 + ROW_H + 10 + BTN_H + 10;
sManual.SetBounds(PAD, y, SECTION_W, manualH);
Controls.Add(sManual);
y += sManual.Height + GAP;
var sStatus = BuildStatusSection();
sStatus.SetBounds(PAD, y, SECTION_W, 34 + 6 * 22 + 8);
Controls.Add(sStatus);
y += sStatus.Height + GAP;
var tools = BuildToolsRow();
tools.SetBounds(PAD, y, SECTION_W, 32);
Controls.Add(tools);
y += tools.Height + PAD;
ClientSize = new Size(FORM_W, y);
}
Panel BuildMonitorSection()
{
var p = Style.MakeSection("Lights Out — turns off all LEDs in fullscreen", out int ty);
monitorEnabledCb = new CheckBox
{
Text = "Enable",
Location = new Point(12, ty + 4),
AutoSize = true,
Checked = cfg.MonitorEnabled,
BackColor = Color.Transparent,
ForeColor = Style.TextPrimary,
Font = Style.Body,
};
monitorEnabledCb.CheckedChanged += (_, _) => OnMonitorToggle();
p.Controls.Add(monitorEnabledCb);
monitorStatus = new Label
{
Text = "Off",
Location = new Point(SECTION_W - 130, ty + 4),
Size = new Size(120, 18),
TextAlign = ContentAlignment.MiddleRight,
ForeColor = Style.TextMuted,
Font = new Font("Segoe UI Semibold", 9f),
BackColor = Color.Transparent,
};
p.Controls.Add(monitorStatus);
silentLaunchCb = new CheckBox
{
Text = "Start minimized to tray on launch",
Location = new Point(12, ty + 32),
AutoSize = true,
Checked = cfg.SilentOnLaunch,
BackColor = Color.Transparent,
ForeColor = Style.TextPrimary,
Font = Style.Body,
};
silentLaunchCb.CheckedChanged += (_, _) =>
{
cfg.SilentOnLaunch = silentLaunchCb.Checked;
cfg.Save();
if (traySilentItem != null) traySilentItem.Checked = silentLaunchCb.Checked;
};
p.Controls.Add(silentLaunchCb);
p.Controls.Add(new Label
{
Text = "Poll (ms):",
Location = new Point(12, ty + 62),
AutoSize = true,
ForeColor = Style.TextMuted,
BackColor = Color.Transparent,
});
pollInterval = new NumericUpDown
{
Location = new Point(82, ty + 60),
Size = new Size(80, 22),
Minimum = 100, Maximum = 5000, Increment = 100,
Value = Math.Clamp(cfg.PollIntervalMs, 100, 5000),
BorderStyle = BorderStyle.FixedSingle,
};
pollInterval.ValueChanged += (_, _) =>
{
cfg.PollIntervalMs = (int)pollInterval.Value;
timer.Interval = cfg.PollIntervalMs;
cfg.Save();
};
p.Controls.Add(pollInterval);
return p;
}
Panel BuildMappingSection()
{
var p = Style.MakeSection("LED ↔ system state", out int ty);
int y = ty + 4;
foreach (var (name, lid) in Leds)
{
p.Controls.Add(NameLbl(name, y));
p.Controls.Add(HexLbl(lid, y));
var cb = new ComboBox
{
Location = new Point(CONTROL_X, y),
Size = new Size(SECTION_W - CONTROL_X - 14, 22),
DropDownStyle = ComboBoxStyle.DropDownList,
FlatStyle = FlatStyle.Flat,
BackColor = Style.BtnBg,
Font = Style.Body,
};
foreach (var (_, lbl) in Sources) cb.Items.Add(lbl);
var curKey = cfg.Mapping.GetValueOrDefault($"0x{lid:X2}", "none");
cb.SelectedItem = Sources.FirstOrDefault(s => s.Key == curKey).Label ?? "None";
byte capLid = lid;
cb.SelectedIndexChanged += (_, _) => OnMappingChange(capLid, (string)cb.SelectedItem!);
mappingCombos[lid] = cb;
p.Controls.Add(cb);
y += ROW_H;
}
return p;
}
Panel BuildManualSection()
{
var p = Style.MakeSection("Manual control", out int ty);
int y = ty + 4;
foreach (var (name, lid) in Leds)
{
p.Controls.Add(NameLbl(name, y));
p.Controls.Add(HexLbl(lid, y));
byte capLid = lid;
p.Controls.Add(Style.FlatButton("On", CONTROL_X, y, BTN_W, BTN_H, () => ManualLed(capLid, Ec.POWER_ON)));
p.Controls.Add(Style.FlatButton("Off", CONTROL_X + BTN_W + 6, y, BTN_W, BTN_H, () => ManualLed(capLid, Ec.POWER_OFF)));
p.Controls.Add(Style.FlatButton("Blink", CONTROL_X + (BTN_W+6)*2, y, BTN_W, BTN_H, () => ManualLed(capLid, Ec.POWER_BLINK)));
y += ROW_H;
}
var sep = new Panel
{
BackColor = Style.Border,
Location = new Point(12, y + 4),
Size = new Size(SECTION_W - 24, 1),
};
p.Controls.Add(sep);
y += 12;
p.Controls.Add(NameLbl("Keyboard", y));
p.Controls.Add(new Label
{
Text = "0x0D",
Location = new Point(HEX_X, y + 4),
Size = new Size(HEX_W, 18),
ForeColor = Style.TextMuted,
Font = Style.Mono,
BackColor = Color.Transparent,
});
p.Controls.Add(Style.FlatButton("Off", CONTROL_X, y, BTN_W, BTN_H, () => ManualKbd(Ec.KBD_OFF)));
p.Controls.Add(Style.FlatButton("Low", CONTROL_X + BTN_W + 6, y, BTN_W, BTN_H, () => ManualKbd(Ec.KBD_LOW)));
p.Controls.Add(Style.FlatButton("High", CONTROL_X + (BTN_W+6)*2, y, BTN_W, BTN_H, () => ManualKbd(Ec.KBD_HIGH)));
y += ROW_H;
var allOff = Style.FlatButton("All off", 12, y + 6, SECTION_W - 24, BTN_H, AllOff);
p.Controls.Add(allOff);
return p;
}
Panel BuildStatusSection()
{
var p = Style.MakeSection("System state", out int ty);
int y = ty + 4;
foreach (var label in new[] { "Caps Lock", "Num Lock", "Mic mute",
"Speaker mute", "Fullscreen", "Keyboard" })
{
p.Controls.Add(new Label
{
Text = label,
Location = new Point(12, y),
Size = new Size(130, 18),
Font = Style.Body,
ForeColor = Style.TextMuted,
BackColor = Color.Transparent,
});
var v = new Label
{
Text = "—",
Location = new Point(150, y),
Size = new Size(SECTION_W - 164, 18),
Font = new Font("Segoe UI Semibold", 9f),
ForeColor = Style.TextPrimary,
BackColor = Color.Transparent,
};
statusLabels[label] = v;
p.Controls.Add(v);
y += 22;
}
return p;
}
Panel BuildToolsRow()
{
var p = new Panel { BackColor = Color.Transparent };
int x = 0;
foreach (var (txt, act) in new (string, Action)[]
{
("Scan LED IDs", ScanDialog),
("Read EC byte", ReadEcDialog),
("About", AboutDialog),
})
{
p.Controls.Add(Style.FlatButton(txt, x, 4, 100, 26, act));
x += 106;
}
return p;
}
Label NameLbl(string text, int y) => new()
{
Text = text,
Location = new Point(12, y + 4),
Size = new Size(NAME_W, 18),
Font = Style.Body,
ForeColor = Style.TextPrimary,
BackColor = Color.Transparent,
};
Label HexLbl(byte lid, int y) => new()
{
Text = $"0x{lid:X2}",
Location = new Point(HEX_X, y + 4),
Size = new Size(HEX_W, 18),
ForeColor = Style.TextMuted,
Font = Style.Mono,
BackColor = Color.Transparent,
};
// ============================================================
// System tray
// ============================================================
void BuildTray()
{
var menu = new ContextMenuStrip
{
Font = Style.Body,
ShowImageMargin = false,
};
var showItem = new ToolStripMenuItem("Show window");
showItem.Click += (_, _) => ShowFromTray();
menu.Items.Add(showItem);
menu.Items.Add(new ToolStripSeparator());
trayMonitorItem = new ToolStripMenuItem("Lights Out (fullscreen dim)")
{
Checked = cfg.MonitorEnabled,
CheckOnClick = true,
};
trayMonitorItem.CheckedChanged += (_, _) =>
monitorEnabledCb.Checked = trayMonitorItem.Checked;
menu.Items.Add(trayMonitorItem);
traySilentItem = new ToolStripMenuItem("Start minimized on launch")
{
Checked = cfg.SilentOnLaunch,
CheckOnClick = true,
};
traySilentItem.CheckedChanged += (_, _) =>
silentLaunchCb.Checked = traySilentItem.Checked;
menu.Items.Add(traySilentItem);
menu.Items.Add(new ToolStripSeparator());
var allOffItem = new ToolStripMenuItem("All LEDs off");
allOffItem.Click += (_, _) => AllOff();
menu.Items.Add(allOffItem);
menu.Items.Add(new ToolStripSeparator());
var exitItem = new ToolStripMenuItem("Exit");
exitItem.Click += (_, _) => { exiting = true; Close(); };
menu.Items.Add(exitItem);
trayIcon = new NotifyIcon
{
Icon = Icon,
Text = Program.AppTitle,
Visible = true,
ContextMenuStrip = menu,
};
trayIcon.DoubleClick += (_, _) => ShowFromTray();
}
Icon BuildAppIcon()
{
// draw a 32x32 "L" in a red rounded square (ThinkPad red)
using var bmp = new Bitmap(32, 32);
using (var g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.Transparent);
using var brush = new SolidBrush(Color.FromArgb(220, 40, 40));
using var path = new GraphicsPath();
int r = 6;
path.AddArc(0, 0, r, r, 180, 90);
path.AddArc(32 - r - 1, 0, r, r, 270, 90);
path.AddArc(32 - r - 1, 32 - r - 1, r, r, 0, 90);
path.AddArc(0, 32 - r - 1, r, r, 90, 90);
path.CloseFigure();
g.FillPath(brush, path);
using var font = new Font("Segoe UI Black", 16f, FontStyle.Bold, GraphicsUnit.Pixel);
using var txtBrush = new SolidBrush(Color.White);
var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
g.DrawString("L", font, txtBrush, new RectangleF(0, 0, 32, 32), sf);
}
return Icon.FromHandle(bmp.GetHicon());
}
void HideToTray()
{
Hide();
ShowInTaskbar = false;
}
void ShowFromTray()
{
Show();
WindowState = FormWindowState.Normal;
ShowInTaskbar = true;
BringToFront();
Activate();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && !exiting)
{
// close button = hide to tray instead of exit
e.Cancel = true;
HideToTray();
return;
}
if (trayIcon != null) { trayIcon.Visible = false; trayIcon.Dispose(); }
base.OnFormClosing(e);
}
// ============================================================
// Event handlers
// ============================================================
void OnMonitorToggle()