我正在使用一个类来增加和减少我所有屏幕的伽玛,然后我启动程序并增加或减少伽玛它工作正常,但过了一段时间(20 秒左右)它不再工作了,我找到了问题,这似乎是Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32();
我需要刷新它然后它再次工作。在示例代码中,这仅在初始化期间完成一次,但为了使其工作,我已将行粘贴到SetBrightness()
方法内,因此每次刷新。这样做可以吗?或者我可以期待问题吗?
这是代码:
public static class Brightness
{
[DllImport("gdi32.dll")]
private unsafe static extern bool SetDeviceGammaRamp(Int32 hdc, void* ramp);
private static bool initialized = false;
private static Int32 hdc;
private static void InitializeClass()
{
if (initialized)
return;
//Get the hardware device context of the screen, we can do
//this by getting the graphics object of null (IntPtr.Zero)
//then getting the HDC and converting that to an Int32.
hdc = Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32();
initialized = true;
}
public static unsafe bool SetBrightness(short brightness)
{
InitializeClass();
hdc = Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32();
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++;
}
}
//For some reason, this always returns false?
bool retVal = SetDeviceGammaRamp(hdc, gArray);
//Memory allocated through stackalloc is automatically free'd
//by the CLR.
return retVal;
}
}
这就是它的名称:
short gammaValue = 128;
void gammaUp_OnButtonDown(object sender, EventArgs e)
{
if (gammaValue < 255)
{
gammaValue += 10;
if (gammaValue > 255)
gammaValue = 255;
Brightness.SetBrightness(gammaValue);
}
}
void gammaDown_OnButtonDown(object sender, EventArgs e)
{
if (gammaValue > 0)
{
gammaValue -= 10;
if (gammaValue < 0)
gammaValue = 0;
Brightness.SetBrightness(gammaValue);
}
}