Creating a DPI-Aware Application

RRR picture RRR · Nov 2, 2010 · Viewed 95.3k times · Source

I have a form application in C#. When I change the monitor's DPI, all the controls move. I used the code this.AutoScaleMode = AutoScaleMode.Dpi, but it didn't avoid the problem.

Does anyone have an idea?

Answer

Trygve picture Trygve · Nov 2, 2010

EDIT: As of .NET 4.7, windows forms has improved support for High DPI. Read more about it on docs.microsoft.com It only works for Win 10 Creators Update and higher though, so it might not be feasible to use this yet depending on your user base.


Difficult, but not impossible. Your best option is to move to WPF of course, but that might not be feasible.

I've spent A LOT of time with this problem. Here are some rules/guidelines to make it work correctly without a FlowLayoutPanel or TableLayoutPanel:

  • Always edit/design your apps in default 96 DPI (100%). If you design in 120DPI (125% f.ex) it will get really bad when you go back to 96 DPI to work with it later.
  • I've used AutoScaleMode.Font with success, I haven't tried AutoScaleMode.DPI much.
  • Make sure you use the default font size on all your containers (forms, panels, tabpage, usercontrols etc). 8,25 px. Preferrably it shouldn't be set in the .Designer.cs file at all for all containers so that it uses the default font from the container class.
  • All containers must use the same AutoScaleMode
  • Make sure all containers have the below line set in the Designer.cs file:

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); // for design in 96 DPI

  • If you need to set different font sizes on labels/textboxes etc. set them per control instead of setting the font on the container class because winforms uses the containers font setting to scale it's contents and having f.ex a panel with a different font size than it's containing form is guaranteed to make problems. It might work if the form and all containers on the form use the same font size, but I haven't tried it.
  • Use another machine or a virtual windows install (VMware, Virtual PC, VirtualBox) with a higher DPI setting to test your design immediatly. Just run the compiled .exe file from the /bin/Debug folder on the DEV machine.

I guarantee that if you follow these guidelines you will be ok, even when you have placed controls with specific anchors and don't use a flowpanel. We have an app built this way deployed on hundreds of machines with different DPI setups and we no longer have any complaints. All forms/containers/grids/buttons/textfield etc sizes are scaled correctly as is the font. Images work too, but they tend to get a little pixellated at high DPI.

EDIT: This link has a lot of good info, especially if you choose to use AutoScaleMode.DPI: link to related stackoverflow question