-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathProgram.cs
More file actions
2362 lines (2020 loc) · 96.1 KB
/
Program.cs
File metadata and controls
2362 lines (2020 loc) · 96.1 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.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Linq;
using System.ServiceProcess;
using System.Threading;
namespace RightClickTools
{
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 myIcon = $@"{myPath}\AppParts\Icons\{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;
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 string sMain = "Right-Click Tools";
static string sSetup = "Install or Remove this tool";
static string sOK = "OK";
static string sYes = "Yes";
static string sNo = "No";
static string sInstall = "Install";
static string sRemove = "Remove";
static string sDone = "Done";
static string[] CmdKeys = { "CmdHere", "CmdAdminHere", "CmdTrustedHere", "PowerShellHere", "PowerShellAdminHere", "PowerShellTrustedHere", "RegEdit", "RegEditAdmin", "RegEditTrusted", "ClearHistory", "TakeOwnHere", "AddDelPathHere", "ShowHide", "RefreshShellHere", "RestartExplorerHere", "FileManagerHere" };
static string[] CmdLabels = { "Cmd here", "Cmd here as Administrator", "Cmd here as TrustedInstaller", "PowerShell here", "PowerShell here as Administrator", "PowerShell here as TrustedInstaller", "RegEdit as User", "RegEdit as Administrator", "RegEdit as TrustedInstaller", "Clear History", "Take ownership and get access", "Add or Remove folder in Path variable", "Toggle display of hidden and system files", "Refresh shell", "Restart Explorer", "Privileged file manager here" };
static string sClearHistory = CmdLabels[9];
static string sTakeOwnHere = CmdLabels[10];
static string sRestartExplorer = CmdLabels[14];
static string sFolderNotAllowed = "Not allowed for this folder";
static string sWarningTakeOwn = "WARNING: Other users may lose access";
static string sUserPath = "User Path";
static string sSystemPath = "System Path";
static string sRecent = "Recent items";
static string sAutoSuggest = "Auto-suggest items";
static string sTemp = "Temporary files";
static string sDefender = "Defender history";
static string sCCM = "Classic context menu";
static string sRestartPC = "A restart is required to clear the Protection history. Restart now?";
static string sOpenFileManager = "Open file manager as...";
static string sAdministrator = "Administrator";
static string sTrustedInstaller = "Trusted Installer";
static string sShellRefresh = "Shell refresh only";
static string sResetIcons = "Reset icon cache";
static string sResetThumbs = "Reset thumbnail cache";
static string sFileManager = "File Manager";
static string sInstallTask = "Privilege elevation task";
static string Option = "";
static string StartDirectory = "";
static string CommandLine = "";
static float ScaleFactor = GetScale();
static bool Dark = isDark();
static bool isAdmin = false;
static bool isFullAdmin = false;
static bool ctrlKey = false;
static bool fLatCB = true;
static bool addTask = true;
static bool removeTask = true;
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 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-and-remove";
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 DefenderCheckbox;
static CheckBox checkboxCCM;
static CheckBox checkboxTask;
[STAThread]
static void Main(string[] args)
{
// If the current folder is a long path, the Elevate function will fail, so let's make C:\ the current folder.
Directory.SetCurrentDirectory(@"C:\");
ctrlKey = (GetAsyncKeyState(0x11) & 0x8000) != 0; //Detect if Ctrl key is pressed
if (!Environment.Is64BitOperatingSystem) bitPath = "32";
LoadLanguageStrings();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
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();
if (args.Length == 0) { InstallRemove(); return; }
Option = args[0];
if (args.Length > 1)
{
StartDirectory = args[1].Replace("|", "");
}
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 "/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":
if (args.Length > 1) { ElevateCfg = args[1]; }
Elevate();
break;
case "/cmdhere":
RunAsUser(CmdExe);
break;
case "/cmdadminhere":
RunAsAdmin(CmdExe);
break;
case "/cmdtrustedhere":
RunAsTrusted(CmdExe);
break;
case "/powershellhere":
GetPSPath();
RunAsUser(PowerShellExe);
break;
case "/powershelladminhere":
GetPSPath();
RunAsAdmin(PowerShellExe);
break;
case "/powershelltrustedhere":
GetPSPath();
RunAsTrusted(PowerShellExe);
break;
case "/regedit":
Environment.SetEnvironmentVariable("__COMPAT_LAYER", "RUNASINVOKER");
if (ctrlKey) clearRegEdit();
CommandLine = "/m";
RunAsUser(RegEditExe);
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 "/takeownhere":
RunTakeOwnHerePS1AsAdmin();
break;
case "/adddelpathhere":
AddDelPathHere();
break;
case "/addpathadmin":
AddPathAdmin();
break;
case "/delpathadmin":
DelPathAdmin();
break;
case "/showhide":
ShowHide();
break;
case "/clearhistory":
ClearHistory();
break;
case "/clearhistoryadmin":
ClearDefenderHistoryTask();
break;
case "/refreshshellhere":
RefreshShellHere();
break;
case "/restartexplorerhere":
helpPage = "restart-explorer";
DialogResult result = CustomMessageBox.Show($"{sRestartExplorer}?", sMain);
if (result == DialogResult.Cancel) return;
RestartExplorer();
break;
default:
return;
}
}
static void GetPSPath()
{
string PSPath = ReadString(myIniFile, "PowerShellHere", "Exe", "");
if (File.Exists(PSPath)) PowerShellExe = PSPath;
}
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 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();
}
static void FileManagerHere()
{
helpPage = "privileged-file-manager-here";
bwidth = 120;
DialogResult result = TwoChoiceBox.Show(sOpenFileManager, sMain, sAdministrator, sTrustedInstaller);
if (result == DialogResult.Cancel) return;
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";
// 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.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)
{
string Recent = Environment.GetFolderPath(Environment.SpecialFolder.Recent);
try
{
Directory.GetFiles(Recent, "*", SearchOption.TopDirectoryOnly).ToList().ForEach(File.Delete);
Directory.GetFiles($@"{Recent}\AutomaticDestinations", "*", SearchOption.TopDirectoryOnly).ToList().ForEach(File.Delete);
Directory.GetFiles($@"{Recent}\CustomDestinations", "*", SearchOption.TopDirectoryOnly).ToList().ForEach(File.Delete);
}
catch
{
}
}
if (AutoSuggestCheckbox.Checked)
{
string parentKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer";
ClearRegValues($@"{parentKey}\RunMRU");
ClearRegValues($@"{parentKey}\TypedPaths");
Process p = new Process();
p.StartInfo.FileName = "Rundll32.exe";
p.StartInfo.Arguments = "InetCpl.cpl,ClearMyTracksByProcess 1";
p.StartInfo.WorkingDirectory = @"C:\";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
}
if (TempFilesCheckbox.Checked)
{
var filesAndFolders = Directory.GetFileSystemEntries(TempPath, "*", SearchOption.TopDirectoryOnly);
foreach (var entry in filesAndFolders)
{
try
{
if (File.Exists(entry))
{
File.Delete(entry);
}
else if (Directory.Exists(entry))
{
Directory.Delete(entry, true);
}
}
catch
{
}
}
}
if (DefenderCheckbox.Checked)
{
ClearDefenderHistory();
}
}
static void ClearRegValues(string keyPath)
{
try
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyPath, true))
{
if (key != null)
{
foreach (string valueName in key.GetValueNames())
{
key.DeleteValue(valueName);
}
}
}
}
catch
{
}
}
static void AddDelPathHere()
{
string path = StartDirectory;
InUserPath = IsPathInEnvironmentVariable(path, UserPath);
InSystemPath = IsPathInEnvironmentVariable(path, SystemPath);
if (path.EndsWith(":")) path += "\\";
DialogResult result = AddDelPathDialog.Show(path, sMain);
if (result == DialogResult.Cancel) return;
if (userPathCheckbox.Checked != InUserPath)
{
if (userPathCheckbox.Checked)
AddPathToEnvironmentVariable(path, UserPath, UserKey, true);
else
RemovePathFromEnvironmentVariable(path, UserPath, UserKey, true);
}
if (systemPathCheckbox.Checked != InSystemPath)
{
if (systemPathCheckbox.Checked)
{
CommandLine = $"/AddPathAdmin \"{StartDirectory}\"";
}
else
{
CommandLine = $"/DelPathAdmin \"{StartDirectory}\"";
}
RunElevated(myExe, "Administrator");
}
}
static bool IsPathInEnvironmentVariable(string pathToCheck, string environmentVariable)
{
string[] paths = environmentVariable.Split(';');
char[] trimThis = { '\\' };
foreach (string p in paths)
{
if (string.Equals(p.Trim(trimThis), pathToCheck, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
static void AddPathToEnvironmentVariable(string pathToAdd, string environmentVariable, string Key, bool User)
{
if (User && InUserPath) return;
if (!User && InSystemPath) return;
if ((pathLength + pathToAdd.Length) > 4095) return;
string newPath = $"{environmentVariable};{pathToAdd}";
newPath = newPath.Replace(";;",";");
Registry.SetValue(Key, "Path", newPath, RegistryValueKind.ExpandString);
}
static void RemovePathFromEnvironmentVariable(string pathToRemove, string environmentVariable, string Key, bool User)
{
if (User && !InUserPath) return;
if (!User && !InSystemPath) return;
string[] paths = environmentVariable.Split(';');
char[] trimThis = { '\\' };
pathToRemove = pathToRemove.Trim(trimThis);
string newPath = "";
foreach (string p in paths)
{
if (!string.Equals(p.Trim(trimThis), pathToRemove, StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(newPath))
{
newPath += ";";
}
newPath += p;
}
}
newPath = newPath.Replace(";;", ";");
Registry.SetValue(Key, "Path", newPath, RegistryValueKind.ExpandString);
}
static void ShowHide()
{
ToggleHiddenFiles(!Hidden);
}
static void RefreshShell()
{
SHChangeNotify(0x08000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
if (buildNumber >= 14393)
{
ToggleHiddenFiles(!Hidden);
ToggleHiddenFiles(Hidden);
}
}
static void RefreshShellHere()
{
DialogResult result = ShellRefreshDialog.Show("", sMain);
if (result == DialogResult.Cancel) return;
RefreshShell();
if (iconCacheCheckbox.Checked || thumbCacheCheckbox.Checked)
{
if (StartDirectory.ToLower().EndsWith("\\desktop"))
{
if (!DesktopWindowFound()) StartDirectory = "";
}
using (Process p = new Process())
{
p.StartInfo = new ProcessStartInfo
{
FileName = "taskkill.exe",
Arguments = "/f /im explorer.exe",
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = true,
CreateNoWindow = true,
};
p.Start();
p.WaitForExit();
}
Thread.Sleep(2000);
if (iconCacheCheckbox.Checked) DeleteCacheFiles("iconcache_*.db");
if (thumbCacheCheckbox.Checked) DeleteCacheFiles("thumbcache_*.db");
Process.Start("explorer.exe");
if (StartDirectory != "") Process.Start("explorer.exe", StartDirectory);
}
}
static void DeleteCacheFiles(string searchPattern)
{
string targetDirectory = $@"{Environment.GetEnvironmentVariable("LocalAppData")}\Microsoft\Windows\Explorer";
try
{
string[] files = Directory.GetFiles(targetDirectory, searchPattern, SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
try { File.Delete(file); }
catch { }
}
}
catch { }
}
static void ToggleHiddenFiles(bool bShow)
{
if (buildNumber >= 14393)
{
Structures.SHELLSTATE state = new Structures.SHELLSTATE();
state.FShowAllObjects = (uint)(bShow ? 1 : 2);
state.FShowSuperHidden = (uint)(bShow ? 1 : 0);
SHGetSetSettings(ref state, Structures.SSF.SSF_SHOWALLOBJECTS | Structures.SSF.SSF_SHOWSUPERHIDDEN, true);
}
else
{
int h1 = 1; int h2 = 1;
if (Hidden) { h1 = 2; h2 = 0; }
Registry.SetValue(AdvKey, "Hidden", h1, RegistryValueKind.DWord);
Registry.SetValue(AdvKey, "ShowSuperHidden", h2, RegistryValueKind.DWord);
Thread.Sleep(100);
SendKeys.SendWait("{F5}");
}
}
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static void SHGetSetSettings(ref Structures.SHELLSTATE lpss, Structures.SSF dwMask, bool bSet);
internal static class Structures
{
[Flags]
public enum SSF : int
{
SSF_SHOWALLOBJECTS = 0x00000001,
SSF_SHOWSUPERHIDDEN = 0x00040000,
}
[StructLayout(LayoutKind.Sequential)]
public struct SHELLSTATE
{
public uint bitvector;
public uint FShowAllObjects
{
get => this.bitvector & 1;
set => this.bitvector = value | this.bitvector;
}
public uint FShowSuperHidden
{
get => (this.bitvector & 0x8000) / 0x8000;
set => this.bitvector = (value * 0x8000) | this.bitvector;
}
}
}
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
static bool DesktopWindowFound()
{
bool desktopFound = false;
IntPtr hwnd = IntPtr.Zero;
do
{
hwnd = FindWindowEx(IntPtr.Zero, hwnd, "CabinetWClass", null);
if (hwnd != IntPtr.Zero)
{
StringBuilder windowTitle = new StringBuilder(256);
GetWindowText(hwnd, windowTitle, windowTitle.Capacity);
string t = windowTitle.ToString().ToLower();
if (t == "desktop" || t == "desktop - file explorer")
{
desktopFound = true;
break;
}
}
}
while (hwnd != IntPtr.Zero);
return desktopFound;
}
static void RestartExplorer()
{
if (StartDirectory.ToLower().EndsWith("\\desktop"))
{
if (!DesktopWindowFound()) StartDirectory = "";
}
RefreshShell();
var processes = Process.GetProcessesByName("explorer");
foreach (var process in processes)
{
try
{
process.Kill();
process.WaitForExit();
}
catch { }
}
if (StartDirectory != "") Process.Start("explorer.exe", StartDirectory);
}
static void CreateChangeDirectoryFile(string EXEFilename)
{
if (EXEFilename == CmdExe)
{
string cdFile = $@"{TempPath}ChangeDirectory.cmd";
StartDirectory = StartDirectory.Replace("%", "%%"); //Escape percent signs
string Data = $"@echo off\r\nchcp 65001>nul\r\ncd /d \"{StartDirectory}\"";
Data += "\r\nstart /b \"\" cmd /c del \"%~f0\"";
File.WriteAllText(cdFile, Data);
CommandLine = $"/k \"{cdFile}\"";
}
if (EXEFilename == PowerShellExe)
{
string cdFile = $@"{TempPath}ChangeDirectory.ps1";
StartDirectory = StartDirectory.Replace("'", "''"); //Escape single quotes
string Data = $@"Set-Location -LiteralPath '{StartDirectory}'";
if (StartDirectory.Contains("~")) Data += "\r\nfunction Prompt {$shortPath = (New-Object -ComObject Scripting.FileSystemObject).GetFolder($pwd).ShortPath; return \"PS $($shortPath)> \"}";
Data += "\r\nStart-Sleep -Milliseconds 100; Remove-Item $MyInvocation.MyCommand.Path -Force\r\n"; //Delete itself when done
File.WriteAllText(cdFile, Data, Encoding.UTF8); //UTF-8 with BOM
CommandLine = $"-NoLogo -NoExit -NoProfile -ExecutionPolicy Bypass -file \"{cdFile}\"";
}
}
static void CreateTakeOwnHerePS1()
{
StartDirectory = StartDirectory.Replace("'", "''"); //Escape single quotes
string PS1Data = $"$SetACL = '{appParts.Replace("'", "''")}\\{bitPath}\\SetACL.exe'\r\n";
PS1Data += "$UserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name\r\n";
PS1Data += $"& $SetACL -on '{StartDirectory}' -ot file -actn setowner -ownr \"n:$UserName\" -rec cont_obj\r\n";
PS1Data += $"& $SetACL -on '{StartDirectory}' -ot file -actn setprot -op \"dacl:np;sacl:np\" -rec cont_obj\r\n";
PS1Data += "Start-Sleep -Milliseconds 100; Remove-Item $MyInvocation.MyCommand.Path -Force\r\n"; //Delete itself when done
string PS1File = $@"{TempPath}TakeOwn.ps1";
File.WriteAllText(PS1File, PS1Data, Encoding.UTF8);
ctrlKey = (GetAsyncKeyState(0x11) & 0x8000) != 0;
string NoExit = ""; if (ctrlKey) NoExit = "-NoExit";
CommandLine = $"{NoExit} -NoLogo -NoProfile -ExecutionPolicy Bypass -file \"{PS1File}\"";
}
static void RunAsUser(string EXEFilename)
{
CreateChangeDirectoryFile(EXEFilename);
Process p = new Process();
p.StartInfo.FileName = EXEFilename;
p.StartInfo.Arguments = CommandLine;
p.StartInfo.WorkingDirectory = @"C:\";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = false;
p.Start();
}
static void RunAsAdmin(string EXEFilename)
{
RunElevated(EXEFilename, "Administrator");
}
static void RunAsTrusted(string EXEFilename)
{
RunElevated(EXEFilename, "TrustedInstaller");
}
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
static void clearRegEdit()
{
try
{
Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", false);
}
catch
{
}
}
static void Elevate()
{
string iniFile = ElevateCfg;
string EXEFilename = ReadString(iniFile, "Process", "EXEFilename", "");
string CommandLine = ReadString(iniFile, "Process", "CommandLine", "");
string RunAs = ReadString(iniFile, "Process", "RunAs", "");
string Dark = ReadString(iniFile, "Process", "Dark", "false");
bool dark = Dark == "True";
File.Delete(ElevateCfg);
if (RunAs == "TrustedInstaller")
{
ServiceController sc = new ServiceController
{
ServiceName = "TrustedInstaller",
};
if (sc.Status != ServiceControllerStatus.Running) sc.Start();
Process[] proc = Process.GetProcessesByName("TrustedInstaller");
if (dark) TrustedInstaller.Run(proc[0].Id, $"{myExe} /Dark");
if (!dark) TrustedInstaller.Run(proc[0].Id, $"{myExe} /Light");
Thread.Sleep(100);
proc = Process.GetProcessesByName("TrustedInstaller");
TrustedInstaller.Run(proc[0].Id, $"{EXEFilename} {CommandLine}");
}
else
{
if (ctrlKey && (EXEFilename == RegEditExe)) clearRegEdit();
Process p = new Process();
p.StartInfo.FileName = EXEFilename;
p.StartInfo.Arguments = CommandLine;
p.StartInfo.WorkingDirectory = @"C:\";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = false;
p.Start();
}
}
static void RunElevated(string EXEFilename, string mode)
{
CreateChangeDirectoryFile(EXEFilename);
string cfg = $"[Process]\r\nEXEFilename={EXEFilename}\r\nCommandLine={CommandLine}\r\nRunAs={mode}\r\nDark={Dark}";
File.WriteAllText(ElevateCfg, cfg);
if (isFullAdmin)
{
Process p = new Process();
p.StartInfo.FileName = SchTasksExe;
p.StartInfo.Arguments = $"/run /tn \"{TaskName}\"";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
}
else
{
if (mode == "Administrator")
{
RunUAC(EXEFilename);
}
else
{
Process p = new Process();
p.StartInfo.FileName = myExe;
p.StartInfo.Arguments = $"/Elevate \"{ElevateCfg}\"";
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Verb = "runas";
p.Start();
}
}
}
static void RunTakeOwnHerePS1AsAdmin()
{
string sStopAll = ReadString(myIniFile, "TakeOwnHere", "StopAll", "");
string[] StopAll = sStopAll.Split(new char[] { '|' });
string sStopRoot = ReadString(myIniFile, "TakeOwnHere", "StopRoot", "");
string[] StopRoot = sStopRoot.Split(new char[] { '|' });
bool Stop = false;
for (int i = 0; i < StopAll.Length; i++)
{
if (StartsWith(StopAll[i], StartDirectory)) { Stop = true; break; }
}
for (int i = 0; i < StopRoot.Length; i++)