如何使不同的窗体控件,适应不同分辨率的屏幕?
问题
当屏幕分辨率提高或降低时,原分辨率显示正常的控件,将变得很小或很大,字体也变得太大或太小。
解决办法
当分辨率变化时,采用递归的方法,对所有的控件放大或缩小。
public static void MainForm_Load(object sender, EventArgs e)
{
// 获取当前屏幕分辨率
Screen screen = Screen.PrimaryScreen;
int currentWidth = screen.Bounds.Width;
int currentHeight = screen.Bounds.Height;
Control t =(Control) sender;
if (t.Width > 1700|| t.Width<1000)
{
// 计算宽度和高度的缩放因子
float widthScale = (float)currentWidth / 1920;
float heightScale = (float)currentHeight / 1080;
// 应用缩放因子
ScaleControls((Control)sender, widthScale, heightScale);
}
}
public static void ScaleControls(Control parentControl, float widthScale, float heightScale)
{
foreach (Control control in parentControl.Controls)
{
// 调整控件的大小和位置
control.Left = (int)(control.Left * widthScale);
control.Top = (int)(control.Top * heightScale);
control.Width = (int)(control.Width * widthScale);
control.Height = (int)(control.Height * heightScale);
if (control.Width > 1700)
{
// 调整字体大小
control.Font = new Font(control.Font.FontFamily, control.Font.Size * Math.Min(widthScale, heightScale));
}
else
control.Font = new Font("宋体", 9);
// 递归处理子控件
if (control.HasChildren)
{
ScaleControls(control, widthScale, heightScale);
}
}