65.9K
CodeProject 正在变化。 阅读更多。
Home

VB.NET 简单自动重复按钮

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.64/5 (18投票s)

2003年10月24日

2分钟阅读

viewsIcon

110765

downloadIcon

1453

基于计时器间隔的 VB.NET 自动重复按钮

Sample Image - RepeatButton.jpg

引言

我希望在我的应用程序中使用一个简单的按钮来增加和减少音乐的音量。我希望在用户按住按钮时音量持续增加。我发现这并不简单,因为按钮的点击事件和 MouseButtons 属性都无法实现这一点。

我在互联网上搜索,找到了 C# 控件示例,用于自动重复按钮,但我没有找到任何 VB.NET 示例。因此,我决定创建一个 RepeatButton,它继承自按钮,并且可以在用户按住按钮时持续执行某些操作。

技术信息

该控件继承自 Button,并在其中包含一个 Timer。当用户点击按钮时(在 MouseDown 事件中),我们启动计时器,当他释放鼠标时(在 MouseUp 事件中),我们停止计时器。

计时器实际上是保持执行用户按住按钮时将要执行的函数的关键。项目中的任何计时器都可以与 RepeatButton 关联。 RepeatButton 还具有一个 Interval 属性,可以设置为与 RepeatButton 关联的计时器的间隔。例如

Dim cmdIncrease As New RepeatButton 'create new RepeatButton

cmdIncrease.Timer = TimerInc 
'Associate TimerInc to the Button 

'(supose timerInc is a Timer in the project)

cmdIncrease.Interval = 200  'Sets the interval for the timer

上面的代码将 RepeatButton cmdIncrease 设置为每 200 毫秒执行 TimerInc.Tick 函数,只要用户按住按钮。当用户释放按钮时,计时器停止(在 MouseUp 事件中)。

代码

RepeatButton 的代码是一个单独的类。它可以作为源代码下载。它实际上是一个 DLL,可以下载并执行,然后您可以将 RepeatButton 控件添加到您的应用程序,只需添加对该 DLL 的引用,或在设计模式下将其添加到您的工具箱即可。

还有一个完整的示例项目可以下载并执行。

这是 RepeatButton 类的代码

Public Class RepeatButton
               Inherits System.Windows.Forms.Button

     Public Sub New()
          AddHandler timer.Tick, AddressOf OnTimer
          timer.Enabled = False
     End Sub

     Public Timer As New timer
     Public Property Interval() As Integer
         Get
               Return timer.Interval
         End Get

         Set(ByVal Value As Integer)
               timer.Interval = Value
         End Set
    End Property

     Private Sub OnTimer(ByVal sender As Object, ByVal e As EventArgs)
          'fire off a click on each timer tick 

          OnClick(EventArgs.Empty)
     End Sub

     Private Sub RepeatButton_MouseDown(ByVal sender As Object, ByVal e As  _
     System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
          'turn on the timer 

          timer.Enabled = True
     End Sub

     Private Sub RepeatButton_MouseUp(ByVal sender As Object, ByVal e As _
     System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
          ' turn off the timer 

          timer.Enabled = False
     End Sub

End Class

结论

我希望您觉得这段代码有用。它非常易于使用。

© . All rights reserved.