Program.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 = 15;
  15. internal readonly static float Minor = 0;
  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. // single-instance mechanism
  55. MUTEX = new Mutex(true, MUTEX_GUID, out _notRunning);
  56. if (!_notRunning)
  57. {
  58. MessageBox.Show(_alreadyRunningMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  59. Environment.Exit(0);
  60. return;
  61. }
  62. if (!Utilities.IsAdmin())
  63. {
  64. string file = Process.GetCurrentProcess().MainModule.FileName;
  65. ProcessStartInfo p = new ProcessStartInfo(file);
  66. p.Verb = "runas";
  67. p.Arguments = string.Join(" ", switches);
  68. Process.Start(p);
  69. Environment.Exit(0);
  70. return;
  71. }
  72. if (!Utilities.IsCompatible())
  73. {
  74. HelperForm f = new HelperForm(null, MessageType.Error, _unsupportedMessage);
  75. f.ShowDialog();
  76. Environment.Exit(0);
  77. return;
  78. }
  79. Required.Deploy();
  80. FontHelper.LoadFont();
  81. if (switches.Length == 1)
  82. {
  83. string arg = switches[0].Trim().ToLowerInvariant();
  84. // UNSAFE mode switch (allows running on Windows Server 2008+)
  85. if (arg == "/unsafe")
  86. {
  87. UNSAFE_MODE = true;
  88. StartMainForm();
  89. return;
  90. }
  91. if (arg == "/disablehpet")
  92. {
  93. Utilities.DisableHPET();
  94. Environment.Exit(0);
  95. return;
  96. }
  97. if (arg == "/enablehpet")
  98. {
  99. Utilities.EnableHPET();
  100. Environment.Exit(0);
  101. return;
  102. }
  103. // [!!!] unlock all cores instruction
  104. if (arg == "/unlockcores")
  105. {
  106. Utilities.UnlockAllCores();
  107. Environment.Exit(0);
  108. return;
  109. }
  110. if (arg == "/repair")
  111. {
  112. Utilities.Repair(true);
  113. return;
  114. }
  115. if (arg == "/version")
  116. {
  117. if (!EXPERIMENTAL_BUILD) MessageBox.Show($"Optimizer: {GetCurrentVersionTostring()}\n\nCoded by: deadmoon © ∞\n\nhttps://github.com/hellzerg/optimizer", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  118. 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);
  119. Environment.Exit(0);
  120. return;
  121. }
  122. // instruct to restart in safe-mode
  123. if (arg == "/restart=safemode")
  124. {
  125. RestartInSafeMode();
  126. }
  127. // instruct to restart normally
  128. if (arg == "/restart=normal")
  129. {
  130. RestartInNormalMode();
  131. }
  132. // disable defender automatically
  133. if (arg == "/restart=disabledefender")
  134. {
  135. // set RunOnce instruction
  136. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerDisableDefender", Assembly.GetExecutingAssembly().Location + " /silentdisabledefender", Microsoft.Win32.RegistryValueKind.String);
  137. RestartInSafeMode();
  138. }
  139. // enable defender automatically
  140. if (arg == "/restart=enabledefender")
  141. {
  142. // set RunOnce instruction
  143. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerEnableDefender", Assembly.GetExecutingAssembly().Location + " /silentenabledefender", Microsoft.Win32.RegistryValueKind.String);
  144. RestartInSafeMode();
  145. }
  146. // return from safe-mode automatically
  147. if (arg == "/silentdisabledefender")
  148. {
  149. DisableDefenderInSafeMode();
  150. RestartInNormalMode();
  151. }
  152. if (arg == "/silentenabledefender")
  153. {
  154. EnableDefenderInSafeMode();
  155. RestartInNormalMode();
  156. }
  157. // disables Defender in SAFE MODE (for Windows 10 1903+ / works in Windows 11 as well)
  158. if (arg == "/disabledefender")
  159. {
  160. DisableDefenderInSafeMode();
  161. MessageBox.Show("Windows Defender has been completely disabled successfully.", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  162. Environment.Exit(0);
  163. return;
  164. }
  165. // other options for disabling specific tools
  166. if (arg.StartsWith("/disable="))
  167. {
  168. string x = arg.Replace("/disable=", string.Empty);
  169. string[] opts = x.Split(',');
  170. bool[] codes =
  171. {
  172. opts.Contains("indicium"),
  173. opts.Contains("uwp"),
  174. opts.Contains("apps"),
  175. opts.Contains("hosts"),
  176. opts.Contains("startup"),
  177. opts.Contains("cleaner"),
  178. opts.Contains("integrator"),
  179. opts.Contains("pinger")
  180. };
  181. StartMainForm(codes);
  182. return;
  183. }
  184. if (arg.StartsWith("/config="))
  185. {
  186. string fileName = arg.Replace("/config=", string.Empty);
  187. if (!File.Exists(fileName))
  188. {
  189. MessageBox.Show(_confNotFoundMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  190. Environment.Exit(0);
  191. return;
  192. }
  193. SilentOps.GetSilentConfig(fileName);
  194. if (SilentOps.CurrentSilentConfig == null)
  195. {
  196. MessageBox.Show(_confInvalidFormatMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  197. Environment.Exit(0);
  198. return;
  199. }
  200. if (SilentOps.CurrentSilentConfig.WindowsVersion == 7 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows7)
  201. {
  202. LoadSettings();
  203. SilentOps.ProcessSilentConfigGeneral();
  204. SilentOps.SilentUpdateOptionsGeneral();
  205. Options.SaveSettings();
  206. }
  207. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 8 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows8)
  208. {
  209. LoadSettings();
  210. SilentOps.ProcessSilentConfigGeneral();
  211. SilentOps.ProcessSilentConfigWindows8();
  212. SilentOps.SilentUpdateOptionsGeneral();
  213. SilentOps.SilentUpdateOptions8();
  214. Options.SaveSettings();
  215. }
  216. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 10 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows10)
  217. {
  218. LoadSettings();
  219. SilentOps.ProcessSilentConfigGeneral();
  220. SilentOps.ProcessSilentConfigWindows10();
  221. SilentOps.SilentUpdateOptionsGeneral();
  222. SilentOps.SilentUpdateOptions10();
  223. Options.SaveSettings();
  224. }
  225. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 11 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows11)
  226. {
  227. LoadSettings();
  228. SilentOps.ProcessSilentConfigGeneral();
  229. SilentOps.ProcessSilentConfigWindows10();
  230. SilentOps.ProcessSilentConfigWindows11();
  231. SilentOps.SilentUpdateOptionsGeneral();
  232. SilentOps.SilentUpdateOptions10();
  233. SilentOps.SilentUpdateOptions11();
  234. Options.SaveSettings();
  235. }
  236. else
  237. {
  238. MessageBox.Show(_confInvalidVersionMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  239. Environment.Exit(0);
  240. }
  241. }
  242. }
  243. else
  244. {
  245. StartMainForm();
  246. }
  247. }
  248. private static void LoadSettings()
  249. {
  250. // for backward compatibility (legacy)
  251. Options.LegacyCheck();
  252. // load settings, if there is no settings, load defaults
  253. try
  254. {
  255. // show FirstRunForm/Language Selector if app is running first time
  256. if (!File.Exists(Options.SettingsFile))
  257. {
  258. Options.LoadSettings();
  259. FirstRunForm frf = new FirstRunForm();
  260. frf.ShowDialog();
  261. }
  262. else
  263. {
  264. Options.LoadSettings();
  265. }
  266. //if (!Options.CurrentOptions.DisableOptimizerTelemetry)
  267. //{
  268. // TelemetryHelper.EnableTelemetryService();
  269. //}
  270. // ideal place to replace internal messages from translation list
  271. _adminMissingMessage = Options.TranslationList["adminMissingMsg"];
  272. _unsupportedMessage = Options.TranslationList["unsupportedMsg"];
  273. _confInvalidFormatMsg = Options.TranslationList["confInvalidFormatMsg"];
  274. _confInvalidVersionMsg = Options.TranslationList["confInvalidVersionMsg"];
  275. _confNotFoundMsg = Options.TranslationList["confNotFoundMsg"];
  276. _argInvalidMsg = Options.TranslationList["argInvalidMsg"];
  277. _alreadyRunningMsg = Options.TranslationList["alreadyRunningMsg"];
  278. }
  279. catch (Exception ex)
  280. {
  281. ErrorLogger.LogError("Program.Main-LoadSettings", ex.Message, ex.StackTrace);
  282. Environment.Exit(0);
  283. }
  284. }
  285. internal static void RestartInSafeMode()
  286. {
  287. Utilities.RunCommand("bcdedit /set {current} safeboot Minimal");
  288. Thread.Sleep(500);
  289. Utilities.Reboot();
  290. Environment.Exit(0);
  291. }
  292. internal static void RestartInNormalMode()
  293. {
  294. Utilities.RunCommand("bcdedit /deletevalue {current} safeboot");
  295. Thread.Sleep(500);
  296. Utilities.Reboot();
  297. Environment.Exit(0);
  298. }
  299. private static void DisableDefenderInSafeMode()
  300. {
  301. File.WriteAllText("DisableDefenderSafeMode.bat", Properties.Resources.DisableDefenderSafeMode1903Plus);
  302. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  303. Thread.Sleep(1000);
  304. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  305. Thread.Sleep(1000);
  306. File.Delete("DisableDefenderSafeMode.bat");
  307. }
  308. private static void EnableDefenderInSafeMode()
  309. {
  310. File.WriteAllText("EnableDefenderSafeMode.bat", Properties.Resources.EnableDefenderSafeMode1903Plus);
  311. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  312. Thread.Sleep(1000);
  313. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  314. Thread.Sleep(1000);
  315. File.Delete("EnableDefenderSafeMode.bat");
  316. }
  317. private static void StartMainForm()
  318. {
  319. LoadSettings();
  320. StartSplashForm();
  321. _MainForm = new MainForm(_SplashForm);
  322. _MainForm.Load += MainForm_Load;
  323. Application.Run(_MainForm);
  324. }
  325. private static void StartMainForm(bool[] codes)
  326. {
  327. LoadSettings();
  328. StartSplashForm();
  329. _MainForm = new MainForm(_SplashForm, codes[0], codes[3], codes[2], codes[1], codes[4], codes[5], codes[6], codes[7]);
  330. _MainForm.Load += MainForm_Load;
  331. Application.Run(_MainForm);
  332. }
  333. private static void StartSplashForm()
  334. {
  335. _SplashForm = new SplashForm();
  336. var splashThread = new Thread(new ThreadStart(
  337. () => Application.Run(_SplashForm)));
  338. splashThread.SetApartmentState(ApartmentState.STA);
  339. splashThread.Start();
  340. }
  341. private static void MainForm_Load(object sender, EventArgs e)
  342. {
  343. if (_SplashForm != null && !_SplashForm.Disposing && !_SplashForm.IsDisposed)
  344. _SplashForm.Invoke(new Action(() => _SplashForm.Close()));
  345. _MainForm.TopMost = true;
  346. _MainForm.Activate();
  347. _MainForm.TopMost = false;
  348. }
  349. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  350. {
  351. return EmbeddedAssembly.Get(args.Name);
  352. }
  353. }
  354. }