2
0

Program.cs 15 KB

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