I have tried to get rid of the flickering effect when updating the graphical content of a panel in my application. Simplified, the Mainform.cs looks like this:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsAppRefreshTest
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
var g = panel1.CreateGraphics();
g.FillRectangle(Brushes.Red, 20, 20, panel1.Width - 40, panel1.Height - 40);
if(panel1.Width>100 && panel1.Height>100) g.FillRectangle(Brushes.Blue, 40, 40, panel1.Width - 80, panel1.Height - 80);
}
private void panel1_SizeChanged(object sender, EventArgs e)
{
panel1.Refresh();
}
}
}
If I set a breakpoint on the first row of panel1_Paint the panel will be cleared to the BackColor as the event is called. This is not what I want - I want the panel to be painted only by the panel1_Paint method, since I draw the whole area every time with a bitmap that has been prepared in my real application.
How do I get Windows Forms NOT to clear the panel with BackColor before the code can paint it?
EDIT: Thanks for the answers, Jimi and Mark! Still using Panel, I was able to solve this issue using the suggestion from Mark, creating a subclass to Panel looking like this:
public class NoBackgroundPanel : Panel
{
public NoBackgroundPanel() { }
protected override void OnPaintBackground(PaintEventArgs e) { }
}
and using this instead of System.Windows.Forms.Panel in MainForm.Designer.cs - InitializeComponent(): this.panel1 = new NoBackgroundPanel();
This was for me the desired solution since I am manually updating a Bitmap used as a doublebuffer in my real application, then drawing that to the full area of the panel when it has to be redrawn.