Utilities.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. try
  438. {
  439. p.Start();
  440. p.WaitForExit();
  441. p.Close();
  442. }
  443. catch (Exception ex)
  444. {
  445. ErrorLogger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  446. }
  447. }
  448. }
  449. internal static void FindFile(string fileName)
  450. {
  451. if (File.Exists(fileName))
  452. {
  453. Process.Start("explorer.exe", "/select, " + fileName);
  454. }
  455. }
  456. internal static string GetShortcutTargetFile(string shortcutFilename)
  457. {
  458. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  459. string filenameOnly = Path.GetFileName(shortcutFilename);
  460. Shell32.Shell shell = new Shell32.Shell();
  461. Shell32.Folder folder = shell.NameSpace(pathOnly);
  462. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  463. if (folderItem != null)
  464. {
  465. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  466. return link.Path;
  467. }
  468. return string.Empty;
  469. }
  470. internal static void RestartExplorer()
  471. {
  472. const string explorer = "explorer.exe";
  473. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  474. foreach (Process process in Process.GetProcesses())
  475. {
  476. try
  477. {
  478. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  479. {
  480. process.Kill();
  481. }
  482. }
  483. catch (Exception ex)
  484. {
  485. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  486. }
  487. }
  488. Thread.Sleep(TimeSpan.FromSeconds(1));
  489. Process.Start(explorer);
  490. }
  491. internal static void FindKeyInRegistry(string key)
  492. {
  493. try
  494. {
  495. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  496. Process.Start("regedit");
  497. }
  498. catch (Exception ex)
  499. {
  500. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  501. }
  502. }
  503. internal static List<string> GetModernApps(bool showAll)
  504. {
  505. List<string> modernApps = new List<string>();
  506. using (PowerShell script = PowerShell.Create())
  507. {
  508. if (showAll)
  509. {
  510. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  511. }
  512. else
  513. {
  514. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  515. }
  516. string tmp = string.Empty;
  517. foreach (PSObject x in script.Invoke())
  518. {
  519. tmp = x.ToString().Trim();
  520. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  521. {
  522. modernApps.Add(tmp);
  523. }
  524. }
  525. }
  526. return modernApps;
  527. }
  528. internal static bool UninstallModernApp(string appName)
  529. {
  530. using (PowerShell script = PowerShell.Create())
  531. {
  532. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  533. script.Invoke();
  534. return script.Streams.Error.Count > 0;
  535. // not working on Windows 7 anymore
  536. //return script.HadErrors;
  537. }
  538. }
  539. internal static void ResetConfiguration(bool withoutRestart = false)
  540. {
  541. try
  542. {
  543. Directory.Delete(Required.CoreFolder, true);
  544. }
  545. catch (Exception ex)
  546. {
  547. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  548. }
  549. finally
  550. {
  551. if (withoutRestart == false)
  552. {
  553. // BYPASS SINGLE-INSTANCE MECHANISM
  554. if (Program.MUTEX != null)
  555. {
  556. Program.MUTEX.ReleaseMutex();
  557. Program.MUTEX.Dispose();
  558. Program.MUTEX = null;
  559. }
  560. Application.Restart();
  561. }
  562. }
  563. }
  564. internal static Task RunAsync(this Process process)
  565. {
  566. var tcs = new TaskCompletionSource<object>();
  567. process.EnableRaisingEvents = true;
  568. process.Exited += (s, e) => tcs.TrySetResult(null);
  569. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  570. return tcs.Task;
  571. }
  572. internal static PingReply PingHost(string nameOrAddress)
  573. {
  574. PingReply reply;
  575. try
  576. {
  577. addressToPing = Dns.GetHostAddresses(nameOrAddress)
  578. .First(address => address.AddressFamily == AddressFamily.InterNetwork);
  579. reply = pinger.Send(addressToPing);
  580. return reply;
  581. }
  582. catch
  583. {
  584. return null;
  585. }
  586. }
  587. internal static bool IsInternetAvailable()
  588. {
  589. const int timeout = 1000;
  590. const string host = "1.1.1.1";
  591. var ping = new Ping();
  592. var buffer = new byte[32];
  593. var pingOptions = new PingOptions();
  594. try
  595. {
  596. var reply = ping.Send(host, timeout, buffer, pingOptions);
  597. return (reply != null && reply.Status == IPStatus.Success);
  598. }
  599. catch (Exception)
  600. {
  601. return false;
  602. }
  603. }
  604. internal static void FlushDNSCache()
  605. {
  606. Utilities.RunBatchFile(Required.ScriptsFolder + "FlushDNSCache.bat");
  607. //Utilities.RunCommand("ipconfig /release && ipconfig /renew && arp -d * && nbtstat -R && nbtstat -RR && ipconfig /flushdns && ipconfig /registerdns");
  608. }
  609. internal static string SanitizeFileFolderName(string fileName)
  610. {
  611. char[] invalids = Path.GetInvalidFileNameChars();
  612. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  613. }
  614. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  615. internal static void EnableGPEDitor()
  616. {
  617. Utilities.RunBatchFile(Required.ScriptsFolder + "GPEditEnablerInHome.bat");
  618. }
  619. internal static void TryDeleteRegistryValue(bool localMachine, string path, string valueName)
  620. {
  621. try
  622. {
  623. if (localMachine) Registry.LocalMachine.OpenSubKey(path, true).DeleteValue(valueName, false);
  624. if (!localMachine) Registry.CurrentUser.OpenSubKey(path, true).DeleteValue(valueName, false);
  625. }
  626. catch { }
  627. }
  628. internal static void DisableProtectedService(string serviceName)
  629. {
  630. using (TokenPrivilege.TakeOwnership)
  631. {
  632. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  633. {
  634. allServicesKey.GrantFullControlOnSubKey(serviceName);
  635. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  636. {
  637. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  638. {
  639. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  640. serviceKey.GrantFullControlOnSubKey(subkeyName);
  641. }
  642. serviceKey.SetValue("Start", "4", RegistryValueKind.DWord);
  643. }
  644. }
  645. }
  646. }
  647. internal static void RestoreWindowsPhotoViewer()
  648. {
  649. const string PHOTO_VIEWER_SHELL_COMMAND =
  650. @"%SystemRoot%\System32\rundll32.exe ""%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll"", ImageView_Fullscreen %1";
  651. const string PHOTO_VIEWER_CLSID = "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}";
  652. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open", "MuiVerb", "@photoviewer.dll,-3043");
  653. Registry.SetValue(
  654. @"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\command", valueName: null,
  655. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  656. );
  657. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  658. string[] imageTypes = { "Paint.Picture", "giffile", "jpegfile", "pngfile" };
  659. foreach (string type in imageTypes)
  660. {
  661. Registry.SetValue(
  662. $@"HKEY_CLASSES_ROOT\{type}\shell\open\command", valueName: null,
  663. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  664. );
  665. Registry.SetValue($@"HKEY_CLASSES_ROOT\{type}\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  666. }
  667. }
  668. internal static void EnableProtectedService(string serviceName)
  669. {
  670. using (TokenPrivilege.TakeOwnership)
  671. {
  672. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  673. {
  674. allServicesKey.GrantFullControlOnSubKey(serviceName);
  675. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  676. {
  677. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  678. {
  679. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  680. serviceKey.GrantFullControlOnSubKey(subkeyName);
  681. }
  682. serviceKey.SetValue("Start", "2", RegistryValueKind.DWord);
  683. }
  684. }
  685. }
  686. }
  687. public static RegistryKey OpenSubKeyWritable(this RegistryKey registryKey, string subkeyName, RegistryRights? rights = null)
  688. {
  689. RegistryKey subKey = null;
  690. if (rights == null)
  691. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree);
  692. else
  693. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, rights.Value);
  694. if (subKey == null)
  695. {
  696. ErrorLogger.LogError("Utilities.OpenSubKeyWritable", $"Subkey {subkeyName} not found.", "-");
  697. }
  698. return subKey;
  699. }
  700. internal static SecurityIdentifier RetrieveCurrentUserIdentifier()
  701. => WindowsIdentity.GetCurrent().User ?? throw new Exception("Unable to retrieve current user SID.");
  702. internal static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName)
  703. {
  704. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName,
  705. RegistryRights.TakeOwnership | RegistryRights.ChangePermissions
  706. ))
  707. {
  708. RegistrySecurity accessRules = subKey.GetAccessControl();
  709. SecurityIdentifier currentUser = RetrieveCurrentUserIdentifier();
  710. accessRules.SetOwner(currentUser);
  711. accessRules.ResetAccessRule(
  712. new RegistryAccessRule(
  713. currentUser,
  714. RegistryRights.FullControl,
  715. InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  716. PropagationFlags.None,
  717. AccessControlType.Allow
  718. )
  719. );
  720. subKey.SetAccessControl(accessRules);
  721. }
  722. }
  723. internal static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
  724. {
  725. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership))
  726. {
  727. RegistrySecurity accessRules = subKey.GetAccessControl();
  728. accessRules.SetOwner(RetrieveCurrentUserIdentifier());
  729. subKey.SetAccessControl(accessRules);
  730. }
  731. }
  732. internal static string GetNETFramework()
  733. {
  734. string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
  735. int netRelease;
  736. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
  737. {
  738. if (ndpKey != null && ndpKey.GetValue("Release") != null)
  739. {
  740. netRelease = (int)ndpKey.GetValue("Release");
  741. }
  742. else
  743. {
  744. return "4.0";
  745. }
  746. }
  747. if (netRelease >= 528040)
  748. return "4.8";
  749. if (netRelease >= 461808)
  750. return "4.7.2";
  751. if (netRelease >= 461308)
  752. return "4.7.1";
  753. if (netRelease >= 460798)
  754. return "4.7";
  755. if (netRelease >= 394802)
  756. return "4.6.2";
  757. if (netRelease >= 394254)
  758. return "4.6.1";
  759. if (netRelease >= 393295)
  760. return "4.6";
  761. if (netRelease >= 379893)
  762. return "4.5.2";
  763. if (netRelease >= 378675)
  764. return "4.5.1";
  765. if (netRelease >= 378389)
  766. return "4.5";
  767. return "4.0";
  768. }
  769. internal static void SearchWith(string term, bool ddg)
  770. {
  771. try
  772. {
  773. if (ddg) Process.Start(string.Format("https://duckduckgo.com/?q={0}", term));
  774. if (!ddg) Process.Start(string.Format("https://www.google.com/search?q={0}", term));
  775. }
  776. catch { }
  777. }
  778. }
  779. }