Utilities.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. ErrorLogger.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. ErrorLogger.LogError("Utilities.ImportRegistryScript", ex.Message, ex.StackTrace);
  195. }
  196. finally
  197. {
  198. p.Dispose();
  199. }
  200. }
  201. internal static void Reboot()
  202. {
  203. Options.SaveSettings();
  204. Process.Start("shutdown.exe", "/r /t 0");
  205. }
  206. internal static void DisableHibernation()
  207. {
  208. Utilities.RunCommand("powercfg -h off");
  209. Utilities.RunCommand("powercfg -h off");
  210. }
  211. internal static void EnableHibernation()
  212. {
  213. Utilities.RunCommand("powercfg -h on");
  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 ServiceController.GetServices().Any(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. ErrorLogger.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. using (Process p = new Process())
  306. {
  307. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  308. p.StartInfo.FileName = "cmd.exe";
  309. p.StartInfo.Arguments = "/C " + command;
  310. p.StartInfo.CreateNoWindow = true;
  311. try
  312. {
  313. p.Start();
  314. p.WaitForExit();
  315. p.Close();
  316. }
  317. catch (Exception ex)
  318. {
  319. ErrorLogger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  320. }
  321. }
  322. }
  323. internal static void FindFile(string fileName)
  324. {
  325. if (File.Exists(fileName)) Process.Start("explorer.exe", $"/select, \"{fileName}\"");
  326. }
  327. internal static void FindFolder(string folder)
  328. {
  329. if (Directory.Exists(folder)) RunCommand($"explorer.exe \"{folder}\"");
  330. }
  331. internal static string GetShortcutTargetFile(string shortcutFilename)
  332. {
  333. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  334. string filenameOnly = Path.GetFileName(shortcutFilename);
  335. Shell32.Shell shell = new Shell32.Shell();
  336. Shell32.Folder folder = shell.NameSpace(pathOnly);
  337. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  338. if (folderItem != null)
  339. {
  340. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  341. return link.Path;
  342. }
  343. return string.Empty;
  344. }
  345. internal static void RestartExplorer()
  346. {
  347. const string explorer = "explorer.exe";
  348. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  349. foreach (Process process in Process.GetProcesses())
  350. {
  351. try
  352. {
  353. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  354. {
  355. process.Kill();
  356. }
  357. }
  358. catch (Exception ex)
  359. {
  360. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  361. }
  362. }
  363. Thread.Sleep(TimeSpan.FromSeconds(1));
  364. Process.Start(explorer);
  365. }
  366. internal static void FindKeyInRegistry(string key)
  367. {
  368. try
  369. {
  370. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  371. Process.Start("regedit");
  372. }
  373. catch (Exception ex)
  374. {
  375. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  376. }
  377. }
  378. internal static void Repair(bool withoutRestart = false)
  379. {
  380. try
  381. {
  382. Directory.Delete(Required.CoreFolder, true);
  383. }
  384. catch (Exception ex)
  385. {
  386. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  387. }
  388. finally
  389. {
  390. if (!withoutRestart)
  391. {
  392. // BYPASS SINGLE-INSTANCE MECHANISM
  393. if (Program.MUTEX != null)
  394. {
  395. Program.MUTEX.ReleaseMutex();
  396. Program.MUTEX.Dispose();
  397. Program.MUTEX = null;
  398. }
  399. Application.Restart();
  400. }
  401. }
  402. }
  403. internal static Task RunAsync(this Process process)
  404. {
  405. var tcs = new TaskCompletionSource<object>();
  406. process.EnableRaisingEvents = true;
  407. process.Exited += (s, e) => tcs.TrySetResult(null);
  408. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  409. return tcs.Task;
  410. }
  411. internal static string SanitizeFileFolderName(string fileName)
  412. {
  413. char[] invalids = Path.GetInvalidFileNameChars();
  414. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  415. }
  416. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  417. internal static void EnableGPEDitor()
  418. {
  419. Utilities.RunBatchFile(Required.ScriptsFolder + "GPEditEnablerInHome.bat");
  420. }
  421. internal static void TryDeleteRegistryValue(bool localMachine, string path, string valueName)
  422. {
  423. try
  424. {
  425. if (localMachine) Registry.LocalMachine.OpenSubKey(path, true).DeleteValue(valueName, false);
  426. if (!localMachine) Registry.CurrentUser.OpenSubKey(path, true).DeleteValue(valueName, false);
  427. }
  428. catch { }
  429. }
  430. internal static void TryDeleteRegistryValueDefaultUsers(string path, string valueName)
  431. {
  432. try
  433. {
  434. Registry.Users.OpenSubKey(path, true).DeleteValue(valueName, false);
  435. }
  436. catch { }
  437. }
  438. internal static void DisableProtectedService(string serviceName)
  439. {
  440. using (TokenPrivilege.TakeOwnership)
  441. {
  442. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  443. {
  444. allServicesKey.GrantFullControlOnSubKey(serviceName);
  445. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  446. {
  447. if (serviceKey == null) return;
  448. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  449. {
  450. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  451. serviceKey.GrantFullControlOnSubKey(subkeyName);
  452. }
  453. serviceKey.SetValue("Start", "4", RegistryValueKind.DWord);
  454. }
  455. }
  456. }
  457. }
  458. internal static void RestoreWindowsPhotoViewer()
  459. {
  460. const string PHOTO_VIEWER_SHELL_COMMAND =
  461. @"%SystemRoot%\System32\rundll32.exe ""%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll"", ImageView_Fullscreen %1";
  462. const string PHOTO_VIEWER_CLSID = "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}";
  463. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open", "MuiVerb", "@photoviewer.dll,-3043");
  464. Registry.SetValue(
  465. @"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\command", valueName: null,
  466. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  467. );
  468. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  469. string[] imageTypes = { "Paint.Picture", "giffile", "jpegfile", "pngfile" };
  470. foreach (string type in imageTypes)
  471. {
  472. Registry.SetValue(
  473. $@"HKEY_CLASSES_ROOT\{type}\shell\open\command", valueName: null,
  474. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  475. );
  476. Registry.SetValue($@"HKEY_CLASSES_ROOT\{type}\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  477. }
  478. }
  479. internal static void EnableProtectedService(string serviceName)
  480. {
  481. using (TokenPrivilege.TakeOwnership)
  482. {
  483. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  484. {
  485. allServicesKey.GrantFullControlOnSubKey(serviceName);
  486. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  487. {
  488. if (serviceKey == null) return;
  489. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  490. {
  491. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  492. serviceKey.GrantFullControlOnSubKey(subkeyName);
  493. }
  494. serviceKey.SetValue("Start", "2", RegistryValueKind.DWord);
  495. }
  496. }
  497. }
  498. }
  499. public static RegistryKey OpenSubKeyWritable(this RegistryKey registryKey, string subkeyName, RegistryRights? rights = null)
  500. {
  501. RegistryKey subKey;
  502. if (rights == null)
  503. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
  504. else
  505. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, rights.Value);
  506. if (subKey == null)
  507. {
  508. ErrorLogger.LogError("Utilities.OpenSubKeyWritable", $"Subkey {subkeyName} not found.", "-");
  509. }
  510. return subKey;
  511. }
  512. internal static SecurityIdentifier RetrieveCurrentUserIdentifier()
  513. => WindowsIdentity.GetCurrent().User ?? throw new Exception("Unable to retrieve current user SID.");
  514. internal static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName)
  515. {
  516. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName,
  517. RegistryRights.TakeOwnership | RegistryRights.ChangePermissions
  518. ))
  519. {
  520. RegistrySecurity accessRules = subKey.GetAccessControl();
  521. SecurityIdentifier currentUser = RetrieveCurrentUserIdentifier();
  522. accessRules.SetOwner(currentUser);
  523. accessRules.ResetAccessRule(
  524. new RegistryAccessRule(
  525. currentUser,
  526. RegistryRights.FullControl,
  527. InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  528. PropagationFlags.None,
  529. AccessControlType.Allow
  530. )
  531. );
  532. subKey.SetAccessControl(accessRules);
  533. }
  534. }
  535. internal static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
  536. {
  537. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership))
  538. {
  539. RegistrySecurity accessRules = subKey.GetAccessControl();
  540. accessRules.SetOwner(RetrieveCurrentUserIdentifier());
  541. subKey.SetAccessControl(accessRules);
  542. }
  543. }
  544. internal static string GetNETFramework()
  545. {
  546. string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
  547. int netRelease;
  548. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
  549. {
  550. if (ndpKey != null && ndpKey.GetValue("Release") != null)
  551. {
  552. netRelease = (int)ndpKey.GetValue("Release");
  553. }
  554. else
  555. {
  556. return "4.0";
  557. }
  558. }
  559. if (netRelease >= 528040)
  560. return "4.8";
  561. if (netRelease >= 461808)
  562. return "4.7.2";
  563. if (netRelease >= 461308)
  564. return "4.7.1";
  565. if (netRelease >= 460798)
  566. return "4.7";
  567. if (netRelease >= 394802)
  568. return "4.6.2";
  569. if (netRelease >= 394254)
  570. return "4.6.1";
  571. if (netRelease >= 393295)
  572. return "4.6";
  573. if (netRelease >= 379893)
  574. return "4.5.2";
  575. if (netRelease >= 378675)
  576. return "4.5.1";
  577. if (netRelease >= 378389)
  578. return "4.5";
  579. return "4.0";
  580. }
  581. internal static void SearchWith(string term, bool ddg)
  582. {
  583. try
  584. {
  585. if (ddg) Process.Start(string.Format("https://duckduckgo.com/?q={0}", term));
  586. if (!ddg) Process.Start(string.Format("https://www.google.com/search?q={0}", term));
  587. }
  588. catch { }
  589. }
  590. internal static void EnableLoginVerbose()
  591. {
  592. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "verbosestatus", 1, RegistryValueKind.DWord);
  593. }
  594. internal static void DisableLoginVerbose()
  595. {
  596. Utilities.TryDeleteRegistryValue(true, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "verbosestatus");
  597. }
  598. // [!!!]
  599. internal static void UnlockAllCores()
  600. {
  601. try
  602. {
  603. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", "ValueMax", 0, RegistryValueKind.DWord);
  604. Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", "ValueMin", 0, RegistryValueKind.DWord);
  605. }
  606. catch { }
  607. }
  608. internal static void DisableHPET()
  609. {
  610. Utilities.RunCommand("bcdedit /deletevalue useplatformclock");
  611. Thread.Sleep(500);
  612. Utilities.RunCommand("bcdedit /set disabledynamictick yes");
  613. }
  614. internal static void EnableHPET()
  615. {
  616. Utilities.RunCommand("bcdedit /set useplatformclock true");
  617. Thread.Sleep(500);
  618. Utilities.RunCommand("bcdedit /set disabledynamictick no");
  619. }
  620. // [!!!]
  621. //internal static void ChangeNumberOfSvcHostByRAM(string ram)
  622. //{
  623. // try
  624. // {
  625. // float kbs = float.Parse(ram);
  626. // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control", "SvcHostSplitThresholdInKB", kbs * 1024 * 1024, RegistryValueKind.DWord);
  627. // }
  628. // catch { }
  629. //}
  630. internal static void RegisterAutoStart()
  631. {
  632. try
  633. {
  634. using (RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  635. {
  636. k.SetValue("Optimizer", Assembly.GetEntryAssembly().Location);
  637. }
  638. }
  639. catch (Exception ex)
  640. {
  641. ErrorLogger.LogError("Utilities.AddToStartup", ex.Message, ex.StackTrace);
  642. }
  643. }
  644. internal static void UnregisterAutoStart()
  645. {
  646. try
  647. {
  648. using (RegistryKey k = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  649. {
  650. k.DeleteValue("Optimizer", false);
  651. }
  652. }
  653. catch (Exception ex)
  654. {
  655. ErrorLogger.LogError("Utilities.DeleteFromStartup", ex.Message, ex.StackTrace);
  656. }
  657. }
  658. internal static void PreventProcessFromRunning(string pName)
  659. {
  660. try
  661. {
  662. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryRights.FullControl))
  663. {
  664. if (ifeo == null) return;
  665. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  666. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options", RegistryRights.FullControl))
  667. {
  668. if (k == null) return;
  669. k.CreateSubKey(pName);
  670. k.GrantFullControlOnSubKey(pName);
  671. using (RegistryKey f = k.OpenSubKeyWritable(pName, RegistryRights.FullControl))
  672. {
  673. if (f == null) return;
  674. f.SetValue("Debugger", @"%windir%\System32\taskkill.exe");
  675. }
  676. }
  677. }
  678. }
  679. catch (Exception ex)
  680. {
  681. ErrorLogger.LogError("Utilities.PreventProcessFromRunning", ex.Message, ex.StackTrace);
  682. }
  683. }
  684. }
  685. }