Utilities.cs 30 KB

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