A Simple Auto Repeat Button on VB.NET






2.64/5 (18 votes)
Oct 24, 2003
2 min read

109951

1453
Auto repeat button in VB.NET based on timer interval
Introduction
I wanted to use in my application a simple button to increase and decrease the volume of the music. I wanted the volume to keep increasing while the user holds the button. I found out that it is not so simple, since both the click event of the button and the MouseButtons
property can't do that.
I searched the Internet and I found C# control samples for a Auto Repeat Button, but I didn't find any VB.NET examples. So I decided to create a RepeatButton
that inherits from button and can keep doing something while the user holds the button.
Technical information
The control inherits from Button
and has a Timer
in it. When user clicks on the button (on the MouseDown
event) we start the timer and when he leaves the mouse (on MouseUp
event) we stop the timer.
The timer is actually what keeps the function that is going to executed while user holds the button. Any timer in the project can be associated to the RepeatButton
. The RepeatButton
has also an Interval
property which can be set to be the interval of the timer associated to the RepeatButton
. For example:
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
The code above sets the RepeatButton
cmdIncrease
to execute the TimerInc.Tick
function every 200ms while the user holds the button. When user leaves the button, the timer stops (at MouseUp
event).
Code
The code for the RepeatButton
is a single class. It can be downloaded as the source. It is actually a DLL that can be downloaded and executed and then you can add the RepeatButton
control to your application simply by adding a reference to this DLL or adding it to your toolbox in design mode.
There is also a complete sample project that can be downloaded and executed.
This is the code for the RepeatButton
class:
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
Conclusion
I hope you find this code useful. It's very easy to use.