Vb中控件的自動(dòng)排列

字號(hào):

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