简体   繁体   中英

Cannot convert from int to System.Drawing.Point when comparing coordinates

I want to check if two sets of coordinates are close to each other. I had a look at this answer , which suggested using the Pythagorean formula to calculate the distance between two points.

The two sets of coordinates I'm comparing is the current position of the mouse, and preset coordinates under the variable point

if(Math.Sqrt(Math.Pow(point.X - this.PointToClient(Cursor.Position.X), 2) + Math.Pow(point.Y - this.PointToClient(Cursor.Position.Y), 2) < 50))
{
   Console.WriteLine("Distance between the points is less than 50");
}

The variable point has the point data type.

I am using this.PointToClient(Cursor.Position) instead of Cursor.Position because I want to get the coordinates relative to the form, instead of relative to the screen. However using this gives me the following error:

Cannot convert from int to System.Drawing.Point

You've put .X and .Y at the wrong side : first convert the point, then take its coordinate.

Another issue is < 50 position

if(Math.Sqrt(Math.Pow(point.X - this.PointToClient(Cursor.Position).X, 2) + 
             Math.Pow(point.Y - this.PointToClient(Cursor.Position).Y, 2)) < 50)
{
   Console.WriteLine("Distance between the points is less than 50");
}

You may want to extract this.PointToClient(Cursor.Position) to have if more readable :

var cursor = PointToClient(Cursor.Position); 

if(Math.Sqrt(Math.Pow(point.X - cursor.X, 2) + 
             Math.Pow(point.Y - cursor.Y, 2)) < 50)
{
   Console.WriteLine("Distance between the points is less than 50");
}

PointToClient expects a Point as argument by you are passing an int. So change this

this.PointToClient(Cursor.Position.X)

to:

this.PointToClient(Cursor.Position).X

And also

this.PointToClient(Cursor.Position.Y)

to

this.PointToClient(Cursor.Position).Y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM