[SOLVED] CreateGraphics() disappears when form is resized

Hey guys,
I am currently working on a project of mine and just noticed that my panel loses it's graphics when the window is resized.
So I've got my mouse_move code:

        private void canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && startDraw)
            {
                pList.Add(e.Location);
                paint();
            }

        }

and then my paint void:

        private void paint()
        {
            Graphics g = canvas.CreateGraphics();
            using (Pen p = new Pen(Color.Black, 1)) //brushcolour&size

            {
                p.StartCap = LineCap.Round;
                p.EndCap = LineCap.Round;
                p.LineJoin = LineJoin.Round;
                g.DrawCurve(p, pList.ToArray());
            }

        }

I suspect this may have to do with the panel refreshing every time the form moves/is transformed.
Any help would be amazing hahaha. Thankssss

A post by brwck

Like 0 Dislike

Hiya @brwck,

Normally, in C# (WinForms specifically) you have to override the "OnPaint" function to do any graphical work, like this (assuming that the "Paint" function you're referencing is for your Form, and not the Panel):

protected override void OnPaint(PaintEventArgs e) {
  base.OnPaint(e);
  Graphics g = canvas.CreateGraphics();
  using (Pen p = new Pen(Color.Black, 1)) { //brushcolour&size
    p.StartCap = LineCap.Round;
    p.EndCap = LineCap.Round;
    p.LineJoin = LineJoin.Round;
    g.DrawCurve(p, pList.ToArray());
  }
}

Relevant .NET docs for reference: https://docs.microsoft.com/en-us/dotnet … trol.paint & https://docs.microsoft.com/en-us/dotnet … int-method

Hope this helps! 1f609

Like +1 Dislike