Live Chat Icon For mobile
Live Chat Icon

WinForms FAQ - Button

Find answers for the most frequently asked questions
Expand All Collapse All

Subclass Button and add a custom Paint event handler that does you custom drawing.

  public class MyButton : System.Windows.Forms.Button
  {
    public MyButton()
    {
      this.Paint += new System.Windows.Forms.PaintEventHandler(this.button1_Paint);
    }
    private void button1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
      //custom drawing
      Pen pen2 = new Pen(Color.Red);
      pen2.Width = 8;
      e.Graphics.DrawLine(pen2, 7, 4, 7, this.Height - 4);
      pen2.Width = 1;
      e.Graphics.DrawEllipse(pen2, this.Width - 16 , 6, 8, 8); 
    }
  }

Permalink

Get a Graphics object for the button and use its MeasureString method to compute the width you need.


Graphics g = button1.CreateGraphics();
float w = g.MeasureString(button1.Text, button1.Font).Width;
g.Dispose();
button1.Width = (int)w + 12; // 12 is for the margins 
Permalink

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);
   	 }
}
Permalink

You can use the Button.Image property to add an image to a button face. Use the Button.ImageAlign (and possibly Button.TextAlign) to layout your button face.

You can also implement custom drawing on a button face as described in the FAQ entitled ‘How can I decorate a button face with custom drawing’.

Permalink

Share with

Share on twitter
Share on facebook
Share on linkedin

Couldn't find the FAQs you're looking for?

Please submit your question and answer.