Utilities.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. if (string.IsNullOrEmpty(command)) return;
  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. Logger.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. Logger.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. Logger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  379. }
  380. }
  381. internal static void Repair(bool withoutRestart = false)
  382. {
  383. try
  384. {
  385. Directory.Delete(CoreHelper.CoreFolder, true);
  386. }
  387. catch (Exception ex)
  388. {
  389. Logger.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(CoreHelper.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. // old and untested method
  462. //internal static void RestoreWindowsPhotoViewer()
  463. //{
  464. // const string PHOTO_VIEWER_SHELL_COMMAND =
  465. // @"%SystemRoot%\System32\rundll32.exe ""%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll"", ImageView_Fullscreen %1";
  466. // const string PHOTO_VIEWER_CLSID = "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}";
  467. // Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open", "MuiVerb", "@photoviewer.dll,-3043");
  468. // Registry.SetValue(
  469. // @"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\command", valueName: null,
  470. // PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  471. // );
  472. // Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  473. // string[] imageTypes = { "Paint.Picture", "giffile", "jpegfile", "pngfile" };
  474. // foreach (string type in imageTypes)
  475. // {
  476. // Registry.SetValue(
  477. // $@"HKEY_CLASSES_ROOT\{type}\shell\open\command", valueName: null,
  478. // PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  479. // );
  480. // Registry.SetValue($@"HKEY_CLASSES_ROOT\{type}\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  481. // }
  482. //}
  483. internal static void EnableProtectedService(string serviceName)
  484. {
  485. using (TokenPrivilege.TakeOwnership)
  486. {
  487. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  488. {
  489. allServicesKey.GrantFullControlOnSubKey(serviceName);
  490. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  491. {
  492. if (serviceKey == null) return;
  493. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  494. {
  495. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  496. serviceKey.GrantFullControlOnSubKey(subkeyName);
  497. }
  498. serviceKey.SetValue("Start", "2", RegistryValueKind.DWord);
  499. }
  500. }
  501. }
  502. }
  503. public static RegistryKey OpenSubKeyWritable(this RegistryKey registryKey, string subkeyName, RegistryRights? rights = null)
  504. {
  505. RegistryKey subKey;
  506. if (rights == null)
  507. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
  508. else
  509. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, rights.Value);
  510. if (subKey == null)
  511. {
  512. Logger.LogError("Utilities.OpenSubKeyWritable", $"Subkey {subkeyName} not found.", "-");
  513. }
  514. return subKey;
  515. }
  516. internal static SecurityIdentifier RetrieveCurrentUserIdentifier()
  517. => WindowsIdentity.GetCurrent().User ?? throw new Exception("Unable to retrieve current user SID.");
  518. internal static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName)
  519. {
  520. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName,
  521. RegistryRights.TakeOwnership | RegistryRights.ChangePermissions
  522. ))
  523. {
  524. RegistrySecurity accessRules = subKey.GetAccessControl();
  525. SecurityIdentifier currentUser = RetrieveCurrentUserIdentifier();
  526. accessRules.SetOwner(currentUser);
  527. accessRules.ResetAccessRule(
  528. new RegistryAccessRule(
  529. currentUser,
  530. RegistryRights.FullControl,
  531. InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  532. PropagationFlags.None,
  533. AccessControlType.Allow
  534. )
  535. );
  536. subKey.SetAccessControl(accessRules);
  537. }
  538. }
  539. internal static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
  540. {
  541. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership))
  542. {
  543. RegistrySecurity accessRules = subKey.GetAccessControl();
  544. accessRules.SetOwner(RetrieveCurrentUserIdentifier());
  545. subKey.SetAccessControl(accessRules);
  546. }
  547. }
  548. internal static string GetNETFramework()
  549. {
  550. string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
  551. int netRelease;
  552. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
  553. {
  554. if (ndpKey != null && ndpKey.GetValue("Release") != null)
  555. {
  556. netRelease = (int)ndpKey.GetValue("Release");
  557. }
  558. else
  559. {
  560. return "4.0";
  561. }
  562. }
  563. if (netRelease >= 528040)
  564. return "4.8";
  565. if (netRelease >= 461808)
  566. return "4.7.2";
  567. if (netRelease >= 461308)
  568. return "4.7.1";
  569. if (netRelease >= 460798)
  570. return "4.7";
  571. if (netRelease >= 394802)
  572. return "4.6.2";
  573. if (netRelease >= 394254)
  574. return "4.6.1";
  575. if (netRelease >= 393295)
  576. return "4.6";
  577. if (netRelease >= 379893)
  578. return "4.5.2";
  579. if (netRelease >= 378675)
  580. return "4.5.1";
  581. if (netRelease >= 378389)
  582. return "4.5";
  583. return "4.0";
  584. }
  585. internal static void SearchWith(string term, bool ddg)
  586. {
  587. try
  588. {
  589. if (ddg) Process.Start(string.Format("https://duckduckgo.com/?q={0}", term));
  590. if (!ddg) Process.Start(string.Format("https://www.google.com/search?q={0}", term));
  591. }
  592. catch { }
  593. }
  594. internal static void EnableLoginVerbose()
  595. {
  596. try
  597. {
  598. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "verbosestatus", 1, RegistryValueKind.DWord);
  599. }
  600. catch (Exception ex)
  601. {
  602. Logger.LogError("Utilities.EnableLoginVerbose", ex.Message, ex.StackTrace);
  603. }
  604. }
  605. internal static void DisableLoginVerbose()
  606. {
  607. Utilities.TryDeleteRegistryValue(true, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "verbosestatus");
  608. }
  609. // [!!!]
  610. internal static void UnlockAllCores()
  611. {
  612. try
  613. {
  614. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", "ValueMax", 0, RegistryValueKind.DWord);
  615. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", "ValueMin", 0, RegistryValueKind.DWord);
  616. }
  617. catch (Exception ex)
  618. {
  619. Logger.LogError("Utilities.UnlockAllCores", ex.Message, ex.StackTrace);
  620. }
  621. }
  622. // value = RAM in GB * 1024 * 1024
  623. internal static void DisableSvcHostProcessSplitting(int ramInGb)
  624. {
  625. try
  626. {
  627. ramInGb = ramInGb * 1024 * 1024;
  628. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB", ramInGb, RegistryValueKind.DWord);
  629. }
  630. catch (Exception ex)
  631. {
  632. Logger.LogError("Utilities.DisableSvcHostProcessSplitting", ex.Message, ex.StackTrace);
  633. }
  634. }
  635. // reset the value to default
  636. internal static void EnableSvcHostProcessSplitting()
  637. {
  638. try
  639. {
  640. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB", 380000, RegistryValueKind.DWord);
  641. }
  642. catch (Exception ex)
  643. {
  644. Logger.LogError("Utilities.EnableSvcHostProcessSplitting", ex.Message, ex.StackTrace);
  645. }
  646. }
  647. internal static void DisableHPET()
  648. {
  649. Utilities.RunCommand("bcdedit /deletevalue useplatformclock");
  650. Thread.Sleep(500);
  651. Utilities.RunCommand("bcdedit /set disabledynamictick yes");
  652. }
  653. internal static void EnableHPET()
  654. {
  655. Utilities.RunCommand("bcdedit /set useplatformclock true");
  656. Thread.Sleep(500);
  657. Utilities.RunCommand("bcdedit /set disabledynamictick no");
  658. }
  659. internal static void RegisterAutoStart()
  660. {
  661. try
  662. {
  663. using (RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  664. {
  665. k.SetValue("Optimizer", Assembly.GetEntryAssembly().Location);
  666. }
  667. }
  668. catch (Exception ex)
  669. {
  670. Logger.LogError("Utilities.AddToStartup", ex.Message, ex.StackTrace);
  671. }
  672. }
  673. internal static void UnregisterAutoStart()
  674. {
  675. try
  676. {
  677. using (RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  678. {
  679. k.DeleteValue("Optimizer", false);
  680. }
  681. }
  682. catch (Exception ex)
  683. {
  684. Logger.LogError("Utilities.DeleteFromStartup", ex.Message, ex.StackTrace);
  685. }
  686. }
  687. internal static void AllowProcessToRun(string pName)
  688. {
  689. try
  690. {
  691. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryRights.FullControl))
  692. {
  693. if (ifeo == null) return;
  694. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  695. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options", RegistryRights.FullControl))
  696. {
  697. if (k == null) return;
  698. k.GrantFullControlOnSubKey(pName);
  699. k.DeleteSubKey(pName);
  700. }
  701. }
  702. }
  703. catch (Exception ex)
  704. {
  705. Logger.LogError("Utilities.AllowProcessToRun", ex.Message, ex.StackTrace);
  706. }
  707. }
  708. internal static void PreventProcessFromRunning(string pName)
  709. {
  710. try
  711. {
  712. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryRights.FullControl))
  713. {
  714. if (ifeo == null) return;
  715. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  716. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options", RegistryRights.FullControl))
  717. {
  718. if (k == null) return;
  719. k.CreateSubKey(pName);
  720. k.GrantFullControlOnSubKey(pName);
  721. using (RegistryKey f = k.OpenSubKeyWritable(pName, RegistryRights.FullControl))
  722. {
  723. if (f == null) return;
  724. f.SetValue("Debugger", @"%windir%\System32\taskkill.exe");
  725. }
  726. }
  727. }
  728. }
  729. catch (Exception ex)
  730. {
  731. Logger.LogError("Utilities.PreventProcessFromRunning", ex.Message, ex.StackTrace);
  732. }
  733. }
  734. // for debugging purposes
  735. internal static void FindDiffInTwoJsons()
  736. {
  737. JObject file1 = JObject.Parse(Properties.Resources.EN);
  738. JObject file2 = JObject.Parse(Properties.Resources.NE);
  739. var p1 = file1.Properties().ToList();
  740. var p2 = file2.Properties().ToList();
  741. var missingProps = p1.Where(expected => p2.Where(actual => actual.Name == expected.Name).Count() == 0);
  742. StringBuilder sb = new StringBuilder();
  743. foreach (var x in missingProps)
  744. {
  745. sb.Append(x.Name + Environment.NewLine);
  746. }
  747. MessageBox.Show(sb.ToString());
  748. }
  749. }
  750. }