Program.cs 16 KB

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