Can I Tell Visual Studio not to Change the DPI of

2020-02-26 09:54发布

问题:

I have a project converted from .NET 1.1 to 3.5 being developed in 2008.

If I open the project on Windows 7, it converts the size of everything to 120dpi sizes. If I then open it with 96 dpi it changes back. Is there any way for me to develop so it looks good in both, and not have Visual Studio change the sizes if opened on a system with different DPI?

This question is perhaps better phrased/duplicated here: visual studio designer dpi setting

Or here: Visual Studio and DPI issue

To be clear what I am trying to do is prevent the control from being resized in the designer when being used by multiple developers with different DPI settings. In all cases where I've noticed this issue I've been working with a .NET 1 or .NET 2 project upgraded to use Visual Studio 2008 originally, now Visual Studio 2010.

Update (in case anyone wants to compete with @Ben for bonus points): I have a form which resizes correctly, but the size of the window gets changed programmatically. Because the designer isn't aware of the dimensions, the window resizes incorrectly if a developer using a different DPI touches the form. Is there a way of getting around that problem other than going back to not scaling the UI at runtime?

For instance: I have two sizes for my window declared, which work correctly if developers use 120 dpi at design time:

private static Size smallSize = new Size(960, 500);
private static Size largeSize = new Size(960, 615);

I'm just trying to wrap my head around what I would need to do to not have a horrible design regression if someone edits the form in a 96dpi designer.

回答1:

AutoScaleMode = AutoScaleMode.None;

See also: ContainerControl.AutoScaleMode property



回答2:

Since I ran into the same issue recently, I wanna share my workaround.

First: KEEP AutoScaleMode = Font! This will work nicely at runtime to make your application DPI-aware. (Even cool per-Monitor DPI Aware).

However, the WinForms Designer in Visual Studio actually evaluates the fonts sizes based on the system's DPI, and thus rescales whenever it thinks it is necessary. This is the core of the problem. This evaluation is triggered because the fonts usually specify their size in "point" (to give a DPI-independent user experience).

My workaround is to change this for design time:

  • Set in your Forms Designer: Font = MS Sans; 11px. This is basically the OS default font, but specified with pixel-size. So no design-time rescaling will ever take place.
  • Now, to get High-DPI adaption back at runtime, change the Font back to use sizes specified in point. E.g. Font = SystemFonts.Default. A good place is in the Ctor right after InitializeComponents.

I wrote the details about my workaround on my Blog: http://www.sgrottel.de/?p=1581&lang=en