[:en]Designing WinForms GUI on Systems with different DPI Settings – It’s all about Font![:]

[:en]Designing WinForms GUI on Systems with different DPI Settings – It’s all about Font![:]
WinForms De-Blurred

[:en]

The Problem

We have projects working with WinForms GUIS. Different Developers work with different Computers, and these have different DPI settings. Every time the Project is opened on a system with different DPIs the WinForms get scaled, which is painfully bad.

Solution Summary

  • Set in your Forms Designer: Font = MS Sans; 11px
  • In the Forms Ctor, after InitializeComponent, set: Font = SystemFonts.DefaultFont
  • Enable DPI-Awareness, either through a manifest or by API function SetProcessDPIAwareness

Solution Details

mmconf_blurless
Make your WinForms GUI less blurry by being DPI aware

A modern Windows approach to High-DPI Displays

More and more Computers get equipped with High-DPI Displays, a trend I like very much. Pixels cannot be small enough. With modern Windows, however, GUI of older Applications get infamously blurry. This is due to Microsoft’s approach for backward-compatibility: applications will be rendered at their native DPI and scaled up to the system’s DPI. This way, the application does not need to know anything about DPI, but user controls will keep a decent size on any setting. While most people hate the blurriness of old GUIs on modern Windows, this approach does make a lot of sense:

  • Backward-Compatibility is instantly given, as nothing changes for the old Applications.
  • The users input experience is retained, as the GUI will keep its apparent size. (Just thing, if you’re old enough, of the original GUI of Winamp, where the buttons in the default skin were sometimes just a few Pixels in size.)
  • (last but not least) for new Applications, Developers hopefully get upset with the blurry look, that they actually invest some time, to do it right!

So, don’t claim it’s all Microsoft’s fault that the GUI of your applications look blurry. Truth is, you were just too lazy to do it right.

Why WinForms?

If you browse the internet in search for how to handle high-DPI settings with WinForms, you are bound to stumble upon a smart-ass telling you to switch to WPF. That person does have a point: WPF is designed to be a GUI for all resolutions. But, that person is also an idiot. Don’t bother discussing.

If you decided to use WinForms, then use WinForms. It is not deprecated, it is not legacy, it is not broken. There are good reasons to use WinForms. One, for example, would be the nice compatibility with Mono (Linux and MacOS). Another one would be compatibility with native GUI controls. Whatever your reason is, don’t let other people easily throw you off track.

If you’re not fixed on WinForms, but want to write a new Application for Windows, then have a look at WPF.

Why does Visual Studio Scale?

Normally Windows works at 96 DPI. That is, you need 96 pixels to fill up one inch of screen space. On a higher setting, let’s say 144 DPI, you need 144 pixels. So, either your GUI elements will look smaller, or your GUI elements must be larger to look the same. Modern graphical content is thus not described in pixels, but often in points (pt). Points are defined as 1/72 inch, that is in screen space, and not in pixels.

WinForms is not a modern GUI. All Elements are designed with pixels. However, higher DPI settings were present in Windows for a long time (accessibility feature). WinForms answers to this by having a mechanism to scale the whole GUI ‘manually’. If a scaling factor different from one is determined, all GUI elements, positions, sizes, etc., are multiplied by that factor, including the overall size of the window. By default, this scaling factor is determined comparing the Font settings of the form. Fonts are usually specified with a size in pt. Windows computes the font size in pixels based on the active DPI value. If WinForms now detects a mismatch between the pixel-based font sizes between design-time specifications and run-time evaluation, the form and all content is scaled. And this is exactly what happens in the Visual Studio Windows Forms designer.

Visual Studio does basically nothing at all. However, the font size evaluation is based on the system’s DPI setting. So on high-DPI systems, the font’s pixel size will be different from the stored design-time pixel size, and thus the whole form will be scaled accordingly. That is a good idea at run-time. I mean, that is the whole point of this mechanism. However, we are still at design time. The problem raises, because the Forms designer in Visual Studio actually runs the WinForms engine. As now all GUI elements change their sizes, the designer is informed (likely by the normal events) and adjusts all generated code to the new sizes and locations. This is, of course, ugly, painful and stupid, if you are going to continue the development on another machine with another, maybe, lower DPI setting.

Disable Scaling at Design-Time, Enable Scaling at Run-Time

What I am writing here is not a premium solution. It is the workaround I found for myself to work best.

