Search code examples
c#winformsbuttoncolors

Adding a circular button to a Windows Form


I have created a circular button in a Windows Form. The button is fine. Only problem is that I want it to be a different color to the background so i set the BackColor to goldenRod. However, it simply creates a "goldenRod" cube around the circular button...how do i make it so that only the button is colored?

public MainForm(){

    InitializeComponent();      
    myButtonObject start = new myButtonObject();
    EventHandler myHandler = new EventHandler(start_Click);
    start.Click += myHandler;
    start.Location = new System.Drawing.Point(5, 5);
    start.Size = new System.Drawing.Size(101, 101);
    start.BackColor=System.Drawing.Color.Goldenrod;
    this.Controls.Add(start);
`}

void start_Click(Object sender, System.EventArgs e)
{
    MessageBox.Show("Start");
}

public class myButtonObject : UserControl
{
    // Draw the new button. 
    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics graphics = e.Graphics;
        Pen myPen = new Pen(Color.Black);
        // Draw the button in the form of a circle
        graphics.DrawEllipse(myPen, 0, 0, 100, 100);
        myPen.Dispose();
    }
}

Solution

  • You need to fill the Ellipse you are drawing during the OnPaint() method.

    graphics.FillEllipse(Brushes.Goldenrod, new Rectangle(0,0,100,100));
    graphics.DrawEllipse(myPen, 0, 0, 100, 100);
    

    Then make sure to remove the start.BackColor property from your MainForm() constructor.