2

重複の可能性:
C# でマウスをリアルに動かす

私はマウスを次のように動かすことができます:

[DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

// move relative from where the cursor is
public static void Move(int xDelta, int yDelta)
{

    mouse_event(0x0001, xDelta, yDelta, 0, 0);
}

とにかくマウスをスムーズに動かして、ユーザーに見えるようにしたいと思います。アニメーション化し、新しい場所に移動するのに 1 秒かかります。その結果、次のように機能する方法を探しています。

 public static void Move(int xDelta, int yDelta, int timeInMiliseconds)
 {
    // i will like to move the mouse to 
         (mouse.getCurentPos().x+xDelta, mouse.getCurentPos().y+yDelta) 
    // in timeInMiliseconds miliseconds

 }
4

1 に答える 1

2

負のデルタをサポートするために編集されました。

これは、 への余分な呼び出しがなく、スムーズであるという完璧な組み合わせですmouse_event

public static void Move(int xDelta, int yDelta, int timeInMilliseconds, bool async = false)
{
    // No need to move the mouse at all.
    if (xDelta == 0 && yDelta == 0) return;

    // No need to move smoothly.
    if (timeInMilliseconds <= 0)
    {
        Move(xDelta, yDelta);
        return;
    }

    // Set direction factors and then make the delta's positive
    var xFactor = 1;
    var yFactor = 1;

    if (xDelta < 0)
    {
        xDelta *= (xFactor = -1);
    }

    if (yDelta < 0)
    {
        yDelta *= (yFactor = -1);
    }

    // Calculate the rates of a single x or y movement, in milliseconds
    // And avoid dividing by zero
    var xRate = xDelta == 0 ? -1 : (double)timeInMilliseconds / xDelta;
    var yRate = yDelta == 0 ? -1 : (double)timeInMilliseconds / yDelta;

    // Make a thread that will move the mouse in the x direction
    var xThread = new Thread(() =>
    {
        // No need to move in the x direction
        if (xDelta == 0) return;

        var sw = Stopwatch.StartNew();
        var c = 1;

        for (var i = 0; i < xDelta; i++)
        {
            // Wait for another "rate" amount of time to pass
            while (sw.ElapsedMilliseconds / xRate < c)
            {
            }

            c++;

            // Move by a single pixel (x)
            Move(xFactor, 0);
        }
    });

    // Make a thread that will move the mouse in the y direction
    var yThread = new Thread(() =>
    {
        // No need to move in the y direction
        if (yDelta == 0) return;

        var sw = Stopwatch.StartNew();
        var c = 1;

        for (var i = 0; i < yDelta; i++)
        {
            // Wait for another "rate" amount of time to pass
            while (sw.ElapsedMilliseconds / yRate < c)
            {
            }

            c++;

            // Move by a single pixel (y)
            Move(0, yFactor);
        }
    });

    // Activate the movers threads
    xThread.Start();
    yThread.Start();

    if (async)
    {
        return;
    }

    // Wait for both to end (remove this if you want it async)
    xThread.Join();
    yThread.Join();
}
于 2012-05-08T00:12:59.670 に答える