Utilities.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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.Reflection;
  8. using System.Security.AccessControl;
  9. using System.Security.Principal;
  10. using System.ServiceProcess;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Windows.Forms;
  14. namespace Optimizer
  15. {
  16. internal static class Utilities
  17. {
  18. // DEPRECATED
  19. //internal readonly static string DefaultEdgeDownloadFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
  20. internal static WindowsVersion CurrentWindowsVersion = WindowsVersion.Unsupported;
  21. static string productName = string.Empty;
  22. static string buildNumber = string.Empty;
  23. internal delegate void SetControlPropertyThreadSafeDelegate(Control control, string propertyName, object propertyValue);
  24. internal static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
  25. {
  26. if (control.InvokeRequired)
  27. {
  28. control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
  29. }
  30. else
  31. {
  32. control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
  33. }
  34. }
  35. internal static IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
  36. {
  37. List<Control> controls = new List<Control>();
  38. foreach (Control child in parent.Controls)
  39. {
  40. controls.AddRange(GetSelfAndChildrenRecursive(child));
  41. }
  42. controls.Add(parent);
  43. return controls;
  44. }
  45. internal static Color ToGrayScale(this Color originalColor)
  46. {
  47. if (originalColor.Equals(Color.Transparent))
  48. return originalColor;
  49. int grayScale = (int)((originalColor.R * .299) + (originalColor.G * .587) + (originalColor.B * .114));
  50. return Color.FromArgb(grayScale, grayScale, grayScale);
  51. }
  52. internal static string GetWindowsDetails()
  53. {
  54. string bitness = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";
  55. if (CurrentWindowsVersion == WindowsVersion.Windows10 || CurrentWindowsVersion == WindowsVersion.Windows11)
  56. {
  57. return string.Format("{0} - {1} ({2})", GetOS(), GetWindows10Build(), bitness);
  58. }
  59. else
  60. {
  61. return string.Format("{0} - ({1})", GetOS(), bitness);
  62. }
  63. }
  64. internal static string GetWindows10Build()
  65. {
  66. return (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "DisplayVersion", "");
  67. }
  68. internal static string GetOS()
  69. {
  70. productName = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", "");
  71. if (productName.Contains("Windows 7"))
  72. {
  73. CurrentWindowsVersion = WindowsVersion.Windows7;
  74. }
  75. if ((productName.Contains("Windows 8")) || (productName.Contains("Windows 8.1")))
  76. {
  77. CurrentWindowsVersion = WindowsVersion.Windows8;
  78. }
  79. if (productName.Contains("Windows 10"))
  80. {
  81. buildNumber = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "CurrentBuild", "");
  82. if (Convert.ToInt32(buildNumber) >= 22000)
  83. {
  84. productName = productName.Replace("Windows 10", "Windows 11");
  85. CurrentWindowsVersion = WindowsVersion.Windows11;
  86. }
  87. else
  88. {
  89. CurrentWindowsVersion = WindowsVersion.Windows10;
  90. }
  91. }
  92. if (Program.UNSAFE_MODE)
  93. {
  94. if (productName.Contains("Windows Server 2008"))
  95. {
  96. CurrentWindowsVersion = WindowsVersion.Windows7;
  97. }
  98. if (productName.Contains("Windows Server 2012"))
  99. {
  100. CurrentWindowsVersion = WindowsVersion.Windows8;
  101. }
  102. if (productName.Contains("Windows Server 2016") || productName.Contains("Windows Server 2019") || productName.Contains("Windows Server 2022"))
  103. {
  104. CurrentWindowsVersion = WindowsVersion.Windows10;
  105. }
  106. }
  107. return productName;
  108. }
  109. internal static string GetBitness()
  110. {
  111. string bitness;
  112. if (Environment.Is64BitOperatingSystem)
  113. {
  114. bitness = "You are working with 64-bit";
  115. }
  116. else
  117. {
  118. bitness = "You are working with 32-bit";
  119. }
  120. return bitness;
  121. }
  122. internal static bool IsAdmin()
  123. {
  124. return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
  125. }
  126. internal static bool IsCompatible()
  127. {
  128. bool legit;
  129. string os = GetOS();
  130. if ((os.Contains("XP")) || (os.Contains("Vista")) || os.Contains("Server 2003"))
  131. {
  132. legit = false;
  133. }
  134. else
  135. {
  136. legit = true;
  137. }
  138. return legit;
  139. }
  140. // DEPRECATED
  141. //internal static string GetEdgeDownloadFolder()
  142. //{
  143. // string current = string.Empty;
  144. // try
  145. // {
  146. // current = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", DefaultEdgeDownloadFolder).ToString();
  147. // }
  148. // catch (Exception ex)
  149. // {
  150. // current = DefaultEdgeDownloadFolder;
  151. // ErrorLogger.LogError("Utilities.GetEdgeDownloadFolder", ex.Message, ex.StackTrace);
  152. // }
  153. // return current;
  154. //}
  155. // DEPRECATED
  156. //internal static void SetEdgeDownloadFolder(string path)
  157. //{
  158. // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", path, RegistryValueKind.String);
  159. //}
  160. internal static void RunBatchFile(string batchFile)
  161. {
  162. try
  163. {
  164. using (Process p = new Process())
  165. {
  166. p.StartInfo.CreateNoWindow = true;
  167. p.StartInfo.FileName = batchFile;
  168. p.StartInfo.UseShellExecute = false;
  169. p.Start();
  170. p.WaitForExit();
  171. p.Close();
  172. }
  173. }
  174. catch (Exception ex)
  175. {
  176. Logger.LogError("Utilities.RunBatchFile", ex.Message, ex.StackTrace);
  177. }
  178. }
  179. internal static void ImportRegistryScript(string scriptFile)
  180. {
  181. string path = "\"" + scriptFile + "\"";
  182. Process p = new Process();
  183. try
  184. {
  185. p.StartInfo.FileName = "regedit.exe";
  186. p.StartInfo.UseShellExecute = false;
  187. p = Process.Start("regedit.exe", "/s " + path);
  188. p.WaitForExit();
  189. }
  190. catch (Exception ex)
  191. {
  192. p.Dispose();
  193. Logger.LogError("Utilities.ImportRegistryScript", ex.Message, ex.StackTrace);
  194. }
  195. finally
  196. {
  197. p.Dispose();
  198. }
  199. }
  200. internal static void Reboot()
  201. {
  202. OptionsHelper.SaveSettings();
  203. Process.Start("shutdown.exe", "/r /t 0");
  204. }
  205. internal static void DisableHibernation()
  206. {
  207. Utilities.RunCommand("powercfg -h off");
  208. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Power", "HibernateEnabled", "0", RegistryValueKind.DWord);
  209. }
  210. internal static void EnableHibernation()
  211. {
  212. Utilities.TryDeleteRegistryValue(true, @"SYSTEM\CurrentControlSet\Control\Power", "HibernateEnabled");
  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 Array.Exists(ServiceController.GetServices(), (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. Logger.LogError("Utilities.StartService", ex.Message, ex.StackTrace);
  246. }
  247. }
  248. }
  249. internal static void EnableFirewall()
  250. {
  251. RunCommand("netsh advfirewall set currentprofile state on");
  252. }
  253. internal static void EnableCommandPrompt()
  254. {
  255. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  256. {
  257. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  258. }
  259. }
  260. internal static void EnableControlPanel()
  261. {
  262. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  263. {
  264. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  265. }
  266. }
  267. internal static void EnableFolderOptions()
  268. {
  269. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  270. {
  271. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  272. }
  273. }
  274. internal static void EnableRunDialog()
  275. {
  276. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  277. {
  278. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  279. }
  280. }
  281. internal static void EnableContextMenu()
  282. {
  283. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  284. {
  285. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  286. }
  287. }
  288. internal static void EnableTaskManager()
  289. {
  290. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  291. {
  292. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  293. }
  294. }
  295. internal static void EnableRegistryEditor()
  296. {
  297. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  298. {
  299. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  300. }
  301. }
  302. internal static void RunCommand(string command)
  303. {
  304. if (string.IsNullOrEmpty(command)) return;
  305. using (Process p = new Process())
  306. {
  307. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  308. p.StartInfo.FileName = "cmd.exe";
  309. p.StartInfo.Arguments = "/C " + command;
  310. p.StartInfo.CreateNoWindow = true;
  311. try
  312. {
  313. p.Start();
  314. p.WaitForExit();
  315. p.Close();
  316. }
  317. catch (Exception ex)
  318. {
  319. Logger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  320. }
  321. }
  322. }
  323. internal static void FindFile(string fileName)
  324. {
  325. if (File.Exists(fileName)) Process.Start("explorer.exe", $"/select, \"{fileName}\"");
  326. }
  327. internal static void FindFolder(string folder)
  328. {
  329. if (Directory.Exists(folder)) RunCommand($"explorer.exe \"{folder}\"");
  330. }
  331. internal static string GetShortcutTargetFile(string shortcutFilename)
  332. {
  333. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  334. string filenameOnly = Path.GetFileName(shortcutFilename);
  335. Shell32.Shell shell = new Shell32.Shell();
  336. Shell32.Folder folder = shell.NameSpace(pathOnly);
  337. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  338. if (folderItem != null)
  339. {
  340. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  341. return link.Path;
  342. }
  343. return string.Empty;
  344. }
  345. internal static void RestartExplorer()
  346. {
  347. const string explorer = "explorer.exe";
  348. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  349. foreach (Process process in Process.GetProcesses())
  350. {
  351. try
  352. {
  353. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  354. {
  355. process.Kill();
  356. }
  357. }
  358. catch (Exception ex)
  359. {
  360. Logger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  361. }
  362. }
  363. Thread.Sleep(TimeSpan.FromSeconds(1));
  364. Process.Start(explorer);
  365. }
  366. internal static void FindKeyInRegistry(string key)
  367. {
  368. try
  369. {
  370. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  371. Process.Start("regedit");
  372. }
  373. catch (Exception ex)
  374. {
  375. Logger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  376. }
  377. }
  378. internal static void Repair(bool withoutRestart = false)
  379. {
  380. try
  381. {
  382. Directory.Delete(CoreHelper.CoreFolder, true);
  383. }
  384. catch (Exception ex)
  385. {
  386. Logger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  387. }
  388. finally
  389. {
  390. if (!withoutRestart)
  391. {
  392. // BYPASS SINGLE-INSTANCE MECHANISM
  393. if (Program.MUTEX != null)
  394. {
  395. Program.MUTEX.ReleaseMutex();
  396. Program.MUTEX.Dispose();
  397. Program.MUTEX = null;
  398. }
  399. Application.Restart();
  400. }
  401. }
  402. }
  403. internal static Task RunAsync(this Process process)
  404. {
  405. var tcs = new TaskCompletionSource<object>();
  406. process.EnableRaisingEvents = true;
  407. process.Exited += (s, e) => tcs.TrySetResult(null);
  408. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  409. return tcs.Task;
  410. }
  411. internal static string SanitizeFileFolderName(string fileName)
  412. {
  413. char[] invalids = Path.GetInvalidFileNameChars();
  414. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  415. }
  416. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  417. internal static void EnableGPEDitor()
  418. {
  419. Utilities.RunBatchFile(CoreHelper.ScriptsFolder + "GPEditEnablerInHome.bat");
  420. }
  421. internal static void TryDeleteRegistryValue(bool localMachine, string path, string valueName)
  422. {
  423. try
  424. {
  425. if (localMachine) Registry.LocalMachine.OpenSubKey(path, true).DeleteValue(valueName, false);
  426. if (!localMachine) Registry.CurrentUser.OpenSubKey(path, true).DeleteValue(valueName, false);
  427. }
  428. catch { }
  429. }
  430. internal static void TryDeleteRegistryValueDefaultUsers(string path, string valueName)
  431. {
  432. try
  433. {
  434. Registry.Users.OpenSubKey(path, true).DeleteValue(valueName, false);
  435. }
  436. catch { }
  437. }
  438. internal static void DisableProtectedService(string serviceName)
  439. {
  440. using (TokenPrivilegeHelper.TakeOwnership)
  441. {
  442. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  443. {
  444. allServicesKey.GrantFullControlOnSubKey(serviceName);
  445. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  446. {
  447. if (serviceKey == null) return;
  448. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  449. {
  450. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  451. serviceKey.GrantFullControlOnSubKey(subkeyName);
  452. }
  453. serviceKey.SetValue("Start", "4", RegistryValueKind.DWord);
  454. }
  455. }
  456. }
  457. }
  458. // old and untested method
  459. //internal static void RestoreWindowsPhotoViewer()
  460. //{
  461. // const string PHOTO_VIEWER_SHELL_COMMAND =
  462. // @"%SystemRoot%\System32\rundll32.exe ""%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll"", ImageView_Fullscreen %1";
  463. // const string PHOTO_VIEWER_CLSID = "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}";
  464. // Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open", "MuiVerb", "@photoviewer.dll,-3043");
  465. // Registry.SetValue(
  466. // @"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\command", valueName: null,
  467. // PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  468. // );
  469. // Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  470. // string[] imageTypes = { "Paint.Picture", "giffile", "jpegfile", "pngfile" };
  471. // foreach (string type in imageTypes)
  472. // {
  473. // Registry.SetValue(
  474. // $@"HKEY_CLASSES_ROOT\{type}\shell\open\command", valueName: null,
  475. // PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  476. // );
  477. // Registry.SetValue($@"HKEY_CLASSES_ROOT\{type}\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  478. // }
  479. //}
  480. internal static void EnableProtectedService(string serviceName)
  481. {
  482. using (TokenPrivilegeHelper.TakeOwnership)
  483. {
  484. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  485. {
  486. allServicesKey.GrantFullControlOnSubKey(serviceName);
  487. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  488. {
  489. if (serviceKey == null) return;
  490. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  491. {
  492. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  493. serviceKey.GrantFullControlOnSubKey(subkeyName);
  494. }
  495. serviceKey.SetValue("Start", "2", RegistryValueKind.DWord);
  496. }
  497. }
  498. }
  499. }
  500. public static RegistryKey OpenSubKeyWritable(this RegistryKey registryKey, string subkeyName, RegistryRights? rights = null)
  501. {
  502. RegistryKey subKey;
  503. if (rights == null)
  504. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
  505. else
  506. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, rights.Value);
  507. if (subKey == null)
  508. {
  509. Logger.LogError("Utilities.OpenSubKeyWritable", $"Subkey {subkeyName} not found.", "-");
  510. }
  511. return subKey;
  512. }
  513. internal static SecurityIdentifier RetrieveCurrentUserIdentifier()
  514. => WindowsIdentity.GetCurrent().User ?? throw new Exception("Unable to retrieve current user SID.");
  515. internal static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName)
  516. {
  517. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName,
  518. RegistryRights.TakeOwnership | RegistryRights.ChangePermissions
  519. ))
  520. {
  521. RegistrySecurity accessRules = subKey.GetAccessControl();
  522. SecurityIdentifier currentUser = RetrieveCurrentUserIdentifier();
  523. accessRules.SetOwner(currentUser);
  524. accessRules.ResetAccessRule(
  525. new RegistryAccessRule(
  526. currentUser,
  527. RegistryRights.FullControl,
  528. InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  529. PropagationFlags.None,
  530. AccessControlType.Allow
  531. )
  532. );
  533. subKey.SetAccessControl(accessRules);
  534. }
  535. }
  536. internal static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
  537. {
  538. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership))
  539. {
  540. RegistrySecurity accessRules = subKey.GetAccessControl();
  541. accessRules.SetOwner(RetrieveCurrentUserIdentifier());
  542. subKey.SetAccessControl(accessRules);
  543. }
  544. }
  545. internal static string GetNETFramework()
  546. {
  547. string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
  548. int netRelease;
  549. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
  550. {
  551. if (ndpKey != null && ndpKey.GetValue("Release") != null)
  552. {
  553. netRelease = (int)ndpKey.GetValue("Release");
  554. }
  555. else
  556. {
  557. return "4.0";
  558. }
  559. }
  560. if (netRelease >= 528040)
  561. return "4.8";
  562. if (netRelease >= 461808)
  563. return "4.7.2";
  564. if (netRelease >= 461308)
  565. return "4.7.1";
  566. if (netRelease >= 460798)
  567. return "4.7";
  568. if (netRelease >= 394802)
  569. return "4.6.2";
  570. if (netRelease >= 394254)
  571. return "4.6.1";
  572. if (netRelease >= 393295)
  573. return "4.6";
  574. if (netRelease >= 379893)
  575. return "4.5.2";
  576. if (netRelease >= 378675)
  577. return "4.5.1";
  578. if (netRelease >= 378389)
  579. return "4.5";
  580. return "4.0";
  581. }
  582. internal static void SearchWith(string term, bool ddg)
  583. {
  584. try
  585. {
  586. if (ddg) Process.Start(string.Format("https://duckduckgo.com/?q={0}", term));
  587. if (!ddg) Process.Start(string.Format("https://www.google.com/search?q={0}", term));
  588. }
  589. catch { }
  590. }
  591. internal static void EnableLoginVerbose()
  592. {
  593. try
  594. {
  595. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "verbosestatus", 1, RegistryValueKind.DWord);
  596. }
  597. catch (Exception ex)
  598. {
  599. Logger.LogError("Utilities.EnableLoginVerbose", ex.Message, ex.StackTrace);
  600. }
  601. }
  602. internal static void DisableLoginVerbose()
  603. {
  604. Utilities.TryDeleteRegistryValue(true, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "verbosestatus");
  605. }
  606. // [!!!]
  607. internal static void UnlockAllCores()
  608. {
  609. try
  610. {
  611. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", "ValueMax", 0, RegistryValueKind.DWord);
  612. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", "ValueMin", 0, RegistryValueKind.DWord);
  613. }
  614. catch (Exception ex)
  615. {
  616. Logger.LogError("Utilities.UnlockAllCores", ex.Message, ex.StackTrace);
  617. }
  618. }
  619. // value = RAM in GB * 1024 * 1024
  620. internal static void DisableSvcHostProcessSplitting(int ramInGb)
  621. {
  622. try
  623. {
  624. ramInGb = ramInGb * 1024 * 1024;
  625. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB", ramInGb, RegistryValueKind.DWord);
  626. }
  627. catch (Exception ex)
  628. {
  629. Logger.LogError("Utilities.DisableSvcHostProcessSplitting", ex.Message, ex.StackTrace);
  630. }
  631. }
  632. // reset the value to default
  633. internal static void EnableSvcHostProcessSplitting()
  634. {
  635. try
  636. {
  637. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB", 380000, RegistryValueKind.DWord);
  638. }
  639. catch (Exception ex)
  640. {
  641. Logger.LogError("Utilities.EnableSvcHostProcessSplitting", ex.Message, ex.StackTrace);
  642. }
  643. }
  644. internal static void DisableHPET()
  645. {
  646. Utilities.RunCommand("bcdedit /deletevalue useplatformclock");
  647. Thread.Sleep(500);
  648. Utilities.RunCommand("bcdedit /set disabledynamictick yes");
  649. }
  650. internal static void EnableHPET()
  651. {
  652. Utilities.RunCommand("bcdedit /set useplatformclock true");
  653. Thread.Sleep(500);
  654. Utilities.RunCommand("bcdedit /set disabledynamictick no");
  655. }
  656. internal static void RegisterAutoStart()
  657. {
  658. try
  659. {
  660. using (RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  661. {
  662. k.SetValue("Optimizer", Assembly.GetEntryAssembly().Location);
  663. }
  664. }
  665. catch (Exception ex)
  666. {
  667. Logger.LogError("Utilities.AddToStartup", ex.Message, ex.StackTrace);
  668. }
  669. }
  670. internal static void UnregisterAutoStart()
  671. {
  672. try
  673. {
  674. using (RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  675. {
  676. k.DeleteValue("Optimizer", false);
  677. }
  678. }
  679. catch (Exception ex)
  680. {
  681. Logger.LogError("Utilities.DeleteFromStartup", ex.Message, ex.StackTrace);
  682. }
  683. }
  684. internal static void AllowProcessToRun(string pName)
  685. {
  686. try
  687. {
  688. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryRights.FullControl))
  689. {
  690. if (ifeo == null) return;
  691. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  692. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options", RegistryRights.FullControl))
  693. {
  694. if (k == null) return;
  695. k.GrantFullControlOnSubKey(pName);
  696. k.DeleteSubKey(pName);
  697. }
  698. }
  699. }
  700. catch (Exception ex)
  701. {
  702. Logger.LogError("Utilities.AllowProcessToRun", ex.Message, ex.StackTrace);
  703. }
  704. }
  705. internal static void PreventProcessFromRunning(string pName)
  706. {
  707. try
  708. {
  709. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryRights.FullControl))
  710. {
  711. if (ifeo == null) return;
  712. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  713. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options", RegistryRights.FullControl))
  714. {
  715. if (k == null) return;
  716. k.CreateSubKey(pName);
  717. k.GrantFullControlOnSubKey(pName);
  718. using (RegistryKey f = k.OpenSubKeyWritable(pName, RegistryRights.FullControl))
  719. {
  720. if (f == null) return;
  721. f.SetValue("Debugger", @"%windir%\System32\taskkill.exe");
  722. }
  723. }
  724. }
  725. }
  726. catch (Exception ex)
  727. {
  728. Logger.LogError("Utilities.PreventProcessFromRunning", ex.Message, ex.StackTrace);
  729. }
  730. }
  731. internal static string GetUserDownloadsFolder()
  732. {
  733. try
  734. {
  735. return Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "{374DE290-123F-4565-9164-39C4925E467B}", string.Empty).ToString();
  736. }
  737. catch (Exception ex)
  738. {
  739. Logger.LogError("Utilities.GetUserDownloadsFolder", ex.Message, ex.StackTrace);
  740. return string.Empty;
  741. }
  742. }
  743. internal static void ReinforceCurrentTweaks()
  744. {
  745. SilentConfig silentConfig = new SilentConfig();
  746. Tweaks silentConfigTweaks = new Tweaks();
  747. silentConfig.Tweaks = silentConfigTweaks;
  748. #region Windows General
  749. silentConfig.Tweaks.EnablePerformanceTweaks = OptionsHelper.CurrentOptions.EnablePerformanceTweaks ? true : (bool?)null;
  750. silentConfig.Tweaks.EnableUtcTime = OptionsHelper.CurrentOptions.EnableUtcTime ? true : (bool?)null;
  751. silentConfig.Tweaks.ShowAllTrayIcons = OptionsHelper.CurrentOptions.ShowAllTrayIcons ? true : (bool?)null;
  752. silentConfig.Tweaks.RemoveMenusDelay = OptionsHelper.CurrentOptions.RemoveMenusDelay ? true : (bool?)null;
  753. silentConfig.Tweaks.DisableNetworkThrottling = OptionsHelper.CurrentOptions.DisableNetworkThrottling ? true : (bool?)null;
  754. silentConfig.Tweaks.DisableWindowsDefender = OptionsHelper.CurrentOptions.DisableWindowsDefender ? true : (bool?)null;
  755. silentConfig.Tweaks.DisableSystemRestore = OptionsHelper.CurrentOptions.DisableSystemRestore ? true : (bool?)null;
  756. silentConfig.Tweaks.DisablePrintService = OptionsHelper.CurrentOptions.DisablePrintService ? true : (bool?)null;
  757. silentConfig.Tweaks.DisableMediaPlayerSharing = OptionsHelper.CurrentOptions.DisableMediaPlayerSharing ? true : (bool?)null;
  758. silentConfig.Tweaks.DisableErrorReporting = OptionsHelper.CurrentOptions.DisableErrorReporting ? true : (bool?)null;
  759. silentConfig.Tweaks.DisableHomeGroup = OptionsHelper.CurrentOptions.DisableHomeGroup ? true : (bool?)null;
  760. silentConfig.Tweaks.DisableSuperfetch = OptionsHelper.CurrentOptions.DisableSuperfetch ? true : (bool?)null;
  761. silentConfig.Tweaks.DisableTelemetryTasks = OptionsHelper.CurrentOptions.DisableTelemetryTasks ? true : (bool?)null;
  762. silentConfig.Tweaks.DisableOffice2016Telemetry = OptionsHelper.CurrentOptions.DisableOffice2016Telemetry ? true : (bool?)null;
  763. silentConfig.Tweaks.DisableCompatibilityAssistant = OptionsHelper.CurrentOptions.DisableCompatibilityAssistant ? true : (bool?)null;
  764. silentConfig.Tweaks.DisableHibernation = OptionsHelper.CurrentOptions.DisableHibernation ? true : (bool?)null;
  765. silentConfig.Tweaks.DisableSMB1 = OptionsHelper.CurrentOptions.DisableSMB1 ? true : (bool?)null;
  766. silentConfig.Tweaks.DisableSMB2 = OptionsHelper.CurrentOptions.DisableSMB2 ? true : (bool?)null;
  767. silentConfig.Tweaks.DisableNTFSTimeStamp = OptionsHelper.CurrentOptions.DisableNTFSTimeStamp ? true : (bool?)null;
  768. silentConfig.Tweaks.DisableFaxService = OptionsHelper.CurrentOptions.DisableFaxService ? true : (bool?)null;
  769. silentConfig.Tweaks.DisableSmartScreen = OptionsHelper.CurrentOptions.DisableSmartScreen ? true : (bool?)null;
  770. silentConfig.Tweaks.DisableStickyKeys = OptionsHelper.CurrentOptions.DisableStickyKeys ? true : (bool?)null;
  771. silentConfig.Tweaks.DisableVisualStudioTelemetry = OptionsHelper.CurrentOptions.DisableVisualStudioTelemetry ? true : (bool?)null;
  772. silentConfig.Tweaks.DisableFirefoxTemeletry = OptionsHelper.CurrentOptions.DisableFirefoxTemeletry ? true : (bool?)null;
  773. silentConfig.Tweaks.DisableChromeTelemetry = OptionsHelper.CurrentOptions.DisableChromeTelemetry ? true : (bool?)null;
  774. silentConfig.Tweaks.DisableNVIDIATelemetry = OptionsHelper.CurrentOptions.DisableNVIDIATelemetry ? true : (bool?)null;
  775. silentConfig.Tweaks.DisableSearch = OptionsHelper.CurrentOptions.DisableSearch ? true : (bool?)null;
  776. #endregion
  777. #region Windows 8.1
  778. silentConfig.Tweaks.DisableOneDrive = OptionsHelper.CurrentOptions.DisableOneDrive ? true : (bool?)null;
  779. #endregion
  780. #region Windows 10
  781. silentConfig.Tweaks.DisableCloudClipboard = OptionsHelper.CurrentOptions.DisableCloudClipboard ? true : (bool?)null;
  782. silentConfig.Tweaks.EnableLegacyVolumeSlider = OptionsHelper.CurrentOptions.EnableLegacyVolumeSlider ? true : (bool?)null;
  783. silentConfig.Tweaks.DisableQuickAccessHistory = OptionsHelper.CurrentOptions.DisableQuickAccessHistory ? true : (bool?)null;
  784. silentConfig.Tweaks.DisableStartMenuAds = OptionsHelper.CurrentOptions.DisableStartMenuAds ? true : (bool?)null;
  785. silentConfig.Tweaks.UninstallOneDrive = OptionsHelper.CurrentOptions.UninstallOneDrive ? true : (bool?)null;
  786. silentConfig.Tweaks.DisableMyPeople = OptionsHelper.CurrentOptions.DisableMyPeople ? true : (bool?)null;
  787. silentConfig.Tweaks.DisableAutomaticUpdates = OptionsHelper.CurrentOptions.DisableAutomaticUpdates ? true : (bool?)null;
  788. silentConfig.Tweaks.ExcludeDrivers = OptionsHelper.CurrentOptions.ExcludeDrivers ? true : (bool?)null;
  789. silentConfig.Tweaks.DisableTelemetryServices = OptionsHelper.CurrentOptions.DisableTelemetryServices ? true : (bool?)null;
  790. silentConfig.Tweaks.DisablePrivacyOptions = OptionsHelper.CurrentOptions.DisablePrivacyOptions ? true : (bool?)null;
  791. silentConfig.Tweaks.DisableCortana = OptionsHelper.CurrentOptions.DisableCortana ? true : (bool?)null;
  792. silentConfig.Tweaks.DisableSensorServices = OptionsHelper.CurrentOptions.DisableSensorServices ? true : (bool?)null;
  793. silentConfig.Tweaks.DisableWindowsInk = OptionsHelper.CurrentOptions.DisableWindowsInk ? true : (bool?)null;
  794. silentConfig.Tweaks.DisableSpellingTyping = OptionsHelper.CurrentOptions.DisableSpellingTyping ? true : (bool?)null;
  795. silentConfig.Tweaks.DisableXboxLive = OptionsHelper.CurrentOptions.DisableXboxLive ? true : (bool?)null;
  796. silentConfig.Tweaks.DisableGameBar = OptionsHelper.CurrentOptions.DisableGameBar ? true : (bool?)null;
  797. silentConfig.Tweaks.DisableInsiderService = OptionsHelper.CurrentOptions.DisableInsiderService ? true : (bool?)null;
  798. silentConfig.Tweaks.DisableStoreUpdates = OptionsHelper.CurrentOptions.DisableStoreUpdates ? true : (bool?)null;
  799. silentConfig.Tweaks.EnableLongPaths = OptionsHelper.CurrentOptions.EnableLongPaths ? true : (bool?)null;
  800. silentConfig.Tweaks.RemoveCastToDevice = OptionsHelper.CurrentOptions.RemoveCastToDevice ? true : (bool?)null;
  801. silentConfig.Tweaks.EnableGamingMode = OptionsHelper.CurrentOptions.EnableGamingMode ? true : (bool?)null;
  802. silentConfig.Tweaks.DisableTPMCheck = OptionsHelper.CurrentOptions.DisableTPMCheck ? true : (bool?)null;
  803. silentConfig.Tweaks.DisableVirtualizationBasedTechnology = OptionsHelper.CurrentOptions.DisableVBS ? true : (bool?)null;
  804. silentConfig.Tweaks.DisableEdgeDiscoverBar = OptionsHelper.CurrentOptions.DisableEdgeDiscoverBar ? true : (bool?)null;
  805. silentConfig.Tweaks.DisableEdgeTelemetry = OptionsHelper.CurrentOptions.DisableEdgeTelemetry ? true : (bool?)null;
  806. silentConfig.Tweaks.RestoreClassicPhotoViewer = OptionsHelper.CurrentOptions.RestoreClassicPhotoViewer ? true : (bool?)null;
  807. silentConfig.Tweaks.DisableNewsInterests = OptionsHelper.CurrentOptions.DisableNewsInterests ? true : (bool?)null;
  808. silentConfig.Tweaks.HideTaskbarSearch = OptionsHelper.CurrentOptions.HideTaskbarSearch ? true : (bool?)null;
  809. silentConfig.Tweaks.HideTaskbarWeather = OptionsHelper.CurrentOptions.HideTaskbarWeather ? true : (bool?)null;
  810. silentConfig.Tweaks.DisableModernStandby = OptionsHelper.CurrentOptions.DisableModernStandby ? true : (bool?)null;
  811. #endregion
  812. #region Windows 11
  813. silentConfig.Tweaks.TaskbarToLeft = OptionsHelper.CurrentOptions.TaskbarToLeft ? true : (bool?)null;
  814. silentConfig.Tweaks.DisableStickers = OptionsHelper.CurrentOptions.DisableStickers ? true : (bool?)null;
  815. silentConfig.Tweaks.CompactMode = OptionsHelper.CurrentOptions.CompactMode ? true : (bool?)null;
  816. silentConfig.Tweaks.DisableSnapAssist = OptionsHelper.CurrentOptions.DisableSnapAssist ? true : (bool?)null;
  817. silentConfig.Tweaks.DisableWidgets = OptionsHelper.CurrentOptions.DisableWidgets ? true : (bool?)null;
  818. silentConfig.Tweaks.DisableChat = OptionsHelper.CurrentOptions.DisableChat ? true : (bool?)null;
  819. silentConfig.Tweaks.ClassicMenu = OptionsHelper.CurrentOptions.ClassicMenu ? true : (bool?)null;
  820. silentConfig.Tweaks.DisableCoPilotAI = OptionsHelper.CurrentOptions.DisableCoPilotAI ? true : (bool?)null;
  821. #endregion
  822. SilentOps.CurrentSilentConfig = silentConfig;
  823. if (CurrentWindowsVersion == WindowsVersion.Windows7)
  824. {
  825. SilentOps.ProcessTweaksGeneral();
  826. }
  827. if (CurrentWindowsVersion == WindowsVersion.Windows8)
  828. {
  829. SilentOps.ProcessTweaksGeneral();
  830. SilentOps.ProcessTweaksWindows8();
  831. }
  832. if (CurrentWindowsVersion == WindowsVersion.Windows10)
  833. {
  834. SilentOps.ProcessTweaksGeneral();
  835. SilentOps.ProcessTweaksWindows10();
  836. }
  837. if (CurrentWindowsVersion == WindowsVersion.Windows11)
  838. {
  839. SilentOps.ProcessTweaksGeneral();
  840. SilentOps.ProcessTweaksWindows10();
  841. SilentOps.ProcessTweaksWindows11();
  842. }
  843. }
  844. }
  845. }