Vb中控件的自動排列

字號:

Vb作為一種流行的可視化編程語言,其強大的界面設計功能為程序設計者省了不少時間。不過在面對大量相同控件的整齊排列時,雖可在設計時排列好,但難免在調試中不小心移動,或后來又增減一些。于是有人用語句在程序中調節(jié),其艱辛是可想而知的(筆者深有體會),即使位置排好了,由于控件添加的先后問題,其索引屬性(.TabIndex)往往一片混亂.能不能讓控件的位置、索引屬性的排序實現(xiàn)自動化呢?經過一番思索,筆者終于找到了很好的解決辦法,并成功應用于自己開發(fā)的注冊表修改器中。
    例子:新建工程,放入一個Frame控件Frame1,再在Frame1 中放入4個復選框checkbox1、checkbox2、checkbox3、checkbox4
    在form_load()子過程中加入一句:ArrangeChildren frame1 運行結果為4個復選框等間距整齊地排列在其容器frame1 中。在設計窗口中,你可以任意調整它們的上下位置,運行后將按它們設計時的上下順序整齊排列,并且它們的索引順序按由下到大排列。(索引順序的作用大家知道吧——讓你的程序支持鍵盤操作)。更妙的是,你可在容器中任意增加、減少控件數(shù)量(類型要一樣),運行后它們都能整齊排列,從而一勞永逸。
    以下是具體的子過程代碼
    Public Sub ArrangeChildren(Father As Control) ´Father為容器控件
    ´功能:
    (1)對容器控件內的子控件的TabIndex值進行排序
    ´排序依據是:由上到下(.Top值由小到大),TabIndex小到大
    (2)對容器控件內的子控件等間距整齊排列
     Dim Child As Control ´窗體中的任一控件
     Dim Children() As Control ´屬于容器中的控件數(shù)組
     Dim Tags() As Integer ´元素的值記錄了控件的TabIndex值
     Dim TempChild As Control ´臨時控件
     Dim i As Integer, j As Integer
     Dim x As Integer, Y As Integer
     Dim wChild As Integer, hChild As Integer
     Dim num As Integer
     Dim strTemp As String
     Const ADJUST as integer=150 ’微調(可適當增減)
    num = 0
     For Each Child In Father.Parent.Controls ‘搜索容器所在窗體中的每一個控件
     If TypeOf Child Is CheckBox Then ‘這個判斷是為了提高效率,可不要
     If Child.Container Is Father Then
     ReDim Preserve Children(num)
     ReDim Preserve Tags(num)
     Set Children(num) = Child
     Children(num).Tag = num
     Tags(num) = Children(num).TabIndex
     num = num + 1
     End If
     End If
     Next
     If num < 1 Then Exit Sub ‘當容器中一個子控件也沒有時,退出
     num = UBound(Children)
     SortProc Tags ‘將數(shù)組Tags()按由小到大順序排序
     ArrayTagProc Children ‘越在屏幕上面的控件,其<.top>值越小,故讓其<.tag>值也小
     For i = 0 To num
     Children(i).TabIndex = Tags(Children(i).Tag)
    Next i ‘越在屏幕上面的控件,其索引值?。▽崿F(xiàn)索引值的排序)
     ArrayTabIndexProc Children ´
     x = 200 ‘控件在其容器中的起始位置
     wChild = 4000 ‘控件寬度
     hChild = 255 ‘控件高度
     Y = (Father.Height - ADJUST - (num + 1) * hChild) / (num + 2)
     For j = 0 To num
     Children(j).Move x, (j + 1) * Y + j * hChild + ADJUST, wChild, hChild
     Next j
    End Sub