You would think that this exists in .NET (like maybe the Screen class) but there is aparently no way in .NET to get the DPI of the screen. So here it is using p/invoke.
Do you find this useful? If so please check out Windward Reports.
public class NativeMethods
{
[DllImport("gdi32.dll", EntryPoint = "CreateDC", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CreateDC(string lpszDriver, string lpszDeviceName, string lpszOutput, IntPtr devMode);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll", SetLastError = true)]
private static extern Int32 GetDeviceCaps(IntPtr hdc, Int32 capindex);
private const int LOGPIXELSX = 88;
private static int _dpi = -1;
public static int DPI
{
get
{
if (_dpi != -1)
return _dpi;
_dpi = 96;
try
{
IntPtr hdc = CreateDC("DISPLAY", null, null, IntPtr.Zero);
if (hdc != IntPtr.Zero)
{
_dpi = GetDeviceCaps(hdc, LOGPIXELSX);
if (_dpi == 0)
_dpi = 96;
DeleteDC(hdc);
}
}
catch (Exception)
{
}
return _dpi;
}
}
}
Do you find this useful? If so please check out Windward Reports.
Thanks a bundle for this, I too spent ages looking through the Screen class and so on. Equally amazed this needed p/invoke, especially with all the Win 7 trumpeting about high DPI support :-. (whistles).
I haven't done enough GDI to have knocked this out quickly myself.. so thanks again!
Posted by: Leonjollans | June 25, 2010 at 05:41 AM
Try changing your screen properties to large fonts - then you will see this as 105.
Posted by: David Thielen | December 24, 2008 at 09:45 AM
This is the same as Graphics.DpiX and Graphics.DpiY in .Net..... which they both don't work properly...
The return value is not resolution independent..... i get 96 dpi as my value on all my resolutions.
Posted by: DJ Burb | December 23, 2008 at 02:44 PM