Force Form To Redraw?
In C# WinForms - I am drawing a line开发者_如何学Go chart in real-time that is based on data received via serial port every 500 ms.
The e.Graphics.DrawLine logic is within the form's OnPaint handler.
Once I receive the data from the serial port, I need to call something that causes the form to redraw so that the OnPaint handler is invoked. I have tried this.Refresh and this.Invalidate, and what happens is that I lose whatever had been drawn previously on the form.
Is there another way to achieve this without losing what has been drawn on your form?
The point is that you should think about storing your drawing data somewhere. As already said, a buffer bitmap is a solution. However, if you have not too much to draw, sometimes it is easier and better to store your drawing data in a variable or an array and redraw everything in the OnPaint event.
Suppose you receive some point data that should be added to the chart. Firs of all you create a point List:
List<Point> points = new List<Point>();
Then each time you get a new point you add it to the list and refresh the form:
points.Add(newPoint);
this.Refresh();
In the OnPaint event put the following code:
private void Form_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLines(Pens.Red, points);
}
This works quite fast up to somehow 100 000 points and uses much less memory than the buffer bitmap solution. But you should decide which way to use according to the drawing complexity.
As rerun said, you need to buffer your form (since it appears that you are discarding the data after you draw it).
This is basically how I would do it:
private Bitmap buffer;
// When drawing the data:
if (this.buffer == null)
{
this.buffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
}
// then draw on buffer
// then refresh the form
this.Refresh();
protected override void OnPaint(PaintEventArgs e)
{
if (this.buffer != null)
{
e.Graphics.DrawImage(this.buffer);
}
}
That said, you probably want to cache your data so you can change the size of the buffer when the form size changes and then redraw the old data on it.
The solution may be this.Invalidate()
the default way to handle this is to create a memory bitmap and draw on that then set the image property of the picture box to the memory bitmap.
You will need to store historical data somewhere and just repaint it.
That will be much easier than say caching and clipping bitmaps.
精彩评论