1.新建一個工程,窗體Form1為缺省窗體,Form1的屬性項Caption=″動態增減控件的例子″。
2.加入兩個命令按鈕(CommandButton),其中:
Command1的屬性項Caption=″增加控件″;
Command2的屬性項Caption=″刪除控件″。
3.加入如下代碼,運行該工程,單擊″增加控件″則出現新增按鈕。若單擊″新增按鈕″時會出現對話框,表明你觸發的是動態增加控件的單擊事件。
Option Explicit
′通過使用WithEvents關鍵字聲明一個對象變量為新的命令按鈕
Private WithEvents NewButton As CommandButton
′增加控件
Private Sub Command1_Click()
If NewButton Is Nothing Then
′增加新的按鈕cmdNew
Set NewButton =Controls.Add(″VB.CommandButton″,″cmdNew″, Me)
′確定新增按鈕cmdNew的位置
NewButton.Move Command1.Left+Command1.Width+240, Command1.Top
NewButton.Caption =″新增的按鈕″
NewButton.Visible = True
End If
End Sub
′刪除控件(注:只能刪除動態增加的控件)
Private Sub Command2_Click()
If NewButton Is Nothing Then
Else
Controls.Remove NewButton
Set NewButton = Nothing
End If
End Sub
′新增控件的單擊事件
Private Sub NewButton_Click()
MsgBox″您選中的是動態增加的按鈕!″
End Sub
注意:如果你希望添加一個用戶控件或任何ActiveX控件到您的窗體,必須把這個控件添加到“工具箱”,或者把控件的License關鍵字添加到Licenses集合中。而且,你不能選定“工程屬性”對話框的“生成”選項卡上的“刪除有關未使用的ActiveX控件”選項,否則controls.Add方法將失敗,因為必需的信息已經被丟失。
延伸閱讀
文章來源于領測軟件測試網 http://www.kjueaiud.com/