很多 Windows 程序使用的窗口都带有使用拆分器分隔的窗格。你可以拖动拆分器来扩大其中一个窗格同时缩小其它的窗格——而这个过程无须更改父窗口的大小。虽然 Visual Basic 6 不提供用于这一用途的控件,但是你可以自己实现这一效果。
创建窗格拆分器的方法是使用一个 Picture Box 控件作为其它控件的容器。在设计窗体时,放两个 Picture Box 控件到窗体上,每个代表一个窗格。例如,对于上部窗格和下部窗格,可以将它们叫做pbTop和pbBotton。然后,将其它控件放在每个窗格对应的 Picture Box 上。
在程序运行时,程序代码调整两个 Picture Box 控件(即两个窗格)的大小从而以预定义的尺寸填充窗口。Picture Box 控件的尺寸会被精确地计算,以使窗体在两个 Picture Box 之间显示一个窄带;这个窄带就作为拆分器。
将窗体的MousePointer属性设计为“7 - Size NS”,以使得在鼠标置于拆分器之上时光标形状变为调整上/下大小的样式。将每个 Picture Box 控件的MousePointer属性设置为“1 - Arrow”。程序还需要一些常量设置拆分器的高度和每个窗格允许的最小高度。
下面拆分器的工作方式:在用户开始拖到拆分器时,拆分器的新位置由鼠标光标的位置所决定。这由MouseMove事件过程实现。在MouseMove事件过程中首先一个叫做ChangePaneSizes的过程被调用;该过程使用新的拆分器位置相应地更改两个窗格的尺寸。任何一个窗格的尺寸都不能小于指定的最小尺寸。
下面的完成这一动作的代码。你可以创建一个 vb 程序亲自试一下这段代码,首先在窗体上放置两个 Picture Box 控件,分别命名为pbTop和pbBottom;然后,将这段代码粘贴到窗体的代码窗口中。这个例子展示的是一个水平拆分器分隔两个窗格,但是你可以对它进行修改,从而得到其它的窗格排列样式。
Option Explicit
Const SPLITTER_HEIGHT = 40
Const MIN_PANE_HEIGHT = 400
' The percentage of the window height
' occupied by the top pane.
Dim TopPanePercent As Single
' True when the splitter is being dragged.
Private Dragging As Boolean
Private Sub ChangePaneSizes()
' Arrange the panes according to the new splitter
position.
Dim TopHeight As Single
Dim BottomHeight As Single
' Do nothing if window is minimized.
If WindowState = vbMinimized Then Exit Sub
TopHeight = (ScaleHeight - SPLITTER_HEIGHT) *
TopPanePercent
If TopHeight < MIN_PANE_HEIGHT Then TopHeight =
MIN_PANE_HEIGHT
pbTop.Move 0, 0, ScaleWidth, TopHeight
BottomHeight = (ScaleHeight - SPLITTER_HEIGHT) -
TopHeight
If BottomHeight >= MIN_PANE_HEIGHT Then
pbBottom.Move 0, TopHeight +
SPLITTER_HEIGHT, ScaleWidth, BottomHeight
End If
End Sub
Private Sub Form_Load()
' Initially each pane gets half the window.
TopPanePercent = 0.5
End Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, _
Y As Single)
' Start dragging the splitter.
Dragging = True
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, _
Y As Single)
' As the splitter is dragged.
' Do nothing if we're not dragging.
If Not Dragging Then Exit Sub
TopPanePercent = Y / ScaleHeight
If TopPanePercent < 0 Then TopPanePercent = 0
If TopPanePercent > 1 Then TopPanePercent = 1
ChangePaneSizes
End Sub
Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, _
Y As Single)
' End dragging the splitter.
Dragging = False
End Sub
Private Sub Form_Resize()
' Change pane sizes if the window is resized.
ChangePaneSizes
End Sub