具有特殊效果的 ToolBar 控件






3.71/5 (16投票s)
2003年11月4日
3分钟阅读

126245

801
带有特殊效果的工具栏控件,继承自 .NET ToolBar 控件。
引言
ToolBarEx
控件实际上是 .NET 框架提供的 ToolBar
控件,但可以为选定的按钮添加效果。其想法是在选定的按钮上实现特殊效果,就像在 Internet Explorer 或 Visual Studio 中一样。
我创建了 10 种不同的效果来应用于 ToolBarEx
,但稍加努力就可以创建更多效果。
代码
这里我不打算展示该类的所有代码,因为它会占用大量空间。但可以在源代码下载中找到。代码的思想非常简单:ToolBarEx
继承自 Toolbar
并具有其所有功能。我只添加了一个新属性,即 effect
。我还处理了 MouseHover
、MouseMove
和 MouseLeave
事件。当鼠标指针移动到工具栏上时,子程序会根据鼠标位置计算出鼠标位于哪个按钮上方,然后对该按钮应用效果,当鼠标在工具栏上移动时也会执行相同的操作。
Private Sub ToolBarEx_MouseHover(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.MouseHover
'btnindex is the index of the button that the mouse is over
'It is calculated using the mouse position
'didtance from mousepointer to the left of toolbar / button size
Dim btnIndex As Integer = _
Int((Me.MousePosition.X - Me.Parent.Left) / (Me.Buttons(0).Rectangle.Width))
'If button selected is between 0 and last button and is
'differentthan the last button selected
.
.
.
End Sub
当鼠标离开工具栏时,我们会恢复按钮未被选中时的图像。为了恢复此图像,该类有一个 Image
(lastImage
) 和一个 Button
(LastButton
),用于保存哪个按钮是最后选中的,以及它未被选中时应该显示的图像。
Private Sub ToolBarEx_MouseLeave(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.MouseLeave
'When mouse leaves the bar
'display the original image on selected button
If Not (m_LastImage Is Nothing) Then
If Effect = Effect.TwoIconsButton And _
Me.Buttons(m_LastButton).ImageIndex > 0 Then
Me.Buttons(m_LastButton).ImageIndex -= 1
Else
Me.ImageList.Images(Me.Buttons(m_LastButton).ImageIndex) _
= m_LastImage
End If
m_LastImage = Nothing
Me.Refresh()
m_LastButton = -1
End If
End Sub
某些效果使用辅助结构,例如另一个 ImageList
,以便在显示的图像为黑白时存储原始图像。这个辅助 ImageList
在 InitLayout
事件中加载。
效果
大多数效果都是通过类中的 createEffect
函数创建的。此函数实际上获取位图,然后逐像素应用我们想要的样式。只有 twoIconsButton
效果没有逐像素效果,因为它使用了 2 个不同的图标。
正如开头所描述的,ToolBarEx
有 10 种不同的效果,它们是
BwToColor
– 黑白到彩色效果此效果使工具栏上的所有按钮都为黑白,除了选中的按钮。
ColorToBw
– 彩色到黑白效果此效果与上一个相反。它使选定的按钮变为黑白色。
BlueSelection
– 蓝色选择效果为选定的按钮提供蓝色遮罩。
Shadow
– 阴影效果选定的图标看起来像它自己的阴影。
Antique
– 古董效果有点像旧电影效果。
Mosaic
– 马赛克效果使选定的图标看起来略有不同。
LightsOff
– 关灯效果选定的图标看起来很暗。
RedHot
– 炙热效果选定的按钮变得比其他按钮更热。
GuessWhat
– 猜猜是什么效果将选定的图标隐藏在蓝色形状中。
TwoIconsButton
– 双图标按钮效果此效果允许用户为同一个按钮选择 2 个不同的图标。一个是在按钮被选中时,另一个是在未选中时。对于第一张图片,0 是未选中,1 是选中,2 是第二个按钮的未选中,3 是第二个按钮的选中,以此类推...
注意:要使用此效果,您必须确保
ImageList
上的图标多于工具栏上的按钮。
使用控件
使用此控件非常简单。就像任何其他 .NET 控件一样,您只需将其添加到工具箱中,方法是右键单击工具栏选项卡。然后将工具栏放置在您希望的位置,并像常规工具栏一样设置属性。
唯一的区别是 ToolBarEx
具有 effect
属性,可以在视觉上或通过代码进行更改。
我希望此控件对您有所帮助,并帮助您了解更多关于 .NET 中控件的各种可能性。