Utilities.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Security.Principal;
  7. using System.Windows.Forms;
  8. using System.IO;
  9. using System.Diagnostics;
  10. using System.ServiceProcess;
  11. using System.Management.Automation;
  12. using System.Drawing;
  13. using System.Threading.Tasks;
  14. using System.Net.NetworkInformation;
  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_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\Main", "Default Download Directory", 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_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\Main", "Default Download Directory", 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. RegistryKey key = hive.OpenSubKey(keyPath, true);
  261. if (key != null)
  262. {
  263. string[] valueNames = key.GetValueNames();
  264. foreach (string x in valueNames)
  265. {
  266. try
  267. {
  268. RegistryStartupItem item = new RegistryStartupItem();
  269. item.Name = x;
  270. item.FileLocation = key.GetValue(x).ToString();
  271. item.Key = key;
  272. item.RegistryLocation = location;
  273. item.StartupType = type;
  274. list.Add(item);
  275. }
  276. catch (Exception ex)
  277. {
  278. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  279. }
  280. }
  281. }
  282. }
  283. }
  284. private static void GetFolderStartupItemsHelper(ref List<StartupItem> list, string[] files, string[] shortcuts)
  285. {
  286. foreach (string file in files)
  287. {
  288. try
  289. {
  290. FolderStartupItem item = new FolderStartupItem();
  291. item.Name = Path.GetFileNameWithoutExtension(file);
  292. item.FileLocation = file;
  293. item.Shortcut = file;
  294. item.RegistryLocation = StartupItemLocation.Folder;
  295. list.Add(item);
  296. }
  297. catch (Exception ex)
  298. {
  299. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  300. }
  301. }
  302. foreach (string shortcut in shortcuts)
  303. {
  304. try
  305. {
  306. FolderStartupItem item = new FolderStartupItem();
  307. item.Name = Path.GetFileNameWithoutExtension(shortcut);
  308. item.FileLocation = GetShortcutTargetFile(shortcut);
  309. item.Shortcut = shortcut;
  310. item.RegistryLocation = StartupItemLocation.Folder;
  311. list.Add(item);
  312. }
  313. catch (Exception ex)
  314. {
  315. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  316. }
  317. }
  318. }
  319. internal static List<StartupItem> GetStartupItems()
  320. {
  321. List<StartupItem> startupItems = new List<StartupItem>();
  322. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.Run);
  323. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.RunOnce);
  324. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.Run);
  325. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.RunOnce);
  326. if (Environment.Is64BitOperatingSystem)
  327. {
  328. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.Run);
  329. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.RunOnce);
  330. }
  331. string[] currentUserFiles = Directory.GetFiles(CurrentUserStartupFolder, "*.exe", SearchOption.AllDirectories);
  332. string[] currentUserShortcuts = Directory.GetFiles(CurrentUserStartupFolder, "*.lnk", SearchOption.AllDirectories);
  333. GetFolderStartupItemsHelper(ref startupItems, currentUserFiles, currentUserShortcuts);
  334. string[] localMachineFiles = Directory.GetFiles(LocalMachineStartupFolder, "*.exe", SearchOption.AllDirectories);
  335. string[] localMachineShortcuts = Directory.GetFiles(LocalMachineStartupFolder, "*.lnk", SearchOption.AllDirectories);
  336. GetFolderStartupItemsHelper(ref startupItems, localMachineFiles, localMachineShortcuts);
  337. return startupItems;
  338. }
  339. internal static void EnableFirewall()
  340. {
  341. RunCommand("netsh advfirewall set currentprofile state on");
  342. }
  343. internal static void EnableCommandPrompt()
  344. {
  345. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  346. {
  347. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  348. }
  349. }
  350. internal static void EnableControlPanel()
  351. {
  352. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  353. {
  354. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  355. }
  356. }
  357. internal static void EnableFolderOptions()
  358. {
  359. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  360. {
  361. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  362. }
  363. }
  364. internal static void EnableRunDialog()
  365. {
  366. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  367. {
  368. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  369. }
  370. }
  371. internal static void EnableContextMenu()
  372. {
  373. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  374. {
  375. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  376. }
  377. }
  378. internal static void EnableTaskManager()
  379. {
  380. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  381. {
  382. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  383. }
  384. }
  385. internal static void EnableRegistryEditor()
  386. {
  387. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  388. {
  389. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  390. }
  391. }
  392. internal static void RunCommand(string command)
  393. {
  394. using (Process p = new Process())
  395. {
  396. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  397. p.StartInfo.FileName = "cmd.exe";
  398. p.StartInfo.Arguments = "/C " + command;
  399. try
  400. {
  401. p.Start();
  402. p.WaitForExit();
  403. p.Close();
  404. }
  405. catch (Exception ex)
  406. {
  407. ErrorLogger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  408. }
  409. }
  410. }
  411. internal static void FindFile(string fileName)
  412. {
  413. if (File.Exists(fileName))
  414. {
  415. Process.Start("explorer.exe", "/select, " + fileName);
  416. }
  417. }
  418. internal static string GetShortcutTargetFile(string shortcutFilename)
  419. {
  420. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  421. string filenameOnly = Path.GetFileName(shortcutFilename);
  422. Shell32.Shell shell = new Shell32.Shell();
  423. Shell32.Folder folder = shell.NameSpace(pathOnly);
  424. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  425. if (folderItem != null)
  426. {
  427. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  428. return link.Path;
  429. }
  430. return string.Empty;
  431. }
  432. internal static void RestartExplorer()
  433. {
  434. const string explorer = "explorer.exe";
  435. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  436. foreach (Process process in Process.GetProcesses())
  437. {
  438. try
  439. {
  440. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  441. {
  442. process.Kill();
  443. }
  444. }
  445. catch (Exception ex)
  446. {
  447. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  448. }
  449. }
  450. Process.Start(explorer);
  451. }
  452. internal static void FindKeyInRegistry(string key)
  453. {
  454. try
  455. {
  456. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  457. Process.Start("regedit");
  458. }
  459. catch (Exception ex)
  460. {
  461. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  462. }
  463. }
  464. internal static List<string> GetModernApps(bool showAll)
  465. {
  466. List<string> modernApps = new List<string>();
  467. using (PowerShell script = PowerShell.Create())
  468. {
  469. if (showAll)
  470. {
  471. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  472. }
  473. else
  474. {
  475. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  476. }
  477. string tmp = string.Empty;
  478. foreach (PSObject x in script.Invoke())
  479. {
  480. tmp = x.ToString().Trim();
  481. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  482. {
  483. modernApps.Add(tmp);
  484. }
  485. }
  486. }
  487. return modernApps;
  488. }
  489. internal static bool UninstallModernApp(string appName)
  490. {
  491. using (PowerShell script = PowerShell.Create())
  492. {
  493. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  494. script.Invoke();
  495. return script.Streams.Error.Count > 0;
  496. // not working on Windows 7 anymore
  497. //return script.HadErrors;
  498. }
  499. }
  500. internal static void ResetConfiguration()
  501. {
  502. try
  503. {
  504. Directory.Delete(Required.CoreFolder, true);
  505. }
  506. catch (Exception ex)
  507. {
  508. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  509. }
  510. finally
  511. {
  512. Application.Restart();
  513. }
  514. }
  515. internal static Task RunAsync(this Process process)
  516. {
  517. var tcs = new TaskCompletionSource<object>();
  518. process.EnableRaisingEvents = true;
  519. process.Exited += (s, e) => tcs.TrySetResult(null);
  520. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  521. return tcs.Task;
  522. }
  523. internal static PingReply PingHost(string nameOrAddress)
  524. {
  525. PingReply reply;
  526. try
  527. {
  528. reply = pinger.Send(nameOrAddress);
  529. return reply;
  530. }
  531. catch
  532. {
  533. return null;
  534. }
  535. }
  536. }
  537. }