Search code examples
c#winformsgdi

Draw ellipse form runtime


I tried to draw a ellipse form at runtime. I set the TransparentKey as same as backColor and the Form borderStyle to none. However it did not work form me. When i run the below code I am not getting the ellipse. I am not sure what missed over here.

public Form1()
{
    InitializeComponent();
    Graphics graphicsObj = this.CreateGraphics();
    SolidBrush sBrush=new SolidBrush(Color.Orange);
    graphicsObj.FillEllipse(sBrush, 30, 30, 60, 30);
    sBrush.Dispose();
    graphicsObj.Dispose();
}

Solution

  • Drawing in WinForms doesn't work like this, at best you'll see it once but when the Paint event re-triggers it'll get removed.
    What you can do is draw your ellipse in the Paint event:

    private void OnPaint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        SolidBrush sBrush=new SolidBrush(Color.Orange);
        graphicsObj.FillEllipse(sBrush, 30, 30, 60, 30);
        sBrush.Dispose();
    }
    

    Edit:

    You can find the OnPaint event on your Form (Events tab) or you could just subscribe to it from your constructor:
    this.Paint += OnPaint;