delphi - SetCursorPos 故障?

标签 delphi winapi cursor cursor-position

我想在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,但这是为什么?

最佳答案

你的代码被卡住了,因为在重复循环中,条件

until (P.X = X) and (P.Y = Y);

当您传递值 X=0 和 Y=Screen.Height 时,永远不会满足,因此您必须修改循环以仅传递有效的屏幕坐标值

  for X := 0 to Screen.Width-1 do
    for Y := 0 to Screen.Height-1 do
      MoveMouse (X, Y, 1); 

您还可以改进检查GetCursorPos结果的方法。和 SetCursorPos功能。

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;

关于delphi - SetCursorPos 故障?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14310040/

相关文章:

Delphi 7 继续使用旧的过时的形式

delphi - 关于delphi中调用静态类的不同方式

delphi - 在 Delphi 6 应用程序中从 FOURCC ID 查找压缩机/过滤器友好名称?

c - 像 Process Hacker 一样卸载 dll

windows - 注册一个全局钩子(Hook),检测鼠标是否拖动文件/文本

安卓 ListView : Application did not close the cursor or database object

Android Studio 光标显示错误

delphi - Datasnap 是否适合最多 8 人的非通信密集型双向多人游戏?

c++ - 如何在 Win32 API 的对话框中显示自定义消息?

带有 slick 的 Oracle ref cursor