本教程介绍如何在Visual Basic编程环境中设置窗体上的控件自适应调整大小和位置,以响应窗口尺寸的变化,实现界面布局的动态优化。
为了实现在VB窗体大小变化后控件自动调整的功能,在Form的Resize事件中调用以下函数即可实现:
```vba
Private Sub Form_Resize()
Dim H, i As Integer
On Error Resume Next
Resize_ALL Me Me代表当前活动的窗体,如Form1或Form2等。
End Sub
```
在模块代码部分添加如下内容以支持自动调整控件大小:
```vba
Public Type ctrObj
Name As String
Index As Long
Parrent As String
Top As Long
Left As Long
Height As Long
Width As Long
ScaleHeight As Long
ScaleWidth As Long
End Type
Private FormRecord() As ctrObj 用于存储窗体信息的数组。
Private ControlRecord() As ctrObj 用于存储控件信息的数组。
Private bRunning As Boolean 标志是否正在运行调整过程。
Private MaxForm As Long 记录最多有多少个窗体被跟踪过。
Private MaxControl As Long
定义一些函数来帮助实现自动调整大小功能:
Function ActualPos(plLeft As Long) As Long
If plLeft < 0 Then
ActualPos = plLeft + 75000
Else
ActualPos = plLeft
End If
End Function
Function FindForm(pfrmIn As Form) As Long 查找窗体。
Dim i As Long
FindForm = -1 默认找不到,返回-1。
If MaxForm > 0 Then 如果有记录的话就遍历数组看是否能找到该窗体。
For i = 0 To (MaxForm - 1)
If FormRecord(i).Name = pfrmIn.Name Then
FindForm = i
Exit Function
End If
Next i
End If
End Function
Function AddForm(pfrmIn As Form) As Long 添加窗体。
Dim FormControl As Control, i As Long
ReDim Preserve FormRecord(MaxForm + 1)
为数组增加一个新元素,记录当前窗体的信息。
With pfrmIn
FormRecord(MaxForm).Name = .Name
FormRecord(MaxForm).Top = .Top 获取并存储窗体的位置、大小等信息。
FormRecord(MaxForm).Left = .Left
FormRecord(MaxForm).Height = .Height
FormRecord(MaxForm).Width = .Width
FormRecord(MaxForm).ScaleHeight = .ScaleHeight
FormRecord(MaxForm).ScaleWidth = .ScaleWidth
End With 遍历窗体上的所有控件,调用AddControl来添加每一个控件。
For Each FormControl In pfrmIn
i = FindControl(FormControl, pfrmIn.Name) If i < 0 Then i = AddControl(FormControl, pfrmIn.Name)
Next FormControl
返回当前记录的索引号。
MaxForm = MaxForm + 1 增加窗体计数器。
AddForm = MaxForm
End Function
Function FindControl(inControl As Control, inName As String) As Long
Dim i As Long
FindControl = -1
For i = 0 To (MaxControl - 1)
If ControlRecord(i).Parrent = inName Then
If ControlRecord(i).Name = inControl.Name Then
On Error Resume Next 如果索引号匹配,则返回该控件的索引。
If ControlRecord(i).Index = inControl.Index Then
FindControl = i Exit Function End If
On Error GoTo 0
End If
Next i
End Function
Function AddControl(inControl As Control, inName As String) As Long 添加控件。
ReDim Preserve ControlRecord(MaxControl + 1)
With inControl
ControlRecord(MaxControl).Name = .Name 获取并存储控件的信息。
ControlRecord(MaxControl).Index = .Index
ControlRecord(MaxControl).Parrent = inName
If TypeOf inControl Is Line Then
If .X1 < 0 Then
ControlRecord(MaxControl).Left = (.Y2 * 75) + (inName * -75)
Else
ControlRecord(MaxControl).Left = .X1 处理Line控件。
End If
Else
ControlRecord(MaxControl).Top = .Top
ControlRecord(MaxControl).Left = ActualPos(.Left)
End With
返回当前记录的索引号。
MaxControl = MaxControl + 1
AddControl = MaxControl
End Function
Function PerWidth(pfrmIn As Form) As Long 计算宽度比例。
Dim i As Long
i = FindForm(pfrmIn)
If i < 0 Then
i = AddForm(pfrmIn) End If 如果找不到就添加。
PerWidth = (pfrmIn.ScaleWidth * 100