2013-01-14 20 views
0

我正在使用TableLayoutPanel來包含控件,我想在窗體大小調整時自動調整大小。我想知道如何在窗體本身被調整大小時與窗體大小成比例地製作窗體的子控件「scale」?儘管TableLayoutPanel自動調整所包含控件的大小,但這些控件保持相同的字體大小。如何在表單大小更改時自動縮放子控件的字體大小?

+2

你有沒有看過一個程序,當窗口變小時,字體變小?這不是它完成的方式。 –

+0

我發佈的答案對我的要求很好。 – gonzobrains

回答

4

這是迄今爲止我提出的最好的方法。我使用了兩個比例因子,並遍歷所有控件以選擇我想要縮放的比例:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace TestTableLayoutPanel 
{ 
    public partial class Form2 : Form 
    { 
     private const float LARGER_FONT_FACTOR = 1.5f; 
     private const float SMALLER_FONT_FACTOR = 0.8f; 

     private int _lastFormSize; 

     public Form2() 
     { 
      InitializeComponent(); 

      this.Resize += new EventHandler(Form2_Resize); 
      _lastFormSize = GetFormArea(this.Size); 
     } 

     private int GetFormArea(Size size) 
     { 
      return size.Height * size.Width; 
     } 

     private void Form2_Resize(object sender, EventArgs e) 
     { 

      var bigger = GetFormArea(this.Size) > _lastFormSize; 
      float scaleFactor = bigger ? LARGER_FONT_FACTOR : SMALLER_FONT_FACTOR; 

      ResizeFont(this.Controls, scaleFactor); 

      _lastFormSize = GetFormArea(this.Size); 

     } 

     private void ResizeFont(Control.ControlCollection coll, float scaleFactor) 
     { 
      foreach (Control c in coll) 
      { 
       if (c.HasChildren) 
       { 
        ResizeFont(c.Controls, scaleFactor); 
       } 
       else 
       { 
        //if (c.GetType().ToString() == "System.Windows.Form.Label") 
        if (true) 
        { 
         // scale font 
         c.Font = new Font(c.Font.FontFamily.Name, c.Font.Size * scaleFactor); 
        } 
       } 
      } 
     } 
    } 
} 
+1

Steven P幫助我通過他的建議在此提出我的問題的答案: http://stackoverflow.com/questions/9510577/resizing-a-label-and-font-of-the-form-基於窗口的大小 – gonzobrains

+0

我編輯了你的帖子以修復代碼格式(它被分成兩部分)。 – Brian

+1

謝謝!我不確定它是如何分裂的,但至少現在已經修復了。 – gonzobrains

相關問題