I need to write something like Adjust screen brightness using C# in VB.NET but there is a pointer parameter in SetDeviceGammaRamp(Int32 hdc, void* ramp)
. In VB6 there is VarPtr()
to get around but it is no longer supported. Every code converter does not work with pointers in VB.NET and C-style pointer in Visual Basic .NET states that there is no such thing as pointers in VB.NET so I wonder if there is a way to get around. Also, how should I declare the function?
BTW adjusting screen brightness is solved in C#, Mac OS X, J2ME, Python and even Android.
C# code:
using System;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
namespace Brightness
{
/// <summary>
/// Class for manipulating the brightness of the screen
/// </summary>
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();
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;
}
}
}
Why code converters don't work with pointers in VB.NET (There is no class called Pointer(Of T)
):
<DllImport("gdi32.dll")> _
Private Shared Function SetDeviceGammaRamp(hdc As Int32, ramp As Pointer(Of System.Void)) As Boolean
End Function
Dim gArray As Pointer(Of Short) = stackalloc
Dim idx As Pointer(Of Short) = gArray
Don't think this is needed as hdc = Graphics.FromHwnd(IntPtr.Zero).GetHdc().ToInt32()
does it.
<DllImport("gdi32.dll")> _
Private Shared Function GetDeviceGammaRamp(hdc As IntPtr, lpRamp As IntPtr) As Boolean
End Function