如何在窗口窗体中单独使子面板失效

本文关键字:失效 单独使 窗口 窗体 | 更新日期: 2023-09-27 18:36:09

我创建了两个自定义面板(ParentPanel 和 ChildPanel),并将 ChildPanel 添加为 ParentPanel 的子面板。现在我想单独使子面板无效。但是在调用 ChildPanel.Invalidate() 时,已经为两个面板(ParentPanel 和 ChildPanel)调用了 OnPaint 方法。

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跳过父面板的绘制。但它将暂停绘制两个面板。

[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();
}

任何人都可以向我建议任何解决方案来单独重绘子面板而不影响父面板吗?

提前谢谢。

问候潘尼尔

如何在窗口窗体中单独使子面板失效

我无法复制问题,孩子不会为父母触发 onpaint。该消息框不会触发重绘,还是按钮按下(如果它在面板上)?