Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to get drawing on C# Form working, but after reading documentation about Graphics class and Draw/Fill methods It still doesn't work for me.

It's the code:

using System.Drawing;
using System.Windows.Forms;

namespace Drawing_Example
{
    public partial class Form1 : Form
    {
        #region Constructors

        public Form1()
        {
            InitializeComponent();

            Pen pen = new Pen(Color.Black, 3f);
            Graphics surface = CreateGraphics();
            surface.DrawEllipse(pen, new Rectangle(0, 0, 200, 300));

            pen.Dispose();
            surface.Dispose();
        }

        #endregion Constructors
    }
}

When I press Start an empty form appears, no drawings. Can you tell me what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
327 views
Welcome To Ask or Share your Answers For Others

1 Answer

You cannot do the drawing in the constructor because the OnPaint() method will overwrite it all when it's called by the framework later.

Instead, override the OnPaint() method and do your drawing there.

Do NOT create your own Graphics object using CreateGraphics(); instead, use the one passed to OnPaint() via e.Graphics as per the example I linked.

(Also, don't dispose e.Graphics when you're done with it - the framework manages that for you.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...