How can I draw on Panel so it does not blink?

2019-02-25 00:17发布

This is my code. When I move cursor over Form it works, circle is moving but it is blinking. 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();
    }
}

2条回答
等我变得足够好
2楼-- · 2019-02-25 00:49

How bout overriding a panel user control and set Doublebuffered to true?

public partial class BufferPanel : Panel
{
    public BufferPanel()
    {
        SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        UpdateStyles();
    }
}
查看更多
祖国的老花朵
3楼-- · 2019-02-25 00:54

You need to draw on a double-buffered control.

Make a class that inherits Control and sets DoubleBuffered = true; in the constructor (this is a protected property).
Use that control instead of your panel it there won't be any flickering.

Also, you should not store a Graphics object for later.
Instead, you should draw on e.Graphics in the Paint handler.

查看更多
登录 后发表回答