2
0

Program.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. /// <summary>
  13. /// Version properties. Do NOT leave them empty
  14. /// </summary>
  15. internal readonly static float Major = 16;
  16. internal readonly static float Minor = 7;
  17. internal readonly static bool EXPERIMENTAL_BUILD = false;
  18. internal static string GetCurrentVersionTostring()
  19. {
  20. return $"{Major.ToString()}.{Minor.ToString()}";
  21. }
  22. internal static float GetCurrentVersionToFloat()
  23. {
  24. return float.Parse(GetCurrentVersionTostring());
  25. }
  26. internal static bool SILENT_MODE = false;
  27. internal static int DPI_PREFERENCE;
  28. // Enables the corresponding Windows tab for Windows Server machines,
  29. // as well as the Advanced tweaks tab
  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 _confInvalidVersionMsg = "Windows version does not match!";
  37. static string _confInvalidFormatMsg = "Config file is in invalid format!";
  38. static string _confNotFoundMsg = "Config file does not exist!";
  39. static string _argInvalidMsg = "Invalid argument! Example: Optimizer.exe /config=win10.json";
  40. static string _alreadyRunningMsg = "Optimizer is already running in the background!";
  41. const string MUTEX_GUID = @"{DEADMOON-0EFC7B8A-D1FC-467F-B4B1-0117C643FE19-OPTIMIZER}";
  42. internal static Mutex MUTEX;
  43. static bool _notRunning;
  44. [System.Runtime.InteropServices.DllImport("user32.dll")]
  45. private static extern bool SetProcessDPIAware();
  46. [STAThread]
  47. static void Main(string[] switches)
  48. {
  49. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  50. AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
  51. EmbeddedAssembly.Load(_jsonAssembly, _jsonAssembly.Replace("Optimizer.", string.Empty));
  52. DPI_PREFERENCE = Convert.ToInt32(Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager", "LastLoadedDPI", "96"));
  53. if (DPI_PREFERENCE <= 0)
  54. {
  55. DPI_PREFERENCE = 96;
  56. }
  57. if (Environment.OSVersion.Version.Major >= 6) SetProcessDPIAware();
  58. Application.EnableVisualStyles();
  59. Application.SetCompatibleTextRenderingDefault(false);
  60. // single-instance mechanism
  61. MUTEX = new Mutex(true, MUTEX_GUID, out _notRunning);
  62. if (!_notRunning)
  63. {
  64. MessageBox.Show(_alreadyRunningMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  65. Environment.Exit(0);
  66. return;
  67. }
  68. if (!Utilities.IsAdmin())
  69. {
  70. string file = Process.GetCurrentProcess().MainModule.FileName;
  71. ProcessStartInfo p = new ProcessStartInfo(file);
  72. p.Verb = "runas";
  73. p.Arguments = string.Join(" ", switches);
  74. Process.Start(p);
  75. Environment.Exit(0);
  76. return;
  77. }
  78. if (!Utilities.IsCompatible())
  79. {
  80. HelperForm f = new HelperForm(null, MessageType.Error, _unsupportedMessage);
  81. f.ShowDialog();
  82. Environment.Exit(0);
  83. return;
  84. }
  85. CoreHelper.Deploy();
  86. FontHelper.LoadFont();
  87. if (switches.Length == 1)
  88. {
  89. string arg = switches[0].Trim().ToLowerInvariant();
  90. // UNSAFE mode switch (allows running on Windows Server 2008+)
  91. if (arg == "/unsafe")
  92. {
  93. UNSAFE_MODE = true;
  94. StartMainForm();
  95. return;
  96. }
  97. if (arg == "/repair")
  98. {
  99. Utilities.Repair(true);
  100. return;
  101. }
  102. if (arg == "/disablehpet")
  103. {
  104. Utilities.DisableHPET();
  105. Environment.Exit(0);
  106. return;
  107. }
  108. if (arg == "/enablehpet")
  109. {
  110. Utilities.EnableHPET();
  111. Environment.Exit(0);
  112. return;
  113. }
  114. // [!!!] unlock all cores instruction
  115. if (arg == "/unlockcores")
  116. {
  117. Utilities.UnlockAllCores();
  118. Environment.Exit(0);
  119. return;
  120. }
  121. if (arg.StartsWith("/svchostsplit="))
  122. {
  123. string x = arg.Replace("/svchostsplit=", string.Empty);
  124. bool isValid = !x.Any(c => !char.IsDigit(c));
  125. if (isValid && int.TryParse(x, out int result)) Utilities.DisableSvcHostProcessSplitting(result);
  126. Environment.Exit(0);
  127. return;
  128. }
  129. if (arg == "/resetsvchostsplit")
  130. {
  131. Utilities.EnableSvcHostProcessSplitting();
  132. Environment.Exit(0);
  133. return;
  134. }
  135. if (arg == "/version")
  136. {
  137. if (!EXPERIMENTAL_BUILD) MessageBox.Show($"Optimizer: {GetCurrentVersionTostring()}\n\nCoded by: deadmoon © ∞\n\nhttps://github.com/hellzerg/optimizer", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  138. 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);
  139. Environment.Exit(0);
  140. return;
  141. }
  142. // instruct to restart in safe-mode
  143. if (arg == "/restart=safemode")
  144. {
  145. RestartInSafeMode();
  146. }
  147. // instruct to restart normally
  148. if (arg == "/restart=normal")
  149. {
  150. RestartInNormalMode();
  151. }
  152. // disable defender automatically
  153. if (arg == "/restart=disabledefender")
  154. {
  155. SetRunOnceDisableDefender();
  156. }
  157. // enable defender automatically
  158. if (arg == "/restart=enabledefender")
  159. {
  160. SetRunOnceEnableDefender();
  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? o1, o2, o3, o4, o5, o6, o7, o8;
  187. if (opts.Contains(Constants.INDICIUM_TOOL)) o1 = true; else o1 = null;
  188. if (opts.Contains(Constants.UWP_TOOL)) o2 = true; else o2 = null;
  189. if (opts.Contains(Constants.APPS_TOOL)) o3 = true; else o3 = null;
  190. if (opts.Contains(Constants.HOSTS_EDITOR)) o4 = true; else o4 = null;
  191. if (opts.Contains(Constants.STARTUP_TOOL)) o5 = true; else o5 = null;
  192. if (opts.Contains(Constants.CLEANER_TOOL)) o6 = true; else o6 = null;
  193. if (opts.Contains(Constants.INTEGRATOR_TOOL)) o7 = true; else o7 = null;
  194. if (opts.Contains(Constants.PINGER_TOOL)) o8 = true; else o8 = null;
  195. StartMainForm(new bool?[] { o1, o2, o3, o4, o5, o6, o7, o8 });
  196. return;
  197. }
  198. if (arg.StartsWith("/config="))
  199. {
  200. UNSAFE_MODE = true;
  201. string fileName = arg.Replace("/config=", string.Empty);
  202. if (!File.Exists(fileName))
  203. {
  204. MessageBox.Show(_confNotFoundMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  205. Environment.Exit(0);
  206. return;
  207. }
  208. SilentOps.GetSilentConfig(fileName);
  209. if (SilentOps.CurrentSilentConfig == null)
  210. {
  211. MessageBox.Show(_confInvalidFormatMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  212. Environment.Exit(0);
  213. return;
  214. }
  215. if (!SilentOps.ProcessWindowsVersionCompatibility())
  216. {
  217. MessageBox.Show(_confInvalidVersionMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  218. Environment.Exit(0);
  219. return;
  220. }
  221. SILENT_MODE = true;
  222. LoadSettings();
  223. SilentOps.ProcessAllActions();
  224. OptionsHelper.SaveSettings();
  225. }
  226. }
  227. else
  228. {
  229. StartMainForm();
  230. }
  231. }
  232. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  233. {
  234. Exception error = (Exception)e.ExceptionObject;
  235. Logger.LogError("Program.Main-UnhandledException", error.Message, error.StackTrace);
  236. }
  237. private static void LoadSettings()
  238. {
  239. // for backward compatibility
  240. OptionsHelper.LegacyCheck();
  241. // load settings, if there is no settings, load defaults
  242. try
  243. {
  244. // show FirstRunForm/Language Selector if app is running first time
  245. if (!File.Exists(OptionsHelper.SettingsFile))
  246. {
  247. OptionsHelper.LoadSettings();
  248. if (!SILENT_MODE)
  249. {
  250. FirstRunForm frf = new FirstRunForm();
  251. frf.ShowDialog();
  252. }
  253. }
  254. else
  255. {
  256. OptionsHelper.LoadSettings();
  257. }
  258. //if (!Options.CurrentOptions.DisableOptimizerTelemetry)
  259. //{
  260. // TelemetryHelper.EnableTelemetryService();
  261. //}
  262. // ideal place to replace internal messages from translation list
  263. _adminMissingMessage = OptionsHelper.TranslationList["adminMissingMsg"];
  264. _unsupportedMessage = OptionsHelper.TranslationList["unsupportedMsg"];
  265. _confInvalidFormatMsg = OptionsHelper.TranslationList["confInvalidFormatMsg"];
  266. _confInvalidVersionMsg = OptionsHelper.TranslationList["confInvalidVersionMsg"];
  267. _confNotFoundMsg = OptionsHelper.TranslationList["confNotFoundMsg"];
  268. _argInvalidMsg = OptionsHelper.TranslationList["argInvalidMsg"];
  269. _alreadyRunningMsg = OptionsHelper.TranslationList["alreadyRunningMsg"];
  270. }
  271. catch (Exception ex)
  272. {
  273. Logger.LogError("Program.Main-LoadSettings", ex.Message, ex.StackTrace);
  274. Environment.Exit(0);
  275. }
  276. }
  277. internal static void RestartInSafeMode()
  278. {
  279. Utilities.RunCommand("bcdedit /set {current} safeboot Minimal");
  280. Thread.Sleep(500);
  281. Utilities.Reboot();
  282. Environment.Exit(0);
  283. }
  284. internal static void RestartInNormalMode()
  285. {
  286. Utilities.RunCommand("bcdedit /deletevalue {current} safeboot");
  287. Thread.Sleep(500);
  288. Utilities.Reboot();
  289. Environment.Exit(0);
  290. }
  291. private static void DisableDefenderInSafeMode()
  292. {
  293. File.WriteAllText("DisableDefenderSafeMode.bat", Properties.Resources.DisableDefenderSafeMode1903Plus);
  294. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  295. Thread.Sleep(1000);
  296. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  297. Thread.Sleep(1000);
  298. File.Delete("DisableDefenderSafeMode.bat");
  299. }
  300. private static void EnableDefenderInSafeMode()
  301. {
  302. File.WriteAllText("EnableDefenderSafeMode.bat", Properties.Resources.EnableDefenderSafeMode1903Plus);
  303. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  304. Thread.Sleep(1000);
  305. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  306. Thread.Sleep(1000);
  307. File.Delete("EnableDefenderSafeMode.bat");
  308. }
  309. internal static void SetRunOnceDisableDefender()
  310. {
  311. // set RunOnce instruction
  312. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerDisableDefender", Assembly.GetExecutingAssembly().Location + " /silentdisabledefender", Microsoft.Win32.RegistryValueKind.String);
  313. RestartInSafeMode();
  314. }
  315. internal static void SetRunOnceEnableDefender()
  316. {
  317. // set RunOnce instruction
  318. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerEnableDefender", Assembly.GetExecutingAssembly().Location + " /silentenabledefender", Microsoft.Win32.RegistryValueKind.String);
  319. RestartInSafeMode();
  320. }
  321. private static void StartMainForm()
  322. {
  323. LoadSettings();
  324. StartSplashForm();
  325. _MainForm = new MainForm(_SplashForm);
  326. _MainForm.Load += MainForm_Load;
  327. Application.Run(_MainForm);
  328. }
  329. private static void StartMainForm(bool?[] codes)
  330. {
  331. LoadSettings();
  332. StartSplashForm();
  333. _MainForm = new MainForm(_SplashForm, codes[0], codes[3], codes[2], codes[1], codes[4], codes[5], codes[6], codes[7]);
  334. _MainForm.Load += MainForm_Load;
  335. Application.Run(_MainForm);
  336. }
  337. private static void StartSplashForm()
  338. {
  339. _SplashForm = new SplashForm();
  340. var splashThread = new Thread(new ThreadStart(
  341. () => Application.Run(_SplashForm)));
  342. splashThread.SetApartmentState(ApartmentState.STA);
  343. splashThread.Start();
  344. }
  345. private static void MainForm_Load(object sender, EventArgs e)
  346. {
  347. if (_SplashForm != null && !_SplashForm.Disposing && !_SplashForm.IsDisposed)
  348. _SplashForm.Invoke(new Action(() => _SplashForm.Close()));
  349. _MainForm.TopMost = true;
  350. _MainForm.Activate();
  351. _MainForm.TopMost = false;
  352. }
  353. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  354. {
  355. return EmbeddedAssembly.Get(args.Name);
  356. }
  357. }
  358. }