所以我试图让我的表单适合所有显示器。有些具有不同的显示分辨率和比例。
我可以调整表单大小以适应显示屏,但其内容的所有属性不会调整为新大小。
我想要的是,如果缩放表单以适合显示,则表单上的控件也应该调整。具体来说,每个控件上都有诸如 Left
、Top
、Width
、Height
等属性。
尺寸可以缩小或放大。
最佳答案
可以(大部分)以编程方式迭代表单上的所有控件,而不必显式调整每个控件。您可能必须为某些类型的控件(例如我在示例中放入的计时器)添加一些异常(exception),但通常您可以使用如下内容:
Option Explicit
Private Type ControlInfo_type
Left As Single
Top As Single
Width As Single
Height As Single
FontSize As Single
End Type
Dim ControlInfos() As ControlInfo_type
Private Sub Form_Load()
Dim ThisControl As Control
ReDim Preserve ControlInfos(0 To 0)
ControlInfos(0).Width = Me.Width
ControlInfos(0).Height = Me.Height
For Each ThisControl In Me.Controls
ReDim Preserve ControlInfos(0 To UBound(ControlInfos) + 1)
On Error Resume Next ' hack to bypass controls with no size or position properties
With ControlInfos(UBound(ControlInfos))
.Left = ThisControl.Left
.Top = ThisControl.Top
.Width = ThisControl.Width
.Height = ThisControl.Height
.FontSize = ThisControl.FontSize
End With
On Error GoTo 0
Next
End Sub
Private Sub Form_Resize()
Dim ThisControl As Control, HorizRatio As Single, VertRatio As Single, Iter As Integer
If Me.WindowState = vbMinimized Then Exit Sub
HorizRatio = Me.Width / ControlInfos(0).Width
VertRatio = Me.Height / ControlInfos(0).Height
Iter = 0
For Each ThisControl In Me.Controls
Iter = Iter + 1
On Error Resume Next ' hack to bypass controls
With ThisControl
.Left = ControlInfos(Iter).Left * HorizRatio
.Top = ControlInfos(Iter).Top * VertRatio
.Width = ControlInfos(Iter).Width * HorizRatio
.Height = ControlInfos(Iter).Height * VertRatio
.FontSize = ControlInfos(Iter).FontSize * HorizRatio
End With
On Error GoTo 0
Next
End Sub
我使用带有 CommandButton、Frame、Timer 和 TextBox 的默认表单对此进行了测试,它似乎工作正常。您可能需要调整外观的最小和最大尺寸的限制,而我对字体的处理非常粗糙;这也可以优化。但也许这可能是一个起点。
此代码取决于每次以相同方式迭代的控件,这可能会中断。解决这个问题的一种方法是使用集合或其他数据结构,并将控件的名称作为键;在 .Resize 事件中迭代时,将按名称查找每个控件。如果任何控件本身就是数组,则需要额外的结构,如果动态加载或卸载控件,则需要更多结构。
关于vb6 - 调整窗体大小时如何自动调整窗体上的控件大小或重新定位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70758773/