计算两个鼠标点之间的距离

时间:2012-12-18 16:16:10

标签: c# math mouse distance

我需要计算鼠标在屏幕上单击的两个位置之间的距离。

目标(x& Y)&鼠标移动事件(e.X& e.Y)上填充了源(X& Y)

我有distance = Math.Sqrt(Math.Pow(targetX - sourceX, 2) + Math.Pow(targetY - sourceY, 2));

这给了我一个结果,但如果我说实话,我不确定测量单位是什么单位或如何转换它。如何将结果转换为有意义的结果,如cm或英寸?我猜我需要考虑屏幕资源吗?

更新 我真的只是在浪费时间。不寻找一个有效的解决方案。它只会持续一两天。

这是MoveMove事件和调用。应该发布之前更清楚。

    private void HookManager_MouseMove(object sender, MouseEventArgs e)
    {

        labelMousePosition.Text = string.Format("x={0:0000}; y={1:0000}", e.X, e.Y);
        AddDistance(Convert.ToDouble(e.X), Convert.ToDouble(e.Y));
    }

    private void AddDistance(double targetX, double targetY)
    {
        if (sourceX != 0 && sourceY != 0)
        {
            double distance = Convert.ToDouble(lblDistanceTravelled.Text);
            distance =+ Math.Sqrt(Math.Pow(targetX - sourceX, 2) + Math.Pow(targetY - sourceY, 2));
            lblDistanceTravelled.Text = distance.ToString();
        }
        sourceX = targetX;
        sourceY = targetY;
    }

3 个答案:

答案 0 :(得分:5)

变量targetX和sourceX最有可能是像素,因此得到的距离将以像素为单位。

要将其转换为“屏幕上的英寸”,您必须知道屏幕的大小。您可以确定每英寸的像素数并从那里进行转换(尽管这只能估算出如果实际将标尺固定在屏幕上会得到什么)。要获得每英寸像素数,请参阅

How do I determine the true pixel size of my Monitor in .NET?

根据这个问题,您可以按照以下方式获得DPI(但请阅读许多警告的接受答案)

PointF dpi = PointF.Empty;
using(Graphics g = this.CreateGraphics()){
    dpi.X = g.DpiX;
    dpi.Y = g.DpiY;
}

单位之间的转换是这样的:

lengthInInches = numberOfPixes / dotsPerInch

这里“点”和“像素”的含义相同。我使用的是通用术语。

答案 1 :(得分:3)

您可以通过

获取“当前DPI”
int currentDPI = 0;  
using (Graphics g = this.CreateGraphics())  
{  
    currentDPI = (int)g.DpiX;      
}

然后你就可以了

double distanceInInches = distance/*InPixels*/ / currentDPI;

但是,系统的DPI设置无法真正依赖于从像素距离到屏幕英寸距离的真正转换。

答案 2 :(得分:1)

        double dpc = this.CreateGraphics().DpiX / 2.54; //Dots Per Centimeter

        //calculate the number of pixels in the line
        double lineLengthInPixels = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));

        //line length in centimenters
        double lineLengthInCentimeters = dpc / lineLengthInPixels;
相关问题