The basic idea is to (manually) disable scaling at design time, and to (manually) enable scaling at run time.

I write scaling, but what we actually change is the Font!

Keep the Form’s AutoScaleMode = Font. That setting is correct and is not the problem at all. The problem is the automatically used font. It is the system’s default font, which specifies its size in pt. Again, a good idea at run time. What we change is the Font setting of the Form, to specify the size in pixels.

In the Designer, set the Font to: Microsoft Sans Serif; 11px

Windows default Font is Microsoft San Serif 8 pt. according to MSDN. Actually, it seems more like 8.25 pt. So this is 8.25/72 inch, which finally results in 8.25 * 96/72 = 11 pixel on a normal DPI system. That is why you set the font to this painfully small looking value. It is the right one! Now edit your GUI on all systems you have. Your Forms will not be scaled by Visual Studio any more. So, design time is fixed.

Now for the run time. That one is easy, too. All we need to do is to ‘reset’ the Form’s font to have its size specified in pt. again. The easiest way to do that is to reassign the system’s default font. Just set it in the constructor, right after InitializeComponent:

Font = SystemFonts.DefaultFont;

This, of course, only works if you are on a system where the system’s default font is as expected, and only if you do not change fonts for the controls inside your form. If you did change some control’s font, you specify the font with pixel size for design time and you update these at run time initialization to use pt.-based sizes again.

Scalable GUI Design

And that is that. If your application is already DPI aware, your forms will now scale nicely. That is, if you designed them correctly.

  • You should not mix docking-based and anchor-based design in the same form. That is bound to produce weird scaling issues.
  • You must use either, otherwise the controls will just randomly shift somewhere.
  • Be aware that the control might no longer fit into your Form, due to the maximum window size. Use flowing layout containers and auto scrollbars.

Enable DPI Awareness

All that, of course, only makes any sense if you enable DPI awareness for your application. There are basically two options:

Manifest-Segment I use:

<application xmlns="urn:schemas-microsoft-com:asm.v3">
  <windowsSettings>
    <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
  </windowsSettings>
</application>

Code I use:

[DllImport("SHCore.dll")]
private static extern bool SetProcessDpiAwareness(PROCESS_DPI_AWARENESS awareness);

private enum PROCESS_DPI_AWARENESS {
    Process_DPI_Unaware = 0,
    Process_System_DPI_Aware = 1,
    Process_Per_Monitor_DPI_Aware = 2
}

[DllImport("user32.dll", SetLastError = true)]
static extern bool SetProcessDPIAware();

internal static void TryEnableDPIAware() {
    try {
        SetProcessDpiAwareness(PROCESS_DPI_AWARENESS.Process_Per_Monitor_DPI_Aware);
    } catch {
        try { // fallback, use (simpler) internal function
            SetProcessDPIAware();
        } catch { }
    }
}

Maybe, you know, that modern Windows can be even more complicated by per-monitor DPI settings. The idea is, that attached external screens have different sizes and resolutions, and should thus be handled with different DPIs. The good news is: this approach here works instantly with per-monitor DPI. When the form is dragged onto another monitor, the system automatically adjusts the font setting, as the font size is at run time specified in points. This automatically triggers a rescaling of the form. Wheee![:]

2 Kommentare zu „[:en]Designing WinForms GUI on Systems with different DPI Settings – It’s all about Font![:]

  1. I tried your approach and this solves problem with changing Location, Margin, AutoScaleDimensions but not Size attribute. Size is still changed if a form is saved on computer with different DPI. I tested this on two Windows 7 computers with different DPI setting. Any suggestions why that works for you and not for me? Default font should be the same Microsoft Sans Serif; 11px. I suspect that main problem lies in minimal size of controls. Many controls like ComboBox, Button, Label have minimal width and height. So if project designed with 96 DPI is opened on system with 120 DPI then controls can be displayed with such small size because minimal size is just higher because of higher DPI. So this is probably reason why Microsoft rather decided to automatically rescale form on high DPI environment. But what they done bad is that values in original form .Designed.cs file are also always updated. This really causes mess if a project is developed from various DPI environments.

    • Hello Chronos, that is weird. I have no idea. I had some issues when a form layout did mix layouting via docking and layouting via anchors at the same time. Apart from that, I never had any problems. What might be interesting, I always start on a 96-DPI system with my projects. Maybe this approach does not work the other way round wenn starting from a high-DPI system? I don’t know.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

*

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.