Disable OnPaintBackground without a subclass panel?

Can I disable panel erasure without subclassing Panel and override OnPaintBackground?

I am trying to achieve double buffering effect without subclassing Panel. I understand that this can be a strange thing, but at least I would like to know if I can or not. The following code example illustrates this:

public partial class Form1 : Form
{
    private Bitmap m_image;

    public Form1()
    {
        InitializeComponent();

        panel1.Paint += new PaintEventHandler(panel1_Paint);
        panel1.MouseMove += new MouseEventHandler(panel1_MouseMove);

        m_image = new Bitmap(panel1.Width, panel1.Height);
    }

    void panel1_MouseMove(object sender, MouseEventArgs e)
    {
        using (Graphics g = Graphics.FromImage(m_image))
        {
            g.FillEllipse(Brushes.Black, new Rectangle(e.X, e.Y, 10, 10));
        }
        panel1.Invalidate();
    }

    void panel1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(m_image, 0, 0);
    }
}

This causes flickering, apparently because it erases the panel with each paint cycle.

+3
source share
3 answers

OnPaintBackground(), WndProc(). . , , . - SetWindowsHookEx() WH_CALLWNDPROC, .

+4

:

panel1.BackgroundImage = m_image;
//on panel1_Paint() function.

?

0

Use reflection to set the DoubleBuffered protected property:

System.Reflection.PropertyInfo aProp =
         typeof(System.Windows.Forms.Control).GetProperty(
               "DoubleBuffered",
               System.Reflection.BindingFlags.NonPublic |
               System.Reflection.BindingFlags.Instance);

aProp.SetValue(panel1, true, null);

You can also make it more efficient by only invalidating the changed area (this almost flickers even without double buffering):

void panel1_MouseMove(object sender, MouseEventArgs e)
{
    Rectangle r = new Rectangle(e.X, e.Y, 10, 10);
    using (Graphics g = Graphics.FromImage(m_image))
    {
        g.FillEllipse(Brushes.Black, r);
    }
    panel1.Invalidate(r);
}
0
source

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


All Articles