|
|
ActivityBar 控件
最后,我们来创建显示动画点的 ActivityBar 控件。
在名为 ActivityBar 的项目中添加一个用户控件。
将该控件的宽度调整为约 110,高度调整为约 20。可以通过拖动边界进行调整,也可以通过在 Properties(属性)窗口中设置 Size 属性进行调整。
其余的操作将通过代码完成。要创建一系列在显示时不停闪烁的动画“灯”,可以使用带有 Timer 控件的一系列 PictureBox 控件。每次 Timer 控件关闭时,我们将使下一个 PictureBox 呈绿色显示,并将已经呈绿色显示的 PictureBox 更改为窗体的背景色。
将 Windows Forms(Windows 窗体)选项卡中的 Timer 控件放入窗体中,然后将其名称更改为 tmAnim。同时将 Interval 属性设置为 300,以获得较好的动画速度。
顺便说一句,Components(组件)选项卡中有一个不同的 Timer 控件。它是一个多线程计时器。也就是说,该计时器将在后台线程中引发 Elapsed 事件,而不是象 Windows 窗体计时器那样在 UI 线程上引发 Elapsed 事件。建立 UI 时这种方法通常会产生相反的效果,因为 Elapsed 事件中的代码显然不能直接与我们的 UI 进行交互。
现在,在控件中添加以下代码:
Private mBoxes As New ArrayList()
Private mCount As Integer
Private Sub ActivityBar_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim index As Integer
If mBoxes.Count = 0 Then
For index = 0 To 6
mBoxes.Add(CreateBox(index))
Next
End If
mCount = 0
End Sub
Private Function CreateBox(ByVal index As Integer) As PictureBox
Dim box As New PictureBox()
With box
SetPosition(box, index)
.BorderStyle = BorderStyle.Fixed3D
.Parent = Me
.Visible = True
End With
Return box
End Function
Private Sub GrayDisplay()
Dim index As Integer
For index = 0 To 6
CType(mBoxes(index), PictureBox).BackColor = Me.BackColor
Next
End Sub
Private Sub SetPosition(ByVal Box As PictureBox, ByVal Index As Integer)
Dim left As Integer = CInt(Me.Width / 2 - 7 * 14 / 2)
Dim top As Integer = CInt(Me.Height / 2 - 5)
With Box
.Height = 10
.Width = 10
.Top = top
.Left = left + Index * 14
End With
End Sub
Private Sub tmAnim_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles tmAnim.Tick
CType(mBoxes((mCount + 1) Mod 7), PictureBox).BackColor = _
Color.LightGreen
CType(mBoxes(mCount Mod 7), PictureBox).BackColor = Me.BackColor
mCount += 1
If mCount > 6 Then mCount = 0
End Sub
Public Sub Start()
CType(mBoxes(0), PictureBox).BackColor = Color.LightGreen
tmAnim.Enabled = True
End Sub
Public Sub [Stop]()
tmAnim.Enabled = False
GrayDisplay()
End Sub
Private Sub ActivityBar_Resize(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Resize
Dim index As Integer
For index = 0 To mBoxes.Count - 1
SetPosition(CType(mBoxes(index), PictureBox), index)
Next
End Sub
窗体的 Load 事件创建 PictureBox 控件并将它们放入数组,这样便于我们在它们之间循环。Timer 控件的 Tick 事件循环显示,使各个控件依次呈绿色。
所有操作由 Start 方法开始,由 Stop 事件结束。由于 Stop 是一个保留字,因此把这个方法名放在方括号内:[Stop]。Stop 方法不仅可以停止计时器,还可以灰显所有框,告诉用户这些框中当前没有活动。 |
|