C#: Get DPI of screen

It used to be the case that most monitors had a screen resolution of 96DPI. When developing software, this meant developers could hard-code values when designing their interfaces.

This is no longer the case. The latest generation of screens and laptops are likely to have very high resolutions, perhaps greater than 200DPI (dots per inch).

At this resolution, fonts and windows would become uselessly small. This is my 13″ laptop display at 3200×1800:

desktop

As you can see, it is quite unusable. Windows can therefore scale up window elements to a more natural size.

Here is my screen at 200% scaling:

desktop2

What this means for developers

When we develop software, we must make sure it works well across a range of user environments, and this now includes testing for a range of screen resolutions.

Fortunately, modern UI libraries will automatically scale built-in elements according to the screen. For example, if you specify the width of a button to be 100 pixels in WPF, on my screen with a scaling of 200%, this button would automatically be rendered at 200 pixels.

However, you may find that some custom elements do not scale properly. You may also be using some ‘fudge factors’ in your code-behind (such as the C# file associated with a XAML file in WPF) that are constant. These may be written in such a way that your UI library doesn’t scale them.

For example, say you have a margin of 10 pixels written in your code-behind. How do you tell your program to scale up this value to any scaling factor?

Get the scaling factor in C#

This is quite easy. Simply calculate the following value in your code:

double factor = System.Windows.PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.M11;

Then, wherever you have a constant value in your code-behind, multiply it by factor, e.g.

button.Left = 10 * factor;

Output

The code above returns a value that is usually between 1 and 2.5. If the user’s system DPI settings are set to 200%, a value of 2.0 should be returned.

To calculate the scaling factor in terms of DPI, multiply by 96. For example, if the system settings are at 200%, the DPI is 196DPI. Note that this value can be changed by the user if they want the screen to appear smaller or larger, so the concept of an ‘inch’ doesn’t always rigorously apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.