开发者

How to get DPI in C# .NET?

开发者 https://www.devze.com 2023-03-23 10:51 出处:网络
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 DPI开发者_开发知识库X and DPIY, which can be used in .NET to get the current

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 DPI开发者_开发知识库X and DPIY, which can be used in .NET to get the current DPI.

Is that correct?

Thanks all.


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();
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号