我创建了两个自定义面板(ParentPanel和ChildPanel),并将ChildPanel添加为ParentPanel的子项。现在我想单独使子面板无效。但是在调用 ChildPanel.Invalidate()时,已经为两个面板调用了OnPaint方法(ParentPanel和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");
}
}
}
我尝试使用 WM_SETREDRAW 跳过ParentPanel的绘图。但它将暂停两个小组的绘制。
[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();
}
任何人都可以建议我在不影响父母的情况下单独重绘子面板的任何解决方案吗?
提前致谢。
此致 Pannir
答案 0 :(得分:-1)
我无法复制问题,孩子不会为父母触发onpaint。那个消息框是不是触发了重绘,或按下面板上的按钮?