Program.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 = 5;
  16. internal readonly static bool EXPERIMENTAL_BUILD = false;
  17. internal static bool SILENT_MODE = false;
  18. internal static int DPI_PREFERENCE;
  19. internal static string GetCurrentVersionTostring()
  20. {
  21. return Major.ToString() + "." + Minor.ToString();
  22. }
  23. internal static float GetCurrentVersion()
  24. {
  25. return float.Parse(GetCurrentVersionTostring());
  26. }
  27. /* END OF VERSION PROPERTIES */
  28. // Enables the corresponding Windows tab for Windows Server machines
  29. internal static bool UNSAFE_MODE = false;
  30. const string _jsonAssembly = @"Optimizer.Newtonsoft.Json.dll";
  31. internal static MainForm _MainForm;
  32. internal static SplashForm _SplashForm;
  33. static string _adminMissingMessage = "Optimizer needs to be run as administrator!\nApp will now close...";
  34. static string _unsupportedMessage = "Optimizer works with Windows 7 and higher!\nApp will now close...";
  35. //static string _renameAppMessage = "It's recommended to rename the app from '{0}' to 'Optimizer' for a better experience.\n\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.conf";
  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. EmbeddedAssembly.Load(_jsonAssembly, _jsonAssembly.Replace("Optimizer.", string.Empty));
  50. AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
  51. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  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. CoreHelper.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 == "/repair")
  94. {
  95. Utilities.Repair(true);
  96. return;
  97. }
  98. if (arg == "/disablehpet")
  99. {
  100. Utilities.DisableHPET();
  101. Environment.Exit(0);
  102. return;
  103. }
  104. if (arg == "/enablehpet")
  105. {
  106. Utilities.EnableHPET();
  107. Environment.Exit(0);
  108. return;
  109. }
  110. // [!!!] unlock all cores instruction
  111. if (arg == "/unlockcores")
  112. {
  113. Utilities.UnlockAllCores();
  114. Environment.Exit(0);
  115. return;
  116. }
  117. if (arg.StartsWith("/svchostsplit="))
  118. {
  119. string x = arg.Replace("/svchostsplit=", string.Empty);
  120. bool isValid = !x.Any(c => !char.IsDigit(c));
  121. if (isValid && int.TryParse(x, out int result)) Utilities.DisableSvcHostProcessSplitting(result);
  122. Environment.Exit(0);
  123. return;
  124. }
  125. if (arg == "/resetsvchostsplit")
  126. {
  127. Utilities.EnableSvcHostProcessSplitting();
  128. Environment.Exit(0);
  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. SetRunOnceDisableDefender();
  152. }
  153. // enable defender automatically
  154. if (arg == "/restart=enabledefender")
  155. {
  156. SetRunOnceEnableDefender();
  157. }
  158. // return from safe-mode automatically
  159. if (arg == "/silentdisabledefender")
  160. {
  161. DisableDefenderInSafeMode();
  162. RestartInNormalMode();
  163. }
  164. if (arg == "/silentenabledefender")
  165. {
  166. EnableDefenderInSafeMode();
  167. RestartInNormalMode();
  168. }
  169. // disables Defender in SAFE MODE (for Windows 10 1903+ / works in Windows 11 as well)
  170. if (arg == "/disabledefender")
  171. {
  172. DisableDefenderInSafeMode();
  173. MessageBox.Show("Windows Defender has been completely disabled successfully.", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  174. Environment.Exit(0);
  175. return;
  176. }
  177. // other options for disabling specific tools
  178. if (arg.StartsWith("/disable="))
  179. {
  180. string x = arg.Replace("/disable=", string.Empty);
  181. string[] opts = x.Split(',');
  182. bool[] codes =
  183. {
  184. opts.Contains("indicium"),
  185. opts.Contains("uwp"),
  186. opts.Contains("apps"),
  187. opts.Contains("hosts"),
  188. opts.Contains("startup"),
  189. opts.Contains("cleaner"),
  190. opts.Contains("integrator"),
  191. opts.Contains("pinger")
  192. };
  193. StartMainForm(codes);
  194. return;
  195. }
  196. if (arg.StartsWith("/config="))
  197. {
  198. string fileName = arg.Replace("/config=", string.Empty);
  199. if (!File.Exists(fileName))
  200. {
  201. MessageBox.Show(_confNotFoundMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  202. Environment.Exit(0);
  203. return;
  204. }
  205. SilentOps.GetSilentConfig(fileName);
  206. if (SilentOps.CurrentSilentConfig == null)
  207. {
  208. MessageBox.Show(_confInvalidFormatMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  209. Environment.Exit(0);
  210. return;
  211. }
  212. if (!SilentOps.ProcessWindowsVersionCompatibility())
  213. {
  214. MessageBox.Show(_confInvalidVersionMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  215. Environment.Exit(0);
  216. return;
  217. }
  218. SILENT_MODE = true;
  219. LoadSettings();
  220. SilentOps.ProcessAllActions();
  221. Options.SaveSettings();
  222. }
  223. }
  224. else
  225. {
  226. StartMainForm();
  227. }
  228. }
  229. private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  230. {
  231. Exception error = (Exception)e.ExceptionObject;
  232. ErrorLogger.LogError("[Program.Main-UnhandledException]", error.Message, error.StackTrace);
  233. }
  234. private static void LoadSettings()
  235. {
  236. // for backward compatibility (legacy)
  237. Options.LegacyCheck();
  238. // load settings, if there is no settings, load defaults
  239. try
  240. {
  241. // show FirstRunForm/Language Selector if app is running first time
  242. if (!File.Exists(Options.SettingsFile))
  243. {
  244. Options.LoadSettings();
  245. if (!SILENT_MODE)
  246. {
  247. FirstRunForm frf = new FirstRunForm();
  248. frf.ShowDialog();
  249. }
  250. }
  251. else
  252. {
  253. Options.LoadSettings();
  254. }
  255. //if (!Options.CurrentOptions.DisableOptimizerTelemetry)
  256. //{
  257. // TelemetryHelper.EnableTelemetryService();
  258. //}
  259. // ideal place to replace internal messages from translation list
  260. _adminMissingMessage = Options.TranslationList["adminMissingMsg"];
  261. _unsupportedMessage = Options.TranslationList["unsupportedMsg"];
  262. _confInvalidFormatMsg = Options.TranslationList["confInvalidFormatMsg"];
  263. _confInvalidVersionMsg = Options.TranslationList["confInvalidVersionMsg"];
  264. _confNotFoundMsg = Options.TranslationList["confNotFoundMsg"];
  265. _argInvalidMsg = Options.TranslationList["argInvalidMsg"];
  266. _alreadyRunningMsg = Options.TranslationList["alreadyRunningMsg"];
  267. }
  268. catch (Exception ex)
  269. {
  270. ErrorLogger.LogError("Program.Main-LoadSettings", ex.Message, ex.StackTrace);
  271. Environment.Exit(0);
  272. }
  273. }
  274. internal static void RestartInSafeMode()
  275. {
  276. Utilities.RunCommand("bcdedit /set {current} safeboot Minimal");
  277. Thread.Sleep(500);
  278. Utilities.Reboot();
  279. Environment.Exit(0);
  280. }
  281. internal static void RestartInNormalMode()
  282. {
  283. Utilities.RunCommand("bcdedit /deletevalue {current} safeboot");
  284. Thread.Sleep(500);
  285. Utilities.Reboot();
  286. Environment.Exit(0);
  287. }
  288. private static void DisableDefenderInSafeMode()
  289. {
  290. File.WriteAllText("DisableDefenderSafeMode.bat", Properties.Resources.DisableDefenderSafeMode1903Plus);
  291. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  292. Thread.Sleep(1000);
  293. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  294. Thread.Sleep(1000);
  295. File.Delete("DisableDefenderSafeMode.bat");
  296. }
  297. private static void EnableDefenderInSafeMode()
  298. {
  299. File.WriteAllText("EnableDefenderSafeMode.bat", Properties.Resources.EnableDefenderSafeMode1903Plus);
  300. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  301. Thread.Sleep(1000);
  302. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  303. Thread.Sleep(1000);
  304. File.Delete("EnableDefenderSafeMode.bat");
  305. }
  306. internal static void SetRunOnceDisableDefender()
  307. {
  308. // set RunOnce instruction
  309. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerDisableDefender", Assembly.GetExecutingAssembly().Location + " /silentdisabledefender", Microsoft.Win32.RegistryValueKind.String);
  310. RestartInSafeMode();
  311. }
  312. internal static void SetRunOnceEnableDefender()
  313. {
  314. // set RunOnce instruction
  315. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerEnableDefender", Assembly.GetExecutingAssembly().Location + " /silentenabledefender", Microsoft.Win32.RegistryValueKind.String);
  316. RestartInSafeMode();
  317. }
  318. private static void StartMainForm()
  319. {
  320. LoadSettings();
  321. StartSplashForm();
  322. _MainForm = new MainForm(_SplashForm);
  323. _MainForm.Load += MainForm_Load;
  324. Application.Run(_MainForm);
  325. }
  326. private static void StartMainForm(bool[] codes)
  327. {
  328. LoadSettings();
  329. StartSplashForm();
  330. _MainForm = new MainForm(_SplashForm, codes[0], codes[3], codes[2], codes[1], codes[4], codes[5], codes[6], codes[7]);
  331. _MainForm.Load += MainForm_Load;
  332. Application.Run(_MainForm);
  333. }
  334. private static void StartSplashForm()
  335. {
  336. _SplashForm = new SplashForm();
  337. var splashThread = new Thread(new ThreadStart(
  338. () => Application.Run(_SplashForm)));
  339. splashThread.SetApartmentState(ApartmentState.STA);
  340. splashThread.Start();
  341. }
  342. private static void MainForm_Load(object sender, EventArgs e)
  343. {
  344. if (_SplashForm != null && !_SplashForm.Disposing && !_SplashForm.IsDisposed)
  345. _SplashForm.Invoke(new Action(() => _SplashForm.Close()));
  346. _MainForm.TopMost = true;
  347. _MainForm.Activate();
  348. _MainForm.TopMost = false;
  349. }
  350. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  351. {
  352. return EmbeddedAssembly.Get(args.Name);
  353. }
  354. }
  355. }