Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
1658 lines (1419 loc) · 59 KB
/
Copy pathProgram.cs
File metadata and controls
1658 lines (1419 loc) · 59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Windows.Forms;
using System.Xml.Serialization;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
// https://archive.softwareheritage.org/save/
public class QuickLauncher : Form, IMessageFilter
{
static string windowName = "Quick Launcher"; // Should match the titleLabel.Text or Form.Text
private NotifyIcon trayIcon;
private ContextMenuStrip trayMenu;
private ToolStripMenuItem idleToggleItem;
private Panel mainPanel;
private FlowLayoutPanel itemsPanel;
private QuickLauncherSettings appSettings;
private readonly string configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), windowName.Replace(" ", ""), windowName.Replace(" ", "") + "Settings.xml");
private QuickItemCollection currentItems { get { return (navigationStack.Count() == 0) ? rootItems : navigationStack.Peek(); } }
private QuickItemCollection rootItems { get { return appSettings.Items; } }
private Keys registeredHotkey { get { return appSettings.GlobalHotkey; } }
private Stack<QuickItemCollection> navigationStack = new Stack<QuickItemCollection>();
// Title bar elements
private Panel titleBar;
private FlowLayoutPanel titleBarRHS;
private Label titleLabel;
private Button closeButton;
private Button editButton;
private bool isDragging = false;
private Point lastCursor;
private Point lastForm;
// Add a unique message ID for communication between instances
private const int WM_SHOW_OR_HIDE_LAUNCHER = 0x0401; // Choose a unique value
// Single-instance IPC: the second instance posts this message to the first
// instance's window. The wParam encodes the requested action so the same
// hidden window can serve multiple entry points (hotkey, tray, CLI).
private const int SHOWMSG_TOGGLE = 0; // show if hidden / close-or-navigate if visible
private const int SHOWMSG_SHOW = 1; // always show
private const int SHOWMSG_EDIT = 2; // open the editor
/// <summary>
/// Command-line interface (handled by the primary instance):
/// QuickLaunch.exe -> toggle launcher (same as hotkey)
/// QuickLaunch.exe /show -> show launcher
/// QuickLaunch.exe /hide -> hide/close launcher
/// QuickLaunch.exe /edit -> open the editor
/// Unknown args are treated as toggle (legacy behaviour).
/// </summary>
private static int ShowMessageWParamForArgs(string[] args)
{
foreach (var raw in args ?? Array.Empty<string>())
{
var a = raw.TrimStart('/', '-').ToLowerInvariant();
switch (a)
{
case "show": return SHOWMSG_SHOW;
case "hide": return SHOWMSG_TOGGLE; // toggles off if visible, shows if hidden
case "edit": return SHOWMSG_EDIT;
}
}
return SHOWMSG_TOGGLE;
}
// P/Invoke declarations for finding and manipulating the window
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private const int SW_RESTORE = 9; // Restore window if minimized
private const int SW_SHOW = 5; // Show window
private const int SW_HIDE = 0; // Hide window
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr SetActiveWindow(IntPtr hWnd);
private const int WM_HOTKEY = 0x0312;
private const int HOTKEY_ID = 9000; // Choose a unique ID for your hotkey
// ---------------------------------------------------------------------
// Idle process-exiter: quits the app after a configurable period without
// any keyboard/mouse interaction (see ActivityMonitor below). The timer
// is only ticking while the launcher window is hidden; showing the
// launcher always counts as activity and resets it.
// ---------------------------------------------------------------------
private System.Windows.Forms.Timer idleExitTimer;
private bool exitingDueToIdle = false;
private bool activityFlagPending = false; // coalescing flag for the message-filter hook
public static QuickLauncher Instance { get; private set; }
/// <summary>
/// Win32 LASTINPUTINFO: seconds since the system-wide last input event.
/// Used as a safety net so an external process injecting keystrokes into a
/// child of this process (e.g. AutoHotkey re-sending SendKeys shortcuts)
/// can never trigger the idle auto-exit while the user is at the keyboard.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
private static double SystemIdleAgeMs()
{
try
{
var lii = new LASTINPUTINFO { cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO)) };
if (!GetLastInputInfo(ref lii)) return -1;
return (Environment.TickCount64 - lii.dwTime);
}
catch { return -1; }
}
private void InitializeIdleExitTimer()
{
idleExitTimer = new System.Windows.Forms.Timer();
// Poll at a fixed cadence; the actual timeout is compared against the
// configurable interval inside the Tick handler (see ApplyIdleSettings).
idleExitTimer.Interval = IdlePollMs;
idleExitTimer.Tick += (s, e) =>
{
if (!appSettings.AutoExitWhenIdle) return;
// Never exit while the window is visible or an item is running.
if (this.Visible || stopAutoClose) return;
double age = ActivityMonitor.LastActivityAgeMs;
// Safety net: LASTINPUTINFO reports input that happened *after* our
// recorded activity (e.g. keystrokes injected into one of our child
// processes by AutoHotkey, which low-level hooks do not observe).
// Trust whichever timestamp is more recent.
double sysAge = SystemIdleAgeMs();
if (sysAge >= 0 && sysAge < age) age = sysAge;
int timeout = (idleExitTimer.Tag is int tmo) ? tmo : IdleTimeoutMs;
if (age < timeout) return;
exitingDueToIdle = true;
idleExitTimer.Stop();
Application.Exit();
};
idleExitTimer.Start();
}
// How often the idle watchdog evaluates the timestamps (independent of the
// user-configurable timeout so polling stays cheap and predictable).
private const int IdlePollMs = 2000;
// Recompute the timeout whenever settings change (e.g. editor save / tray toggle).
private void ApplyIdleSettings()
{
if (idleExitTimer == null) return;
idleExitTimer.Tag = IdleTimeoutMs; // effective timeout, checked on each tick
idleExitTimer.Enabled = appSettings.AutoExitWhenIdle;
UpdateIdleToggleText();
}
// Keep the tray menu item label in sync with the configured timeout.
private void UpdateIdleToggleText()
{
if (idleToggleItem == null) return;
idleToggleItem.Text = appSettings.AutoExitWhenIdle
? $"Auto-exit when idle ({appSettings.IdleTimeoutSeconds}s)"
: "Auto-exit when idle (off)";
}
private int IdleTimeoutMs
{
get
{
var secs = appSettings.IdleTimeoutSeconds;
if (secs <= 0) secs = QuickLauncherSettings.DefaultIdleTimeoutSeconds;
return secs * 1000;
}
}
/// <summary>
/// Call this from every keyboard/mouse event that indicates the user is
/// interacting with the launcher. It resets the idle-exit countdown and,
/// as a safety net, restarts the monitor if a previous Application.Exit
/// was cancelled by another open form (e.g. the editor dialog).
/// </summary>
public static void RecordActivity()
{
ActivityMonitor.RecordActivity();
var inst = Instance;
if (inst != null && inst.exitingDueToIdle)
{
inst.exitingDueToIdle = false;
inst.ApplyIdleSettings();
}
}
// ------------------------------------------------------------------
// IMessageFilter: coalesced activity tracking for ALL messages pumped
// by this app's message loop (launcher window, editor dialog, tray).
// Input messages are frequent, so instead of writing the timestamp on
// every single one we set a flag and flush it at most once per 250 ms.
// ------------------------------------------------------------------
private const int ActivityFlushIntervalMs = 250;
private long lastActivityFlushTicks = 0;
public bool PreFilterMessage(ref Message m)
{
// WM_KEYDOWN..WM_MOUSELAST covers all keyboard & mouse input messages.
if (m.Msg >= 0x0100 && m.Msg <= 0x02FF)
{
activityFlagPending = true;
}
else if (activityFlagPending)
{
activityFlagPending = false;
var now = Environment.TickCount64;
if (now - lastActivityFlushTicks >= ActivityFlushIntervalMs)
{
lastActivityFlushTicks = now;
RecordActivity();
}
}
return false; // never consume messages
}
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, Keys vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[DllImport("user32")]
private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwnd2, int x, int y, int cx, int cy, int flags);
// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowpos
//instead of calling SetForegroundWindow
//SWP_NOSIZE = 1, SWP_NOMOVE = 2 -> keep the current pos and size (ignore x,y,cx,cy).
//the second param = -1 -> set window as Topmost.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Hide(); // Hide initially
// Register the global hotkey when the form loads. The hotkey is what
// summons the launcher, so it must work even without the tray icon;
// (previously it was gated on UseTrayIcon, which left no way to show
// the window when running tray-less).
RegisterGlobalHotkey();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
// If the user clicks the 'X', just hide the form and keep the tray icon
if (appSettings.UseTrayIcon && e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true; // Cancel the closing event
CloseOrHide();
}
else
{
// If closing for other reasons (e.g., Application.Exit), let it proceed
// Unregister hotkey (already handled in Dispose)
base.OnFormClosing(e);
}
}
private void InitializeTrayIcon()
{
Icon appIcon = SystemIcons.Application;
var iconResourceName = "QuickLaunch.Plant - Leafs.ico";
using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(iconResourceName))
{
if (stream != null)
{
try
{
appIcon = new Icon(stream);
}
catch (ArgumentException ex) // Catch potential errors from Icon constructor (e.g., invalid icon format)
{
}
}
else
{
}
}
trayMenu = new ContextMenuStrip();
var showItem = new ToolStripMenuItem("Show");
showItem.Click += (s, e) => ShowLauncher();
var editItem = new ToolStripMenuItem("Edit");
editItem.Click += (s, e) => OpenEditor();
var reloadItem = new ToolStripMenuItem("Reload Settings");
reloadItem.Click += (s, e) => ReloadSettingsFromDisk();
var openFolderItem = new ToolStripMenuItem("Open Settings Folder");
openFolderItem.Click += (s, e) => { try { Process.Start("explorer.exe", Path.GetDirectoryName(configPath)); } catch { } };
// Tray icon on/off toggle (hotkey registration is only active with the tray).
var trayToggleItem = new ToolStripMenuItem("Show Tray Icon")
{
Checked = appSettings.UseTrayIcon,
CheckOnClick = true
};
trayToggleItem.CheckedChanged += (s, e) =>
{
appSettings.UseTrayIcon = ((ToolStripMenuItem)s).Checked;
SaveConfiguration();
UpdateTrayVisibility();
RefreshGlobalHotkey();
};
// Idle-exit on/off toggle (kept in sync via SettingChanged).
idleToggleItem = new ToolStripMenuItem()
{
Checked = appSettings.AutoExitWhenIdle,
CheckOnClick = true
};
UpdateIdleToggleText();
idleToggleItem.CheckedChanged += (s, e) =>
{
appSettings.AutoExitWhenIdle = ((ToolStripMenuItem)s).Checked;
SaveConfiguration();
ApplyIdleSettings();
RecordActivity(); // toggling counts as usage -> fresh countdown
};
var exitItem = new ToolStripMenuItem("Exit");
exitItem.Click += (s, e) => Application.Exit(); // Use Application.Exit() to close the app properly
trayMenu.Items.Add(showItem);
trayMenu.Items.Add(editItem);
trayMenu.Items.Add(new ToolStripSeparator());
trayMenu.Items.Add(trayToggleItem);
trayMenu.Items.Add(idleToggleItem);
trayMenu.Items.Add(reloadItem);
trayMenu.Items.Add(openFolderItem);
trayMenu.Items.Add(new ToolStripSeparator()); // Optional separator
trayMenu.Items.Add(exitItem);
// Refresh dynamic labels (idle timeout text) each time the menu opens.
trayMenu.Opening += (s, e) => UpdateIdleToggleText();
trayIcon = new NotifyIcon()
{
Icon = appIcon,
// Icon = new Icon("path/to/your/icon.ico"), // Load a custom icon
Text = windowName, // Tooltip text
ContextMenuStrip = trayMenu, // Assign the context menu
Visible = false // actual visibility is driven by UpdateTrayVisibility()
};
// Optional: Double-clicking the tray icon can show the launcher
trayIcon.DoubleClick += (s, e) => ShowLauncher();
}
private int titleBarHeight = 26;
public QuickLauncher()
{
Instance = this;
// Load configuration
LoadConfiguration();
var panelWidth = 400;
var panelColor = Color.FromArgb(30, 30, 30);
var titleBarColor = Color.FromArgb(40, 40, 40);
// Initialize form
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.Manual;
this.BackColor = panelColor;
this.Size = new Size(panelWidth, 600);
this.WindowState = FormWindowState.Normal;
this.MinimizeBox = false;
this.MaximizeBox = false;
titleLabel = new Label
{
Text = windowName,
ForeColor = Color.White,
//BackColor = Color.Red,
TextAlign = ContentAlignment.MiddleCenter,
//Location = new Point(5, 5),
Anchor = AnchorStyles.Left | AnchorStyles.Right,
Dock = DockStyle.Fill,
//Width = panelWidth,
//AutoSize = true,
};
editButton = new Button
{
FlatStyle = FlatStyle.Flat,
ForeColor = Color.White,
Text = "Σ",
Size = new Size(titleBarHeight, titleBarHeight - 4),
Anchor = AnchorStyles.Right,
};
editButton.FlatAppearance.BorderSize = 0;
editButton.Click += (s, e) => OpenEditor();
closeButton = new Button
{
FlatStyle = FlatStyle.Flat,
ForeColor = Color.White,
Text = "✖",
Size = new Size(titleBarHeight, titleBarHeight - 4),
Anchor = AnchorStyles.Right // Anchor to the top-right
};
closeButton.FlatAppearance.BorderSize = 0;
closeButton.Click += (s, e) => { CloseOrHide(); };
// Title bar elements
titleBarRHS = new FlowLayoutPanel
{
Anchor = AnchorStyles.Right,
FlowDirection = FlowDirection.RightToLeft,
AutoSize = true,
AutoSizeMode = AutoSizeMode.GrowAndShrink,
};
titleBarRHS.Controls.Add(closeButton);
titleBarRHS.Controls.Add(editButton);
// Create title bar
titleBar = new Panel
{
Height = titleBarHeight,
Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right,
};
titleBar.Controls.Add(titleBarRHS);
titleBar.Controls.Add(titleLabel);
// Make title bar draggable
titleLabel.MouseDown += (s, e) => { isDragging = true; lastCursor = Cursor.Position; lastForm = this.Location; };
titleLabel.MouseMove += (s, e) => { if (isDragging) { this.Location = new Point(lastForm.X + (Cursor.Position.X - lastCursor.X), lastForm.Y + (Cursor.Position.Y - lastCursor.Y)); } };
titleLabel.MouseUp += (s, e) => { isDragging = false; };
// Create main content panel
itemsPanel = new FlowLayoutPanel
{
FlowDirection = FlowDirection.LeftToRight,
WrapContents = true,
AutoScroll = true,
//Width = this.Width,
//Height = this.Height,
Dock = DockStyle.Fill,
Padding = new Padding { Top = titleBarHeight },
//BackColor = Color.Red
};
mainPanel = new Panel
{
BackColor = panelColor,
Dock = DockStyle.Fill,
};
mainPanel.Controls.Add(titleBar);
mainPanel.Controls.Add(itemsPanel);
this.Controls.Add(mainPanel);
BuildUI();
// Handle form events. Any keyboard/mouse interaction with the launcher
// counts as activity and resets the idle-exit countdown (RecordActivity).
this.Deactivate += (s, e) => this.Hide();
this.KeyPreview = true;
this.KeyDown += (s, e) => {
RecordActivity();
if (e.KeyCode == Keys.Escape)
{
if (navigationStack.Count > 0)
{
// Go back to parent
navigationStack.Pop();
BuildUI();
}
else
{
CloseOrHide();
}
}
};
// Center on screen initially
CenterOnScreen();
SetWindowPos(this.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x1 | 0x2); // required to prevent app from closing automaticlaly when started if not focused and topmost.
SetActiveWindow(this.Handle);
// Install the global mouse/keyboard activity monitor that feeds the
// idle-exit timer (low-level hooks + message filter fallback).
ActivityMonitor.Install();
// Coalesced in-app activity tracking for every form/dialog we pump
// messages for (also covers the case where the low-level hooks fail).
Application.AddMessageFilter(this);
// Start the idle process-exiter countdown.
InitializeIdleExitTimer();
// DEBUG ONLY
//OpenEditor();
//System.Environment.Exit(0);
// The tray icon is always created so the app remains reachable even
// when UseTrayIcon is later toggled off/on without a restart; its
// visibility is driven by the setting via UpdateTrayVisibility().
InitializeTrayIcon();
UpdateTrayVisibility();
}
/// <summary>
/// Show or hide the tray icon according to <c>appSettings.UseTrayIcon</c>.
/// Safe to call before the tray icon exists.
/// </summary>
private void UpdateTrayVisibility()
{
if (trayIcon != null)
trayIcon.Visible = appSettings.UseTrayIcon;
}
/// <summary>
/// Re-register (or unregister) the global hotkey from the current settings.
/// </summary>
private void RefreshGlobalHotkey()
{
try { UnregisterHotKey(this.Handle, HOTKEY_ID); } catch { }
try { RegisterGlobalHotkey(); } catch { }
}
private void CloseOrHide()
{
RecordActivity(); // hiding via user action is still "usage"
this.Hide();
if (!appSettings.UseTrayIcon)
Application.Exit(); // no tray to live in -> same shutdown as idle-exit
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
}
private void LoadConfiguration()
{
if (!File.Exists(configPath))
{
CreateDefaultConfiguration();
SaveConfiguration();
return;
}
try
{
var serializer = new XmlSerializer(typeof(QuickLauncherSettings));
using var reader = new StreamReader(configPath);
appSettings = (QuickLauncherSettings)serializer.Deserialize(reader);
}
catch
{
appSettings = new QuickLauncherSettings();
}
if (appSettings.Items == null)
{
CreateDefaultConfiguration();
}
}
/// <summary>
/// Re-read the settings file from disk and rebuild the UI. Handy if you
/// edit QuickLauncherSettings.xml by hand (or with another tool) without
/// going through the editor.
/// </summary>
private void ReloadSettingsFromDisk()
{
navigationStack.Clear();
LoadConfiguration();
BuildUI();
ApplyIdleSettings();
UpdateTrayVisibility();
RefreshGlobalHotkey();
}
private void SaveConfiguration()
{
var dir = Path.GetDirectoryName(configPath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
var serializer = new XmlSerializer(typeof(QuickLauncherSettings));
using var writer = new StreamWriter(configPath);
serializer.Serialize(writer, appSettings);
}
private void CreateDefaultConfiguration()
{
if (appSettings == null) appSettings = new QuickLauncherSettings();
appSettings.Items = new QuickItemCollection()
{
Items = {
new QuickItem { Name = "Notepad", Type = QuickItemType.App, Path = "notepad.exe", ShortcutKey = Keys.N },
new QuickItem { Name = "Calculator", Type = QuickItemType.App, Path = "calc.exe", ShortcutKey = Keys.C },
new QuickItem { Name = "Command Prompt", Type = QuickItemType.App, Path = "cmd.exe", ShortcutKey = Keys.D },
new QuickItem { Name = "Utilities", Type = QuickItemType.Folder, ButtonColor = GetDefaultItemColor(QuickItemType.Folder), Items = new List<QuickItem>
{
new QuickItem { Name = "Paint", Type = QuickItemType.App, Path = "mspaint.exe", ShortcutKey = Keys.P },
new QuickItem { Name = "WordPad", Type = QuickItemType.App, Path = "write.exe", ShortcutKey = Keys.W },
new QuickItem { Name = "System Info", Type = QuickItemType.Command, ButtonColor = GetDefaultItemColor(QuickItemType.Command), Path = "systeminfo", ShortcutKey = Keys.I }
}
}
}
};
}
private void CenterOnScreen()
{
var screen = Screen.FromPoint(Cursor.Position);
var workingArea = screen.WorkingArea;
this.Location = new Point(
workingArea.Left + (workingArea.Width - this.Width) / 2,
workingArea.Top + (workingArea.Height - this.Height) / 2
);
}
public void ShowLauncher()
{
RecordActivity(); // summoning the launcher counts as usage
FixStack();
CenterOnScreen();
this.Show();
this.BringToFront();
this.Focus();
FocusFirstButton();
}
private void FocusFirstButton()
{
if (itemsPanel.Controls.Count > 0)
{
((Button)itemsPanel.Controls[0]).Focus();
}
}
private void BuildUI()
{
// Button dimensions
const int bw = 180;
const int bh = 50;
const int p = 3;
itemsPanel.Controls.Clear();
if (currentItems == null)
{
this.Size = new Size(bw + 2 * p, bh + 2 * p + titleBarHeight);
return;
}
// Get monitor info and calculate aspect ratios
var screen = Screen.FromControl(this); // Use 'this' or the mainPanel
var workingArea = screen.WorkingArea;
double a = (double)workingArea.Width / workingArea.Height;
// Determine size
var N = currentItems.Items.Count();
double n = Math.Sqrt(N * a * bh / bw);
int n_cols = Math.Max(1, (int)Math.Ceiling(n));
int n_rows = (int)Math.Ceiling((double)N / n_cols);
int calculated_width = n_cols * (bw + p) + p;
int calculated_height = n_rows * (bh + p) + p;
this.Size = new Size(calculated_width, calculated_height + titleBarHeight);
foreach (var item in currentItems.Items)
{
var btn = new Button
{
Text = $"{item.Name}".Replace("\\n", "\n"),
Width = bw,
Height = bh,
FlatStyle = FlatStyle.Flat,
BackColor = (item.ButtonColor == Color.Transparent) ? GetDefaultItemColor(item.Type) : item.ButtonColor,
ForeColor = item.FontColor,
Font = item.Font,
UseVisualStyleBackColor = false,
Tag = item,
Padding = new Padding(0, 0, 0, 0),
Margin = new Padding(p, p, 0, 0),
AutoSize = true,
MaximumSize = new Size(bw, bh),
MinimumSize = new Size(bw, bh),
};
QuickLauncherEditor.CTT(btn, item.Desc);
// Shortcut Label
var sLbl = new Label
{
Text = $"{sKey.GetKeyDisplay(item.ShortcutKey, true)}",
// Create a new font based on the button's font family, but with a smaller size
Font = new Font(btn.Font.FontFamily, 8F, FontStyle.Regular),
Location = new Point(btn.Width - 50, btn.Height - 18), // Now X = btn.Width - label.Width, Y = btn.Height - label.Height
// Set a fixed size for the label
Size = new Size(50, 15), // Width = 20, Height = 15
// Optional: Style the label
ForeColor = item.FontColor, // Example: Different color for the shortcut
BackColor = Color.Transparent, // So it doesn't obscure the button's background
TextAlign = ContentAlignment.BottomRight // Align text within the label
};
btn.Controls.Add(sLbl);
btn.FlatAppearance.BorderSize = 0;
btn.Click += (s, e) => { RecordActivity(); ExecuteItem((QuickItem)((Button)s).Tag, (ModifierKeys == Keys.Control) ? QuickItemType.App : ((ModifierKeys == Keys.Shift) ? QuickItemType.Command : null)); };
btn.KeyDown += ButtonKeyDown;
btn.MouseEnter += (s, e) => {
var btn = (Button)s;
btn.ForeColor = (item.ButtonColor == Color.Transparent) ? GetDefaultItemColor(item.Type) : item.ButtonColor;
btn.BackColor = item.FontColor;
((Button)s).Focus();
};
btn.MouseDown += (s, e) => RecordActivity(); // mouse interaction resets idle-exit timer
btn.MouseLeave += (s, e) =>
{
var btn = (Button)s;
btn.BackColor = (item.ButtonColor == Color.Transparent) ? GetDefaultItemColor(item.Type) : item.ButtonColor;
btn.ForeColor = item.FontColor;
((Button)s).Focus();
};
itemsPanel.Controls.Add(btn);
}
CenterOnScreen();
}
public static Color GetDefaultItemColor(QuickItemType type)
{
switch (type)
{
case QuickItemType.App: return Color.FromArgb(50, 100, 50);
case QuickItemType.Command: return Color.FromArgb(100, 50, 50);
case QuickItemType.Shortcut: return Color.FromArgb(50, 50, 100);
case QuickItemType.Folder: return Color.FromArgb(100, 100, 50);
default: return Color.FromArgb(50, 50, 50);
}
}
/*
* additional processinfo flags that might be useful or should be optional
UseShellExecute = false, // Can be true, but false might be preferred for hiding cmd window
CreateNoWindow = true, // Hide the schtasks window
WindowStyle = ProcessWindowStyle.Hidden // Alternative to CreateNoWindow
*/
private void ExecuteItem(QuickItem item, QuickItemType? forceType = null)
{
RecordActivity();
var type = (forceType.HasValue) ? forceType.Value : item.Type;
var path = item.Path;
var args = item.Args;
var workingDir = item.WorkingDir;
var se = item.useShellExecute;
var cnw = item.noWindow;
top:
switch (type)
{
case QuickItemType.App:
if (path != "")
{
stopAutoClose = true;
try
{
var si = new ProcessStartInfo() {
WorkingDirectory = (workingDir == "") ? Path.GetDirectoryName(item.Path) : workingDir,
FileName = path,
Arguments = args,
Verb = (item.RunAsAdmin) ? "runas" : "",
UseShellExecute = se,
CreateNoWindow = cnw,
WindowStyle = (cnw) ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal,
};
var p = Process.Start(si);
this.Hide();
if (item.Close)
CloseOrHide();
else
{
p.WaitForExit();
SetWindowPos(this.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x1 | 0x2);
this.Show();
}
}
catch (Exception ex)
{
MessageBox.Show($"Error executing app: {ex.Message}");
SetWindowPos(this.Handle, new IntPtr(0), 0, 0, 0, 0, 0x1 | 0x2);
this.Show();
stopAutoClose = false;
}
stopAutoClose = false;
}
break;
case QuickItemType.Command:
if (path != "")
{
ExecuteCommand(item);
if (item.Close)
CloseOrHide();
}
break;
case QuickItemType.Shortcut:
// SendKeys targets the foreground window, so the launcher must
// be hidden first or it would receive its own keystrokes.
this.Hide();
System.Threading.Thread.Sleep(50); // let activation settle
try { SendKeys.SendWait(item.Path); }
catch (Exception ex) { MessageBox.Show($"Error sending keys: {ex.Message}"); }
if (item.Close)
CloseOrHide();
else
this.Show();
break;
case QuickItemType.GlobalShortcut:
// Synthesize a system-wide key combo via keybd_event. The Path
// holds the combo with modifiers (e.g. "Ctrl+Alt+Delete",
// "Win+D"); Args is unused.
this.Hide(); // give the foreground to whatever receives it
System.Threading.Thread.Sleep(50);
try { SendGlobalShortcut(item.Path); }
catch (Exception ex) { MessageBox.Show($"Error sending global shortcut: {ex.Message}"); }
if (item.Close)
CloseOrHide();
else
this.Show();
break;
case QuickItemType.Folder:
navigationStack.Push(item);
BuildUI();
break;
case QuickItemType.Task:
type = QuickItemType.App;
path = "C:\\Windows\\System32\\schtasks.exe";
// Quote the task name too so names with spaces/special chars are safe.
args = "/Run /TN \"" + (item.TaskName ?? "").Replace("\"", "\\\"") + "\"";
workingDir = "";
goto top;
break;
}
}
// ------------------------------------------------------------------
// GlobalShortcut support: parse a combo string like "Ctrl+Alt+F1" or
// "Win+D" into VK codes and inject it system-wide with keybd_event.
// ------------------------------------------------------------------
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
private const uint KEYEVENTF_KEYUP = 0x0002;
private const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
private static Keys? ParseShortcutToken(string token)
{
token = token.Trim();
switch (token.ToLowerInvariant())
{
case "ctrl": case "control": return Keys.Control;
case "alt": case "menu": return Keys.Alt;
case "shift": return Keys.Shift;
case "win": case "windows": return Keys.LWin;
}
if (token.Length == 1)
{
char c = char.ToUpperInvariant(token[0]);
if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) return (Keys)c;
}
if (Enum.TryParse<Keys>(token, true, out var parsed)) return parsed;
return null;
}
private static void SendGlobalShortcut(string combo)
{
if (string.IsNullOrWhiteSpace(combo)) return;
var parts = combo.Split(new[] { '+' }, StringSplitOptions.RemoveEmptyEntries);
var mods = new List<Keys>();
Keys main = Keys.None;
foreach (var p in parts)
{
var k = ParseShortcutToken(p);
if (k == null) continue;
var kk = k.Value;
if (kk == Keys.Control || kk == Keys.Alt || kk == Keys.Shift || kk == Keys.LWin || kk == Keys.RWin)
mods.Add(kk);
else
main = kk;
}
if (main == Keys.None) return;
void Tap(Keys vk, bool down) =>
keybd_event((byte)vk, 0, (down ? 0u : KEYEVENTF_KEYUP) | (((uint)vk & 0xF0) == 0x70 ? KEYEVENTF_EXTENDEDKEY : 0), UIntPtr.Zero);
foreach (var m in mods) Tap(m, true);
Tap(main, true);
Tap(main, false);
for (int i = mods.Count - 1; i >= 0; i--) Tap(mods[i], false);
}
private void ExecuteCommand(QuickItem item)
{
var processInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/C {item.Path} {item.Args}",
UseShellExecute = item.useShellExecute,
CreateNoWindow = item.noWindow,
WindowStyle = (item.noWindow) ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = (item.WorkingDir == "") ? Path.GetDirectoryName(item.Path) : item.WorkingDir,
Verb = (item.RunAsAdmin) ? "runas" : "",
};
//processInfo.ArgumentList.Add(item.Args);
try
{
using (var process = Process.Start(processInfo))
{
stopAutoClose = true;
this.Hide();
SetWindowPos(this.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x1 | 0x2);
process.WaitForExit();
SetWindowPos(this.Handle, new IntPtr(0), 0, 0, 0, 0, 0x1 | 0x2);
this.Show();
stopAutoClose = false;
}
}
catch (Exception ex)
{
MessageBox.Show($"Error executing command: {ex.Message}");
SetWindowPos(this.Handle, new IntPtr(0), 0, 0, 0, 0, 0x1 | 0x2);
this.Show();
stopAutoClose = false;
}
}
private void ButtonKeyDown(object sender, KeyEventArgs e)