You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何开发Windows屏幕亮度调节程序?PyWin32实现遇阻求助

问题分析与解决方案

你的代码存在两个核心问题,导致屏幕亮度毫无变化:

1. 错误使用SC_MONITORPOWER指令

win32con.SC_MONITORPOWER是用来控制显示器电源状态(唤醒/待机/关闭)的指令,和调节亮度完全无关。你传入的参数10是无效值,系统不会做出任何响应。该指令的有效参数为:

  • 1:唤醒显示器
  • 2:将显示器切换至待机状态
  • 3:关闭显示器

2. 逻辑完全无效

你的adjust函数中,if和else分支执行的是完全相同的代码,根本做不到针对不同窗口调节亮度的效果。


正确的亮度调节实现方法

Windows下调节屏幕亮度需要调用专门的系统接口,以下提供两种可行方案:

方案一:使用WMI(简单易实现)

WMI可以直接调用系统接口完成亮度调节,无需复杂的Win32消息操作:

import win32gui
import wmi
import time

def get_active_window_title():
    window_handle = win32gui.GetForegroundWindow()
    return win32gui.GetWindowText(window_handle)

def set_brightness(level):
    # 亮度范围为0-100
    c = wmi.WMI(namespace='wmi')
    brightness_methods = c.WmiMonitorBrightnessMethods()[0]
    brightness_methods.WmiSetBrightness(level, 0)

def adjust():
    active_app = get_active_window_title()
    if "Action center" in active_app:
        set_brightness(80)  # 打开操作中心时设为80%亮度
    else:
        set_brightness(50)  # 其他窗口设为50%亮度

while True:
    adjust()
    time.sleep(1)  # 每秒检测一次,避免占用过高CPU

方案二:调用Win32 API(更底层)

通过ctypes调用系统动态链接库的函数,直接操作显示器设备:

import win32gui
import ctypes
import time

user32 = ctypes.WinDLL('user32.dll')
gdi32 = ctypes.WinDLL('gdi32.dll')

def get_active_window_title():
    window_handle = win32gui.GetForegroundWindow()
    return win32gui.GetWindowText(window_handle)

def set_brightness(level):
    # 亮度范围0-100,转换为0-255的设备值
    gamma_ramp = (ctypes.c_short * 3 * 256)(*(int(level * i / 100) for i in range(256)) * 3)
    hdc = user32.GetDC(0)
    gdi32.SetDeviceGammaRamp(hdc, gamma_ramp)
    user32.ReleaseDC(0, hdc)

def adjust():
    active_app = get_active_window_title()
    if "Action center" in active_app:
        set_brightness(80)
    else:
        set_brightness(50)

while True:
    adjust()
    time.sleep(1)

额外注意事项

  • 程序需要管理员权限运行,否则可能无法修改系统亮度设置
  • 必须保留time.sleep(1),否则无限循环会导致CPU占用率飙升
  • 部分笔记本电脑需要在电源设置中允许第三方程序调节亮度

内容的提问来源于stack exchange,提问作者AlEzAh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 21:17:13