Utilities.cs 21 KB

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