SetCursorPos失灵了吗?

3

我想在Delphi中编写一个过程,以模拟具有特定速度的移动鼠标指针(类似于AutoIT MouseMove函数)。

要么我的代码有问题,要么SetCursorPos在被调用太多次后出现故障。

这是我编写的函数:

procedure MoveMouse ( X, Y, Speed : Integer);
var
  P     : TPoint;
  NewX  : Integer;
  NewY  : Integer;
begin
  if X < 0 then exit;
  if Y < 0 then exit;
  if X > Screen.Height then exit;
  if Y > Screen.Width then Exit;
  repeat
    GetCursorPos(P);
    NewX := P.X;
    NewY := P.Y;
    if P.X <> X then begin
      if P.X > X then begin
        NewX := P.X - 1;
      end else begin
        NewX := P.X + 1;
      end;
    end;
    if P.Y <> Y then begin
      if P.Y > Y then begin
        NewY := P.Y - 1;
      end else begin
        NewY := P.Y + 1;
      end;
    end;
    sleep (Speed);
    SetCursorPos(NewX, NewY);
  until (P.X = X) and (P.Y = Y);
end;

我这样使用它:
procedure TForm1.btn1Click(Sender: TObject);
var
  X : Integer;
  Y : Integer;
begin
  for X := 0 to Screen.Width do begin
    for Y := 0 to Screen.Height do begin
      MouseClick (X, Y, 1);
    end;
  end;
end;

鼠标指针因某种原因卡在特定的X点,然后跳回0,0,但是为什么会这样?

1个回答

6
你的代码卡住了,因为在循环中,条件没有得到满足。
until (P.X = X) and (P.Y = Y);

当你传递X=0和Y=屏幕高度时,会出现不满足的情况,因此你需要修改循环以仅传递有效的屏幕坐标值。
  for X := 0 to Screen.Width-1 do
    for Y := 0 to Screen.Height-1 do
      MoveMouse (X, Y, 1); 

此外,您可以通过检查 GetCursorPosSetCursorPos 函数的结果来改进您的方法。

procedure MoveMouse ( X, Y, Speed : Word);
var
  P     : TPoint;
  NewX  : Integer;
  NewY  : Integer;
begin
  if X > Screen.Width-1  then Exit;
  if Y > Screen.Height-1 then Exit;
  repeat
    if not GetCursorPos(P) then RaiseLastOSError;
    NewX := P.X;
    NewY := P.Y;
    if P.X <> X then
    begin
      if P.X > X then
        NewX := P.X - 1
      else
        NewX := P.X + 1;
    end;

    if P.Y <> Y then
    begin
      if P.Y > Y then
        NewY := P.Y - 1
      else
        NewY := P.Y + 1
    end;
    Sleep (Speed);
    if not SetCursorPos(NewX, NewY) then RaiseLastOSError;
  until (P.X = X) and (P.Y = Y);
end;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接