I have a component, an inherited Panel, where I am overriding the OnPaint event to draw a graph with 500 points. Since I need to do some selection on the graph, it is flickering. I have found this DoubleBuffered property but when I set it to True, in the panel constructor, the drawing disappears. I debug it and I see that the drawing methods still execute but there is nothing on the panel. Does anyone know why would this happen?
This is .NET 3.5 - C#. Winforms application
try
{
Graphics g = e.Graphics;
//Draw _graphArea:
g.DrawRectangle(Pens.Black, _graphArea);
_drawingObjectList.DrawGraph(g, _mainLinePen, _diffLinePen, _dotPen, _dotBrush, _notSelectedBrush, _selectedBrush);开发者_如何学Go
DrawSelectionRectangle(g);
g.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Panel descendant constructor:
this.BackColor = Color.White;
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.UpdateStyles();
Try using ControlStyles.OptimizedDoubleBuffered
instead. It's faster and usually works better. Make sure ControlStyles.AllPaintingInWmPaint
and ControlStyles.UserPaint
are also enabled.
Now, OnPaint()
should be the only stuff that draw to the window and this method must only be called from invalidation or by using Refresh()
; you must never call OnPaint()
yourself. Do not dispose the Graphics
object. If you fail any of those conditions, flickering and various other drawing bugs might occur.
class MyControl : UserControl
{
public MyControl()
{
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(Color.Red);
}
void RandomEventThatRequiresRefresh(object sender, EventArgs e)
{
Refresh();
}
}
精彩评论