
程序代码:
Option Explicit
Private Const 间距 = 64
Private Const 删除框右边距 = 32
Private Const 按钮左边距 = 64
Dim x1 As Single, y1 As Single
Dim piccount As Long '按钮最大index,省略每次都去查找
Dim picwidth As Long '按钮宽度,包含了间距在内
Dim gbleft As Long '删除框与对应按钮的左边距
Private Sub Command2_Click()
Dim i As Long
i = (pic.Count - 3) * picwidth '计算最小值
If x1 > -i Then '大于最小值
x1 = x1 - picwidth '左移
Call MovePic '显示移动后的效果
End If
End Sub
Private Sub Command3_Click()
If x1 < 按钮左边距 Then '可以右移
x1 = x1 + picwidth '右移
Call MovePic '显示
End If
End Sub
Private Sub Form_Load()
'----------初始化控件位置-------------
pic(0).Left = -pic(0).Width '这个不显示,不处理就是了
gb(0).Left = -gb(0).Width '这二个都是移出窗体就行了,只会复制 top 属性
Command1.Left = 按钮左边距
'----------初始化全局变量---------------
x1 = 按钮左边距
picwidth = pic(0).Width + 间距 '按钮宽
gbleft = pic(0).Width - gb(0).Width - 删除框右边距 '计算删除框在按钮的左边位置
piccount = 0
End Sub
'添加按钮
Private Sub Command1_Click()
Call AddPic '添加按钮
Call MovePic '位置
If Command1.Left + Command1.Width > Me.Width Then '如果添加按钮超出窗体,则调用一次向左移
Call Command2_Click
End If
'Command1.Move pic(pic.UBound).Left + pic(pic.UBound).Width + 128 '本行移动到 movepic 中处理
End Sub
'添加Picture
Sub AddPic()
Dim ii As Integer
piccount = piccount + 1 'index计数加1
Load pic(piccount) '载入
pic(piccount).Visible = True '显示
pic(piccount).Caption = "按钮" & piccount '为了显示明显而增加的
'gb 的下标与 pic 的下标对应,直接使用就可以了
Load gb(piccount) '载入
gb(piccount).Visible = True '显示
gb(piccount).ZOrder
End Sub
'移动Picture
Sub MovePic()
Dim pp As CommandButton '变量 类型 为这个控件的类型
Dim i As Long, j As Long, m As Long
i = x1
m = 0
For Each pp In pic '遍类所有的控件
If pp.Index > 0 Then '0号不处理 ,如果需要再指定某个值不处理,在这个条件中再加
j = i + m * picwidth '重新定位
If j >= 按钮左边距 Then '新的位置是否在允许显示的范围
pp.Left = j '新的位置
gb(pp.Index).Left = j + gbleft
pp.Visible = True '显示
gb(pp.Index).Visible = True
Else
pp.Visible = False '否则不显示,
gb(pp.Index).Visible = False
End If
m = m + 1 '计数
End If
Next pp
Command1.Left = i + picwidth * m '添加按钮 的位置
End Sub
'删除Picture
Private Sub gb_Click(Index As Integer)
If Index <> 0 Then '不删除0号
Unload pic(Index) '删除控件
Unload gb(Index) '删除控件
Call MovePic '删除后,重新定位
End If
If Command1.Left = 按钮左边距 Then '如果删除后,没有显示一个按钮,
Call Command3_Click '那么自动向右移一个
End If
If Index = piccount Then '如果是删除最后的按钮,需要重新计算最大值
Dim pp As CommandButton
piccount = 0
For Each pp In pic
If piccount < pp.Index Then
piccount = pp.Index
End If
Next
End If
End Sub