-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
2150 lines (1843 loc) · 76.5 KB
/
Copy pathProgram.cs
File metadata and controls
2150 lines (1843 loc) · 76.5 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
// havWndSwitcher
//
// ABOUT
//
// A WinForms background app that registers global hotkeys to switch windows with optional switching rules.
//
// REVISION HISTORY
//
// v1.0 (2025-12-31) - First release.
//
// LICENSE
//
// MIT License
//
// Copyright (c) 2025 René Nicolaus
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.Json;
namespace havWndSwitcher
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
AppPaths.Ensure(); // Create config dir
ConfigService.Load(AppPaths.ConfigFile);
var resolvedLanguage = Localization.ResolveLanguage(AppPaths.LangRoot, ConfigService.CurrentConfig.Language);
if (!string.Equals(resolvedLanguage, ConfigService.CurrentConfig.Language, StringComparison.OrdinalIgnoreCase))
{
ConfigService.CurrentConfig.Language = resolvedLanguage;
ConfigService.Save(AppPaths.ConfigFile);
}
Localization.Initialize(AppPaths.LangRoot, resolvedLanguage);
Application.Run(new SwitcherApp()); // No UI window
}
}
static class Localization
{
private static Dictionary<string, string> _languages = new();
public static void Initialize(string langRoot, string language)
{
_languages = LoadLanguageFile(Path.Combine(langRoot, "en.json")) ?? new Dictionary<string, string>();
if (!string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
{
MergeLanguageFile(Path.Combine(langRoot, $"{language}.json"), _languages);
}
}
public static string Entry(string key, params object[] args)
{
if (!_languages.TryGetValue(key, out var value))
{
value = key;
}
return args.Length == 0 ? value : string.Format(value, args);
}
public static string ResolveLanguage(string langRoot, string? requested)
{
var available = GetAvailableLanguages(langRoot).Select(x => x.Code).ToList();
if (!string.IsNullOrWhiteSpace(requested))
{
var normalized = requested!.Trim();
if (available.Contains(normalized, StringComparer.OrdinalIgnoreCase))
{
return normalized;
}
var dashIndex = normalized.IndexOf('-');
if (dashIndex > 0)
{
var shortCode = normalized.Substring(0, dashIndex);
if (available.Contains(shortCode, StringComparer.OrdinalIgnoreCase))
{
return shortCode;
}
}
}
var cultureCode = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
if (available.Contains(cultureCode, StringComparer.OrdinalIgnoreCase))
{
return cultureCode;
}
return "en";
}
public static List<(string Code, string Name)> GetAvailableLanguages(string langRoot)
{
if (!Directory.Exists(langRoot))
{
return [("en", "English")];
}
var list = new List<(string Code, string Name)>();
foreach (var file in Directory.GetFiles(langRoot, "*.json"))
{
var name = Path.GetFileNameWithoutExtension(file);
if (!string.IsNullOrWhiteSpace(name))
{
list.Add((name, ReadLanguageName(file, name)));
}
}
if (list.Count == 0)
{
return [("en", "English")];
}
list.Sort((a, b) => StringComparer.OrdinalIgnoreCase.Compare(a.Code, b.Code));
return list;
}
private static Dictionary<string, string>? LoadLanguageFile(string path)
{
if (!File.Exists(path))
{
return null;
}
try
{
var json = File.ReadAllText(path);
return JsonSerializer.Deserialize<Dictionary<string, string>>(json);
}
catch
{
}
return null;
}
private static void MergeLanguageFile(string path, Dictionary<string, string> target)
{
var data = LoadLanguageFile(path);
if (data is null)
{
return;
}
foreach (var kvp in data)
{
target[kvp.Key] = kvp.Value;
}
}
private static string ReadLanguageName(string path, string fallback)
{
var data = LoadLanguageFile(path);
if (data is not null && data.TryGetValue("LanguageName", out var name) && !string.IsNullOrWhiteSpace(name))
{
return name;
}
return fallback;
}
}
// Location: %AppData%\havWndSwitcher\config.json
class SwitcherConfig
{
public string Language { get; set; } = "en";
#if DEBUG
public bool DebugOverlay { get; set; } = false;
#endif
public bool PreferPerMonitor { get; set; } = true;
public bool SkipFullscreen { get; set; } = true;
public bool SuspendWhenFullscreen { get; set; } = true;
public bool BoostNewWindows { get; set; } = true;
public bool TaskbarWindowsOnly { get; set; } = true;
public bool PreferMainWindowPerProcess { get; set; } = true;
public bool IncludeMinimizedWindows { get; set; } = false;
public int BoostWindowAgeSeconds { get; set; } = 5;
public int NextWindowKey { get; set; } = (int)Keys.OemPeriod;
public int PreviousWindowKey { get; set; } = (int)Keys.Oemcomma;
public uint NextWindowModifiers { get; set; } = 0;
public uint PreviousWindowModifiers { get; set; } = 0;
public int FullscreenOverrideKey { get; set; } = (int)Keys.ShiftKey;
}
static class ConfigService
{
private static readonly JsonSerializerOptions _jsonSerializerOptions = new() { WriteIndented = true };
public static SwitcherConfig CurrentConfig { get; private set; } = new();
public static void Load(string path)
{
if (!File.Exists(path))
{
// Write default config on first run
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, JsonSerializer.Serialize(CurrentConfig, _jsonSerializerOptions));
return;
}
var json = File.ReadAllText(path);
CurrentConfig = JsonSerializer.Deserialize<SwitcherConfig>(json) ?? new();
}
public static void Save(string path)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, JsonSerializer.Serialize(CurrentConfig, _jsonSerializerOptions));
}
public static void ResetToDefaults()
{
CurrentConfig = new SwitcherConfig();
}
}
static class AppPaths
{
public static readonly string AppRoot = AppContext.BaseDirectory;
public static readonly string ConfigRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "havWndSwitcher");
public static string ConfigFile => Path.Combine(ConfigRoot, "config.json");
public static string LangRoot => Path.Combine(AppRoot, "languages");
public static void Ensure()
{
Directory.CreateDirectory(ConfigRoot);
}
}
#if DEBUG
class DebugOverlay : Form
{
private readonly Label _label = new();
public DebugOverlay()
{
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = false;
TopMost = true;
BackColor = Color.Black;
ForeColor = Color.Lime;
Opacity = 0.75;
Padding = new Padding(8);
AutoSize = true;
_label.AutoSize = true;
Controls.Add(_label);
StartPosition = FormStartPosition.Manual;
Location = new Point(10, 10);
}
public void UpdateText(string text)
{
_label.Text = text;
}
}
#endif
class MessageWindow : NativeWindow, IDisposable
{
private readonly SwitcherApp _app;
private const int WM_HOTKEY = 0x0312;
public MessageWindow(SwitcherApp app)
{
_app = app;
CreateHandle(new CreateParams()); // Invisible, no taskbar entry
}
protected override void WndProc(ref Message message)
{
if (message.Msg == WM_HOTKEY)
{
_app.OnHotkey(message.WParam.ToInt32());
}
base.WndProc(ref message);
}
public void Dispose()
{
DestroyHandle();
GC.SuppressFinalize(this);
}
}
class SettingsDialog : Form
{
private sealed class LanguageOption(string code, string label)
{
public string Code { get; } = code;
public string Label { get; } = label;
public override string ToString() => Label;
}
private sealed class ModifierOption(string label, uint modifier)
{
public string Label { get; } = label;
public uint Modifier { get; } = modifier;
public override string ToString() => Label;
}
private readonly TextBox _nextWindowKeyBox = new();
private readonly TextBox _previousWindowKeyBox = new();
private readonly CheckedListBox _nextWindowMods = new();
private readonly CheckedListBox _previousWindowMods = new();
private readonly TextBox _overrideKeyBox = new();
private readonly Button _nextWindowCapture = new();
private readonly Button _previousWindowCapture = new();
private readonly Button _overrideCapture = new();
private readonly NumericUpDown _freshSeconds = new();
private readonly ComboBox _language = new();
private TextBox? _captureTarget;
private Action<Keys>? _captureSetter;
private bool _suppressModifierEvents;
public Keys NextWindowKey => _nextWindowKey;
public Keys PreviousWindowKey => _previousWindowKey;
public uint NextWindowModifiers => GetModifiers(_nextWindowMods);
public uint PreviousWindowModifiers => GetModifiers(_previousWindowMods);
public Keys FullscreenOverrideKey => _overrideKey;
public int BoostWindowAgeSeconds => (int)_freshSeconds.Value;
public string Language => (_language.SelectedItem as LanguageOption)?.Code ?? "en";
private Keys _nextWindowKey;
private Keys _previousWindowKey;
private Keys _overrideKey;
public SettingsDialog(Keys nextWindow, Keys previousWindow, uint nextWindowMods, uint previousWindowMods, Keys fullscreenOverrideKey, int boostWindowAgeSeconds, string language)
{
Text = Localization.Entry("Dialog_Settings_Title");
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = false;
MinimizeBox = false;
StartPosition = FormStartPosition.CenterScreen;
KeyPreview = true;
KeyDown += OnDialogKeyDown;
var nextWindowLabel = new Label { Text = Localization.Entry("Dialog_NextWindow"), AutoSize = true };
var nextWindowModsLabel = new Label { Text = Localization.Entry("Dialog_Modifiers"), AutoSize = true };
var previousWindowLabel = new Label { Text = Localization.Entry("Dialog_PreviousWindow"), AutoSize = true };
var previousWindowModsLabel = new Label { Text = Localization.Entry("Dialog_Modifiers"), AutoSize = true };
var overrideLabel = new Label { Text = Localization.Entry("Dialog_FullscreenOverride"), AutoSize = true };
var freshLabel = new Label { Text = Localization.Entry("Dialog_BoostWindowAge"), AutoSize = true };
var languageLabel = new Label { Text = Localization.Entry("Dialog_Language"), AutoSize = true };
_nextWindowKey = nextWindow;
_previousWindowKey = previousWindow;
_overrideKey = fullscreenOverrideKey;
const int leftMargin = 12;
const int rowGap = 12;
const int labelToControlOffset = 4;
const int labelToButtonOffset = 6;
const int bottomMargin = 12;
var captureLeft = 350;
var labelRight = new[]
{
nextWindowLabel,
nextWindowModsLabel,
previousWindowLabel,
previousWindowModsLabel,
overrideLabel
}.Max(label => leftMargin + TextRenderer.MeasureText(label.Text, label.Font).Width);
var fieldLeft = Math.Max(100, labelRight + 8);
var fieldWidth = Math.Max(120, captureLeft - fieldLeft - 10);
_nextWindowCapture.Click += (_, __) => BeginCapture(_nextWindowKeyBox, value => _nextWindowKey = value);
_previousWindowCapture.Click += (_, __) => BeginCapture(_previousWindowKeyBox, value => _previousWindowKey = value);
_overrideCapture.Click += (_, __) => BeginCapture(_overrideKeyBox, value => _overrideKey = value);
_freshSeconds.Width = 80;
_freshSeconds.Minimum = 1;
_freshSeconds.Maximum = 60;
_freshSeconds.Value = Math.Max(1, Math.Min(60, boostWindowAgeSeconds));
_language.Width = fieldWidth;
_language.DropDownStyle = ComboBoxStyle.DropDownList;
_language.Items.AddRange(BuildLanguageOptions().Cast<object>().ToArray());
var selectedLang = string.IsNullOrWhiteSpace(language) ? "en" : language;
_language.SelectedItem = FindLanguageOption(selectedLang) ?? _language.Items.Cast<LanguageOption>().FirstOrDefault();
_nextWindowMods.Width = fieldWidth;
_previousWindowMods.Width = fieldWidth;
_nextWindowMods.CheckOnClick = true;
_previousWindowMods.CheckOnClick = true;
var modifierOptions = new[]
{
new ModifierOption(Localization.Entry("Modifier_AltGr"), SwitcherApp.MOD_ALT | SwitcherApp.MOD_CONTROL),
new ModifierOption(Localization.Entry("Modifier_Alt"), SwitcherApp.MOD_ALT),
new ModifierOption(Localization.Entry("Modifier_Ctrl"), SwitcherApp.MOD_CONTROL),
new ModifierOption(Localization.Entry("Modifier_Shift"), SwitcherApp.MOD_SHIFT),
new ModifierOption(Localization.Entry("Modifier_Win"), SwitcherApp.MOD_WIN)
};
_nextWindowMods.Items.AddRange(modifierOptions.Cast<object>().ToArray());
_previousWindowMods.Items.AddRange(modifierOptions.Select(option =>
new ModifierOption(option.Label, option.Modifier)).Cast<object>().ToArray());
_nextWindowMods.ItemCheck += (_, e) => HandleModifierItemCheck(_nextWindowMods, e);
_previousWindowMods.ItemCheck += (_, e) => HandleModifierItemCheck(_previousWindowMods, e);
_nextWindowMods.IntegralHeight = false;
_previousWindowMods.IntegralHeight = false;
_nextWindowMods.Height = (_nextWindowMods.ItemHeight * _nextWindowMods.Items.Count) + 4;
_previousWindowMods.Height = (_previousWindowMods.ItemHeight * _previousWindowMods.Items.Count) + 4;
ApplyModifiers(_nextWindowMods, nextWindowMods);
ApplyModifiers(_previousWindowMods, previousWindowMods);
var y = 16;
nextWindowLabel.Location = new Point(leftMargin, y);
ConfigureKeyBox(_nextWindowKeyBox, new Point(fieldLeft, y - labelToControlOffset), fieldWidth, _nextWindowKey);
ConfigureCaptureButton(_nextWindowCapture, new Point(captureLeft, y - labelToButtonOffset));
y = (y - labelToControlOffset) + _nextWindowKeyBox.Height + rowGap;
nextWindowModsLabel.Location = new Point(leftMargin, y);
_nextWindowMods.Location = new Point(fieldLeft, y - labelToControlOffset);
y = (y - labelToControlOffset) + _nextWindowMods.Height + rowGap;
previousWindowLabel.Location = new Point(leftMargin, y);
ConfigureKeyBox(_previousWindowKeyBox, new Point(fieldLeft, y - labelToControlOffset), fieldWidth, _previousWindowKey);
ConfigureCaptureButton(_previousWindowCapture, new Point(captureLeft, y - labelToButtonOffset));
y = (y - labelToControlOffset) + _previousWindowKeyBox.Height + rowGap;
previousWindowModsLabel.Location = new Point(leftMargin, y);
_previousWindowMods.Location = new Point(fieldLeft, y - labelToControlOffset);
y = (y - labelToControlOffset) + _previousWindowMods.Height + rowGap;
overrideLabel.Location = new Point(leftMargin, y);
ConfigureKeyBox(_overrideKeyBox, new Point(fieldLeft, y - labelToControlOffset), fieldWidth, _overrideKey);
ConfigureCaptureButton(_overrideCapture, new Point(captureLeft, y - labelToButtonOffset));
y = (y - labelToControlOffset) + _overrideKeyBox.Height + rowGap;
freshLabel.Location = new Point(leftMargin, y);
_freshSeconds.Location = new Point(260, y - labelToControlOffset);
y = (y - labelToControlOffset) + _freshSeconds.Height + rowGap;
languageLabel.Location = new Point(leftMargin, y);
_language.Location = new Point(fieldLeft, y - labelToControlOffset);
y = (y - labelToControlOffset) + _language.Height + rowGap;
var reset = new Button { Text = Localization.Entry("Dialog_Reset"), Location = new Point(leftMargin, y), Width = 110 };
var ok = new Button { Text = Localization.Entry("Dialog_OK"), DialogResult = DialogResult.OK, Location = new Point(265, y) };
var cancel = new Button { Text = Localization.Entry("Dialog_Cancel"), DialogResult = DialogResult.Cancel, Location = new Point(345, y) };
ClientSize = new Size(440, y + reset.Height + bottomMargin);
reset.Click += (_, __) => ResetKeyBindings();
AcceptButton = ok;
CancelButton = cancel;
Controls.AddRange([
nextWindowLabel, _nextWindowKeyBox, _nextWindowCapture,
nextWindowModsLabel, _nextWindowMods,
previousWindowLabel, _previousWindowKeyBox, _previousWindowCapture,
previousWindowModsLabel, _previousWindowMods,
overrideLabel, _overrideKeyBox, _overrideCapture,
freshLabel, _freshSeconds,
languageLabel, _language,
reset, ok, cancel
]);
}
private static void ConfigureKeyBox(TextBox box, Point location, int width, Keys key)
{
box.Location = location;
box.Width = width;
box.ReadOnly = true;
box.Text = HotkeyText.FormatKey(key);
box.TabStop = true;
}
private static void ConfigureCaptureButton(Button button, Point location)
{
button.Text = Localization.Entry("Dialog_Change");
button.Location = location;
button.Size = new Size(75, 23);
}
private IEnumerable<LanguageOption> BuildLanguageOptions()
{
foreach (var item in Localization.GetAvailableLanguages(AppPaths.LangRoot))
{
yield return new LanguageOption(item.Code, item.Name);
}
}
private LanguageOption? FindLanguageOption(string code)
{
foreach (LanguageOption option in _language.Items)
{
if (string.Equals(option.Code, code, StringComparison.OrdinalIgnoreCase))
{
return option;
}
}
var fallback = new LanguageOption(code, GetLanguageLabel(code));
_language.Items.Add(fallback);
return fallback;
}
private static string GetLanguageLabel(string code)
{
return code;
}
private void ResetKeyBindings()
{
_nextWindowKey = Keys.OemPeriod;
_previousWindowKey = Keys.Oemcomma;
_overrideKey = Keys.ShiftKey;
_nextWindowKeyBox.Text = HotkeyText.FormatKey(_nextWindowKey);
_previousWindowKeyBox.Text = HotkeyText.FormatKey(_previousWindowKey);
_overrideKeyBox.Text = HotkeyText.FormatKey(_overrideKey);
ApplyModifiers(_nextWindowMods, SwitcherApp.MOD_NONE);
ApplyModifiers(_previousWindowMods, SwitcherApp.MOD_NONE);
_freshSeconds.Value = 5;
}
private void BeginCapture(TextBox box, Action<Keys> setter)
{
_captureTarget = box;
_captureSetter = setter;
box.Text = Localization.Entry("Dialog_PressAKey");
Focus();
}
private void OnDialogKeyDown(object? sender, KeyEventArgs e)
{
if (_captureTarget is null || _captureSetter is null)
{
return;
}
_captureSetter(e.KeyCode);
_captureTarget.Text = HotkeyText.FormatKey(e.KeyCode);
_captureTarget = null;
_captureSetter = null;
e.SuppressKeyPress = true;
e.Handled = true;
}
private static uint GetModifiers(CheckedListBox list)
{
uint mods = 0;
foreach (var item in list.CheckedItems)
{
if (item is ModifierOption option)
{
mods |= option.Modifier;
}
}
return mods;
}
private static void ApplyModifiers(CheckedListBox list, uint mods)
{
var remaining = mods;
for (int index = 0; index < list.Items.Count; ++index)
{
if (list.Items[index] is ModifierOption option &&
(remaining & option.Modifier) == option.Modifier)
{
list.SetItemChecked(index, true);
remaining &= ~option.Modifier;
}
else
{
list.SetItemChecked(index, false);
}
}
}
private void HandleModifierItemCheck(CheckedListBox list, ItemCheckEventArgs e)
{
if (_suppressModifierEvents)
{
return;
}
if (list.Items[e.Index] is not ModifierOption option)
{
return;
}
var altGrMask = SwitcherApp.MOD_ALT | SwitcherApp.MOD_CONTROL;
if (option.Modifier == altGrMask && e.NewValue == CheckState.Checked)
{
SetModifierChecked(list, SwitcherApp.MOD_ALT, false);
SetModifierChecked(list, SwitcherApp.MOD_CONTROL, false);
}
else if ((option.Modifier == SwitcherApp.MOD_ALT || option.Modifier == SwitcherApp.MOD_CONTROL) &&
e.NewValue == CheckState.Checked)
{
SetModifierChecked(list, altGrMask, false);
}
}
private void SetModifierChecked(CheckedListBox list, uint modifier, bool check)
{
_suppressModifierEvents = true;
try
{
for (int index = 0; index < list.Items.Count; ++index)
{
if (list.Items[index] is ModifierOption option && option.Modifier == modifier)
{
list.SetItemChecked(index, check);
}
}
}
finally
{
_suppressModifierEvents = false;
}
}
}
static class HotkeyText
{
public static string FormatHotkey(uint modifiers, int keyCode)
{
var modifierText = FormatModifiers(modifiers);
var keyText = FormatKey((Keys)keyCode);
if (string.IsNullOrEmpty(modifierText))
{
return keyText;
}
return $"{modifierText}+{keyText}";
}
public static string FormatModifiers(uint modifiers)
{
var parts = new List<string>();
if ((modifiers & SwitcherApp.MOD_CONTROL) != 0)
{
parts.Add(Localization.Entry("Modifier_Ctrl"));
}
if ((modifiers & SwitcherApp.MOD_ALT) != 0)
{
parts.Add(Localization.Entry("Modifier_Alt"));
}
if ((modifiers & SwitcherApp.MOD_SHIFT) != 0)
{
parts.Add(Localization.Entry("Modifier_Shift"));
}
if ((modifiers & SwitcherApp.MOD_WIN) != 0)
{
parts.Add(Localization.Entry("Modifier_Win"));
}
return string.Join("+", parts);
}
public static string FormatKey(Keys key)
{
if (key is >= Keys.D0 and <= Keys.D9)
{
var digit = (int)key - (int)Keys.D0;
return Localization.Entry($"Key_Digit{digit}");
}
if (key is >= Keys.NumPad0 and <= Keys.NumPad9)
{
var digit = (int)key - (int)Keys.NumPad0;
return Localization.Entry($"Key_Numpad{digit}");
}
return key switch
{
Keys.Return => Localization.Entry("Key_Enter"),
Keys.Escape => Localization.Entry("Key_Esc"),
Keys.Back => Localization.Entry("Key_Backspace"),
Keys.Tab => Localization.Entry("Key_Tab"),
Keys.Space => Localization.Entry("Key_Space"),
Keys.Insert => Localization.Entry("Key_Insert"),
Keys.Delete => Localization.Entry("Key_Delete"),
Keys.Home => Localization.Entry("Key_Home"),
Keys.End => Localization.Entry("Key_End"),
Keys.PageUp => Localization.Entry("Key_PageUp"),
Keys.PageDown => Localization.Entry("Key_PageDown"),
Keys.Left => Localization.Entry("Key_Left"),
Keys.Right => Localization.Entry("Key_Right"),
Keys.Up => Localization.Entry("Key_Up"),
Keys.Down => Localization.Entry("Key_Down"),
Keys.PrintScreen => Localization.Entry("Key_PrintScreen"),
Keys.Pause => Localization.Entry("Key_Pause"),
Keys.CapsLock => Localization.Entry("Key_CapsLock"),
Keys.NumLock => Localization.Entry("Key_NumLock"),
Keys.Scroll => Localization.Entry("Key_ScrollLock"),
Keys.LWin => Localization.Entry("Key_LeftWin"),
Keys.RWin => Localization.Entry("Key_RightWin"),
Keys.ShiftKey => Localization.Entry("Key_Shift"),
Keys.ControlKey => Localization.Entry("Key_Ctrl"),
Keys.Menu => Localization.Entry("Key_Alt"),
Keys.LMenu => Localization.Entry("Key_LeftAlt"),
Keys.RMenu => Localization.Entry("Key_RightAlt"),
Keys.Apps => Localization.Entry("Key_Menu"),
Keys.Add => Localization.Entry("Key_NumpadAdd"),
Keys.Subtract => Localization.Entry("Key_NumpadSubtract"),
Keys.Multiply => Localization.Entry("Key_NumpadMultiply"),
Keys.Divide => Localization.Entry("Key_NumpadDivide"),
Keys.Decimal => Localization.Entry("Key_NumpadDecimal"),
Keys.Oemcomma => Localization.Entry("Key_Comma"),
Keys.OemPeriod => Localization.Entry("Key_Period"),
Keys.OemMinus => Localization.Entry("Key_Minus"),
Keys.Oemplus => Localization.Entry("Key_Equals"),
Keys.OemQuestion => Localization.Entry("Key_Slash"),
Keys.OemSemicolon => Localization.Entry("Key_Semicolon"),
Keys.OemQuotes => Localization.Entry("Key_Apostrophe"),
Keys.OemOpenBrackets => Localization.Entry("Key_LeftBracket"),
Keys.OemCloseBrackets => Localization.Entry("Key_RightBracket"),
Keys.OemPipe or Keys.OemBackslash or Keys.Oem102 => Localization.Entry("Key_Backslash"),
Keys.Oemtilde => Localization.Entry("Key_Grave"),
_ => key.ToString()
};
}
}
class SwitcherApp : ApplicationContext
{
static class NativeHotkeys
{
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, int vk);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
}
static class NativeWindows
{
public const uint MONITOR_DEFAULTTONEAREST = 2;
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr GetWindow(IntPtr hWnd, uint cmd);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow(IntPtr hWnd, uint flags);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
[DllImport("user32.dll")]
public static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO mi);
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
[DllImport("dwmapi.dll")]
public static extern int DwmGetWindowAttribute(IntPtr hWnd, int dwAttribute, out RECT pvAttribute, int cbAttribute);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
public struct MONITORINFO
{
public uint cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
}
}
[DllImport("user32.dll")]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
const int GWL_STYLE = -16;
const int GWL_EXSTYLE = -20;
const int WS_EX_TOOLWINDOW = 0x00000080;
const int WS_EX_APPWINDOW = 0x00040000;
const int WS_CAPTION = 0x00C00000;
const int WS_THICKFRAME = 0x00040000;
const int WS_MAXIMIZE = 0x01000000;
const int WS_CHILD = 0x40000000;
const int SW_RESTORE = 9;
const int HOTKEY_NEXT_WINDOW = 1;
const int HOTKEY_PREVIOUS_WINDOW = 2;
const int HOTKEY_NEXT_WINDOW_OVERRIDE = 3;
const int HOTKEY_PREVIOUS_WINDOW_OVERRIDE = 4;
// Modifiers
public const uint MOD_NONE = 0x0000;
public const uint MOD_ALT = 0x0001;
public const uint MOD_CONTROL = 0x0002;
public const uint MOD_SHIFT = 0x0004;
public const uint MOD_WIN = 0x0008;
const uint GW_OWNER = 4;
private readonly NotifyIcon _tray;
private readonly MessageWindow _msgWindow;
#if DEBUG
private DebugOverlay? _overlay;
private ToolStripMenuItem? _toggleDebugOverlay;
#endif
private ToolStripMenuItem? _togglePreferPerMonitor;
private ToolStripMenuItem? _toggleSkipFullscreen;
private ToolStripMenuItem? _toggleSuspendWhenFullscreen;
private ToolStripMenuItem? _toggleBoostNewWindows;
private ToolStripMenuItem? _toggleTaskbarWindowsOnly;
private ToolStripMenuItem? _togglePreferMainWindowPerProcess;
private ToolStripMenuItem? _toggleIncludeMinimized;
// Boost target process
private static uint _boostTargetPid = 0;
// First-seen timestamps
private static readonly Dictionary<IntPtr, DateTime> _windowSeen = [];
private static readonly DateTime _seededAt = DateTime.MinValue;
private static readonly Dictionary<IntPtr, bool> _lastFullscreen = [];
private static readonly TimeSpan _cycleWindow = TimeSpan.FromMilliseconds(1500);
private List<IntPtr>? _cycleWindows;
private DateTime _cycleExpiresAt = DateTime.MinValue;
// Configurable freshness window
private TimeSpan _boostWindowAge => TimeSpan.FromSeconds(ConfigService.CurrentConfig.BoostWindowAgeSeconds);
public SwitcherApp()
{
_msgWindow = new MessageWindow(this);
_tray = BuildTrayIcon();
AppPaths.Ensure();
ConfigService.Load(AppPaths.ConfigFile);
var resolvedLanguage = Localization.ResolveLanguage(AppPaths.LangRoot, ConfigService.CurrentConfig.Language);
if (!string.Equals(resolvedLanguage, ConfigService.CurrentConfig.Language, StringComparison.OrdinalIgnoreCase))
{
ConfigService.CurrentConfig.Language = resolvedLanguage;
ConfigService.Save(AppPaths.ConfigFile);
}
Localization.Initialize(AppPaths.LangRoot, resolvedLanguage);
RebuildTrayMenu();
SeedWindowSeen();
#if DEBUG
if (ConfigService.CurrentConfig.DebugOverlay)
{
_overlay = new DebugOverlay();
_overlay.Show();
}
#endif
if (!RegisterHotkeys())
{
ShowTrayWarning(Localization.Entry("Hotkeys_Registration_Failed_All"));
}
else
{
ShowTrayInfo(Localization.Entry("Hotkeys_Registration_Success"));
}
}
public void OnHotkey(int id)
{
switch (id)
{
case HOTKEY_NEXT_WINDOW:
case HOTKEY_NEXT_WINDOW_OVERRIDE:
CycleNextWindow();
break;
case HOTKEY_PREVIOUS_WINDOW:
case HOTKEY_PREVIOUS_WINDOW_OVERRIDE:
CyclePreviousWindow();
break;
}
}
protected override void ExitThreadCore()
{
UnregisterHotkeys();
_tray.Visible = false;
_tray.Dispose();
_msgWindow.DestroyHandle();
base.ExitThreadCore();
}
private bool RegisterHotkeys()
{
uint nextWindowMods = ConfigService.CurrentConfig.NextWindowModifiers;
uint previousWindowMods = ConfigService.CurrentConfig.PreviousWindowModifiers;
bool nextWindow = NativeHotkeys.RegisterHotKey(_msgWindow.Handle, HOTKEY_NEXT_WINDOW, nextWindowMods, ConfigService.CurrentConfig.NextWindowKey);
bool previousWindow = NativeHotkeys.RegisterHotKey(_msgWindow.Handle, HOTKEY_PREVIOUS_WINDOW, previousWindowMods, ConfigService.CurrentConfig.PreviousWindowKey);
RegisterOverrideHotkeys(nextWindowMods, previousWindowMods);
if (!nextWindow || !previousWindow)
{
var missing = new List<string>();
if (!nextWindow)
{
missing.Add(Localization.Entry("Dialog_NextWindow"));
}
if (!previousWindow)
{
missing.Add(Localization.Entry("Dialog_PreviousWindow"));
}
ShowTrayWarning(Localization.Entry("Hotkeys_Registration_Failed", string.Join(", ", missing)));
}
return nextWindow && previousWindow;
}
private void RegisterOverrideHotkeys(uint nextWindowMods, uint previousWindowMods)
{
uint overrideModifier = GetOverrideModifier();
if (overrideModifier == MOD_NONE)
{
return;
}
uint nextWindowOverrideMods = nextWindowMods | overrideModifier;
if (nextWindowOverrideMods != nextWindowMods)
{
NativeHotkeys.RegisterHotKey(_msgWindow.Handle, HOTKEY_NEXT_WINDOW_OVERRIDE, nextWindowOverrideMods, ConfigService.CurrentConfig.NextWindowKey);
}
uint previousWindowOverrideMods = previousWindowMods | overrideModifier;
if (previousWindowOverrideMods != previousWindowMods)
{
NativeHotkeys.RegisterHotKey(_msgWindow.Handle, HOTKEY_PREVIOUS_WINDOW_OVERRIDE, previousWindowOverrideMods, ConfigService.CurrentConfig.PreviousWindowKey);
}
}
private void UnregisterHotkeys()
{
NativeHotkeys.UnregisterHotKey(_msgWindow.Handle, HOTKEY_NEXT_WINDOW);
NativeHotkeys.UnregisterHotKey(_msgWindow.Handle, HOTKEY_PREVIOUS_WINDOW);
NativeHotkeys.UnregisterHotKey(_msgWindow.Handle, HOTKEY_NEXT_WINDOW_OVERRIDE);
NativeHotkeys.UnregisterHotKey(_msgWindow.Handle, HOTKEY_PREVIOUS_WINDOW_OVERRIDE);
}
private void ShowTrayInfo(string message)
{
_tray.BalloonTipTitle = Localization.Entry("App_Title");