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

我创建了一个派生自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); } } 

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