检查光标是否在某个半径

时间:2016-01-26 11:19:48

标签: c# geometry

实际上我正在尝试做一个程序,告诉你是否在我的秘密半径内。  我将Point设置为例如 x = 1000且y = 400,并且我将半径设置为例如50,如果我的光标距离点的半径为50,它将写入控制台“你在半径,x是1000,y是400”。

这不是家庭作业或任何类似的东西,我只是尝试新的东西。

好的,所以这就是我尝试过的,不能继续前进了。

-NOTE:半径应该是圆圈,所以我猜我需要实现 r PI 但是我不太确定怎么做它以编程方式:

class Program
{
    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool GetCursorPos(out System.Drawing.Point point);

    [DllImport("user32.dll")]
    public static extern int GetAsyncKeyState(System.Windows.Forms.Keys vKey);

    static void Main(string[] args){
        Point cursorPoint;
        Point myPos = Point.Empty;
        myPos.X = 1000;
        myPos.Y = 400;
        int myRadius = 50;
        while (true){
            //if pressed ESC let me end the program.
            if (GetAsyncKeyState(Keys.Escape) > 0)
                return;
            //get cursor pos and store it in cursorPoint
            GetCursorPos(out cursorPoint);

            //here should be a check with some calculation about radius, but I can't do that..
            Console.WriteLine("You are in radius and your cursor coordinations are X:{0}|Y:{1}",cursorPoint.X,cursorPoint.Y);
            //help cpu
            Thread.Sleep(16);
        }

    }
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

你只需要使用毕达哥拉斯来计算点之间的距离,并将其与范围进行比较。

通常你需要平方根来找到两点之间的距离,但是如果你只需要比较一个范围,你可以改为对范围进行平方并避免使用平方根。

例如:

static bool isInRange(Point p1, Point p2, int range)
{
    int rangeSquared = range * range;

    int deltaX = p2.X - p1.X;
    int deltaY = p2.Y - p1.Y;

    int distanceSquared = deltaX*deltaX + deltaY*deltaY;

    return distanceSquared <= rangeSquared;
}

另请注意,如果坐标变得太大,这些计算会溢出,但屏幕上的像素坐标不会发生这种情况。

答案 1 :(得分:0)

据我所知,你的问题是关于确定一条直线上两点之间的距离,即围绕其中心的圆的半径。

为此,您首先需要x和y中的增量。然后你使用毕达哥拉斯定理(找到here)。

  <className>com.worklight.core.auth.ext.LdapLoginModule</className>
        <parameter name="ldapProviderUrl" value="ldap://forumsys.com:389"/>
        <parameter name="ldapTimeoutMs" value="2000"/>
        <parameter name="ldapSecurityAuthentication" value="simple"/>
        <parameter name="validationType" value="searchPattern"/>
        <parameter name="ldapSecurityPrincipalPattern" value="uid={username},ou=mathematicians,dc=example,dc=com"/>
        <parameter name="ldapSearchFilterPattern" value="(uid={username})"/>     
        <parameter name="ldapSearchBase" value="dc=example,dc=com"/>