I have created the two custom panels (ParentPanel and ChildPanel) and added the ChildPanel as children of the ParentPanel. Now i want to invalidate the child panel alone. But while calling ChildPanel.Invalidate(), OnPaint method have been called for both panels (ParentPanel and ChildPanel).
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private ParentPanel parentPanel;
public Form1()
{
InitializeComponent();
parentPanel = new ParentPanel();
parentPanel.Size = new Size(300, 200);
parentPanel.Location = new Point(3,30);
var button1 = new Button();
button1.Text = "Invalidate Child";
button1.Size = new Size(130, 25);
button1.Location = new Point(3,3);
button1.Click += button1_Click;
this.Controls.Add(parentPanel);
this.Controls.Add(button1);
}
private void button1_Click(object sender, EventArgs e)
{
this.parentPanel.ChildPanel.Invalidate();
}
}
public class ParentPanel : Panel
{
public ChildPanel ChildPanel { get; set; }
public ParentPanel()
{
BackColor = Color.Yellow;
ChildPanel = new ChildPanel();
this.Controls.Add(ChildPanel);
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.Selectable |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
MessageBox.Show("Parent Panel invalidated");
base.OnPaint(e);
}
}
public class ChildPanel : Panel
{
public ChildPanel()
{
BackColor = Color.Transparent;
Anchor = AnchorStyles.Left | AnchorStyles.Top;
Dock = DockStyle.Fill;
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.Selectable |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
MessageBox.Show("Child Panel Invalidated");
}
}
}
I have tried to skip the drawing of ParentPanel by using WM_SETREDRAW. But it will suspend drawing of both panels.
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing(Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
//parent.Refresh();
}
Can anyone please suggest me any solution to redraw the child panel alone without affecting parent?
Thanks in advance.
Regards, Pannir