C#代码:
public void AutoScale(Form frm)
{
frm.Tag = frm.Width.ToString() + "," + frm.Height.ToString();
frm.SizeChanged += new EventHandler(frmScreen_SizeChanged);
}
private void frmScreen_SizeChanged(object sender, EventArgs e)
{
string[] tmp = ((Form)sender).Tag.ToString().Split(',');
float width = (float)((Form)sender).Width / (float)Convert.ToInt16(tmp[0]);
float heigth = (float)((Form)sender).Height / (float)Convert.ToInt16(tmp[1]);
((Form)sender).Tag = ((Form)sender).Width.ToString() + "," + ((Form)sender).Height;
foreach (Control control in ((Form)sender).Controls)
{
control.Scale(new SizeF(width, heigth));
}
}
public frmScreen()
{
InitializeComponent();
AutoScale(this);
}
VB代码:
Option Explicit
Private Type MeFrmControl
iControl As Object
Left As Long
Top As Long
Width As Long
Height As Long
End Type
Dim iFrmCs() As MeFrmControl '''自动缩放窗体内控件
Private Sub Form_Load()
'''最好将代码放到LOad的最后执行
''''===============================
'''自动缩放窗体内控件 开始
''''===============================
With Me
.ScaleMode = 3
.ScaleHeight = 1000
.ScaleWidth = 1000
End With
Dim iFC As Control, i As Long
i = -1
On Error Resume Next
For Each iFC In Me.Controls
If UCase(TypeName(iFC)) <> "MENU" Then '在这里你可以添加不希望或不支持运行时改变大小的控件名
ReDim Preserve iFrmCs(i + 1) As MeFrmControl
i = i + 1
With iFrmCs(i)
Set .iControl = iFC
.Left = iFC.Left
.Top = iFC.Top
.Width = iFC.Width
.Height = iFC.Height
End With
End If
Next
ScaleMode = 1
''''===============================
'''自动缩放窗体内控件 结束
''''===============================
End Sub
Private Sub Form_Resize()
''''===============================
'''自动缩放窗体内控件 开始
''''===============================
If Me.WindowState = 1 Then Exit Sub
Dim iFC As Long
With Me
.ScaleMode = 3
.ScaleHeight = 1000
.ScaleWidth = 1000
End With
For iFC = 0 To UBound(iFrmCs)
iFrmCs(iFC).iControl.Move iFrmCs(iFC).Left, iFrmCs(iFC).Top, iFrmCs(iFC).Width, iFrmCs(iFC).Height
Next
ScaleMode = 1
''''===============================
'''自动缩放窗体内控件 结束
''''===============================
End Sub