Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

25. Windows Forms Button

25.5 How can I get button to fire a click event at specific time intervals while the mouse is down like a scrollbar button?


Shawn Burke posted the following solution on the microsoft.public.dotnet.framework.windowsforms newsgroup.

public class RepeatButton : Button
{
     private Timer timer1;

     public int Interval
     {
          get
          {
               return Timer.Interval;
          }
          set
          {
               Timer.Interval = value;
          }
     }

     private Timer Timer
     {
          get
          {
               if (timer1 == null)
               {
               // create and setup our timer.
                     timer1 = new Timer();
               timer1.Tick += new EventHandler(OnTimer);
               timer1.Enabled = false;
               }
               return timer1;
          }
     }

     protected override void OnMouseDown(MouseEventArgs me)
     {
          base.OnMouseDown(me);

          // turn on the timer
          Timer.Enabled = true;
     }

     protected override void OnMouseUp(MouseEventArgs me)
     {
          // turn off the timer
          Timer.Enabled = false;
          base.OnMouseUp(me);
     }

     private void OnTimer(object sender, EventArgs e)
     {
          // fire off a click on each timer tick
           //
           OnClick(EventArgs.Empty);
      }
}