【问题标题】:A problem with overriding OnPaint when DoubleBuffered set to true当 DoubleBuffered 设置为 true 时覆盖 OnPaint 的问题
【发布时间】:2011-03-16 09:13:05
【问题描述】:

我创建了一个派生自 Panel 的自定义控件。我用它来显示一个使用 BackgroundImage 属性的图像。我覆盖 OnClick 方法并将 isSelected 设置为 true,然后调用 Invalidate 方法并在覆盖的 OnPaint 中绘制一个矩形。 一切都很好,直到我将 DoubleBuffered 设置为 true。矩形被绘制,然后被擦除,我不明白为什么会发生这种情况。

public CustomControl()
    : base()
{
    base.DoubleBuffered = true;

    base.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);
}

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

    PaintSelection();
}

private void PaintSelection()
{
    if (isSelected)
    {
        Graphics graphics = CreateGraphics();
        graphics.DrawRectangle(SelectionPen, DisplayRectangle.Left, DisplayRectangle.Top, DisplayRectangle.Width - 1, DisplayRectangle.Height - 1);
    }
}

【问题讨论】:

    标签: c# winforms doublebuffered onpaint


    【解决方案1】:

    在您的PaintSelection 中,您不应创建新的Graphics 对象,因为该对象将绘制到前端缓冲区,然后会立即被后端缓冲区的内容覆盖。

    改为在PaintEventArgs 中传递Graphics

    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
        PaintSelection(pe.Graphics);
    }
    
    private void PaintSelection(Graphics graphics)
    {
        if (isSelected)
        {
            graphics.DrawRectangle(SelectionPen, DisplayRectangle.Left, DisplayRectangle.Top, DisplayRectangle.Width - 1, DisplayRectangle.Height - 1);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-18
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多