using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace PowerToggle
{
class Program
{
[DllImport("powrprof.dll", SetLastError = true)]
static extern uint PowerSetActiveScheme(IntPtr UserRootPowerKey, ref Guid SchemeGuid);
[DllImport("powrprof.dll", SetLastError = true)]
static extern uint PowerGetActiveScheme(IntPtr UserRootPowerKey, out IntPtr ActivePolicyGuid);
[DllImport("powrprof.dll", SetLastError = true)]
static extern uint PowerSetActiveOverlayScheme(ref Guid OverlayGuid);
[DllImport("powrprof.dll", SetLastError = true)]
static extern uint PowerGetActualOverlayScheme(out Guid ActualOverlayGuid);
[StructLayout(LayoutKind.Sequential)]
struct SYSTEM_POWER_STATUS
{
public byte ACLineStatus;
public byte BatteryFlag;
public byte BatteryLifePercent;
public byte SystemStatusFlag;
public uint BatteryLifeTime;
public uint BatteryFullLifeTime;
}
[DllImport("kernel32.dll")]
static extern bool GetSystemPowerStatus(out SYSTEM_POWER_STATUS lpSystemPowerStatus);
static readonly Guid BuiltinHighPerf = new Guid("8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c");
static readonly Guid BuiltinPowerSaver = new Guid("a1841308-3541-4fab-bc81-f71556f20b4a");
static readonly Guid OverlayMaxPerf = new Guid("ded574b5-45a0-4f42-8737-46345c09c238");
static readonly Guid OverlayBetterBattery = new Guid("961cc777-2547-4f9d-8174-7d86181b8a7a");
const int BalloonTimeout = 3000;
static Guid schemeHighPerf = Guid.Empty;
static Guid schemePowerSaver = Guid.Empty;
static byte brightnessHigh = 100;
static byte brightnessSaver = 40;
static bool isLenovo = false;
static bool overlaySupported = true;
static NotifyIcon notifyIcon;
static ToolStripMenuItem statusItem;
static bool isHighPerf = true;
static System.Windows.Forms.Timer balloonTimer;
static Icon iconHighPerf;
static Icon iconPowerSaver;
[STAThread]
static void Main()
{
bool createdNew;
using (var mtx = new System.Threading.Mutex(true, "Global\\PowerToggleApp", out createdNew))
{
if (!createdNew) return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
isLenovo = DetectLenovo();
if (!LoadConfig())
{
if (!InitializeSchemes())
{
MessageBox.Show(
"初始化电源方案失败。\n" +
"请以管理员身份运行此程序。",
"PowerToggle - 初始化错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
try
{
Guid test;
PowerGetActualOverlayScheme(out test);
}
catch (EntryPointNotFoundException)
{
overlaySupported = false;
}
balloonTimer = new System.Windows.Forms.Timer();
balloonTimer.Tick += (s, e) =>
{
balloonTimer.Stop();
notifyIcon.Visible = false;
notifyIcon.Visible = true;
};
SetupTray();
Microsoft.Win32.SystemEvents.PowerModeChanged += OnPowerModeChanged;
if (isLenovo) KillLenovoITS();
var timer = new System.Windows.Forms.Timer();
timer.Interval = 3000;
timer.Tick += (s, e) =>
{
if (isLenovo) KillLenovoITS();
PollStatus();
};
timer.Start();
SyncCurrentState();
RefreshStatus();
Application.Run();
}
}
static void ShowBalloon(string title, string text, ToolTipIcon icon, int timeoutMs)
{
notifyIcon.ShowBalloonTip(timeoutMs, title, text, icon);
balloonTimer.Interval = timeoutMs;
balloonTimer.Stop();
balloonTimer.Start();
}
static string ConfigPath
{
get { return Path.Combine(AppDir, "PowerToggle.ini"); }
}
static string AppDir
{
get { return Path.GetDirectoryName(Application.ExecutablePath); }
}
static bool LoadConfig()
{
try
{
if (!File.Exists(ConfigPath)) return false;
foreach (string line in File.ReadAllLines(ConfigPath))
{
string trimmed = line.Trim();
if (trimmed.StartsWith("#") || trimmed.StartsWith("[") || trimmed == "") continue;
int eq = trimmed.IndexOf('=');
if (eq < 0) continue;
string key = trimmed.Substring(0, eq).Trim();
string val = trimmed.Substring(eq + 1).Trim();
switch (key)
{
case "HighPerfScheme":
Guid.TryParse(val, out schemeHighPerf);
break;
case "PowerSaverScheme":
Guid.TryParse(val, out schemePowerSaver);
break;
case "HighBrightness":
byte.TryParse(val, out brightnessHigh);
break;
case "SaverBrightness":
byte.TryParse(val, out brightnessSaver);
break;
}
}
if (schemeHighPerf == Guid.Empty || !SchemeExists(schemeHighPerf)) return false;
if (schemePowerSaver == Guid.Empty || !SchemeExists(schemePowerSaver)) return false;
return true;
}
catch { return false; }
}
static void SaveConfig()
{
try
{
string content = "# PowerToggle 配置文件\r\n" +
"# 自动生成 - 可手动修改亮度值\r\n\r\n" +
"[Schemes]\r\n" +
"HighPerfScheme=" + schemeHighPerf.ToString() + "\r\n" +
"PowerSaverScheme=" + schemePowerSaver.ToString() + "\r\n\r\n" +
"[Settings]\r\n" +
"# 屏幕亮度百分比 (0-100)\r\n" +
"HighBrightness=" + brightnessHigh + "\r\n" +
"SaverBrightness=" + brightnessSaver + "\r\n";
File.WriteAllText(ConfigPath, content);
}
catch { }
}
static bool InitializeSchemes()
{
try
{
schemeHighPerf = DuplicateScheme(BuiltinHighPerf);
if (schemeHighPerf == Guid.Empty) return false;
ConfigureScheme(schemeHighPerf,
brightnessAc: brightnessHigh,
brightnessDc: (byte)Math.Min((int)brightnessHigh, 80),
cpuMinAc: 100, cpuMinDc: 50,
sleepAc: 0, sleepDc: 1800,
displayOffAc: 0, displayOffDc: 300);
schemePowerSaver = DuplicateScheme(BuiltinPowerSaver);
if (schemePowerSaver == Guid.Empty) return false;
ConfigureScheme(schemePowerSaver,
brightnessAc: brightnessSaver,
brightnessDc: brightnessSaver,
cpuMinAc: 5, cpuMinDc: 5,
sleepAc: 1800, sleepDc: 900,
displayOffAc: 300, displayOffDc: 120);
SetSchemeSetting(schemeHighPerf, "SUB_ENERGYSAVER", "ESBATTTHRESHOLD", 0, 0);
SetSchemeSetting(schemePowerSaver, "SUB_ENERGYSAVER", "ESBATTTHRESHOLD", 100, 100);
SaveConfig();
Guid g = schemeHighPerf;
PowerSetActiveScheme(IntPtr.Zero, ref g);
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("初始化错误: " + ex.Message);
return false;
}
}
static Guid DuplicateScheme(Guid sourceGuid)
{
try
{
var psi = new ProcessStartInfo("powercfg", "/duplicatescheme " + sourceGuid.ToString("B"))
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
var p = Process.Start(psi);
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
p.WaitForExit(5000);
string combined = output + error;
int idx = combined.IndexOf("GUID: ");
if (idx >= 0)
{
int start = idx + 6;
int end = combined.IndexOf(" ", start);
if (end < 0) end = combined.IndexOf("\n", start);
if (end < 0) end = combined.IndexOf("\r", start);
if (end > start)
{
string guidStr = combined.Substring(start, end - start).Trim();
Guid result;
if (Guid.TryParse(guidStr, out result)) return result;
}
}
return Guid.Empty;
}
catch { return Guid.Empty; }
}
static void ConfigureScheme(Guid scheme,
byte brightnessAc, byte brightnessDc,
int cpuMinAc, int cpuMinDc,
int sleepAc, int sleepDc,
int displayOffAc, int displayOffDc)
{
string g = scheme.ToString();
SetSchemeSettingRaw(g, "SUB_VIDEO", "VIDEONORMALLEVEL", brightnessAc, brightnessDc);
SetSchemeSettingRaw(g, "SUB_VIDEO", "f1fbfde2-a960-4165-9f88-50667911ce96", brightnessAc, brightnessDc);
SetSchemeSettingRaw(g, "SUB_PROCESSOR", "PROCTHROTTLEMIN", cpuMinAc, cpuMinDc);
SetSchemeSettingRaw(g, "SUB_SLEEP", "STANDBYIDLE", sleepAc, sleepDc);
SetSchemeSettingRaw(g, "SUB_VIDEO", "VIDEOIDLE", displayOffAc, displayOffDc);
SetSchemeSettingRaw(g, "SUB_VIDEO", "ADAPTBRIGHT", 0, 0);
}
static void SetSchemeSetting(Guid scheme, string subgroup, string setting, int acValue, int dcValue)
{
SetSchemeSettingRaw(scheme.ToString(), subgroup, setting, acValue, dcValue);
}
static void SetSchemeSettingRaw(string schemeGuid, string subgroup, string setting, int acValue, int dcValue)
{
try
{
RunPowerCfg("/setacvalueindex " + schemeGuid + " " + subgroup + " " + setting + " " + acValue);
RunPowerCfg("/setdcvalueindex " + schemeGuid + " " + subgroup + " " + setting + " " + dcValue);
}
catch { }
}
static void RunPowerCfg(string args)
{
try
{
var psi = new ProcessStartInfo("powercfg", args)
{
UseShellExecute = false,
CreateNoWindow = true
};
var p = Process.Start(psi);
p.WaitForExit(5000);
}
catch { }
}
static bool SchemeExists(Guid guid)
{
try
{
var psi = new ProcessStartInfo("powercfg", "/query " + guid.ToString())
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
var p = Process.Start(psi);
string output = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd();
p.WaitForExit(3000);
return !output.Contains("not exist") && !output.Contains("not found") && output.Contains("GUID");
}
catch { return false; }
}
static bool DetectLenovo()
{
try
{
using (var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Manufacturer FROM Win32_ComputerSystem"))
{
foreach (ManagementObject obj in searcher.Get())
{
string manufacturer = Convert.ToString(obj["Manufacturer"]).ToUpperInvariant();
if (manufacturer.Contains("LENOVO")) return true;
}
}
}
catch { }
return false;
}
static void KillLenovoITS()
{
try
{
foreach (var p in Process.GetProcessesByName("ITSPowerMode"))
{
try { p.Kill(); p.WaitForExit(1000); } catch { }
}
}
catch { }
}
static void SetBrightness(byte brightness)
{
try
{
using (var searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM WmiMonitorBrightnessMethods"))
{
foreach (ManagementObject obj in searcher.Get())
{
obj.InvokeMethod("WmiSetBrightness", new object[] { (uint)1, brightness });
}
}
}
catch { }
}
static void SwitchToHighPerf()
{
try
{
Guid g = schemeHighPerf;
PowerSetActiveScheme(IntPtr.Zero, ref g);
System.Threading.Thread.Sleep(200);
if (overlaySupported)
{
try { Guid ov = OverlayMaxPerf; PowerSetActiveOverlayScheme(ref ov); } catch { }
System.Threading.Thread.Sleep(200);
}
SetBrightness(brightnessHigh);
isHighPerf = true;
RefreshStatus();
}
catch (Exception ex)
{
ShowBalloon("错误", ex.Message, ToolTipIcon.Error, BalloonTimeout);
}
}
static void SwitchToPowerSaver()
{
try
{
Guid g = schemePowerSaver;
PowerSetActiveScheme(IntPtr.Zero, ref g);
System.Threading.Thread.Sleep(200);
if (overlaySupported)
{
try { Guid ov = OverlayBetterBattery; PowerSetActiveOverlayScheme(ref ov); } catch { }
System.Threading.Thread.Sleep(200);
}
SetBrightness(brightnessSaver);
isHighPerf = false;
RefreshStatus();
}
catch (Exception ex)
{
ShowBalloon("错误", ex.Message, ToolTipIcon.Error, BalloonTimeout);
}
}
static void ToggleMode()
{
if (isLenovo) KillLenovoITS();
if (isHighPerf)
SwitchToPowerSaver();
else
SwitchToHighPerf();
System.Threading.Thread.Sleep(300);
SyncCurrentState();
RefreshStatus();
ShowBalloon(
isHighPerf ? "高性能模式" : "节能模式",
GetStatusString(), ToolTipIcon.Info, BalloonTimeout);
}
static void SyncCurrentState()
{
try
{
Guid current = GetActiveScheme();
isHighPerf = current == schemeHighPerf;
}
catch { }
}
static void PollStatus()
{
try
{
Guid current = GetActiveScheme();
bool newIsHigh = current == schemeHighPerf;
if (newIsHigh != isHighPerf)
{
isHighPerf = newIsHigh;
RefreshStatus();
}
}
catch { }
}
static string GetStatusString()
{
try
{
SYSTEM_POWER_STATUS ps;
GetSystemPowerStatus(out ps);
string ac = ps.ACLineStatus == 1 ? "插电" : "电池";
string es = ps.SystemStatusFlag == 1 ? "开" : "关";
int brightness = -1;
try
{
using (var searcher = new ManagementObjectSearcher("root\\WMI", "SELECT CurrentBrightness FROM WmiMonitorBrightness"))
{
foreach (ManagementObject obj in searcher.Get())
brightness = Convert.ToInt32(obj["CurrentBrightness"]);
}
}
catch { }
string overlayStr = "";
if (overlaySupported)
{
try
{
Guid ov;
PowerGetActualOverlayScheme(out ov);
if (ov == OverlayMaxPerf) overlayStr = "最佳性能";
else if (ov == OverlayBetterBattery) overlayStr = "最佳能效";
else overlayStr = "平衡";
}
catch { }
}
return string.Format("亮度: {0}%\n电源模式: {1}\n节能模式: {2}\n供电: {3} 电量: {4}%",
brightness >= 0 ? brightness.ToString() : "?",
overlayStr, es, ac, ps.BatteryLifePercent);
}
catch { return ""; }
}
static Guid GetActiveScheme()
{
IntPtr ptr;
uint ret = PowerGetActiveScheme(IntPtr.Zero, out ptr);
if (ret != 0) return Guid.Empty;
try
{
byte[] bytes = new byte[16];
Marshal.Copy(ptr, bytes, 0, 16);
return new Guid(bytes);
}
finally { Marshal.FreeHGlobal(ptr); }
}
static void OnPowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
{
if (e.Mode == Microsoft.Win32.PowerModes.Resume)
{
System.Threading.Thread.Sleep(2000);
if (isLenovo) KillLenovoITS();
SwitchToHighPerf();
ShowBalloon("系统已唤醒", "已自动切换至高性能模式", ToolTipIcon.Info, BalloonTimeout);
}
}
static void SetupTray()
{
if (notifyIcon != null)
{
notifyIcon.Visible = false;
notifyIcon.Dispose();
notifyIcon = null;
}
notifyIcon = new NotifyIcon();
notifyIcon.Text = "PowerToggle";
notifyIcon.Visible = true;
var menu = new ContextMenuStrip();
statusItem = new ToolStripMenuItem("加载中...");
statusItem.Enabled = false;
menu.Items.Add(statusItem);
menu.Items.Add(new ToolStripSeparator());
var switchItem = new ToolStripMenuItem("切换模式");
switchItem.Click += (s, e) => ToggleMode();
menu.Items.Add(switchItem);
menu.Items.Add(new ToolStripSeparator());
var settingsItem = new ToolStripMenuItem("亮度设置");
var highLabel = new ToolStripMenuItem("高性能亮度: " + brightnessHigh + "%");
highLabel.Click += (s, e) => EditBrightness(true);
var saverLabel = new ToolStripMenuItem("节能亮度: " + brightnessSaver + "%");
saverLabel.Click += (s, e) => EditBrightness(false);
settingsItem.DropDownItems.Add(highLabel);
settingsItem.DropDownItems.Add(saverLabel);
menu.Items.Add(settingsItem);
if (isLenovo)
{
var lenovoItem = new ToolStripMenuItem("联想 ITS 防护: 已启用");
lenovoItem.Enabled = false;
menu.Items.Add(lenovoItem);
}
menu.Items.Add(new ToolStripSeparator());
var aboutItem = new ToolStripMenuItem("关于 PowerToggle");
aboutItem.Click += (s, e) => ShowAbout();
menu.Items.Add(aboutItem);
var exitItem = new ToolStripMenuItem("退出");
exitItem.Click += (s, e) => ExitApp();
menu.Items.Add(exitItem);
notifyIcon.ContextMenuStrip = menu;
notifyIcon.MouseClick += (s, e) =>
{
if (e.Button == MouseButtons.Left) ToggleMode();
};
}
static void EditBrightness(bool isHigh)
{
string title = isHigh ? "高性能亮度设置" : "节能亮度设置";
int current = isHigh ? brightnessHigh : brightnessSaver;
string input = ShowInputDialog(title, "请输入亮度值 (0-100):", current.ToString());
if (string.IsNullOrEmpty(input)) return;
int value;
if (int.TryParse(input.Trim(), out value) && value >= 0 && value <= 100)
{
if (isHigh) brightnessHigh = (byte)value;
else brightnessSaver = (byte)value;
SaveConfig();
if (isHighPerf == isHigh) SetBrightness((byte)value);
notifyIcon.ContextMenuStrip.Dispose();
SetupTray();
SyncCurrentState();
RefreshStatus();
ShowBalloon("已保存", title + " 已设为 " + value + "%", ToolTipIcon.Info, BalloonTimeout);
}
else
{
MessageBox.Show("请输入 0 到 100 之间的数字。", "输入无效",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
static string ShowInputDialog(string title, string prompt, string defaultValue)
{
Form form = new Form();
form.Text = title;
form.StartPosition = FormStartPosition.CenterScreen;
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.MaximizeBox = false;
form.MinimizeBox = false;
form.Width = 300;
form.Height = 150;
Label label = new Label();
label.Text = prompt;
label.Left = 15;
label.Top = 15;
label.Width = 260;
form.Controls.Add(label);
TextBox textBox = new TextBox();
textBox.Text = defaultValue;
textBox.Left = 15;
textBox.Top = 40;
textBox.Width = 260;
form.Controls.Add(textBox);
Button okBtn = new Button();
okBtn.Text = "确定";
okBtn.Left = 150;
okBtn.Top = 75;
okBtn.Width = 55;
okBtn.DialogResult = DialogResult.OK;
form.Controls.Add(okBtn);
Button cancelBtn = new Button();
cancelBtn.Text = "取消";
cancelBtn.Left = 210;
cancelBtn.Top = 75;
cancelBtn.Width = 65;
cancelBtn.DialogResult = DialogResult.Cancel;
form.Controls.Add(cancelBtn);
form.AcceptButton = okBtn;
form.CancelButton = cancelBtn;
return form.ShowDialog() == DialogResult.OK ? textBox.Text : null;
}
static void ShowAbout()
{
string msg = "PowerToggle v1.0\n\n" +
"Windows 10/11 一键电源模式切换工具\n\n" +
"功能:\n" +
" - 高性能 / 节能模式一键切换\n" +
" - 通过 WMI 强制控制屏幕亮度\n" +
" - 同步 Windows 电源模式滑条\n" +
(isLenovo ? " - 联想 ITS 冲突防护\n" : "") +
" - 系统唤醒后自动切回高性能\n" +
" - 可自定义各模式亮度\n\n" +
"https://gitcode.com/LLLAAAAA\n" +
"MIT 开源许可证";
MessageBox.Show(msg, "关于 PowerToggle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
static void RefreshStatus()
{
try
{
string name = isHighPerf ? "高性能" : "节能";
statusItem.Text = "当前: " + name;
notifyIcon.Text = "PowerToggle - " + name;
if (iconHighPerf == null) iconHighPerf = CreateHighPerfIcon();
if (iconPowerSaver == null) iconPowerSaver = CreatePowerSaverIcon();
Icon want = isHighPerf ? iconHighPerf : iconPowerSaver;
if (!ReferenceEquals(notifyIcon.Icon, want)) notifyIcon.Icon = want;
}
catch { }
}
[DllImport("user32.dll", SetLastError = true)]
static extern bool DestroyIcon(IntPtr handle);
static Icon IconFromBitmap(Bitmap bmp)
{
IntPtr h = bmp.GetHicon();
try
{
using (Icon borrowed = Icon.FromHandle(h))
{
return (Icon)borrowed.Clone();
}
}
finally
{
DestroyIcon(h);
}
}
static Icon CreateHighPerfIcon()
{
using (Bitmap bmp = new Bitmap(32, 32))
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.Transparent);
using (var brush = new LinearGradientBrush(
new Rectangle(2, 2, 28, 28), Color.FromArgb(255, 170, 50), Color.FromArgb(230, 120, 20), 45f))
{
g.FillEllipse(brush, 2, 2, 28, 28);
}
PointF[] bolt = new PointF[]
{
new PointF(19, 5), new PointF(11, 18),
new PointF(16, 18), new PointF(12, 27),
new PointF(22, 13), new PointF(17, 13),
new PointF(20, 5)
};
g.FillPolygon(Brushes.White, bolt);
g.DrawPolygon(new Pen(Color.FromArgb(80, 50, 0), 0.5f), bolt);
return IconFromBitmap(bmp);
}
}
static Icon CreatePowerSaverIcon()
{
using (Bitmap bmp = new Bitmap(32, 32))
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.Transparent);
using (var brush = new LinearGradientBrush(
new Rectangle(2, 2, 28, 28), Color.FromArgb(80, 200, 80), Color.FromArgb(40, 160, 40), 45f))
{
g.FillEllipse(brush, 2, 2, 28, 28);
}
g.FillEllipse(Brushes.White, 9, 9, 14, 14);
using (var brush = new SolidBrush(Color.FromArgb(40, 160, 40)))
{
g.FillEllipse(brush, 11, 7, 12, 12);
}
using (var pen = new Pen(Color.White, 2f))
{
g.DrawLine(pen, 16, 20, 16, 27);
}
return IconFromBitmap(bmp);
}
}
static void ExitApp()
{
if (balloonTimer != null) balloonTimer.Stop();
notifyIcon.Visible = false;
notifyIcon.Dispose();
if (iconHighPerf != null) { iconHighPerf.Dispose(); iconHighPerf = null; }
if (iconPowerSaver != null) { iconPowerSaver.Dispose(); iconPowerSaver = null; }
Application.Exit();
}
}
}