我试图在c#中制作一个眼睛保护程序,它应该会在一段时间的工作后使屏幕变暗。为了改变屏幕亮度,我遵循了使用SetDeviceGammaRamp方法的这篇(https://www.codeproject.com/Articles/47355/Setting-Screen-Brightness-in-C)文章。我的代码如下:
private unsafe void dimScreen()
{
var brightness = 10;
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++;
}
}
SetDeviceGammaRamp(hdc, gArray);
Thread.Sleep(10000);
}
但是,屏幕不会永久改变亮度(或至少持续10秒钟),而是闪烁半秒钟。在休眠状态下多次调用SetDeviceGammaRamp并没有改变这种情况,我得到的只是几次这样的眨眼。如果我改变亮度变量,那个闪烁的亮度也会改变,所以我假设hdc和gArray变量被正确分配。我试图寻找其他解决方案,但大多数使用这种方法,似乎没有人有这个问题。关于问题可能是什么想法?
UPD:似乎一直存在问题。它注意到伽玛的变化并将其重置为先前的值。答案 0 :(得分:0)
这里是C#中可以设置屏幕亮度的代码。你可以尝试一下。
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);
}
}
}
实际上你的代码没有错误。你如何使用这个dimScreen()
函数?也许你用不恰当的逻辑来做这件事。
我在这里找到了一个带图片的教程:http://www.lattepanda.com/topic-f11t3020.html