Delphi SetCursorPos故障?
我想在delphi中编写一个程序来模拟以特定速度移动的鼠标指针(类似于AutoIT MouseMove函数)。 要么我的代码错误,要么SetCursorPos在调用太多次后出现故障。 以下是我的功能:Delphi SetCursorPos故障?,delphi,winapi,cursor,cursor-position,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 <
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;
由于某种原因,鼠标指针在某个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);
还可以改进检查和函数结果的方法
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;
程序移动鼠标(X,Y,速度:Word);
变量
P:TPoint;
NewX:整数;
NewY:整数;
开始
如果X>Screen.Width-1,则退出;
如果Y>屏幕高度-1,则退出;
重复
如果不是GetCursorPos(P),则为RAISELASTERROR;
NewX:=P.X;
NewY:=P.Y;
如果P.X那么
开始
如果P.X>X,那么
NewX:=P.X-1
其他的
NewX:=P.X+1;
结束;
如果P.Y.那么
开始
如果P.Y>Y,那么
NewY:=P.Y-1
其他的
NewY:=P.Y+1
结束;
睡眠(速度);
如果未设置CursorPos(NewX,NewY),则为RAISELASTERROR;
直到(P.X=X)和(P.Y=Y);
结束;
就是这样!非常感谢你!
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;