[C#]表單放大或縮小後,控制項跟著表單比例放大

  • 64169
  • 0
  • 2010-08-02

表單放大或縮小後,控制項跟著表單比例放大

有時候會希望表單放大或縮小後,控制項跟著表單比例放大

在Visual Studio 2005後,可以透過Control.Anchor 屬性做設定(感謝regionbbs與larrynung 指教)

Control.Anchor 屬性

取得或設定控制項繫結至的容器邊緣,並決定控制項隨其父代重新調整大小的方式。

命名空間: System.Windows.Forms
組件: System.Windows.Forms (在 system.windows.forms.dll 中)

 http://msdn.microsoft.com/zh-tw/library/system.windows.forms.control.anchor(VS.80).aspx

 

而假如想要透過寫程式的方式計算比例大小的話,可以分成以下的步驟

Step1.紀錄Form本來的大小(長與寬)
Step2.Form.Resize事件觸發時用目前大小與之前大小計算長寬縮放比例
     (目前大小/本來大小)(需注意大小為0的狀況)
Step3.把控制項大小*長寬縮放比例
Step4.把Form本來大小值設為目前大小值

以下為程式碼

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


namespace FormResize
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        double oldWidth;
        double oldHeight;

        private void Form1_Load(object sender, EventArgs e)
        {
            // Step1.紀錄Form本來的大小(長與寬)
            oldWidth = this.Width;
            oldHeight = this.Height;
        }


        private void Form1_Resize(object sender, EventArgs e)
        {
            // Step2.計算比例
            double x = (this.Width / oldWidth);
            double y = (this.Height / oldHeight);

            // Step3.控制項 Resize
            button1.Width = Convert.ToInt32(x * button1.Width);
            button1.Height = Convert.ToInt32(y * button1.Height);
            button2.Width = Convert.ToInt32(x * button2.Width);
            button2.Height = Convert.ToInt32(y * button2.Height);
            textBox1.Width = Convert.ToInt32(x * textBox1.Width);
            textBox1.Height = Convert.ToInt32(y * textBox1.Height);
            textBox2.Width = Convert.ToInt32(x * textBox2.Width);
            textBox2.Height = Convert.ToInt32(y * textBox2.Height);

            // Step4.把Form本來大小值設為目前大小值
            oldWidth = this.Width;
            oldHeight = this.Height;
        }



    }

}

執行結果

原始Form

放大Form

縮小Form

 

參考
http://www.programmer-club.com/pc2020v5/Forum/ShowSameTitleN.asp?URL=N&board_pc2020=vbdotnet&index=4&id=14009&mode=&type_pc2020=sametitleLevel-2=

http://www.blueshop.com.tw/board/show.asp?subcde=BRD200902190134363RD&fumcde