G
G
German2019-04-12 08:31:56
C++ / C#
German, 2019-04-12 08:31:56

How to smoothly move the mouse at a given speed in WinAPI?

It is required to be able to move the mouse in some direction, vertically, horizontally or vertically-horizontally, smoothly and at a certain speed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Warlodya, 2019-04-12
@Warlodya

Here is the implementation of the Bresenham algorithm which I use which I use

spoiler
void moveMouseLine(int endX, int endY)
{
  int d = 0;
  POINT p;
  GetCursorPos(&p);
  
  int currentX = p.x;
  int currentY = p.y;
  int dx = abs(endX - currentX);
  int dy = abs(endY - currentY);

  int dx2 = 2 * dx; // slope scaling factors to
  int dy2 = 2 * dy; // avoid floating point

  int ix = currentX < endX ? 1 * Const::MIN_MOUSE_SPEED : -1 * Const::MIN_MOUSE_SPEED; // increment direction
  int iy = currentY < endY ? 1 * Const::MIN_MOUSE_SPEED : -1 * Const::MIN_MOUSE_SPEED;

  int x = currentX;
  int y = currentY;
  int pauseLenght = 500/(dx+dy+1)+10;
  if (dx >= dy) {
    while (true) {
      moveMouse(x, y);
      if (abs(x - endX) < Const::MAX_MOUSE_SPEED) {
        moveMouse(endX, endY);

        break;
      }
      x += ix;
      d += dy2;
      if (d > dx) {
        y += iy;
        d -= dx2;
      }
      Sleep(pauseLenght);
    }
  }
  else {
    while (true) {
      moveMouse(x, y);
      if (abs(y - endY) < Const::MAX_MOUSE_SPEED) {
        moveMouse(endX, endY);
        break;
      }
      y += iy;
      d += dx2;
      if (d > dy) {
        x += ix;
        d -= dy2;
      }
      Sleep(pauseLenght);
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question