简体   繁体   中英

Is there a way to retrieve a device's DPI without using GDI+/WinForms “Graphics” class?

Is it possible to get my devices DPI from c# using a native win api call?

I know how to get the dpi from a windows forms application and the current code I have is:

  Graphics g = Graphics.FromImage(new Bitmap(10, 10));

  var scaleX = g.DpiX / 96.0f;
  var scaleY = g.DpiY / 96.0f;

I was wondering if the is a win api call that can make things easier.

What about a WMI Query to the Win32_DesktopMonitor class ?

PixelsPerXLogicalInch

 Data type: uint32 Access type: Read-only Qualifiers: Units (Pixels per Logical Inch) 

Resolution along the x-axis (horizontal direction) of the monitor.

PixelsPerYLogicalInch

 Data type: uint32 Access type: Read-only Qualifiers: Units (Pixels per Logical Inch) 

Resolution along the y-axis (vertical direction) of the monitor.

You might use it similar to this question :

ManagementObjectSearcher monitorObjectSearch = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor");

foreach (ManagementObject monitor in monitorObjectSearch.Get())
{
      Debug.WriteLine(monitor["PixelsPerXLogicalInch");
      Debug.WriteLine(monitor["PixelsPerYLogicalInch");
}

There is also the Windows API Route with GetDeviceCaps , but I've read that there are some issues with it on Windows 7 so your mileage may be different.

There is also the Direct2D GetDesktopDpi ( mentioned by Alex ), which looks like it would require doing some COM Interop calls, and may or may not be as clean and will only work Windows versions where Direct2D is available. Some additional information on Direct2D and .NET.

there is api for that, http://msdn.microsoft.com/en-us/library/windows/desktop/dd371316(v=vs.85).aspx called getDesktopApi, but i've never used it. i assume it's as easy as doing any interop call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM