根据在按键事件中按下的按键设置boolean 标志。
在OnMouseMove 中记录鼠标位置,如果为空。否则计算行进的距离,并根据您已经设置的加速或减速标志对其进行放大或衰减。
要抑制或放大,一旦你从最后一点的 X 和 Y 变化,乘以 2,或除以 2...(你可以选择自己的数字),现在将新的 YX 变化添加到当前鼠标 XY 坐标并设置鼠标位置。
这是MouseMove 的样子,以及一些需要的私有变量。在我的示例中,您必须包含 Forms 作为参考。我没有在我的 Include 语句中包含 Forms,因为它破坏了 WPF 应用程序中的 IntelliSense。您仍然需要使用 KeyDown 事件维护这些 _speedUp 和 _slowDown 变量
private bool entering = true;
private Point _previousPoint;
private bool _speedUp;
private bool _slowDown;
private double _speedMod = 2;
private double _slowMod = .5;
private void OnMouseMove(object sender, MouseEventArgs e)
{
Point curr = new Point(System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y);
if (entering)
{
_previousPoint = curr;
entering = false;
}
if (_previousPoint == curr)
return; // The mouse hasn't really moved
Vector delta = curr - _previousPoint;
if (_slowDown && !_speedUp)
delta *= _slowMod;
else if (_speedUp && !_slowDown)
delta *= _speedMod;
else
{
_previousPoint = curr;
return; //no modifiers... lets not do anything
}
Point newPoint = _previousPoint + delta;
_previousPoint = newPoint;
//Set the point
System.Windows.Forms.Cursor.Position = new System.Drawing.Point((int)newPoint.X, (int)newPoint.Y);
}
编辑:我把按键事件放在我的窗口定义中,它工作得很好。尽管正如该线程的 cmets 中所指出的,使用Keyboard.IsKeyDown 要简单得多。我还编辑了上面的代码,以免引起奇怪的跳跃问题
private void Window_KeyDown(object sender, KeyEventArgs e)
{
_slowDown = true;
if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
_slowDown = true;
else if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
_speedUp = true;
}
private void Window_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
_slowDown = false;
else if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
_speedUp = false;
}
private void Window_MouseLeave(object sender, MouseEventArgs e)
{
entering = true;
}