Utilities.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 DisableHibernation()
  208. {
  209. Utilities.RunCommand("powercfg -h off");
  210. Utilities.RunCommand("powercfg -h off");
  211. }
  212. internal static void EnableHibernation()
  213. {
  214. Utilities.RunCommand("powercfg -h on");
  215. Utilities.RunCommand("powercfg -h on");
  216. }
  217. internal static void ActivateMainForm()
  218. {
  219. Program._MainForm.Activate();
  220. }
  221. internal static bool ServiceExists(string serviceName)
  222. {
  223. return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName));
  224. }
  225. internal static void StopService(string serviceName)
  226. {
  227. if (ServiceExists(serviceName))
  228. {
  229. ServiceController sc = new ServiceController(serviceName);
  230. if (sc.CanStop)
  231. {
  232. sc.Stop();
  233. }
  234. }
  235. }
  236. internal static void StartService(string serviceName)
  237. {
  238. if (ServiceExists(serviceName))
  239. {
  240. ServiceController sc = new ServiceController(serviceName);
  241. try
  242. {
  243. sc.Start();
  244. }
  245. catch (Exception ex)
  246. {
  247. ErrorLogger.LogError("Utilities.StartService", ex.Message, ex.StackTrace);
  248. }
  249. }
  250. }
  251. private static void GetRegistryStartupItemsHelper(ref List<StartupItem> list, StartupItemLocation location, StartupItemType type)
  252. {
  253. string keyPath = string.Empty;
  254. RegistryKey hive = null;
  255. if (location == StartupItemLocation.HKLM)
  256. {
  257. hive = Registry.LocalMachine;
  258. if (type == StartupItemType.Run)
  259. {
  260. keyPath = LocalMachineRun;
  261. }
  262. else if (type == StartupItemType.RunOnce)
  263. {
  264. keyPath = LocalMachineRunOnce;
  265. }
  266. }
  267. else if (location == StartupItemLocation.HKLMWoW)
  268. {
  269. hive = Registry.LocalMachine;
  270. if (type == StartupItemType.Run)
  271. {
  272. keyPath = LocalMachineRunWoW;
  273. }
  274. else if (type == StartupItemType.RunOnce)
  275. {
  276. keyPath = LocalMachineRunOnceWow;
  277. }
  278. }
  279. else if (location == StartupItemLocation.HKCU)
  280. {
  281. hive = Registry.CurrentUser;
  282. if (type == StartupItemType.Run)
  283. {
  284. keyPath = CurrentUserRun;
  285. }
  286. else if (type == StartupItemType.RunOnce)
  287. {
  288. keyPath = CurrentUserRunOnce;
  289. }
  290. }
  291. if (hive != null)
  292. {
  293. try
  294. {
  295. RegistryKey key = hive.OpenSubKey(keyPath, true);
  296. if (key != null)
  297. {
  298. string[] valueNames = key.GetValueNames();
  299. foreach (string x in valueNames)
  300. {
  301. try
  302. {
  303. RegistryStartupItem item = new RegistryStartupItem();
  304. item.Name = x;
  305. item.FileLocation = key.GetValue(x).ToString();
  306. item.Key = key;
  307. item.RegistryLocation = location;
  308. item.StartupType = type;
  309. list.Add(item);
  310. }
  311. catch (Exception ex)
  312. {
  313. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  314. }
  315. }
  316. }
  317. }
  318. catch (Exception ex)
  319. {
  320. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  321. }
  322. }
  323. }
  324. private static void GetFolderStartupItemsHelper(ref List<StartupItem> list, string[] files, string[] shortcuts)
  325. {
  326. foreach (string file in files)
  327. {
  328. try
  329. {
  330. FolderStartupItem item = new FolderStartupItem();
  331. item.Name = Path.GetFileNameWithoutExtension(file);
  332. item.FileLocation = file;
  333. item.Shortcut = file;
  334. item.RegistryLocation = StartupItemLocation.Folder;
  335. list.Add(item);
  336. }
  337. catch (Exception ex)
  338. {
  339. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  340. }
  341. }
  342. foreach (string shortcut in shortcuts)
  343. {
  344. try
  345. {
  346. FolderStartupItem item = new FolderStartupItem();
  347. item.Name = Path.GetFileNameWithoutExtension(shortcut);
  348. item.FileLocation = GetShortcutTargetFile(shortcut);
  349. item.Shortcut = shortcut;
  350. item.RegistryLocation = StartupItemLocation.Folder;
  351. list.Add(item);
  352. }
  353. catch (Exception ex)
  354. {
  355. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  356. }
  357. }
  358. }
  359. internal static List<StartupItem> GetStartupItems()
  360. {
  361. List<StartupItem> startupItems = new List<StartupItem>();
  362. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.Run);
  363. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.RunOnce);
  364. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.Run);
  365. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.RunOnce);
  366. if (Environment.Is64BitOperatingSystem)
  367. {
  368. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.Run);
  369. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.RunOnce);
  370. }
  371. if (Directory.Exists(CurrentUserStartupFolder))
  372. {
  373. string[] currentUserFiles = Directory.EnumerateFiles(CurrentUserStartupFolder, "*.*", SearchOption.AllDirectories)
  374. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  375. string[] currentUserShortcuts = Directory.GetFiles(CurrentUserStartupFolder, "*.lnk", SearchOption.AllDirectories);
  376. GetFolderStartupItemsHelper(ref startupItems, currentUserFiles, currentUserShortcuts);
  377. }
  378. if (Directory.Exists(LocalMachineStartupFolder))
  379. {
  380. string[] localMachineFiles = Directory.EnumerateFiles(LocalMachineStartupFolder, "*.*", SearchOption.AllDirectories)
  381. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  382. string[] localMachineShortcuts = Directory.GetFiles(LocalMachineStartupFolder, "*.lnk", SearchOption.AllDirectories);
  383. GetFolderStartupItemsHelper(ref startupItems, localMachineFiles, localMachineShortcuts);
  384. }
  385. return startupItems;
  386. }
  387. internal static void EnableFirewall()
  388. {
  389. RunCommand("netsh advfirewall set currentprofile state on");
  390. }
  391. internal static void EnableCommandPrompt()
  392. {
  393. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  394. {
  395. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  396. }
  397. }
  398. internal static void EnableControlPanel()
  399. {
  400. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  401. {
  402. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  403. }
  404. }
  405. internal static void EnableFolderOptions()
  406. {
  407. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  408. {
  409. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  410. }
  411. }
  412. internal static void EnableRunDialog()
  413. {
  414. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  415. {
  416. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  417. }
  418. }
  419. internal static void EnableContextMenu()
  420. {
  421. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  422. {
  423. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  424. }
  425. }
  426. internal static void EnableTaskManager()
  427. {
  428. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  429. {
  430. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  431. }
  432. }
  433. internal static void EnableRegistryEditor()
  434. {
  435. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  436. {
  437. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  438. }
  439. }
  440. internal static void RunCommand(string command)
  441. {
  442. using (Process p = new Process())
  443. {
  444. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  445. p.StartInfo.FileName = "cmd.exe";
  446. p.StartInfo.Arguments = "/C " + command;
  447. p.StartInfo.CreateNoWindow = true;
  448. try
  449. {
  450. p.Start();
  451. p.WaitForExit();
  452. p.Close();
  453. }
  454. catch (Exception ex)
  455. {
  456. ErrorLogger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  457. }
  458. }
  459. }
  460. internal static void FindFile(string fileName)
  461. {
  462. if (File.Exists(fileName)) Process.Start("explorer.exe", $"/select, \"{fileName}\"");
  463. }
  464. internal static string GetShortcutTargetFile(string shortcutFilename)
  465. {
  466. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  467. string filenameOnly = Path.GetFileName(shortcutFilename);
  468. Shell32.Shell shell = new Shell32.Shell();
  469. Shell32.Folder folder = shell.NameSpace(pathOnly);
  470. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  471. if (folderItem != null)
  472. {
  473. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  474. return link.Path;
  475. }
  476. return string.Empty;
  477. }
  478. internal static void RestartExplorer()
  479. {
  480. const string explorer = "explorer.exe";
  481. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  482. foreach (Process process in Process.GetProcesses())
  483. {
  484. try
  485. {
  486. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  487. {
  488. process.Kill();
  489. }
  490. }
  491. catch (Exception ex)
  492. {
  493. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  494. }
  495. }
  496. Thread.Sleep(TimeSpan.FromSeconds(1));
  497. Process.Start(explorer);
  498. }
  499. internal static void FindKeyInRegistry(string key)
  500. {
  501. try
  502. {
  503. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  504. Process.Start("regedit");
  505. }
  506. catch (Exception ex)
  507. {
  508. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  509. }
  510. }
  511. internal static List<string> GetModernApps(bool showAll)
  512. {
  513. List<string> modernApps = new List<string>();
  514. using (PowerShell script = PowerShell.Create())
  515. {
  516. if (showAll)
  517. {
  518. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  519. }
  520. else
  521. {
  522. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  523. }
  524. string tmp = string.Empty;
  525. foreach (PSObject x in script.Invoke())
  526. {
  527. tmp = x.ToString().Trim();
  528. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  529. {
  530. modernApps.Add(tmp);
  531. }
  532. }
  533. }
  534. return modernApps;
  535. }
  536. internal static bool UninstallModernApp(string appName)
  537. {
  538. using (PowerShell script = PowerShell.Create())
  539. {
  540. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  541. script.Invoke();
  542. return script.Streams.Error.Count > 0;
  543. // not working on Windows 7 anymore
  544. //return script.HadErrors;
  545. }
  546. }
  547. internal static void ResetConfiguration(bool withoutRestart = false)
  548. {
  549. try
  550. {
  551. Directory.Delete(Required.CoreFolder, true);
  552. }
  553. catch (Exception ex)
  554. {
  555. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  556. }
  557. finally
  558. {
  559. if (!withoutRestart)
  560. {
  561. // BYPASS SINGLE-INSTANCE MECHANISM
  562. if (Program.MUTEX != null)
  563. {
  564. Program.MUTEX.ReleaseMutex();
  565. Program.MUTEX.Dispose();
  566. Program.MUTEX = null;
  567. }
  568. Application.Restart();
  569. }
  570. }
  571. }
  572. internal static Task RunAsync(this Process process)
  573. {
  574. var tcs = new TaskCompletionSource<object>();
  575. process.EnableRaisingEvents = true;
  576. process.Exited += (s, e) => tcs.TrySetResult(null);
  577. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  578. return tcs.Task;
  579. }
  580. internal static PingReply PingHost(string nameOrAddress)
  581. {
  582. PingReply reply;
  583. try
  584. {
  585. addressToPing = Dns.GetHostAddresses(nameOrAddress)
  586. .First(address => address.AddressFamily == AddressFamily.InterNetwork);
  587. reply = pinger.Send(addressToPing);
  588. return reply;
  589. }
  590. catch
  591. {
  592. return null;
  593. }
  594. }
  595. internal static bool IsInternetAvailable()
  596. {
  597. const int timeout = 1000;
  598. const string host = "1.1.1.1";
  599. var ping = new Ping();
  600. var buffer = new byte[32];
  601. var pingOptions = new PingOptions();
  602. try
  603. {
  604. var reply = ping.Send(host, timeout, buffer, pingOptions);
  605. return (reply != null && reply.Status == IPStatus.Success);
  606. }
  607. catch (Exception)
  608. {
  609. return false;
  610. }
  611. }
  612. internal static void FlushDNSCache()
  613. {
  614. Utilities.RunBatchFile(Required.ScriptsFolder + "FlushDNSCache.bat");
  615. //Utilities.RunCommand("ipconfig /release && ipconfig /renew && arp -d * && nbtstat -R && nbtstat -RR && ipconfig /flushdns && ipconfig /registerdns");
  616. }
  617. internal static string SanitizeFileFolderName(string fileName)
  618. {
  619. char[] invalids = Path.GetInvalidFileNameChars();
  620. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  621. }
  622. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  623. internal static void EnableGPEDitor()
  624. {
  625. Utilities.RunBatchFile(Required.ScriptsFolder + "GPEditEnablerInHome.bat");
  626. }
  627. internal static void TryDeleteRegistryValue(bool localMachine, string path, string valueName)
  628. {
  629. try
  630. {
  631. if (localMachine) Registry.LocalMachine.OpenSubKey(path, true).DeleteValue(valueName, false);
  632. if (!localMachine) Registry.CurrentUser.OpenSubKey(path, true).DeleteValue(valueName, false);
  633. }
  634. catch { }
  635. }
  636. internal static void DisableProtectedService(string serviceName)
  637. {
  638. using (TokenPrivilege.TakeOwnership)
  639. {
  640. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  641. {
  642. allServicesKey.GrantFullControlOnSubKey(serviceName);
  643. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  644. {
  645. if (serviceKey == null) return;
  646. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  647. {
  648. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  649. serviceKey.GrantFullControlOnSubKey(subkeyName);
  650. }
  651. serviceKey.SetValue("Start", "4", RegistryValueKind.DWord);
  652. }
  653. }
  654. }
  655. }
  656. internal static void RestoreWindowsPhotoViewer()
  657. {
  658. const string PHOTO_VIEWER_SHELL_COMMAND =
  659. @"%SystemRoot%\System32\rundll32.exe ""%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll"", ImageView_Fullscreen %1";
  660. const string PHOTO_VIEWER_CLSID = "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}";
  661. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open", "MuiVerb", "@photoviewer.dll,-3043");
  662. Registry.SetValue(
  663. @"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\command", valueName: null,
  664. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  665. );
  666. Registry.SetValue(@"HKEY_CLASSES_ROOT\Applications\photoviewer.dll\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  667. string[] imageTypes = { "Paint.Picture", "giffile", "jpegfile", "pngfile" };
  668. foreach (string type in imageTypes)
  669. {
  670. Registry.SetValue(
  671. $@"HKEY_CLASSES_ROOT\{type}\shell\open\command", valueName: null,
  672. PHOTO_VIEWER_SHELL_COMMAND, RegistryValueKind.ExpandString
  673. );
  674. Registry.SetValue($@"HKEY_CLASSES_ROOT\{type}\shell\open\DropTarget", "Clsid", PHOTO_VIEWER_CLSID);
  675. }
  676. }
  677. internal static void EnableProtectedService(string serviceName)
  678. {
  679. using (TokenPrivilege.TakeOwnership)
  680. {
  681. using (RegistryKey allServicesKey = Registry.LocalMachine.OpenSubKeyWritable(@"SYSTEM\CurrentControlSet\Services"))
  682. {
  683. allServicesKey.GrantFullControlOnSubKey(serviceName);
  684. using (RegistryKey serviceKey = allServicesKey.OpenSubKeyWritable(serviceName))
  685. {
  686. if (serviceKey == null) return;
  687. foreach (string subkeyName in serviceKey.GetSubKeyNames())
  688. {
  689. serviceKey.TakeOwnershipOnSubKey(subkeyName);
  690. serviceKey.GrantFullControlOnSubKey(subkeyName);
  691. }
  692. serviceKey.SetValue("Start", "2", RegistryValueKind.DWord);
  693. }
  694. }
  695. }
  696. }
  697. public static RegistryKey OpenSubKeyWritable(this RegistryKey registryKey, string subkeyName, RegistryRights? rights = null)
  698. {
  699. RegistryKey subKey = null;
  700. if (rights == null)
  701. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree);
  702. else
  703. subKey = registryKey.OpenSubKey(subkeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, rights.Value);
  704. if (subKey == null)
  705. {
  706. ErrorLogger.LogError("Utilities.OpenSubKeyWritable", $"Subkey {subkeyName} not found.", "-");
  707. }
  708. return subKey;
  709. }
  710. internal static SecurityIdentifier RetrieveCurrentUserIdentifier()
  711. => WindowsIdentity.GetCurrent().User ?? throw new Exception("Unable to retrieve current user SID.");
  712. internal static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName)
  713. {
  714. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName,
  715. RegistryRights.TakeOwnership | RegistryRights.ChangePermissions
  716. ))
  717. {
  718. RegistrySecurity accessRules = subKey.GetAccessControl();
  719. SecurityIdentifier currentUser = RetrieveCurrentUserIdentifier();
  720. accessRules.SetOwner(currentUser);
  721. accessRules.ResetAccessRule(
  722. new RegistryAccessRule(
  723. currentUser,
  724. RegistryRights.FullControl,
  725. InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
  726. PropagationFlags.None,
  727. AccessControlType.Allow
  728. )
  729. );
  730. subKey.SetAccessControl(accessRules);
  731. }
  732. }
  733. internal static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
  734. {
  735. using (RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership))
  736. {
  737. RegistrySecurity accessRules = subKey.GetAccessControl();
  738. accessRules.SetOwner(RetrieveCurrentUserIdentifier());
  739. subKey.SetAccessControl(accessRules);
  740. }
  741. }
  742. internal static string GetNETFramework()
  743. {
  744. string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
  745. int netRelease;
  746. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
  747. {
  748. if (ndpKey != null && ndpKey.GetValue("Release") != null)
  749. {
  750. netRelease = (int)ndpKey.GetValue("Release");
  751. }
  752. else
  753. {
  754. return "4.0";
  755. }
  756. }
  757. if (netRelease >= 528040)
  758. return "4.8";
  759. if (netRelease >= 461808)
  760. return "4.7.2";
  761. if (netRelease >= 461308)
  762. return "4.7.1";
  763. if (netRelease >= 460798)
  764. return "4.7";
  765. if (netRelease >= 394802)
  766. return "4.6.2";
  767. if (netRelease >= 394254)
  768. return "4.6.1";
  769. if (netRelease >= 393295)
  770. return "4.6";
  771. if (netRelease >= 379893)
  772. return "4.5.2";
  773. if (netRelease >= 378675)
  774. return "4.5.1";
  775. if (netRelease >= 378389)
  776. return "4.5";
  777. return "4.0";
  778. }
  779. internal static void SearchWith(string term, bool ddg)
  780. {
  781. try
  782. {
  783. if (ddg) Process.Start(string.Format("https://duckduckgo.com/?q={0}", term));
  784. if (!ddg) Process.Start(string.Format("https://www.google.com/search?q={0}", term));
  785. }
  786. catch { }
  787. }
  788. internal static void PreventProcessFromRunning(string pName)
  789. {
  790. try
  791. {
  792. using (RegistryKey ifeo = Registry.LocalMachine.OpenSubKeyWritable(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
  793. {
  794. if (ifeo == null) return;
  795. ifeo.GrantFullControlOnSubKey("Image File Execution Options");
  796. using (RegistryKey k = ifeo.OpenSubKeyWritable("Image File Execution Options"))
  797. {
  798. if (k == null) return;
  799. k.CreateSubKey(pName);
  800. k.GrantFullControlOnSubKey(pName);
  801. using (RegistryKey f = k.OpenSubKeyWritable(pName))
  802. {
  803. if (f == null) return;
  804. f.SetValue("Debugger", @"%windir%\System32\taskkill.exe");
  805. }
  806. }
  807. }
  808. }
  809. catch (Exception ex)
  810. {
  811. ErrorLogger.LogError("Utilities.PreventProcessFromRunning", ex.Message, ex.StackTrace);
  812. }
  813. }
  814. }
  815. }