繁体   English   中英

表格的高度与宽度之比应恒定

[英]Ratio between height and width of the form should be constant

我有一个带有两个图片框和一些按钮的表单,我希望它们根据屏幕分辨率进行组织。 这是我的代码:

public partial class Form1 : Form
    {         
        int SystemWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
        int SystemHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
        double ratio;

        public Form1()
        {               
            InitializeComponent();
            this.Width = SystemWidth-200;
            this.Height = SystemHeight-200;
           // this.WindowState = FormWindowState.Maximized;

            ratio= SystemWidth / SystemHeight;

        }

        private void Form1_Resize(object sender, EventArgs e)
        {           
            Anordnen();  
        }

        private void Anordnen()
        {
            pic1.Width = this.ClientSize.Width / 2 - 30;
            pic2.Width = this.ClientSize.Width / 2 - 30;
            pic1.Left = 20;
            pic2.Left = pic1.Right + 20;

            btnVergleichen.Left = pic1.Right + 10 - btnVergleichen.Width / 2;
            btnEinlesen1.Left = pic1.Left + pic1.Width / 2 - btnEinlesen1.Width / 2;
            btnBewerten1.Left = pic1.Left + pic1.Width / 2 - btnBewerten1.Width / 2;
            btnEinlesen2.Left = pic2.Left + pic2.Width / 2 - btnEinlesen2.Width / 2;
            btnBewerten2.Left = pic2.Left + pic2.Width / 2 - btnBewerten2.Width / 2;
        }

现在,我希望SystemWidth和SystemHeight之间的比率始终保持不变。 如果我放大表格的宽度,则高度会自动变大。 我所有的尝试都失败了。

试试这个代码:

public partial class Form1 : Form
{         
    int SystemWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
    int SystemHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
    private readonly double Ratio;
    private int oldWidth;
    private int oldHeight;

    public Form1()
    {               
        InitializeComponent();

        Ratio = (double)SystemWidth / SystemHeight;
        Size = new Size((int)(SystemWidth - 200 * Ratio), SystemHeight - 200);
    }

    protected override void OnResizeBegin(EventArgs e)
    {
        oldWidth = Width;
        oldHeight = Height;
        base.OnResizeBegin(e);
    }

    protected override void OnResize(EventArgs e)
    {
        int dw = Width - oldWidth;
        int dh = Height - oldHeight;
        if (Math.Abs(dw) < Math.Abs(dh * Ratio))
            Width = (int)(oldWidth + dh * Ratio);
        else
            Height = (int)(oldHeight + dw / Ratio);
        base.OnResize(e);
    }
}

编辑
条件if (dw > dh * Ratio)替换为if (Math.Abs(dw) < Math.Abs(dh * Ratio))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM