2014-04-04 47 views
1

我有一個帶有兩個圖片框和一些按鈕的窗體,我希望它們根據屏幕分辨率自行組織。這裏是我的代碼:窗體的高度和寬度之間的比率應該是恆定的

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之間的比例始終保持不變。如果我放大窗體的寬度,高度應該會自動變大。我所有的嘗試失敗了。

回答

0

試試這個代碼:

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 (Math.Abs(dw) < Math.Abs(dh * Ratio))更換條件if (dw > dh * Ratio)

+0

我沒有得到任何錯誤,但它不起作用... – user3498536

+0

完美地適用於我。請澄清究竟*不起作用*?你如何調整表單的大小? – Dmitry

+0

這裏是我的問題的簡短視頻(在描述中,我寫過這些問題......):https://www.youtube.com/watch?v=PZWaZpJpEMI&feature=youtu.be – user3498536

相關問題