Program.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 = 3;
  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 /config=win10.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. CoreHelper.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.StartsWith("/svchostsplit="))
  111. {
  112. string x = arg.Replace("/svchostsplit=", string.Empty);
  113. bool isValid = !x.Any(c => !char.IsDigit(c));
  114. if (isValid && int.TryParse(x, out int result)) Utilities.DisableSvcHostProcessSplitting(result);
  115. Environment.Exit(0);
  116. return;
  117. }
  118. if (arg == "/resetsvchostsplit")
  119. {
  120. Utilities.EnableSvcHostProcessSplitting();
  121. Environment.Exit(0);
  122. return;
  123. }
  124. if (arg == "/repair")
  125. {
  126. Utilities.Repair(true);
  127. return;
  128. }
  129. if (arg == "/version")
  130. {
  131. if (!EXPERIMENTAL_BUILD) MessageBox.Show($"Optimizer: {GetCurrentVersionTostring()}\n\nCoded by: deadmoon © ∞\n\nhttps://github.com/hellzerg/optimizer", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  132. 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);
  133. Environment.Exit(0);
  134. return;
  135. }
  136. // instruct to restart in safe-mode
  137. if (arg == "/restart=safemode")
  138. {
  139. RestartInSafeMode();
  140. }
  141. // instruct to restart normally
  142. if (arg == "/restart=normal")
  143. {
  144. RestartInNormalMode();
  145. }
  146. // disable defender automatically
  147. if (arg == "/restart=disabledefender")
  148. {
  149. SetRunOnceDisableDefender();
  150. }
  151. // enable defender automatically
  152. if (arg == "/restart=enabledefender")
  153. {
  154. SetRunOnceEnableDefender();
  155. }
  156. // return from safe-mode automatically
  157. if (arg == "/silentdisabledefender")
  158. {
  159. DisableDefenderInSafeMode();
  160. RestartInNormalMode();
  161. }
  162. if (arg == "/silentenabledefender")
  163. {
  164. EnableDefenderInSafeMode();
  165. RestartInNormalMode();
  166. }
  167. // disables Defender in SAFE MODE (for Windows 10 1903+ / works in Windows 11 as well)
  168. if (arg == "/disabledefender")
  169. {
  170. DisableDefenderInSafeMode();
  171. MessageBox.Show("Windows Defender has been completely disabled successfully.", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  172. Environment.Exit(0);
  173. return;
  174. }
  175. // other options for disabling specific tools
  176. if (arg.StartsWith("/disable="))
  177. {
  178. string x = arg.Replace("/disable=", string.Empty);
  179. string[] opts = x.Split(',');
  180. bool[] codes =
  181. {
  182. opts.Contains("indicium"),
  183. opts.Contains("uwp"),
  184. opts.Contains("apps"),
  185. opts.Contains("hosts"),
  186. opts.Contains("startup"),
  187. opts.Contains("cleaner"),
  188. opts.Contains("integrator"),
  189. opts.Contains("pinger")
  190. };
  191. StartMainForm(codes);
  192. return;
  193. }
  194. if (arg.StartsWith("/config="))
  195. {
  196. string fileName = arg.Replace("/config=", string.Empty);
  197. if (!File.Exists(fileName))
  198. {
  199. MessageBox.Show(_confNotFoundMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  200. Environment.Exit(0);
  201. return;
  202. }
  203. SilentOps.GetSilentConfig(fileName);
  204. if (SilentOps.CurrentSilentConfig == null)
  205. {
  206. MessageBox.Show(_confInvalidFormatMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  207. Environment.Exit(0);
  208. return;
  209. }
  210. if (!SilentOps.ProcessWindowsVersionCompatibility())
  211. {
  212. MessageBox.Show(_confInvalidVersionMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  213. Environment.Exit(0);
  214. return;
  215. }
  216. LoadSettings();
  217. //SilentOps.ProcessAllActions();
  218. Options.SaveSettings();
  219. }
  220. }
  221. else
  222. {
  223. StartMainForm();
  224. }
  225. }
  226. private static void LoadSettings()
  227. {
  228. // for backward compatibility (legacy)
  229. Options.LegacyCheck();
  230. // load settings, if there is no settings, load defaults
  231. try
  232. {
  233. // show FirstRunForm/Language Selector if app is running first time
  234. if (!File.Exists(Options.SettingsFile))
  235. {
  236. Options.LoadSettings();
  237. FirstRunForm frf = new FirstRunForm();
  238. frf.ShowDialog();
  239. }
  240. else
  241. {
  242. Options.LoadSettings();
  243. }
  244. //if (!Options.CurrentOptions.DisableOptimizerTelemetry)
  245. //{
  246. // TelemetryHelper.EnableTelemetryService();
  247. //}
  248. // ideal place to replace internal messages from translation list
  249. _adminMissingMessage = Options.TranslationList["adminMissingMsg"];
  250. _unsupportedMessage = Options.TranslationList["unsupportedMsg"];
  251. _confInvalidFormatMsg = Options.TranslationList["confInvalidFormatMsg"];
  252. _confInvalidVersionMsg = Options.TranslationList["confInvalidVersionMsg"];
  253. _confNotFoundMsg = Options.TranslationList["confNotFoundMsg"];
  254. _argInvalidMsg = Options.TranslationList["argInvalidMsg"];
  255. _alreadyRunningMsg = Options.TranslationList["alreadyRunningMsg"];
  256. }
  257. catch (Exception ex)
  258. {
  259. ErrorLogger.LogError("Program.Main-LoadSettings", ex.Message, ex.StackTrace);
  260. Environment.Exit(0);
  261. }
  262. }
  263. internal static void RestartInSafeMode()
  264. {
  265. Utilities.RunCommand("bcdedit /set {current} safeboot Minimal");
  266. Thread.Sleep(500);
  267. Utilities.Reboot();
  268. Environment.Exit(0);
  269. }
  270. internal static void RestartInNormalMode()
  271. {
  272. Utilities.RunCommand("bcdedit /deletevalue {current} safeboot");
  273. Thread.Sleep(500);
  274. Utilities.Reboot();
  275. Environment.Exit(0);
  276. }
  277. private static void DisableDefenderInSafeMode()
  278. {
  279. File.WriteAllText("DisableDefenderSafeMode.bat", Properties.Resources.DisableDefenderSafeMode1903Plus);
  280. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  281. Thread.Sleep(1000);
  282. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  283. Thread.Sleep(1000);
  284. File.Delete("DisableDefenderSafeMode.bat");
  285. }
  286. private static void EnableDefenderInSafeMode()
  287. {
  288. File.WriteAllText("EnableDefenderSafeMode.bat", Properties.Resources.EnableDefenderSafeMode1903Plus);
  289. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  290. Thread.Sleep(1000);
  291. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  292. Thread.Sleep(1000);
  293. File.Delete("EnableDefenderSafeMode.bat");
  294. }
  295. internal static void SetRunOnceDisableDefender()
  296. {
  297. // set RunOnce instruction
  298. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerDisableDefender", Assembly.GetExecutingAssembly().Location + " /silentdisabledefender", Microsoft.Win32.RegistryValueKind.String);
  299. RestartInSafeMode();
  300. }
  301. internal static void SetRunOnceEnableDefender()
  302. {
  303. // set RunOnce instruction
  304. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerEnableDefender", Assembly.GetExecutingAssembly().Location + " /silentenabledefender", Microsoft.Win32.RegistryValueKind.String);
  305. RestartInSafeMode();
  306. }
  307. private static void StartMainForm()
  308. {
  309. LoadSettings();
  310. StartSplashForm();
  311. _MainForm = new MainForm(_SplashForm);
  312. _MainForm.Load += MainForm_Load;
  313. Application.Run(_MainForm);
  314. }
  315. private static void StartMainForm(bool[] codes)
  316. {
  317. LoadSettings();
  318. StartSplashForm();
  319. _MainForm = new MainForm(_SplashForm, codes[0], codes[3], codes[2], codes[1], codes[4], codes[5], codes[6], codes[7]);
  320. _MainForm.Load += MainForm_Load;
  321. Application.Run(_MainForm);
  322. }
  323. private static void StartSplashForm()
  324. {
  325. _SplashForm = new SplashForm();
  326. var splashThread = new Thread(new ThreadStart(
  327. () => Application.Run(_SplashForm)));
  328. splashThread.SetApartmentState(ApartmentState.STA);
  329. splashThread.Start();
  330. }
  331. private static void MainForm_Load(object sender, EventArgs e)
  332. {
  333. if (_SplashForm != null && !_SplashForm.Disposing && !_SplashForm.IsDisposed)
  334. _SplashForm.Invoke(new Action(() => _SplashForm.Close()));
  335. _MainForm.TopMost = true;
  336. _MainForm.Activate();
  337. _MainForm.TopMost = false;
  338. }
  339. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  340. {
  341. return EmbeddedAssembly.Get(args.Name);
  342. }
  343. }
  344. }