C# Learning Graphics: Can someone explain what is wrong with this code?

jBallou 0 Reputation points
2025-03-24T23:10:38.8966667+00:00

I'm working on a graphics program and the structure of my program is not working. I'm thinking that an answer to the question of why my code doesn't work will help me understand what is wrong with my program.

Here is some code - why is an ellipse not being drawn on my form? I am not getting any error messages from VS.

Net 9.0, VS 2022 (so basic name spaces are automatically added.)

Thanks!

namespace Testing

{

public partial class Form1 : Form

{

    private Graphics g;

    public Form1()

    {

        InitializeComponent();

        g = this.CreateGraphics();

        Draw();

    }

    private void Draw()

    {

        Pen pen = new Pen(Color.Red, 3);

        g.DrawEllipse(pen, 50, 50, 100, 100);

    }

}

}

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,404 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Marcin Policht 44,090 Reputation points MVP
    2025-03-24T23:46:44.0466667+00:00

    As far as I can tell, the issue with your program is that you are calling CreateGraphics() and drawing in the constructor (Form1()). This might be problematic because the form is not yet fully initialized and displayed when Draw() is called. Additionally, anything drawn using CreateGraphics() will not persist if the form is refreshed (e.g., minimized and restored) because the drawing is not being done inside the OnPaint event.

    You might want to try overriding the OnPaint method to ensure that the ellipse is drawn correctly and persists when the form is redrawn.

    namespace Testing
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            protected override void OnPaint(PaintEventArgs e)
            {
                base.OnPaint(e);
                
                using (Pen pen = new Pen(Color.Red, 3))
                {
                    e.Graphics.DrawEllipse(pen, 50, 50, 100, 100);
                }
            }
        }
    }
    

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.