クラスを使用してすべての画面のガンマを増減し、プログラムを開始してガンマを増減すると正常に動作しますが、しばらくすると (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);
}
}