Search code examples
c#chartscursorcursor-position

How to display cross hairs intersecting at the cursor position in chart area?


I have a line chart and I added cross-hair to show x and y axes values but there is a problem. The intersection of the X and Y axis cursor markers is not the same as the Mouse cursor location. I use the MouseMove event and as you see in picture my Mouse cursor(showed as red circle) is far away from intersection point.

How can I make the cross hairs intersect at the Mouse cursor position?

Here is my code;

private void chrtAcq_MouseMove(object sender, MouseEventArgs e)
{        
    lab_X_Axis.Location=new Point((e.X),90);
    lab_Y_Axis.Location=new Point(123, (e.Y));

    if (e.X<=125 || e.Y >=495|| e.Y<=90||e.X>=830)
    {
        lab_X_Axis.Visible = false;
        lab_Y_Axis.Visible = false;
        lab_X_Axis_Cur.Visible = false;
    }
    else
    {
        lab_X_Axis.Visible = true;
        lab_Y_Axis.Visible = true;
        lab_X_Axis_Cur.Visible = true;
    }
    try
    {
        Double yValue=chrtAcq.ChartAreas[0].AxisY.PixelPositionToValue(e.Y);
        double xValue = chrtAcq.ChartAreas[0].AxisX.PixelPositionToValue(e.X);
        lab_X_Axis_Cur.Text = String.Concat(String.Concat(Math.Round(xValue, 5).ToString(), " , "), Math.Round(yValue, 5).ToString());
        lab_X_Axis_Cur.Location = new Point(750, e.Y);
    }
    catch (Exception)
    {            
        throw;
    }
}

My display of chart area and cursor(red point) and x-y axes lines:

My display of chart area and cursor(red point) and x-y axes lines


Solution

  • I assume you are working in WinForms and that you want to have the crossed line to match the cursor position and that the lines are very thin Labels (that's a lot of assumptions here)! Otherwise this answer might be utter nonsense ;)

    The problem is that when you use the MouseEventArgs.X property you get:

    the mouse coordinate values are relative to the coordinates of the control that raised the event. Some events related to drag-and-drop operations have associated mouse-coordinate values that are relative to the form origin or the screen origin.

    Your offset in the X-Dimension is exactly the difference between the left border of the form and the left border of the chart. If you calculate this offset and add it to your coordinates it will work just fine:

    int x_offset = chart1.Location.X;
    int y_offset = chart1.Location.Y;
    
    lab_X_Axis.Location = new Point((e.X+x_offset), 90);
    lab_Y_Axis.Location = new Point(123, (e.Y+y_offset));
    

    The result should look like this:

    enter image description here

    One last point: you can use String.Format to make your label of point values a little more readable:

    lab_X_Axis_Cur.Text = String.Format("X: {0} Y: {1}",Math.Round(xValue, 5), Math.Round(yValue, 5));