Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I make a Button trigger a Click event at specific time intervals while the mouse is down like a ScrollBar button?

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 the timer
        timer1 = new Timer();
        timer1.Tick += new EventHandler( OnTimer );
        timer1.Enabled = false;
      }
      return timer1;
    }
  }

  protected override void OnMouseDown( MouseEventArgs me )
  {
    base.OnMouseDown( me );
    Timer.Enabled = true; // turn on the timer
  }

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

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

Shawn Burke, Microsoft