Make System.Windows.Forms.Button into a RepeatButton

Recently, I was trying to get caught up on my blog reading and read Scott Hanselman’s blog post about SyntaxHighlighter. Well, this encouraged me to install Windows Live Writer and try this plugin out. (I was always bothered that I had to create pngs with my code snippets in them for my blog post on name scopes in WPF.)

Well, I quickly found out that a blog at www.wordpress.com can not use plugins. Argh. So, I finally broke down, decided to register a domain, and installed WordPress to it.

So, this post is really a test of whether I have correctly set up Alex Gorbatchev’s SyntaxHighlighter, but I thought I would go ahead and post something interesting as well. So, without further adieu:

Recently, I thought … “I love WPF’s RepeatButton. How can I make the System.Windows.Forms.Button into a RepeatButton?”

So here is some code to do that:

public class RepeatButton : System.Windows.Forms.Button
{
    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);

        if (e.Button == MouseButtons.Left)
        {
            OnClick(EventArgs.Empty);
            RepeatButton.repeatButtonTimer.Tick += new EventHandler(repeatButtonTimer_Tick);
            repeatButtonTimer.Start();
        }
    }
    protected override void OnMouseUp(MouseEventArgs e)
    {
        this.mousingUp = true;

        base.OnMouseUp(e);

        if (e.Button == MouseButtons.Left)
        {
            repeatButtonTimer.Stop();
            RepeatButton.repeatButtonTimer.Tick -= new EventHandler(repeatButtonTimer_Tick);
        }

        this.mousingUp = false;
    }

    protected override void OnClick(EventArgs e)
    {
        if (this.mousingUp) return;

        base.OnClick(e);
    }

    private void repeatButtonTimer_Tick(object sender, EventArgs e)
    {
        OnClick(EventArgs.Empty);
    }

    private bool mousingUp = false;

    static RepeatButton()
    {
        repeatButtonTimer.Interval = 250;
    }
    private static System.Windows.Forms.Timer repeatButtonTimer = new Timer();
}

4 thoughts on “Make System.Windows.Forms.Button into a RepeatButton”

  1. Great code, thanks a lot.

    I just slightly modified repeatButtonTimer_Tick as follows:

        private void repeatButtonTimer_Tick(object sender, EventArgs e)
        {
          if (base.Enabled)
            base.OnClick(EventArgs.Empty);
          else
          {
            repeatButtonTimer.Stop();
            RepeatButton.repeatButtonTimer.Tick -= 
                new EventHandler(repeatButtonTimer_Tick);
          }
        }
    

    Without that, the button keeps repeating the click event … even if it is disabled (in my case, when reaching the first or last row of a grid that I am scrolling through).

Leave a Reply