2
0

Utilities.cs 37 KB

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