Utilities.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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
  128. {
  129. current = DefaultEdgeDownloadFolder;
  130. }
  131. return current;
  132. }
  133. internal static void SetEdgeDownloadFolder(string path)
  134. {
  135. 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);
  136. }
  137. internal static void RunBatchFile(string batchFile)
  138. {
  139. try
  140. {
  141. using (Process p = new Process())
  142. {
  143. p.StartInfo.CreateNoWindow = true;
  144. p.StartInfo.FileName = batchFile;
  145. p.StartInfo.UseShellExecute = false;
  146. p.Start();
  147. p.WaitForExit();
  148. p.Close();
  149. }
  150. }
  151. catch { }
  152. }
  153. internal static void ImportRegistryScript(string scriptFile)
  154. {
  155. string path = "\"" + scriptFile + "\"";
  156. Process p = new Process();
  157. try
  158. {
  159. p.StartInfo.FileName = "regedit.exe";
  160. p.StartInfo.UseShellExecute = false;
  161. p = Process.Start("regedit.exe", "/s " + path);
  162. p.WaitForExit();
  163. }
  164. catch
  165. {
  166. p.Dispose();
  167. }
  168. finally
  169. {
  170. p.Dispose();
  171. }
  172. }
  173. internal static void Reboot()
  174. {
  175. Process.Start("shutdown", "/r /t 0");
  176. }
  177. internal static void ActivateMainForm()
  178. {
  179. Program.MainForm.Activate();
  180. }
  181. internal static bool ServiceExists(string serviceName)
  182. {
  183. return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName));
  184. }
  185. internal static void StopService(string serviceName)
  186. {
  187. if (ServiceExists(serviceName))
  188. {
  189. ServiceController sc = new ServiceController(serviceName);
  190. if (sc.CanStop)
  191. {
  192. sc.Stop();
  193. }
  194. }
  195. }
  196. internal static void StartService(string serviceName)
  197. {
  198. if (ServiceExists(serviceName))
  199. {
  200. ServiceController sc = new ServiceController(serviceName);
  201. try
  202. {
  203. sc.Start();
  204. }
  205. catch { }
  206. }
  207. }
  208. private static void GetRegistryStartupItemsHelper(ref List<StartupItem> list, StartupItemLocation location, StartupItemType type)
  209. {
  210. string keyPath = string.Empty;
  211. RegistryKey hive = null;
  212. if (location == StartupItemLocation.HKLM)
  213. {
  214. hive = Registry.LocalMachine;
  215. if (type == StartupItemType.Run)
  216. {
  217. keyPath = LocalMachineRun;
  218. }
  219. else if (type == StartupItemType.RunOnce)
  220. {
  221. keyPath = LocalMachineRunOnce;
  222. }
  223. }
  224. else if (location == StartupItemLocation.HKLMWoW)
  225. {
  226. hive = Registry.LocalMachine;
  227. if (type == StartupItemType.Run)
  228. {
  229. keyPath = LocalMachineRunWoW;
  230. }
  231. else if (type == StartupItemType.RunOnce)
  232. {
  233. keyPath = LocalMachineRunOnceWow;
  234. }
  235. }
  236. else if (location == StartupItemLocation.HKCU)
  237. {
  238. hive = Registry.CurrentUser;
  239. if (type == StartupItemType.Run)
  240. {
  241. keyPath = CurrentUserRun;
  242. }
  243. else if (type == StartupItemType.RunOnce)
  244. {
  245. keyPath = CurrentUserRunOnce;
  246. }
  247. }
  248. if (hive != null)
  249. {
  250. RegistryKey key = hive.OpenSubKey(keyPath, true);
  251. if (key != null)
  252. {
  253. string[] valueNames = key.GetValueNames();
  254. foreach (string x in valueNames)
  255. {
  256. try
  257. {
  258. RegistryStartupItem item = new RegistryStartupItem();
  259. item.Name = x;
  260. item.FileLocation = key.GetValue(x).ToString();
  261. item.Key = key;
  262. item.RegistryLocation = location;
  263. item.StartupType = type;
  264. list.Add(item);
  265. }
  266. catch { }
  267. }
  268. }
  269. }
  270. }
  271. private static void GetFolderStartupItemsHelper(ref List<StartupItem> list, string[] files, string[] shortcuts)
  272. {
  273. foreach (string file in files)
  274. {
  275. try
  276. {
  277. FolderStartupItem item = new FolderStartupItem();
  278. item.Name = Path.GetFileNameWithoutExtension(file);
  279. item.FileLocation = file;
  280. item.Shortcut = file;
  281. item.RegistryLocation = StartupItemLocation.Folder;
  282. list.Add(item);
  283. }
  284. catch { }
  285. }
  286. foreach (string shortcut in shortcuts)
  287. {
  288. try
  289. {
  290. FolderStartupItem item = new FolderStartupItem();
  291. item.Name = Path.GetFileNameWithoutExtension(shortcut);
  292. item.FileLocation = GetShortcutTargetFile(shortcut);
  293. item.Shortcut = shortcut;
  294. item.RegistryLocation = StartupItemLocation.Folder;
  295. list.Add(item);
  296. }
  297. catch { }
  298. }
  299. }
  300. internal static List<StartupItem> GetStartupItems()
  301. {
  302. List<StartupItem> startupItems = new List<StartupItem>();
  303. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.Run);
  304. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.RunOnce);
  305. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.Run);
  306. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.RunOnce);
  307. if (Environment.Is64BitOperatingSystem)
  308. {
  309. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.Run);
  310. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.RunOnce);
  311. }
  312. string[] currentUserFiles = Directory.GetFiles(CurrentUserStartupFolder, "*.exe", SearchOption.AllDirectories);
  313. string[] currentUserShortcuts = Directory.GetFiles(CurrentUserStartupFolder, "*.lnk", SearchOption.AllDirectories);
  314. GetFolderStartupItemsHelper(ref startupItems, currentUserFiles, currentUserShortcuts);
  315. string[] localMachineFiles = Directory.GetFiles(LocalMachineStartupFolder, "*.exe", SearchOption.AllDirectories);
  316. string[] localMachineShortcuts = Directory.GetFiles(LocalMachineStartupFolder, "*.lnk", SearchOption.AllDirectories);
  317. GetFolderStartupItemsHelper(ref startupItems, localMachineFiles, localMachineShortcuts);
  318. return startupItems;
  319. }
  320. internal static void EnableFirewall()
  321. {
  322. RunCommand("netsh advfirewall set currentprofile state on");
  323. }
  324. internal static void EnableCommandPrompt()
  325. {
  326. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  327. {
  328. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  329. }
  330. }
  331. internal static void EnableControlPanel()
  332. {
  333. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  334. {
  335. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  336. }
  337. }
  338. internal static void EnableFolderOptions()
  339. {
  340. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  341. {
  342. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  343. }
  344. }
  345. internal static void EnableRunDialog()
  346. {
  347. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  348. {
  349. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  350. }
  351. }
  352. internal static void EnableContextMenu()
  353. {
  354. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  355. {
  356. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  357. }
  358. }
  359. internal static void EnableTaskManager()
  360. {
  361. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  362. {
  363. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  364. }
  365. }
  366. internal static void EnableRegistryEditor()
  367. {
  368. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  369. {
  370. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  371. }
  372. }
  373. internal static void RunCommand(string command)
  374. {
  375. using (Process p = new Process())
  376. {
  377. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  378. p.StartInfo.FileName = "cmd.exe";
  379. p.StartInfo.Arguments = "/C " + command;
  380. try
  381. {
  382. p.Start();
  383. p.WaitForExit();
  384. p.Close();
  385. }
  386. catch { }
  387. }
  388. }
  389. internal static void FindFile(string fileName)
  390. {
  391. if (File.Exists(fileName))
  392. {
  393. Process.Start("explorer.exe", "/select, " + fileName);
  394. }
  395. }
  396. internal static string GetShortcutTargetFile(string shortcutFilename)
  397. {
  398. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  399. string filenameOnly = Path.GetFileName(shortcutFilename);
  400. Shell32.Shell shell = new Shell32.Shell();
  401. Shell32.Folder folder = shell.NameSpace(pathOnly);
  402. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  403. if (folderItem != null)
  404. {
  405. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  406. return link.Path;
  407. }
  408. return string.Empty;
  409. }
  410. internal static void RestartExplorer()
  411. {
  412. const string explorer = "explorer.exe";
  413. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  414. foreach (Process process in Process.GetProcesses())
  415. {
  416. try
  417. {
  418. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  419. {
  420. process.Kill();
  421. }
  422. }
  423. catch { }
  424. }
  425. Process.Start(explorer);
  426. }
  427. internal static void FindKeyInRegistry(string key)
  428. {
  429. try
  430. {
  431. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  432. Process.Start("regedit");
  433. }
  434. catch { }
  435. }
  436. internal static List<string> GetModernApps(bool showAll)
  437. {
  438. List<string> modernApps = new List<string>();
  439. using (PowerShell script = PowerShell.Create())
  440. {
  441. if (showAll)
  442. {
  443. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  444. }
  445. else
  446. {
  447. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  448. }
  449. string tmp = string.Empty;
  450. foreach (PSObject x in script.Invoke())
  451. {
  452. tmp = x.ToString().Trim();
  453. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  454. {
  455. modernApps.Add(tmp);
  456. }
  457. }
  458. }
  459. return modernApps;
  460. }
  461. internal static bool UninstallModernApp(string appName)
  462. {
  463. using (PowerShell script = PowerShell.Create())
  464. {
  465. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  466. script.Invoke();
  467. return script.Streams.Error.Count > 0;
  468. // not working on Windows 7 anymore
  469. //return script.HadErrors;
  470. }
  471. }
  472. internal static void ResetConfiguration()
  473. {
  474. try
  475. {
  476. Directory.Delete(Required.CoreFolder, true);
  477. }
  478. catch { }
  479. finally
  480. {
  481. Application.Restart();
  482. }
  483. }
  484. internal static Task RunAsync(this Process process)
  485. {
  486. var tcs = new TaskCompletionSource<object>();
  487. process.EnableRaisingEvents = true;
  488. process.Exited += (s, e) => tcs.TrySetResult(null);
  489. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  490. return tcs.Task;
  491. }
  492. }
  493. }