Program.cs 17 KB

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