Utilities.cs 34 KB

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