Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
2771 lines (2673 loc) · 155 KB
/
Copy pathProgram.cs
File metadata and controls
2771 lines (2673 loc) · 155 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json;
using Microsoft.Win32;
static class Program
{
[STAThread]
static void Main(string[] args)
{
if (ReleaseUpdater.LaunchStagedUpdate(args)) return;
Debug.Assert(Taskbar.ToAbgr(unchecked((int)0x80112233)) == unchecked((int)0x80332211));
Debug.Assert(SwissGermanTranslations.Of("Fenster öffnen") == "Fänschter öffne");
Debug.Assert(SwissGermanTranslations.Of("Mail · 3 Fenster (erste 2)") == "Mail · 3 Fänschter (erschti 2)");
Debug.Assert(SwissGermanTranslations.ToGerman("Mail · 3 Fänschter (erschti 2)") == "Mail · 3 Fenster (erste 2)");
Debug.Assert(SwissGermanTranslations.ToGerman("Profil") == "Profil");
ApplicationConfiguration.Initialize();
Application.AddMessageFilter(new ComboWheelFilter());
if (args.Contains("--folders")) { FolderStackTaskbarLauncher.RunPopup(); return; }
if (args.Contains("--exit")) { ExitRunning(); return; }
if (args.Length == 2 && args[0] == "--workspace" && Guid.TryParse(args[1], out var workspaceId))
{
var scene = Settings.Load().Workspaces.FirstOrDefault(item => item.Id == workspaceId);
if (scene != null)
{
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(15));
try { Task.Run(() => WorkspaceController.RestoreAsync(scene, stop.Token)).GetAwaiter().GetResult(); }
catch (OperationCanceledException) { }
}
return;
}
Application.Run(new MainForm(args.Contains("--tray")));
}
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern uint RegisterWindowMessage(string name);
[DllImport("user32.dll")] static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
public static readonly uint ExitMessage = RegisterWindowMessage("winBar.Exit");
public static readonly uint TaskbarCreatedMessage = RegisterWindowMessage("TaskbarCreated");
// Lets scripts and agents stop the tray instance cleanly (taskbar restored), e.g. before editing settings.json.
static void ExitRunning()
{
var others = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
.Where(p => p.Id != Environment.ProcessId).ToList();
PostMessage(new IntPtr(0xFFFF), ExitMessage, IntPtr.Zero, IntPtr.Zero); // HWND_BROADCAST
foreach (var p in others) p.WaitForExit(5000);
}
}
static class Taskbar
{
[StructLayout(LayoutKind.Sequential)] struct AccentPolicy { public int AccentState, AccentFlags, GradientColor, AnimationId; }
[StructLayout(LayoutKind.Sequential)] struct WinCompAttrData { public int Attribute; public IntPtr Data; public int SizeOfData; }
[StructLayout(LayoutKind.Sequential)] struct RECT { public int L, T, R, B; }
[StructLayout(LayoutKind.Sequential)] struct APPBARDATA { public int cbSize; public IntPtr hWnd; public uint uCallbackMessage, uEdge; public RECT rc; public IntPtr lParam; }
[DllImport("user32.dll")] static extern int SetWindowCompositionAttribute(IntPtr h, ref WinCompAttrData d);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindow(string c, string? w);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string c, string? w);
[DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd);
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out NativeRect rect);
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
[DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern bool IsZoomed(IntPtr h);
[DllImport("user32.dll", EntryPoint = "GetWindowLongW")] static extern int GetWindowLong(IntPtr h, int index);
[DllImport("dwmapi.dll")] static extern int DwmGetColorizationColor(out uint color, out bool opaqueBlend);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr SendMessageTimeout(IntPtr h, uint msg, IntPtr w, string l, uint flags, uint timeout, out IntPtr res);
[DllImport("shell32.dll")] static extern IntPtr SHAppBarMessage(uint msg, ref APPBARDATA d);
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
[DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint msg, IntPtr w, IntPtr l);
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
delegate void WinEventProc(IntPtr hook, uint eventType, IntPtr window, int objectId, int childId, uint eventThread, uint eventTime);
[DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr module,
WinEventProc callback, uint processId, uint threadId, uint flags);
[DllImport("user32.dll")] static extern bool UnhookWinEvent(IntPtr hook);
[DllImport("Windows.UI.Xaml.dll", CharSet = CharSet.Unicode)] static extern int InitializeXamlDiagnosticsEx(string endPoint, uint pid, string? diagDll, string tapDll, Guid tapClsid, string? initData);
public static int ToAbgr(int argb) => (int)((uint)argb & 0xFF00FF00) | ((argb & 0xFF) << 16) | ((argb >> 16) & 0xFF);
static IEnumerable<IntPtr> Handles()
{
var main = FindWindow("Shell_TrayWnd", null);
if (main != IntPtr.Zero) yield return main;
var h = IntPtr.Zero;
while ((h = FindWindowEx(IntPtr.Zero, h, "Shell_SecondaryTrayWnd", null)) != IntPtr.Zero) yield return h;
}
// Undocumented API (same as TranslucentTB). state: 0 off, 1 gradient, 2 transparent gradient, 3 blur, 4 acrylic.
public static void SetAccent(int state, int abgr)
{
var policy = new AccentPolicy { AccentState = state, AccentFlags = 2, GradientColor = abgr };
int size = Marshal.SizeOf(policy);
var ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(policy, ptr, false);
var data = new WinCompAttrData { Attribute = 19, Data = ptr, SizeOfData = size };
foreach (var h in Handles()) SetWindowCompositionAttribute(h, ref data);
}
finally { Marshal.FreeHGlobal(ptr); }
}
// Windows 11 draws the taskbar background in XAML over the window, hiding the accent above.
// tap\TaskbarTap.dll (loaded into explorer like TranslucentTB does) fades that XAML background out.
static readonly Guid TapClsid = new("3F0F7A5E-8E3B-4C1D-9B2A-6D1E5C7A9B42");
static readonly string TapDll = Path.Combine(AppContext.BaseDirectory, "TaskbarTap.dll");
static int injecting;
static uint injectedPid;
static long nextInject;
static long fastInjectUntil = Environment.TickCount64 + 30_000;
static IntPtr lastTapWindow;
static IntPtr previewReceiver, lastPreviewRegisteredWindow;
static bool? lastBackground, lastPinned;
static int lastTrayMask = -1;
static int lastKeepPinned = -1;
static ulong lastStackRanges = ulong.MaxValue;
static int lastStackFlags = -1;
static long nextPinnedRefresh;
// Class name carries a version: an older TaskbarTap.dll still loaded in explorer does not know newer messages.
static IntPtr NewTapWindow() => FindWindowEx(new IntPtr(-3), IntPtr.Zero, "TaskbarTweakerTap16", null); // HWND_MESSAGE
static IntPtr LegacyTapWindow() => FindWindowEx(new IntPtr(-3), IntPtr.Zero, "TaskbarTweakerTap15", null);
// Keep using the prior helper until Explorer next starts. Loading two
// visual-tree callbacks into one Explorer process would duplicate effects.
static IntPtr TapWindow() { var current = NewTapWindow(); return current != IntPtr.Zero ? current : LegacyTapWindow(); }
public static bool WheelNeedsExplorerRestart => NewTapWindow() == IntPtr.Zero && LegacyTapWindow() != IntPtr.Zero;
public static IntPtr NativeTapWindow => TapWindow();
static IntPtr lastBrushWindow;
static int lastBrushState = -1, lastBrushColor;
public static void SetXamlBrush(int state, int abgr)
{
var window = TapWindow();
if (window == IntPtr.Zero) { lastBrushWindow = IntPtr.Zero; return; }
if (window == lastBrushWindow && state == lastBrushState && abgr == lastBrushColor) return;
PostMessage(window, 0x8006, (IntPtr)state, (IntPtr)abgr);
lastBrushWindow = window;
lastBrushState = state;
lastBrushColor = abgr;
}
static IntPtr lastHoverWindow;
static int lastHoverMode = -1;
public static void SetHoverAnimation(int mode)
{
var window = TapWindow();
if (window == IntPtr.Zero) { lastHoverWindow = IntPtr.Zero; return; }
mode = Math.Clamp(mode, 0, 3);
if (window == lastHoverWindow && mode == lastHoverMode) return;
if (PostMessage(window, 0x8007, (IntPtr)mode, IntPtr.Zero))
{
lastHoverWindow = window;
lastHoverMode = mode;
}
}
static IntPtr lastWheelWindow;
static bool? lastWheelEnabled;
public static void SetWheelCycle(bool enabled)
{
var window = NewTapWindow();
if (window == IntPtr.Zero) { lastWheelWindow = IntPtr.Zero; return; }
if (window == lastWheelWindow && enabled == lastWheelEnabled) return;
if (PostMessage(window, 0x8009, enabled ? 1 : 0, IntPtr.Zero))
{
lastWheelWindow = window;
lastWheelEnabled = enabled;
}
}
static readonly Dictionary<IntPtr, bool> entranceWasHidden = [];
static readonly Dictionary<IntPtr, long> entranceShowPendingSince = [];
static readonly WinEventProc entranceCallback = OnEntranceWindowEvent;
static GCHandle entranceCallbackHandle;
static IntPtr entranceHook;
static uint entranceExplorerPid;
static int entranceMode, entranceDuration;
static long nextAutoHideCheck;
static bool cachedAutoHide;
static void StopEntranceHook()
{
if (entranceHook != IntPtr.Zero) UnhookWinEvent(entranceHook);
entranceHook = IntPtr.Zero;
entranceExplorerPid = 0;
if (entranceCallbackHandle.IsAllocated) entranceCallbackHandle.Free();
}
public static void StopEntranceTracking()
{
StopEntranceHook();
entranceWasHidden.Clear();
entranceShowPendingSince.Clear();
}
static void EnsureEntranceHook()
{
GetWindowThreadProcessId(FindWindow("Shell_TrayWnd", null), out uint pid);
if (entranceHook != IntPtr.Zero && entranceExplorerPid == pid) return;
StopEntranceHook();
entranceWasHidden.Clear();
entranceShowPendingSince.Clear();
if (pid == 0) return;
// Explorer's window-location event arrives as its native auto-hide reveal begins.
// The callback runs on this WinForms UI thread; no polling animation timer is needed.
entranceCallbackHandle = GCHandle.Alloc(entranceCallback);
entranceHook = SetWinEventHook(0x800B, 0x800B, IntPtr.Zero, entranceCallback, pid, 0, 0x0002);
if (entranceHook == IntPtr.Zero) entranceCallbackHandle.Free();
else entranceExplorerPid = pid;
}
static void OnEntranceWindowEvent(IntPtr hook, uint eventType, IntPtr window, int objectId, int childId,
uint eventThread, uint eventTime)
{
try
{
if (hook != entranceHook || objectId != 0 || childId != 0 || !Handles().Contains(window)) return;
ObserveEntrance(window, animate: true);
}
catch { /* An Explorer or display transition must not unwind through a native callback. */ }
}
static void ObserveEntrance(IntPtr window, bool animate)
{
if (!IsWindowVisible(window) || !GetWindowRect(window, out var rect)) return;
var bar = Rectangle.FromLTRB(rect.Left, rect.Top, rect.Right, rect.Bottom);
var visible = Rectangle.Intersect(bar, Screen.FromHandle(window).Bounds);
bool hidden = visible.Height <= 2 || visible.Width <= 2;
bool revealing = visible.Height > 2 && visible.Width > 2;
if (!entranceWasHidden.TryGetValue(window, out bool wasHidden) || hidden)
{
entranceWasHidden[window] = hidden;
entranceShowPendingSince.Remove(window);
return;
}
if (!revealing || !wasHidden) return;
if (!animate)
{
// Let the window event start the effect. A timer tick must not consume
// the reveal first and make a later event look like a second movement.
long now = Environment.TickCount64;
if (!entranceShowPendingSince.TryGetValue(window, out long firstSeen))
entranceShowPendingSince[window] = now;
else if (now - firstSeen > 300)
{
entranceWasHidden[window] = false;
entranceShowPendingSince.Remove(window);
}
return;
}
bool late = entranceShowPendingSince.TryGetValue(window, out long firstVisible) &&
Environment.TickCount64 - firstVisible > 300;
entranceWasHidden[window] = false;
entranceShowPendingSince.Remove(window);
var tap = TapWindow();
if (!late && tap != IntPtr.Zero)
PostMessage(tap, 0x8008, window, (IntPtr)((entranceDuration << 8) | entranceMode));
}
public static void PollEntrance(int mode, int durationMs, bool enabled)
{
entranceMode = Math.Clamp(mode, 0, 3);
entranceDuration = Math.Clamp(durationMs, 80, 450);
if (entranceMode == 0 || !enabled) { StopEntranceTracking(); return; }
if (Environment.TickCount64 >= nextAutoHideCheck)
{
cachedAutoHide = AutoHide;
nextAutoHideCheck = Environment.TickCount64 + 1000;
}
if (!cachedAutoHide) { StopEntranceTracking(); return; }
EnsureEntranceHook();
var handles = Handles().ToArray();
foreach (var stale in entranceWasHidden.Keys.Except(handles).ToArray()) entranceWasHidden.Remove(stale);
foreach (var stale in entranceShowPendingSince.Keys.Except(handles).ToArray()) entranceShowPendingSince.Remove(stale);
foreach (var h in handles) ObserveEntrance(h, animate: false);
}
public static void ExplorerRestarted()
{
nextInject = 0;
fastInjectUntil = Environment.TickCount64 + 30_000;
}
public static bool SupportsMonitorLayouts => Environment.OSVersion.Version.Build >= 22000 && File.Exists(TapDll);
public static void SetPreviewReceiver(IntPtr handle)
{
if (previewReceiver == handle) return;
if (handle == IntPtr.Zero)
{
var tap = TapWindow();
if (tap != IntPtr.Zero) PostMessage(tap, 0x8004, IntPtr.Zero, IntPtr.Zero);
}
previewReceiver = handle;
lastPreviewRegisteredWindow = IntPtr.Zero;
}
// hideBackground: fade XAML background; trayMask: tray parts; hidePinned: show pinned-only buttons on demand.
public static void Tap(bool hideBackground, int trayMask, bool hidePinned, int keepPinned, ulong stackRanges = 0, int stackFlags = 0,
bool requireHelper = false)
{
var w = TapWindow();
if (w != IntPtr.Zero)
{
if (w != lastTapWindow) { lastTapWindow = w; lastPreviewRegisteredWindow = IntPtr.Zero; lastBackground = lastPinned = null; lastTrayMask = lastKeepPinned = lastStackFlags = -1; lastStackRanges = ulong.MaxValue; }
if (previewReceiver != IntPtr.Zero && w != lastPreviewRegisteredWindow)
{
PostMessage(w, 0x8004, previewReceiver, IntPtr.Zero);
lastPreviewRegisteredWindow = w;
}
if (lastBackground != hideBackground) { PostMessage(w, 0x8000, hideBackground ? 1 : 0, IntPtr.Zero); lastBackground = hideBackground; }
if (lastTrayMask != trayMask) { PostMessage(w, 0x8001, trayMask, IntPtr.Zero); lastTrayMask = trayMask; }
if (lastPinned != hidePinned || lastKeepPinned != keepPinned || (hidePinned && Environment.TickCount64 >= nextPinnedRefresh))
{
PostMessage(w, 0x8002, (keepPinned << 1) | (hidePinned ? 1 : 0), IntPtr.Zero);
lastPinned = hidePinned;
lastKeepPinned = keepPinned;
nextPinnedRefresh = Environment.TickCount64 + 5000;
}
if (lastStackRanges != stackRanges || lastStackFlags != stackFlags)
{
PostMessage(w, 0x8003, (IntPtr)unchecked((long)stackRanges), (IntPtr)stackFlags);
lastStackRanges = stackRanges;
lastStackFlags = stackFlags;
}
return;
}
if (lastTapWindow != IntPtr.Zero) { MonitorTapProtocol.Invalidate(); IdentityStackProtocol.Invalidate(); }
lastTapWindow = IntPtr.Zero;
lastPreviewRegisteredWindow = IntPtr.Zero;
if ((!requireHelper && !hideBackground && trayMask == 0 && !hidePinned && stackRanges == 0) ||
Environment.OSVersion.Version.Build < 22000 || !File.Exists(TapDll)) return;
if (Environment.TickCount64 < nextInject || Interlocked.Exchange(ref injecting, 1) == 1) return;
// Explorer may still be starting: retry every second just after sign-in or a restart, later every 5 s.
nextInject = Environment.TickCount64 + (Environment.TickCount64 < fastInjectUntil ? 1000 : 5000);
GetWindowThreadProcessId(FindWindow("Shell_TrayWnd", null), out var pid);
// Injected fine but no window: an old DLL from the same path is loaded. Re-injecting would only stack it up.
if (pid == 0 || pid == injectedPid) { injecting = 0; return; }
Task.Run(() =>
{
// Explorer only accepts its own endpoint names (VisualDiagConnection1, 2, ...) and rejects others with
// ERROR_NOT_FOUND; names are reusable, so scan from 1 instead of counting up across explorer restarts.
try
{
for (int i = 1; i <= 100; i++)
{
int hr = InitializeXamlDiagnosticsEx($"VisualDiagConnection{i}", pid, null, TapDll, TapClsid, null);
if (hr == 0) injectedPid = pid;
if (hr != unchecked((int)0x80070490)) break;
}
}
catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException) { }
finally { injecting = 0; }
});
}
public static void Show(bool visible) { foreach (var h in Handles()) ShowWindow(h, visible ? 5 : 0); }
public static IEnumerable<Rectangle> VisibleBounds()
{
foreach (var h in Handles())
if (IsWindowVisible(h) && GetWindowRect(h, out var r) && r.Right > r.Left && r.Bottom > r.Top)
yield return Rectangle.FromLTRB(r.Left, r.Top, r.Right, r.Bottom);
}
public static bool CoveredByFullscreenWindow(Rectangle bar)
{
var foreground = GetForegroundWindow();
if (foreground == IntPtr.Zero || foreground == FindWindow("Shell_TrayWnd", null) || !GetWindowRect(foreground, out var r)) return false;
var screen = (MonitorTaskbars.ScreenFor(bar) ?? Screen.FromRectangle(bar)).Bounds;
return LooksFullscreen(Rectangle.FromLTRB(r.Left, r.Top, r.Right, r.Bottom), screen,
IsZoomed(foreground), GetWindowLong(foreground, -16)); // GWL_STYLE
}
internal static bool LooksFullscreen(Rectangle window, Rectangle screen, bool maximized, int style)
{
if (window.Left > screen.Left + 2 || window.Top > screen.Top + 2 ||
window.Right < screen.Right - 2 || window.Bottom < screen.Bottom - 2) return false;
const int wsCaption = 0x00C00000;
// A normal maximized window extends its resize frame just past the
// monitor edge or retains a caption. F11 and borderless games usually
// remove that frame, even when Windows reports them as maximized.
bool ordinaryMaximized = maximized && (((style & wsCaption) == wsCaption) ||
window.Left < screen.Left - 2 || window.Top < screen.Top - 2 ||
window.Right > screen.Right + 2 || window.Bottom > screen.Bottom + 2);
return !ordinaryMaximized;
}
public static bool ActiveWindowMaximized => IsZoomed(GetForegroundWindow());
public static IntPtr ForegroundWindow => GetForegroundWindow();
static long nextTintRead;
static int cachedTintRgb;
static bool tintAvailable;
public static void InvalidateSystemTint() => nextTintRead = 0;
public static int SystemTint(int manualColor)
{
if (Environment.TickCount64 >= nextTintRead)
{
nextTintRead = Environment.TickCount64 + 30000;
tintAvailable = DwmGetColorizationColor(out uint accent, out _) == 0;
if (tintAvailable)
{
bool light = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "SystemUsesLightTheme", 0) is int mode && mode != 0;
int baseColor = light ? 0xF2F4F7 : 0x1A2232;
int Blend(int shift)
{
int a = (int)(accent >> shift) & 0xFF;
int b = (baseColor >> shift) & 0xFF;
return (a * 35 + b * 65) / 100;
}
cachedTintRgb = (Blend(16) << 16) | (Blend(8) << 8) | Blend(0);
}
}
return tintAvailable ? (manualColor & unchecked((int)0xFF000000)) | cachedTintRgb : manualColor;
}
[StructLayout(LayoutKind.Sequential)] struct NativeRect { public int Left, Top, Right, Bottom; }
static APPBARDATA Abd() => new() { cbSize = Marshal.SizeOf<APPBARDATA>(), hWnd = FindWindow("Shell_TrayWnd", null) };
public static bool AutoHide
{
get { var d = Abd(); return ((long)SHAppBarMessage(4, ref d) & 1) != 0; } // ABM_GETSTATE
set { var d = Abd(); d.lParam = value ? 1 : 2; SHAppBarMessage(10, ref d); } // ABM_SETSTATE
}
public static void Notify() => SendMessageTimeout(0xFFFF, 0x1A, IntPtr.Zero, "TraySettings", 2, 1000, out _);
public static async Task RestartExplorer()
{
foreach (var p in Process.GetProcessesByName("explorer")) { try { p.Kill(); } catch { /* other user's explorer */ } }
await Task.Delay(2500);
if (Process.GetProcessesByName("explorer").Length == 0) Process.Start("explorer.exe");
}
}
record Tweak(string Label, string Key, string Name, int Default, string[]? Options = null)
{
public int Get() { using var k = Registry.CurrentUser.OpenSubKey(Key); return k?.GetValue(Name) is int v ? v : Default; }
public void Set(int v) { using var k = Registry.CurrentUser.CreateSubKey(Key); k.SetValue(Name, v, RegistryValueKind.DWord); }
}
class Settings
{
public int Style { get; set; }
public int Color { get; set; } = 0x40000000;
public bool HideTaskbar { get; set; }
public bool EdgeHandle { get; set; }
public int TrayHide { get; set; } // bit mask, see TaskbarTap.cpp kParts
public bool ShowDesignClock { get; set; } // compatibility with settings saved before ClockLayout existed
public int ClockLayout { get; set; } // 0 off, 1 time, 2 time and date
public bool ClockOnPrimaryOnly { get; set; }
public string? SecondaryTimeZoneId { get; set; }
public List<string> WorldTimeZoneIds { get; set; } = [];
public ShortcutConfig Shortcuts { get; set; } = new();
public bool ShowMediaRail { get; set; }
public bool HidePinnedUntilAlt { get; set; }
public bool FocusLens { get; set; }
public bool WheelCycleWindows { get; set; }
public int HoverAnimation { get; set; }
public int EntranceAnimation { get; set; }
public int EntranceDurationMs { get; set; } = 200;
public int KeepPinnedCount { get; set; }
public bool TrayOnDemand { get; set; }
public int[]? RightModes { get; set; }
public bool AutoContrast { get; set; }
public bool WallpaperAccent { get; set; }
public bool FollowWindowsTheme { get; set; }
public string LightThemeId { get; set; } = "pearl";
public string DarkThemeId { get; set; } = "glass";
public bool AppAccent { get; set; }
public Dictionary<string, int> AppAccentColors { get; set; } = [];
public bool ContextStyle { get; set; }
public int MaximizedStyle { get; set; } = 2;
public CleanBackup? CleanBackup { get; set; }
public List<string> HiddenPrograms { get; set; } = [];
public List<string> PresentationHiddenPrograms { get; set; } = [];
public List<SavedProfile?> Profiles { get; set; } = [null, null];
public bool WelcomeSeen { get; set; }
public bool AutoUpdates { get; set; } = true;
public string Language { get; set; } = Localization.English;
public AppStackConfig AppStacks { get; set; } = new();
public List<string> FolderStackPaths { get; set; } = [];
public List<string> SharedThemes { get; set; } = [];
public List<SceneSnapshot> Scenes { get; set; } = [];
public List<SceneRule> SceneRules { get; set; } = [];
public List<WorkspaceScene> Workspaces { get; set; } = [];
public List<MonitorLayout> MonitorLayouts { get; set; } = [];
public static readonly string Dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TaskbarTweaker");
static string FilePath => Path.Combine(Dir, "settings.json");
public static Settings Load()
{
try { return Parse(File.ReadAllText(FilePath)); }
catch { return new() { RightModes = RightAreaModes.Default() }; }
}
// Reads settings JSON and repairs out-of-range or missing values. Throws on invalid JSON.
internal static Settings Parse(string json)
{
{
var s = JsonSerializer.Deserialize<Settings>(json) ?? new();
if (s.ShowDesignClock && s.ClockLayout == 0) s.ClockLayout = 2;
s.ClockLayout = Math.Clamp(s.ClockLayout, 0, 2);
s.HoverAnimation = Math.Clamp(s.HoverAnimation, 0, 3);
s.EntranceAnimation = Math.Clamp(s.EntranceAnimation, 0, 3);
s.EntranceDurationMs = Math.Clamp(s.EntranceDurationMs, 80, 450);
s.Style = Math.Clamp(s.Style, 0, 5);
s.MaximizedStyle = Math.Clamp(s.MaximizedStyle, 0, 5);
s.KeepPinnedCount = Math.Clamp(s.KeepPinnedCount, 0, 5);
s.RightModes = RightAreaModes.Normalize(s.RightModes, s.TrayHide, s.TrayOnDemand);
s.AppStacks ??= new();
s.AppStacks.Normalize();
s.FolderStackPaths ??= [];
s.PresentationHiddenPrograms ??= [];
s.SharedThemes ??= [];
s.Language ??= Localization.English;
s.Scenes ??= [];
s.SceneRules ??= [];
s.Workspaces ??= [];
s.MonitorLayouts ??= [];
s.WorldTimeZoneIds = (s.WorldTimeZoneIds ?? []).Take(2).Select(id => id ?? "").ToList();
if (s.Shortcuts == null || !s.Shortcuts.IsValid()) s.Shortcuts = new();
s.AppAccentColors = (s.AppAccentColors ?? []).Where(item => Path.IsPathFullyQualified(item.Key))
.GroupBy(item => item.Key, StringComparer.OrdinalIgnoreCase).Take(40)
.ToDictionary(group => group.Key, group => group.Last().Value & 0xFFFFFF, StringComparer.OrdinalIgnoreCase);
s.Profiles ??= [null, null];
while (s.Profiles.Count < 2) s.Profiles.Add(null);
if (s.Profiles.Count > 2) s.Profiles.RemoveRange(2, s.Profiles.Count - 2);
return s;
}
}
public void Save() { Directory.CreateDirectory(Dir); File.WriteAllText(FilePath, JsonSerializer.Serialize(this)); }
}
class CleanBackup
{
public Dictionary<string, int> Values { get; set; } = [];
public int TrayHide { get; set; }
public bool TrayOnDemand { get; set; }
public int[]? RightModes { get; set; }
}
class SavedProfile
{
public int Version { get; set; } = 1;
public int Style { get; set; }
public int Color { get; set; }
public bool AutoContrast { get; set; }
public bool WallpaperAccent { get; set; }
public bool AppAccent { get; set; }
public bool ContextStyle { get; set; }
public int MaximizedStyle { get; set; } = 2;
public int ClockLayout { get; set; }
public bool ClockOnPrimaryOnly { get; set; }
public string? SecondaryTimeZoneId { get; set; }
public bool ShowMediaRail { get; set; }
public bool HidePinnedUntilAlt { get; set; }
public bool FocusLens { get; set; }
public bool WheelCycleWindows { get; set; }
public int HoverAnimation { get; set; }
public int EntranceAnimation { get; set; }
public int EntranceDurationMs { get; set; } = 200;
public AppStackConfig? AppStacks { get; set; }
public int KeepPinnedCount { get; set; }
public int TrayHide { get; set; }
public bool TrayOnDemand { get; set; }
public int[]? RightModes { get; set; }
public bool AutoHide { get; set; }
public bool EdgeHandle { get; set; }
public Dictionary<string, int> Tweaks { get; set; } = [];
public List<string> HiddenPrograms { get; set; } = [];
}
class MainForm : Form
{
const string Adv = @"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced";
const string Search = @"Software\Microsoft\Windows\CurrentVersion\Search";
const string Taskband = @"Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband";
const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
static readonly Tweak[] Tweaks =
[
new("Ausrichtung", Adv, "TaskbarAl", 1, ["Links", "Mitte"]),
new("Suche", Search, "SearchboxTaskbarMode", 1, ["Ausgeblendet", "Nur Symbol", "Suchfeld", "Schaltfläche"]),
new("Gruppieren / Beschriftung", Adv, "TaskbarGlomLevel", 0, ["Immer gruppieren, keine Beschriftung", "Wenn Taskleiste voll", "Nie gruppieren"]),
new("Aufgabenansicht-Button", Adv, "ShowTaskViewButton", 1),
new("Widgets", Adv, "TaskbarDa", 1),
new("Copilot-Button", Adv, "ShowCopilotButton", 1),
new("Chat/Teams-Button", Adv, "TaskbarMn", 1),
new("Badges (Zähler auf Icons)", Adv, "TaskbarBadges", 1),
new("Blinkende Apps", Adv, "TaskbarFlashing", 1),
new("Sekunden in der Uhr", Adv, "ShowSecondsInSystemClock", 0),
new("Desktop-anzeigen-Ecke ganz rechts", Adv, "TaskbarSd", 1),
new("Taskleiste auf allen Monitoren", Adv, "MMTaskbarEnabled", 1),
new("\"Task beenden\" im Rechtsklickmenü", Adv + @"\TaskbarDeveloperSettings", "TaskbarEndTask", 0),
];
static readonly Dictionary<string, (string English, string German)> TweakHints = new()
{
["TaskbarAl"] = ("Where the app icons sit: on the left like Windows 10, or centered.", "Wo die App-Symbole sitzen: links wie bei Windows 10 oder mittig."),
["SearchboxTaskbarMode"] = ("How Windows Search appears on the taskbar.", "Wie die Windows-Suche auf der Taskleiste erscheint."),
["TaskbarGlomLevel"] = ("Whether the windows of one app share a single button, and when window names are shown.", "Ob die Fenster einer App einen gemeinsamen Button teilen und wann Fensternamen angezeigt werden."),
["ShowTaskViewButton"] = ("Button for Task View, the overview of open windows and desktops.", "Button für die Aufgabenansicht, die Übersicht über offene Fenster und Desktops."),
["TaskbarDa"] = ("Weather and news panel on the left of the taskbar.", "Wetter- und Newsbereich links auf der Taskleiste."),
["ShowCopilotButton"] = ("Button that opens Copilot.", "Button, der Copilot öffnet."),
["TaskbarMn"] = ("Teams chat button on older Windows 11 versions.", "Teams-Chat-Button auf älteren Windows-11-Versionen."),
["TaskbarBadges"] = ("Small counters on app icons, for example for unread mail.", "Kleine Zähler auf App-Symbolen, zum Beispiel für ungelesene Mails."),
["TaskbarFlashing"] = ("Apps that need your attention blink orange.", "Apps, die deine Aufmerksamkeit brauchen, blinken orange."),
["ShowSecondsInSystemClock"] = ("Shows seconds in the Windows clock. Uses a little more power.", "Zeigt Sekunden in der Windows-Uhr. Braucht etwas mehr Energie."),
["TaskbarSd"] = ("Clicking the far right edge of the taskbar shows the desktop.", "Ein Klick auf den äußersten rechten Rand der Taskleiste zeigt den Desktop."),
["MMTaskbarEnabled"] = ("Shows a taskbar on every monitor, not only on the main one.", "Zeigt auf jedem Monitor eine Taskleiste, nicht nur auf dem Hauptmonitor."),
["TaskbarEndTask"] = ("Adds \"End task\" to the right-click menu of taskbar apps, to close apps that stopped responding.", "Fügt dem Rechtsklickmenü von Taskleisten-Apps \"Task beenden\" hinzu, um hängende Apps zu schließen."),
};
static readonly Dictionary<string, int> CleanValues = new()
{
["SearchboxTaskbarMode"] = 0,
["ShowTaskViewButton"] = 0,
["TaskbarDa"] = 0,
["ShowCopilotButton"] = 0,
["TaskbarMn"] = 0,
["TaskbarBadges"] = 0,
["TaskbarFlashing"] = 0,
};
readonly Settings s = Settings.Load();
ThemePicker? themePickerControl;
CheckBox? followThemeToggle;
Action? refreshAppearance;
readonly System.Windows.Forms.Timer timer = new() { Interval = 100 };
readonly AltSettingsButton altButton;
readonly DesignClock clock = new();
readonly TaskbarEdgeHandle edgeHandle = new();
readonly FullscreenTaskbarReveal fullscreenReveal = new();
readonly MediaRail mediaRail;
IStackPopup? stackPreview;
IntPtr stackPreviewBar;
int stackPreviewSlot = -1;
readonly CancellationTokenSource workspaceStop = new();
readonly ProgramHider programHider = new();
ReleaseUpdater? updater;
bool updateReady;
readonly NotifyIcon tray;
readonly SettingsShell settingsShell;
readonly HashSet<string> builtPages = new(StringComparer.Ordinal);
readonly List<SettingsIllustration> illustrations = [];
TableLayoutPanel grid = null!;
bool startHidden, exiting, reverting, openHotkeyWasDown, pinnedRevealed, rightRevealed, lastPinnedHidden, lastMaximized, updaterStarted;
bool presentationMode, presentationHotkeyWasDown, folderHotkeyWasDown;
DateTimeOffset? focusSessionEnd;
CheckBox? presentationToggle;
ToolStripMenuItem? presentationMenu;
long nextProgramScan, nextVisualRefresh, nextClockRefresh, rightRevealUntil, nextStackDensity;
int lastEffectiveTrayMask = -1;
ulong appliedStackRanges = ulong.MaxValue;
int appliedStackFlags = -1;
bool stackCollapseActive = true;
bool nativeLayoutReady;
IntPtr seenTapWindow;
long nextMonitorRefresh;
long nextSceneCheck;
long pendingDisplayCheckUntil;
int lastMonitorCount = Screen.AllScreens.Length;
bool restoringDockWorkspace;
string? activeAutoSceneId;
SceneSnapshot? beforeAutoScene;
int lastProfileHotkey;
int lastStackShortcutMask;
void UpdateClocks()
{
if (s.HideTaskbar || presentationMode || (s.ClockLayout == 0 &&
!s.MonitorLayouts.Any(layout => layout.Version == 1 && layout.ClockEnabled && layout.ClockLayout > 0)))
{
clock.HideAll();
return;
}
clock.SetWorldZones(s.WorldTimeZoneIds);
var pointer = Cursor.Position;
bool altDown = AltSettingsButton.AltDown;
clock.Update((screen, bar) =>
{
var visual = MonitorLayouts.Resolve(screen, s, s.MonitorLayouts, nativeLayoutReady);
if (visual.ClockLayout == 0) return new MonitorClock(0, visual.SecondaryTimeZoneId); // nothing to place
var overrideLayout = nativeLayoutReady ? MonitorLayouts.ForScreen(screen, s.MonitorLayouts) : null;
var modes = overrideLayout?.NativeVisibilityEnabled == true && overrideLayout.RightModes is { Length: 4 }
? overrideLayout.RightModes : s.RightModes!;
bool pointerRevealed = bar != Rectangle.Empty && RightAreaModes.HasMousePeek(modes) && NearRightArea(bar, pointer);
var layout = !s.HideTaskbar && !presentationMode && visual.ClockAllowed &&
RightAreaModes.ClockVisible(modes, rightRevealed || altDown, pointerRevealed) ? visual.ClockLayout : 0;
return new MonitorClock(layout, visual.SecondaryTimeZoneId);
});
}
bool HasNativeLayoutOverrides() => s.MonitorLayouts.Any(layout => layout.Version == 1 &&
(layout.AppearanceEnabled || layout.NativeVisibilityEnabled || layout.NativePinnedEnabled || layout.NativeStacksEnabled));
bool SendMonitorLayouts(bool altDown, Point pointer)
{
var tap = Taskbar.NativeTapWindow;
if (tap == IntPtr.Zero) return false;
var bars = MonitorTaskbars.Enumerate();
if (bars.Count == 0 || bars.Count > 8) return false;
var foreground = Taskbar.ForegroundWindow;
var foregroundScreen = foreground == IntPtr.Zero ? null : Screen.FromHandle(foreground);
bool maximized = Taskbar.ActiveWindowMaximized;
bool sampleAppIcon = s.AppAccent || s.MonitorLayouts.Any(layout => layout.AppAccent);
int? appTint = sampleAppIcon || s.AppAccentColors.Count > 0
? AppAccent.ForegroundColor(foreground, sampleAppIcon, s.AppAccentColors) : null;
var entries = new List<MonitorTapEntry>(bars.Count);
foreach (var bar in bars)
{
var layout = MonitorLayouts.ForScreen(bar.Screen, s.MonitorLayouts);
var visual = MonitorLayouts.Resolve(bar.Screen, s, s.MonitorLayouts, true);
bool activeHere = foregroundScreen != null &&
string.Equals(foregroundScreen.DeviceName, bar.Screen.DeviceName, StringComparison.OrdinalIgnoreCase);
int style = visual.ContextStyle && maximized && activeHere ? visual.MaximizedStyle : visual.Style;
var (accentState, accentColor) = MonitorAccent.Resolve(bar.Screen, visual, activeHere, maximized, appTint);
var modes = layout?.NativeVisibilityEnabled == true && layout.RightModes is { Length: 4 }
? layout.RightModes : s.RightModes!;
bool pointerOnBar = bar.Bounds.Contains(pointer);
bool pointerRevealed = RightAreaModes.HasMousePeek(modes) && NearRightArea(bar.Bounds, pointer);
bool focusActive = focusSessionEnd is { } focusEnd && DateTimeOffset.UtcNow < focusEnd;
uint trayMask = (uint)(presentationMode || focusActive ? 31 : RightAreaModes.HiddenMask(modes,
altDown || rightRevealed, pointerRevealed));
// Copy only for a per-monitor stack override; this runs every 200 ms for every taskbar.
var stacks = s.AppStacks;
if (layout?.NativeStacksEnabled == true)
{
stacks = stacks.Copy();
stacks.Enabled = true;
var visible = (layout.VisibleStackIds ?? []).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var group in stacks.Groups) group.Enabled = visible.Contains(group.Id.ToString("N"));
}
ulong spans = stacks.PackRanges();
bool hidePinned = layout?.NativePinnedEnabled == true ? layout.HidePinnedUntilAlt && !altDown :
s.HidePinnedUntilAlt && !pinnedRevealed;
if (spans != 0 || stacks.IdentityMask != 0) hidePinned = false;
uint keepPinned = (uint)(layout?.NativePinnedEnabled == true ? Math.Clamp(layout.KeepPinnedCount, 0, 5) : s.KeepPinnedCount);
// Alt, pointer and collapse only matter to stacks; leaving them out for bars without stacks
// keeps the tap from reapplying every taskbar item each time the pointer crosses the bar.
bool stacksHere = spans != 0 || stacks.IdentityMask != 0;
uint flags = (uint)((style > 0 ? 1 : 0) | (hidePinned ? 2 : 0) | (stacksHere && altDown ? 4 : 0) |
(stacksHere && pointerOnBar ? 8 : 0) | (stacksHere && stackCollapseActive ? 16 : 0));
entries.Add(new MonitorTapEntry(bar.Handle, spans, trayMask, flags, keepPinned,
(uint)accentState, unchecked((uint)accentColor), (uint)stacks.IdentityMask));
}
return MonitorTapProtocol.Send(tap, entries);
}
IEnumerable<string> CurrentHiddenPrograms => (s.HiddenPrograms ?? []).Concat(presentationMode ? s.PresentationHiddenPrograms ?? [] : []);
bool? lastSystemLight;
// Applies the light/dark theme only when Windows' mode actually changed (or the user just
// changed the follow settings). winBar's own WM_SETTINGCHANGE broadcasts also land here and
// must not undo a profile, scene or accent choice the user made under the same Windows mode.
void SyncWindowsTheme(bool force = false)
{
if (!s.FollowWindowsTheme) { lastSystemLight = null; return; }
bool light = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",
"SystemUsesLightTheme", 0) is int value && value != 0;
if (!force && lastSystemLight == light) return;
lastSystemLight = light;
var theme = ThemeCatalog.Find(light ? s.LightThemeId : s.DarkThemeId) ??
ThemeCatalog.Find(light ? "pearl" : "glass")!;
if (ThemeCatalog.Match(s)?.Id == theme.Id) return;
ThemeCatalog.ApplyTo(s, theme);
s.Save();
themePickerControl?.SetSelectedTheme(theme.Id);
refreshAppearance?.Invoke();
RefreshIllustrations();
nextVisualRefresh = nextMonitorRefresh = 0;
}
void DisableWindowsThemeFollow()
{
if (!s.FollowWindowsTheme) return;
s.FollowWindowsTheme = false;
if (followThemeToggle != null) followThemeToggle.Checked = false;
}
internal static Icon AppIcon(Size size)
{
using var stream = typeof(MainForm).Assembly.GetManifestResourceStream("winbar.ico")!;
return new Icon(stream, size);
}
public MainForm(bool startHidden)
{
this.startHidden = startHidden;
Localization.Configure(s.Language);
MainSettingsTranslations.Register();
settingsShell = new SettingsShell();
Text = Localization.T("winBar · Settings", "winBar · Einstellungen");
ClientSize = new Size(LogicalToDeviceUnits(960), Math.Min(LogicalToDeviceUnits(700), Screen.PrimaryScreen!.WorkingArea.Height * 9 / 10));
MinimumSize = new Size(LogicalToDeviceUnits(740), LogicalToDeviceUnits(500));
StartPosition = FormStartPosition.CenterScreen;
Icon = AppIcon(SystemInformation.IconSize);
Controls.Add(settingsShell);
altButton = new AltSettingsButton(OpenWindow, ChooseFocusSession, ShowPowerQuickMenu, ShowWorkspaceQuickMenu);
mediaRail = new MediaRail(this);
Header("Aussehen");
Section("Choose a theme", "Design auswählen");
foreach (var json in s.SharedThemes.Take(16))
try { ThemeCatalog.RegisterShared(ThemePackage.Import(json)); }
catch (Exception ex) when (ex is InvalidDataException or JsonException) { }
SyncWindowsTheme();
var themePicker = new ThemePicker();
themePickerControl = themePicker;
themePicker.SetSelectedTheme(ThemeCatalog.Match(s)?.Id);
themePicker.ThemeSelected += theme =>
{
DisableWindowsThemeFollow();
ThemeCatalog.ApplyTo(s, theme);
s.Save();
refreshAppearance?.Invoke();
RefreshIllustrations();
nextVisualRefresh = 0;
};
themePicker.Tag = Ui.OutsideCard;
Add(themePicker);
Section("Automatic light and dark", "Automatisch hell und dunkel");
var followWindowsTheme = Check("Follow Windows light/dark mode", s.FollowWindowsTheme);
followThemeToggle = followWindowsTheme;
Hint("When Windows switches between light and dark mode, winBar switches to the matching theme below.",
"Wenn Windows zwischen hellem und dunklem Modus wechselt, wechselt winBar zum passenden Design darunter.");
var themeChoices = ThemeCatalog.All.Take(6).Select(theme => theme.Name).ToArray();
var themeIds = ThemeCatalog.All.Take(6).Select(theme => theme.Id).ToArray();
var lightTheme = Combo("Light mode theme", themeChoices,
Math.Max(0, Array.IndexOf(themeIds, s.LightThemeId)));
var darkTheme = Combo("Dark mode theme", themeChoices,
Math.Max(0, Array.IndexOf(themeIds, s.DarkThemeId)));
lightTheme.Enabled = darkTheme.Enabled = s.FollowWindowsTheme;
followWindowsTheme.CheckedChanged += (_, _) =>
{
if (reverting) return;
s.FollowWindowsTheme = followWindowsTheme.Checked;
lightTheme.Enabled = darkTheme.Enabled = followWindowsTheme.Checked;
s.Save(); SyncWindowsTheme(force: true);
};
lightTheme.SelectedIndexChanged += (_, _) =>
{
if (reverting) return;
s.LightThemeId = themeIds[lightTheme.SelectedIndex];
s.Save(); SyncWindowsTheme(force: true);
};
darkTheme.SelectedIndexChanged += (_, _) =>
{
if (reverting) return;
s.DarkThemeId = themeIds[darkTheme.SelectedIndex];
s.Save(); SyncWindowsTheme(force: true);
};
var themeActions = new FlowLayoutPanel { AutoSize = true, WrapContents = true, Margin = Padding.Empty };
var exportTheme = new ModernButton { Text = "Design teilen…", AutoSize = true };
exportTheme.Click += (_, _) =>
{
using var file = new System.Windows.Forms.SaveFileDialog { Filter = "winBar-Design (*.json)|*.json", FileName = "winbar-design.json" };
if (file.ShowDialog(this) != DialogResult.OK) return;
var name = Path.GetFileNameWithoutExtension(file.FileName);
if (string.IsNullOrWhiteSpace(name)) name = "Eigenes Design";
name = name[..Math.Min(name.Length, 32)];
var color = Color.FromArgb(s.Color | unchecked((int)0xFF000000));
var current = ThemeCatalog.Match(s) ?? new ThemeDefinition("custom", name, "Eigenes winBar-Design",
s.Style, s.Color, s.AutoContrast, s.ContextStyle, s.MaximizedStyle, color, color, color);
try { ThemePackage.ExportFile(file.FileName, current); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ MessageBox.Show($"Design konnte nicht gespeichert werden:\n{ex.Message}", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); }
};
var importTheme = new ModernButton { Text = "Design laden…", AutoSize = true };
importTheme.Click += (_, _) =>
{
using var file = new System.Windows.Forms.OpenFileDialog { Filter = "winBar-Design (*.json)|*.json", CheckFileExists = true };
if (file.ShowDialog(this) != DialogResult.OK) return;
try
{
var theme = ThemePackage.ImportFile(file.FileName);
if (!ThemeCatalog.RegisterShared(theme)) throw new InvalidDataException("Zu viele Designs gespeichert.");
var json = ThemePackage.Export(theme);
s.SharedThemes.RemoveAll(saved =>
{
try { return ThemePackage.Import(saved).Id == theme.Id; }
catch (InvalidDataException) { return false; }
});
s.SharedThemes.Add(json);
DisableWindowsThemeFollow();
ThemeCatalog.ApplyTo(s, theme);
s.Save();
themePicker.RefreshThemes();
refreshAppearance?.Invoke();
nextVisualRefresh = 0;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{ MessageBox.Show($"Design konnte nicht geladen werden:\n{ex.Message}", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); }
};
themeActions.Controls.AddRange([exportTheme, importTheme]);
themeActions.Tag = Ui.OutsideCard;
Add(themeActions);
Guide(SettingsIllustrationKind.Appearance);
Section("Style and color", "Stil und Farbe");
var style = Combo("Stil", ["Standard", "Komplett transparent", "Farbe (getönt)", "Blur", "Acrylic", "Kontrast-Transparent"], s.Style);
(string, string)[] styleHints =
[
("Windows draws the taskbar as usual.", "Windows zeichnet die Taskleiste wie gewohnt."),
("No background at all; only icons and text stay visible.", "Gar kein Hintergrund; nur Symbole und Text bleiben sichtbar."),
("A flat color layer in the color and opacity below.", "Eine flache Farbfläche in der Farbe und Deckkraft darunter."),
("Blurs whatever is behind the taskbar and adds a light tint.", "Zeichnet alles hinter der Taskleiste unscharf und tönt es leicht."),
("Frosted glass like Windows menus: blur plus a stronger tint.", "Milchglas wie in Windows-Menüs: Unschärfe plus kräftigere Tönung."),
("Transparent, but darkens on bright wallpapers so icons stay readable.", "Transparent, wird aber auf hellen Hintergründen dunkler, damit Symbole lesbar bleiben."),
];
OptionHint(style, styleHints);
var colorBtn = new ModernButton { FlatStyle = FlatStyle.Flat, AutoSize = true };
colorBtn.Click += (_, _) =>
{
using var dlg = new ColorDialog { Color = Color.FromArgb(s.Color | unchecked((int)0xFF000000)), FullOpen = true };
if (dlg.ShowDialog() == DialogResult.OK) { DisableWindowsThemeFollow(); s.Color = (s.Color & unchecked((int)0xFF000000)) | (dlg.Color.ToArgb() & 0xFFFFFF); s.Save(); ShowColor(); RefreshIllustrations(); nextVisualRefresh = 0; }
};
var colorLbl = Caption("Farbe");
Add(colorBtn, colorLbl);
var alphaLbl = Caption("");
var alpha = new OpacitySlider { Value = (s.Color >> 24) & 0xFF };
alpha.ValueChanged += (_, _) =>
{
if (reverting) return;
DisableWindowsThemeFollow();
s.Color = (alpha.Value << 24) | (s.Color & 0xFFFFFF);
if (!alpha.IsDragging) s.Save();
ShowAlpha(); ShowColor(); RefreshIllustrations(); nextVisualRefresh = 0;
};
alpha.DragCompleted += (_, _) => s.Save();
Add(alpha, alphaLbl);
var opacityHint = new Label { AutoSize = true, ForeColor = SystemColors.GrayText };
Add(opacityHint, Caption(""));
style.SelectedIndexChanged += (_, _) =>
{
if (reverting) return;
DisableWindowsThemeFollow();
s.Style = style.SelectedIndex;
if (s.Style == 4) NormalizeAcrylicColor();
s.Save(); ShowStyle(); RefreshIllustrations(); nextVisualRefresh = 0;
};
ShowColor(); ShowAlpha(); ShowStyle();
void ShowColor()
{
var c = Color.FromArgb(s.Color | unchecked((int)0xFF000000));
bool usesTint = MonitorAccent.UsesManualTint(s.Style) ||
(s.ContextStyle && MonitorAccent.UsesManualTint(s.MaximizedStyle));
bool canChoose = usesTint && !s.AutoContrast && !s.AppAccent && !s.WallpaperAccent;
colorBtn.BackColor = canChoose ? c : Color.FromArgb(239, 243, 249);
colorBtn.ForeColor = canChoose && c.GetBrightness() <= 0.5f ? Color.White : Color.FromArgb(39, 58, 83);
colorBtn.Text = canChoose ? $"#{c.R:X2}{c.G:X2}{c.B:X2} – {Localization.T("change…", "ändern…")}" :
!usesTint ? s.Style == 5 ? Localization.T("Color adapts automatically", "Farbe passt sich automatisch an") :
Localization.T("Choose a tinted style", "Getönten Stil wählen") :
s.AutoContrast ? Localization.T("Color follows Windows", "Farbe folgt Windows") :
s.WallpaperAccent ? Localization.T("Color follows the wallpaper", "Farbe folgt dem Hintergrundbild") :
Localization.T("Color follows the active app", "Farbe folgt der aktiven App");
themePicker.SetSelectedTheme(ThemeCatalog.Match(s)?.Id);
}
void ShowAlpha() => alphaLbl.Text = Localization.T("Opacity", "Deckkraft");
void NormalizeAcrylicColor()
{
if ((s.Color & unchecked((int)0xFF000000)) != 0) return;
int rgb = s.Color & 0xFFFFFF;
s.Color = unchecked((int)0xA0000000) | (rgb == 0 ? 0x002A405A : rgb);
alpha.Value = (s.Color >> 24) & 0xFF;
ShowColor(); ShowAlpha();
}
// Only Farbe/Blur/Acrylic use the color; "transparent" always sends 0.
void ShowStyle()
{
bool usesTint = MonitorAccent.UsesManualTint(s.Style) ||
(s.ContextStyle && MonitorAccent.UsesManualTint(s.MaximizedStyle));
colorBtn.Enabled = colorLbl.Enabled = usesTint && !s.AutoContrast && !s.AppAccent && !s.WallpaperAccent;
alpha.Enabled = alphaLbl.Enabled = usesTint;
opacityHint.Text = !usesTint && (s.Style == 5 || (s.ContextStyle && s.MaximizedStyle == 5))
? Localization.T("Contrast clear stays subtle on dark backgrounds and adds a dark tint on bright ones.",
"Kontrast-Transparent bleibt auf dunklem Hintergrund dezent und tönt auf hellem dunkler.")
: !usesTint
? Localization.T("Choose Tinted color, Blur or Acrylic to adjust opacity.", "Wähle Getönt, Blur oder Acrylic, um die Deckkraft einzustellen.")
: Localization.T("Drag anywhere on the bar or use the arrow keys.", "Ziehe an einer beliebigen Stelle oder nutze die Pfeiltasten.");
ShowColor();
}
Section("Color sources", "Farbquellen");
var autoContrast = Check("Tönung an Windows-Akzent und hell/dunkel anpassen", s.AutoContrast);
Hint("Takes the tint from your Windows accent color and adjusts it when Windows switches between light and dark.",
"Übernimmt die Tönung aus deiner Windows-Akzentfarbe und passt sie an, wenn Windows zwischen hell und dunkel wechselt.");
var wallpaperAccent = Check(Localization.T("Tint from each display's wallpaper", "Tönung aus dem Hintergrundbild je Monitor"), s.WallpaperAccent);
Hint("Each monitor gets a calm tint taken from its own wallpaper.", "Jeder Monitor bekommt eine ruhige Tönung aus seinem eigenen Hintergrundbild.");
var appAccent = Check("Tönung aus dem Symbol der aktiven App ableiten", s.AppAccent);
autoContrast.CheckedChanged += (_, _) =>
{
if (reverting) return;
s.AutoContrast = autoContrast.Checked;
if (s.AutoContrast) { s.WallpaperAccent = false; wallpaperAccent.Checked = false; }
s.Save(); ShowStyle(); RefreshIllustrations(); nextVisualRefresh = 0;
};
wallpaperAccent.CheckedChanged += (_, _) =>
{
if (reverting) return;
s.WallpaperAccent = wallpaperAccent.Checked;
if (s.WallpaperAccent)
{
s.AutoContrast = s.AppAccent = false;
reverting = true; autoContrast.Checked = appAccent.Checked = false; reverting = false;
WallpaperAccent.Invalidate();
}
s.Save(); ShowStyle(); RefreshIllustrations(); nextVisualRefresh = nextMonitorRefresh = 0;
};
appAccent.CheckedChanged += (_, _) =>
{