3

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

target(x & Y) & source(X & Y) 在鼠标移动事件 (eX & eY) 上填充

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

这给了我一个结果,但老实说,我不确定测量的单位是什么或如何转换它。如何将该结果转换为有意义的结果,例如厘米或英寸?我猜我需要考虑屏幕分辨率?

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

这是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;
    }
4

3 回答 3

5

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

为了将其转换为“屏幕上的英寸”,您必须知道屏幕的大小。您可以确定每英寸的像素数并从那里进行转换(尽管这仅提供了您将尺子实际放在屏幕上时所获得的估计值)。要获得每英寸的像素,请参阅

如何在 .NET 中确定监视器的真实像素大小?

从那个问题中,您可以获得如下 DPI(但请阅读已接受的答案以了解许多警告)

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

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

lengthInInches = numberOfPixes / dotsPerInch

这里的“点”和“像素”是同一个意思。我使用的是通用术语。

于 2012-12-18T16:18:07.470 回答
3

您可以通过以下方式获取“当前 DPI”

int currentDPI = 0;  
using (Graphics g = this.CreateGraphics())  
{  
    currentDPI = (int)g.DpiX;      
}

然后你可以得到

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

但是,不能真正依赖系统的 DPI 设置来实现从像素距离到屏幕英寸距离的真正转换。

于 2012-12-18T16:20:43.787 回答
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;
于 2012-12-18T16:19:18.480 回答