Utilities.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Management.Automation;
  9. using System.Net;
  10. using System.Net.NetworkInformation;
  11. using System.Net.Sockets;
  12. using System.Reflection;
  13. using System.Security.AccessControl;
  14. using System.Security.Principal;
  15. using System.ServiceProcess;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using System.Windows.Forms;
  19. namespace Optimizer
  20. {
  21. internal static class Utilities
  22. {
  23. internal static readonly string LocalMachineRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  24. internal static readonly string LocalMachineRunOnce = "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  25. internal static readonly string LocalMachineRunWoW = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run";
  26. internal static readonly string LocalMachineRunOnceWow = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  27. internal static readonly string CurrentUserRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  28. internal static readonly string CurrentUserRunOnce = "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  29. internal static readonly string LocalMachineStartupFolder = CleanHelper.ProgramData + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
  30. internal static readonly string CurrentUserStartupFolder = CleanHelper.ProfileAppDataRoaming + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
  31. // DEPRECATED
  32. //internal readonly static string DefaultEdgeDownloadFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
  33. internal static WindowsVersion CurrentWindowsVersion = WindowsVersion.Unsupported;
  34. static string productName = string.Empty;
  35. static string buildNumber = string.Empty;
  36. internal delegate void SetControlPropertyThreadSafeDelegate(Control control, string propertyName, object propertyValue);
  37. internal static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
  38. {
  39. if (control.InvokeRequired)
  40. {
  41. control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
  42. }
  43. else
  44. {
  45. control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
  46. }
  47. }
  48. internal static IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
  49. {
  50. List<Control> controls = new List<Control>();
  51. foreach (Control child in parent.Controls)
  52. {
  53. controls.AddRange(GetSelfAndChildrenRecursive(child));
  54. }
  55. controls.Add(parent);
  56. return controls;
  57. }
  58. internal static Color ToGrayScale(this Color originalColor)
  59. {
  60. if (originalColor.Equals(Color.Transparent))
  61. return originalColor;
  62. int grayScale = (int)((originalColor.R * .299) + (originalColor.G * .587) + (originalColor.B * .114));
  63. return Color.FromArgb(grayScale, grayScale, grayScale);
  64. }
  65. internal static string GetWindows10Build()
  66. {
  67. return (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId", "");
  68. }
  69. internal static string GetOS()
  70. {
  71. productName = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", "");
  72. if (productName.Contains("Windows 7"))
  73. {
  74. CurrentWindowsVersion = WindowsVersion.Windows7;
  75. }
  76. if ((productName.Contains("Windows 8")) || (productName.Contains("Windows 8.1")))
  77. {
  78. CurrentWindowsVersion = WindowsVersion.Windows8;
  79. }
  80. if (productName.Contains("Windows 10"))
  81. {
  82. buildNumber = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "CurrentBuild", "");
  83. if (Convert.ToInt32(buildNumber) >= 22000)
  84. {
  85. productName = productName.Replace("Windows 10", "Windows 11");
  86. CurrentWindowsVersion = WindowsVersion.Windows11;
  87. }
  88. else
  89. {
  90. CurrentWindowsVersion = WindowsVersion.Windows10;
  91. }
  92. }
  93. if (Program.UNSAFE_MODE)
  94. {
  95. if (productName.Contains("Windows Server 2008"))
  96. {
  97. CurrentWindowsVersion = WindowsVersion.Windows7;
  98. }
  99. if (productName.Contains("Windows Server 2012"))
  100. {
  101. CurrentWindowsVersion = WindowsVersion.Windows8;
  102. }
  103. if (productName.Contains("Windows Server 2016") || productName.Contains("Windows Server 2019") || productName.Contains("Windows Server 2022"))
  104. {
  105. CurrentWindowsVersion = WindowsVersion.Windows10;
  106. }
  107. }
  108. return productName;
  109. }
  110. internal static string GetBitness()
  111. {
  112. string bitness = string.Empty;
  113. if (Environment.Is64BitOperatingSystem)
  114. {
  115. bitness = "You are working with 64-bit";
  116. }
  117. else
  118. {
  119. bitness = "You are working with 32-bit";
  120. }
  121. return bitness;
  122. }
  123. internal static bool IsAdmin()
  124. {
  125. return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
  126. }
  127. internal static bool IsCompatible()
  128. {
  129. bool legit;
  130. string os = GetOS();
  131. if ((os.Contains("XP")) || (os.Contains("Vista")) || os.Contains("Server 2003"))
  132. {
  133. legit = false;
  134. }
  135. else
  136. {
  137. legit = true;
  138. }
  139. return legit;
  140. }
  141. // DEPRECATED
  142. //internal static string GetEdgeDownloadFolder()
  143. //{
  144. // string current = string.Empty;
  145. // try
  146. // {
  147. // current = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", DefaultEdgeDownloadFolder).ToString();
  148. // }
  149. // catch (Exception ex)
  150. // {
  151. // current = DefaultEdgeDownloadFolder;
  152. // ErrorLogger.LogError("Utilities.GetEdgeDownloadFolder", ex.Message, ex.StackTrace);
  153. // }
  154. // return current;
  155. //}
  156. // DEPRECATED
  157. //internal static void SetEdgeDownloadFolder(string path)
  158. //{
  159. // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", path, RegistryValueKind.String);
  160. //}
  161. internal static void RunBatchFile(string batchFile)
  162. {
  163. try
  164. {
  165. using (Process p = new Process())
  166. {
  167. p.StartInfo.CreateNoWindow = true;
  168. p.StartInfo.FileName = batchFile;
  169. p.StartInfo.UseShellExecute = false;
  170. p.Start();
  171. p.WaitForExit();
  172. p.Close();
  173. }
  174. }
  175. catch (Exception ex)
  176. {
  177. ErrorLogger.LogError("Utilities.RunBatchFile", ex.Message, ex.StackTrace);
  178. }
  179. }
  180. internal static void ImportRegistryScript(string scriptFile)
  181. {
  182. string path = "\"" + scriptFile + "\"";
  183. Process p = new Process();
  184. try
  185. {
  186. p.StartInfo.FileName = "regedit.exe";
  187. p.StartInfo.UseShellExecute = false;
  188. p = Process.Start("regedit.exe", "/s " + path);
  189. p.WaitForExit();
  190. }
  191. catch (Exception ex)
  192. {
  193. p.Dispose();
  194. ErrorLogger.LogError("Utilities.ImportRegistryScript", ex.Message, ex.StackTrace);
  195. }
  196. finally
  197. {
  198. p.Dispose();
  199. }
  200. }
  201. internal static void Reboot()
  202. {
  203. Utilities.RunCommand("shutdown /r /t 0");
  204. }
  205. internal static void DisableHibernation()
  206. {
  207. Utilities.RunCommand("powercfg -h off");
  208. Utilities.RunCommand("powercfg -h off");
  209. }
  210. internal static void EnableHibernation()
  211. {
  212. Utilities.RunCommand("powercfg -h on");
  213. Utilities.RunCommand("powercfg -h on");
  214. }
  215. internal static void ActivateMainForm()
  216. {
  217. Program._MainForm.Activate();
  218. }
  219. internal static bool ServiceExists(string serviceName)
  220. {
  221. return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName));
  222. }
  223. internal static void StopService(string serviceName)
  224. {
  225. if (ServiceExists(serviceName))
  226. {
  227. ServiceController sc = new ServiceController(serviceName);
  228. if (sc.CanStop)
  229. {
  230. sc.Stop();
  231. }
  232. }
  233. }
  234. internal static void StartService(string serviceName)
  235. {
  236. if (ServiceExists(serviceName))
  237. {
  238. ServiceController sc = new ServiceController(serviceName);
  239. try
  240. {
  241. sc.Start();
  242. }
  243. catch (Exception ex)
  244. {
  245. ErrorLogger.LogError("Utilities.StartService", ex.Message, ex.StackTrace);
  246. }
  247. }
  248. }
  249. private static void GetRegistryStartupItemsHelper(ref List<StartupItem> list, StartupItemLocation location, StartupItemType type)
  250. {
  251. string keyPath = string.Empty;
  252. RegistryKey hive = null;
  253. if (location == StartupItemLocation.HKLM)
  254. {
  255. hive = Registry.LocalMachine;
  256. if (type == StartupItemType.Run)
  257. {
  258. keyPath = LocalMachineRun;
  259. }
  260. else if (type == StartupItemType.RunOnce)
  261. {
  262. keyPath = LocalMachineRunOnce;
  263. }
  264. }
  265. else if (location == StartupItemLocation.HKLMWoW)
  266. {
  267. hive = Registry.LocalMachine;
  268. if (type == StartupItemType.Run)
  269. {
  270. keyPath = LocalMachineRunWoW;
  271. }
  272. else if (type == StartupItemType.RunOnce)
  273. {
  274. keyPath = LocalMachineRunOnceWow;
  275. }
  276. }
  277. else if (location == StartupItemLocation.HKCU)
  278. {
  279. hive = Registry.CurrentUser;
  280. if (type == StartupItemType.Run)
  281. {
  282. keyPath = CurrentUserRun;
  283. }
  284. else if (type == StartupItemType.RunOnce)
  285. {
  286. keyPath = CurrentUserRunOnce;
  287. }
  288. }
  289. if (hive != null)
  290. {
  291. try
  292. {
  293. RegistryKey key = hive.OpenSubKey(keyPath, true);
  294. if (key != null)
  295. {
  296. string[] valueNames = key.GetValueNames();
  297. foreach (string x in valueNames)
  298. {
  299. try
  300. {
  301. RegistryStartupItem item = new RegistryStartupItem();
  302. item.Name = x;
  303. item.FileLocation = key.GetValue(x).ToString();
  304. item.Key = key;
  305. item.RegistryLocation = location;
  306. item.StartupType = type;
  307. list.Add(item);
  308. }
  309. catch (Exception ex)
  310. {
  311. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  312. }
  313. }
  314. }
  315. }
  316. catch (Exception ex)
  317. {
  318. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  319. }
  320. }
  321. }
  322. private static void GetFolderStartupItemsHelper(ref List<StartupItem> list, string[] files, string[] shortcuts)
  323. {
  324. foreach (string file in files)
  325. {
  326. try
  327. {
  328. FolderStartupItem item = new FolderStartupItem();
  329. item.Name = Path.GetFileNameWithoutExtension(file);
  330. item.FileLocation = file;
  331. item.Shortcut = file;
  332. item.RegistryLocation = StartupItemLocation.Folder;
  333. list.Add(item);
  334. }
  335. catch (Exception ex)
  336. {
  337. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  338. }
  339. }
  340. foreach (string shortcut in shortcuts)
  341. {
  342. try
  343. {
  344. FolderStartupItem item = new FolderStartupItem();
  345. item.Name = Path.GetFileNameWithoutExtension(shortcut);
  346. item.FileLocation = GetShortcutTargetFile(shortcut);
  347. item.Shortcut = shortcut;
  348. item.RegistryLocation = StartupItemLocation.Folder;
  349. list.Add(item);
  350. }
  351. catch (Exception ex)
  352. {
  353. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  354. }
  355. }
  356. }
  357. internal static List<StartupItem> GetStartupItems()
  358. {
  359. List<StartupItem> startupItems = new List<StartupItem>();
  360. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.Run);
  361. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.RunOnce);
  362. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.Run);
  363. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.RunOnce);
  364. if (Environment.Is64BitOperatingSystem)
  365. {
  366. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.Run);
  367. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.RunOnce);
  368. }
  369. if (Directory.Exists(CurrentUserStartupFolder))
  370. {
  371. string[] currentUserFiles = Directory.EnumerateFiles(CurrentUserStartupFolder, "*.*", SearchOption.AllDirectories)
  372. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  373. string[] currentUserShortcuts = Directory.GetFiles(CurrentUserStartupFolder, "*.lnk", SearchOption.AllDirectories);
  374. GetFolderStartupItemsHelper(ref startupItems, currentUserFiles, currentUserShortcuts);
  375. }
  376. if (Directory.Exists(LocalMachineStartupFolder))
  377. {
  378. string[] localMachineFiles = Directory.EnumerateFiles(LocalMachineStartupFolder, "*.*", SearchOption.AllDirectories)
  379. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  380. string[] localMachineShortcuts = Directory.GetFiles(LocalMachineStartupFolder, "*.lnk", SearchOption.AllDirectories);
  381. GetFolderStartupItemsHelper(ref startupItems, localMachineFiles, localMachineShortcuts);
  382. }
  383. return startupItems;
  384. }
  385. internal static void EnableFirewall()
  386. {
  387. RunCommand("netsh advfirewall set currentprofile state on");
  388. }
  389. internal static void EnableCommandPrompt()
  390. {
  391. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  392. {
  393. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  394. }
  395. }
  396. internal static void EnableControlPanel()
  397. {
  398. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  399. {
  400. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  401. }
  402. }
  403. internal static void EnableFolderOptions()
  404. {
  405. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  406. {
  407. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  408. }
  409. }
  410. internal static void EnableRunDialog()
  411. {
  412. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  413. {
  414. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  415. }
  416. }
  417. internal static void EnableContextMenu()
  418. {
  419. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  420. {
  421. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  422. }
  423. }
  424. internal static void EnableTaskManager()
  425. {
  426. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  427. {
  428. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  429. }
  430. }
  431. internal static void EnableRegistryEditor()
  432. {
  433. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  434. {
  435. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  436. }
  437. }
  438. internal static void RunCommand(string command)
  439. {
  440. using (Process p = new Process())
  441. {
  442. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  443. p.StartInfo.FileName = "cmd.exe";
  444. p.StartInfo.Arguments = "/C " + command;
  445. p.StartInfo.CreateNoWindow = true;
  446. try
  447. {
  448. p.Start();
  449. p.WaitForExit();
  450. p.Close();
  451. }
  452. catch (Exception ex)
  453. {
  454. ErrorLogger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  455. }
  456. }
  457. }
  458. internal static void FindFile(string fileName)
  459. {
  460. if (File.Exists(fileName)) Process.Start("explorer.exe", $"/select, \"{fileName}\"");
  461. }
  462. internal static string GetShortcutTargetFile(string shortcutFilename)
  463. {
  464. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  465. string filenameOnly = Path.GetFileName(shortcutFilename);
  466. Shell32.Shell shell = new Shell32.Shell();
  467. Shell32.Folder folder = shell.NameSpace(pathOnly);
  468. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  469. if (folderItem != null)
  470. {
  471. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  472. return link.Path;
  473. }
  474. return string.Empty;
  475. }
  476. internal static void RestartExplorer()
  477. {
  478. const string explorer = "explorer.exe";
  479. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  480. foreach (Process process in Process.GetProcesses())
  481. {
  482. try
  483. {
  484. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  485. {
  486. process.Kill();
  487. }
  488. }
  489. catch (Exception ex)
  490. {
  491. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  492. }
  493. }
  494. Thread.Sleep(TimeSpan.FromSeconds(1));
  495. Process.Start(explorer);
  496. }
  497. internal static void FindKeyInRegistry(string key)
  498. {
  499. try
  500. {
  501. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  502. Process.Start("regedit");
  503. }
  504. catch (Exception ex)
  505. {
  506. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  507. }
  508. }
  509. internal static List<string> GetModernApps(bool showAll)
  510. {
  511. List<string> modernApps = new List<string>();
  512. using (PowerShell script = PowerShell.Create())
  513. {
  514. if (showAll)
  515. {
  516. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  517. }
  518. else
  519. {
  520. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  521. }
  522. string tmp = string.Empty;
  523. foreach (PSObject x in script.Invoke())
  524. {
  525. tmp = x.ToString().Trim();
  526. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  527. {
  528. modernApps.Add(tmp);
  529. }
  530. }
  531. }
  532. return modernApps;
  533. }
  534. internal static bool UninstallModernApp(string appName)
  535. {
  536. using (PowerShell script = PowerShell.Create())
  537. {
  538. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  539. script.Invoke();
  540. return script.Streams.Error.Count > 0;
  541. // not working on Windows 7 anymore
  542. //return script.HadErrors;
  543. }
  544. }
  545. internal static void ResetConfiguration(bool withoutRestart = false)
  546. {
  547. try
  548. {
  549. Directory.Delete(Required.CoreFolder, true);
  550. }
  551. catch (Exception ex)
  552. {
  553. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  554. }
  555. finally
  556. {
  557. if (!withoutRestart)
  558. {
  559. // BYPASS SINGLE-INSTANCE MECHANISM
  560. if (Program.MUTEX != null)
  561. {
  562. Program.MUTEX.ReleaseMutex();
  563. Program.MUTEX.Dispose();
  564. Program.MUTEX = null;
  565. }
  566. Application.Restart();
  567. }
  568. }
  569. }
  570. internal static Task RunAsync(this Process process)
  571. {
  572. var tcs = new TaskCompletionSource<object>();
  573. process.EnableRaisingEvents = true;
  574. process.Exited += (s, e) => tcs.TrySetResult(null);
  575. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  576. return tcs.Task;
  577. }
  578. internal static string SanitizeFileFolderName(string fileName)
  579. {
  580. char[] invalids = Path.GetInvalidFileNameChars();
  581. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  582. }
  583. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  584. internal static void EnableGPEDitor()
  585. {
  586. Utilities.RunBatchFile(Required.ScriptsFolder + "GPEditEnablerInHome.bat");
  587. }
  588. internal static void TryDeleteRegistryValue(bool localMachine, string path, string valueName)
  589. {
  590. try
  591. {
  592. if (localMachine) Registry.LocalMachine.OpenSubKey(path, true).DeleteValue(valueName, false);
  593. if (!localMachine) Registry.CurrentUser.OpenSubKey(path, true).DeleteValue(valueName, false);
  594. }
  595. catch { }
  596. }
  597. internal static void DisableProtectedService(string serviceName)
  598. {
  599. using (TokenPrivilege.TakeOwnership)
  600. {
  601. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  602. {
  603. allServicesKey.GrantFullControlOnSubKey(serviceName);
  604. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  605. {
  606. if (serviceKey == null) return;
  607. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  608. {
  609. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  610. serviceKey.GrantFullControlOnSubKey(subkeyName);
  611. }
  612. serviceKey.SetValue("Start", "4", RegistryValueKind.DWord);
  613. }
  614. }
  615. }
  616. }
  617. internal static void RestoreWindowsPhotoViewer()
  618. {
  619. const string PHOTO_VIEWER_SHELL_COMMAND =
  620. @"%SystemRoot%\System32\rundll32.exe ""%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll"", ImageView_Fullscreen %1";
  621. const string PHOTO_VIEWER_CLSID = "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}";
  622. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open", "MuiVerb", "@photoviewer.dll,-3043");
  623. Registry.SetValue(
  624. @"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\command", valueName: null,
  625. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  626. );
  627. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  628. string[] imageTypes = { "Paint.Picture", "giffile", "jpegfile", "pngfile" };
  629. foreach (string type in imageTypes)
  630. {
  631. Registry.SetValue(
  632. $@"HKEY_CLASSES_ROOT\{type}\shell\open\command", valueName: null,
  633. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  634. );
  635. Registry.SetValue($@"HKEY_CLASSES_ROOT\{type}\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  636. }
  637. }
  638. internal static void EnableProtectedService(string serviceName)
  639. {
  640. using (TokenPrivilege.TakeOwnership)
  641. {
  642. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  643. {
  644. allServicesKey.GrantFullControlOnSubKey(serviceName);
  645. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  646. {
  647. if (serviceKey == null) return;
  648. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  649. {
  650. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  651. serviceKey.GrantFullControlOnSubKey(subkeyName);
  652. }
  653. serviceKey.SetValue("Start", "2", RegistryValueKind.DWord);
  654. }
  655. }
  656. }
  657. }
  658. public static RegistryKey OpenSubKeyWritable(this RegistryKey registryKey, string subkeyName, RegistryRights? rights = null)
  659. {
  660. RegistryKey subKey = null;
  661. if (rights == null)
  662. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree);
  663. else
  664. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, rights.Value);
  665. if (subKey == null)
  666. {
  667. ErrorLogger.LogError("Utilities.OpenSubKeyWritable", $"Subkey {subkeyName} not found.", "-");
  668. }
  669. return subKey;
  670. }
  671. internal static SecurityIdentifier RetrieveCurrentUserIdentifier()
  672. => WindowsIdentity.GetCurrent().User ?? throw new Exception("Unable to retrieve current user SID.");
  673. internal static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName)
  674. {
  675. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName,
  676. RegistryRights.TakeOwnership | RegistryRights.ChangePermissions
  677. ))
  678. {
  679. RegistrySecurity accessRules = subKey.GetAccessControl();
  680. SecurityIdentifier currentUser = RetrieveCurrentUserIdentifier();
  681. accessRules.SetOwner(currentUser);
  682. accessRules.ResetAccessRule(
  683. new RegistryAccessRule(
  684. currentUser,
  685. RegistryRights.FullControl,
  686. InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  687. PropagationFlags.None,
  688. AccessControlType.Allow
  689. )
  690. );
  691. subKey.SetAccessControl(accessRules);
  692. }
  693. }
  694. internal static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
  695. {
  696. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership))
  697. {
  698. RegistrySecurity accessRules = subKey.GetAccessControl();
  699. accessRules.SetOwner(RetrieveCurrentUserIdentifier());
  700. subKey.SetAccessControl(accessRules);
  701. }
  702. }
  703. internal static string GetNETFramework()
  704. {
  705. string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
  706. int netRelease;
  707. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
  708. {
  709. if (ndpKey != null && ndpKey.GetValue("Release") != null)
  710. {
  711. netRelease = (int)ndpKey.GetValue("Release");
  712. }
  713. else
  714. {
  715. return "4.0";
  716. }
  717. }
  718. if (netRelease >= 528040)
  719. return "4.8";
  720. if (netRelease >= 461808)
  721. return "4.7.2";
  722. if (netRelease >= 461308)
  723. return "4.7.1";
  724. if (netRelease >= 460798)
  725. return "4.7";
  726. if (netRelease >= 394802)
  727. return "4.6.2";
  728. if (netRelease >= 394254)
  729. return "4.6.1";
  730. if (netRelease >= 393295)
  731. return "4.6";
  732. if (netRelease >= 379893)
  733. return "4.5.2";
  734. if (netRelease >= 378675)
  735. return "4.5.1";
  736. if (netRelease >= 378389)
  737. return "4.5";
  738. return "4.0";
  739. }
  740. internal static void SearchWith(string term, bool ddg)
  741. {
  742. try
  743. {
  744. if (ddg) Process.Start(string.Format("https://duckduckgo.com/?q={0}", term));
  745. if (!ddg) Process.Start(string.Format("https://www.google.com/search?q={0}", term));
  746. }
  747. catch { }
  748. }
  749. internal static void PreventProcessFromRunning(string pName)
  750. {
  751. try
  752. {
  753. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
  754. {
  755. if (ifeo == null) return;
  756. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  757. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options"))
  758. {
  759. if (k == null) return;
  760. k.CreateSubKey(pName);
  761. k.GrantFullControlOnSubKey(pName);
  762. using (RegistryKey f = k.OpenSubKeyWritable(pName))
  763. {
  764. if (f == null) return;
  765. f.SetValue("Debugger", @"%windir%\System32\taskkill.exe");
  766. }
  767. }
  768. }
  769. }
  770. catch (Exception ex)
  771. {
  772. ErrorLogger.LogError("Utilities.PreventProcessFromRunning", ex.Message, ex.StackTrace);
  773. }
  774. }
  775. }
  776. }