How can I draw a panel so that it does not blink?

This is my code. When I move the cursor over the Form, it works, the circle moves, but it blinks. How can i fix this?

public partial class Preprocesor : Form
{
    int x, y;
    Graphics g;

    public Preprocesor()
    {
        InitializeComponent();
    }

    private void Preprocesor_Load(object sender, EventArgs e)
    {
        g = pnlMesh.CreateGraphics();
    }

    private void pnlMesh_Paint(object sender, PaintEventArgs e)
    {
        g.Clear(Color.White);
        g.FillEllipse(Brushes.Black, x, y, 10, 10);
    }

    private void pnlMesh_MouseMove(object sender, MouseEventArgs e)
    {
        x = e.X;
        y = e.Y;
        pnlMesh.Invalidate();
    }
}
+3
source share
2 answers

You need to use a double buffer.

Create a class that inherits Controland sets DoubleBuffered = true;in the constructor (this is a protected property).
Use this control instead of your panel, there will not be any flicker.

In addition, you should not store the object Graphicsfor future use.
Instead, you should draw e.Graphicsin the handler Paint.

+5
source

Doublebuffered true?

public partial class BufferPanel : Panel
{
    public BufferPanel()
    {
        SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        UpdateStyles();
    }
}
+4

Source: https://habr.com/ru/post/1787346/


All Articles