2
0

Program.cs 20 KB

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