Utilities.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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.Management.Automation;
  9. using System.Net.NetworkInformation;
  10. using System.Reflection;
  11. using System.Security.Principal;
  12. using System.ServiceProcess;
  13. using System.Threading.Tasks;
  14. using System.Windows.Forms;
  15. namespace Optimizer
  16. {
  17. internal static class Utilities
  18. {
  19. internal static readonly string LocalMachineRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  20. internal static readonly string LocalMachineRunOnce = "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  21. internal static readonly string LocalMachineRunWoW = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run";
  22. internal static readonly string LocalMachineRunOnceWow = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  23. internal static readonly string CurrentUserRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  24. internal static readonly string CurrentUserRunOnce = "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  25. internal static readonly string LocalMachineStartupFolder = CleanHelper.ProgramData + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
  26. internal static readonly string CurrentUserStartupFolder = CleanHelper.ProfileAppDataRoaming + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
  27. // DEPRECATED
  28. //internal readonly static string DefaultEdgeDownloadFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
  29. internal static WindowsVersion CurrentWindowsVersion = WindowsVersion.Unsupported;
  30. internal static Ping pinger = new Ping();
  31. internal delegate void SetControlPropertyThreadSafeDelegate(Control control, string propertyName, object propertyValue);
  32. internal static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
  33. {
  34. if (control.InvokeRequired)
  35. {
  36. control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
  37. }
  38. else
  39. {
  40. control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
  41. }
  42. }
  43. internal static IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
  44. {
  45. List<Control> controls = new List<Control>();
  46. foreach (Control child in parent.Controls)
  47. {
  48. controls.AddRange(GetSelfAndChildrenRecursive(child));
  49. }
  50. controls.Add(parent);
  51. return controls;
  52. }
  53. internal static Color ToGrayScale(this Color originalColor)
  54. {
  55. if (originalColor.Equals(Color.Transparent))
  56. return originalColor;
  57. int grayScale = (int)((originalColor.R * .299) + (originalColor.G * .587) + (originalColor.B * .114));
  58. return Color.FromArgb(grayScale, grayScale, grayScale);
  59. }
  60. internal static string GetOS()
  61. {
  62. string os = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", "");
  63. if (os.Contains("Windows 7"))
  64. {
  65. CurrentWindowsVersion = WindowsVersion.Windows7;
  66. }
  67. if ((os.Contains("Windows 8")) || (os.Contains("Windows 8.1")))
  68. {
  69. CurrentWindowsVersion = WindowsVersion.Windows8;
  70. }
  71. if (os.Contains("Windows 10"))
  72. {
  73. CurrentWindowsVersion = WindowsVersion.Windows10;
  74. }
  75. if (Program.UNSAFE_MODE)
  76. {
  77. if (os.Contains("Windows Server 2008"))
  78. {
  79. CurrentWindowsVersion = WindowsVersion.Windows7;
  80. }
  81. if (os.Contains("Windows Server 2012"))
  82. {
  83. CurrentWindowsVersion = WindowsVersion.Windows8;
  84. }
  85. if (os.Contains("Windows Server 2016") || os.Contains("Windows Server 2019"))
  86. {
  87. CurrentWindowsVersion = WindowsVersion.Windows10;
  88. }
  89. }
  90. return os;
  91. }
  92. internal static string GetBitness()
  93. {
  94. string bitness = string.Empty;
  95. if (Environment.Is64BitOperatingSystem)
  96. {
  97. bitness = "You are working with 64-bit";
  98. }
  99. else
  100. {
  101. bitness = "You are working with 32-bit";
  102. }
  103. return bitness;
  104. }
  105. internal static bool IsAdmin()
  106. {
  107. return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
  108. }
  109. internal static bool IsCompatible()
  110. {
  111. bool legit;
  112. string os = GetOS();
  113. if ((os.Contains("XP")) || (os.Contains("Vista")) || os.Contains("Server 2003"))
  114. {
  115. legit = false;
  116. }
  117. else
  118. {
  119. legit = true;
  120. }
  121. return legit;
  122. }
  123. // DEPRECATED
  124. //internal static string GetEdgeDownloadFolder()
  125. //{
  126. // string current = string.Empty;
  127. // try
  128. // {
  129. // current = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", DefaultEdgeDownloadFolder).ToString();
  130. // }
  131. // catch (Exception ex)
  132. // {
  133. // current = DefaultEdgeDownloadFolder;
  134. // ErrorLogger.LogError("Utilities.GetEdgeDownloadFolder", ex.Message, ex.StackTrace);
  135. // }
  136. // return current;
  137. //}
  138. // DEPRECATED
  139. //internal static void SetEdgeDownloadFolder(string path)
  140. //{
  141. // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", path, RegistryValueKind.String);
  142. //}
  143. internal static void RunBatchFile(string batchFile)
  144. {
  145. try
  146. {
  147. using (Process p = new Process())
  148. {
  149. p.StartInfo.CreateNoWindow = true;
  150. p.StartInfo.FileName = batchFile;
  151. p.StartInfo.UseShellExecute = false;
  152. p.Start();
  153. p.WaitForExit();
  154. p.Close();
  155. }
  156. }
  157. catch (Exception ex)
  158. {
  159. ErrorLogger.LogError("Utilities.RunBatchFile", ex.Message, ex.StackTrace);
  160. }
  161. }
  162. internal static void ImportRegistryScript(string scriptFile)
  163. {
  164. string path = "\"" + scriptFile + "\"";
  165. Process p = new Process();
  166. try
  167. {
  168. p.StartInfo.FileName = "regedit.exe";
  169. p.StartInfo.UseShellExecute = false;
  170. p = Process.Start("regedit.exe", "/s " + path);
  171. p.WaitForExit();
  172. }
  173. catch (Exception ex)
  174. {
  175. p.Dispose();
  176. ErrorLogger.LogError("Utilities.ImportRegistryScript", ex.Message, ex.StackTrace);
  177. }
  178. finally
  179. {
  180. p.Dispose();
  181. }
  182. }
  183. internal static void Reboot()
  184. {
  185. Utilities.RunCommand("shutdown /r /t 0");
  186. }
  187. internal static void ActivateMainForm()
  188. {
  189. Program.MainForm.Activate();
  190. }
  191. internal static bool ServiceExists(string serviceName)
  192. {
  193. return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName));
  194. }
  195. internal static void StopService(string serviceName)
  196. {
  197. if (ServiceExists(serviceName))
  198. {
  199. ServiceController sc = new ServiceController(serviceName);
  200. if (sc.CanStop)
  201. {
  202. sc.Stop();
  203. }
  204. }
  205. }
  206. internal static void StartService(string serviceName)
  207. {
  208. if (ServiceExists(serviceName))
  209. {
  210. ServiceController sc = new ServiceController(serviceName);
  211. try
  212. {
  213. sc.Start();
  214. }
  215. catch (Exception ex)
  216. {
  217. ErrorLogger.LogError("Utilities.StartService", ex.Message, ex.StackTrace);
  218. }
  219. }
  220. }
  221. private static void GetRegistryStartupItemsHelper(ref List<StartupItem> list, StartupItemLocation location, StartupItemType type)
  222. {
  223. string keyPath = string.Empty;
  224. RegistryKey hive = null;
  225. if (location == StartupItemLocation.HKLM)
  226. {
  227. hive = Registry.LocalMachine;
  228. if (type == StartupItemType.Run)
  229. {
  230. keyPath = LocalMachineRun;
  231. }
  232. else if (type == StartupItemType.RunOnce)
  233. {
  234. keyPath = LocalMachineRunOnce;
  235. }
  236. }
  237. else if (location == StartupItemLocation.HKLMWoW)
  238. {
  239. hive = Registry.LocalMachine;
  240. if (type == StartupItemType.Run)
  241. {
  242. keyPath = LocalMachineRunWoW;
  243. }
  244. else if (type == StartupItemType.RunOnce)
  245. {
  246. keyPath = LocalMachineRunOnceWow;
  247. }
  248. }
  249. else if (location == StartupItemLocation.HKCU)
  250. {
  251. hive = Registry.CurrentUser;
  252. if (type == StartupItemType.Run)
  253. {
  254. keyPath = CurrentUserRun;
  255. }
  256. else if (type == StartupItemType.RunOnce)
  257. {
  258. keyPath = CurrentUserRunOnce;
  259. }
  260. }
  261. if (hive != null)
  262. {
  263. try
  264. {
  265. RegistryKey key = hive.OpenSubKey(keyPath, true);
  266. if (key != null)
  267. {
  268. string[] valueNames = key.GetValueNames();
  269. foreach (string x in valueNames)
  270. {
  271. try
  272. {
  273. RegistryStartupItem item = new RegistryStartupItem();
  274. item.Name = x;
  275. item.FileLocation = key.GetValue(x).ToString();
  276. item.Key = key;
  277. item.RegistryLocation = location;
  278. item.StartupType = type;
  279. list.Add(item);
  280. }
  281. catch (Exception ex)
  282. {
  283. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  284. }
  285. }
  286. }
  287. }
  288. catch (Exception ex)
  289. {
  290. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  291. }
  292. }
  293. }
  294. private static void GetFolderStartupItemsHelper(ref List<StartupItem> list, string[] files, string[] shortcuts)
  295. {
  296. foreach (string file in files)
  297. {
  298. try
  299. {
  300. FolderStartupItem item = new FolderStartupItem();
  301. item.Name = Path.GetFileNameWithoutExtension(file);
  302. item.FileLocation = file;
  303. item.Shortcut = file;
  304. item.RegistryLocation = StartupItemLocation.Folder;
  305. list.Add(item);
  306. }
  307. catch (Exception ex)
  308. {
  309. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  310. }
  311. }
  312. foreach (string shortcut in shortcuts)
  313. {
  314. try
  315. {
  316. FolderStartupItem item = new FolderStartupItem();
  317. item.Name = Path.GetFileNameWithoutExtension(shortcut);
  318. item.FileLocation = GetShortcutTargetFile(shortcut);
  319. item.Shortcut = shortcut;
  320. item.RegistryLocation = StartupItemLocation.Folder;
  321. list.Add(item);
  322. }
  323. catch (Exception ex)
  324. {
  325. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  326. }
  327. }
  328. }
  329. internal static List<StartupItem> GetStartupItems()
  330. {
  331. List<StartupItem> startupItems = new List<StartupItem>();
  332. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.Run);
  333. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.RunOnce);
  334. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.Run);
  335. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.RunOnce);
  336. if (Environment.Is64BitOperatingSystem)
  337. {
  338. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.Run);
  339. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.RunOnce);
  340. }
  341. if (Directory.Exists(CurrentUserStartupFolder))
  342. {
  343. string[] currentUserFiles = Directory.EnumerateFiles(CurrentUserStartupFolder, "*.*", SearchOption.AllDirectories)
  344. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  345. string[] currentUserShortcuts = Directory.GetFiles(CurrentUserStartupFolder, "*.lnk", SearchOption.AllDirectories);
  346. GetFolderStartupItemsHelper(ref startupItems, currentUserFiles, currentUserShortcuts);
  347. }
  348. if (Directory.Exists(LocalMachineStartupFolder))
  349. {
  350. string[] localMachineFiles = Directory.EnumerateFiles(LocalMachineStartupFolder, "*.*", SearchOption.AllDirectories)
  351. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  352. string[] localMachineShortcuts = Directory.GetFiles(LocalMachineStartupFolder, "*.lnk", SearchOption.AllDirectories);
  353. GetFolderStartupItemsHelper(ref startupItems, localMachineFiles, localMachineShortcuts);
  354. }
  355. return startupItems;
  356. }
  357. internal static void EnableFirewall()
  358. {
  359. RunCommand("netsh advfirewall set currentprofile state on");
  360. }
  361. internal static void EnableCommandPrompt()
  362. {
  363. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  364. {
  365. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  366. }
  367. }
  368. internal static void EnableControlPanel()
  369. {
  370. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  371. {
  372. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  373. }
  374. }
  375. internal static void EnableFolderOptions()
  376. {
  377. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  378. {
  379. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  380. }
  381. }
  382. internal static void EnableRunDialog()
  383. {
  384. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  385. {
  386. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  387. }
  388. }
  389. internal static void EnableContextMenu()
  390. {
  391. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  392. {
  393. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  394. }
  395. }
  396. internal static void EnableTaskManager()
  397. {
  398. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  399. {
  400. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  401. }
  402. }
  403. internal static void EnableRegistryEditor()
  404. {
  405. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  406. {
  407. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  408. }
  409. }
  410. internal static void RunCommand(string command)
  411. {
  412. using (Process p = new Process())
  413. {
  414. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  415. p.StartInfo.FileName = "cmd.exe";
  416. p.StartInfo.Arguments = "/C " + command;
  417. try
  418. {
  419. p.Start();
  420. p.WaitForExit();
  421. p.Close();
  422. }
  423. catch (Exception ex)
  424. {
  425. ErrorLogger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  426. }
  427. }
  428. }
  429. internal static void FindFile(string fileName)
  430. {
  431. if (File.Exists(fileName))
  432. {
  433. Process.Start("explorer.exe", "/select, " + fileName);
  434. }
  435. }
  436. internal static string GetShortcutTargetFile(string shortcutFilename)
  437. {
  438. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  439. string filenameOnly = Path.GetFileName(shortcutFilename);
  440. Shell32.Shell shell = new Shell32.Shell();
  441. Shell32.Folder folder = shell.NameSpace(pathOnly);
  442. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  443. if (folderItem != null)
  444. {
  445. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  446. return link.Path;
  447. }
  448. return string.Empty;
  449. }
  450. internal static void RestartExplorer()
  451. {
  452. const string explorer = "explorer.exe";
  453. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  454. foreach (Process process in Process.GetProcesses())
  455. {
  456. try
  457. {
  458. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  459. {
  460. process.Kill();
  461. }
  462. }
  463. catch (Exception ex)
  464. {
  465. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  466. }
  467. }
  468. Process.Start(explorer);
  469. }
  470. internal static void FindKeyInRegistry(string key)
  471. {
  472. try
  473. {
  474. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  475. Process.Start("regedit");
  476. }
  477. catch (Exception ex)
  478. {
  479. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  480. }
  481. }
  482. internal static List<string> GetModernApps(bool showAll)
  483. {
  484. List<string> modernApps = new List<string>();
  485. using (PowerShell script = PowerShell.Create())
  486. {
  487. if (showAll)
  488. {
  489. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  490. }
  491. else
  492. {
  493. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  494. }
  495. string tmp = string.Empty;
  496. foreach (PSObject x in script.Invoke())
  497. {
  498. tmp = x.ToString().Trim();
  499. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  500. {
  501. modernApps.Add(tmp);
  502. }
  503. }
  504. }
  505. return modernApps;
  506. }
  507. internal static bool UninstallModernApp(string appName)
  508. {
  509. using (PowerShell script = PowerShell.Create())
  510. {
  511. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  512. script.Invoke();
  513. return script.Streams.Error.Count > 0;
  514. // not working on Windows 7 anymore
  515. //return script.HadErrors;
  516. }
  517. }
  518. internal static void ResetConfiguration(bool withoutRestart = false)
  519. {
  520. try
  521. {
  522. Directory.Delete(Required.CoreFolder, true);
  523. }
  524. catch (Exception ex)
  525. {
  526. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  527. }
  528. finally
  529. {
  530. if (withoutRestart == false) Application.Restart();
  531. }
  532. }
  533. internal static Task RunAsync(this Process process)
  534. {
  535. var tcs = new TaskCompletionSource<object>();
  536. process.EnableRaisingEvents = true;
  537. process.Exited += (s, e) => tcs.TrySetResult(null);
  538. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  539. return tcs.Task;
  540. }
  541. internal static PingReply PingHost(string nameOrAddress)
  542. {
  543. PingReply reply;
  544. try
  545. {
  546. reply = pinger.Send(nameOrAddress);
  547. return reply;
  548. }
  549. catch
  550. {
  551. return null;
  552. }
  553. }
  554. internal static bool IsInternetAvailable()
  555. {
  556. const int timeout = 1000;
  557. const string host = "1.1.1.1";
  558. var ping = new Ping();
  559. var buffer = new byte[32];
  560. var pingOptions = new PingOptions();
  561. try
  562. {
  563. var reply = ping.Send(host, timeout, buffer, pingOptions);
  564. return (reply != null && reply.Status == IPStatus.Success);
  565. }
  566. catch (Exception)
  567. {
  568. return false;
  569. }
  570. }
  571. internal static void FlushDNSCache()
  572. {
  573. Utilities.RunCommand("ipconfig /release && ipconfig /flushdns && ipconfig /renew");
  574. }
  575. internal static string SanitizeFileFolderName(string fileName)
  576. {
  577. char[] invalids = Path.GetInvalidFileNameChars();
  578. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  579. }
  580. }
  581. }