Learn Programming
Learn Programming

Reputation: 161

How to get DPI in C# .NET?

I'm trying to build a Windows Forms application using C#.

How do I get the DPI in .NET?

I've read before that there is DPIX and DPIY, which can be used in .NET to get the current DPI.

Is that correct?

Thanks all.

Upvotes: 16

Views: 53561

Answers (2)

Pavel Vladov
Pavel Vladov

Reputation: 4837

Modern Way to Get the DPI in a WinForms Application

In .NET Framework 4.7 or newer (for example .NET 6.0), you can use the Control.DeviceDpi property to get the DPI value for the screen on which the control is currently being displayed.

int dpi = this.DeviceDpi;

The value returned by the Control.DeviceDpi property depends on the DPI awareness mode of the application.

In .NET 5.0 and newer, you can set the DPI awareness of a WinForms application in its entry point using the Application.SetHighDpiMode method. Possible modes are listed on this MSDN page. The best mode is "PerMonitorV2", which takes into account the DPI settings of the current screen:

Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);

In .NET 4.7 and .NET 4.8 you should declare the DPI awareness of your application in a manifest file. I recommend "PerMonitorV2". Please take a look at the following documentation topic for more information and an example:

Setting the default DPI awareness for a process

Upvotes: 9

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56747

Use an instance of the Graphics class. You get this using the following within your form (could be in form's Load event handler):

float dx, dy;

Graphics g = this.CreateGraphics();
try
{
    dx = g.DpiX;
    dy = g.DpiY;
}
finally
{
    g.Dispose();
}

Upvotes: 34

Related Questions