Program.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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 = 14;
  15. internal readonly static float Minor = 1;
  16. internal readonly static bool EXPERIMENTAL_BUILD = false;
  17. internal static string GetCurrentVersionTostring()
  18. {
  19. return Major.ToString() + "." + Minor.ToString();
  20. }
  21. internal static float GetCurrentVersion()
  22. {
  23. return float.Parse(GetCurrentVersionTostring());
  24. }
  25. /* END OF VERSION PROPERTIES */
  26. // Enables the corresponding Windows tab for Windows Server machines
  27. internal static bool UNSAFE_MODE = false;
  28. const string _jsonAssembly = @"Optimizer.Newtonsoft.Json.dll";
  29. internal static MainForm _MainForm;
  30. internal static SplashForm _SplashForm;
  31. static string _adminMissingMessage = "Optimizer needs to be run as administrator!\nApp will now close...";
  32. static string _unsupportedMessage = "Optimizer works with Windows 7 and higher!\nApp will now close...";
  33. //static string _renameAppMessage = "It's recommended to rename the app from '{0}' to 'Optimizer' for a better experience.\n\nApp will now close...";
  34. static string _confInvalidVersionMsg = "Windows version does not match!";
  35. static string _confInvalidFormatMsg = "Config file is in invalid format!";
  36. static string _confNotFoundMsg = "Config file does not exist!";
  37. static string _argInvalidMsg = "Invalid argument! Example: Optimizer.exe /silent.conf";
  38. static string _alreadyRunningMsg = "Optimizer is already running in the background!";
  39. const string MUTEX_GUID = @"{DEADMOON-0EFC7B8A-D1FC-467F-B4B1-0117C643FE19-OPTIMIZER}";
  40. internal static Mutex MUTEX;
  41. static bool _notRunning;
  42. [System.Runtime.InteropServices.DllImport("user32.dll")]
  43. private static extern bool SetProcessDPIAware();
  44. [STAThread]
  45. static void Main(string[] switches)
  46. {
  47. EmbeddedAssembly.Load(_jsonAssembly, _jsonAssembly.Replace("Optimizer.", string.Empty));
  48. AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
  49. if (Environment.OSVersion.Version.Major >= 6) SetProcessDPIAware();
  50. Application.EnableVisualStyles();
  51. Application.SetCompatibleTextRenderingDefault(false);
  52. // prompt to change filename to 'Optimizer' (skip if experimental build)
  53. // annoying?
  54. //if (!EXPERIMENTAL_BUILD && Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location) != "Optimizer")
  55. //{
  56. // MessageBox.Show(string.Format(_renameAppMessage, Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)), "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  57. // Environment.Exit(0);
  58. //}
  59. // single-instance mechanism
  60. using (MUTEX = new Mutex(true, MUTEX_GUID, out _notRunning))
  61. {
  62. if (!_notRunning)
  63. {
  64. MessageBox.Show(_alreadyRunningMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  65. Environment.Exit(0);
  66. }
  67. else
  68. {
  69. if (!Utilities.IsAdmin())
  70. {
  71. string file = Process.GetCurrentProcess().MainModule.FileName;
  72. ProcessStartInfo p = new ProcessStartInfo(file);
  73. p.Verb = "runas";
  74. p.Arguments = string.Join(" ", switches);
  75. Process.Start(p);
  76. Environment.Exit(0);
  77. }
  78. else
  79. {
  80. if (Utilities.IsCompatible())
  81. {
  82. Required.Deploy();
  83. // for backward compatibility (legacy)
  84. Options.LegacyCheck();
  85. // load settings, if there is no settings, load defaults
  86. try
  87. {
  88. // show FirstRunForm/Language Selector if app is running first time
  89. if (!File.Exists(Options.SettingsFile))
  90. {
  91. Options.LoadSettings();
  92. FirstRunForm frf = new FirstRunForm();
  93. frf.ShowDialog();
  94. }
  95. else
  96. {
  97. Options.LoadSettings();
  98. }
  99. // ideal place to replace internal messages from translation list
  100. _adminMissingMessage = Options.TranslationList["adminMissingMsg"];
  101. _unsupportedMessage = Options.TranslationList["unsupportedMsg"];
  102. _confInvalidFormatMsg = Options.TranslationList["confInvalidFormatMsg"];
  103. _confInvalidVersionMsg = Options.TranslationList["confInvalidVersionMsg"];
  104. _confNotFoundMsg = Options.TranslationList["confNotFoundMsg"];
  105. _argInvalidMsg = Options.TranslationList["argInvalidMsg"];
  106. _alreadyRunningMsg = Options.TranslationList["alreadyRunningMsg"];
  107. }
  108. catch (Exception ex)
  109. {
  110. ErrorLogger.LogError("Program.Main", ex.Message, ex.StackTrace);
  111. Environment.Exit(0);
  112. }
  113. FontHelper.LoadFont();
  114. for (int z = 0; z < switches.Length; z++) switches[z] = switches[z].ToLowerInvariant();
  115. // checking for silent config argument
  116. if (switches.Length == 1)
  117. {
  118. string arg = switches[0].Trim();
  119. // UNSAFE mode switch (allows running on Windows Server 2008+)
  120. if (arg == "/unsafe")
  121. {
  122. UNSAFE_MODE = true;
  123. StartSplashForm();
  124. _MainForm = new MainForm(_SplashForm);
  125. _MainForm.Load += MainForm_Load;
  126. Application.Run(_MainForm);
  127. return;
  128. }
  129. if (arg == "/disablehpet")
  130. {
  131. Utilities.DisableHPET();
  132. Environment.Exit(0);
  133. }
  134. if (arg == "/enablehpet")
  135. {
  136. Utilities.EnableHPET();
  137. Environment.Exit(0);
  138. }
  139. if (arg == "/addstartup")
  140. {
  141. Utilities.RegisterAutoStart();
  142. Environment.Exit(0);
  143. }
  144. if (arg == "/deletestartup")
  145. {
  146. Utilities.UnregisterAutoStart();
  147. Environment.Exit(0);
  148. }
  149. // [!!!] unlock all cores instruction
  150. if (arg == "/unlockcores")
  151. {
  152. Utilities.UnlockAllCores();
  153. Environment.Exit(0);
  154. }
  155. // resets configuration
  156. if (arg == "/reset")
  157. {
  158. Utilities.Repair(true);
  159. return;
  160. }
  161. // displays build info
  162. if (arg == "/version")
  163. {
  164. if (!EXPERIMENTAL_BUILD) MessageBox.Show($"Optimizer: {GetCurrentVersionTostring()}\n\nCoded by: deadmoon © ∞\n\nhttps://github.com/hellzerg/optimizer", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  165. 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);
  166. Environment.Exit(0);
  167. }
  168. // hibernation switches
  169. if (arg == "/disablehibernate")
  170. {
  171. Utilities.DisableHibernation();
  172. Environment.Exit(0);
  173. }
  174. if (arg == "/enablehibernate")
  175. {
  176. Utilities.EnableHibernation();
  177. Environment.Exit(0);
  178. }
  179. // instruct to restart in safe-mode
  180. if (arg == "/restart=safemode")
  181. {
  182. RestartInSafeMode();
  183. }
  184. // instruct to restart normally
  185. if (arg == "/restart=normal")
  186. {
  187. RestartInNormalMode();
  188. }
  189. // disable defender automatically
  190. if (arg == "/restart=disabledefender")
  191. {
  192. // set RunOnce instruction
  193. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerDisableDefender", Assembly.GetExecutingAssembly().Location + " /silentdisabledefender", Microsoft.Win32.RegistryValueKind.String);
  194. RestartInSafeMode();
  195. }
  196. // enable defender automatically
  197. if (arg == "/restart=enabledefender")
  198. {
  199. // set RunOnce instruction
  200. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerEnableDefender", Assembly.GetExecutingAssembly().Location + " /silentenabledefender", Microsoft.Win32.RegistryValueKind.String);
  201. RestartInSafeMode();
  202. }
  203. // return from safe-mode automatically
  204. if (arg == "/silentdisabledefender")
  205. {
  206. DisableDefenderInSafeMode();
  207. RestartInNormalMode();
  208. }
  209. if (arg == "/silentenabledefender")
  210. {
  211. EnableDefenderInSafeMode();
  212. RestartInNormalMode();
  213. }
  214. // other options for disabling specific tools
  215. if (arg.StartsWith("/disable="))
  216. {
  217. string x = arg.Replace("/disable=", string.Empty);
  218. string[] opts = x.Split(',');
  219. bool disableIndicium = opts.Contains("indicium");
  220. bool disableUWPTool = opts.Contains("uwp");
  221. bool disableAppsTool = opts.Contains("apps");
  222. bool disableHostsEditor = opts.Contains("hosts");
  223. bool disableStartupTool = opts.Contains("startup");
  224. bool disableCleaner = opts.Contains("cleaner");
  225. bool disableIntegrator = opts.Contains("integrator");
  226. bool disablePinger = opts.Contains("pinger");
  227. StartSplashForm();
  228. _MainForm = new MainForm(_SplashForm, disableIndicium, disableHostsEditor, disableAppsTool, disableUWPTool, disableStartupTool, disableCleaner, disableIntegrator, disablePinger);
  229. _MainForm.Load += MainForm_Load;
  230. Application.Run(_MainForm);
  231. return;
  232. }
  233. // disables Defender in SAFE MODE (for Windows 10 1903+ / works in Windows 11 as well)
  234. if (arg == "/disabledefender")
  235. {
  236. DisableDefenderInSafeMode();
  237. MessageBox.Show("Windows Defender has been completely disabled successfully.", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  238. Environment.Exit(0);
  239. return;
  240. }
  241. if (arg.StartsWith("/"))
  242. {
  243. if (File.Exists(arg.Remove(0, 1)))
  244. {
  245. SilentOps.GetSilentConfig(arg.Remove(0, 1));
  246. if (SilentOps.CurrentSilentConfig != null)
  247. {
  248. if (SilentOps.CurrentSilentConfig.WindowsVersion == 7 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows7)
  249. {
  250. SilentOps.ProcessSilentConfigGeneral();
  251. SilentOps.SilentUpdateOptionsGeneral();
  252. Options.SaveSettings();
  253. }
  254. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 8 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows8)
  255. {
  256. SilentOps.ProcessSilentConfigGeneral();
  257. SilentOps.ProcessSilentConfigWindows8();
  258. SilentOps.SilentUpdateOptionsGeneral();
  259. SilentOps.SilentUpdateOptions8();
  260. Options.SaveSettings();
  261. }
  262. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 10 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows10)
  263. {
  264. SilentOps.ProcessSilentConfigGeneral();
  265. SilentOps.ProcessSilentConfigWindows10();
  266. SilentOps.SilentUpdateOptionsGeneral();
  267. SilentOps.SilentUpdateOptions10();
  268. Options.SaveSettings();
  269. }
  270. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 11 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows11)
  271. {
  272. SilentOps.ProcessSilentConfigGeneral();
  273. SilentOps.ProcessSilentConfigWindows10();
  274. SilentOps.ProcessSilentConfigWindows11();
  275. SilentOps.SilentUpdateOptionsGeneral();
  276. SilentOps.SilentUpdateOptions10();
  277. SilentOps.SilentUpdateOptions11();
  278. Options.SaveSettings();
  279. }
  280. else
  281. {
  282. MessageBox.Show(_confInvalidVersionMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  283. Environment.Exit(0);
  284. }
  285. }
  286. else
  287. {
  288. MessageBox.Show(_confInvalidFormatMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  289. Environment.Exit(0);
  290. }
  291. }
  292. else
  293. {
  294. MessageBox.Show(_confNotFoundMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  295. Environment.Exit(0);
  296. }
  297. }
  298. else
  299. {
  300. MessageBox.Show(_argInvalidMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  301. Environment.Exit(0);
  302. }
  303. }
  304. else
  305. {
  306. StartSplashForm();
  307. _MainForm = new MainForm(_SplashForm);
  308. _MainForm.Load += MainForm_Load;
  309. Application.Run(_MainForm);
  310. }
  311. }
  312. else
  313. {
  314. HelperForm f = new HelperForm(null, MessageType.Error, _unsupportedMessage);
  315. f.ShowDialog();
  316. Environment.Exit(0);
  317. }
  318. }
  319. }
  320. }
  321. }
  322. //internal static void ForceExit()
  323. //{
  324. // Environment.Exit(0);
  325. //}
  326. private static void RestartInSafeMode()
  327. {
  328. Utilities.RunCommand("bcdedit /set {current} safeboot Minimal");
  329. Thread.Sleep(500);
  330. Utilities.Reboot();
  331. Environment.Exit(0);
  332. }
  333. private static void RestartInNormalMode()
  334. {
  335. Utilities.RunCommand("bcdedit /deletevalue {current} safeboot");
  336. Thread.Sleep(500);
  337. Utilities.Reboot();
  338. Environment.Exit(0);
  339. }
  340. private static void DisableDefenderInSafeMode()
  341. {
  342. File.WriteAllText("DisableDefenderSafeMode.bat", Properties.Resources.DisableDefenderSafeMode1903Plus);
  343. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  344. Thread.Sleep(1000);
  345. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  346. Thread.Sleep(1000);
  347. File.Delete("DisableDefenderSafeMode.bat");
  348. }
  349. private static void EnableDefenderInSafeMode()
  350. {
  351. File.WriteAllText("EnableDefenderSafeMode.bat", Properties.Resources.EnableDefenderSafeMode1903Plus);
  352. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  353. Thread.Sleep(1000);
  354. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  355. Thread.Sleep(1000);
  356. File.Delete("EnableDefenderSafeMode.bat");
  357. }
  358. private static void StartSplashForm()
  359. {
  360. _SplashForm = new SplashForm();
  361. var splashThread = new Thread(new ThreadStart(
  362. () => Application.Run(_SplashForm)));
  363. splashThread.SetApartmentState(ApartmentState.STA);
  364. splashThread.Start();
  365. }
  366. private static void MainForm_Load(object sender, EventArgs e)
  367. {
  368. if (_SplashForm != null && !_SplashForm.Disposing && !_SplashForm.IsDisposed)
  369. _SplashForm.Invoke(new Action(() => _SplashForm.Close()));
  370. _MainForm.TopMost = true;
  371. _MainForm.Activate();
  372. _MainForm.TopMost = false;
  373. }
  374. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  375. {
  376. return EmbeddedAssembly.Get(args.Name);
  377. }
  378. }
  379. }