Utilities.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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;
  10. using System.Net.NetworkInformation;
  11. using System.Net.Sockets;
  12. using System.Reflection;
  13. using System.Security.AccessControl;
  14. using System.Security.Principal;
  15. using System.ServiceProcess;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using System.Windows.Forms;
  19. namespace Optimizer
  20. {
  21. internal static class Utilities
  22. {
  23. internal static readonly string LocalMachineRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  24. internal static readonly string LocalMachineRunOnce = "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  25. internal static readonly string LocalMachineRunWoW = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run";
  26. internal static readonly string LocalMachineRunOnceWow = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  27. internal static readonly string CurrentUserRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  28. internal static readonly string CurrentUserRunOnce = "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  29. internal static readonly string LocalMachineStartupFolder = CleanHelper.ProgramData + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
  30. internal static readonly string CurrentUserStartupFolder = CleanHelper.ProfileAppDataRoaming + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
  31. // DEPRECATED
  32. //internal readonly static string DefaultEdgeDownloadFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
  33. internal static WindowsVersion CurrentWindowsVersion = WindowsVersion.Unsupported;
  34. internal static Ping pinger = new Ping();
  35. static IPAddress addressToPing;
  36. static string productName = string.Empty;
  37. static string buildNumber = string.Empty;
  38. internal delegate void SetControlPropertyThreadSafeDelegate(Control control, string propertyName, object propertyValue);
  39. internal static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
  40. {
  41. if (control.InvokeRequired)
  42. {
  43. control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
  44. }
  45. else
  46. {
  47. control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
  48. }
  49. }
  50. internal static IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
  51. {
  52. List<Control> controls = new List<Control>();
  53. foreach (Control child in parent.Controls)
  54. {
  55. controls.AddRange(GetSelfAndChildrenRecursive(child));
  56. }
  57. controls.Add(parent);
  58. return controls;
  59. }
  60. internal static Color ToGrayScale(this Color originalColor)
  61. {
  62. if (originalColor.Equals(Color.Transparent))
  63. return originalColor;
  64. int grayScale = (int)((originalColor.R * .299) + (originalColor.G * .587) + (originalColor.B * .114));
  65. return Color.FromArgb(grayScale, grayScale, grayScale);
  66. }
  67. internal static string GetWindows10Build()
  68. {
  69. return (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId", "");
  70. }
  71. internal static string GetOS()
  72. {
  73. productName = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", "");
  74. if (productName.Contains("Windows 7"))
  75. {
  76. CurrentWindowsVersion = WindowsVersion.Windows7;
  77. }
  78. if ((productName.Contains("Windows 8")) || (productName.Contains("Windows 8.1")))
  79. {
  80. CurrentWindowsVersion = WindowsVersion.Windows8;
  81. }
  82. if (productName.Contains("Windows 10"))
  83. {
  84. buildNumber = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "CurrentBuild", "");
  85. if (Convert.ToInt32(buildNumber) >= 22000)
  86. {
  87. productName = productName.Replace("Windows 10", "Windows 11");
  88. CurrentWindowsVersion = WindowsVersion.Windows11;
  89. }
  90. else
  91. {
  92. CurrentWindowsVersion = WindowsVersion.Windows10;
  93. }
  94. }
  95. if (Program.UNSAFE_MODE)
  96. {
  97. if (productName.Contains("Windows Server 2008"))
  98. {
  99. CurrentWindowsVersion = WindowsVersion.Windows7;
  100. }
  101. if (productName.Contains("Windows Server 2012"))
  102. {
  103. CurrentWindowsVersion = WindowsVersion.Windows8;
  104. }
  105. if (productName.Contains("Windows Server 2016") || productName.Contains("Windows Server 2019") || productName.Contains("Windows Server 2022"))
  106. {
  107. CurrentWindowsVersion = WindowsVersion.Windows10;
  108. }
  109. }
  110. return productName;
  111. }
  112. internal static string GetBitness()
  113. {
  114. string bitness = string.Empty;
  115. if (Environment.Is64BitOperatingSystem)
  116. {
  117. bitness = "You are working with 64-bit";
  118. }
  119. else
  120. {
  121. bitness = "You are working with 32-bit";
  122. }
  123. return bitness;
  124. }
  125. internal static bool IsAdmin()
  126. {
  127. return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
  128. }
  129. internal static bool IsCompatible()
  130. {
  131. bool legit;
  132. string os = GetOS();
  133. if ((os.Contains("XP")) || (os.Contains("Vista")) || os.Contains("Server 2003"))
  134. {
  135. legit = false;
  136. }
  137. else
  138. {
  139. legit = true;
  140. }
  141. return legit;
  142. }
  143. // DEPRECATED
  144. //internal static string GetEdgeDownloadFolder()
  145. //{
  146. // string current = string.Empty;
  147. // try
  148. // {
  149. // current = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", DefaultEdgeDownloadFolder).ToString();
  150. // }
  151. // catch (Exception ex)
  152. // {
  153. // current = DefaultEdgeDownloadFolder;
  154. // ErrorLogger.LogError("Utilities.GetEdgeDownloadFolder", ex.Message, ex.StackTrace);
  155. // }
  156. // return current;
  157. //}
  158. // DEPRECATED
  159. //internal static void SetEdgeDownloadFolder(string path)
  160. //{
  161. // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", path, RegistryValueKind.String);
  162. //}
  163. internal static void RunBatchFile(string batchFile)
  164. {
  165. try
  166. {
  167. using (Process p = new Process())
  168. {
  169. p.StartInfo.CreateNoWindow = true;
  170. p.StartInfo.FileName = batchFile;
  171. p.StartInfo.UseShellExecute = false;
  172. p.Start();
  173. p.WaitForExit();
  174. p.Close();
  175. }
  176. }
  177. catch (Exception ex)
  178. {
  179. ErrorLogger.LogError("Utilities.RunBatchFile", ex.Message, ex.StackTrace);
  180. }
  181. }
  182. internal static void ImportRegistryScript(string scriptFile)
  183. {
  184. string path = "\"" + scriptFile + "\"";
  185. Process p = new Process();
  186. try
  187. {
  188. p.StartInfo.FileName = "regedit.exe";
  189. p.StartInfo.UseShellExecute = false;
  190. p = Process.Start("regedit.exe", "/s " + path);
  191. p.WaitForExit();
  192. }
  193. catch (Exception ex)
  194. {
  195. p.Dispose();
  196. ErrorLogger.LogError("Utilities.ImportRegistryScript", ex.Message, ex.StackTrace);
  197. }
  198. finally
  199. {
  200. p.Dispose();
  201. }
  202. }
  203. internal static void Reboot()
  204. {
  205. Utilities.RunCommand("shutdown /r /t 0");
  206. }
  207. internal static void ActivateMainForm()
  208. {
  209. Program._MainForm.Activate();
  210. }
  211. internal static bool ServiceExists(string serviceName)
  212. {
  213. return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName));
  214. }
  215. internal static void StopService(string serviceName)
  216. {
  217. if (ServiceExists(serviceName))
  218. {
  219. ServiceController sc = new ServiceController(serviceName);
  220. if (sc.CanStop)
  221. {
  222. sc.Stop();
  223. }
  224. }
  225. }
  226. internal static void StartService(string serviceName)
  227. {
  228. if (ServiceExists(serviceName))
  229. {
  230. ServiceController sc = new ServiceController(serviceName);
  231. try
  232. {
  233. sc.Start();
  234. }
  235. catch (Exception ex)
  236. {
  237. ErrorLogger.LogError("Utilities.StartService", ex.Message, ex.StackTrace);
  238. }
  239. }
  240. }
  241. private static void GetRegistryStartupItemsHelper(ref List<StartupItem> list, StartupItemLocation location, StartupItemType type)
  242. {
  243. string keyPath = string.Empty;
  244. RegistryKey hive = null;
  245. if (location == StartupItemLocation.HKLM)
  246. {
  247. hive = Registry.LocalMachine;
  248. if (type == StartupItemType.Run)
  249. {
  250. keyPath = LocalMachineRun;
  251. }
  252. else if (type == StartupItemType.RunOnce)
  253. {
  254. keyPath = LocalMachineRunOnce;
  255. }
  256. }
  257. else if (location == StartupItemLocation.HKLMWoW)
  258. {
  259. hive = Registry.LocalMachine;
  260. if (type == StartupItemType.Run)
  261. {
  262. keyPath = LocalMachineRunWoW;
  263. }
  264. else if (type == StartupItemType.RunOnce)
  265. {
  266. keyPath = LocalMachineRunOnceWow;
  267. }
  268. }
  269. else if (location == StartupItemLocation.HKCU)
  270. {
  271. hive = Registry.CurrentUser;
  272. if (type == StartupItemType.Run)
  273. {
  274. keyPath = CurrentUserRun;
  275. }
  276. else if (type == StartupItemType.RunOnce)
  277. {
  278. keyPath = CurrentUserRunOnce;
  279. }
  280. }
  281. if (hive != null)
  282. {
  283. try
  284. {
  285. RegistryKey key = hive.OpenSubKey(keyPath, true);
  286. if (key != null)
  287. {
  288. string[] valueNames = key.GetValueNames();
  289. foreach (string x in valueNames)
  290. {
  291. try
  292. {
  293. RegistryStartupItem item = new RegistryStartupItem();
  294. item.Name = x;
  295. item.FileLocation = key.GetValue(x).ToString();
  296. item.Key = key;
  297. item.RegistryLocation = location;
  298. item.StartupType = type;
  299. list.Add(item);
  300. }
  301. catch (Exception ex)
  302. {
  303. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  304. }
  305. }
  306. }
  307. }
  308. catch (Exception ex)
  309. {
  310. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  311. }
  312. }
  313. }
  314. private static void GetFolderStartupItemsHelper(ref List<StartupItem> list, string[] files, string[] shortcuts)
  315. {
  316. foreach (string file in files)
  317. {
  318. try
  319. {
  320. FolderStartupItem item = new FolderStartupItem();
  321. item.Name = Path.GetFileNameWithoutExtension(file);
  322. item.FileLocation = file;
  323. item.Shortcut = file;
  324. item.RegistryLocation = StartupItemLocation.Folder;
  325. list.Add(item);
  326. }
  327. catch (Exception ex)
  328. {
  329. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  330. }
  331. }
  332. foreach (string shortcut in shortcuts)
  333. {
  334. try
  335. {
  336. FolderStartupItem item = new FolderStartupItem();
  337. item.Name = Path.GetFileNameWithoutExtension(shortcut);
  338. item.FileLocation = GetShortcutTargetFile(shortcut);
  339. item.Shortcut = shortcut;
  340. item.RegistryLocation = StartupItemLocation.Folder;
  341. list.Add(item);
  342. }
  343. catch (Exception ex)
  344. {
  345. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  346. }
  347. }
  348. }
  349. internal static List<StartupItem> GetStartupItems()
  350. {
  351. List<StartupItem> startupItems = new List<StartupItem>();
  352. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.Run);
  353. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.RunOnce);
  354. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.Run);
  355. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.RunOnce);
  356. if (Environment.Is64BitOperatingSystem)
  357. {
  358. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.Run);
  359. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.RunOnce);
  360. }
  361. if (Directory.Exists(CurrentUserStartupFolder))
  362. {
  363. string[] currentUserFiles = Directory.EnumerateFiles(CurrentUserStartupFolder, "*.*", SearchOption.AllDirectories)
  364. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  365. string[] currentUserShortcuts = Directory.GetFiles(CurrentUserStartupFolder, "*.lnk", SearchOption.AllDirectories);
  366. GetFolderStartupItemsHelper(ref startupItems, currentUserFiles, currentUserShortcuts);
  367. }
  368. if (Directory.Exists(LocalMachineStartupFolder))
  369. {
  370. string[] localMachineFiles = Directory.EnumerateFiles(LocalMachineStartupFolder, "*.*", SearchOption.AllDirectories)
  371. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  372. string[] localMachineShortcuts = Directory.GetFiles(LocalMachineStartupFolder, "*.lnk", SearchOption.AllDirectories);
  373. GetFolderStartupItemsHelper(ref startupItems, localMachineFiles, localMachineShortcuts);
  374. }
  375. return startupItems;
  376. }
  377. internal static void EnableFirewall()
  378. {
  379. RunCommand("netsh advfirewall set currentprofile state on");
  380. }
  381. internal static void EnableCommandPrompt()
  382. {
  383. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  384. {
  385. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  386. }
  387. }
  388. internal static void EnableControlPanel()
  389. {
  390. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  391. {
  392. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  393. }
  394. }
  395. internal static void EnableFolderOptions()
  396. {
  397. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  398. {
  399. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  400. }
  401. }
  402. internal static void EnableRunDialog()
  403. {
  404. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  405. {
  406. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  407. }
  408. }
  409. internal static void EnableContextMenu()
  410. {
  411. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  412. {
  413. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  414. }
  415. }
  416. internal static void EnableTaskManager()
  417. {
  418. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  419. {
  420. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  421. }
  422. }
  423. internal static void EnableRegistryEditor()
  424. {
  425. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  426. {
  427. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  428. }
  429. }
  430. internal static void RunCommand(string command)
  431. {
  432. using (Process p = new Process())
  433. {
  434. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  435. p.StartInfo.FileName = "cmd.exe";
  436. p.StartInfo.Arguments = "/C " + command;
  437. p.StartInfo.CreateNoWindow = true;
  438. try
  439. {
  440. p.Start();
  441. p.WaitForExit();
  442. p.Close();
  443. }
  444. catch (Exception ex)
  445. {
  446. ErrorLogger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  447. }
  448. }
  449. }
  450. internal static void FindFile(string fileName)
  451. {
  452. if (File.Exists(fileName))
  453. {
  454. Process.Start("explorer.exe", "/select, " + fileName);
  455. }
  456. }
  457. internal static string GetShortcutTargetFile(string shortcutFilename)
  458. {
  459. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  460. string filenameOnly = Path.GetFileName(shortcutFilename);
  461. Shell32.Shell shell = new Shell32.Shell();
  462. Shell32.Folder folder = shell.NameSpace(pathOnly);
  463. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  464. if (folderItem != null)
  465. {
  466. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  467. return link.Path;
  468. }
  469. return string.Empty;
  470. }
  471. internal static void RestartExplorer()
  472. {
  473. const string explorer = "explorer.exe";
  474. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  475. foreach (Process process in Process.GetProcesses())
  476. {
  477. try
  478. {
  479. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  480. {
  481. process.Kill();
  482. }
  483. }
  484. catch (Exception ex)
  485. {
  486. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  487. }
  488. }
  489. Thread.Sleep(TimeSpan.FromSeconds(1));
  490. Process.Start(explorer);
  491. }
  492. internal static void FindKeyInRegistry(string key)
  493. {
  494. try
  495. {
  496. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  497. Process.Start("regedit");
  498. }
  499. catch (Exception ex)
  500. {
  501. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  502. }
  503. }
  504. internal static List<string> GetModernApps(bool showAll)
  505. {
  506. List<string> modernApps = new List<string>();
  507. using (PowerShell script = PowerShell.Create())
  508. {
  509. if (showAll)
  510. {
  511. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  512. }
  513. else
  514. {
  515. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  516. }
  517. string tmp = string.Empty;
  518. foreach (PSObject x in script.Invoke())
  519. {
  520. tmp = x.ToString().Trim();
  521. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  522. {
  523. modernApps.Add(tmp);
  524. }
  525. }
  526. }
  527. return modernApps;
  528. }
  529. internal static bool UninstallModernApp(string appName)
  530. {
  531. using (PowerShell script = PowerShell.Create())
  532. {
  533. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  534. script.Invoke();
  535. return script.Streams.Error.Count > 0;
  536. // not working on Windows 7 anymore
  537. //return script.HadErrors;
  538. }
  539. }
  540. internal static void ResetConfiguration(bool withoutRestart = false)
  541. {
  542. try
  543. {
  544. Directory.Delete(Required.CoreFolder, true);
  545. }
  546. catch (Exception ex)
  547. {
  548. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  549. }
  550. finally
  551. {
  552. if (withoutRestart == false)
  553. {
  554. // BYPASS SINGLE-INSTANCE MECHANISM
  555. if (Program.MUTEX != null)
  556. {
  557. Program.MUTEX.ReleaseMutex();
  558. Program.MUTEX.Dispose();
  559. Program.MUTEX = null;
  560. }
  561. Application.Restart();
  562. }
  563. }
  564. }
  565. internal static Task RunAsync(this Process process)
  566. {
  567. var tcs = new TaskCompletionSource<object>();
  568. process.EnableRaisingEvents = true;
  569. process.Exited += (s, e) => tcs.TrySetResult(null);
  570. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  571. return tcs.Task;
  572. }
  573. internal static PingReply PingHost(string nameOrAddress)
  574. {
  575. PingReply reply;
  576. try
  577. {
  578. addressToPing = Dns.GetHostAddresses(nameOrAddress)
  579. .First(address => address.AddressFamily == AddressFamily.InterNetwork);
  580. reply = pinger.Send(addressToPing);
  581. return reply;
  582. }
  583. catch
  584. {
  585. return null;
  586. }
  587. }
  588. internal static bool IsInternetAvailable()
  589. {
  590. const int timeout = 1000;
  591. const string host = "1.1.1.1";
  592. var ping = new Ping();
  593. var buffer = new byte[32];
  594. var pingOptions = new PingOptions();
  595. try
  596. {
  597. var reply = ping.Send(host, timeout, buffer, pingOptions);
  598. return (reply != null && reply.Status == IPStatus.Success);
  599. }
  600. catch (Exception)
  601. {
  602. return false;
  603. }
  604. }
  605. internal static void FlushDNSCache()
  606. {
  607. Utilities.RunBatchFile(Required.ScriptsFolder + "FlushDNSCache.bat");
  608. //Utilities.RunCommand("ipconfig /release && ipconfig /renew && arp -d * && nbtstat -R && nbtstat -RR && ipconfig /flushdns && ipconfig /registerdns");
  609. }
  610. internal static string SanitizeFileFolderName(string fileName)
  611. {
  612. char[] invalids = Path.GetInvalidFileNameChars();
  613. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  614. }
  615. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  616. internal static void EnableGPEDitor()
  617. {
  618. Utilities.RunBatchFile(Required.ScriptsFolder + "GPEditEnablerInHome.bat");
  619. }
  620. internal static void TryDeleteRegistryValue(bool localMachine, string path, string valueName)
  621. {
  622. try
  623. {
  624. if (localMachine) Registry.LocalMachine.OpenSubKey(path, true).DeleteValue(valueName, false);
  625. if (!localMachine) Registry.CurrentUser.OpenSubKey(path, true).DeleteValue(valueName, false);
  626. }
  627. catch { }
  628. }
  629. internal static void DisableProtectedService(string serviceName)
  630. {
  631. using (TokenPrivilege.TakeOwnership)
  632. {
  633. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  634. {
  635. allServicesKey.GrantFullControlOnSubKey(serviceName);
  636. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  637. {
  638. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  639. {
  640. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  641. serviceKey.GrantFullControlOnSubKey(subkeyName);
  642. }
  643. serviceKey.SetValue("Start", "4", RegistryValueKind.DWord);
  644. }
  645. }
  646. }
  647. }
  648. internal static void RestoreWindowsPhotoViewer()
  649. {
  650. const string PHOTO_VIEWER_SHELL_COMMAND =
  651. @"%SystemRoot%\System32\rundll32.exe ""%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll"", ImageView_Fullscreen %1";
  652. const string PHOTO_VIEWER_CLSID = "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}";
  653. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open", "MuiVerb", "@photoviewer.dll,-3043");
  654. Registry.SetValue(
  655. @"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\command", valueName: null,
  656. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  657. );
  658. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  659. string[] imageTypes = { "Paint.Picture", "giffile", "jpegfile", "pngfile" };
  660. foreach (string type in imageTypes)
  661. {
  662. Registry.SetValue(
  663. $@"HKEY_CLASSES_ROOT\{type}\shell\open\command", valueName: null,
  664. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  665. );
  666. Registry.SetValue($@"HKEY_CLASSES_ROOT\{type}\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  667. }
  668. }
  669. internal static void EnableProtectedService(string serviceName)
  670. {
  671. using (TokenPrivilege.TakeOwnership)
  672. {
  673. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  674. {
  675. allServicesKey.GrantFullControlOnSubKey(serviceName);
  676. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  677. {
  678. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  679. {
  680. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  681. serviceKey.GrantFullControlOnSubKey(subkeyName);
  682. }
  683. serviceKey.SetValue("Start", "2", RegistryValueKind.DWord);
  684. }
  685. }
  686. }
  687. }
  688. public static RegistryKey OpenSubKeyWritable(this RegistryKey registryKey, string subkeyName, RegistryRights? rights = null)
  689. {
  690. RegistryKey subKey = null;
  691. if (rights == null)
  692. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree);
  693. else
  694. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, rights.Value);
  695. if (subKey == null)
  696. {
  697. ErrorLogger.LogError("Utilities.OpenSubKeyWritable", $"Subkey {subkeyName} not found.", "-");
  698. }
  699. return subKey;
  700. }
  701. internal static SecurityIdentifier RetrieveCurrentUserIdentifier()
  702. => WindowsIdentity.GetCurrent().User ?? throw new Exception("Unable to retrieve current user SID.");
  703. internal static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName)
  704. {
  705. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName,
  706. RegistryRights.TakeOwnership | RegistryRights.ChangePermissions
  707. ))
  708. {
  709. RegistrySecurity accessRules = subKey.GetAccessControl();
  710. SecurityIdentifier currentUser = RetrieveCurrentUserIdentifier();
  711. accessRules.SetOwner(currentUser);
  712. accessRules.ResetAccessRule(
  713. new RegistryAccessRule(
  714. currentUser,
  715. RegistryRights.FullControl,
  716. InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  717. PropagationFlags.None,
  718. AccessControlType.Allow
  719. )
  720. );
  721. subKey.SetAccessControl(accessRules);
  722. }
  723. }
  724. internal static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
  725. {
  726. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership))
  727. {
  728. RegistrySecurity accessRules = subKey.GetAccessControl();
  729. accessRules.SetOwner(RetrieveCurrentUserIdentifier());
  730. subKey.SetAccessControl(accessRules);
  731. }
  732. }
  733. internal static string GetNETFramework()
  734. {
  735. string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
  736. int netRelease;
  737. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
  738. {
  739. if (ndpKey != null && ndpKey.GetValue("Release") != null)
  740. {
  741. netRelease = (int)ndpKey.GetValue("Release");
  742. }
  743. else
  744. {
  745. return "4.0";
  746. }
  747. }
  748. if (netRelease >= 528040)
  749. return "4.8";
  750. if (netRelease >= 461808)
  751. return "4.7.2";
  752. if (netRelease >= 461308)
  753. return "4.7.1";
  754. if (netRelease >= 460798)
  755. return "4.7";
  756. if (netRelease >= 394802)
  757. return "4.6.2";
  758. if (netRelease >= 394254)
  759. return "4.6.1";
  760. if (netRelease >= 393295)
  761. return "4.6";
  762. if (netRelease >= 379893)
  763. return "4.5.2";
  764. if (netRelease >= 378675)
  765. return "4.5.1";
  766. if (netRelease >= 378389)
  767. return "4.5";
  768. return "4.0";
  769. }
  770. internal static void SearchWith(string term, bool ddg)
  771. {
  772. try
  773. {
  774. if (ddg) Process.Start(string.Format("https://duckduckgo.com/?q={0}", term));
  775. if (!ddg) Process.Start(string.Format("https://www.google.com/search?q={0}", term));
  776. }
  777. catch { }
  778. }
  779. }
  780. }