Program.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. for (int z = 0; z < switches.Length; z++) switches[z] = switches[z].ToLowerInvariant();
  110. // checking for silent config argument
  111. if (switches.Length == 1)
  112. {
  113. string arg = switches[0].Trim();
  114. // UNSAFE mode switch (allows running on Windows Server 2008+)
  115. if (arg == "/unsafe")
  116. {
  117. UNSAFE_MODE = true;
  118. StartSplashForm();
  119. _MainForm = new MainForm(_SplashForm);
  120. _MainForm.Load += MainForm_Load;
  121. Application.Run(_MainForm);
  122. return;
  123. }
  124. if (arg == "/disablehpet")
  125. {
  126. Utilities.DisableHPET();
  127. Environment.Exit(0);
  128. }
  129. if (arg == "/enablehpet")
  130. {
  131. Utilities.EnableHPET();
  132. Environment.Exit(0);
  133. }
  134. if (arg == "/addstartup")
  135. {
  136. Utilities.AddToStartup();
  137. Environment.Exit(0);
  138. }
  139. if (arg == "/deletestartup")
  140. {
  141. Utilities.DeleteFromStartup();
  142. Environment.Exit(0);
  143. }
  144. // [!!!] unlock all cores instruction
  145. if (arg == "/unlockcores")
  146. {
  147. Utilities.UnlockAllCores();
  148. Environment.Exit(0);
  149. }
  150. // resets configuration
  151. if (arg == "/reset")
  152. {
  153. Utilities.ResetConfiguration(true);
  154. return;
  155. }
  156. // displays build info
  157. if (arg == "/version")
  158. {
  159. if (!EXPERIMENTAL_BUILD) MessageBox.Show($"Optimizer: {GetCurrentVersionTostring()}\n\nCoded by: deadmoon © ∞\n\nhttps://github.com/hellzerg/optimizer", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  160. 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);
  161. Environment.Exit(0);
  162. }
  163. // hibernation switches
  164. if (arg == "/disablehibernate")
  165. {
  166. Utilities.DisableHibernation();
  167. Environment.Exit(0);
  168. }
  169. if (arg == "/enablehibernate")
  170. {
  171. Utilities.EnableHibernation();
  172. Environment.Exit(0);
  173. }
  174. // instruct to restart in safe-mode
  175. if (arg == "/restart=safemode")
  176. {
  177. RestartInSafeMode();
  178. }
  179. // instruct to restart normally
  180. if (arg == "/restart=normal")
  181. {
  182. RestartInNormalMode();
  183. }
  184. // disable defender automatically
  185. if (arg == "/restart=disabledefender")
  186. {
  187. // set RunOnce instruction
  188. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerDisableDefender", Assembly.GetExecutingAssembly().Location + " /silentdisabledefender", Microsoft.Win32.RegistryValueKind.String);
  189. RestartInSafeMode();
  190. }
  191. // enable defender automatically
  192. if (arg == "/restart=enabledefender")
  193. {
  194. // set RunOnce instruction
  195. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerEnableDefender", Assembly.GetExecutingAssembly().Location + " /silentenabledefender", Microsoft.Win32.RegistryValueKind.String);
  196. RestartInSafeMode();
  197. }
  198. // return from safe-mode automatically
  199. if (arg == "/silentdisabledefender")
  200. {
  201. DisableDefenderInSafeMode();
  202. RestartInNormalMode();
  203. }
  204. if (arg == "/silentenabledefender")
  205. {
  206. EnableDefenderInSafeMode();
  207. RestartInNormalMode();
  208. }
  209. // other options for disabling specific tools
  210. if (arg.StartsWith("/disable="))
  211. {
  212. string x = arg.Replace("/disable=", string.Empty);
  213. string[] opts = x.Split(',');
  214. bool disableIndicium = opts.Contains("indicium");
  215. bool disableUWPTool = opts.Contains("uwp");
  216. bool disableAppsTool = opts.Contains("apps");
  217. bool disableHostsEditor = opts.Contains("hosts");
  218. bool disableStartupTool = opts.Contains("startup");
  219. bool disableCleaner = opts.Contains("cleaner");
  220. bool disableIntegrator = opts.Contains("integrator");
  221. bool disablePinger = opts.Contains("pinger");
  222. StartSplashForm();
  223. _MainForm = new MainForm(_SplashForm, disableIndicium, disableHostsEditor, disableAppsTool, disableUWPTool, disableStartupTool, disableCleaner, disableIntegrator, disablePinger);
  224. _MainForm.Load += MainForm_Load;
  225. Application.Run(_MainForm);
  226. return;
  227. }
  228. // disables Defender in SAFE MODE (for Windows 10 1903+ / works in Windows 11 as well)
  229. if (arg == "/disabledefender")
  230. {
  231. DisableDefenderInSafeMode();
  232. MessageBox.Show("Windows Defender has been completely disabled successfully.", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  233. Environment.Exit(0);
  234. return;
  235. }
  236. if (arg.StartsWith("/"))
  237. {
  238. if (File.Exists(arg.Remove(0, 1)))
  239. {
  240. SilentOps.GetSilentConfig(arg.Remove(0, 1));
  241. if (SilentOps.CurrentSilentConfig != null)
  242. {
  243. if (SilentOps.CurrentSilentConfig.WindowsVersion == 7 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows7)
  244. {
  245. SilentOps.ProcessSilentConfigGeneral();
  246. SilentOps.SilentUpdateOptionsGeneral();
  247. Options.SaveSettings();
  248. }
  249. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 8 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows8)
  250. {
  251. SilentOps.ProcessSilentConfigGeneral();
  252. SilentOps.ProcessSilentConfigWindows8();
  253. SilentOps.SilentUpdateOptionsGeneral();
  254. SilentOps.SilentUpdateOptions8();
  255. Options.SaveSettings();
  256. }
  257. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 10 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows10)
  258. {
  259. SilentOps.ProcessSilentConfigGeneral();
  260. SilentOps.ProcessSilentConfigWindows10();
  261. SilentOps.SilentUpdateOptionsGeneral();
  262. SilentOps.SilentUpdateOptions10();
  263. Options.SaveSettings();
  264. }
  265. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 11 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows11)
  266. {
  267. SilentOps.ProcessSilentConfigGeneral();
  268. SilentOps.ProcessSilentConfigWindows10();
  269. SilentOps.ProcessSilentConfigWindows11();
  270. SilentOps.SilentUpdateOptionsGeneral();
  271. SilentOps.SilentUpdateOptions10();
  272. SilentOps.SilentUpdateOptions11();
  273. Options.SaveSettings();
  274. }
  275. else
  276. {
  277. MessageBox.Show(_confInvalidVersionMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  278. Environment.Exit(0);
  279. }
  280. }
  281. else
  282. {
  283. MessageBox.Show(_confInvalidFormatMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  284. Environment.Exit(0);
  285. }
  286. }
  287. else
  288. {
  289. MessageBox.Show(_confNotFoundMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  290. Environment.Exit(0);
  291. }
  292. }
  293. else
  294. {
  295. MessageBox.Show(_argInvalidMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  296. Environment.Exit(0);
  297. }
  298. }
  299. else
  300. {
  301. StartSplashForm();
  302. _MainForm = new MainForm(_SplashForm);
  303. _MainForm.Load += MainForm_Load;
  304. Application.Run(_MainForm);
  305. }
  306. }
  307. else
  308. {
  309. HelperForm f = new HelperForm(null, MessageType.Error, _unsupportedMessage);
  310. f.ShowDialog();
  311. Environment.Exit(0);
  312. }
  313. }
  314. }
  315. }
  316. }
  317. //internal static void ForceExit()
  318. //{
  319. // Environment.Exit(0);
  320. //}
  321. private static void RestartInSafeMode()
  322. {
  323. Utilities.RunCommand("bcdedit /set {current} safeboot Minimal");
  324. Thread.Sleep(500);
  325. Utilities.Reboot();
  326. Environment.Exit(0);
  327. }
  328. private static void RestartInNormalMode()
  329. {
  330. Utilities.RunCommand("bcdedit /deletevalue {current} safeboot");
  331. Thread.Sleep(500);
  332. Utilities.Reboot();
  333. Environment.Exit(0);
  334. }
  335. private static void DisableDefenderInSafeMode()
  336. {
  337. File.WriteAllText("DisableDefenderSafeMode.bat", Properties.Resources.DisableDefenderSafeMode1903Plus);
  338. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  339. Thread.Sleep(1000);
  340. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  341. Thread.Sleep(1000);
  342. File.Delete("DisableDefenderSafeMode.bat");
  343. }
  344. private static void EnableDefenderInSafeMode()
  345. {
  346. File.WriteAllText("EnableDefenderSafeMode.bat", Properties.Resources.EnableDefenderSafeMode1903Plus);
  347. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  348. Thread.Sleep(1000);
  349. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  350. Thread.Sleep(1000);
  351. File.Delete("EnableDefenderSafeMode.bat");
  352. }
  353. private static void StartSplashForm()
  354. {
  355. _SplashForm = new SplashForm();
  356. var splashThread = new Thread(new ThreadStart(
  357. () => Application.Run(_SplashForm)));
  358. splashThread.SetApartmentState(ApartmentState.STA);
  359. splashThread.Start();
  360. }
  361. private static void MainForm_Load(object sender, EventArgs e)
  362. {
  363. if (_SplashForm != null && !_SplashForm.Disposing && !_SplashForm.IsDisposed)
  364. _SplashForm.Invoke(new Action(() => _SplashForm.Close()));
  365. _MainForm.TopMost = true;
  366. _MainForm.Activate();
  367. _MainForm.TopMost = false;
  368. }
  369. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  370. {
  371. return EmbeddedAssembly.Get(args.Name);
  372. }
  373. }
  374. }