Stephan Hutterer
Stephan Hutterer

Reputation: 67

windows forms: create transparent graphic upon a chart in C#

I exhaustively used the search but have not been able to find a satisfying solution to my problem.

I programmed a data visualization using a chart (datavisualization.charting.chart). This chart changes steadily since it shows some kind of simulation results. I would like to draw for example a line upon the chart (depending on the mouse position) in order to show context sensitive information.

Therefore, I tried two implementations, none of both works exactly as I would like it to:

plotLine is called on MouseMove- Event

gGraph is created from the underlying graph using: chartCreateGraphics();

protected void plotLine(object sender, System.EventArgs e)
{
  if (this.chart.Series.Count > 0) //ensure that the chart shows data
  {
    plotChart(); // this plots the underlying chart
    penGraph = new Pen(Color.Black);
    Point point1 = new Point(Form1.MousePosition.X - chart.Location.X, 0);
    Point point2 = new Point(Form1.MousePosition.X - chart.Location.X,     
    chart.Location.Y + chart.Size.Height);
    gGraph.DrawLine(penGraph, point1, point2);
    penGraph.Dispose();     
  }
}

Here, the line disappears each time immediately after being plotted, but should remain as long as the mouse is not moved.

protected void plotLine(object sender, System.EventArgs e)
{
  penGraph = new Pen(Color.Black);
  Point point1 = new Point(Form1.MousePosition.X - chart.Location.X, 0);
  Point point2 = new Point(Form1.MousePosition.X - chart.Location.X,     
  chart.Location.Y + chart.Size.Height);
  gGraph.DrawLine(penGraph, point1, point2);
  penGraph.Dispose();           
}

Here, all plotted lines remain in the graphics surface as long as the chart is not plotted by new. (only the last line should remain in order to indicate the mouse position)

Can anybody help me?

Upvotes: 1

Views: 613

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124790

You should be drawing in the OnPaint event. You are circumventing the update model and are seeing the effects of doing so. Sure, you do some drawing in MouseMove, but when the Paint event fires it will simply be erased.

Put your code in OnPaint first. On mouse move simply record whatever data you need to (i.e., mouse position) and then call Invalidate() on the chart. When you do that the Paint event will be called and your drawing code will fire.

Rule of thumb; never draw from anywhere but the Paint event.

Upvotes: 1

Related Questions