2
0

Program.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 = 0;
  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. // checking for silent config argument
  106. if (switches.Length == 1)
  107. {
  108. string arg = switches[0].Trim();
  109. // UNSAFE mode switch (allows running on Windows Server 2008+)
  110. if (arg == "/unsafe")
  111. {
  112. UNSAFE_MODE = true;
  113. StartSplashForm();
  114. _MainForm = new MainForm(_SplashForm);
  115. _MainForm.Load += MainForm_Load;
  116. Application.Run(_MainForm);
  117. return;
  118. }
  119. // resets configuration
  120. if (arg == "/reset")
  121. {
  122. Utilities.ResetConfiguration(true);
  123. return;
  124. }
  125. // displays build info
  126. if (arg == "/version")
  127. {
  128. if (!EXPERIMENTAL_BUILD) MessageBox.Show($"Optimizer: {GetCurrentVersionTostring()}\n\nCoded by: deadmoon © ∞\n\nhttps://github.com/hellzerg/optimizer", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  129. 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);
  130. Environment.Exit(0);
  131. }
  132. // hibernation switches
  133. if (arg == "/disablehibernate")
  134. {
  135. Utilities.DisableHibernation();
  136. Environment.Exit(0);
  137. }
  138. if (arg == "/enablehibernate")
  139. {
  140. Utilities.EnableHibernation();
  141. Environment.Exit(0);
  142. }
  143. // instruct to restart in safe-mode
  144. if (arg == "/restart=safemode")
  145. {
  146. RestartInSafeMode();
  147. }
  148. // instruct to restart normally
  149. if (arg == "/restart=normal")
  150. {
  151. RestartInNormalMode();
  152. }
  153. // disable defender automatically
  154. if (arg == "/restart=disabledefender")
  155. {
  156. // set RunOnce instruction
  157. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerDisableDefender", Assembly.GetExecutingAssembly().Location + " /silentdisabledefender", Microsoft.Win32.RegistryValueKind.String);
  158. RestartInSafeMode();
  159. }
  160. // enable defender automatically
  161. if (arg == "/restart=enabledefender")
  162. {
  163. // set RunOnce instruction
  164. Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce", "*OptimizerEnableDefender", Assembly.GetExecutingAssembly().Location + " /silentenabledefender", Microsoft.Win32.RegistryValueKind.String);
  165. RestartInSafeMode();
  166. }
  167. // return from safe-mode automatically
  168. if (arg == "/silentdisabledefender")
  169. {
  170. DisableDefenderInSafeMode();
  171. RestartInNormalMode();
  172. }
  173. if (arg == "/silentenabledefender")
  174. {
  175. EnableDefenderInSafeMode();
  176. RestartInNormalMode();
  177. }
  178. // other options for disabling specific tools
  179. if (arg.StartsWith("/disable="))
  180. {
  181. string x = arg.Replace("/disable=", string.Empty);
  182. string[] opts = x.Split(',');
  183. bool disableIndicium = opts.Contains("indicium");
  184. bool disableUWPTool = opts.Contains("uwp");
  185. bool disableAppsTool = opts.Contains("apps");
  186. bool disableHostsEditor = opts.Contains("hosts");
  187. bool disableStartupTool = opts.Contains("startup");
  188. bool disableCleaner = opts.Contains("cleaner");
  189. bool disableIntegrator = opts.Contains("integrator");
  190. bool disablePinger = opts.Contains("pinger");
  191. StartSplashForm();
  192. _MainForm = new MainForm(_SplashForm, disableIndicium, disableHostsEditor, disableAppsTool, disableUWPTool, disableStartupTool, disableCleaner, disableIntegrator, disablePinger);
  193. _MainForm.Load += MainForm_Load;
  194. Application.Run(_MainForm);
  195. return;
  196. }
  197. // disables Defender in SAFE MODE (for Windows 10 1903+ / works in Windows 11 as well)
  198. if (arg == "/disabledefender")
  199. {
  200. DisableDefenderInSafeMode();
  201. MessageBox.Show("Windows Defender has been completely disabled successfully.", "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  202. Environment.Exit(0);
  203. return;
  204. }
  205. if (arg.StartsWith("/"))
  206. {
  207. if (File.Exists(arg.Remove(0, 1)))
  208. {
  209. SilentOps.GetSilentConfig(arg.Remove(0, 1));
  210. if (SilentOps.CurrentSilentConfig != null)
  211. {
  212. if (SilentOps.CurrentSilentConfig.WindowsVersion == 7 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows7)
  213. {
  214. SilentOps.ProcessSilentConfigGeneral();
  215. SilentOps.SilentUpdateOptionsGeneral();
  216. Options.SaveSettings();
  217. }
  218. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 8 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows8)
  219. {
  220. SilentOps.ProcessSilentConfigGeneral();
  221. SilentOps.ProcessSilentConfigWindows8();
  222. SilentOps.SilentUpdateOptionsGeneral();
  223. SilentOps.SilentUpdateOptions8();
  224. Options.SaveSettings();
  225. }
  226. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 10 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows10)
  227. {
  228. SilentOps.ProcessSilentConfigGeneral();
  229. SilentOps.ProcessSilentConfigWindows10();
  230. SilentOps.SilentUpdateOptionsGeneral();
  231. SilentOps.SilentUpdateOptions10();
  232. Options.SaveSettings();
  233. }
  234. else if (SilentOps.CurrentSilentConfig.WindowsVersion == 11 && Utilities.CurrentWindowsVersion == WindowsVersion.Windows11)
  235. {
  236. SilentOps.ProcessSilentConfigGeneral();
  237. SilentOps.ProcessSilentConfigWindows10();
  238. SilentOps.ProcessSilentConfigWindows11();
  239. SilentOps.SilentUpdateOptionsGeneral();
  240. SilentOps.SilentUpdateOptions10();
  241. SilentOps.SilentUpdateOptions11();
  242. Options.SaveSettings();
  243. }
  244. else
  245. {
  246. MessageBox.Show(_confInvalidVersionMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  247. Environment.Exit(0);
  248. }
  249. }
  250. else
  251. {
  252. MessageBox.Show(_confInvalidFormatMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  253. Environment.Exit(0);
  254. }
  255. }
  256. else
  257. {
  258. MessageBox.Show(_confNotFoundMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  259. Environment.Exit(0);
  260. }
  261. }
  262. else
  263. {
  264. MessageBox.Show(_argInvalidMsg, "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
  265. Environment.Exit(0);
  266. }
  267. }
  268. else
  269. {
  270. StartSplashForm();
  271. _MainForm = new MainForm(_SplashForm);
  272. _MainForm.Load += MainForm_Load;
  273. Application.Run(_MainForm);
  274. }
  275. }
  276. else
  277. {
  278. HelperForm f = new HelperForm(null, MessageType.Error, _unsupportedMessage);
  279. f.ShowDialog();
  280. Environment.Exit(0);
  281. }
  282. }
  283. }
  284. }
  285. }
  286. //internal static void ForceExit()
  287. //{
  288. // Environment.Exit(0);
  289. //}
  290. private static void RestartInSafeMode()
  291. {
  292. Utilities.RunCommand("bcdedit /set {current} safeboot Minimal");
  293. Thread.Sleep(500);
  294. Utilities.Reboot();
  295. Environment.Exit(0);
  296. }
  297. private static void RestartInNormalMode()
  298. {
  299. Utilities.RunCommand("bcdedit /deletevalue {current} safeboot");
  300. Thread.Sleep(500);
  301. Utilities.Reboot();
  302. Environment.Exit(0);
  303. }
  304. private static void DisableDefenderInSafeMode()
  305. {
  306. File.WriteAllText("DisableDefenderSafeMode.bat", Properties.Resources.DisableDefenderSafeMode1903Plus);
  307. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  308. Thread.Sleep(1000);
  309. Utilities.RunBatchFile("DisableDefenderSafeMode.bat");
  310. Thread.Sleep(1000);
  311. File.Delete("DisableDefenderSafeMode.bat");
  312. }
  313. private static void EnableDefenderInSafeMode()
  314. {
  315. File.WriteAllText("EnableDefenderSafeMode.bat", Properties.Resources.EnableDefenderSafeMode1903Plus);
  316. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  317. Thread.Sleep(1000);
  318. Utilities.RunBatchFile("EnableDefenderSafeMode.bat");
  319. Thread.Sleep(1000);
  320. File.Delete("EnableDefenderSafeMode.bat");
  321. }
  322. private static void StartSplashForm()
  323. {
  324. _SplashForm = new SplashForm();
  325. var splashThread = new Thread(new ThreadStart(
  326. () => Application.Run(_SplashForm)));
  327. splashThread.SetApartmentState(ApartmentState.STA);
  328. splashThread.Start();
  329. }
  330. private static void MainForm_Load(object sender, EventArgs e)
  331. {
  332. if (_SplashForm != null && !_SplashForm.Disposing && !_SplashForm.IsDisposed)
  333. _SplashForm.Invoke(new Action(() => _SplashForm.Close()));
  334. _MainForm.TopMost = true;
  335. _MainForm.Activate();
  336. _MainForm.TopMost = false;
  337. }
  338. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  339. {
  340. return EmbeddedAssembly.Get(args.Name);
  341. }
  342. }
  343. }