Utilities.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. using Microsoft.Win32;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Security.AccessControl;
  11. using System.Security.Principal;
  12. using System.ServiceProcess;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using System.Windows.Forms;
  17. namespace Optimizer
  18. {
  19. internal static class Utilities
  20. {
  21. // DEPRECATED
  22. //internal readonly static string DefaultEdgeDownloadFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
  23. internal static WindowsVersion CurrentWindowsVersion = WindowsVersion.Unsupported;
  24. static string productName = string.Empty;
  25. static string buildNumber = string.Empty;
  26. internal delegate void SetControlPropertyThreadSafeDelegate(Control control, string propertyName, object propertyValue);
  27. internal static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
  28. {
  29. if (control.InvokeRequired)
  30. {
  31. control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
  32. }
  33. else
  34. {
  35. control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
  36. }
  37. }
  38. internal static IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
  39. {
  40. List<Control> controls = new List<Control>();
  41. foreach (Control child in parent.Controls)
  42. {
  43. controls.AddRange(GetSelfAndChildrenRecursive(child));
  44. }
  45. controls.Add(parent);
  46. return controls;
  47. }
  48. internal static Color ToGrayScale(this Color originalColor)
  49. {
  50. if (originalColor.Equals(Color.Transparent))
  51. return originalColor;
  52. int grayScale = (int)((originalColor.R * .299) + (originalColor.G * .587) + (originalColor.B * .114));
  53. return Color.FromArgb(grayScale, grayScale, grayScale);
  54. }
  55. internal static string GetWindowsDetails()
  56. {
  57. string bitness = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";
  58. if (CurrentWindowsVersion == WindowsVersion.Windows10 || CurrentWindowsVersion == WindowsVersion.Windows11)
  59. {
  60. return string.Format("{0} - {1} ({2})", GetOS(), GetWindows10Build(), bitness);
  61. }
  62. else
  63. {
  64. return string.Format("{0} - ({1})", GetOS(), bitness);
  65. }
  66. }
  67. internal static string GetWindows10Build()
  68. {
  69. return (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "DisplayVersion", "");
  70. }
  71. internal static string GetOS()
  72. {
  73. productName = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", "");
  74. if (productName.Contains("Windows 7"))
  75. {
  76. CurrentWindowsVersion = WindowsVersion.Windows7;
  77. }
  78. if ((productName.Contains("Windows 8")) || (productName.Contains("Windows 8.1")))
  79. {
  80. CurrentWindowsVersion = WindowsVersion.Windows8;
  81. }
  82. if (productName.Contains("Windows 10"))
  83. {
  84. buildNumber = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "CurrentBuild", "");
  85. if (Convert.ToInt32(buildNumber) >= 22000)
  86. {
  87. productName = productName.Replace("Windows 10", "Windows 11");
  88. CurrentWindowsVersion = WindowsVersion.Windows11;
  89. }
  90. else
  91. {
  92. CurrentWindowsVersion = WindowsVersion.Windows10;
  93. }
  94. }
  95. if (Program.UNSAFE_MODE)
  96. {
  97. if (productName.Contains("Windows Server 2008"))
  98. {
  99. CurrentWindowsVersion = WindowsVersion.Windows7;
  100. }
  101. if (productName.Contains("Windows Server 2012"))
  102. {
  103. CurrentWindowsVersion = WindowsVersion.Windows8;
  104. }
  105. if (productName.Contains("Windows Server 2016") || productName.Contains("Windows Server 2019") || productName.Contains("Windows Server 2022"))
  106. {
  107. CurrentWindowsVersion = WindowsVersion.Windows10;
  108. }
  109. }
  110. return productName;
  111. }
  112. internal static string GetBitness()
  113. {
  114. string bitness;
  115. if (Environment.Is64BitOperatingSystem)
  116. {
  117. bitness = "You are working with 64-bit";
  118. }
  119. else
  120. {
  121. bitness = "You are working with 32-bit";
  122. }
  123. return bitness;
  124. }
  125. internal static bool IsAdmin()
  126. {
  127. return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
  128. }
  129. internal static bool IsCompatible()
  130. {
  131. bool legit;
  132. string os = GetOS();
  133. if ((os.Contains("XP")) || (os.Contains("Vista")) || os.Contains("Server 2003"))
  134. {
  135. legit = false;
  136. }
  137. else
  138. {
  139. legit = true;
  140. }
  141. return legit;
  142. }
  143. // DEPRECATED
  144. //internal static string GetEdgeDownloadFolder()
  145. //{
  146. // string current = string.Empty;
  147. // try
  148. // {
  149. // current = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", DefaultEdgeDownloadFolder).ToString();
  150. // }
  151. // catch (Exception ex)
  152. // {
  153. // current = DefaultEdgeDownloadFolder;
  154. // ErrorLogger.LogError("Utilities.GetEdgeDownloadFolder", ex.Message, ex.StackTrace);
  155. // }
  156. // return current;
  157. //}
  158. // DEPRECATED
  159. //internal static void SetEdgeDownloadFolder(string path)
  160. //{
  161. // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", path, RegistryValueKind.String);
  162. //}
  163. internal static void RunBatchFile(string batchFile)
  164. {
  165. try
  166. {
  167. using (Process p = new Process())
  168. {
  169. p.StartInfo.CreateNoWindow = true;
  170. p.StartInfo.FileName = batchFile;
  171. p.StartInfo.UseShellExecute = false;
  172. p.Start();
  173. p.WaitForExit();
  174. p.Close();
  175. }
  176. }
  177. catch (Exception ex)
  178. {
  179. Logger.LogError("Utilities.RunBatchFile", ex.Message, ex.StackTrace);
  180. }
  181. }
  182. internal static void ImportRegistryScript(string scriptFile)
  183. {
  184. string path = "\"" + scriptFile + "\"";
  185. Process p = new Process();
  186. try
  187. {
  188. p.StartInfo.FileName = "regedit.exe";
  189. p.StartInfo.UseShellExecute = false;
  190. p = Process.Start("regedit.exe", "/s " + path);
  191. p.WaitForExit();
  192. }
  193. catch (Exception ex)
  194. {
  195. p.Dispose();
  196. Logger.LogError("Utilities.ImportRegistryScript", ex.Message, ex.StackTrace);
  197. }
  198. finally
  199. {
  200. p.Dispose();
  201. }
  202. }
  203. internal static void Reboot()
  204. {
  205. Options.SaveSettings();
  206. Process.Start("shutdown.exe", "/r /t 0");
  207. }
  208. internal static void DisableHibernation()
  209. {
  210. Utilities.RunCommand("powercfg -h off");
  211. Utilities.RunCommand("powercfg -h off");
  212. }
  213. internal static void EnableHibernation()
  214. {
  215. Utilities.RunCommand("powercfg -h on");
  216. Utilities.RunCommand("powercfg -h on");
  217. }
  218. internal static void ActivateMainForm()
  219. {
  220. Program._MainForm.Activate();
  221. }
  222. internal static bool ServiceExists(string serviceName)
  223. {
  224. return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName));
  225. }
  226. internal static void StopService(string serviceName)
  227. {
  228. if (ServiceExists(serviceName))
  229. {
  230. ServiceController sc = new ServiceController(serviceName);
  231. if (sc.CanStop)
  232. {
  233. sc.Stop();
  234. }
  235. }
  236. }
  237. internal static void StartService(string serviceName)
  238. {
  239. if (ServiceExists(serviceName))
  240. {
  241. ServiceController sc = new ServiceController(serviceName);
  242. try
  243. {
  244. sc.Start();
  245. }
  246. catch (Exception ex)
  247. {
  248. Logger.LogError("Utilities.StartService", ex.Message, ex.StackTrace);
  249. }
  250. }
  251. }
  252. internal static void EnableFirewall()
  253. {
  254. RunCommand("netsh advfirewall set currentprofile state on");
  255. }
  256. internal static void EnableCommandPrompt()
  257. {
  258. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  259. {
  260. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  261. }
  262. }
  263. internal static void EnableControlPanel()
  264. {
  265. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  266. {
  267. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  268. }
  269. }
  270. internal static void EnableFolderOptions()
  271. {
  272. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  273. {
  274. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  275. }
  276. }
  277. internal static void EnableRunDialog()
  278. {
  279. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  280. {
  281. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  282. }
  283. }
  284. internal static void EnableContextMenu()
  285. {
  286. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  287. {
  288. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  289. }
  290. }
  291. internal static void EnableTaskManager()
  292. {
  293. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  294. {
  295. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  296. }
  297. }
  298. internal static void EnableRegistryEditor()
  299. {
  300. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  301. {
  302. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  303. }
  304. }
  305. internal static void RunCommand(string command)
  306. {
  307. using (Process p = new Process())
  308. {
  309. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  310. p.StartInfo.FileName = "cmd.exe";
  311. p.StartInfo.Arguments = "/C " + command;
  312. p.StartInfo.CreateNoWindow = true;
  313. try
  314. {
  315. p.Start();
  316. p.WaitForExit();
  317. p.Close();
  318. }
  319. catch (Exception ex)
  320. {
  321. Logger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  322. }
  323. }
  324. }
  325. internal static void FindFile(string fileName)
  326. {
  327. if (File.Exists(fileName)) Process.Start("explorer.exe", $"/select, \"{fileName}\"");
  328. }
  329. internal static void FindFolder(string folder)
  330. {
  331. if (Directory.Exists(folder)) RunCommand($"explorer.exe \"{folder}\"");
  332. }
  333. internal static string GetShortcutTargetFile(string shortcutFilename)
  334. {
  335. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  336. string filenameOnly = Path.GetFileName(shortcutFilename);
  337. Shell32.Shell shell = new Shell32.Shell();
  338. Shell32.Folder folder = shell.NameSpace(pathOnly);
  339. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  340. if (folderItem != null)
  341. {
  342. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  343. return link.Path;
  344. }
  345. return string.Empty;
  346. }
  347. internal static void RestartExplorer()
  348. {
  349. const string explorer = "explorer.exe";
  350. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  351. foreach (Process process in Process.GetProcesses())
  352. {
  353. try
  354. {
  355. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  356. {
  357. process.Kill();
  358. }
  359. }
  360. catch (Exception ex)
  361. {
  362. Logger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  363. }
  364. }
  365. Thread.Sleep(TimeSpan.FromSeconds(1));
  366. Process.Start(explorer);
  367. }
  368. internal static void FindKeyInRegistry(string key)
  369. {
  370. try
  371. {
  372. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  373. Process.Start("regedit");
  374. }
  375. catch (Exception ex)
  376. {
  377. Logger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  378. }
  379. }
  380. internal static void Repair(bool withoutRestart = false)
  381. {
  382. try
  383. {
  384. Directory.Delete(CoreHelper.CoreFolder, true);
  385. }
  386. catch (Exception ex)
  387. {
  388. Logger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  389. }
  390. finally
  391. {
  392. if (!withoutRestart)
  393. {
  394. // BYPASS SINGLE-INSTANCE MECHANISM
  395. if (Program.MUTEX != null)
  396. {
  397. Program.MUTEX.ReleaseMutex();
  398. Program.MUTEX.Dispose();
  399. Program.MUTEX = null;
  400. }
  401. Application.Restart();
  402. }
  403. }
  404. }
  405. internal static Task RunAsync(this Process process)
  406. {
  407. var tcs = new TaskCompletionSource<object>();
  408. process.EnableRaisingEvents = true;
  409. process.Exited += (s, e) => tcs.TrySetResult(null);
  410. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  411. return tcs.Task;
  412. }
  413. internal static string SanitizeFileFolderName(string fileName)
  414. {
  415. char[] invalids = Path.GetInvalidFileNameChars();
  416. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  417. }
  418. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  419. internal static void EnableGPEDitor()
  420. {
  421. Utilities.RunBatchFile(CoreHelper.ScriptsFolder + "GPEditEnablerInHome.bat");
  422. }
  423. internal static void TryDeleteRegistryValue(bool localMachine, string path, string valueName)
  424. {
  425. try
  426. {
  427. if (localMachine) Registry.LocalMachine.OpenSubKey(path, true).DeleteValue(valueName, false);
  428. if (!localMachine) Registry.CurrentUser.OpenSubKey(path, true).DeleteValue(valueName, false);
  429. }
  430. catch { }
  431. }
  432. internal static void TryDeleteRegistryValueDefaultUsers(string path, string valueName)
  433. {
  434. try
  435. {
  436. Registry.Users.OpenSubKey(path, true).DeleteValue(valueName, false);
  437. }
  438. catch { }
  439. }
  440. internal static void DisableProtectedService(string serviceName)
  441. {
  442. using (TokenPrivilege.TakeOwnership)
  443. {
  444. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  445. {
  446. allServicesKey.GrantFullControlOnSubKey(serviceName);
  447. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  448. {
  449. if (serviceKey == null) return;
  450. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  451. {
  452. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  453. serviceKey.GrantFullControlOnSubKey(subkeyName);
  454. }
  455. serviceKey.SetValue("Start", "4", RegistryValueKind.DWord);
  456. }
  457. }
  458. }
  459. }
  460. // old and untested method
  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. Logger.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. try
  596. {
  597. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "verbosestatus", 1, RegistryValueKind.DWord);
  598. }
  599. catch (Exception ex)
  600. {
  601. Logger.LogError("Utilities.EnableLoginVerbose", ex.Message, ex.StackTrace);
  602. }
  603. }
  604. internal static void DisableLoginVerbose()
  605. {
  606. Utilities.TryDeleteRegistryValue(true, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "verbosestatus");
  607. }
  608. // [!!!]
  609. internal static void UnlockAllCores()
  610. {
  611. try
  612. {
  613. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", "ValueMax", 0, RegistryValueKind.DWord);
  614. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", "ValueMin", 0, RegistryValueKind.DWord);
  615. }
  616. catch (Exception ex)
  617. {
  618. Logger.LogError("Utilities.UnlockAllCores", ex.Message, ex.StackTrace);
  619. }
  620. }
  621. // value = RAM in GB * 1024 * 1024
  622. internal static void DisableSvcHostProcessSplitting(int ramInGb)
  623. {
  624. try
  625. {
  626. ramInGb = ramInGb * 1024 * 1024;
  627. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB", ramInGb, RegistryValueKind.DWord);
  628. }
  629. catch (Exception ex)
  630. {
  631. Logger.LogError("Utilities.DisableSvcHostProcessSplitting", ex.Message, ex.StackTrace);
  632. }
  633. }
  634. // reset the value to default
  635. internal static void EnableSvcHostProcessSplitting()
  636. {
  637. try
  638. {
  639. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB", 380000, RegistryValueKind.DWord);
  640. }
  641. catch (Exception ex)
  642. {
  643. Logger.LogError("Utilities.EnableSvcHostProcessSplitting", ex.Message, ex.StackTrace);
  644. }
  645. }
  646. internal static void DisableHPET()
  647. {
  648. Utilities.RunCommand("bcdedit /deletevalue useplatformclock");
  649. Thread.Sleep(500);
  650. Utilities.RunCommand("bcdedit /set disabledynamictick yes");
  651. }
  652. internal static void EnableHPET()
  653. {
  654. Utilities.RunCommand("bcdedit /set useplatformclock true");
  655. Thread.Sleep(500);
  656. Utilities.RunCommand("bcdedit /set disabledynamictick no");
  657. }
  658. internal static void RegisterAutoStart()
  659. {
  660. try
  661. {
  662. using (RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  663. {
  664. k.SetValue("Optimizer", Assembly.GetEntryAssembly().Location);
  665. }
  666. }
  667. catch (Exception ex)
  668. {
  669. Logger.LogError("Utilities.AddToStartup", ex.Message, ex.StackTrace);
  670. }
  671. }
  672. internal static void UnregisterAutoStart()
  673. {
  674. try
  675. {
  676. using (RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  677. {
  678. k.DeleteValue("Optimizer", false);
  679. }
  680. }
  681. catch (Exception ex)
  682. {
  683. Logger.LogError("Utilities.DeleteFromStartup", ex.Message, ex.StackTrace);
  684. }
  685. }
  686. internal static void AllowProcessToRun(string pName)
  687. {
  688. try
  689. {
  690. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryRights.FullControl))
  691. {
  692. if (ifeo == null) return;
  693. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  694. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options", RegistryRights.FullControl))
  695. {
  696. if (k == null) return;
  697. k.GrantFullControlOnSubKey(pName);
  698. k.DeleteSubKey(pName);
  699. }
  700. }
  701. }
  702. catch (Exception ex)
  703. {
  704. Logger.LogError("Utilities.AllowProcessToRun", ex.Message, ex.StackTrace);
  705. }
  706. }
  707. internal static void PreventProcessFromRunning(string pName)
  708. {
  709. try
  710. {
  711. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryRights.FullControl))
  712. {
  713. if (ifeo == null) return;
  714. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  715. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options", RegistryRights.FullControl))
  716. {
  717. if (k == null) return;
  718. k.CreateSubKey(pName);
  719. k.GrantFullControlOnSubKey(pName);
  720. using (RegistryKey f = k.OpenSubKeyWritable(pName, RegistryRights.FullControl))
  721. {
  722. if (f == null) return;
  723. f.SetValue("Debugger", @"%windir%\System32\taskkill.exe");
  724. }
  725. }
  726. }
  727. }
  728. catch (Exception ex)
  729. {
  730. Logger.LogError("Utilities.PreventProcessFromRunning", ex.Message, ex.StackTrace);
  731. }
  732. }
  733. // for debugging purposes
  734. internal static void FindDiffInTwoJsons()
  735. {
  736. JObject file1 = JObject.Parse(Properties.Resources.EN);
  737. JObject file2 = JObject.Parse(Properties.Resources.KO);
  738. var p1 = file1.Properties().ToList();
  739. var p2 = file2.Properties().ToList();
  740. var missingProps = p1.Where(expected => p2.Where(actual => actual.Name == expected.Name).Count() == 0);
  741. StringBuilder sb = new StringBuilder();
  742. foreach (var x in missingProps)
  743. {
  744. sb.Append(x.Name + Environment.NewLine);
  745. }
  746. MessageBox.Show(sb.ToString());
  747. }
  748. }
  749. }