2010-07-15 68 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