DoubleBuffered设置为true时覆盖OnPaint的问题

Dmi*_*pov 1 c# doublebuffered onpaint winforms

我创建了一个派生自Panel的自定义控件.我用它来使用BackgroundImage属性显示一个Image.我重写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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 6

在你的PaintSelection,你不应该创建一个新的Graphics对象,因为该对象将绘制到前缓冲区,然后由后缓冲区的内容迅速透支.

油漆到Graphics传入的PaintEventArgs代替:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)