I have a widescreen monitor and I want to keep aspect ratio of my application and even handle "wrong" resolution that might be set.
For example monitor can display perfect circle with resolution 1920x1080. But circle looks like ellipse when resolution 1400x1050 is set.
Our client is really picky on this and asks to determine and resize app to display perfect circle with any resolution and monitor we can handle.
So is it possible somehow to scale application and keep aspect ratio to display it with proper proportions on real device?
You could override the OnResize
event of the Form
to preserve its aspect ratio:
private static readonly Size MaxResolution = GetMaxResolution();
private static double AspectRatio = (double)MaxResolution.Width / MaxResolution.Height;
private readonly PointF Dpi;
public YourForm() // constructor
{
Dpi = GetDpi();
AspectRatio *= Dpi.X / Dpi.Y;
}
private PointF GetDpi()
{
PointF dpi = PointF.Empty;
using (Graphics g = CreateGraphics())
{
dpi.X = g.DpiX;
dpi.Y = g.DpiY;
}
return dpi;
}
private static Size GetMaxResolution()
{
var scope = new ManagementScope();
var q = new ObjectQuery("SELECT * FROM CIM_VideoControllerResolution");
using (var searcher = new ManagementObjectSearcher(scope, q))
{
var results = searcher.Get();
int maxHResolution = 0;
int maxVResolution = 0;
foreach (var item in results)
{
if (item.GetPropertyValue("HorizontalResolution") == null)
continue;
int h = int.Parse(item["HorizontalResolution"].ToString());
int v = int.Parse(item["VerticalResolution"].ToString());
if (h > maxHResolution || v > maxVResolution)
{
maxHResolution = h;
maxVResolution = v;
}
}
return new Size(maxHResolution, maxVResolution);
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
int minWidth = Math.Min(Width, (int)(Height * AspectRatio));
if (WindowState == FormWindowState.Normal)
Size = new Size(minWidth, (int)(minWidth / AspectRatio));
}
EDIT
Assuming that the maximum screen resolution reflects the "square" requirement, you could get all the screen resolutions as described here and here. You only need to find the "maximum" of them.
Notice, that Windows usually doesn't have real DPI values, I use DPI only to compare the horizontal DPI with the vertical one.