- 1 year ago
Windows Forms application DPI support does not work when location is changed dynamically
When working with Windows Forms applications and DPI scaling, it's important to consider the impact of dynamic changes to the form's location. By default, Windows Forms applications are not automatically DPI-aware, and changing the form's location dynamically may not adjust the DPI scaling as expected.
To ensure proper DPI scaling when dynamically changing the form's location, you can follow these steps:
Enable DPI Awareness:
- Open the
app.manifest
file associated with your Windows Forms application. - Uncomment the line
<dpiAware>true</dpiAware>
to enable DPI awareness. - Save the file.
- Open the
Handle the
SizeChanged
Event:- Subscribe to the
SizeChanged
event of your form. - In the event handler, force a re-evaluation of the DPI scaling and adjust the form's layout and controls accordingly.
csharpprivate void Form1_SizeChanged(object sender, EventArgs e)
{
if (Environment.OSVersion.Version.Major >= 6) // Check for Windows Vista or later
{
float dpiX, dpiY;
using (Graphics graphics = CreateGraphics())
{
dpiX = graphics.DpiX;
dpiY = graphics.DpiY;
}
// Adjust the form's layout and controls based on the new DPI scaling
// Example: Multiply the original location by the ratio of the current DPI scaling to the default DPI (96)
int originalX = 100; // Example original X location
int originalY = 100; // Example original Y location
int newX = (int)(originalX * (dpiX / 96));
int newY = (int)(originalY * (dpiY / 96));
Location = new Point(newX, newY);
}
}
Adjust the code inside the event handler to match your specific requirements and the layout adjustments you need to make when the form's size changes.
- Subscribe to the
By enabling DPI awareness and handling the SizeChanged
event to adjust the form's layout and controls based on the current DPI scaling, you can ensure proper DPI support even when the form's location is changed dynamically.