我可以将鼠标移动为:
[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
}
答案 0 :(得分: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();
}