C# 使用C调节屏幕亮度#

C# 使用C调节屏幕亮度#,c#,C#,如何在C#中调整屏幕亮度?查看API函数。这里有一篇CodeProject文章描述了如何从C#使用它: 请注意,您的图形卡必须支持这一点,但我认为大多数现代图形卡都支持,但我不知道 编辑:由于CodeProject文章似乎已关闭,另一个从C#调用它的地方是。刚刚打开了SetMonitorBrightness函数 实际上,您可以使用SetDeviceGammaRamp()以C#为单位设置屏幕亮度 创建新的windows窗体应用程序并复制以下代码。只需将轨迹栏和按钮拖动到窗口 using Syste

如何在C#中调整屏幕亮度?

查看API函数。这里有一篇CodeProject文章描述了如何从C#使用它:

请注意,您的图形卡必须支持这一点,但我认为大多数现代图形卡都支持,但我不知道


编辑:由于CodeProject文章似乎已关闭,另一个从C#调用它的地方是。

刚刚打开了
SetMonitorBrightness
函数

实际上,您可以使用
SetDeviceGammaRamp()
以C#为单位设置屏幕亮度

创建新的windows窗体应用程序并复制以下代码。只需将轨迹栏和按钮拖动到窗口

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Runtime.InteropServices; 
namespace brightnesscontrol 
{ 
   public partial class Form1 : Form 
   { 
       [DllImport("gdi32.dll")] 
       private unsafe static extern bool SetDeviceGammaRamp(Int32 hdc, void* ramp); 
       private static bool initialized = false; 
       private static Int32 hdc; 
       private static int a; 
       public Form1() 
       { 
           InitializeComponent(); 
       } 
       private static void InitializeClass() 
       { 
           if (initialized) 
               return; 
           hdc = Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32(); 
           initialized = true; 
       } 
       public static unsafe bool SetBrightness(int brightness) 
       { 
           InitializeClass(); 
           if (brightness > 255) 
               brightness = 255; 
           if (brightness < 0) 
               brightness = 0; 
           short* gArray = stackalloc short[3 * 256]; 
           short* idx = gArray; 
           for (int j = 0; j < 3; j++) 
           { 
               for (int i = 0; i < 256; i++) 
               { 
                   int arrayVal = i * (brightness + 128); 
                   if (arrayVal > 65535) 
                       arrayVal = 65535; 
                   *idx = (short)arrayVal; 
                   idx++; 
               } 
           } 
           bool retVal = SetDeviceGammaRamp(hdc, gArray); 
           return retVal; 
       } 
       private void trackBar1_Scroll(object sender, EventArgs e) 
       { 
       } 
       private void button1_Click(object sender, EventArgs e) 
       { 
           a = trackBar1.Value; 
           SetBrightness(a); 
       } 
   } 
} 
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用System.Runtime.InteropServices;
名称空间亮度控制
{ 
公共部分类Form1:Form
{ 
[DllImport(“gdi32.dll”)]
专用不安全静态外部布尔设置设备Gammaramp(Int32 hdc,void*ramp);
私有静态bool initialized=false;
专用静态Int32 hdc;
私有静态INTA;
公共表格1()
{ 
初始化组件();
} 
私有静态void InitializeClass()
{ 
如果(已初始化)
返回;
hdc=Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32();
初始化=真;
} 
公共静态光亮度(整数亮度)
{ 
初始化类();
如果(亮度>255)
亮度=255;
如果(亮度<0)
亮度=0;
short*gArray=stackalloc short[3*256];
short*idx=gArray;
对于(int j=0;j<3;j++)
{ 
对于(int i=0;i<256;i++)
{ 
int arrayVal=i*(亮度+128);
如果(arrayVal>65535)
arrayVal=65535;
*idx=(短)arrayVal;
idx++;
} 
} 
bool retVal=SetDeviceGammaRamp(hdc,gArray);
返回返回;
} 
私有void trackBar1_滚动(对象发送方,事件参数e)
{ 
} 
私有无效按钮1\u单击(对象发送者,事件参数e)
{ 
a=轨迹栏1.值;
正确性(a);
} 
} 
} 
也许您需要更改轨迹栏的最大值和最小值


您可以按照这里的教程进行操作。更多图片和详细信息:

