如何在图表区的光标位置显示相交的十字线?

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

我有一个折线图,我添加了十字准线来显示 x 和 y 轴值,但是有问题。 X 和 Y 轴光标标记的交点与鼠标光标位置不同。我使用 MouseMove 事件,正如您在图片中看到的,我的鼠标光标(显示为红色圆圈)远离交叉点。

如何使十字线在鼠标光标位置相交?

这是我的代码;

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;
    }
}

我的图表区和光标(红点)和x-y轴的显示:

我假设您在 WinForms 中工作,并且您希望交叉线与光标位置相匹配,并且这些线非常细 Labels(这里有很多假设)!否则这个答案可能完全是胡说八道 ;)

问题是,当您使用 MouseEventArgs.X 属性 时,您会得到:

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.

您在 X 维度中的偏移量恰好是表格左边框与图表左边框之间的差值。如果您计算此偏移量并将其添加到您的坐标中,它将正常工作:

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));

结果应如下所示:

最后一点:您可以使用 String.Format 使您的点值标签更具可读性:

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