Search code examples
c#graphicsdoublebuffered

Double buffering doesn't work on a panel?


I'm working on a small painting program similar to ms paint. At the moment, I'm trying to implement 'select function'. I'm facing flickering problem so I've did some researches and I found out, that I should create my own Panel class.

public class MyDisplay : Panel
    {   
        public MyDisplay()
        {
            this.DoubleBuffered = true;            

            this.SetStyle(ControlStyles.UserPaint |
              ControlStyles.AllPaintingInWmPaint |
              ControlStyles.ResizeRedraw |
              ControlStyles.ContainerControl |
              ControlStyles.OptimizedDoubleBuffer |
              ControlStyles.SupportsTransparentBackColor
              , true);

            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.UpdateStyles();
        }
    }

In main form there are fields:

MyDisplay panel1 = new MyDisplay();
Graphics graphics1 = panel1.CreateGraphics();

I use 3 events on a panel:

  1. MouseDown - I get here Point p1
  2. MouseMove - thats, where I get flickering problem, I'm calling graphics1.drawRectangle(...) and graphics1.Clear() everytime clicked mouse moves
  3. MouseUp - I just draw rectangle for the last time.

What's wrong with that? Why do I still face flickering problem even though whole panel is white and theres only 1 rectangle in there? Thank you.

edit:

I've overwrote OnPaint method but I still don't know what to do next.

   protected override void OnPaint(PaintEventArgs e)
    {
        // Call the OnPaint method of the base class.
        base.OnPaint(e);
        // Call methods of the System.Drawing.Graphics object.
        e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle);
    } 

edit2: Should I paint on bitmap/image and override OnPaint method to copy image from there and paste it to panel?


Solution

  • Delete the line defining the graphics1 field.

    Perform ALL painting in the override of OnPaint, using the Graphics object passed in with the PaintEventArgs object. Use the methods Invalidate(), Refresh(), and Update() to control the timing of repainting from other code.

    Callback if you encounter any specific difficulties with this design.