Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable OnPaintBackground without subclassing Panel?

Is there any way to disable the erasing of a panel without subclassing Panel and overriding OnPaintBackground?

I am trying to achieve a double buffering effect without subclassing Panel. I understand that this may be a weird thing to try to do, but I'd at least like to know if I can or not. The following code sample 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 a flickering, presumably because it is erasing the panel at each paint cycle.

like image 605
WildCrustacean Avatar asked Dec 17 '25 19:12

WildCrustacean


1 Answers

You can hack OnPaintBackground() or you can hack WndProc(). Either requires deriving your own class. It's trivial, I just don't see why you'd avoid it. The long distance shot is SetWindowsHookEx() with a WH_CALLWNDPROC hook, too silly really.

like image 165
Hans Passant Avatar answered Dec 20 '25 03:12

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!