gpt4 book ai didi

delphi - 如何在Delphi中制作一次性定时器功能(如JavaScript中的setTimeout)?

转载 作者:行者123 更新时间:2023-12-03 14:34:38 28 4
gpt4 key购买 nike

setTimeout对 JavaScript 语言很有帮助。你会如何在delphi中创建这个函数?

SetTimeOut(procedure (Sender: TObject);
begin
Self.Counter := Self.Counter + 1;
end, 200);

最佳答案

我想你可以离开TTimer照原样并尝试使用 SetTimer函数并使用其回调函数。您需要将计时器 ID 及其(匿名)方法存储在某个集合中。由于您没有提到您的 Delphi 版本,我使用了一个简单的类和 TObjectList作为一个集合。

原理很简单,调用 SetTimer 即可指定回调函数的函数,并使用匿名方法将新实例化的系统计时器 ID 存储到集合中。当执行该回调函数时,通过 ID 在集合中找到引发该回调的计时器,杀死它,执行匿名方法并将其从集合中删除。这是示例代码:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Contnrs;

type
TOnTimerProc = reference to procedure;
TOneShotTimer = class
ID: UINT_PTR;
Proc: TOnTimerProc;
end;
procedure SetTimeout(AProc: TOnTimerProc; ATimeout: Cardinal);

type
TForm1 = class(TForm)
Timer1: TTimer;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
TimerList: TObjectList;

implementation

{$R *.dfm}

procedure TimerProc(hwnd: HWND; uMsg: UINT; idEvent: UINT_PTR;
dwTime: DWORD); stdcall;
var
I: Integer;
Timer: TOneShotTimer;
begin
for I := 0 to TimerList.Count - 1 do
begin
Timer := TOneShotTimer(TimerList[I]);
if Timer.ID = idEvent then
begin
KillTimer(0, idEvent);
Timer.Proc();
TimerList.Delete(I);
Break;
end;
end;
end;

procedure SetTimeout(AProc: TOnTimerProc; ATimeout: Cardinal);
var
Timer: TOneShotTimer;
begin
Timer := TOneShotTimer.Create;
Timer.ID := SetTimer(0, 0, ATimeout, @TimerProc);
Timer.Proc := AProc;
TimerList.Add(Timer);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
SetTimeout(procedure
begin
ShowMessage('OnTimer');
end,
1000
);
end;

initialization
TimerList := TObjectList.Create;
TimerList.OwnsObjects := True;

finalization
TimerList.Free;

end.


简化版本(Delphi 2009 以上):

就像@David 的评论所建议的那样,这里的代码与上面相同,只是在一个单独的单元中使用泛型字典。此单元中 SetTimeout 的用法与上面的代码相同:

unit OneShotTimer;

interface

uses
Windows, Generics.Collections;

type
TOnTimerProc = reference to procedure;
procedure SetTimeout(AProc: TOnTimerProc; ATimeout: Cardinal);

var
TimerList: TDictionary<UINT_PTR, TOnTimerProc>;

implementation

procedure TimerProc(hwnd: HWND; uMsg: UINT; idEvent: UINT_PTR;
dwTime: DWORD); stdcall;
var
Proc: TOnTimerProc;
begin
if TimerList.TryGetValue(idEvent, Proc) then
try
KillTimer(0, idEvent);
Proc();
finally
TimerList.Remove(idEvent);
end;
end;

procedure SetTimeout(AProc: TOnTimerProc; ATimeout: Cardinal);
begin
TimerList.Add(SetTimer(0, 0, ATimeout, @TimerProc), AProc);
end;

initialization
TimerList := TDictionary<UINT_PTR, TOnTimerProc>.Create;
finalization
TimerList.Free;

end.

关于delphi - 如何在Delphi中制作一次性定时器功能(如JavaScript中的setTimeout)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468787/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com