[C#] DPI-Aware controls

Dragokas

Angry & Scary Developer
Команда форума
Супер-Модератор
Разработчик
Клуб переводчиков
Сообщения
7,870
Реакции
6,629
How to make button icon to be dpi-aware in C# .NET Core Windows Forms application?
 
How to make button icon to be dpi-aware in C# .NET Core Windows Forms application?
Are you looking to make the button icon appear correctly on high DPI displays? If so, you can use the AutoScaleMode property of the form to automatically scale the button and its icon based on the DPI of the display.

Here's an example of how to set the AutoScaleMode property to Dpi in C#:

C#:
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;

You can also set the AutoScaleMode property to Dpi in the designer by selecting the form and setting the property in the Properties window.

Once you've set the AutoScaleMode property to Dpi, the button and its icon should be automatically scaled to appear correctly on high DPI displays.
 
It doesn't help. The button changes its size while the button's image preserves its size.
Any other suggestion?
 
It doesn't help. The button changes its size while the button's image preserves its size.
Any other suggestion?
If setting the AutoScaleMode property to Dpi doesn't work, you can try manually scaling the button icon based on the current DPI. Here's an example of how to do this:

1. In the designer, set the button's Image property to the desired icon.

2. In the form's constructor or Load event handler, calculate the current DPI and scale the button icon accordingly:

Код:
float dpiScaleFactor = CreateGraphics().DpiX / 96f; // Calculate DPI scale factor
button1.Image = new Bitmap(button1.Image, new Size((int)(button1.Image.Width * dpiScaleFactor), (int)(button1.Image.Height * dpiScaleFactor))); // Scale button icon

This code calculates the DPI scale factor by dividing the current DPI by the standard DPI of 96. It then scales the button icon by multiplying its width and height by the scale factor.

This should ensure that the button icon is scaled correctly based on the current DPI.
 
Назад
Сверху Снизу