Portable Tool for an Ideal Windows Setup
C# activatorbloatware-removalcsharpdebloatdebloaterdisable-servicesmonitoring-systemportableprivacy-toolsregistry-tweakssystem-tuningsystem-utilitytelemetrytweakerwindows-10windows-11windows-debloatwindows-defenderwindows-optimizationwindows-tweaks
fix noty action & import tweaks & upd locales fix crash null & recovery wd
Greedeks509653a12f0e
diff --git a/.Source/GTweak/Languages/en/Localize.xaml b/.Source/GTweak/Languages/en/Localize.xamlindex 40bceaae..46520d1e 100644--- a/.Source/GTweak/Languages/en/Localize.xaml+++ b/.Source/GTweak/Languages/en/Localize.xaml@@ -41,7 +41,7 @@<v:String x:Key="export_warning_noty">It doesn't make sense, apply at least one tweak first</v:String><v:String x:Key="success_onedrive_noty">OneDrive recovery is now underway and will take a while</v:String><v:String x:Key="error_onedrive_noty">OneDrive setup file missing, recovery impossible</v:String>- <v:String x:Key="warn_wd_noty">Expect the process to terminate automatically and the system to restart</v:String>+ <v:String x:Key="warn_wd_noty">Await the process completion followed by system restart</v:String><v:String x:Key="info_wd_noty">It will take some time, please wait a bit</v:String><v:String x:Key="warn_firewall_noty">Your firewall is disabled, turn it on and apply the tweak again</v:String><v:String x:Key="warn_activate_noty">To start - activate Windows. Not all tweaks can be applied</v:String>diff --git a/.Source/GTweak/Languages/fr/Localize.xaml b/.Source/GTweak/Languages/fr/Localize.xamlindex c4d7f13e..7d5fadf8 100644--- a/.Source/GTweak/Languages/fr/Localize.xaml+++ b/.Source/GTweak/Languages/fr/Localize.xaml@@ -41,7 +41,7 @@<v:String x:Key="export_warning_noty">Cela n’a pas de sens, appliquez au moins un réglage d’abord</v:String><v:String x:Key="success_onedrive_noty">Le processus de récupération OneDrive a commencé, cela prendra un certain temps</v:String><v:String x:Key="error_onedrive_noty">OneDrive setup file missing, recovery impossible</v:String>- <v:String x:Key="warn_wd_noty">Expect the process to terminate automatically and the system to restart</v:String>+ <v:String x:Key="warn_wd_noty">Await the process completion followed by system restart</v:String><v:String x:Key="info_wd_noty">Le processus prendra un certain temps, veuillez patienter</v:String><v:String x:Key="warn_firewall_noty">Votre pare-feu est désactivé, activez-le et appliquez à nouveau le réglage</v:String><v:String x:Key="warn_activate_noty">Pour commencer - activez Windows. Tous les réglages ne peuvent pas être appliqués</v:String>diff --git a/.Source/GTweak/Languages/hu/Localize.xaml b/.Source/GTweak/Languages/hu/Localize.xamlindex 2deadf57..7b201e0c 100644--- a/.Source/GTweak/Languages/hu/Localize.xaml+++ b/.Source/GTweak/Languages/hu/Localize.xaml@@ -41,7 +41,7 @@<v:String x:Key="export_warning_noty">Nincs értelme, először legalább egy módosítást alkalmazzon</v:String><v:String x:Key="success_onedrive_noty">A OneDrive helyreállítása már folyamatban van, és eltart egy ideig</v:String><v:String x:Key="error_onedrive_noty">A OneDrive telepítőfájlja hiányzik, a helyreállítás lehetetlen</v:String>- <v:String x:Key="warn_wd_noty">Expect the process to terminate automatically and the system to restart</v:String>+ <v:String x:Key="warn_wd_noty">Await the process completion followed by system restart</v:String><v:String x:Key="info_wd_noty">Eltart egy ideig, kérlek, várj egy kicsit</v:String><v:String x:Key="warn_firewall_noty">A tűzfal le van tiltva, kapcsolja be, és alkalmazza újra a módosítást</v:String><v:String x:Key="warn_activate_noty">Indításhoz - aktiválja a Windows rendszert. Nem minden módosítás alkalmazható</v:String>diff --git a/.Source/GTweak/Languages/it/Localize.xaml b/.Source/GTweak/Languages/it/Localize.xamlindex 4edc5f68..d8bdb81a 100644--- a/.Source/GTweak/Languages/it/Localize.xaml+++ b/.Source/GTweak/Languages/it/Localize.xaml@@ -41,7 +41,7 @@<v:String x:Key="export_warning_noty">Non ha senso, applica almeno una modifica prima</v:String><v:String x:Key="success_onedrive_noty">Il ripristino di OneDrive è in corso e richiederà un po' di tempo</v:String><v:String x:Key="error_onedrive_noty">OneDrive setup file missing, recovery impossible</v:String>- <v:String x:Key="warn_wd_noty">Expect the process to terminate automatically and the system to restart</v:String>+ <v:String x:Key="warn_wd_noty">Await the process completion followed by system restart</v:String><v:String x:Key="info_wd_noty">Ci vorrà un po' di tempo, attendi</v:String><v:String x:Key="warn_firewall_noty">Il tuo firewall è disattivato, attivalo e applica nuovamente la modifica</v:String><v:String x:Key="warn_activate_noty">Per iniziare - attiva Windows. Non tutte le modifiche possono essere applicate</v:String>diff --git a/.Source/GTweak/Languages/ko/Localize.xaml b/.Source/GTweak/Languages/ko/Localize.xamlindex f92d1599..4f249bf2 100644--- a/.Source/GTweak/Languages/ko/Localize.xaml+++ b/.Source/GTweak/Languages/ko/Localize.xaml@@ -41,7 +41,7 @@<v:String x:Key="export_warning_noty">이해가 되지 않는다면 먼저 한 가지 이상의 조정을 적용하세요</v:String><v:String x:Key="success_onedrive_noty">OneDrive 복구 프로세스가 시작되었습니다. 시간이 좀 걸릴 것입니다</v:String><v:String x:Key="error_onedrive_noty">OneDrive 설정 파일이 누락되어 복구가 불가능합니다</v:String>- <v:String x:Key="warn_wd_noty">Expect the process to terminate automatically and the system to restart</v:String>+ <v:String x:Key="warn_wd_noty">Await the process completion followed by system restart</v:String><v:String x:Key="info_wd_noty">이 과정은 다소 시간이 걸리므로 잠시 기다려주세요</v:String><v:String x:Key="warn_firewall_noty">방화벽이 비활성화되어 있으면 방화벽을 켜고 다시 조정을 적용하세요</v:String><v:String x:Key="warn_activate_noty">시작하려면 - Windows를 활성화합니다. 모든 조정을 적용할 수 있는 것은 아닙니다</v:String>diff --git a/.Source/GTweak/Languages/pl/Localize.xaml b/.Source/GTweak/Languages/pl/Localize.xamlindex d88ba304..11017d8f 100644--- a/.Source/GTweak/Languages/pl/Localize.xaml+++ b/.Source/GTweak/Languages/pl/Localize.xaml@@ -40,7 +40,7 @@<v:String x:Key="export_warning_noty">Nie ma sensu, zastosuj najpierw przynajmniej jedną modyfikację</v:String><v:String x:Key="success_onedrive_noty">Trwa przywracanie OneDrive, potrwa to chwilę</v:String><v:String x:Key="error_onedrive_noty">Brak pliku instalacyjnego OneDrive, przywracanie niemożliwe</v:String>- <v:String x:Key="warn_wd_noty">Expect the process to terminate automatically and the system to restart</v:String>+ <v:String x:Key="warn_wd_noty">Await the process completion followed by system restart</v:String><v:String x:Key="info_wd_noty">To zajmie trochę czasu, proszę czekać</v:String><v:String x:Key="warn_firewall_noty">Twoja zapora jest wyłączona, włącz ją i zastosuj modyfikację ponownie</v:String><v:String x:Key="warn_activate_noty">Aby rozpocząć - aktywuj Windows. Nie wszystkie modyfikacje można zastosować</v:String>diff --git a/.Source/GTweak/Languages/pt-br/Localize.xaml b/.Source/GTweak/Languages/pt-br/Localize.xamlindex 723355e4..a6ea404e 100644--- a/.Source/GTweak/Languages/pt-br/Localize.xaml+++ b/.Source/GTweak/Languages/pt-br/Localize.xaml@@ -41,7 +41,7 @@<v:String x:Key="export_warning_noty">Não faz sentido, aplique pelo menos um ajuste primeiro</v:String><v:String x:Key="success_onedrive_noty">A recuperação do OneDrive está em andamento e levará um tempo</v:String><v:String x:Key="error_onedrive_noty">OneDrive setup file missing, recovery impossible</v:String>- <v:String x:Key="warn_wd_noty">Expect the process to terminate automatically and the system to restart</v:String>+ <v:String x:Key="warn_wd_noty">Await the process completion followed by system restart</v:String><v:String x:Key="info_wd_noty">Levará algum tempo, por favor, espere um pouco</v:String><v:String x:Key="warn_firewall_noty">Seu firewall está desativado, ative-o e aplique o ajuste novamente</v:String><v:String x:Key="warn_activate_noty">Para começar - ative o Windows. Nem todos os ajustes podem ser aplicados</v:String>diff --git a/.Source/GTweak/Languages/ru/Localize.xaml b/.Source/GTweak/Languages/ru/Localize.xamlindex 9314c61c..db7ee556 100644--- a/.Source/GTweak/Languages/ru/Localize.xaml+++ b/.Source/GTweak/Languages/ru/Localize.xaml@@ -41,7 +41,7 @@<v:String x:Key="export_warning_noty">Это не имеет смысла, сначала примените хотя бы один твик</v:String><v:String x:Key="success_onedrive_noty">Начался процесс восстановления OneDrive, который займет некоторое время</v:String><v:String x:Key="error_onedrive_noty">Отсутствует установочный файл OneDrive, восстановление невозможно</v:String>- <v:String x:Key="warn_wd_noty">Ожидайте автоматического завершения процесса с последующим перезапуском системы</v:String>+ <v:String x:Key="warn_wd_noty">Ожидайте завершения процесса с последующим перезапуском системы</v:String><v:String x:Key="info_wd_noty">Это займет некоторое время, пожалуйста, подождите немного</v:String><v:String x:Key="warn_firewall_noty">У вас отключен брандмауэр, включите и примените твик снова</v:String><v:String x:Key="warn_activate_noty">Для начала активируйте - Windows. Не все твики смогут примениться</v:String>diff --git a/.Source/GTweak/Languages/uk/Localize.xaml b/.Source/GTweak/Languages/uk/Localize.xamlindex 662903cf..b54b5ad2 100644--- a/.Source/GTweak/Languages/uk/Localize.xaml+++ b/.Source/GTweak/Languages/uk/Localize.xaml@@ -41,7 +41,7 @@<v:String x:Key="export_warning_noty">Це не має сенсу, спочатку застосуйте принаймні одне налаштування</v:String><v:String x:Key="success_onedrive_noty">Розпочато процес відновлення OneDrive, на це потрібен деякий час</v:String><v:String x:Key="error_onedrive_noty">OneDrive setup file missing, recovery impossible</v:String>- <v:String x:Key="warn_wd_noty">Expect the process to terminate automatically and the system to restart</v:String>+ <v:String x:Key="warn_wd_noty">Await the process completion followed by system restart</v:String><v:String x:Key="info_wd_noty">Процес потребує деякого часу, будь ласка, зачекайте</v:String><v:String x:Key="warn_firewall_noty">Ваш брандмауер вимкнено, увімкніть та застосовуйте налаштування знову</v:String><v:String x:Key="warn_activate_noty">Для початку активуйте Windows. Не всі налаштування можна застосовувати на не активованій ОС</v:String>diff --git a/.Source/GTweak/Utilities/Helpers/TakingOwnership.cs b/.Source/GTweak/Utilities/Helpers/TakingOwnership.csindex 4b1572a1..e68b5fc0 100644--- a/.Source/GTweak/Utilities/Helpers/TakingOwnership.cs+++ b/.Source/GTweak/Utilities/Helpers/TakingOwnership.cs@@ -1,6 +1,6 @@-using System;+using System;using System.Runtime.InteropServices;-using System.Threading.Tasks;+using GTweak.Utilities.Controls;namespace GTweak.Utilities.Helpers{@@ -185,84 +185,92 @@ namespace GTweak.Utilities.Helpersinternal static void GrantAdministratorsAccess(string name, SE_OBJECT_TYPE type){- Task.Run(delegate+ SID_IDENTIFIER_AUTHORITY sidNTAuthority = SECURITY_NT_AUTHORITY;++ IntPtr sidAdmin = IntPtr.Zero;+ IntPtr sidUsers = IntPtr.Zero;+ IntPtr sidTrustedInstaller = IntPtr.Zero;+ IntPtr sidWD = IntPtr.Zero;++ AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ref sidAdmin);+ AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, ref sidUsers);+ AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_TRUSTED_INSTALLER, 0, 0, 0, 0, 0, 0, ref sidTrustedInstaller);+ AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_WD, 0, 0, 0, 0, 0, 0, ref sidWD);++ EXPLICIT_ACCESS[] explicitAccesss = new EXPLICIT_ACCESS[4];++ explicitAccesss[0].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL;+ explicitAccesss[0].grfAccessMode = ACCESS_MODE.SET_ACCESS;+ explicitAccesss[0].grfInheritance = NO_INHERITANCE;+ explicitAccesss[0].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;+ explicitAccesss[0].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;+ explicitAccesss[0].Trustee.ptstrName = sidAdmin;++ explicitAccesss[1].grfAccessPermissions = ACCESS_MASK.GENERIC_READ | ACCESS_MASK.GENERIC_WRITE;+ explicitAccesss[1].grfAccessMode = ACCESS_MODE.SET_ACCESS;+ explicitAccesss[1].grfInheritance = NO_INHERITANCE;+ explicitAccesss[1].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;+ explicitAccesss[1].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;+ explicitAccesss[1].Trustee.ptstrName = sidUsers;++ explicitAccesss[2].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL;+ explicitAccesss[2].grfAccessMode = ACCESS_MODE.DENY_ACCESS;+ explicitAccesss[2].grfInheritance = NO_INHERITANCE;+ explicitAccesss[2].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;+ explicitAccesss[2].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;+ explicitAccesss[2].Trustee.ptstrName = sidTrustedInstaller;++ explicitAccesss[3].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL;+ explicitAccesss[3].grfAccessMode = ACCESS_MODE.DENY_ACCESS;+ explicitAccesss[3].grfInheritance = NO_INHERITANCE;+ explicitAccesss[3].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;+ explicitAccesss[3].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;+ explicitAccesss[3].Trustee.ptstrName = sidWD;++ IntPtr acl = IntPtr.Zero;+ SetEntriesInAcl(4, ref explicitAccesss[0], (IntPtr)0, ref acl);++ static void setPrivilege(string privilege, bool allow){- SID_IDENTIFIER_AUTHORITY sidNTAuthority = SECURITY_NT_AUTHORITY;-- IntPtr sidAdmin = IntPtr.Zero;- IntPtr sidUsers = IntPtr.Zero;- IntPtr sidTrustedInstaller = IntPtr.Zero;- IntPtr sidWD = IntPtr.Zero;-- AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ref sidAdmin);- AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, ref sidUsers);- AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_TRUSTED_INSTALLER, 0, 0, 0, 0, 0, 0, ref sidTrustedInstaller);- AllocateAndInitializeSid(ref sidNTAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_WD, 0, 0, 0, 0, 0, 0, ref sidWD);-- EXPLICIT_ACCESS[] explicitAccesss = new EXPLICIT_ACCESS[4];-- explicitAccesss[0].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL;- explicitAccesss[0].grfAccessMode = ACCESS_MODE.SET_ACCESS;- explicitAccesss[0].grfInheritance = NO_INHERITANCE;- explicitAccesss[0].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;- explicitAccesss[0].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;- explicitAccesss[0].Trustee.ptstrName = sidAdmin;-- explicitAccesss[1].grfAccessPermissions = ACCESS_MASK.GENERIC_READ | ACCESS_MASK.GENERIC_WRITE;- explicitAccesss[1].grfAccessMode = ACCESS_MODE.SET_ACCESS;- explicitAccesss[1].grfInheritance = NO_INHERITANCE;- explicitAccesss[1].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;- explicitAccesss[1].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;- explicitAccesss[1].Trustee.ptstrName = sidUsers;-- explicitAccesss[2].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL;- explicitAccesss[2].grfAccessMode = ACCESS_MODE.DENY_ACCESS;- explicitAccesss[2].grfInheritance = NO_INHERITANCE;- explicitAccesss[2].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;- explicitAccesss[2].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;- explicitAccesss[2].Trustee.ptstrName = sidTrustedInstaller;-- explicitAccesss[3].grfAccessPermissions = ACCESS_MASK.GENERIC_ALL;- explicitAccesss[3].grfAccessMode = ACCESS_MODE.DENY_ACCESS;- explicitAccesss[3].grfInheritance = NO_INHERITANCE;- explicitAccesss[3].Trustee.TrusteeForm = TRUSTEE_FORM.TRUSTEE_IS_SID;- explicitAccesss[3].Trustee.TrusteeType = TRUSTEE_TYPE.TRUSTEE_IS_GROUP;- explicitAccesss[3].Trustee.ptstrName = sidWD;-- IntPtr acl = IntPtr.Zero;- SetEntriesInAcl(4, ref explicitAccesss[0], (IntPtr)0, ref acl);-- static void setPrivilege(string privilege, bool allow)+ TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES();+ OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out IntPtr token);++ if (allow){- TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES();- OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out IntPtr token);-- if (allow)- {- LookupPrivilegeValueA(null, privilege, out LUID luid);- tokenPrivileges.PrivilegeCount = 1;- tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1];- tokenPrivileges.Privileges[0].Luid = luid;- tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;- }-- AdjustTokenPrivileges(token, false, ref tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero);- CloseHandle(token);+ LookupPrivilegeValueA(null, privilege, out LUID luid);+ tokenPrivileges.PrivilegeCount = 1;+ tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1];+ tokenPrivileges.Privileges[0].Luid = luid;+ tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;}- setPrivilege(SE_TAKE_OWNERSHIP_NAME, true);+ AdjustTokenPrivileges(token, false, ref tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero);+ CloseHandle(token);+ }++ setPrivilege(SE_TAKE_OWNERSHIP_NAME, true);++ try+ {+ if (sidAdmin != IntPtr.Zero)+ {+ SetNamedSecurityInfo(name, type, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, sidAdmin, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);+ }- SetNamedSecurityInfo(name, type, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, sidAdmin, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);- SetNamedSecurityInfo(name, type, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, acl, IntPtr.Zero);+ if (acl != IntPtr.Zero)+ {+ SetNamedSecurityInfo(name, type, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, acl, IntPtr.Zero);+ }+ }+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }- setPrivilege(SE_TAKE_OWNERSHIP_NAME, false);+ setPrivilege(SE_TAKE_OWNERSHIP_NAME, false);- FreeSid(sidAdmin);- FreeSid(sidUsers);- FreeSid(sidTrustedInstaller);- FreeSid(sidWD);- LocalFree(acl);- }).Wait();+ FreeSid(sidAdmin);+ FreeSid(sidUsers);+ FreeSid(sidTrustedInstaller);+ FreeSid(sidWD);+ LocalFree(acl);}}}\ No newline at end of filediff --git a/.Source/GTweak/Utilities/Tweaks/DefenderManager/BackupRights.cs b/.Source/GTweak/Utilities/Tweaks/DefenderManager/BackupRights.csindex 20f0952b..6a586826 100644--- a/.Source/GTweak/Utilities/Tweaks/DefenderManager/BackupRights.cs+++ b/.Source/GTweak/Utilities/Tweaks/DefenderManager/BackupRights.cs@@ -6,6 +6,7 @@ using GTweak.Utilities.Controls;using GTweak.Utilities.Managers;using Microsoft.Win32;using Newtonsoft.Json;+using Newtonsoft.Json.Linq;namespace GTweak.Utilities.Tweaks.DefenderManager{@@ -27,6 +28,9 @@ namespace GTweak.Utilities.Tweaks.DefenderManager[@"SYSTEM\CurrentControlSet\Services\MsSecWfp"] = RegistryHive.LocalMachine,[@"SYSTEM\CurrentControlSet\Services\webthreatdefsvc"] = RegistryHive.LocalMachine,[@"SYSTEM\CurrentControlSet\Services\webthreatdefusersvc"] = RegistryHive.LocalMachine,+ [@"SYSTEM\CurrentControlSet\Services\wscsvc"] = RegistryHive.LocalMachine,+ [@"SYSTEM\CurrentControlSet\Services\WdFilter"] = RegistryHive.LocalMachine,+ [@"SYSTEM\CurrentControlSet\Services\WdFilter\Instances\WdFilter Instance"] = RegistryHive.LocalMachine,[@"SYSTEM\CurrentControlSet\Control\CI"] = RegistryHive.LocalMachine,[@"SYSTEM\CurrentControlSet\Control\CI\Policy"] = RegistryHive.LocalMachine,[@"SYSTEM\CurrentControlSet\Control\CI\State"] = RegistryHive.LocalMachine,@@ -78,16 +82,33 @@ namespace GTweak.Utilities.Tweaks.DefenderManager[@"SOFTWARE\Microsoft\Windows Advanced Threat Protection"] = RegistryHive.LocalMachine,[@"SOFTWARE\Microsoft\Windows Defender Security Center\Notifications"] = RegistryHive.LocalMachine,[@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"] = RegistryHive.LocalMachine,+ [@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\MsMpEng.exe"] = RegistryHive.LocalMachine,+ [@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\runtimebroker.exe"] = RegistryHive.LocalMachine,+ [@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\MRT.exe"] = RegistryHive.LocalMachine,};+ private sealed class RegistryValueBackup+ {+ internal string Kind { get; set; }+ internal object Value { get; set; }+ }++ private class FileRightsInfo+ {+ internal string OriginalPath { get; set; }+ internal string Owner { get; set; }+ internal string Permissions { get; set; }+ internal string Sddl { get; set; }+ }+internal static void ExportRights(){try{Directory.CreateDirectory(PathLocator.Folders.DefenderBackup);- Dictionary<string, Dictionary<string, object>> allValues = new Dictionary<string, Dictionary<string, object>>();- Dictionary<string, string> aclDataDict = new Dictionary<string, string>();+ Dictionary<string, Dictionary<string, RegistryValueBackup>> allValues = new Dictionary<string, Dictionary<string, RegistryValueBackup>>(StringComparer.OrdinalIgnoreCase);+ Dictionary<string, string> aclDataDict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);if (_storageRegPaths == null || _storageRegPaths.Count == 0){@@ -99,101 +120,153 @@ namespace GTweak.Utilities.Tweaks.DefenderManagerstring path = entry.Key;RegistryHive hive = entry.Value;- try+ foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 }){- using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Registry64);- using RegistryKey key = baseKey.OpenSubKey(path, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey | RegistryRights.ReadPermissions);+ string keyId = $"{view}:{path}";- if (key == null)- {- continue;- }- Dictionary<string, object> values = new Dictionary<string, object>();- foreach (string valueName in key.GetValueNames())+ try{- object val = key.GetValue(valueName);- if (val is byte[] byteVal)+ using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view);+ using RegistryKey key = baseKey.OpenSubKey(path, RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey | RegistryRights.ReadPermissions);++ if (key == null){- values[valueName] = Convert.ToBase64String(byteVal);+ continue;}- else++ var values = new Dictionary<string, RegistryValueBackup>(StringComparer.Ordinal);++ foreach (string valueName in key.GetValueNames()){- values[valueName] = val;+ try+ {+ RegistryValueKind kind = key.GetValueKind(valueName);+ object val = key.GetValue(valueName);++ if (val is byte[] bytes)+ {+ values[valueName] = new RegistryValueBackup+ {+ Kind = kind.ToString(),+ Value = Convert.ToBase64String(bytes)+ };+ }+ else+ {+ values[valueName] = new RegistryValueBackup+ {+ Kind = kind.ToString(),+ Value = val+ };+ }+ }+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }}- }- allValues[path] = values;- try- {- RegistrySecurity security = key.GetAccessControl();- string aclData = security.GetSecurityDescriptorSddlForm(AccessControlSections.All);- aclDataDict[path] = aclData;+ allValues[keyId] = values;++ try+ {+ RegistrySecurity security = key.GetAccessControl(AccessControlSections.All);+ string aclData = security.GetSecurityDescriptorSddlForm(AccessControlSections.All);+ aclDataDict[keyId] = aclData;+ }+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }}catch (Exception ex) { ErrorLogging.LogDebug(ex); }}- catch (Exception ex) { ErrorLogging.LogDebug(ex); }}File.WriteAllText(PathLocator.Files.BackupDataJson, JsonConvert.SerializeObject(allValues, Formatting.Indented));File.WriteAllText(PathLocator.Files.BackupRightsAcl, JsonConvert.SerializeObject(aclDataDict, Formatting.Indented));-}catch (Exception ex) { ErrorLogging.LogDebug(ex); }}-internal static void ImportRights(){if (File.Exists(PathLocator.Files.BackupDataJson) && File.Exists(PathLocator.Files.BackupRightsAcl)){try{- Dictionary<string, Dictionary<string, object>> allValues = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(File.ReadAllText(PathLocator.Files.BackupDataJson));+ Dictionary<string, Dictionary<string, RegistryValueBackup>> allValues = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, RegistryValueBackup>>>(File.ReadAllText(PathLocator.Files.BackupDataJson));Dictionary<string, string> aclDataDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(PathLocator.Files.BackupRightsAcl));- foreach (var entry in _storageRegPaths)+ if (allValues == null){- string path = entry.Key;- RegistryHive hive = entry.Value;+ return;+ }++ foreach (var kv in allValues)+ {+ string keyId = kv.Key;+ string[] parts = keyId.Split(new[] { ':' }, 2);+ if (parts.Length != 2)+ {+ continue;+ }++ if (!Enum.TryParse(parts[0], out RegistryView view))+ {+ continue;+ }++ string path = parts[1];++ if (!_storageRegPaths.TryGetValue(path, out RegistryHive hive))+ {+ hive = RegistryHive.LocalMachine;+ }try{- using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Registry64);- using RegistryKey key = baseKey.OpenSubKey(path, true) ?? baseKey.CreateSubKey(path);+ using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, view);+ using RegistryKey key = baseKey.CreateSubKey(path, true);if (key == null){continue;}- if (allValues.ContainsKey(path))+ foreach (var valuePair in kv.Value){- foreach (var pair in allValues[path])+ string valueName = valuePair.Key;+ RegistryValueBackup backup = valuePair.Value;++ if (backup == null){- object val = pair.Value;+ continue;+ }- if (val is string sVal)+ if (!Enum.TryParse(backup.Kind, out RegistryValueKind kind))+ {+ try{- try- {- val = Convert.FromBase64String(sVal);- }- catch- {- val = sVal;- }+ key.SetValue(valueName, ConvertJTokenToObject(backup.Value));}+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }- key.SetValue(pair.Key, val);+ continue;+ }++ try+ {+ object valueToSet = ConvertBackupValueToClr(backup.Value, kind);+ key.SetValue(valueName, valueToSet, kind);}+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }}- if (aclDataDict.ContainsKey(path))+ if (aclDataDict != null && aclDataDict.TryGetValue(keyId, out string sddl) && !string.IsNullOrWhiteSpace(sddl)){- string aclData = aclDataDict[path];- RegistrySecurity security = new RegistrySecurity();- security.SetSecurityDescriptorSddlForm(aclData);- key.SetAccessControl(security);+ try+ {+ RegistrySecurity security = new RegistrySecurity();+ security.SetSecurityDescriptorSddlForm(sddl);++ key.SetAccessControl(security);+ }+ catch (Exception ex) { ErrorLogging.LogDebug(ex); }}}catch (Exception ex) { ErrorLogging.LogDebug(ex); }@@ -202,5 +275,80 @@ namespace GTweak.Utilities.Tweaks.DefenderManagercatch (Exception ex) { ErrorLogging.LogDebug(ex); }}}++ private static object ConvertBackupValueToClr(object rawValue, RegistryValueKind kind)+ {+ if (rawValue is JToken token)+ {+ switch (kind)+ {+ case RegistryValueKind.Binary:+ string b64 = token.Type == JTokenType.String ? token.ToObject<string>() : token.ToString(Formatting.None);+ return Convert.FromBase64String(b64);+ case RegistryValueKind.DWord:+ return token.ToObject<int>();+ case RegistryValueKind.QWord:+ return token.ToObject<long>();+ case RegistryValueKind.MultiString:+ return token.ToObject<string[]>();+ case RegistryValueKind.String:+ case RegistryValueKind.ExpandString:+ return token.ToObject<string>();+ case RegistryValueKind.None:+ default:+ return token.ToObject<object>();+ }+ }++ switch (kind)+ {+ case RegistryValueKind.Binary:+ if (rawValue is string s)+ {+ return Convert.FromBase64String(s);+ }++ if (rawValue is byte[] bytes)+ {+ return bytes;+ }++ break;+ case RegistryValueKind.DWord:+ return Convert.ToInt32(rawValue);+ case RegistryValueKind.QWord:+ return Convert.ToInt64(rawValue);+ case RegistryValueKind.MultiString:+ if (rawValue is JArray jarr)+ {+ return jarr.ToObject<string[]>();+ }++ if (rawValue is string[] sa)+ {+ return sa;+ }++ break;+ case RegistryValueKind.String:+ case RegistryValueKind.ExpandString:+ return rawValue?.ToString();+ case RegistryValueKind.None:+ default:+ return rawValue;+ }++ return rawValue;+ }++ private static object ConvertJTokenToObject(object tokenOrObj)+ {+ if (tokenOrObj is JToken t)+ {+ return t.ToObject<object>();+ }++ return tokenOrObj;+ }}}diff --git a/.Source/GTweak/Utilities/Tweaks/DefenderManager/WindowsDefender.cs b/.Source/GTweak/Utilities/Tweaks/DefenderManager/WindowsDefender.csindex 532595ef..a5a622f3 100644--- a/.Source/GTweak/Utilities/Tweaks/DefenderManager/WindowsDefender.cs+++ b/.Source/GTweak/Utilities/Tweaks/DefenderManager/WindowsDefender.cs@@ -109,7 +109,6 @@ namespace GTweak.Utilities.Tweaks.DefenderManager@"reg delete ""HKCU\Software\Microsoft\Windows\CurrentVersion\AppHost"" /v EnableWebContentEvaluation /t REG_DWORD /d 0 /f & " +@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\MicrosoftEdge\PhishingFilter"" /v EnabledV9 /f & " +@"reg add ""HKLM\SOFTWARE\Microsoft\Windows Defender"" /v PUAProtection /t REG_DWORD /d 2 /f & " +- @"reg add ""HKLM\SOFTWARE\Microsoft\Windows Defender\Features"" /v TamperProtection /t REG_DWORD /d 1 /f & " +@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\MRT"" /v DontOfferThroughWUA /f & " +@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\MRT"" /v DontReportInfectionInformation /f & " +@"reg delete ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\SmartScreen"" /v ConfigureAppInstallControl /f & " +@@ -122,17 +121,7 @@ namespace GTweak.Utilities.Tweaks.DefenderManagerRegistryHelp.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer", "SmartScreenEnabled", "On", RegistryValueKind.String);RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows\System", "EnableSmartScreen");RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\Policy Manager");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\MpEngine");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\Scan");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\SmartScreen");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\Reporting");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\SpyNet");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\UX Configuration");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender Security Center");RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Microsoft Antimalware");- RegistryHelp.DeleteFolderTree(Registry.LocalMachine, @"SOFTWARE\Policies\Microsoft\Windows Defender\Signature Updates");RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Security Center", "FirstRunDisabled");RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Security Center", "AntiVirusOverride");RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Security Center", "FirewallOverride");@@ -179,9 +168,11 @@ namespace GTweak.Utilities.Tweaks.DefenderManagerRegistryHelp.Write(Registry.ClassesRoot, @"CLSID\{09A47860-11B0-4DA5-AFA5-26D86198A780}\InprocServer32", "", PathLocator.Folders.SystemDrive + @"Program Files\Windows Defender\shellext.dll", RegistryValueKind.String);RegistryHelp.Write(Registry.ClassesRoot, @"CLSID\{09A47860-11B0-4DA5-AFA5-26D86198A780}\InprocServer32", "ThreadingModel", "Apartment", RegistryValueKind.String);- ManageExclusions(false);+ RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows defender\Windows defender Exploit Guard\ASR", "EnableASRConsumers");+ RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows defender\Windows defender Exploit Guard\Controlled Folder Access", "EnableControlledFolderAccess");+ RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows Defender\Windows Defender Exploit Guard\Network Protection", "EnableNetworkProtection");- CommandExecutor.RunCommandAsTrustedInstaller($@"{PathLocator.Executable.NSudo} -U:T -P:E -M:S -ShowWindowMode:Hide cmd /c " ++ CommandExecutor.RunCommandAsTrustedInstaller($@"{PathLocator.Executable.NSudo}-U:T -P:E -M:S -ShowWindowMode:Hide cmd /c " +@"reg delete HKLM\SYSTEM\CurrentControlSet\Services\WinDefend /v AutorunsDisabled /f & " +@"reg add HKLM\SYSTEM\CurrentControlSet\Services\wscsvc /v DelayedAutoStart /t REG_DWORD /d 1 /f & " +@"reg add ""HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Instances\WdFilter Instance"" /v Altitude /t REG_SZ /d 328010 /f & " +@@ -198,30 +189,19 @@ namespace GTweak.Utilities.Tweaks.DefenderManager@"reg add ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender"" /v DisableAntiSpyware /t REG_DWORD /d 0 /f & " +@"reg add ""HKLM\SOFTWARE\Policies\Microsoft\Windows Defender"" /v DisableAntiVirus /t REG_DWORD /d 0 /f");- RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows defender\Windows defender Exploit Guard\ASR", "EnableASRConsumers");- RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows defender\Windows defender Exploit Guard\Controlled Folder Access", "EnableControlledFolderAccess");- RegistryHelp.DeleteValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows Defender\Windows Defender Exploit Guard\Network Protection", "EnableNetworkProtection");-- ImportRights();-+ ManageExclusions(false);SetTaskState(true, winDefenderTasks);+ CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathLocator.Executable.NSudo}"" -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c {CleanCommand(string.Join(" & ", services.Select(kv => $@"reg add ""HKLM\SYSTEM\CurrentControlSet\Services\{kv.Key}"" /v Start /t REG_DWORD /d {kv.Value} /f")))}""");+foreach (var (path, normal, block) in fileMappings){- string sourcePath = Path.Combine(path, block);- string targetName = normal;-- CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathLocator.Executable.NSudo}"" -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c ""{CleanCommand(string.Join(" && ", new[] {- $@"takeown /f ""{sourcePath}"" /a",- $@"icacls ""{sourcePath}"" /inheritance:r",- $@"icacls ""{sourcePath}"" /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18",- $@"icacls ""{sourcePath}"" /grant ""{Environment.UserName}"":F",- $@"rename ""{sourcePath}"" ""{targetName}"""- }))}""");+ CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathLocator.Executable.NSudo}"" -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c ""rename ""{Path.Combine(path, block)}"" ""{normal}""""");}- CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathLocator.Executable.NSudo}"" -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c ""{CleanCommand(string.Join(" & ", services.Select(kv => $@"reg add \""HKLM\SYSTEM\CurrentControlSet\Services\{kv.Key}\"" /v Start /t REG_DWORD /d {kv.Value} /f")))}""");+ ImportRights();+ InvokePowerShell("Get-AppxPackage Microsoft.SecHealthUI -AllUsers | Reset-AppxPackage");InvokePowerShell(@"Get-AppXpackage Microsoft.WindowsDefender | Foreach {Add-AppxPackage -DisableDevelopmentMode -Register ""$($_.InstallLocation)\AppXManifest.xml""}");}@@ -233,16 +213,7 @@ namespace GTweak.Utilities.Tweaks.DefenderManagerforeach (var (path, normal, block) in fileMappings){- string sourcePath = Path.Combine(path, normal);- string targetName = block;-- CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathLocator.Executable.NSudo}"" -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c ""{CleanCommand(string.Join(" && ", new[] {- $@"takeown /f ""{sourcePath}"" /a",- $@"icacls ""{sourcePath}"" /inheritance:r",- $@"icacls ""{sourcePath}"" /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18",- $@"icacls ""{sourcePath}"" /grant ""{Environment.UserName}"":F",- $@"rename ""{sourcePath}"" ""{targetName}"""- }))}""");+ CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathLocator.Executable.NSudo}"" -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c ""rename ""{Path.Combine(path, normal)}"" ""{block}""""");}CommandExecutor.RunCommandAsTrustedInstaller($@"""{PathLocator.Executable.NSudo}"" -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c {CleanCommand(string.Join(" & ", services.Select(kv => $@"reg add ""HKLM\SYSTEM\CurrentControlSet\Services\{kv.Key}"" /v Start /t REG_DWORD /d 4 /f")))}""");@@ -430,7 +401,6 @@ namespace GTweak.Utilities.Tweaks.DefenderManagerRegistryHelp.DeleteFolderTree(Registry.ClassesRoot, @"Drive\shellex\ContextMenuHandlers\EPP");RegistryHelp.DeleteFolderTree(Registry.ClassesRoot, @"CLSID\{09A47860-11B0-4DA5-AFA5-26D86198A780}\InprocServer32");- CommandExecutor.RunCommand("Get-PSDrive -PSProvider FileSystem | ForEach-Object { Add-MpPreference -ExclusionPath \"$($_.Root)\" } ", true);ManageExclusions(true);foreach (var directory in new[]@@ -449,7 +419,7 @@ namespace GTweak.Utilities.Tweaks.DefenderManagerforeach (var filePath in Directory.EnumerateFiles(directory, "*", SearchOption.TopDirectoryOnly)){- CommandExecutor.RunCommandAsTrustedInstaller($@"{PathLocator.Executable.NSudo} -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c ""takeown /f \""{filePath}\"" /r /d y && icacls \""{filePath}\"" /inheritance:r /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18 && icacls \""{filePath}\"" /grant {Environment.UserName}:F /t && rd /s /q \""{filePath}\""""");+ CommandExecutor.RunCommandAsTrustedInstaller($@"{PathLocator.Executable.NSudo} -U:T -P:E -M:S -ShowWindowMode:Hide -Wait cmd /c ""takeown /f \""{filePath}\"" /r /d y && icacls \""{filePath}\"" /inheritance:r /remove *S-1-5-32-544 *S-1-5-11 *S-1-5-32-545 *S-1-5-18 && icacls \""{filePath}\"" /grant {Environment.UserName}:F /t && del /q \""{filePath}\""""");for (int i = 0; Directory.Exists(filePath) && i < 10; i++){@@ -475,7 +445,18 @@ namespace GTweak.Utilities.Tweaks.DefenderManagerRegistryHelp.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "PromptOnSecureDesktop", 0, RegistryValueKind.DWord);RegistryHelp.Write(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "Shell", $"explorer.exe, {PathLocator.Executable.DisablingWD} /unlock", RegistryValueKind.String, true);- CommandExecutor.RunCommandAsTrustedInstaller("/c \"bcdedit /set {current} safeboot minimal && shutdown /r /f /t 0\"");++ ProcessStartInfo psi = new ProcessStartInfo+ {+ FileName = PathLocator.Executable.BcdEdit,+ Arguments = "/set {current} safeboot minimal",+ UseShellExecute = false,+ CreateNoWindow = true,+ RedirectStandardOutput = true,+ RedirectStandardError = true+ };+ Process.Start(psi)?.WaitForExit();+ CommandExecutor.RunCommand("/c shutdown /r /f /t 0");}private static void ManageExclusions(bool isDisable)diff --git a/.Source/GTweak/Utilities/Tweaks/SystemTweaks.cs b/.Source/GTweak/Utilities/Tweaks/SystemTweaks.csindex bed3e807..b9a28ddf 100644--- a/.Source/GTweak/Utilities/Tweaks/SystemTweaks.cs+++ b/.Source/GTweak/Utilities/Tweaks/SystemTweaks.cs@@ -247,18 +247,22 @@ namespace GTweak.Utilities.Tweaksbreak;case "TglButton3":BlockWDefender(isDisabled);+ ArchiveManager.Unarchive(PathLocator.Executable.NSudo, Properties.Resources.NSudoLC);+ ArchiveManager.Unarchive(PathLocator.Executable.DisablingWD, Properties.Resources.DisablingWD);if (canShowWindow){OverlayWindow overlayWindow = new OverlayWindow();overlayWindow.Show();- ArchiveManager.Unarchive(PathLocator.Executable.NSudo, Properties.Resources.NSudoLC);- ArchiveManager.Unarchive(PathLocator.Executable.DisablingWD, Properties.Resources.DisablingWD);-BackgroundQueue backgroundQueue = new BackgroundQueue();await backgroundQueue.QueueTask(delegate { NotificationManager.Show(isDisabled ? "warn" : "info", isDisabled ? "warn_wd_noty" : "info_wd_noty").Perform(); });await backgroundQueue.QueueTask(delegate { WindowsDefender.SetProtectionState(isDisabled); });- await backgroundQueue.QueueTask(delegate { NotificationManager.Show().WithDelay(300).Restart(); });++ if (!isDisabled)+ {+ await backgroundQueue.QueueTask(delegate { NotificationManager.Show().WithDelay(300).Restart(); });+ CommandExecutor.RunCommand($"/c timeout /t 10 && del /f \"{PathLocator.Executable.NSudo}\"");+ }overlayWindow.Close();}diff --git a/.Source/GTweak/Windows/ImportWindow.xaml.cs b/.Source/GTweak/Windows/ImportWindow.xaml.csindex c3dac138..35253bc8 100644--- a/.Source/GTweak/Windows/ImportWindow.xaml.cs+++ b/.Source/GTweak/Windows/ImportWindow.xaml.cs@@ -68,15 +68,15 @@ namespace GTweak.Windowsvar allSections = new (string Section, Action<string, bool> TweakAction, IEnumerable<KeyValuePair<string, NotificationManager.NoticeAction>> NoticeActions, IEnumerable<KeyValuePair<string, bool>> ExplorerMapping)[]{- (INIManager.SectionConf, _confTweaks.ApplyTweaks, NotificationManager.ConfActions, null),- (INIManager.SectionIntf, _intfTweaks.ApplyTweaks, NotificationManager.IntfActions, ExplorerManager.IntfMapping),- (INIManager.SectionSvc, _svcTweaks.ApplyTweaks, null, null),- (INIManager.SectionSys, null, NotificationManager.SysActions, null)+ (INIManager.SectionConf, _confTweaks.ApplyTweaks, NotificationManager.ConfActions, null),+ (INIManager.SectionIntf, _intfTweaks.ApplyTweaks, NotificationManager.IntfActions, ExplorerManager.IntfMapping),+ (INIManager.SectionSvc, _svcTweaks.ApplyTweaks, null, null),+ (INIManager.SectionSys, null, NotificationManager.SysActions, null)};var allTweaks = new List<(string section, string tweak, string value)>();- foreach (var (Section, _, _, _) in allSections.Where(sectionInfo => iniManager.IsThereSection(sectionInfo.Section)))+ foreach (var (Section, _, _, _) in allSections.Where(s => iniManager.IsThereSection(s.Section))){var keys = iniManager.GetKeysOrValue(Section);var values = iniManager.GetKeysOrValue(Section, false);@@ -89,9 +89,16 @@ namespace GTweak.Windowsif (totalTweaks == 0){progress.Report(100);+ return;}- foreach (var (section, tweak, value) in allTweaks)+ var sysTweaks = allTweaks.Where(t => t.section == INIManager.SectionSys).ToList();+ var sysTweaksLast = sysTweaks.Where(t => t.tweak == "TglButton3").ToList();+ var sysTweaksFirst = sysTweaks.Where(t => t.tweak != "TglButton3").ToList();++ var tweaksToApply = allTweaks.Where(t => t.section != INIManager.SectionSys).Concat(sysTweaksFirst).Concat(sysTweaksLast).ToList();++ foreach (var (section, tweak, value) in tweaksToApply){token.ThrowIfCancellationRequested();try@@ -102,36 +109,45 @@ namespace GTweak.Windows{_sysTweaks.ApplyTweaks(tweak, Convert.ToBoolean(value));}- else if (tweak == "TglButton8")+ else if (tweak == "TglButton3"){BackgroundQueue backgroundQueue = new BackgroundQueue();- await backgroundQueue.QueueTask(delegate { _sysTweaks.ApplyTweaks(tweak, Convert.ToBoolean(value), false); });+ await backgroundQueue.QueueTask(delegate+ {+ _sysTweaks.ApplyTweaks(tweak, Convert.ToBoolean(value), false);+ });++ if (!Convert.ToBoolean(value))+ {+ CommandExecutor.RunCommand($"/c timeout /t 10 && del /f \"{PathLocator.Executable.NSudo}\"");+ }}else{_sysTweaks.ApplyTweaksSlider(tweak, Convert.ToUInt32(value));}- foreach (var act in NotificationManager.SysActions.Where(get => get.Key == tweak))+ foreach (var act in NotificationManager.SysActions.Where(a => a.Key == tweak)){_requiredActions.Add(act.Value);}}else{- var (Section, TweakAction, NoticeActions, ExplorerMapping) = allSections.First(s => s.Section == section);+ var (Section, TweakAction, NoticeActions, ExplorerMapping) =+ allSections.First(s => s.Section == section);TweakAction?.Invoke(tweak, Convert.ToBoolean(value));if (NoticeActions != null){- foreach (var act in NoticeActions.Where(get => get.Key == tweak))+ foreach (var act in NoticeActions.Where(a => a.Key == tweak)){_requiredActions.Add(act.Value);}}- if (ExplorerMapping != null && ExplorerMapping.Any(get => get.Key == tweak && get.Value == true))+ if (ExplorerMapping != null && ExplorerMapping.Any(a => a.Key == tweak && a.Value)){_isExpRestartNeed = true;}@@ -142,12 +158,16 @@ namespace GTweak.Windows}}}- catch (Exception ex) { ErrorLogging.LogDebug(ex); }+ catch (Exception ex)+ {+ ErrorLogging.LogDebug(ex);+ }appliedTweaks++;progress.Report((byte)((double)appliedTweaks / totalTweaks * 100));await Task.Delay(700, token);}}+}}diff --git a/.Source/GTweak/Windows/NotificationWindow.xaml.cs b/.Source/GTweak/Windows/NotificationWindow.xaml.csindex afffe9d1..09ee0659 100644--- a/.Source/GTweak/Windows/NotificationWindow.xaml.cs+++ b/.Source/GTweak/Windows/NotificationWindow.xaml.cs@@ -42,7 +42,13 @@ namespace GTweak.Windowsprivate void ButtonClose_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) => Close();- private void Grid_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) => CommandExecutor.RunCommand(RequiredAction == NotificationManager.NoticeAction.Logout ? @"/c logoff" : @"/c shutdown /r /t 0");+ private void Grid_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)+ {+ if (RequiredAction != NotificationManager.NoticeAction.None)+ {+ CommandExecutor.RunCommand(RequiredAction == NotificationManager.NoticeAction.Logout ? @"/c logoff" : @"/c shutdown /r /t 0");+ }+ }private void Window_Loaded(object sender, RoutedEventArgs e){