Utilities.cs 39 KB

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