Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
4360 lines (3782 loc) · 171 KB
/
Copy pathProgram.cs
File metadata and controls
4360 lines (3782 loc) · 171 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 Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Linq;
using System.ServiceProcess;
using System.Threading;
using System.Text.RegularExpressions;
namespace RightClickTools
{
partial class Program
{
static string myName = typeof(Program).Namespace;
static string myPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
static string myExe = System.Reflection.Assembly.GetExecutingAssembly().Location;
static string TempPath = Path.GetTempPath(); //Includes trailing backslash
static string ElevateCfg = $@"{TempPath}Elevate.cfg";
static string appParts = $@"{myPath}\AppParts";
static string myIniFile = $@"{appParts}\{myName}.ini";
static string MoreToolsIni = $@"{appParts}\MoreTools.ini";
static string LauncherIni = $@"{appParts}\Launcher.ini";
static string IconFolder = $@"{myPath}\AppParts\Icons";
static string myIcon = $@"{IconFolder}\{myName}.ico";
static string AdvKey = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced";
static string perKey = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
static string ExpKey = @"HKEY_LOCAL_MACHINE\Software\Classes\AppID\{CDCBCFCA-3CDC-436f-A4E2-0E02075250C2}";
static string bitPath = "64";
static bool Hidden = false;
static string NTkey = @"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion";
static int buildNumber = int.Parse(Registry.GetValue(NTkey, "CurrentBuild", "").ToString());
static bool Win11 = buildNumber >= 21996;
static bool Win11Install = false;
static bool AnyInstall = false;
// Determine icon folder based on Windows version
// Windows 7/8: 7600-9600, Windows 10: 10240-21995, Windows 11: 21996+
static string GetIconFolderForVersion()
{
if (Win11) return "Win11";
if (buildNumber >= 10240) return "Win10";
return "Win7"; // Windows 7 and 8/8.1
}
static string CCMfolder = FindCustomCommandsFolder(true);
static string CCMA = @"Software\Classes\CLSID\{86CA1AA0-34AA-4E8B-A509-50C905BAE2A2}";
static string CCMB = $@"{CCMA}\InprocServer32";
static bool Win10ContextMenu = false;
static bool NoTrustedInstaller = false;
static string EditorExe = "notepad.exe";
static string[] CmdKeys = { "CmdHere", "PowerShellHere", "PowerShellCoreHere", "FileManagerHere", "SearchHere", "RegEdit", "ClearHistory", "UnblockHere", "TakeOwnHere", "AddDelPathHere", "ShowHide", "RefreshShellHere", "FolderOptionsHere", "RestartExplorerHere", "Settings", "MoreToolsHere" };
static string Option = "";
static string StartDirectory = "";
static string CommandLine = "";
internal static float ScaleFactor = GetScale();
internal static bool Dark = isDark();
static bool isAdmin = false;
static bool isFullAdmin = false;
static bool ctrlKey = false;
static IntPtr explorerHwnd = IntPtr.Zero;
static bool addTask = true;
static bool removeTask = true;
static bool Stop = false;
static string UserKey = @"HKEY_CURRENT_USER\Environment";
static string SystemKey = @"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment";
static string UserPath = (string)Registry.GetValue(UserKey, "Path", "");
static string SystemPath = (string)Registry.GetValue(SystemKey, "Path", "");
static bool InUserPath = false;
static bool InSystemPath = false;
static int pathLength = UserPath.Length + SystemPath.Length;
static string UIkey = @"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Authentication\LogonUI";
static string userSID = "";
static string CmdExe = @"C:\Windows\System32\Cmd.exe";
static string PowerShellExe = @"C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe";
static string PowerShellCoreExe = @"pwsh.exe";
static string RegEditExe = @"C:\Windows\RegEdit.exe";
static string SchTasksExe = @"C:\Windows\System32\SchTasks.exe";
static string UserName = Environment.GetEnvironmentVariable("UserName");
static string TaskName = $@"MyTasks\{myName}-{UserName}";
static string helpPage = "install";
static int bwidth = 75;
static CheckBox userPathCheckbox;
static CheckBox systemPathCheckbox;
static CheckBox ShellRefreshCheckbox;
static CheckBox iconCacheCheckbox;
static CheckBox thumbCacheCheckbox;
static CheckBox RecentItemsCheckbox;
static CheckBox AutoSuggestCheckbox;
static CheckBox TempFilesCheckbox;
static CheckBox RecycleBinCheckbox;
static CheckBox DefenderCheckbox;
static CheckBox SpecifiedFoldersCheckbox;
static CheckBox checkboxCCM;
static CheckBox checkboxTask;
static CheckBox checkboxUnblockAdmin;
static bool needsIconCacheReset = false;
static bool useWindowsTerminal = false;
static string originalPowerShellExe = "";
static string originalExe = "";
static string[] mainArgs = null; // Store args for theme change restart
static bool themeChanged = false; // Flag to indicate theme has changed
static Point savedDialogPosition = Point.Empty; // Save dialog position for theme change relaunch
static bool useOriginalPosition = false; // Use saved dialog position on next dialog launch
// Folder where per-user settings are stored. When FullyPortable is enabled and the
// program folder is writable this will point to a local "AppData" subfolder, otherwise
// it defaults to %LocalAppData%\RightClickTools.
static string UserSettingsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RightClickTools");
[STAThread]
static void Main(string[] args)
{
// Store args for potential theme change restart
mainArgs = args;
// Save cursor position for initial dialog launch
if (savedDialogPosition == Point.Empty)
{
savedDialogPosition = Cursor.Position;
}
// If the current folder is a long path, the Elevate function will fail, so let's make C:\ the current folder.
Directory.SetCurrentDirectory(@"C:\");
explorerHwnd = GetForegroundWindow(); // Capture Explorer's HWND before it loses foreground
ctrlKey = (GetAsyncKeyState(0x11) & 0x8000) != 0; //Detect if Ctrl key is pressed
if (!Environment.Is64BitOperatingSystem) bitPath = "32";
// Process /Lang= parameter before initializing user settings
string installerLang = null;
if (args.Length > 0)
{
foreach (string arg in args)
{
if (arg.StartsWith("/Lang=", StringComparison.OrdinalIgnoreCase))
{
installerLang = arg.Substring(6);
break;
}
}
}
InitializeUserSettingsFile();
// Set language from installer if provided
if (!string.IsNullOrEmpty(installerLang))
{
WriteString(myIniFile, "General", "Lang", installerLang);
}
LoadLanguageStrings();
StringsFromCmdLabels();
// Read NoTrustedInstaller setting from INI file
NoTrustedInstaller = ReadString(myIniFile, "General", "NoTrustedInstaller", "0") == "1";
// Read Editor setting from INI file
string editorPath = ReadString(myIniFile, "General", "Editor", "");
if (!string.IsNullOrEmpty(editorPath) && File.Exists(editorPath))
{
EditorExe = editorPath;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Subscribe to system theme changes
Microsoft.Win32.SystemEvents.UserPreferenceChanged += OnSystemThemeChanged;
isAdmin = IsCurrentUserInAdminGroup();
isFullAdmin = isAdmin && TaskExists();
try { Hidden = (int)Registry.GetValue(AdvKey, "Hidden", 0) == 1; } catch { }
try { userSID = (string)Registry.GetValue(UIkey, "LastLoggedOnUserSID", ""); } catch { }
if (userSID == "") findUserSID();
// Handle protocol activation (from MSIX context menu to break out of AppContainer)
if (args.Length > 0 && args[0].StartsWith("rightclicktools:", StringComparison.OrdinalIgnoreCase))
{
HandleProtocolActivation(args[0]);
return;
}
// If a directory was passed in addition to an option, save it to registry immediately
if (args.Length > 1)
{
string passedDirectory = args[1].Replace("|", "");
if (!string.IsNullOrEmpty(passedDirectory) && Directory.Exists(passedDirectory))
{
Registry.SetValue(@"HKEY_CURRENT_USER\Software\RightClickTools", "StartDirectory", passedDirectory, RegistryValueKind.String);
}
}
// Load StartDirectory from registry (set by context menu or previous dialog)
try
{
string savedDirectory = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\RightClickTools", "StartDirectory", "");
if (!string.IsNullOrEmpty(savedDirectory) && Directory.Exists(savedDirectory))
{
StartDirectory = savedDirectory;
}
else
{
StartDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
}
catch { }
// Main execution loop - restart if theme changes
do
{
themeChanged = false;
if (args.Length == 0)
{
Launcher();
}
else
{
Option = args[0];
// When launched as an elevated helper (/Elevate), the cfg file path is passed as args[1].
// It must be captured here (in Main where args is in scope) before ExecuteCommand runs,
// because the elevated process may compute a different %TEMP% path than the calling user.
if (Option.Equals("/Elevate", StringComparison.OrdinalIgnoreCase) && args.Length > 1)
{
ElevateCfg = args[1];
}
ExecuteCommand();
}
} while (themeChanged);
}
static void ExecuteCommand()
{
switch (Option.ToLower())
{
case "/dark":
SetExplorerOptions(0);
break;
case "/light":
SetExplorerOptions(1);
break;
case "/install":
Install(false);
break;
case "/installmin":
addTask = false;
Install(false);
break;
case "/remove":
Remove(false);
break;
case "/removemin":
removeTask = false;
Remove(false);
break;
case "/hkuinstall":
HKUInstall();
break;
case "/hkuinstallmin":
addTask = false;
HKUInstall();
break;
case "/hkutaskonly":
TaskInstall(false);
break;
case "/hkuremove":
HKURemove();
break;
case "/taskinstall":
TaskInstall(true);
break;
case "/taskremove":
TaskRemove(true);
break;
case "/taskinstallquiet":
TaskInstall(false);
break;
case "/taskremovequiet":
TaskRemove(false);
break;
case "/elevate":
Elevate();
break;
case "/cmdhere":
CmdHere();
break;
case "/powershellhere":
PowerShellHere();
break;
case "/powershellcorehere":
GetPowerShellCorePath();
PowerShellCoreHere();
break;
case "/searchhere":
SearchHere();
break;
case "/searchhelper":
OpenSearchHelper();
break;
case "/regedit":
RegEdit();
break;
case "/regeditadmin":
CommandLine = "/m";
RunAsAdmin(RegEditExe);
break;
case "/regedittrusted":
CommandLine = "/m";
RunAsTrusted(RegEditExe);
break;
case "/allowelevatedexplorer":
object runAsValue = Registry.GetValue(ExpKey, "RunAs", null);
if (runAsValue != null && runAsValue.ToString() == "Interactive User")
{
Registry.SetValue(ExpKey, "RunAs", "", RegistryValueKind.String);
Thread.Sleep(5000);
Registry.SetValue(ExpKey, "RunAs", "Interactive User", RegistryValueKind.String);
}
break;
case "/minifilemanager":
OpenFileDialog fd = new OpenFileDialog
{
Title = sFileManager,
Filter = "",
InitialDirectory = StartDirectory,
Multiselect = true
};
fd.ShowDialog();
break;
case "/filemanagerhere":
FileManagerHere();
break;
case "/unblockhere":
UnblockHere();
break;
case "/unblockadmin":
UnblockDirectory();
break;
case "/takeownhere":
RunTakeOwnHerePS1AsAdmin();
break;
case "/adddelpathhere":
AddDelPathHere();
break;
case "/addpathadmin":
AddPathAdmin();
break;
case "/delpathadmin":
DelPathAdmin();
break;
case "/showhide":
ShowHide();
break;
case "/clearhistory":
ClearHistory();
break;
case "/setacltempfiles":
RunSetACLOnTempFiles();
break;
case "/clearhistoryadmin":
ClearDefenderHistoryTask();
break;
case "/refreshshellhere":
RefreshShellHere();
break;
case "/reseticoncache":
ResetCachesAndRestartExplorer(true, false);
break;
case "/restartexplorerhere":
helpPage = "restart-explorer";
DialogResult result = CustomMessageBox.Show($"{sRestartExplorer}?", sMain);
if (result == DialogResult.Cancel) return;
RestartExplorer();
break;
case "/folderoptionshere":
FolderOptionsHere();
break;
case "/settings":
SettingsDialog.Show();
break;
case "/shortcuttool":
ShortcutTool();
break;
case "/datetimetool":
DateTimeTool();
break;
case "/moretoolshere":
MoreTools();
break;
case "/setup":
Setup();
break;
default:
return;
}
}
// Handle system theme changes and restart the application
static void OnSystemThemeChanged(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
{
// Only respond to General category changes (which includes theme changes)
if (e.Category == Microsoft.Win32.UserPreferenceCategory.General)
{
bool newDarkMode = isDark();
if (newDarkMode != Dark)
{
Dark = newDarkMode;
themeChanged = true;
useOriginalPosition = true; // Use saved position on relaunch
// If any form is open, capture its position and close it
if (Application.OpenForms.Count > 0)
{
Form form = Application.OpenForms[0];
form.Invoke(new Action(() =>
{
savedDialogPosition = form.Location; // Save the current dialog position
form.Close();
}));
}
}
}
}
static void InitializeUserSettingsFile()
{
// Determine the user settings folder.
// If FullyPortable=1 is set in the AppParts INI and the program folder is writable,
// use a local "AppData" sub-folder instead of %LocalAppData%\RightClickTools.
string appPartsIniFile = Path.Combine(appParts, $"{myName}.ini");
bool fullyPortable = IniFileParser.ReadValue("General", "FullyPortable", "0", appPartsIniFile) == "1";
string portableFolder = Path.Combine(myPath, "AppData");
if (fullyPortable && !IsDirectoryWritable(myPath))
fullyPortable = false;
string userSettingsFolder = fullyPortable
? portableFolder
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RightClickTools");
// Publish the chosen settings folder for other partial classes to use
UserSettingsFolder = userSettingsFolder;
string userSettingsFile = Path.Combine(userSettingsFolder, $"{myName}.ini");
string userMoreToolsFile = Path.Combine(userSettingsFolder, "MoreTools.ini");
try
{
// Create directory if it doesn't exist
if (!Directory.Exists(userSettingsFolder))
{
Directory.CreateDirectory(userSettingsFolder);
}
// --- RightClickTools.ini ---
if (!File.Exists(userSettingsFile) && File.Exists(appPartsIniFile))
{
File.Copy(appPartsIniFile, userSettingsFile, false);
}
// Update myIniFile to point to the user's copy
if (File.Exists(userSettingsFile))
{
myIniFile = userSettingsFile;
}
// --- MoreTools.ini ---
string appPartsMoreTools = Path.Combine(appParts, "MoreTools.ini");
if (!File.Exists(userMoreToolsFile) && File.Exists(appPartsMoreTools))
{
File.Copy(appPartsMoreTools, userMoreToolsFile, false);
}
else if (File.Exists(userMoreToolsFile) && File.Exists(appPartsMoreTools))
{
int srcRev = IniFileParser.ReadIniRevision(appPartsMoreTools);
int destRev = IniFileParser.ReadIniRevision(userMoreToolsFile);
if (srcRev > destRev)
{
IniFileParser.MergeMissingSections(appPartsMoreTools, userMoreToolsFile);
IniFileParser.UpdateIniRevision(userMoreToolsFile, srcRev);
}
}
// Update MoreToolsIni to point to the user's copy
if (File.Exists(userMoreToolsFile))
{
MoreToolsIni = userMoreToolsFile;
}
// --- Launcher.ini ---
string userLauncherFile = Path.Combine(userSettingsFolder, "Launcher.ini");
string appPartsLauncher = Path.Combine(appParts, "Launcher.ini");
if (!File.Exists(userLauncherFile) && File.Exists(appPartsLauncher))
{
File.Copy(appPartsLauncher, userLauncherFile, false);
}
else if (File.Exists(userLauncherFile) && File.Exists(appPartsLauncher))
{
int srcRev = IniFileParser.ReadIniRevision(appPartsLauncher);
int destRev = IniFileParser.ReadIniRevision(userLauncherFile);
if (srcRev > destRev)
{
IniFileParser.MergeMissingSections(appPartsLauncher, userLauncherFile);
IniFileParser.UpdateIniRevision(userLauncherFile, srcRev);
}
}
// Update LauncherIni to point to the user's copy
if (File.Exists(userLauncherFile))
{
LauncherIni = userLauncherFile;
}
}
catch
{
// If copy fails, continue using original files
}
}
static void GetPowerShellCorePath()
{
string PSPath = ReadString(myIniFile, "PowerShellCoreHere", "Exe", "");
if (File.Exists(PSPath)) PowerShellCoreExe = PSPath;
}
static bool IsDirectoryWritable(string dirPath)
{
try
{
string testFile = Path.Combine(dirPath, Path.GetRandomFileName());
using (File.Create(testFile)) { }
File.Delete(testFile);
return true;
}
catch
{
return false;
}
}
static void SetExplorerOptions(int light)
{
Registry.SetValue(perKey, "AppsUseLightTheme", light, RegistryValueKind.DWord);
Registry.SetValue(perKey, "SystemUsesLightTheme", light, RegistryValueKind.DWord);
Registry.SetValue(AdvKey, "Hidden", 1, RegistryValueKind.DWord);
Registry.SetValue(AdvKey, "ShowSuperHidden", 1, RegistryValueKind.DWord);
Registry.SetValue(AdvKey, "HideFileExt", 0, RegistryValueKind.DWord);
Registry.SetValue(AdvKey, "UseCompactMode", 1, RegistryValueKind.DWord);
}
static void findUserSID()
{
string userName = "";
try { userName = (string)Registry.GetValue(UIkey, "LastLoggedOnUser", ""); } catch { }
if (userName == "") return;
userName = userName.Substring(userName.LastIndexOf('\\') + 1);
using (RegistryKey hkeyUsers = Registry.Users)
{
foreach (string userSid in hkeyUsers.GetSubKeyNames())
{
try
{
using (RegistryKey volatileEnvKey = hkeyUsers.OpenSubKey($@"{userSid}\Volatile Environment"))
{
if (volatileEnvKey != null)
{
object usernameValue = volatileEnvKey.GetValue("USERNAME");
if (usernameValue != null && usernameValue.ToString().Equals(userName, StringComparison.OrdinalIgnoreCase))
{
userSID = userSid;
return;
}
}
}
}
catch { }
}
}
userSID = "";
}
static void HandleProtocolActivation(string protocolUri)
{
try
{
// Parse the protocol URI: rightclicktools:command?path=<encoded_path>
// Example: rightclicktools:ShowHide?path=C%3A%5CUsers%5CFerch%5CDesktop
string uri = protocolUri.Substring("rightclicktools:".Length);
int questionMarkIndex = uri.IndexOf('?');
if (questionMarkIndex == -1)
{
// No parameters, just command
Option = "/" + uri;
StartDirectory = "";
}
else
{
Option = "/" + uri.Substring(0, questionMarkIndex);
// Parse query string
string queryString = uri.Substring(questionMarkIndex + 1);
string[] parameters = queryString.Split('&');
foreach (string param in parameters)
{
if (param.StartsWith("path=", StringComparison.OrdinalIgnoreCase))
{
string encodedPath = param.Substring(5);
// URL decode the path
StartDirectory = Uri.UnescapeDataString(encodedPath);
StartDirectory = StartDirectory.Replace("|", "");
break;
}
}
}
// Now execute the command using the existing switch statement
ExecuteCommand();
}
catch
{
// Silently ignore protocol parsing errors
}
}
static bool IsCurrentUserInAdminGroup()
{
var claims = new WindowsPrincipal(WindowsIdentity.GetCurrent()).Claims;
var adminClaimID = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Value;
return claims.Any(c => c.Value == adminClaimID);
}
static bool TaskExists()
{
Process process = new Process();
process.StartInfo.FileName = "schtasks.exe";
process.StartInfo.Arguments = $"/query /tn {TaskName}";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
static void RunUAC(string fileName)
{
Process p = new Process();
p.StartInfo.FileName = fileName;
p.StartInfo.Arguments = CommandLine;
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Verb = "runas";
p.Start();
p.WaitForExit();
}
// Returns the effective DialogResult based on RunAs setting and Ctrl key:
// OK=run as user, Yes=run as admin, No=run as TrustedInstaller, Cancel=cancelled.
// RunAs=0 (or not set): run as user without a dialog.
// RunAs=1: run as admin without a dialog.
// RunAs=2: run as TrustedInstaller without a dialog.
// RunAs=3 or Ctrl held: prompt the user.
static DialogResult GetRunAsResult(string section, string title)
{
int runAs = 0;
int.TryParse(ReadString(myIniFile, section, "RunAs", "0"), out runAs);
if (runAs == 3 || ctrlKey)
{
bwidth = 120;
return ThreeChoiceBox.Show(title, sMain, sUser, sAdministrator, sTrustedInstaller, !NoTrustedInstaller, topmost: true);
}
if (runAs == 1) return DialogResult.Yes;
if (runAs == 2) return NoTrustedInstaller ? DialogResult.Yes : DialogResult.No;
return DialogResult.OK;
}
// Like GetRunAsResult, but executes the action from inside the ThreeChoiceBox dialog
// (while the form is still foreground) so that GUI apps launched as User can take the foreground.
static void RunFromDialog(string section, string title, Action<DialogResult> execute)
{
int runAs = 0;
int.TryParse(ReadString(myIniFile, section, "RunAs", "0"), out runAs);
if (runAs == 3 || ctrlKey)
{
bwidth = 120;
ThreeChoiceBox.Show(title, sMain, sUser, sAdministrator, sTrustedInstaller, !NoTrustedInstaller, topmost: true, onResult: execute);
return;
}
// Non-dialog cases: execute directly (these already open on top without a dialog).
if (runAs == 1) execute(DialogResult.Yes);
else if (runAs == 2) execute(NoTrustedInstaller ? DialogResult.Yes : DialogResult.No);
else execute(DialogResult.OK);
}
static void CmdHere()
{
helpPage = "commands";
// Check for Windows Terminal admin option
int wtAdmin = 0;
int.TryParse(ReadString(myIniFile, "CmdHere", "WTadmin", "0"), out wtAdmin);
DialogResult result = GetRunAsResult("CmdHere", sCmdHere);
if (result == DialogResult.Cancel) return;
useWindowsTerminal = false;
originalExe = "";
if (result == DialogResult.OK)
{
RunAsUser(CmdExe);
}
if (result == DialogResult.Yes)
{
useWindowsTerminal = (wtAdmin == 1 && IsWindowsTerminalInstalled());
originalExe = CmdExe;
RunAsAdmin(CmdExe);
}
if (result == DialogResult.No)
{
// Don't use Windows Terminal for TrustedInstaller - it's not supported
RunAsTrusted(CmdExe);
}
useWindowsTerminal = false;
originalExe = "";
}
static void PowerShellHere()
{
helpPage = "commands";
// Check for Windows Terminal admin option
int wtAdmin = 0;
int.TryParse(ReadString(myIniFile, "PowerShellHere", "WTadmin", "0"), out wtAdmin);
DialogResult result = GetRunAsResult("PowerShellHere", sPowerShellHere);
if (result == DialogResult.Cancel) return;
useWindowsTerminal = false;
originalPowerShellExe = "";
originalExe = "";
if (result == DialogResult.OK)
{
RunAsUser(PowerShellExe);
}
if (result == DialogResult.Yes)
{
useWindowsTerminal = (wtAdmin == 1 && IsWindowsTerminalInstalled());
originalPowerShellExe = PowerShellExe;
originalExe = PowerShellExe;
RunAsAdmin(PowerShellExe);
}
if (result == DialogResult.No)
{
// Don't use Windows Terminal for TrustedInstaller - it's not supported
RunAsTrusted(PowerShellExe);
}
useWindowsTerminal = false;
originalPowerShellExe = "";
originalExe = "";
}
static void PowerShellCoreHere()
{
helpPage = "commands";
// Check if PowerShell Core is installed
if (!IsPowerShellCoreInstalled())
{
CustomMessageBox.Show(sPowerShellCoreNotInstalled, sMain);
return;
}
// Check for Windows Terminal admin option
int wtAdmin = 0;
int.TryParse(ReadString(myIniFile, "PowerShellCoreHere", "WTadmin", "0"), out wtAdmin);
DialogResult result = GetRunAsResult("PowerShellCoreHere", sPowerShellCoreHere);
if (result == DialogResult.Cancel) return;
useWindowsTerminal = false;
originalPowerShellExe = "";
originalExe = "";
if (result == DialogResult.OK)
{
RunAsUser(PowerShellCoreExe);
}
if (result == DialogResult.Yes)
{
useWindowsTerminal = (wtAdmin == 1 && IsWindowsTerminalInstalled());
originalPowerShellExe = PowerShellCoreExe;
originalExe = PowerShellCoreExe;
RunAsAdmin(PowerShellCoreExe);
}
if (result == DialogResult.No)
{
// Don't use Windows Terminal for TrustedInstaller - it's not supported
RunAsTrusted(PowerShellCoreExe);
}
useWindowsTerminal = false;
originalPowerShellExe = "";
originalExe = "";
}
static void RegEdit()
{
helpPage = "regedit";
bool shiftKey = (GetAsyncKeyState(0x10) & 0x8000) != 0; // Detect if Shift key is pressed
RunFromDialog("RegEdit", sRegEdit, (result) =>
{
if (result == DialogResult.OK)
{
Environment.SetEnvironmentVariable("__COMPAT_LAYER", "RUNASINVOKER");
if (shiftKey) clearRegEdit();
CommandLine = "/m";
RunAsUser(RegEditExe);
}
if (result == DialogResult.Yes)
{
if (shiftKey) clearRegEdit();
CommandLine = "/m";
RunAsAdmin(RegEditExe);
}
if (result == DialogResult.No)
{
CommandLine = "/m";
RunAsTrusted(RegEditExe);
}
});
}
static void FileManagerHere()
{
helpPage = "file-manager-here";
RunFromDialog("FileManagerHere", sFileManagerHere, (result) =>
{
CommandLine = $"\"{StartDirectory}\"";
string FMExe = ReadString(myIniFile, "FileManagerHere", "Exe", "");
// Set file manager to Explorer if no valid third-party file manager is set
if (FMExe == "" || $@"\{FMExe}".ToLower().EndsWith("\\explorer.exe") || !File.Exists(FMExe))
{
if (Win11 && result == DialogResult.No)
{
CommandLine = $"/MiniFileManager \"{StartDirectory}\"";
FMExe = myExe;
}
else
{
FMExe = "explorer.exe";
if (result == DialogResult.OK)
{
RunAsUser(FMExe);
return;
}
// Check registry value that prevents Explorer to run elevated
object runAsValue = Registry.GetValue(ExpKey, "RunAs", null);
if (runAsValue != null && runAsValue.ToString() == "Interactive User")
{
if (isFullAdmin)
{
// Temporarily allow Explorer to run elevated
CommandLine = "/AllowElevatedExplorer";
RunAsTrusted(myExe);
// Wait for registry entry to be updated
for (int i = 0; i < 100; i++)
{
Thread.Sleep(20);
runAsValue = Registry.GetValue(ExpKey, "RunAs", null);
if (runAsValue == null || runAsValue.ToString() != "Interactive User") break;
}
CommandLine = $"\"{StartDirectory}\"";
}
else
{
CommandLine = $"/MiniFileManager \"{StartDirectory}\"";
FMExe = myExe;
}
}
}
}
if (result == DialogResult.OK) RunAsUser(FMExe);
if (result == DialogResult.Yes) RunAsAdmin(FMExe);
if (result == DialogResult.No) RunAsTrusted(FMExe);
});
}
static void AddPathAdmin()
{
char[] trimThis = { '\\' };
string path = StartDirectory.Trim(trimThis);
InUserPath = IsPathInEnvironmentVariable(path, UserPath);
InSystemPath = IsPathInEnvironmentVariable(path, SystemPath);
AddPathToEnvironmentVariable(path, SystemPath, SystemKey, false);
}
static void DelPathAdmin()
{
char[] trimThis = { '\\' };
string path = StartDirectory.Trim(trimThis);
InUserPath = IsPathInEnvironmentVariable(path, UserPath);
InSystemPath = IsPathInEnvironmentVariable(path, SystemPath);
RemovePathFromEnvironmentVariable(path, SystemPath, SystemKey, false);
}
static void ClearHistory()
{
DialogResult result = ClearHistoryDialog.Show(sClearHistory, sMain);
if (result == DialogResult.Cancel) return;
if (RecentItemsCheckbox.Checked)
{