C# 将Double Buffered设置为true时重写OnPaint的问题

C# 将Double Buffered设置为true时重写OnPaint的问题,c#,winforms,doublebuffered,onpaint,C#,Winforms,Doublebuffered,Onpaint,我已经创建了一个从面板派生的自定义控件。我使用它来显示使用BackgroundImage属性的图像。我重写OnClick方法并将isSelected设置为true,然后调用Invalidate方法并在重写的OnPaint中绘制一个矩形。 在我将DoubleBuffered设置为true之前,一切都很顺利。矩形被画出来,然后被擦除,我不明白为什么会发生这种情况 public CustomControl() : base() { base.DoubleBuffered = true;

我已经创建了一个从面板派生的自定义控件。我使用它来显示使用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);
    }
}

PaintSelection
中,不应创建新的
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);
    }
}

PaintSelection
中,不应创建新的
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);
    }
}