2010-07-15 70 views
1

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

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

回答

6

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

画图到GraphicsPaintEventArgs,而不是通过:

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

我知道这是容易的,谢谢! – 2010-07-15 12:15:03