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.
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 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
cmdIncrease.Timer = TimerInc
cmdIncrease.Interval = 200
The code above sets the
cmdIncrease to execute the
TimerInc.Tick function every 200ms while the user holds the button. When user leaves the button, the timer stops (at
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
Public Class RepeatButton
Public Sub New()
AddHandler timer.Tick, AddressOf OnTimer
timer.Enabled = False
Public Timer As New timer
Public Property Interval() As Integer
Set(ByVal Value As Integer)
timer.Interval = Value
Private Sub OnTimer(ByVal sender As Object, ByVal e As EventArgs)
Private Sub RepeatButton_MouseDown(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
timer.Enabled = True
Private Sub RepeatButton_MouseUp(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp
timer.Enabled = False
I hope you find this code useful. It's very easy to use.