以下是更改Windows设置亮度的代码(适用于笔记本电脑):

使用系统;
使用制度管理;
公共静态类窗口设置亮度控制器
{
公共静态int Get()
{
使用var mclass=newmanagementclass(“WmiMonitorBrightness”)
{
范围=新的管理范围(@“\\.\root\wmi”)
};
使用var instances=mclass.GetInstances();
foreach(实例中的ManagementObject实例)
{
返回(字节)实例.GetPropertyValue(“CurrentBrightness”);
}
返回0;
}
公共静态无效集(整数亮度)
{
使用var mclass=newmanagementclass(“WmiMonitorBrightnessMethods”)
{
范围=新的管理范围(@“\\.\root\wmi”)
};
使用var instances=mclass.GetInstances();
var args=新对象[]{1,亮度};
foreach(实例中的ManagementObject实例)
{
InvokeMethod(“WmiSetBrightness”,args);
}
}
}
下面是更改亮度和外部显示器的代码(但不适用于笔记本电脑等内置显示器)

此代码是@help代码的修改版本,使用
EnumDisplayMonitors
而不是
MonitorFromWindow
,因此它不会 需要窗口来运行和搜索所有监视器,而不仅仅是一个监视器 窗户现在开着

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Runtime.InteropServices;
公共类PhilicalMonitorRightnessController:IDisposable
{
#德林波特地区
[DllImport(“dxva2.dll”,EntryPoint=“GetNumberOfPhysicalMonitorsFromHMONITOR”)]
[返回:Marshallas(UnmanagedType.Bool)]
私有静态外部布尔从hMonitor获取物理监控器的编号(IntPtr hMonitor,参考uint pdwNumberOfPhysicalMonitors);
[DllImport(“dxva2.dll”,EntryPoint=“GetPhysicalMonitorsFromHMONITOR”)]
[返回:Marshallas(UnmanagedType.Bool)]
私有静态外部布尔从hMonitor获取物理监视器(IntPtr hMonitor、uint DWPhysicalMonitor阵列物理化、[Out]物理监视器[]物理监视器阵列);
[DllImport(“dxva2.dll”,EntryPoint=“GetMonitorBrightness”)]
[返回:Marshallas(UnmanagedType.Bool)]
专用静态外部布尔GetMonitorBrightness(IntPtr句柄、参考单元最小亮度、参考单元当前亮度、参考单元最大亮度);
[DllImport(“dxva2.dll”,EntryPoint=“SetMonitorBrightness”)]
[返回:Marshallas(UnmanagedType.Bool)]
专用静态外部布尔设置监视器亮度(IntPtr句柄,uint-newBrightness);
[DllImport(“dxva2.dll”,EntryPoint=“DestroyPhysicalMonitor”)]
[返回:Marshallas(UnmanagedType.Bool)]
专用静态外部物理监测器(IntPtr hMonitor);
[DllImport(“dxva2.dll”,EntryPoint=“DestroyPhysicalMonitors”)]
[返回:Marshallas(UnmanagedType.Bool)]
公共静态外部网络物理监视器(uint DWPhysicalMonitorarySize,[In]PhysicalMonitor[]PPPhysicalMonitorarray);
[DllImport(“user32.dll”)]
静态外部bool EnumDisplayMonitors(IntPtr hdc、IntPtr lprcClip、EnumMonitorsDelegate lpfneum、IntPtr dwData);
德莱格
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct PHYSICAL_MONITOR
{
    public IntPtr hPhysicalMonitor;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    public string szPhysicalMonitorDescription;
}

public class BrightnessController : IDisposable
{
    [DllImport("user32.dll", EntryPoint = "MonitorFromWindow")]
    public static extern IntPtr MonitorFromWindow([In] IntPtr hwnd, uint dwFlags);

    [DllImport("dxva2.dll", EntryPoint = "DestroyPhysicalMonitors")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool DestroyPhysicalMonitors(uint dwPhysicalMonitorArraySize, ref PHYSICAL_MONITOR[] pPhysicalMonitorArray);

    [DllImport("dxva2.dll", EntryPoint = "GetNumberOfPhysicalMonitorsFromHMONITOR")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetNumberOfPhysicalMonitorsFromHMONITOR(IntPtr hMonitor, ref uint pdwNumberOfPhysicalMonitors);

    [DllImport("dxva2.dll", EntryPoint = "GetPhysicalMonitorsFromHMONITOR")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetPhysicalMonitorsFromHMONITOR(IntPtr hMonitor, uint dwPhysicalMonitorArraySize, [Out] PHYSICAL_MONITOR[] pPhysicalMonitorArray);

    [DllImport("dxva2.dll", EntryPoint = "GetMonitorBrightness")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetMonitorBrightness(IntPtr handle, ref uint minimumBrightness, ref uint currentBrightness, ref uint maxBrightness);

    [DllImport("dxva2.dll", EntryPoint = "SetMonitorBrightness")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetMonitorBrightness(IntPtr handle, uint newBrightness);

    private uint _physicalMonitorsCount = 0;
    private PHYSICAL_MONITOR[] _physicalMonitorArray;

    private IntPtr _firstMonitorHandle;

    private uint _minValue = 0;
    private uint _maxValue = 0;
    private uint _currentValue = 0;

    public BrightnessController(IntPtr windowHandle)
    {
        uint dwFlags = 0u;
        IntPtr ptr = MonitorFromWindow(windowHandle, dwFlags);
        if (!GetNumberOfPhysicalMonitorsFromHMONITOR(ptr, ref _physicalMonitorsCount))
        {
            throw new Exception("Cannot get monitor count!");
        }
        _physicalMonitorArray = new PHYSICAL_MONITOR[_physicalMonitorsCount];

        if (!GetPhysicalMonitorsFromHMONITOR(ptr, _physicalMonitorsCount, _physicalMonitorArray))
        {
            throw new Exception("Cannot get phisical monitor handle!");
        }
        _firstMonitorHandle = _physicalMonitorArray[0].hPhysicalMonitor;

        if (!GetMonitorBrightness(_firstMonitorHandle, ref _minValue, ref _currentValue, ref _maxValue))
        {
            throw new Exception("Cannot get monitor brightness!");
        }
    }

    public void SetBrightness(int newValue) // 0 ~ 100
    {
        newValue = Math.Min(newValue, Math.Max(0, newValue));
        _currentValue = (_maxValue - _minValue) * (uint)newValue / 100u + _minValue;
        SetMonitorBrightness(_firstMonitorHandle, _currentValue);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_physicalMonitorsCount > 0)
            {
                DestroyPhysicalMonitors(_physicalMonitorsCount, ref _physicalMonitorArray);
            }
        }
    }
}
//get the actual percentage of brightness
static int GetCurrentBrightness()
{
    //define scope (namespace)
    System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");
    //define query
    System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness");
    //output current brightness
    System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);
    System.Management.ManagementObjectCollection moc = mos.Get();
    //store result
    byte curBrightness = 0;
    foreach (System.Management.ManagementObject o in moc)
    {
        curBrightness = (byte)o.GetPropertyValue("CurrentBrightness");
        break; //only work on the first object
    }
    moc.Dispose();
    mos.Dispose();
    return (int)curBrightness;
}

//array of valid brightness values in percent
static byte[] GetBrightnessLevels()
{
    //define scope (namespace)
    System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");
    //define query
    System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness");
    //output current brightness
    System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);
    byte[] BrightnessLevels = new byte[0];
    try
    {
        System.Management.ManagementObjectCollection moc = mos.Get();
        //store result
        foreach (System.Management.ManagementObject o in moc)
        {
            BrightnessLevels = (byte[])o.GetPropertyValue("Level");
            break; //only work on the first object
        }
        moc.Dispose();
        mos.Dispose();

    }
    catch (Exception)
    {
        MessageBox.Show("Sorry, Your System does not support this brightness control...");
    }
    return BrightnessLevels;
}

static void SetBrightness(byte targetBrightness)
{
    //define scope (namespace)
    System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI");
    //define query
    System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightnessMethods");
    //output current brightness
    System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q);
    System.Management.ManagementObjectCollection moc = mos.Get();
    foreach (System.Management.ManagementObject o in moc)
    {
        o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness });
        //note the reversed order - won't work otherwise!
        break; //only work on the first object
    }

    moc.Dispose();
    mos.Dispose();
}