【问题标题】:OnPaint method is being call for every child control正在为每个子控件调用 OnPaint 方法
【发布时间】:2009-03-07 06:16:29
【问题描述】:

我有一个 UserControl(WinForms,.net 2.0),我有这个:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    var rect = e.ClipRectangle;
    var pen = new Pen(Brushes.LightGray, 1);

    e.Graphics.DrawRectangle(pen, rect);
}

我基本上想在 UserControl 上画一个边框,但是矩形也在所有子控件中绘制! 我从来没有读过它应该为每个子控件调用,有解决方案吗?

【问题讨论】:

    标签: c# winforms drawing onpaint


    【解决方案1】:

    为什么要使用PaintEventArgs.ClipRectangle 来确定矩形的边界?尝试改用Control.ClientRectangle

    【讨论】:

      【解决方案2】:

      因为子控件使父控件无效,导致每个控件都触发此方法。

      不要使用 e 作为参数(e 将是触发事件的任何控件,无论是否为子控件),而是使用控件名称显式。

      【讨论】:

      • 您的意思是像(PaintEventArgs UserControl) 还是像UserControl.Graphics 这样的传递参数?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多