2
0

Utilities.cs 23 KB

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