I ame using a class to increase and decrease the gamma of all my screens, then i start the program and increase or decrease the gamma it works fine, but after a while (20 seconds or so) it does not work anymore, ive located the problem and it seems to be the Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32();
i need to refresh this and then it works again. in the example code this is only done once during initialisation, but to make it work i have pasted the line inside the SetBrightness()
method, so everytime it is refreshed. is it ok to do it like this or can i expect problems?
This is the code:
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;
}
}
This is how it is called:
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);
}
}
I don't see any problem specifically with using
Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32();
twice, although I would expect the value to be the same both times, unless something external to your program is affecting it.I would be more concerned about the following section always returning false.
The documentation specifies
so I would say that something is not working correctly for that call to always return false.