Program.cs 22 KB

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