Repository navigation
Expand file tree
/
Copy pathMainForm.cs
More file actions
2796 lines (2490 loc) · 111 KB
/
Copy pathMainForm.cs
File metadata and controls
2796 lines (2490 loc) · 111 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.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
using MHelper.Hardware;
namespace MHelper
{
internal static class UiDpi
{
[DllImport("user32.dll")]
private static extern uint GetDpiForSystem();
public static float GetScale(Control ctrl)
{
float baseScale = 1.0f;
try
{
uint dpi = GetDpiForSystem();
if (dpi >= 96 && dpi <= 480) baseScale = dpi / 96f;
}
catch { }
if (baseScale <= 1.0f && ctrl != null)
{
try
{
using (Graphics g = ctrl.CreateGraphics())
{
if (g.DpiX >= 96f) baseScale = g.DpiX / 96f;
}
}
catch { }
}
return baseScale * UiFonts.TextScale;
}
}
internal static class UiChrome
{
[DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
public static void ApplyRoundedDarkBorder(IntPtr hwnd, Color borderColor)
{
try
{
int dark = 1;
DwmSetWindowAttribute(hwnd, 20, ref dark, sizeof(int));
int cornerPref = 2; // DWMWCP_ROUND
DwmSetWindowAttribute(hwnd, 33, ref cornerPref, sizeof(int));
int borderCol = ColorTranslator.ToWin32(borderColor);
DwmSetWindowAttribute(hwnd, 34, ref borderCol, sizeof(int));
}
catch { }
}
public static void BeginDragWindow(Form form, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && form != null && form.IsHandleCreated)
{
ReleaseCapture();
SendMessage(form.Handle, 0x00A1 /* WM_NCLBUTTONDOWN */, 0x02 /* HTCAPTION */, 0);
}
}
}
internal sealed class ModernDarkColorTable : ProfessionalColorTable
{
public override Color ToolStripDropDownBackground { get { return Color.FromArgb(24, 26, 31); } }
public override Color MenuBorder { get { return Color.FromArgb(56, 62, 74); } }
public override Color MenuItemBorder { get { return Color.Transparent; } }
public override Color MenuItemSelected { get { return Color.FromArgb(58, 64, 78); } }
public override Color SeparatorDark { get { return Color.FromArgb(56, 62, 74); } }
public override Color SeparatorLight { get { return Color.FromArgb(56, 62, 74); } }
public override Color ImageMarginGradientBegin { get { return Color.FromArgb(24, 26, 31); } }
public override Color ImageMarginGradientMiddle { get { return Color.FromArgb(24, 26, 31); } }
public override Color ImageMarginGradientEnd { get { return Color.FromArgb(24, 26, 31); } }
}
internal sealed class ModernDarkMenuRenderer : ToolStripProfessionalRenderer
{
private static readonly Color BgMenu = Color.FromArgb(24, 26, 31);
private static readonly Color BorderMenu = Color.FromArgb(56, 62, 74);
private static readonly Color HoverItem = Color.FromArgb(52, 58, 72);
private static readonly Color HoverDanger = Color.FromArgb(135, 30, 56);
private static readonly Color TextNormal = Color.FromArgb(242, 244, 248);
private static readonly Color TextDanger = Color.FromArgb(255, 205, 214);
private static readonly Color TextDisabled = Color.FromArgb(118, 126, 140);
public ModernDarkMenuRenderer() : base(new ModernDarkColorTable())
{
RoundedEdges = false;
}
private static GraphicsPath CreateRoundedRect(Rectangle bounds, int radius)
{
int d = radius * 2;
var path = new GraphicsPath();
path.AddArc(bounds.X, bounds.Y, d, d, 180, 90);
path.AddArc(bounds.Right - d, bounds.Y, d, d, 270, 90);
path.AddArc(bounds.Right - d, bounds.Bottom - d, d, d, 0, 90);
path.AddArc(bounds.X, bounds.Bottom - d, d, d, 90, 90);
path.CloseFigure();
return path;
}
protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e)
{
using (var bg = new SolidBrush(BgMenu))
{
e.Graphics.FillRectangle(bg, e.AffectedBounds);
}
}
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
{
var r = new Rectangle(0, 0, e.AffectedBounds.Width - 1, e.AffectedBounds.Height - 1);
using (var pen = new Pen(BorderMenu, 1f))
{
e.Graphics.DrawRectangle(pen, r);
}
}
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
{
if (e.Item == null || !e.Item.Enabled) return;
if (!e.Item.Selected && !e.Item.Pressed) return;
int menuW = (e.ToolStrip != null) ? e.ToolStrip.ClientSize.Width : e.Item.Width;
int padX = Math.Max(4, (int)Math.Round(4 * UiFonts.TextScale));
var pill = new Rectangle(-e.Item.Bounds.X + padX, 1, Math.Max(8, menuW - padX * 2), Math.Max(8, e.Item.Height - 2));
bool isDanger = "danger".Equals(e.Item.Tag as string, StringComparison.Ordinal);
Color fill = isDanger ? HoverDanger : HoverItem;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (GraphicsPath path = CreateRoundedRect(pill, 5))
using (var br = new SolidBrush(fill))
{
e.Graphics.FillPath(br, path);
}
}
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
{
int menuW = (e.ToolStrip != null) ? e.ToolStrip.ClientSize.Width : e.Item.Width;
int padX = Math.Max(10, (int)Math.Round(10 * UiFonts.TextScale));
int x1 = -e.Item.Bounds.X + padX;
int x2 = -e.Item.Bounds.X + Math.Max(padX, menuW - padX);
int y = e.Item.Height / 2;
using (var pen = new Pen(BorderMenu, 1f))
{
e.Graphics.DrawLine(pen, x1, y, x2, y);
}
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
if (e.Item == null) return;
bool isDanger = "danger".Equals(e.Item.Tag as string, StringComparison.Ordinal);
Color textCol = !e.Item.Enabled
? TextDisabled
: (isDanger && (e.Item.Selected || e.Item.Pressed) ? TextDanger : TextNormal);
int menuW = (e.ToolStrip != null) ? e.ToolStrip.ClientSize.Width : e.Item.Width;
var rect = new Rectangle(-e.Item.Bounds.X, 0, Math.Max(1, menuW), e.Item.Height);
TextRenderer.DrawText(
e.Graphics,
e.Text,
e.TextFont,
rect,
textCol,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding);
}
}
internal sealed class ModernDarkMenuStrip : ContextMenuStrip
{
public ModernDarkMenuStrip()
{
ShowImageMargin = false;
ShowCheckMargin = false;
DropShadowEnabled = true;
BackColor = Color.FromArgb(24, 26, 31);
ForeColor = Color.FromArgb(242, 244, 248);
Font = UiFonts.Regular86;
int hPad = (int)Math.Round(4 * UiFonts.TextScale);
int vPad = (int)Math.Round(6 * UiFonts.TextScale);
Padding = new Padding(hPad, vPad, hPad, vPad);
Renderer = new ModernDarkMenuRenderer();
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
UiChrome.ApplyRoundedDarkBorder(Handle, Color.FromArgb(56, 62, 74));
}
}
/// <summary>
/// Pre-cached dual-scale (100% / 150%) shared fonts so toggling text size
/// or opening/closing sub-forms creates zero per-open GDI font handles.
/// </summary>
internal static class UiFonts
{
private sealed class FontSet
{
public readonly Font Title;
public readonly Font SubWindowTitle;
public readonly Font MainBody;
public readonly Font DialogBody;
public readonly Font Semibold90;
public readonly Font Semibold88;
public readonly Font Semibold85;
public readonly Font Semibold84;
public readonly Font Semibold83;
public readonly Font CardHeader;
public readonly Font Regular86;
public readonly Font Regular85;
public readonly Font Regular83;
public readonly Font Regular82;
public readonly Font Regular80;
public FontSet(float scale)
{
Title = new Font("Segoe UI Semibold", 13.5f * scale, FontStyle.Bold);
SubWindowTitle = new Font("Segoe UI Semibold", 11.5f * scale, FontStyle.Bold);
MainBody = new Font("Segoe UI", 9.5f * scale, FontStyle.Regular);
DialogBody = new Font("Segoe UI", 9.0f * scale, FontStyle.Regular);
Semibold90 = new Font("Segoe UI Semibold", 9.0f * scale, FontStyle.Regular);
Semibold88 = new Font("Segoe UI Semibold", 8.8f * scale, FontStyle.Regular);
Semibold85 = new Font("Segoe UI Semibold", 8.5f * scale, FontStyle.Regular);
Semibold84 = new Font("Segoe UI Semibold", 8.4f * scale, FontStyle.Regular);
Semibold83 = new Font("Segoe UI Semibold", 8.3f * scale, FontStyle.Regular);
CardHeader = new Font("Segoe UI Semibold", 7.8f * scale, FontStyle.Bold);
Regular86 = new Font("Segoe UI", 8.6f * scale, FontStyle.Regular);
Regular85 = new Font("Segoe UI", 8.5f * scale, FontStyle.Regular);
Regular83 = new Font("Segoe UI", 8.3f * scale, FontStyle.Regular);
Regular82 = new Font("Segoe UI", 8.2f * scale, FontStyle.Regular);
Regular80 = new Font("Segoe UI", 8.0f * scale, FontStyle.Regular);
}
}
private static readonly FontSet NormalSet = new FontSet(1.0f);
private static readonly FontSet LargeSet = new FontSet(1.5f);
public static bool LargeText { get; private set; }
public static float TextScale { get { return LargeText ? 1.5f : 1.0f; } }
public static void SetLargeText(bool large)
{
LargeText = large;
}
private static FontSet Current { get { return LargeText ? LargeSet : NormalSet; } }
public static Font Title { get { return Current.Title; } }
public static Font SubWindowTitle { get { return Current.SubWindowTitle; } }
public static Font MainBody { get { return Current.MainBody; } }
public static Font DialogBody { get { return Current.DialogBody; } }
public static Font Semibold90 { get { return Current.Semibold90; } }
public static Font Semibold88 { get { return Current.Semibold88; } }
public static Font Semibold85 { get { return Current.Semibold85; } }
public static Font Semibold84 { get { return Current.Semibold84; } }
public static Font Semibold83 { get { return Current.Semibold83; } }
public static Font CardHeader { get { return Current.CardHeader; } }
public static Font Regular86 { get { return Current.Regular86; } }
public static Font Regular85 { get { return Current.Regular85; } }
public static Font Regular83 { get { return Current.Regular83; } }
public static Font Regular82 { get { return Current.Regular82; } }
public static Font Regular80 { get { return Current.Regular80; } }
}
/// <summary>
/// Minimal dark-themed slider replacing legacy white Win32 TrackBar.
/// Supports click-to-seek, drag, mouse wheel, keyboard arrows, and step snapping.
/// </summary>
internal sealed class ModernSlider : Control
{
private static readonly Color TrackBg = Color.FromArgb(20, 22, 27);
private static readonly Color TrackBorder = Color.FromArgb(56, 62, 74);
private static readonly Color ThumbFill = Color.FromArgb(245, 247, 250);
private int _min;
private int _max = 100;
private int _value = 50;
private int _step = 1;
private Color _accent = Color.FromArgb(59, 130, 246);
private bool _hover;
private bool _dragging;
public event EventHandler ValueChanged;
public event EventHandler ValueCommitted;
public ModernSlider(int min, int max, int value, int step, Color accent)
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer |
ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true);
_min = min;
_max = Math.Max(min + 1, max);
_step = Math.Max(1, step);
_accent = accent;
_value = SnapAndClamp(value);
Cursor = Cursors.Hand;
TabStop = true;
}
public int Minimum { get { return _min; } }
public int Maximum { get { return _max; } }
public int Value
{
get { return _value; }
set { SetInternal(value, true); }
}
public bool IsDragging { get { return _dragging; } }
public void SetValueSilently(int value)
{
SetInternal(value, false);
}
public void SetAccentColor(Color c)
{
if (_accent != c)
{
_accent = c;
Invalidate();
}
}
private int SnapAndClamp(int raw)
{
int clamped = Math.Max(_min, Math.Min(_max, raw));
if (_step > 1)
{
int offset = (int)Math.Round((clamped - _min) / (double)_step) * _step;
clamped = Math.Max(_min, Math.Min(_max, _min + offset));
}
return clamped;
}
private void SetInternal(int nextRaw, bool raiseEvent)
{
int next = SnapAndClamp(nextRaw);
if (next == _value) return;
_value = next;
Invalidate();
if (raiseEvent && ValueChanged != null)
ValueChanged(this, EventArgs.Empty);
}
private int ValueFromX(int x)
{
int pad = Math.Max(8, Height / 2);
int usable = Math.Max(1, Width - pad * 2);
double ratio = Math.Max(0.0, Math.Min(1.0, (x - pad) / (double)usable));
int raw = (int)Math.Round(_min + ratio * (_max - _min));
return SnapAndClamp(raw);
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(BackColor);
int pad = Math.Max(8, Height / 2);
int usable = Math.Max(1, Width - pad * 2);
int trackH = Math.Max(6, Height / 4);
int trackY = (Height - trackH) / 2;
double ratio = (_value - _min) / (double)(_max - _min);
int fillW = (int)Math.Round(ratio * usable);
int thumbX = pad + fillW;
int thumbR = Math.Max(6, (int)Math.Round(Height * 0.28));
using (var trackBrush = new SolidBrush(TrackBg))
using (var trackPen = new Pen(TrackBorder, 1f))
{
var trackRect = new Rectangle(pad, trackY, usable, trackH);
g.FillRectangle(trackBrush, trackRect);
g.DrawRectangle(trackPen, trackRect);
}
if (fillW > 0)
{
Color fillCol = Enabled ? _accent : Color.FromArgb(90, 96, 110);
using (var fillBrush = new SolidBrush(fillCol))
{
g.FillRectangle(fillBrush, pad, trackY, fillW, trackH);
}
}
var thumbRect = new Rectangle(thumbX - thumbR, (Height / 2) - thumbR, thumbR * 2, thumbR * 2);
Color ringCol = Enabled ? _accent : TrackBorder;
using (var thumbBrush = new SolidBrush(Enabled ? ThumbFill : Color.FromArgb(140, 145, 155)))
using (var ringPen = new Pen(ringCol, (_hover || _dragging) ? 2.2f : 1.5f))
{
g.FillEllipse(thumbBrush, thumbRect);
g.DrawEllipse(ringPen, thumbRect);
}
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
_hover = true;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_hover = false;
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (!Enabled || e.Button != MouseButtons.Left) return;
Focus();
_dragging = true;
Capture = true;
SetInternal(ValueFromX(e.X), true);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (_dragging && Enabled)
{
if ((e.Button & MouseButtons.Left) == 0)
{
_dragging = false;
Capture = false;
Invalidate();
return;
}
SetInternal(ValueFromX(e.X), true);
}
}
protected override void OnMouseCaptureChanged(EventArgs e)
{
base.OnMouseCaptureChanged(e);
if (_dragging && !Capture)
{
_dragging = false;
Invalidate();
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (_dragging && e.Button == MouseButtons.Left)
{
_dragging = false;
Capture = false;
Invalidate();
if (ValueCommitted != null) ValueCommitted(this, EventArgs.Empty);
}
}
protected override void OnMouseWheel(MouseEventArgs e)
{
base.OnMouseWheel(e);
if (!Enabled || e.Delta == 0) return;
int dir = e.Delta > 0 ? 1 : -1;
int before = _value;
SetInternal(_value + dir * _step, true);
if (_value != before && ValueCommitted != null)
ValueCommitted(this, EventArgs.Empty);
}
protected override bool IsInputKey(Keys keyData)
{
switch (keyData & Keys.KeyCode)
{
case Keys.Left:
case Keys.Right:
case Keys.Up:
case Keys.Down:
case Keys.Home:
case Keys.End:
return true;
}
return base.IsInputKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!Enabled) return;
int next = _value;
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Down) next = _value - _step;
else if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Up) next = _value + _step;
else if (e.KeyCode == Keys.Home) next = _min;
else if (e.KeyCode == Keys.End) next = _max;
else return;
int before = _value;
SetInternal(next, true);
if (_value != before && ValueCommitted != null)
ValueCommitted(this, EventArgs.Empty);
e.Handled = true;
}
}
/// <summary>
/// Small-A / Large-A header button toggling between 100% and 150% UI text size,
/// with unmistakable visual highlight on the active size.
/// </summary>
internal sealed class FontSizeToggleButton : Control
{
private static readonly Color FillNormal = Color.FromArgb(46, 51, 62);
private static readonly Color FillHover = Color.FromArgb(58, 64, 78);
private static readonly Color FillActive = Color.FromArgb(59, 130, 246);
private static readonly Color FillActiveHover = Color.FromArgb(74, 142, 250);
private static readonly Color BorderSubtle = Color.FromArgb(56, 62, 74);
private static readonly Color TextPrimary = Color.FromArgb(242, 244, 248);
private static readonly Color TextMuted = Color.FromArgb(148, 156, 170);
private static readonly Color TextOnBlueMuted = Color.FromArgb(175, 224, 240, 255);
private bool _isLarge;
private bool _hover;
public event EventHandler ToggleClicked;
public bool IsLarge
{
get { return _isLarge; }
set
{
if (_isLarge != value)
{
_isLarge = value;
Invalidate();
}
}
}
public FontSizeToggleButton()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer |
ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true);
Cursor = Cursors.Hand;
TabStop = false;
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
_hover = true;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_hover = false;
Invalidate();
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
if (ToggleClicked != null) ToggleClicked(this, EventArgs.Empty);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.Space || e.KeyCode == Keys.Enter)
{
if (ToggleClicked != null) ToggleClicked(this, EventArgs.Empty);
e.Handled = true;
}
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
Color bg = _isLarge ? (_hover ? FillActiveHover : FillActive) : (_hover ? FillHover : FillNormal);
Color border = _isLarge ? FillActive : BorderSubtle;
var rect = new Rectangle(0, 0, Math.Max(1, Width - 1), Math.Max(1, Height - 1));
using (var bgBrush = new SolidBrush(bg))
using (var borderPen = new Pen(border, 1f))
{
g.FillRectangle(bgBrush, rect);
g.DrawRectangle(borderPen, rect);
}
float smallPx = Math.Max(8.5f, Height * 0.43f);
float largePx = Math.Max(12.5f, Height * 0.67f);
float barH = Math.Max(2f, Height * 0.085f);
float bottomY = Height * 0.74f;
float gap = Math.Max(2.5f, Width * 0.055f);
using (var fSmall = new Font("Segoe UI Semibold", smallPx, _isLarge ? FontStyle.Regular : FontStyle.Bold, GraphicsUnit.Pixel))
using (var fLarge = new Font("Segoe UI Semibold", largePx, _isLarge ? FontStyle.Bold : FontStyle.Regular, GraphicsUnit.Pixel))
using (var sf = new StringFormat(StringFormat.GenericTypographic))
{
sf.FormatFlags |= StringFormatFlags.NoWrap;
SizeF szSmall = g.MeasureString("A", fSmall, 200, sf);
SizeF szLarge = g.MeasureString("A", fLarge, 200, sf);
float totalW = szSmall.Width + gap + szLarge.Width;
float startX = (Width - totalW) / 2f;
float smallX = startX;
float largeX = startX + szSmall.Width + gap;
Color cSmall = _isLarge ? TextOnBlueMuted : TextPrimary;
Color cLarge = _isLarge ? Color.White : TextMuted;
Color barCol = _isLarge ? Color.White : FillActive;
using (var bSmall = new SolidBrush(cSmall))
using (var bLarge = new SolidBrush(cLarge))
using (var bBar = new SolidBrush(barCol))
{
g.DrawString("A", fSmall, bSmall, smallX, bottomY - szSmall.Height, sf);
g.DrawString("A", fLarge, bLarge, largeX, bottomY - szLarge.Height, sf);
float barY = Math.Min(Height - barH - 2f, bottomY + Math.Max(1.5f, Height * 0.06f));
if (_isLarge)
g.FillRectangle(bBar, largeX, barY, szLarge.Width, barH);
else
g.FillRectangle(bBar, smallX, barY, szSmall.Width, barH);
}
}
}
}
internal sealed class InfoBadge : Control
{
private static readonly Color BorderSubtle = Color.FromArgb(56, 62, 74);
private static readonly Color AccentBlue = Color.FromArgb(59, 130, 246);
private static readonly Color TextPrimary = Color.FromArgb(242, 244, 248);
private static readonly Color TextMuted = Color.FromArgb(156, 163, 175);
private bool _hover;
public InfoBadge()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer |
ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);
Cursor = Cursors.Hand;
TabStop = false;
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
_hover = true;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_hover = false;
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(BackColor);
var rect = new Rectangle(1, 1, Math.Max(4, Width - 3), Math.Max(4, Height - 3));
if (_hover)
{
using (var fill = new SolidBrush(Color.FromArgb(46, 56, 74)))
g.FillEllipse(fill, rect);
}
using (var pen = new Pen(_hover ? AccentBlue : BorderSubtle, 1.3f))
g.DrawEllipse(pen, rect);
TextRenderer.DrawText(
g,
"i",
UiFonts.Semibold83,
ClientRectangle,
_hover ? TextPrimary : TextMuted,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPrefix | TextFormatFlags.NoPadding);
}
}
public sealed class MainForm : Form
{
private static readonly Color BgWindow = Color.FromArgb(24, 26, 31);
private static readonly Color BgCard = Color.FromArgb(34, 38, 46);
private static readonly Color BgButton = Color.FromArgb(46, 51, 62);
private static readonly Color BgButtonHover = Color.FromArgb(58, 64, 78);
private static readonly Color BorderSubtle = Color.FromArgb(56, 62, 74);
private static readonly Color TextPrimary = Color.FromArgb(242, 244, 248);
private static readonly Color TextMuted = Color.FromArgb(156, 163, 175);
private static readonly Color AccentBlue = Color.FromArgb(59, 130, 246);
private static readonly Color AccentRed = Color.FromArgb(225, 29, 72);
private static readonly Color AccentGreen = Color.FromArgb(16, 185, 129);
private static readonly Color AccentAmber = Color.FromArgb(245, 158, 11);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool DestroyIcon(IntPtr hIcon);
private readonly MsiAcpi _acpi;
private readonly RyzenSmuController _smu;
private readonly KeyboardRgbController _rgb;
private readonly AppSettings _settings;
private readonly EventWaitHandle _activateEvent;
private readonly RegisteredWaitHandle _activateWaitReg;
private readonly string _acpiError;
private readonly string _modelName;
private readonly NotifyIcon _trayIcon;
private readonly System.Windows.Forms.Timer _refreshTimer;
private readonly ToolTip _toolTip = new ToolTip { AutoPopDelay = 25000, InitialDelay = 120, ReshowDelay = 50, ShowAlways = true };
private float _dpi;
private const string AllHiddenStatusText = "All categories hidden — click '⚙ Settings' to enable modules.";
private int _refreshInFlight;
private int _pendingGpuMuxRead;
private int _lastDeactivateTicks;
private bool _allowClose;
private bool _cleanedUp;
private bool _modalOpen;
private bool _gpuSwitchInProgress;
private Form _activeModal;
private bool _suppressStartupCheck;
// Cached UEFI GPU MUX state (read on popup open & after switch, NOT every 2s tick)
private FirmwareGpuInfo _cachedGpuInfo;
private string _cachedGpuErr = "Reading firmware...";
// Header telemetry
private Label _lblSubtitle;
private Label _lblTempRpm;
private Label _lblBatteryInfo;
// Card containers (for dynamic category visibility & zero-gap reflow)
private Panel _cardPerf;
private Panel _cardFan;
private Panel _cardGpu;
private Panel _cardBat;
// Performance Mode buttons
private Button _btnEco;
private Button _btnBalanced;
private Button _btnExtreme;
// Fan / Cooling buttons
private Button _btnFanAuto;
private Button _btnFanSilent;
private Button _btnCoolerBoost;
// GPU MUX buttons
private Label _lblGpuStatus;
private Button _btnGpuHybrid;
private Button _btnGpuDiscrete;
private Button _btnGpuIntegrated;
// Battery Limit controls
private Label _lblBatLimit;
private Button _btnBat60;
private Button _btnBat80;
private Button _btnBat100;
private ModernSlider _sliderBat;
// Sub-window & Footer controls
private FontSizeToggleButton _btnTextScale;
private Button _btnFansPower;
private Button _btnKeyboardRgb;
private Button _btnExtra;
private CheckBox _chkStartup;
private Button _btnExit;
private Label _lblStatusMsg;
private bool _lastCustomFanActive;
// Dynamic tray menu items
private ToolStripMenuItem _miFansPower;
private ToolStripMenuItem _miExtra;
private ToolStripMenuItem _miKeyboardRgb;
private ToolStripSeparator _miSepRgb;
private ToolStripMenuItem _miRgbOff;
private ToolStripSeparator _miSepBattery;
private ToolStripMenuItem _miBat60;
private ToolStripMenuItem _miBat80;
private ToolStripMenuItem _miBat100;
private int S(int px) { return (int)Math.Round(px * _dpi); }
public MainForm(MsiAcpi acpi, RyzenSmuController smu, KeyboardRgbController rgb, AppSettings settings, EventWaitHandle activateEvent, string acpiError, bool startHidden)
{
_acpi = acpi;
_smu = smu;
_rgb = rgb;
_settings = settings;
_activateEvent = activateEvent;
_acpiError = acpiError;
_modelName = QueryModelName();
AutoScaleMode = AutoScaleMode.None;
_dpi = UiDpi.GetScale(this);
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
TopMost = true;
BackColor = BgWindow;
ForeColor = TextPrimary;
Font = UiFonts.MainBody;
ClientSize = new Size(S(392), S(576));
DoubleBuffered = true;
BuildUi(null);
_refreshTimer = new System.Windows.Forms.Timer { Interval = 2000 };
_refreshTimer.Tick += delegate { RefreshHardwareStateAsync(false); };
_trayIcon = new NotifyIcon
{
Icon = CreateTrayIcon(),
Text = FitTrayTooltip("M-Helper (" + _modelName + ")"),
Visible = true,
ContextMenuStrip = BuildTrayMenu()
};
_trayIcon.MouseClick += (s, e) =>
{
if (e.Button == MouseButtons.Left) TogglePopup();
};
ApplyCategoryLayout();
if (_activateEvent != null)
{
_activateWaitReg = ThreadPool.RegisterWaitForSingleObject(
_activateEvent,
delegate
{
if (!IsDisposed && IsHandleCreated)
{
try { BeginInvoke((Action)ShowPopup); } catch { }
}
},
null,
-1,
false);
}
Deactivate += (s, e) =>
{
if (!_modalOpen && Visible)
{
_lastDeactivateTicks = Environment.TickCount;
HidePopup();
}
};
KeyPreview = true;
KeyDown += (s, e) =>
{
if (e.KeyCode == Keys.Escape && !_modalOpen) HidePopup();
};
SystemEvents.PowerModeChanged += OnPowerModeChanged;
RyzenSnapshotSettings snap = _settings.GetSnapshot();
UiCategorySettings initCats = _settings.GetCategories();
if (snap.CrashGuardTriggered)
{
SetStatus("Crash guard: previous Ryzen SMU apply didn't pass 60s check; auto-apply disabled.", true);
}
else
{
if (StartupTask.IsInstalledBinaryOutdated())
{
SetStatus("Startup copy in Program Files is older — re-toggle Startup to update.", true);
}
if (snap.AutoApplyOnStartup && initCats.ShowRyzenTuning)
{
ScheduleAutoApplyRyzen(500);
}
}
if (startHidden)
{
Opacity = 0;
Shown += (s, e) =>
{
Hide();
Opacity = 1;
};
}
else
{
Shown += (s, e) =>
{
PositionAboveTray();
RefreshHardwareStateAsync(true);
if (_settings.GetCategories().AnyEcPollingNeeded)
_refreshTimer.Start();
};
}
}
private static string FitTrayTooltip(string text)
{
return text.Length > 63 ? text.Substring(0, 63) : text;
}
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Resume)
{
RyzenSnapshotSettings snap = _settings.GetSnapshot();
UiCategorySettings cats = _settings.GetCategories();
if (snap.AutoApplyOnStartup && cats.ShowRyzenTuning)
{
ScheduleAutoApplyRyzen(2500);
}
}
}
private void ScheduleAutoApplyRyzen(int delayMs)
{
if (!_settings.GetCategories().ShowRyzenTuning) return;
RyzenSnapshotSettings initial = _settings.GetSnapshot();
if (!initial.CoEnabled && !initial.TdpEnabled && !initial.TempEnabled) return;
ThreadPool.QueueUserWorkItem(delegate
{
try
{
if (delayMs > 0) Thread.Sleep(delayMs);
if (IsDisposed || !RyzenSmuController.IsPawnIoInstalled()) return;
if (!_settings.GetCategories().ShowRyzenTuning) return;
RyzenSnapshotSettings rs = _settings.GetSnapshot();
if (!rs.AutoApplyOnStartup) return;
if (!rs.CoEnabled && !rs.TdpEnabled && !rs.TempEnabled) return;
_settings.ApplyWithCrashGuard(
_smu,
rs.CoEnabled ? (int?)rs.CoAllCore : null,
rs.TdpEnabled ? (int?)rs.TdpWatts : null,
rs.TempEnabled ? (int?)rs.TempLimitC : null);
}
catch { }
});
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
UiChrome.ApplyRoundedDarkBorder(Handle, BorderSubtle);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (var pen = new Pen(BorderSubtle, 1))
e.Graphics.DrawRectangle(pen, 0, 0, Width - 1, Height - 1);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
bool systemClosing = e.CloseReason == CloseReason.WindowsShutDown || e.CloseReason == CloseReason.TaskManagerClosing;
if (!_allowClose && !systemClosing && e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
HidePopup();
return;
}
if (!_cleanedUp)
{
_cleanedUp = true;