// Zero Frame engine: every tweak, its check, its backup and its undo. No PowerShell anywhere. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Management; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Text; using System.Text.RegularExpressions; using System.Web.Script.Serialization; using Microsoft.Win32; namespace ZeroFrame { public class Tweak { public string Id, Pack, Name, Preset, Impact, Why; public Func Test; public Action Apply; public bool Reboot, OneTime; public bool IsTool { get { return Preset == "Tool"; } } } public class Check { public string Area, Value, Detail, Level; // Level: ok | warn | info | tip } static class Native { [DllImport("user32.dll")] public static extern bool SystemParametersInfo(uint a, uint b, int[] c, uint d); [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] public static extern bool SystemParametersInfoPtr(uint a, uint b, IntPtr c, uint d); [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)] public static extern int CM_Locate_DevNodeW(out uint dev, string id, int flags); [DllImport("cfgmgr32.dll")] public static extern int CM_Get_Parent(out uint parent, uint dev, int flags); [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)] public static extern int CM_Get_Device_IDW(uint dev, StringBuilder buf, int len, int flags); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DEVMODE { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName; public short dmSpecVersion, dmDriverVersion, dmSize, dmDriverExtra; public int dmFields; public int dmPositionX, dmPositionY, dmDisplayOrientation, dmDisplayFixedOutput; public short dmColor, dmDuplex, dmYResolution, dmTTOption, dmCollate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName; public short dmLogPixels; public int dmBitsPerPel, dmPelsWidth, dmPelsHeight, dmDisplayFlags, dmDisplayFrequency; public int dmICMMethod, dmICMIntent, dmMediaType, dmDitherType, dmReserved1, dmReserved2, dmPanningWidth, dmPanningHeight; } // Windows' official restore-point API (srclient.dll): begin, then end, so the point is finalized immediately. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)] public struct RESTOREPOINTINFOW { public int dwEventType; public int dwRestorePtType; public long llSequenceNumber; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string szDescription; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct STATEMGRSTATUS { public uint nStatus; public long llSequenceNumber; } [DllImport("srclient.dll", CharSet = CharSet.Unicode)] static extern bool SRSetRestorePointW(ref RESTOREPOINTINFOW info, out STATEMGRSTATUS status); // Returns false only if the API isn't available; otherwise status is 0 on success or a Windows error code. public static bool TryRestorePoint(string desc, out long seq, out uint status) { seq = 0; status = 0; try { RESTOREPOINTINFOW begin = new RESTOREPOINTINFOW { dwEventType = 100, dwRestorePtType = 12, llSequenceNumber = 0, szDescription = desc }; STATEMGRSTATUS st; bool ok = SRSetRestorePointW(ref begin, out st); if (!ok || st.nStatus != 0) { status = st.nStatus != 0 ? st.nStatus : 1u; return true; } seq = st.llSequenceNumber; RESTOREPOINTINFOW end = new RESTOREPOINTINFOW { dwEventType = 101, dwRestorePtType = 12, llSequenceNumber = seq, szDescription = desc }; SRSetRestorePointW(ref end, out st); return true; } catch (DllNotFoundException) { return false; } catch (EntryPointNotFoundException) { return false; } } [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern bool EnumDisplaySettings(string dev, int mode, ref DEVMODE dm); [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int ChangeDisplaySettingsEx(string dev, ref DEVMODE dm, IntPtr hwnd, int flags, IntPtr lp); static DEVMODE NewMode() { DEVMODE d = new DEVMODE(); d.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE)); return d; } public static int CurrentHz() { DEVMODE d = NewMode(); EnumDisplaySettings(null, -1, ref d); return d.dmDisplayFrequency; } public static int BestHz() { DEVMODE cur = NewMode(); EnumDisplaySettings(null, -1, ref cur); int best = cur.dmDisplayFrequency; DEVMODE m = NewMode(); for (int i = 0; EnumDisplaySettings(null, i, ref m); i++) if (m.dmPelsWidth == cur.dmPelsWidth && m.dmPelsHeight == cur.dmPelsHeight && m.dmBitsPerPel == cur.dmBitsPerPel && m.dmDisplayFrequency > best) best = m.dmDisplayFrequency; return best; } public static int SetHz(int hz) { DEVMODE d = NewMode(); EnumDisplaySettings(null, -1, ref d); d.dmDisplayFrequency = hz; d.dmFields = 0x400000; int r = ChangeDisplaySettingsEx(null, ref d, IntPtr.Zero, 0x4, IntPtr.Zero); // test the mode first if (r != 0) return r; return ChangeDisplaySettingsEx(null, ref d, IntPtr.Zero, 0x1, IntPtr.Zero); // then apply and save } } public class Engine { public static readonly string DataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ZeroFrame"); static readonly string BackupFile = Path.Combine(DataDir, "backup.json"); static readonly string LogFile = Path.Combine(DataDir, "zerodelay.log"); const string GuidRx = "[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}"; const string NicClass = @"SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}"; public Action OnLog; public bool NicChanged; public readonly bool IsLaptop; public readonly List Tweaks = new List(); List> backup = new List>(); readonly JavaScriptSerializer json = new JavaScriptSerializer(); public static readonly string[] PackOrder = { "CPU & Power", "Input", "GPU & Display", "Network", "Windows UI", "Background", "Storage", "Maintenance" }; public static readonly Dictionary PackDesc = new Dictionary { { "CPU & Power", "Full clocks, awake cores and fast boost, so frame times stay flat." }, { "Input", "True 1:1 mouse, ports that never sleep, no pop-ups mid-match." }, { "GPU & Display", "Max refresh rate, modern presentation, variable refresh, no background capture." }, { "Network", "Steadier packets on Ethernet and Wi-Fi, and no upload hogs mid-match." }, { "Windows UI", "Instant menus, startup apps ready sooner, snappier alt-tab." }, { "Background", "Fewer things waking up behind your game, without breaking your apps." }, { "Storage", "Drives that never stall, fast SSD writes, gigabytes of junk cleared." }, { "Maintenance", "Microsoft's own repair and cleanup tools. They run only when you pick them." } }; public Engine() { try { using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT Name FROM Win32_Battery")) IsLaptop = s.Get().Count > 0; } catch { } Build(); } // ------------------------------------------------------------------ logging public void Log(string m) { string line = "[" + DateTime.Now.ToString("HH:mm:ss") + "] " + m; try { Directory.CreateDirectory(DataDir); File.AppendAllText(LogFile, line + Environment.NewLine); } catch { } if (OnLog != null) OnLog(line); } // ------------------------------------------------------------------ process helper public static string Run(string file, string args, out int code) { ProcessStartInfo psi = new ProcessStartInfo(file, args); psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; try { using (Process p = Process.Start(psi)) { string o = p.StandardOutput.ReadToEnd(); p.StandardError.ReadToEnd(); p.WaitForExit(); code = p.ExitCode; return o; } } catch { code = -1; return ""; } } static string Run(string file, string args) { int c; return Run(file, args, out c); } // ------------------------------------------------------------------ backup store public int BackupCount { get { LoadBackup(); return backup.Count; } } void LoadBackup() { backup = new List>(); try { string legacy = Path.Combine(Path.GetDirectoryName(DataDir), "ZeroDelay", "backup.json"); if (!File.Exists(BackupFile) && File.Exists(legacy)) { Directory.CreateDirectory(DataDir); File.Copy(legacy, BackupFile); } if (!File.Exists(BackupFile)) return; object o = json.DeserializeObject(File.ReadAllText(BackupFile).TrimStart('\uFEFF')); foreach (object item in Arr(o)) { Dictionary d = item as Dictionary; if (d != null) backup.Add(d); } Dictionary single = o as Dictionary; if (single != null) backup.Add(single); } catch (Exception ex) { Log("Could not read the backup file: " + ex.Message); } } void SaveBackup() { Directory.CreateDirectory(DataDir); File.WriteAllText(BackupFile, json.Serialize(backup), new UTF8Encoding(false)); } void AddBackup(params object[] kv) { Dictionary d = new Dictionary(); for (int i = 0; i + 1 < kv.Length; i += 2) d[(string)kv[i]] = kv[i + 1]; string key = (string)d["Key"]; foreach (Dictionary e in backup) if (S(e, "Key") == key) return; // keep only the true original backup.Add(d); SaveBackup(); } static object[] Arr(object v) { if (v == null || v is string || v is Dictionary) return new object[0]; object[] a = v as object[]; if (a != null) return a; IEnumerable en = v as IEnumerable; if (en == null) return new object[0]; List l = new List(); foreach (object x in en) l.Add(x); return l.ToArray(); } static string S(Dictionary d, string k) { object v; return d.TryGetValue(k, out v) && v != null ? Convert.ToString(v) : null; } static bool Bool(Dictionary d, string k) { object v; return d.TryGetValue(k, out v) && v is bool && (bool)v; } static int? Int(object o) { if (o == null) return null; try { return Convert.ToInt32(o); } catch { } int r; return int.TryParse(Convert.ToString(o), out r) ? r : (int?)null; } // ------------------------------------------------------------------ registry static RegistryKey Hive(string path, out string sub) { if (path.StartsWith(@"HKLM:\", StringComparison.OrdinalIgnoreCase)) { sub = path.Substring(6); return RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); } if (path.StartsWith(@"HKCU:\", StringComparison.OrdinalIgnoreCase)) { sub = path.Substring(6); return RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64); } throw new ArgumentException("Unknown registry path " + path); } public static object RegGet(string path, string name) { try { string sub; using (RegistryKey b = Hive(path, out sub)) using (RegistryKey k = b.OpenSubKey(sub)) return k == null ? null : k.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); } catch { return null; } } static int? RegInt(string path, string name) { return Int(RegGet(path, name)); } static string RegStr(string path, string name) { object o = RegGet(path, name); return o == null ? null : Convert.ToString(o); } void SetReg(string path, string name, object value, RegistryValueKind kind) { string sub; using (RegistryKey b = Hive(path, out sub)) { bool existed = false; object old = null; string oldType = null; using (RegistryKey k = b.OpenSubKey(sub)) { if (k != null && k.GetValueNames().Contains(name, StringComparer.OrdinalIgnoreCase)) { existed = true; old = k.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames); oldType = k.GetValueKind(name).ToString(); } } AddBackup("Key", "reg|" + path + "|" + name, "Kind", "reg", "Path", path, "Name", name, "Existed", existed, "Value", old, "Type", oldType); using (RegistryKey k = b.CreateSubKey(sub)) k.SetValue(name, value, kind); } } void Dword(string path, string name, int v) { SetReg(path, name, v, RegistryValueKind.DWord); } void Str(string path, string name, string v) { SetReg(path, name, v, RegistryValueKind.String); } // ------------------------------------------------------------------ power plans public static string ActiveScheme() { Match m = Regex.Match(Run("powercfg", "/getactivescheme"), GuidRx); return m.Success ? m.Value.ToLowerInvariant() : ""; } static int? PowerAc(string scheme, string sub, string setting) { int c; string o = Run("powercfg", "/qh " + scheme + " " + sub + " " + setting, out c); if (c != 0 || o.Trim().Length == 0) o = Run("powercfg", "/q " + scheme + " " + sub + " " + setting, out c); MatchCollection ms = Regex.Matches(o, @"0x([0-9a-fA-F]{8})\s*$", RegexOptions.Multiline); if (ms.Count < 2) return null; return Convert.ToInt32(ms[ms.Count - 2].Groups[1].Value, 16); } static bool PowerIs(string sub, string setting, int want) { int? v = PowerAc(ActiveScheme(), sub, setting); return v == null || v == want; } void SetPower(string sub, string setting, int value) { string scheme = ActiveScheme(); int? old = PowerAc(scheme, sub, setting); if (old == null) { Log(" (not available on this PC)"); return; } AddBackup("Key", "pwr|" + scheme + "|" + sub + "|" + setting, "Kind", "pwr", "Scheme", scheme, "Sub", sub, "Setting", setting, "Value", old.Value); Run("powercfg", "/setacvalueindex " + scheme + " " + sub + " " + setting + " " + value); Run("powercfg", "/setactive " + scheme); } // ------------------------------------------------------------------ services static string SvcKey(string n) { return @"HKLM:\SYSTEM\CurrentControlSet\Services\" + n; } static bool SvcExists(string n) { return RegGet(SvcKey(n), "Start") != null; } void SetService(string n, string mode) { if (!SvcExists(n)) return; AddBackup("Key", "svc|" + n, "Kind", "svc", "Name", n, "Start", RegInt(SvcKey(n), "Start"), "Delayed", RegInt(SvcKey(n), "DelayedAutostart")); Run("sc.exe", "config \"" + n + "\" start= " + mode); if (mode == "disabled") try { using (ServiceController s = new ServiceController(n)) if (s.Status != ServiceControllerStatus.Stopped) s.Stop(); } catch { } Log(" " + n + " -> " + (mode == "demand" ? "Manual" : "Disabled")); } // ------------------------------------------------------------------ network adapters (registry based, any driver language) class Nic { public string Name, Guid, Key; } static List Nics() { List list = new List(); try { using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT NetConnectionID, GUID FROM Win32_NetworkAdapter WHERE PhysicalAdapter = TRUE AND NetConnectionStatus = 2")) foreach (ManagementObject m in s.Get()) { string g = Convert.ToString(m["GUID"]); string key = NicKey(g); if (key != null) list.Add(new Nic { Name = Convert.ToString(m["NetConnectionID"]), Guid = g, Key = key }); } } catch { } return list; } static Nic NicByName(string name) { try { using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT NetConnectionID, GUID FROM Win32_NetworkAdapter WHERE PhysicalAdapter = TRUE")) foreach (ManagementObject m in s.Get()) if (string.Equals(Convert.ToString(m["NetConnectionID"]), name, StringComparison.OrdinalIgnoreCase)) { string g = Convert.ToString(m["GUID"]); string key = NicKey(g); if (key != null) return new Nic { Name = name, Guid = g, Key = key }; } } catch { } return null; } static string NicKey(string guid) { using (RegistryKey b = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) using (RegistryKey c = b.OpenSubKey(NicClass)) { if (c == null) return null; foreach (string n in c.GetSubKeyNames()) { try { using (RegistryKey k = c.OpenSubKey(n)) if (k != null && string.Equals(Convert.ToString(k.GetValue("NetCfgInstanceId")), guid, StringComparison.OrdinalIgnoreCase)) return @"HKLM:\" + NicClass + @"\" + n; } catch { } } } return null; } static bool NicAllows(Nic n, string kw, string val) { try { string sub; using (RegistryKey b = Hive(n.Key + @"\Ndi\Params\" + kw + @"\Enum", out sub)) using (RegistryKey k = b.OpenSubKey(sub)) return k != null && k.GetValueNames().Contains(val); } catch { return false; } } static string NicValue(Nic n, string kw) { string v = RegStr(n.Key, kw); return v ?? RegStr(n.Key + @"\Ndi\Params\" + kw, "default"); } void SetNic(string[] keywords, string val) { foreach (Nic n in Nics()) foreach (string kw in keywords) { if (!NicAllows(n, kw, val) || NicValue(n, kw) == val) continue; SetReg(n.Key, kw, val, RegistryValueKind.String); NicChanged = true; Log(" " + n.Name + ": " + kw + " -> " + val); } } static bool NicIs(string[] keywords, string val) { foreach (Nic n in Nics()) foreach (string kw in keywords) if (NicAllows(n, kw, val) && NicValue(n, kw) != val) return false; return true; } public void RestartNics() { Log("Restarting network adapters (offline for a few seconds)..."); foreach (Nic n in Nics()) { try { using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE GUID = '" + n.Guid + "'")) foreach (ManagementObject m in s.Get()) { m.InvokeMethod("Disable", null); System.Threading.Thread.Sleep(1500); m.InvokeMethod("Enable", null); } } catch (Exception ex) { Log(" Could not restart " + n.Name + ": " + ex.Message); } } } // ------------------------------------------------------------------ WMI, tasks, devices, display static object Cim(string ns, string query, string prop) { try { using (ManagementObjectSearcher s = new ManagementObjectSearcher(new ManagementScope(@"\\.\" + ns), new ObjectQuery(query))) foreach (ManagementObject m in s.Get()) return m[prop]; } catch { } return null; } static readonly string[] TuneNames = { "Disabled", "HighlyRestricted", "Restricted", "Normal", "Experimental" }; static bool? TaskEnabled(string full) { int c; string x = Run("schtasks.exe", "/Query /TN \"" + full + "\" /XML", out c); if (c != 0 || x.Length == 0) return null; Match set = Regex.Match(x, "(.*?)", RegexOptions.Singleline); Match en = Regex.Match(set.Success ? set.Groups[1].Value : "", @"(true|false)"); return !en.Success || en.Groups[1].Value == "true"; } void SetTask(string path, string name) { bool? en = TaskEnabled(path + name); if (en == null) return; AddBackup("Key", "task|" + path + name, "Kind", "task", "Path", path, "Name", name, "Enabled", en.Value); if (en.Value) { Run("schtasks.exe", "/Change /TN \"" + path + name + "\" /Disable"); Log(" " + name + " -> disabled"); } } public static string HidDebug() { List l = HidUsb(); return l.Count + " device(s): " + string.Join(", ", l.ToArray()); } static List HidUsb() { List ids = new List(); try { using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT DeviceID FROM Win32_PnPEntity WHERE (PNPClass = 'Mouse' OR PNPClass = 'Keyboard') AND ConfigManagerErrorCode = 0")) foreach (ManagementObject m in s.Get()) { uint dev; if (Native.CM_Locate_DevNodeW(out dev, Convert.ToString(m["DeviceID"]), 0) != 0) continue; for (int i = 0; i < 4; i++) { uint p; if (Native.CM_Get_Parent(out p, dev, 0) != 0) break; StringBuilder sb = new StringBuilder(512); if (Native.CM_Get_Device_IDW(p, sb, sb.Capacity, 0) != 0) break; string id = sb.ToString(); if (id.StartsWith(@"USB\", StringComparison.OrdinalIgnoreCase) && id.IndexOf("ROOT_HUB", StringComparison.OrdinalIgnoreCase) < 0 && !ids.Contains(id)) ids.Add(id); dev = p; } } } catch { } return ids; } static int? LastAccess() { Match m = Regex.Match(Run("fsutil", "behavior query disablelastaccess"), @"=\s*(\d)"); return m.Success ? int.Parse(m.Groups[1].Value) : (int?)null; } static void ApplyInputLive() { Native.SystemParametersInfo(0x0004, 0, new int[] { 0, 0, 0 }, 3); // mouse acceleration off Native.SystemParametersInfoPtr(0x0071, 0, (IntPtr)10, 3); // pointer speed 10 (6/11) Native.SystemParametersInfoPtr(0x0017, 0, IntPtr.Zero, 3); // keyboard delay 0 Native.SystemParametersInfoPtr(0x000B, 31, IntPtr.Zero, 3); // keyboard repeat 31 } const string Dx = @"HKCU:\Software\Microsoft\DirectX\UserGpuPreferences"; static bool DxHas(string flag) { return (RegStr(Dx, "DirectXUserGlobalSettings") ?? "").Contains(flag); } void SetDx(string name, string val) { List parts = (RegStr(Dx, "DirectXUserGlobalSettings") ?? "").Split(';').Where(p => p.Length > 0 && !p.StartsWith(name + "=")).ToList(); parts.Add(name + "=" + val); Str(Dx, "DirectXUserGlobalSettings", string.Join(";", parts) + ";"); } // ------------------------------------------------------------------ restore point (required) static uint LastRestoreSeq() { uint max = 0; try { using (ManagementObjectSearcher s = new ManagementObjectSearcher(new ManagementScope(@"\\.\root\default"), new ObjectQuery("SELECT SequenceNumber FROM SystemRestore"))) foreach (ManagementObject m in s.Get()) max = Math.Max(max, Convert.ToUInt32(m["SequenceNumber"])); } catch { } return max; } // True if the "original Windows" restore point from before the first tweak still exists. static bool RestorePointExists(string desc) { try { using (ManagementObjectSearcher s = new ManagementObjectSearcher(new ManagementScope(@"\\.\root\default"), new ObjectQuery("SELECT Description FROM SystemRestore"))) foreach (ManagementObject m in s.Get()) if (Convert.ToString(m["Description"]) == desc) return true; } catch { } return false; } static string RestoreError(uint code) { switch (code) { case 1058: return "System Protection is turned off for drive C:."; case 112: return "there isn't enough free disk space."; case 1460: return "Windows was busy making another restore point. Try again in a minute."; default: return "Windows error code " + code + "."; } } public static bool HasBaseline() { try { using (ManagementObjectSearcher s = new ManagementObjectSearcher(new ManagementScope(@"\\.\root\default"), new ObjectQuery("SELECT Description FROM SystemRestore"))) foreach (ManagementObject m in s.Get()) { string d = Convert.ToString(m["Description"]); if (d.StartsWith("Zero Frame", StringComparison.OrdinalIgnoreCase) || d.StartsWith("ZeroDelay", StringComparison.OrdinalIgnoreCase)) return true; } } catch { } return false; } // One restore point of the PC as it was before Zero Frame's first tweak. Later runs reuse it. public bool CreateRestorePoint() { Log("Creating a Windows restore point (this can take a minute)..."); string drive = Path.GetPathRoot(Environment.SystemDirectory); try { using (ManagementClass sr = new ManagementClass(new ManagementScope(@"\\.\root\default"), new ManagementPath("SystemRestore"), null)) { try { sr.InvokeMethod("Enable", new object[] { drive }); } catch { } Dword(@"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore", "SystemRestorePointCreationFrequency", 0); string desc = "Zero Frame " + DateTime.Now.ToString("yyyy-MM-dd HH:mm"); long seq; uint status; if (Native.TryRestorePoint(desc, out seq, out status)) { if (status == 0) { Log("Restore point created: " + desc); return true; } Log(" Windows couldn't create the restore point: " + RestoreError(status)); return false; } // Restore-point API unavailable: fall back to WMI and look for the new point by its name. ManagementBaseObject inP = sr.GetMethodParameters("CreateRestorePoint"); inP["Description"] = desc; inP["RestorePointType"] = 12u; inP["EventType"] = 100u; sr.InvokeMethod("CreateRestorePoint", inP, null); for (int i = 0; i < 30; i++) { if (RestorePointExists(desc)) { Log("Restore point created: " + desc); return true; } System.Threading.Thread.Sleep(2000); } } } catch (Exception ex) { Log(" " + ex.Message); } Log("A restore point could not be created, so nothing was changed."); return false; } // ------------------------------------------------------------------ apply / undo public bool IsApplied(Tweak t) { if (t.OneTime || t.Test == null) return false; try { return t.Test(); } catch { return false; } } public bool DefaultFor(Tweak t, string preset) { if (t.IsTool) return false; if (IsLaptop && (t.Id == "power.plan" || t.Id == "power.cores")) return false; return preset == "Competitive" || t.Preset == "Safe"; } // Returns null if stopped before changing anything, otherwise whether a restart is needed. public bool? ApplyAll(List selected, bool restorePoint) { LoadBackup(); NicChanged = false; bool reboot = false; Log("Applying " + selected.Count + " tweaks."); if (restorePoint) { if (!CreateRestorePoint()) return null; } else Log("Skipping the restore point, as you chose. Every changed value is still saved for Undo."); foreach (Tweak t in selected) { try { Log("Applying: " + t.Name); t.Apply(); if (t.Reboot) reboot = true; } catch (Exception ex) { Log(" Skipped: " + ex.Message); } } if (NicChanged) RestartNics(); Log("Done. Every original value is saved for Undo."); return reboot; } public int UndoAll() { LoadBackup(); if (backup.Count == 0) { Log("Nothing to undo: no Zero Frame changes are recorded on this PC."); return 0; } Log("Restoring " + backup.Count + " original values..."); bool nic = false; for (int i = backup.Count - 1; i >= 0; i--) { Dictionary e = backup[i]; try { switch (S(e, "Kind")) { case "reg": RestoreReg(e); if ((S(e, "Path") ?? "").IndexOf("4d36e972", StringComparison.OrdinalIgnoreCase) >= 0) nic = true; break; case "svc": { int? start = Int(e.ContainsKey("Start") ? e["Start"] : null); string mode = start == 2 ? (Int(e.ContainsKey("Delayed") ? e["Delayed"] : null) == 1 ? "delayed-auto" : "auto") : start == 3 ? "demand" : start == 4 ? "disabled" : null; if (mode != null) Run("sc.exe", "config \"" + S(e, "Name") + "\" start= " + mode); if (start == 2) try { using (ServiceController s = new ServiceController(S(e, "Name"))) s.Start(); } catch { } break; } case "pwr": Run("powercfg", "/setacvalueindex " + S(e, "Scheme") + " " + S(e, "Sub") + " " + S(e, "Setting") + " " + Int(e["Value"])); break; case "plan": Run("powercfg", "/setactive " + S(e, "Scheme")); break; case "nic": // written by Zero Frame 1.x/2.0 (PowerShell edition) { Nic n = NicByName(S(e, "Adapter")); object[] v = Arr(e["Value"]); if (n != null && v.Length > 0) { string sub; using (RegistryKey b = Hive(n.Key, out sub)) using (RegistryKey k = b.CreateSubKey(sub)) k.SetValue(S(e, "Keyword"), Convert.ToString(v[0]), RegistryValueKind.String); nic = true; } break; } case "tcp": Run("netsh", "int tcp set global autotuninglevel=" + (S(e, "Value") ?? "normal").ToLowerInvariant()); break; case "rssg": Run("netsh", "int tcp set global rss=" + ((S(e, "Value") ?? "") == "Disabled" ? "disabled" : "enabled")); break; case "task": if (Bool(e, "Enabled")) Run("schtasks.exe", "/Change /TN \"" + S(e, "Path") + S(e, "Name") + "\" /Enable"); break; case "hz": { int? hz = Int(e["Value"]); if (hz != null) Native.SetHz(hz.Value); break; } case "fsutil": { int? v = Int(e.ContainsKey("Value") ? e["Value"] : null); if (v != null) Run("fsutil", "behavior set disablelastaccess " + v); break; } } } catch (Exception ex) { Log(" Could not restore " + S(e, "Key") + ": " + ex.Message); } } Run("powercfg", "/setactive " + ActiveScheme()); if (nic) RestartNics(); try { File.Move(BackupFile, BackupFile.Replace(".json", "-undone-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".json")); } catch { } int n2 = backup.Count; backup.Clear(); Log("Everything is back to how it was. Restart your PC to finish."); return n2; } void RestoreReg(Dictionary e) { string path = S(e, "Path"), name = S(e, "Name"), sub; using (RegistryKey b = Hive(path, out sub)) { if (!Bool(e, "Existed")) { using (RegistryKey k = b.OpenSubKey(sub, true)) if (k != null) k.DeleteValue(name, false); return; } RegistryValueKind kind = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), S(e, "Type"), true); object v = e["Value"], val; switch (kind) { case RegistryValueKind.DWord: val = unchecked((int)Convert.ToInt64(v)); break; case RegistryValueKind.QWord: val = Convert.ToInt64(v); break; case RegistryValueKind.Binary: val = Arr(v).Select(x => Convert.ToByte(x)).ToArray(); break; case RegistryValueKind.MultiString: val = Arr(v).Select(x => Convert.ToString(x)).ToArray(); break; default: val = Convert.ToString(v); break; } using (RegistryKey k = b.CreateSubKey(sub)) k.SetValue(name, val, kind); } } // ------------------------------------------------------------------ checkup (read-only) public List Checkup() { List r = new List(); try { int cur = Native.CurrentHz(), best = Native.BestHz(); r.Add(new Check { Area = "Display", Value = cur + " Hz", Level = best > cur + 1 ? "warn" : "ok", Detail = best > cur + 1 ? "Your monitor supports " + best + " Hz. The GPU & Display pack can switch it." : "Running at its highest refresh rate." }); } catch { } try { using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT Name, DriverDate FROM Win32_VideoController")) foreach (ManagementObject m in s.Get()) { string name = Convert.ToString(m["Name"]); if (name.IndexOf("Basic", StringComparison.OrdinalIgnoreCase) >= 0 && name.IndexOf("Display", StringComparison.OrdinalIgnoreCase) >= 0) continue; DateTime? drv = null; try { drv = ManagementDateTimeConverter.ToDateTime(Convert.ToString(m["DriverDate"])); } catch { } bool old = drv != null && (DateTime.Now - drv.Value).TotalDays > 180; string tip = name.IndexOf("NVIDIA", StringComparison.OrdinalIgnoreCase) >= 0 ? "Set Reflex to On + Boost in games, and Low Latency Mode to Ultra in the NVIDIA app for the rest." : name.IndexOf("AMD", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("Radeon", StringComparison.OrdinalIgnoreCase) >= 0 ? "Turn on Anti-Lag 2 in supported games and Radeon Anti-Lag for the rest." : "Turn on XeLL in games that support it."; r.Add(new Check { Area = "Graphics", Value = name.Replace("NVIDIA GeForce ", "").Replace("AMD Radeon ", "Radeon "), Level = old ? "warn" : "tip", Detail = (old ? "Driver is from " + drv.Value.ToString("MMM yyyy") + ". Update it. " : "") + tip }); break; } } catch { } try { NetworkInterface up = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback && n.GetIPProperties().GatewayAddresses.Any(g => g.Address.AddressFamily == AddressFamily.InterNetwork)); if (up != null) { bool wifi = up.NetworkInterfaceType == NetworkInterfaceType.Wireless80211; IPAddress gw = up.GetIPProperties().GatewayAddresses.First(g => g.Address.AddressFamily == AddressFamily.InterNetwork).Address; long[] router = PingMany(gw), net = PingMany(IPAddress.Parse("1.1.1.1")); string detail = wifi ? "On Wi-Fi. An Ethernet cable is the biggest single fix for ping spikes." : "Wired connection."; string value = "—"; if (net.Length > 0) { value = (long)net.Average() + " ms"; detail += " Jitter " + (net.Max() - net.Min()) + " ms to the internet."; } if (router.Length > 0) detail += " Router " + (long)router.Average() + " ms."; r.Add(new Check { Area = "Network", Value = value, Detail = detail, Level = wifi || (net.Length > 0 && net.Max() - net.Min() > 15) ? "warn" : "ok" }); } } catch { } try { double gb = 0; using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT TotalPhysicalMemory FROM Win32_ComputerSystem")) foreach (ManagementObject m in s.Get()) gb = Math.Round(Convert.ToDouble(m["TotalPhysicalMemory"]) / 1073741824.0); r.Add(new Check { Area = "Memory", Value = gb + " GB", Level = gb <= 16 ? "tip" : "ok", Detail = gb <= 16 ? "If games stutter after long sessions, the free ISLC tool can help. See Undo & tools." : "Plenty. Standby-memory cleaners such as ISLC won't make a difference here." }); } catch { } try { List av = new List(); using (ManagementObjectSearcher s = new ManagementObjectSearcher(new ManagementScope(@"\\.\root\SecurityCenter2"), new ObjectQuery("SELECT displayName FROM AntiVirusProduct"))) foreach (ManagementObject m in s.Get()) av.Add(Convert.ToString(m["displayName"])); r.Add(new Check { Area = "Security", Value = av.Count > 0 ? av[0] : "None found", Level = av.Count > 0 ? "ok" : "warn", Detail = "Zero Frame never disables or removes antivirus, Windows Update or Memory Integrity." }); } catch { } try { int startup = 0; using (ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT Name FROM Win32_StartupCommand")) startup = s.Get().Count; r.Add(new Check { Area = "Startup", Value = startup + " apps", Level = startup > 12 ? "warn" : "info", Detail = Process.GetProcesses().Length + " processes running. Review startup apps in Task Manager > Startup apps." }); } catch { } if (IsLaptop) r.Add(new Check { Area = "Laptop", Value = "Detected", Level = "info", Detail = "Play plugged in. Power tweaks only change plugged-in behavior." }); return r; } static long[] PingMany(IPAddress a) { List l = new List(); using (Ping p = new Ping()) for (int i = 0; i < 6; i++) try { PingReply r = p.Send(a, 1000); if (r.Status == IPStatus.Success) l.Add(r.RoundtripTime); } catch { } return l.ToArray(); } // ------------------------------------------------------------------ the catalog void Add(string id, string pack, string name, string preset, string impact, string why, Func test, Action apply, bool reboot = false, bool oneTime = false) { Tweaks.Add(new Tweak { Id = id, Pack = pack, Name = name, Preset = preset, Impact = impact, Why = why, Test = test, Apply = apply, Reboot = reboot, OneTime = oneTime }); } void Build() { const string HighPerf = "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"; const string SubUsb = "2a737441-1930-4402-8d77-b2bebba308a3", UsbSuspend = "48e6b7a6-50f5-4782-a5d4-53bb8f07e226"; const string SubPcie = "501a4d13-42af-4429-9fd1-a8218c268e20", Aspm = "ee12f906-d277-404b-b6da-e5fa1a576df5"; const string SubCpu = "54533251-82be-4824-96c1-47b60b740d00", MinCores = "0cc5b647-c1df-4637-891a-dec35c318583"; const string Boost = "be337238-0d82-4146-a960-4f3749d470c7", Epp = "36687f9e-e3a5-4dbf-b1dc-15eb381c6863", MinState = "893dee8e-2bef-41e0-89c6-b55d0929964c"; const string SubWifi = "19cbb8fa-5279-450e-9fac-8a3d5fedd0c1", WifiPower = "12bbebe6-58d6-4636-95bb-3217ef867c1a"; const string SubDisk = "0012ee47-9041-4b5d-9b77-535fba8b1442", DiskIdle = "6738e2c4-e8a5-4a42-b16a-e040e769756e"; const string Mmcss = @"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile"; const string Cdm = @"HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager"; string[] cdmKeys = { "SilentInstalledAppsEnabled", "SystemPaneSuggestionsEnabled", "SoftLandingEnabled", "SubscribedContent-338388Enabled", "SubscribedContent-338389Enabled", "SubscribedContent-353694Enabled", "SubscribedContent-353696Enabled", "SubscribedContent-310093Enabled", "SubscribedContent-338393Enabled" }; string[] eee = { "*EEE", "EEE", "AdvancedEEE", "EEELinkAdvertisement", "EnableGreenEthernet", "GreenEthernet", "PowerSavingMode", "GigaLite", "ULPMode" }; string[][] bgSvc = { new[] { "MapsBroker", "demand" }, new[] { "RetailDemo", "disabled" }, new[] { "Fax", "demand" }, new[] { "TrkWks", "demand" }, new[] { "WMPNetworkSvc", "demand" }, new[] { "InventorySvc", "demand" } }; string[][] tasks = { new[] { @"\Microsoft\Windows\Application Experience\", "Microsoft Compatibility Appraiser" }, new[] { @"\Microsoft\Windows\Application Experience\", "ProgramDataUpdater" }, new[] { @"\Microsoft\Windows\Customer Experience Improvement Program\", "Consolidator" }, new[] { @"\Microsoft\Windows\Customer Experience Improvement Program\", "UsbCeip" }, new[] { @"\Microsoft\Windows\DiskDiagnostic\", "Microsoft-Windows-DiskDiagnosticDataCollector" }, new[] { @"\Microsoft\Windows\Feedback\Siuf\", "DmClient" }, new[] { @"\Microsoft\Windows\Feedback\Siuf\", "DmClientOnScenarioDownload" } }; // CPU & Power Add("power.plan", "CPU & Power", "High Performance power plan", "Safe", "High", "Stops the CPU dropping its clock speed mid-match, which causes frame-time spikes. Off by default on laptops to protect battery life.", () => { string a = ActiveScheme(); return a == HighPerf || a == (RegStr(@"HKLM:\SOFTWARE\Zero Frame", "Scheme") ?? "-").ToLowerInvariant(); }, () => { AddBackup("Key", "plan", "Kind", "plan", "Scheme", ActiveScheme()); string target = HighPerf; if (Run("powercfg", "/list").IndexOf(HighPerf, StringComparison.OrdinalIgnoreCase) < 0) { target = Regex.Match(Run("powercfg", "-duplicatescheme " + HighPerf), GuidRx).Value; Str(@"HKLM:\SOFTWARE\Zero Frame", "Scheme", target); } Run("powercfg", "/setactive " + target); }); Add("power.usb", "CPU & Power", "USB selective suspend off", "Safe", "Medium", "Windows can put USB ports to sleep. Waking your mouse or keyboard port can add a stutter. Plugged-in power only.", () => PowerIs(SubUsb, UsbSuspend, 0), () => SetPower(SubUsb, UsbSuspend, 0)); Add("power.pcie", "CPU & Power", "PCIe link power saving off", "Safe", "Low", "Keeps the graphics card and NVMe drive links at full speed instead of napping between frames.", () => PowerIs(SubPcie, Aspm, 0), () => SetPower(SubPcie, Aspm, 0)); Add("power.cores", "CPU & Power", "Keep all CPU cores awake", "Competitive", "Low", "Stops Windows parking CPU cores, so a game thread never waits for a core to wake. Uses a little more power at idle.", () => PowerIs(SubCpu, MinCores, 100), () => SetPower(SubCpu, MinCores, 100)); Add("cpu.boost", "CPU & Power", "Aggressive CPU boost", "Competitive", "Medium", "Lets the processor jump to its boost clock the moment a game needs it. Runs a little warmer under load.", () => PowerIs(SubCpu, Boost, 2), () => SetPower(SubCpu, Boost, 2)); Add("cpu.epp", "CPU & Power", "Performance-first CPU clocking", "Competitive", "Medium", "Tells Intel Speed Shift and AMD CPPC to favor speed over power when plugged in, so clocks ramp up faster when a fight starts.", () => PowerIs(SubCpu, Epp, 0), () => SetPower(SubCpu, Epp, 0)); Add("cpu.minstate", "CPU & Power", "CPU never idles below full speed", "Competitive", "Low", "Minimum processor state 100% when plugged in, so the CPU never climbs from a low clock when a frame arrives. Uses more power at idle.", () => PowerIs(SubCpu, MinState, 100), () => SetPower(SubCpu, MinState, 100)); Add("cpu.throttle", "CPU & Power", "No power throttling of open apps", "Competitive", "Low", "Stops Windows slowing down apps it thinks are in the background, such as Discord, OBS or voice chat, while you play.", () => RegInt(@"HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerThrottling", "PowerThrottlingOff") == 1, () => Dword(@"HKLM:\SYSTEM\CurrentControlSet\Control\Power\PowerThrottling", "PowerThrottlingOff", 1)); Add("sys.timer", "CPU & Power", "Precise game timers", "Competitive", "Low", "On Windows 11, a game's high-precision timer keeps working when it's minimized or on another monitor. A documented Windows setting, not a boot hack.", () => RegInt(@"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\kernel", "GlobalTimerResolutionRequests") == 1, () => Dword(@"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\kernel", "GlobalTimerResolutionRequests", 1), true); // Input Add("input.mouse", "Input", "True 1:1 mouse (no acceleration)", "Safe", "High", "Turns off Enhance pointer precision and sets the 6/11 pointer speed, so every count your mouse sends moves the cursor exactly one pixel.", () => RegStr(@"HKCU:\Control Panel\Mouse", "MouseSpeed") == "0" && RegStr(@"HKCU:\Control Panel\Mouse", "MouseSensitivity") == "10", () => { const string m = @"HKCU:\Control Panel\Mouse"; Str(m, "MouseSpeed", "0"); Str(m, "MouseThreshold1", "0"); Str(m, "MouseThreshold2", "0"); Str(m, "MouseSensitivity", "10"); ApplyInputLive(); }); Add("input.keyboard", "Input", "Fastest key repeat", "Safe", "Low", "Shortest delay and fastest repeat rate for held keys. Does not change how fast a single press registers.", () => RegStr(@"HKCU:\Control Panel\Keyboard", "KeyboardDelay") == "0" && RegStr(@"HKCU:\Control Panel\Keyboard", "KeyboardSpeed") == "31", () => { Str(@"HKCU:\Control Panel\Keyboard", "KeyboardDelay", "0"); Str(@"HKCU:\Control Panel\Keyboard", "KeyboardSpeed", "31"); ApplyInputLive(); }); Add("input.accesskeys", "Input", "No Sticky Keys pop-ups", "Safe", "Medium", "Pressing Shift five times can open a pop-up that minimizes your game. Only the shortcuts are turned off; the features stay in Settings.", () => RegStr(@"HKCU:\Control Panel\Accessibility\StickyKeys", "Flags") == "506", () => { Str(@"HKCU:\Control Panel\Accessibility\StickyKeys", "Flags", "506"); Str(@"HKCU:\Control Panel\Accessibility\Keyboard Response", "Flags", "122"); Str(@"HKCU:\Control Panel\Accessibility\ToggleKeys", "Flags", "58"); }); Add("input.usbpower", "Input", "Mouse and keyboard never sleep", "Safe", "Medium", "Turns off USB power saving on the exact ports your mouse and keyboard use, so the first movement after a pause is never delayed. Finishes after a restart.", () => { List ids = HidUsb(); return ids.Count > 0 && ids.All(id => RegInt(@"HKLM:\SYSTEM\CurrentControlSet\Enum\" + id + @"\Device Parameters", "EnhancedPowerManagementEnabled") == 0); }, () => { if (HidUsb().Count == 0) Log(" No USB mouse or keyboard found (Bluetooth and PS/2 devices don't use this setting)."); foreach (string id in HidUsb()) { string p = @"HKLM:\SYSTEM\CurrentControlSet\Enum\" + id + @"\Device Parameters"; try { Dword(p, "EnhancedPowerManagementEnabled", 0); Dword(p, "AllowIdleIrpInD3", 0); Log(" " + id); } catch { Log(" Windows protects " + id + ", skipped."); } } }, true); // GPU & Display Add("gfx.refresh", "GPU & Display", "Monitor at its highest refresh rate", "Safe", "High", "Many PCs run a 144 Hz or faster monitor at 60 Hz without anyone noticing. Switches your main display to the highest rate it reports. Windows tests the mode first.", () => Native.CurrentHz() >= Native.BestHz(), () => { int cur = Native.CurrentHz(), best = Native.BestHz(); if (best <= cur) { Log(" Already at the maximum, " + cur + " Hz."); return; } AddBackup("Key", "hz|primary", "Kind", "hz", "Value", cur); int r = Native.SetHz(best); if (r != 0) throw new Exception("Windows rejected " + best + " Hz. Your display stays at " + cur + " Hz."); Log(" " + cur + " Hz -> " + best + " Hz"); }); Add("gfx.gamemode", "GPU & Display", "Game Mode on", "Safe", "Medium", "Gives the game priority and holds back Windows Update installs and notifications while you play.", () => RegInt(@"HKCU:\Software\Microsoft\GameBar", "AutoGameModeEnabled") != 0, () => Dword(@"HKCU:\Software\Microsoft\GameBar", "AutoGameModeEnabled", 1)); Add("gfx.dvr", "GPU & Display", "Background recording off", "Safe", "Medium", "Stops Xbox Game Bar recording gameplay in the background, which costs GPU time. NVIDIA, AMD and OBS recording still work.", () => RegInt(@"HKCU:\System\GameConfigStore", "GameDVR_Enabled") == 0, () => { Dword(@"HKCU:\System\GameConfigStore", "GameDVR_Enabled", 0); Dword(@"HKCU:\Software\Microsoft\Windows\CurrentVersion\GameDVR", "AppCaptureEnabled", 0); }); Add("gfx.windowed", "GPU & Display", "Optimizations for windowed games", "Safe", "High", "Moves borderless DirectX 10/11 games onto the modern flip presentation path, cutting display latency close to exclusive fullscreen.", () => DxHas("SwapEffectUpgradeEnable=1"), () => SetDx("SwapEffectUpgradeEnable", "1")); Add("gfx.vrr", "GPU & Display", "Variable refresh for windowed games", "Safe", "Medium", "Lets G-Sync and FreeSync work in borderless and older games: no tearing, without the lag of V-Sync. No effect on fixed-refresh monitors.", () => DxHas("VRROptimizeEnable=1"), () => SetDx("VRROptimizeEnable", "1")); Add("gfx.hags", "GPU & Display", "Hardware-accelerated GPU scheduling", "Competitive", "Medium", "Lets the graphics card schedule its own work, which can lower latency and is required for frame generation. Needs a restart.", () => RegInt(@"HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers", "HwSchMode") == 2, () => Dword(@"HKLM:\SYSTEM\CurrentControlSet\Control\GraphicsDrivers", "HwSchMode", 2), true); Add("gfx.mmcss", "GPU & Display", "Game thread priority", "Competitive", "Low", "Raises the Windows multimedia scheduler priority for games, so background tasks get less CPU time while a game is in focus.", () => RegInt(Mmcss + @"\Tasks\Games", "GPU Priority") == 8 && RegInt(Mmcss, "SystemResponsiveness") == 10, () => { Dword(Mmcss, "SystemResponsiveness", 10); Dword(Mmcss + @"\Tasks\Games", "GPU Priority", 8); Dword(Mmcss + @"\Tasks\Games", "Priority", 6); Str(Mmcss + @"\Tasks\Games", "Scheduling Category", "High"); Str(Mmcss + @"\Tasks\Games", "SFIO Priority", "High"); }); Add("gfx.transparency", "GPU & Display", "Transparency effects off", "Competitive", "Low", "Removes the blur behind the taskbar and Start menu. Frees a little GPU time on lower-end graphics cards.", () => RegInt(@"HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "EnableTransparency") == 0, () => Dword(@"HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "EnableTransparency", 0)); Add("gfx.gpupref", "GPU & Display", "Fast GPU by default (laptops)", "Competitive", "Medium", "On laptops with two graphics chips, games sometimes launch on the slow one. Makes the high-performance GPU the default. Uses more battery.", () => DxHas("GpuPreference=2"), () => SetDx("GpuPreference", "2")); // Network Add("net.autotune", "Network", "Repair TCP auto-tuning", "Safe", "Medium", "Many tweak tools turn this off. It doesn't lower ping, but it caps download speed. This puts it back to the Windows default.", () => { int? v = Int(Cim(@"root\StandardCimv2", "SELECT AutoTuningLevelLocal FROM MSFT_NetTCPSetting WHERE SettingName = 'Internet'", "AutoTuningLevelLocal")); return v == null || v == 3; }, () => { int? v = Int(Cim(@"root\StandardCimv2", "SELECT AutoTuningLevelLocal FROM MSFT_NetTCPSetting WHERE SettingName = 'Internet'", "AutoTuningLevelLocal")); AddBackup("Key", "tcp|autotune", "Kind", "tcp", "Value", v != null && v >= 0 && v < 5 ? TuneNames[v.Value] : "Normal"); Run("netsh", "int tcp set global autotuninglevel=normal"); }); Add("net.rss", "Network", "Receive Side Scaling on", "Safe", "Medium", "Spreads network traffic across CPU cores. With it off, one busy core handles every packet, which adds jitter while gaming.", () => { int? g = Int(Cim(@"root\StandardCimv2", "SELECT ReceiveSideScaling FROM MSFT_NetOffloadGlobalSetting", "ReceiveSideScaling")); return (g == null || g == 1) && NicIs(new[] { "*RSS" }, "1"); }, () => { int? g = Int(Cim(@"root\StandardCimv2", "SELECT ReceiveSideScaling FROM MSFT_NetOffloadGlobalSetting", "ReceiveSideScaling")); if (g == 0) { AddBackup("Key", "rssg", "Kind", "rssg", "Value", "Disabled"); Run("netsh", "int tcp set global rss=enabled"); Log(" Windows RSS -> Enabled"); } SetNic(new[] { "*RSS" }, "1"); }); Add("net.eee", "Network", "Ethernet power saving off", "Safe", "Medium", "Energy-Efficient Ethernet and Green Ethernet let the network card doze between packets, adding small, random delays.", () => NicIs(eee, "0"), () => SetNic(eee, "0")); Add("net.p2p", "Network", "No update sharing with strangers", "Safe", "Medium", "Windows can upload updates to other PCs over the internet, using your upload bandwidth mid-match. Updates still download normally.", () => { int? v = RegInt(@"HKLM:\SOFTWARE\Policies\Microsoft\Windows\DeliveryOptimization", "DODownloadMode"); return v == 0 || v == 99 || v == 100; }, () => Dword(@"HKLM:\SOFTWARE\Policies\Microsoft\Windows\DeliveryOptimization", "DODownloadMode", 0)); Add("net.wifi", "Network", "Wi-Fi at full power", "Safe", "Medium", "Sets the Wi-Fi adapter to Maximum Performance when plugged in, so the radio doesn't doze between packets and spike your ping.", () => PowerIs(SubWifi, WifiPower, 0), () => SetPower(SubWifi, WifiPower, 0)); Add("net.intmod", "Network", "Interrupt moderation off", "Competitive", "Low", "The network card stops batching packets before telling the CPU, so each packet arrives a fraction of a millisecond sooner. Costs a little CPU.", () => NicIs(new[] { "*InterruptModeration" }, "0"), () => SetNic(new[] { "*InterruptModeration" }, "0")); Add("net.nagle", "Network", "Nagle off for TCP games", "Competitive", "Low", "Sends small TCP packets immediately instead of bundling them. Helps TCP games such as some MMOs; most shooters use UDP and are unaffected.", () => TcpInterfaces().All(p => RegInt(p, "TcpAckFrequency") == 1), () => { foreach (string p in TcpInterfaces()) { Dword(p, "TcpAckFrequency", 1); Dword(p, "TCPNoDelay", 1); } }); // Windows UI Add("ui.menus", "Windows UI", "Instant menus", "Safe", "Low", "Windows waits 400 ms before opening sub-menus. This cuts it to 100 ms, so the desktop feels as quick as your games.", () => { int? v = Int(RegStr(@"HKCU:\Control Panel\Desktop", "MenuShowDelay")); return v != null && v <= 100; }, () => Str(@"HKCU:\Control Panel\Desktop", "MenuShowDelay", "100")); Add("ui.startup", "Windows UI", "No startup app delay", "Safe", "Low", "Windows holds back startup apps for several seconds after you sign in. This lets them start right away.", () => RegInt(@"HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Serialize", "StartupDelayInMSec") == 0, () => Dword(@"HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Serialize", "StartupDelayInMSec", 0)); Add("ui.animations", "Windows UI", "Snappier window animations", "Competitive", "Low", "Turns off the minimize, maximize and taskbar animations, so alt-tabbing is instant. Takes effect after you sign out.", () => RegStr(@"HKCU:\Control Panel\Desktop\WindowMetrics", "MinAnimate") == "0", () => { Str(@"HKCU:\Control Panel\Desktop\WindowMetrics", "MinAnimate", "0"); Dword(@"HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarAnimations", 0); }); // Background Add("bg.telemetry", "Background", "Telemetry service off", "Safe", "Low", "Stops the Connected User Experiences and Telemetry service from collecting and uploading data in the background during play.", () => { int? s = RegInt(SvcKey("DiagTrack"), "Start"); return s == null || s == 4; }, () => { SetService("DiagTrack", "disabled"); SetService("dmwappushservice", "disabled"); }); Add("bg.tasks", "Background", "Telemetry scheduled tasks off", "Safe", "Medium", "Disables the Compatibility Appraiser and customer-experience tasks that wake on a schedule and can spike disk and CPU for minutes, sometimes mid-game.", () => tasks.All(t => TaskEnabled(t[0] + t[1]) != true), () => { foreach (string[] t in tasks) SetTask(t[0], t[1]); }); Add("bg.services", "Background", "Unused services start on demand", "Safe", "Low", "Maps, Fax, retail demo, link tracking and media sharing services stop starting with Windows. Windows still starts them the moment something needs them.", () => bgSvc.All(s => RegInt(SvcKey(s[0]), "Start") != 2), () => { foreach (string[] s in bgSvc) SetService(s[0], s[1]); }); Add("bg.suggestions", "Background", "No silent app installs or ads", "Safe", "Low", "Stops Windows quietly downloading suggested apps and tips, which use bandwidth and disk in the background.", () => RegInt(Cdm, "SilentInstalledAppsEnabled") == 0, () => { foreach (string k in cdmKeys) Dword(Cdm, k, 0); }); Add("bg.widgets", "Background", "Widgets board off", "Safe", "Low", "The Widgets panel keeps a web process running to refresh news and weather. This turns the board off.", () => RegInt(@"HKLM:\SOFTWARE\Policies\Microsoft\Dsh", "AllowNewsAndInterests") == 0, () => { try { Dword(@"HKLM:\SOFTWARE\Policies\Microsoft\Dsh", "AllowNewsAndInterests", 0); } catch { throw new Exception("Windows protects this setting on your build. Turn Widgets off in Settings > Personalization > Taskbar instead."); } }); Add("bg.recall", "Background", "Recall snapshots off", "Safe", "Low", "On Copilot+ PCs, Recall saves and analyzes screenshots every few seconds. This turns snapshot saving off. No effect on other PCs.", () => RegInt(@"HKCU:\Software\Policies\Microsoft\Windows\WindowsAI", "DisableAIDataAnalysis") == 1, () => Dword(@"HKCU:\Software\Policies\Microsoft\Windows\WindowsAI", "DisableAIDataAnalysis", 1)); Add("bg.websearch", "Background", "Start menu web search off", "Competitive", "Low", "Start menu searches stay on your PC instead of also querying Bing. Faster search, less background network use.", () => RegInt(@"HKCU:\Software\Policies\Microsoft\Windows\Explorer", "DisableSearchBoxSuggestions") == 1, () => Dword(@"HKCU:\Software\Policies\Microsoft\Windows\Explorer", "DisableSearchBoxSuggestions", 1)); // Storage Add("st.diskidle", "Storage", "Hard drives never spin down", "Safe", "Medium", "A sleeping hard drive takes several seconds to spin back up, freezing a game that loads from it. Plugged-in power only; SSDs are unaffected.", () => PowerIs(SubDisk, DiskIdle, 0), () => SetPower(SubDisk, DiskIdle, 0)); Add("st.lastaccess", "Storage", "No last-access timestamps", "Safe", "Low", "Stops Windows writing a \"last opened\" time every time a file is read, saving thousands of tiny writes while a game streams assets.", () => { int? v = LastAccess(); return v == null || v == 1 || v == 3; }, () => { AddBackup("Key", "fsutil|lastaccess", "Kind", "fsutil", "Value", LastAccess()); Run("fsutil", "behavior set disablelastaccess 1"); }); Add("sys.trim", "Storage", "SSD TRIM pass", "Safe", "Low", "Tells your SSDs which blocks are free so writes stay fast. The same job Windows runs weekly. Nothing to undo.", null, () => { foreach (DriveInfo d in DriveInfo.GetDrives()) if (d.DriveType == DriveType.Fixed && d.IsReady) { int c; Run("defrag.exe", d.Name.TrimEnd('\\') + " /L", out c); if (c == 0) Log(" TRIM " + d.Name); } }, false, true); Add("sys.temp", "Storage", "Clear old temp files", "Safe", "Low", "Deletes temporary files older than 2 days. Files in use are skipped. Nothing to undo; these files are disposable by design.", null, () => { long n = 0, bytes = 0; DateTime cut = DateTime.Now.AddDays(-2); foreach (string dir in new[] { Path.GetTempPath(), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Temp") }) CleanDir(dir, cut, ref n, ref bytes); Log(" Cleared " + n + " files (" + (bytes / 1048576) + " MB)"); }, false, true); Add("st.docache", "Storage", "Clear update delivery cache", "Safe", "Low", "Deletes cached copies of already-installed update files. Windows downloads them again only if it ever needs them.", null, () => { string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"ServiceProfiles\NetworkService\AppData\Local\Microsoft\Windows\DeliveryOptimization\Cache"); long n = 0, bytes = 0; try { using (ServiceController s = new ServiceController("DoSvc")) { if (s.Status == ServiceControllerStatus.Running) { s.Stop(); s.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(15)); } } } catch { } CleanDir(dir, DateTime.MaxValue, ref n, ref bytes); try { using (ServiceController s = new ServiceController("DoSvc")) s.Start(); } catch { } Log(" Cleared " + (bytes / 1048576) + " MB"); }, false, true); // Maintenance Add("mt.cleanup", "Maintenance", "Clean up old Windows updates", "Tool", "Low", "Removes superseded Windows update files with Microsoft's own DISM tool, often freeing several GB. Installed updates stay. Takes 5 to 15 minutes.", null, () => { int c; Run("Dism.exe", "/Online /Cleanup-Image /StartComponentCleanup /NoRestart", out c); Log(" DISM finished (exit " + c + ")."); }, false, true); Add("mt.repair", "Maintenance", "Repair Windows system files", "Tool", "Medium", "Runs Microsoft's DISM RestoreHealth and System File Checker to fix corrupted system files, a common cause of crashes and stutter. Needs internet; 10 to 30 minutes.", null, () => { int c; Run("Dism.exe", "/Online /Cleanup-Image /RestoreHealth /NoRestart", out c); Log(" DISM RestoreHealth finished (exit " + c + ")."); Run("sfc.exe", "/scannow", out c); Log(" System File Checker finished (exit " + c + "). Details: C:\\Windows\\Logs\\CBS\\CBS.log"); }, false, true); } static List TcpInterfaces() { List l = new List(); const string root = @"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"; try { using (RegistryKey b = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) using (RegistryKey k = b.OpenSubKey(root)) foreach (string n in k.GetSubKeyNames()) using (RegistryKey i = k.OpenSubKey(n)) { List ips = new List(); foreach (string v in new[] { "DhcpIPAddress", "IPAddress" }) { object o = i.GetValue(v); if (o is string) ips.Add((string)o); else if (o is string[]) ips.AddRange((string[])o); } if (ips.Any(x => x.Length > 0 && x != "0.0.0.0")) l.Add(@"HKLM:\" + root + @"\" + n); } } catch { } return l; } static void CleanDir(string dir, DateTime cut, ref long n, ref long bytes) { if (!Directory.Exists(dir)) return; Stack st = new Stack(); st.Push(dir); while (st.Count > 0) { string d = st.Pop(); try { foreach (string s in Directory.GetDirectories(d)) st.Push(s); } catch { } string[] files; try { files = Directory.GetFiles(d); } catch { continue; } foreach (string f in files) { try { FileInfo fi = new FileInfo(f); if (fi.LastWriteTime >= cut) continue; long len = fi.Length; fi.Attributes = FileAttributes.Normal; fi.Delete(); n++; bytes += len; } catch { } } } } } }