コントロール適応サイズ【C#】
1、抽象的な適応サイズからのクラスは以下の通りである.
2、適応サイズが必要なFormインタフェースで、loadとresize方法で応用する:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace FormAutoSize
{
class AutomaticSize
{
/*
* , Anchor Dock .
private AutomaticSize automaticSize = new AutomaticSize();
private void FrmPwd_Load(object sender, EventArgs e)
{
automaticSize.Width = this.Width;
automaticSize.Height = this.Height;
automaticSize.SetTag(this);
}
private void FrmPwd_Resize(object sender, EventArgs e)
{
automaticSize.ControlResize(this);
}
*/
private float width;
private float height;
public float Height
{
get { return height; }
set { height = value; }
}
public float Width
{
get { return width; }
set { width = value; }
}
/// <summary>
/// Tag
/// </summary>
/// <param name="controls"> </param>
public void SetTag(Control controls)
{
foreach (Control control in controls.Controls)
{
control.Tag = control.Width + ":" + control.Height + ":" + control.Left + ":" + control.Top + ":" + control.Font.Size;
if (control.Controls.Count > 0)
{
SetTag(control);
}
}
}
/// <summary>
///
/// </summary>
/// <param name="newX">X </param>
/// <param name="newY">Y </param>
/// <param name="controls"> </param>
private void SetControls(float newX, float newY, Control controls)
{
foreach (Control control in controls.Controls)
{
string[] myTag = control.Tag.ToString().Split(':');
//
float length = Convert.ToSingle(myTag[0]) * newX;
control.Width = (int)length;
//
length = Convert.ToSingle(myTag[1]) * newY;
control.Height = (int)length;
// X
length = Convert.ToSingle(myTag[2]) * newX;
control.Left = (int)length;
// Y
length = Convert.ToSingle(myTag[3]) * newY;
control.Top = (int)length;
Single currentSize = Convert.ToSingle(myTag[4]) * newY;
control.Font = new System.Drawing.Font(control.Font.Name, currentSize, control.Font.Style, control.Font.Unit);
if (control.Controls.Count > 0)
{
SetControls(newX, newY, control);
}
}
}
/// <summary>
///
/// </summary>
public void ControlResize(Control control)
{
float newX = control.Width / this.width;
float newY = control.Height / this.height;
SetControls(newX, newY, control);
}
}
}
2、適応サイズが必要なFormインタフェースで、loadとresize方法で応用する:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace FormAutoSize
{
public partial class Form1 : Form
{
private AutomaticSize automaticSize = new AutomaticSize();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
automaticSize.Width = this.Width;
automaticSize.Height = this.Height;
automaticSize.SetTag(this);
}
private void Form1_Resize(object sender, EventArgs e)
{
automaticSize.ControlResize(this);
}
}
}