VB动态添加控件并对其进行拖放操作改变位置
用Controls.Add添加控件
Dim WithEvents mypic As PictureBox
Private Sub Command1_Click()
Set mypic = Controls.Add("VB.PictureBox", "mypic")
mypic.Left = 50
mypic.Top = 50
mypic.Visible = True
End Sub
至于拖放操作,在程序中设置好mypic控件的有关属性后,处理mypic的有关事件即可
注意:
如果是控件数组的话,建议采用:load 控件数组名(索引) 的方法添加控件
'可先手工画一个控件,Visable设置为False,Index设置为0
'若需要多个就用load object(index)来加载,并把它们的visable设置为true;不需要多个就真接把原有的那个的visable设成显示就行了。
Private Declare Function ReleaseCapture Lib "user32" () As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" ( _
ByVal hwnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, lParam As Any) As Long
Private Sub Command1_MouseDown(Index As Integer, Button As Integer, _
Shift As Integer, X As Single, Y As Single)
If Button = 1 Then
ReleaseCapture '移动控件
SendMessage Command1(Index).hwnd, &HA1, 2, 0&
End If
End Sub
Private Sub Form_Click()
On Error GoTo endsub
For i = 1 To 5
Load Command1(i) '生成控件
Command1(i).Top = Command1(i - 1).Top
Command1(i).Left = Command1(i - 1).Left + Command1(i - 1).Width Command1(i).Visible = True
Next
Exit Sub
End Sub
‘例如:添加一个commandbutton
Private Sub Form_Load()
With Form1!cmdOk
.Visible = True
.Width = 500
.Caption = "确认(&Y)"
End With
End Sub
‘删除控件。