Creando un Delay en delphi (o Sleep o Pause)

Desde Torry's Delphi Pages, podemos encontrar una buena implementación de la mano de Simon Grossenbacher. Estas funciones nos permiten crear retardos y pausas sin que la CPU llegue hasta el 100%. Están probadas y testadas y yo las utilizo en mis aplicaciones. Aquí os dejo el código fuente:





// 1. Delay

procedure Delay(dwMilliseconds: Longint);
var
iStart, iStop: DWORD;
begin
iStart := GetTickCount;
repeat
iStop := GetTickCount;
Application.ProcessMessages;
Sleep(1);
until (iStop - iStart) >= dwMilliseconds;
end;

// 2. Delay con API

procedure Delay(msecs: Longint);
var
targettime: Longint;
Msg: TMsg;
begin
targettime := GetTickCount + msecs;
while targettime > GetTickCount do
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
if Msg.message = WM_QUIT then
begin
PostQuitMessage(Msg.wParam);
Break;
end;
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;

// 3. Sleep

{
The Sleep function suspends the execution of the current
thread for a specified interval.
}

Sleep(dwMilliseconds: Word);


// 4. Combined Delay

{
Including the Sleep in the loop prevents the app from hogging
100% of the CPU for doing practically nothing but running around the loop.
}

procedure PauseFunc(delay: DWORD);
var
lTicks: DWORD;
begin
lTicks := GetTickCount + delay;
repeat
Sleep(100);
Application.ProcessMessages;
until (lTicks <= GetTickCount) or Application.Terminated;
end;

// 5. more resource sparing:

procedure Delay(Milliseconds: Integer);
var
Tick: DWORD;
Event: THandle;
begin
Event := CreateEvent(nil, False, False, nil);
try
Tick := GetTickCount + DWORD(Milliseconds);
while (Milliseconds > 0) and
(MsgWaitForMultipleObjects(1, Event, False, Milliseconds,
QS_ALLINPUT) <> WAIT_TIMEOUT) do
begin
Application.ProcessMessages;
Milliseconds := Tick - GetTickCount;
end;
finally
CloseHandle(Event);
end;
end;




Comments

Popular Posts