Domanda

I have a form with two pictureboxes and some buttons, and I want them to organize themselves depending on the screen resolution. Here is my code:

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;
        }

Now I want the ratio between SystemWidth and SystemHeight to always stay the same. If I enlarge the width of the form, the height should get automatically bigger. All my tries failed.

È stato utile?

Soluzione

Try this code:

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);
    }
}

EDIT
The condition if (dw > dh * Ratio) replaced with the if (Math.Abs(dw) < Math.Abs(dh * Ratio)).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top