2
0

Utilities.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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)) Process.Start("explorer.exe", $"/select, \"{fileName}\"");
  453. }
  454. internal static string GetShortcutTargetFile(string shortcutFilename)
  455. {
  456. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  457. string filenameOnly = Path.GetFileName(shortcutFilename);
  458. Shell32.Shell shell = new Shell32.Shell();
  459. Shell32.Folder folder = shell.NameSpace(pathOnly);
  460. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  461. if (folderItem != null)
  462. {
  463. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  464. return link.Path;
  465. }
  466. return string.Empty;
  467. }
  468. internal static void RestartExplorer()
  469. {
  470. const string explorer = "explorer.exe";
  471. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  472. foreach (Process process in Process.GetProcesses())
  473. {
  474. try
  475. {
  476. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  477. {
  478. process.Kill();
  479. }
  480. }
  481. catch (Exception ex)
  482. {
  483. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  484. }
  485. }
  486. Thread.Sleep(TimeSpan.FromSeconds(1));
  487. Process.Start(explorer);
  488. }
  489. internal static void FindKeyInRegistry(string key)
  490. {
  491. try
  492. {
  493. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  494. Process.Start("regedit");
  495. }
  496. catch (Exception ex)
  497. {
  498. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  499. }
  500. }
  501. internal static List<string> GetModernApps(bool showAll)
  502. {
  503. List<string> modernApps = new List<string>();
  504. using (PowerShell script = PowerShell.Create())
  505. {
  506. if (showAll)
  507. {
  508. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  509. }
  510. else
  511. {
  512. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  513. }
  514. string tmp = string.Empty;
  515. foreach (PSObject x in script.Invoke())
  516. {
  517. tmp = x.ToString().Trim();
  518. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  519. {
  520. modernApps.Add(tmp);
  521. }
  522. }
  523. }
  524. return modernApps;
  525. }
  526. internal static bool UninstallModernApp(string appName)
  527. {
  528. using (PowerShell script = PowerShell.Create())
  529. {
  530. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  531. script.Invoke();
  532. return script.Streams.Error.Count > 0;
  533. // not working on Windows 7 anymore
  534. //return script.HadErrors;
  535. }
  536. }
  537. internal static void ResetConfiguration(bool withoutRestart = false)
  538. {
  539. try
  540. {
  541. Directory.Delete(Required.CoreFolder, true);
  542. }
  543. catch (Exception ex)
  544. {
  545. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  546. }
  547. finally
  548. {
  549. if (withoutRestart == false)
  550. {
  551. // BYPASS SINGLE-INSTANCE MECHANISM
  552. if (Program.MUTEX != null)
  553. {
  554. Program.MUTEX.ReleaseMutex();
  555. Program.MUTEX.Dispose();
  556. Program.MUTEX = null;
  557. }
  558. Application.Restart();
  559. }
  560. }
  561. }
  562. internal static Task RunAsync(this Process process)
  563. {
  564. var tcs = new TaskCompletionSource<object>();
  565. process.EnableRaisingEvents = true;
  566. process.Exited += (s, e) => tcs.TrySetResult(null);
  567. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  568. return tcs.Task;
  569. }
  570. internal static PingReply PingHost(string nameOrAddress)
  571. {
  572. PingReply reply;
  573. try
  574. {
  575. addressToPing = Dns.GetHostAddresses(nameOrAddress)
  576. .First(address => address.AddressFamily == AddressFamily.InterNetwork);
  577. reply = pinger.Send(addressToPing);
  578. return reply;
  579. }
  580. catch
  581. {
  582. return null;
  583. }
  584. }
  585. internal static bool IsInternetAvailable()
  586. {
  587. const int timeout = 1000;
  588. const string host = "1.1.1.1";
  589. var ping = new Ping();
  590. var buffer = new byte[32];
  591. var pingOptions = new PingOptions();
  592. try
  593. {
  594. var reply = ping.Send(host, timeout, buffer, pingOptions);
  595. return (reply != null && reply.Status == IPStatus.Success);
  596. }
  597. catch (Exception)
  598. {
  599. return false;
  600. }
  601. }
  602. internal static void FlushDNSCache()
  603. {
  604. Utilities.RunBatchFile(Required.ScriptsFolder + "FlushDNSCache.bat");
  605. //Utilities.RunCommand("ipconfig /release && ipconfig /renew && arp -d * && nbtstat -R && nbtstat -RR && ipconfig /flushdns && ipconfig /registerdns");
  606. }
  607. internal static string SanitizeFileFolderName(string fileName)
  608. {
  609. char[] invalids = Path.GetInvalidFileNameChars();
  610. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  611. }
  612. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  613. internal static void EnableGPEDitor()
  614. {
  615. Utilities.RunBatchFile(Required.ScriptsFolder + "GPEditEnablerInHome.bat");
  616. }
  617. internal static void TryDeleteRegistryValue(bool localMachine, string path, string valueName)
  618. {
  619. try
  620. {
  621. if (localMachine) Registry.LocalMachine.OpenSubKey(path, true).DeleteValue(valueName, false);
  622. if (!localMachine) Registry.CurrentUser.OpenSubKey(path, true).DeleteValue(valueName, false);
  623. }
  624. catch { }
  625. }
  626. internal static void DisableProtectedService(string serviceName)
  627. {
  628. using (TokenPrivilege.TakeOwnership)
  629. {
  630. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  631. {
  632. allServicesKey.GrantFullControlOnSubKey(serviceName);
  633. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  634. {
  635. if (serviceKey == null) return;
  636. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  637. {
  638. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  639. serviceKey.GrantFullControlOnSubKey(subkeyName);
  640. }
  641. serviceKey.SetValue("Start", "4", RegistryValueKind.DWord);
  642. }
  643. }
  644. }
  645. }
  646. internal static void RestoreWindowsPhotoViewer()
  647. {
  648. const string PHOTO_VIEWER_SHELL_COMMAND =
  649. @"%SystemRoot%\System32\rundll32.exe ""%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll"", ImageView_Fullscreen %1";
  650. const string PHOTO_VIEWER_CLSID = "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}";
  651. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open", "MuiVerb", "@photoviewer.dll,-3043");
  652. Registry.SetValue(
  653. @"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\command", valueName: null,
  654. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  655. );
  656. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  657. string[] imageTypes = { "Paint.Picture", "giffile", "jpegfile", "pngfile" };
  658. foreach (string type in imageTypes)
  659. {
  660. Registry.SetValue(
  661. $@"HKEY_CLASSES_ROOT\{type}\shell\open\command", valueName: null,
  662. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  663. );
  664. Registry.SetValue($@"HKEY_CLASSES_ROOT\{type}\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  665. }
  666. }
  667. internal static void EnableProtectedService(string serviceName)
  668. {
  669. using (TokenPrivilege.TakeOwnership)
  670. {
  671. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  672. {
  673. allServicesKey.GrantFullControlOnSubKey(serviceName);
  674. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  675. {
  676. if (serviceKey == null) return;
  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. internal static void PreventProcessFromRunning(string pName)
  779. {
  780. try
  781. {
  782. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
  783. {
  784. if (ifeo == null) return;
  785. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  786. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options"))
  787. {
  788. if (k == null) return;
  789. k.CreateSubKey(pName);
  790. k.GrantFullControlOnSubKey(pName);
  791. using (RegistryKey f = k.OpenSubKeyWritable(pName))
  792. {
  793. if (f == null) return;
  794. f.SetValue("Debugger", @"%windir%\System32\taskkill.exe");
  795. }
  796. }
  797. }
  798. }
  799. catch (Exception ex)
  800. {
  801. ErrorLogger.LogError("Utilities.PreventProcessFromRunning", ex.Message, ex.StackTrace);
  802. }
  803. }
  804. }
  805. }