2012-05-08 163 views
0

可能重复:
C# moving the mouse around realistically鼠标移动与速度

我可以移动鼠标为:

[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

对不起,我会投票结束。对此感到抱歉 –

+0

其实,其他问题的答案可能会对mouse_event进行多次不必要的调用。查看我的答案编辑。 – SimpleVar

回答

2

EDITED支持负增量的。

这是平滑的和没有额外的电话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(); 
} 
+0

非常感谢您的帮助。我想让它减速。我想我可以通过减少xRate和yRate来做到这一点。我会尽量接受你的答案。 –

+0

当xDelta是负数时它不起作用... –

+0

@TonoNam我也意识到了这一点。编辑为支持负三角洲。 – SimpleVar