以下是“进度”表单的部分代码。
除了 ProgressBars(从代码中删除)之外,它还有一个 TLabel (LblDots),我想更改其中的标题(点数增加)。
在 FormShow/FormClose 中,TDotterThread 被创建和销毁。
问题:
我看到 Synchronize(DoUpdate) 过程仅在程序不做繁重工作时才调用更新标签。
这是进度表:
unit FrmBusy;
interface
uses
System.SyncObjs, Windows, Messages, SysUtils, System.Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TUpdateEvent = procedure of object; // 'of object' to prevent 'Incompatible types: regular procedure and method pointer'
type
TDotterThread = class(TThread) // Thread to update LblDots
private
FTick: TEvent;
FUpdater: TUpdateEvent;
protected
procedure Execute; override;
procedure DoUpdate;
public
constructor Create;
destructor Destroy; override;
property Updater: TUpdateEvent read FUpdater write FUpdater;
procedure Stop;
end;
type
TFormBusy = class(TForm)
LblDots: TLabel;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FShowDots: Boolean;
FDotterThread: TDotterThread;
procedure UpdateDots;
public
property ShowDots: Boolean write FShowDots;
end;
implementation
{$R *.DFM}
procedure TFormBusy.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FShowDots then FDotterThread.Stop; // Calls Terminate and is FreeOnTerminate
end;
procedure TFormBezig.UpdateDots;
var s: String;
begin
s := LblDots.Caption;
if Length(s) = 50 then s := '' else s := s + '.';
LblDots.Caption := s;
Application.ProcessMessages;
end;
procedure TFormBusy.FormShow(Sender: TObject);
begin
LblDots.Caption := '';
if FShowDots then
begin
FDotterThread := TDotterThread.Create;
FDotterThread.Updater := Self.UpdateDots;
FDotterThread.Start;
end;
BringWindowToTop(Self.Handle);
end;
{ TDotterThread }
constructor TDotterThread.Create;
begin
FTick := TEvent.Create(nil, True, False, '');
FreeOnTerminate := true;
inherited Create(true); // Suspended
end;
destructor TDotterThread.Destroy;
begin
FTick.Free;
inherited;
end;
procedure TDotterThread.DoUpdate;
begin
if Assigned(FUpdater) then FUpdater;
end;
procedure TDotterThread.Execute;
begin
while not Terminated do
begin
FTick.WaitFor(1000);
Synchronize(DoUpdate);
end;
end;
procedure TDotterThread.Stop;
begin
Terminate;
FTick.SetEvent;
end;
end.
该表单的调用和创建方式如下:
procedure TFrmTest.FormCreate(Sender: TObject);
begin
FFormBusy := TFormBusy.Create(nil);
end;
procedure TFrmTest.FormDestroy(Sender: TObject);
begin
FFormBusy.Free;
end;
procedure TFrmTest.BtnCompareClick(Sender: TObject);
begin
FrmTest.FFormBusy.ShowDots := true;
FrmTest.FFormBusy.Show;
FrmTest.FFormBusy.Update label/progress bar
DoHeavyWork1();
FrmTest.FFormBusy.Update label/progress bar
DoHeavyWork2();
etc.
end;
我究竟做错了什么?
TIA