Program.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading;
  6. using System.Windows.Forms;
  7. namespace Optimizer
  8. {
  9. static class Program
  10. {
  11. /* VERSION PROPERTIES */
  12. /* DO NOT LEAVE THEM EMPTY */
  13. internal readonly static float Major = 13;
  14. internal readonly static float Minor = 8;
  15. internal readonly static bool EXPERIMENTAL_BUILD = false;
  16. internal static string GetCurrentVersionTostring()
  17. {
  18. return Major.ToString() + "." + Minor.ToString();
  19. }
  20. internal static float GetCurrentVersion()
  21. {
  22. return float.Parse(GetCurrentVersionTostring());
  23. }
  24. /* END OF VERSION PROPERTIES */
  25. // Enables the corresponding Windows tab for Windows Server machines
  26. internal static bool UNSAFE_MODE = false;
  27. const string _jsonAssembly = @"Optimizer.Newtonsoft.Json.dll";
  28. internal static MainForm _MainForm;
  29. internal static SplashForm _SplashForm;
  30. static string _adminMissingMessage = "Optimizer needs to be run as administrator!\nApp will now close...";
  31. static string _unsupportedMessage = "Optimizer works in Windows 7 or higher!\nApp will now close...";
  32. //static string _renameAppMessage = "It's recommended to rename the app from '{0}' to 'Optimizer' for a better experience.\n\nApp will now close...";
  33. static string _confInvalidVersionMsg = "Windows version does not match!";
  34. static string _confInvalidFormatMsg = "Config file is in invalid format!";
  35. static string _confNotFoundMsg = "Config file does not exist!";
  36. static string _argInvalidMsg = "Invalid argument! Example: Optimizer.exe /silent.conf";
  37. static string _alreadyRunningMsg = "Optimizer is already running in the background!";
  38. const string MUTEX_GUID = @"{DEADMOON-0EFC7B8A-D1FC-467F-B4B1-0117C643FE19-OPTIMIZER}";
  39. internal static Mutex MUTEX;
  40. static bool _notRunning;
  41. [System.Runtime.InteropServices.DllImport("user32.dll")]
  42. private static extern bool SetProcessDPIAware();
  43. [STAThread]
  44. static void Main(string[] switches)
  45. {
  46. EmbeddedAssembly.Load(_jsonAssembly, _jsonAssembly.Replace("Optimizer.", string.Empty));
  47. AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
  48. if (Environment.OSVersion.Version.Major >= 6) SetProcessDPIAware();
  49. Application.EnableVisualStyles();
  50. Application.SetCompatibleTextRenderingDefault(false);
  51. // prompt to change filename to 'Optimizer' (skip if experimental build)
  52. // annoying?
  53. //if (!EXPERIMENTAL_BUILD && Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location) != "Optimizer")
  54. //{
  55. // MessageBox.Show(string.Format(_renameAppMessage, Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)), "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  56. // Environment.Exit(0);
  57. //}
  58. // single-instance mechanism
  59. using (MUTEX = new Mutex(true, MUTEX_GUID, out _notRunning))
  60. {
  61. if (!_notRunning)
  62. {
  63. MessageBox.Show(_alreadyRunningMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  64. Environment.Exit(0);
  65. }
  66. else
  67. {
  68. if (!Utilities.IsAdmin())
  69. {
  70. HelperForm f = new HelperForm(null, MessageType.Error, _adminMissingMessage);
  71. f.ShowDialog();
  72. Environment.Exit(0);
  73. }
  74. else
  75. {
  76. if (Utilities.IsCompatible())
  77. {
  78. Required.Deploy();
  79. // for backward compatibility (legacy)
  80. Options.LegacyCheck();
  81. // load settings, if there is no settings, load defaults
  82. try
  83. {
  84. // show FirstRunForm/Language Selector if app is running first time
  85. if (!File.Exists(Options.SettingsFile))
  86. {
  87. Options.LoadSettings();
  88. FirstRunForm frf = new FirstRunForm();
  89. frf.ShowDialog();
  90. }
  91. else
  92. {
  93. Options.LoadSettings();
  94. }
  95. // ideal place to replace internal messages from translation list
  96. _adminMissingMessage = Options.TranslationList["adminMissingMsg"];
  97. _unsupportedMessage = Options.TranslationList["unsupportedMsg"];
  98. _confInvalidFormatMsg = Options.TranslationList["confInvalidFormatMsg"];
  99. _confInvalidVersionMsg = Options.TranslationList["confInvalidVersionMsg"];
  100. _confNotFoundMsg = Options.TranslationList["confNotFoundMsg"];
  101. _argInvalidMsg = Options.TranslationList["argInvalidMsg"];
  102. _alreadyRunningMsg = Options.TranslationList["alreadyRunningMsg"];
  103. }
  104. catch (Exception ex)
  105. {
  106. ErrorLogger.LogError("Program.Main", ex.Message, ex.StackTrace);
  107. Environment.Exit(0);
  108. }
  109. FontHelper.LoadFont();
  110. for (int z = 0; z < switches.Length; z++) switches[z] = switches[z].ToLowerInvariant();
  111. // checking for silent config argument
  112. if (switches.Length == 1)
  113. {
  114. string arg = switches[0].Trim();
  115. // UNSAFE mode switch (allows running on Windows Server 2008+)
  116. if (arg == "/unsafe")
  117. {
  118. UNSAFE_MODE = true;
  119. StartSplashForm();
  120. _MainForm = new MainForm(_SplashForm);
  121. _MainForm.Load += MainForm_Load;
  122. Application.Run(_MainForm);
  123. return;
  124. }
  125. if (arg == "/disablehpet")
  126. {
  127. Utilities.DisableHPET();
  128. Environment.Exit(0);
  129. }
  130. if (arg == "/enablehpet")
  131. {
  132. Utilities.EnableHPET();
  133. Environment.Exit(0);
  134. }
  135. if (arg == "/addstartup")
  136. {
  137. Utilities.AddToStartup();
  138. Environment.Exit(0);
  139. }
  140. if (arg == "/deletestartup")
  141. {
  142. Utilities.DeleteFromStartup();
  143. Environment.Exit(0);
  144. }
  145. // [!!!] unlock all cores instruction
  146. if (arg == "/unlockcores")
  147. {
  148. Utilities.UnlockAllCores();
  149. Environment.Exit(0);
  150. }
  151. // resets configuration
  152. if (arg == "/reset")
  153. {
  154. Utilities.ResetConfiguration(true);
  155. return;
  156. }
  157. // displays build info
  158. if (arg == "/version")
  159. {
  160. if (!EXPERIMENTAL_BUILD) MessageBox.Show($"Optimizer: {GetCurrentVersionTostring()}\n\nCoded by: deadmoon © ∞\n\nhttps://github.com/hellzerg/optimizer", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  161. else MessageBox.Show("Optimizer: EXPERIMENTAL BUILD. PLEASE DELETE AFTER TESTING.\n\nCoded by: deadmoon © ∞\n\nhttps://github.com/hellzerg/optimizer", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  162. Environment.Exit(0);
  163. }
  164. // hibernation switches
  165. if (arg == "/disablehibernate")
  166. {
  167. Utilities.DisableHibernation();
  168. Environment.Exit(0);
  169. }
  170. if (arg == "/enablehibernate")
  171. {
  172. Utilities.EnableHibernation();
  173. Environment.Exit(0);
  174. }
  175. // instruct to restart in safe-mode
  176. if (arg == "/restart=safemode")
  177. {
  178. RestartInSafeMode();
  179. }
  180. // instruct to restart normally
  181. if (arg == "/restart=normal")
  182. {
  183. RestartInNormalMode();
  184. }
  185. // disable defender automatically
  186. if (arg == "/restart=disabledefender")
  187. {
  188. // set RunOnce instruction
  189. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerDisableDefender", Assembly.GetExecutingAssembly().Location + " /silentdisabledefender", Microsoft.Win32.RegistryValueKind.String);
  190. RestartInSafeMode();
  191. }
  192. // enable defender automatically
  193. if (arg == "/restart=enabledefender")
  194. {
  195. // set RunOnce instruction
  196. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerEnableDefender", Assembly.GetExecutingAssembly().Location + " /silentenabledefender", Microsoft.Win32.RegistryValueKind.String);
  197. RestartInSafeMode();
  198. }
  199. // return from safe-mode automatically
  200. if (arg == "/silentdisabledefender")
  201. {
  202. DisableDefenderInSafeMode();
  203. RestartInNormalMode();
  204. }
  205. if (arg == "/silentenabledefender")
  206. {
  207. EnableDefenderInSafeMode();
  208. RestartInNormalMode();
  209. }
  210. // other options for disabling specific tools
  211. if (arg.StartsWith("/disable="))
  212. {
  213. string x = arg.Replace("/disable=", string.Empty);
  214. string[] opts = x.Split(',');
  215. bool disableIndicium = opts.Contains("indicium");
  216. bool disableUWPTool = opts.Contains("uwp");
  217. bool disableAppsTool = opts.Contains("apps");
  218. bool disableHostsEditor = opts.Contains("hosts");
  219. bool disableStartupTool = opts.Contains("startup");
  220. bool disableCleaner = opts.Contains("cleaner");
  221. bool disableIntegrator = opts.Contains("integrator");
  222. bool disablePinger = opts.Contains("pinger");
  223. StartSplashForm();
  224. _MainForm = new MainForm(_SplashForm, disableIndicium, disableHostsEditor, disableAppsTool, disableUWPTool, disableStartupTool, disableCleaner, disableIntegrator, disablePinger);
  225. _MainForm.Load += MainForm_Load;
  226. Application.Run(_MainForm);
  227. return;
  228. }
  229. // disables Defender in SAFE MODE (for Windows 10 1903+ / works in Windows 11 as well)
  230. if (arg == "/disabledefender")
  231. {
  232. DisableDefenderInSafeMode();
  233. MessageBox.Show("Windows Defender has been completely disabled successfully.", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  234. Environment.Exit(0);
  235. return;
  236. }
  237. if (arg.StartsWith("/"))
  238. {
  239. if (File.Exists(arg.Remove(0, 1)))
  240. {
  241. SilentOps.GetSilentConfig(arg.Remove(0, 1));
  242. if (SilentOps.CurrentSilentConfig != null)
  243. {
  244. if (SilentOps.CurrentSilentConfig.WindowsVersion == 7 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows7)
  245. {
  246. SilentOps.ProcessSilentConfigGeneral();
  247. SilentOps.SilentUpdateOptionsGeneral();
  248. Options.SaveSettings();
  249. }
  250. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 8 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows8)
  251. {
  252. SilentOps.ProcessSilentConfigGeneral();
  253. SilentOps.ProcessSilentConfigWindows8();
  254. SilentOps.SilentUpdateOptionsGeneral();
  255. SilentOps.SilentUpdateOptions8();
  256. Options.SaveSettings();
  257. }
  258. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 10 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows10)
  259. {
  260. SilentOps.ProcessSilentConfigGeneral();
  261. SilentOps.ProcessSilentConfigWindows10();
  262. SilentOps.SilentUpdateOptionsGeneral();
  263. SilentOps.SilentUpdateOptions10();
  264. Options.SaveSettings();
  265. }
  266. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 11 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows11)
  267. {
  268. SilentOps.ProcessSilentConfigGeneral();
  269. SilentOps.ProcessSilentConfigWindows10();
  270. SilentOps.ProcessSilentConfigWindows11();
  271. SilentOps.SilentUpdateOptionsGeneral();
  272. SilentOps.SilentUpdateOptions10();
  273. SilentOps.SilentUpdateOptions11();
  274. Options.SaveSettings();
  275. }
  276. else
  277. {
  278. MessageBox.Show(_confInvalidVersionMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  279. Environment.Exit(0);
  280. }
  281. }
  282. else
  283. {
  284. MessageBox.Show(_confInvalidFormatMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  285. Environment.Exit(0);
  286. }
  287. }
  288. else
  289. {
  290. MessageBox.Show(_confNotFoundMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  291. Environment.Exit(0);
  292. }
  293. }
  294. else
  295. {
  296. MessageBox.Show(_argInvalidMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  297. Environment.Exit(0);
  298. }
  299. }
  300. else
  301. {
  302. StartSplashForm();
  303. _MainForm = new MainForm(_SplashForm);
  304. _MainForm.Load += MainForm_Load;
  305. Application.Run(_MainForm);
  306. }
  307. }
  308. else
  309. {
  310. HelperForm f = new HelperForm(null, MessageType.Error, _unsupportedMessage);
  311. f.ShowDialog();
  312. Environment.Exit(0);
  313. }
  314. }
  315. }
  316. }
  317. }
  318. //internal static void ForceExit()
  319. //{
  320. // Environment.Exit(0);
  321. //}
  322. private static void RestartInSafeMode()
  323. {
  324. Utilities.RunCommand("bcdedit /set {current} safeboot Minimal");
  325. Thread.Sleep(500);
  326. Utilities.Reboot();
  327. Environment.Exit(0);
  328. }
  329. private static void RestartInNormalMode()
  330. {
  331. Utilities.RunCommand("bcdedit /deletevalue {current} safeboot");
  332. Thread.Sleep(500);
  333. Utilities.Reboot();
  334. Environment.Exit(0);
  335. }
  336. private static void DisableDefenderInSafeMode()
  337. {
  338. File.WriteAllText("DisableDefenderSafeMode.bat", Properties.Resources.DisableDefenderSafeMode1903Plus);
  339. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  340. Thread.Sleep(1000);
  341. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  342. Thread.Sleep(1000);
  343. File.Delete("DisableDefenderSafeMode.bat");
  344. }
  345. private static void EnableDefenderInSafeMode()
  346. {
  347. File.WriteAllText("EnableDefenderSafeMode.bat", Properties.Resources.EnableDefenderSafeMode1903Plus);
  348. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  349. Thread.Sleep(1000);
  350. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  351. Thread.Sleep(1000);
  352. File.Delete("EnableDefenderSafeMode.bat");
  353. }
  354. private static void StartSplashForm()
  355. {
  356. _SplashForm = new SplashForm();
  357. var splashThread = new Thread(new ThreadStart(
  358. () => Application.Run(_SplashForm)));
  359. splashThread.SetApartmentState(ApartmentState.STA);
  360. splashThread.Start();
  361. }
  362. private static void MainForm_Load(object sender, EventArgs e)
  363. {
  364. if (_SplashForm != null && !_SplashForm.Disposing && !_SplashForm.IsDisposed)
  365. _SplashForm.Invoke(new Action(() => _SplashForm.Close()));
  366. _MainForm.TopMost = true;
  367. _MainForm.Activate();
  368. _MainForm.TopMost = false;
  369. }
  370. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  371. {
  372. return EmbeddedAssembly.Get(args.Name);
  373. }
  374. }
  375. }