02.05.2017, 13:56
|
|
Let Me Show You
|
|
Регистрация: 30.04.2010
Адрес: Северодвинск
Сообщения: 5,426
Версия Delphi: 7, XE5
Репутация: 59586
|
|
На форме 5 меток и кнопка. При нажатии на кнопку стартует поток с незанятой меткой. После завершения потока метка снова освобождается.
Код:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TMyThread = class(TThread)
protected
procedure Execute; override;
public
FLabel: TLabel;
constructor Create(ALabel: TLabel); overload;
end;
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure ThreadTerminate(Sender: TObject);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMyThread }
constructor TMyThread.Create(ALabel: TLabel);
begin
FLabel:=ALabel;
FreeOnTerminate:=True;
inherited Create(False);
end;
procedure TMyThread.Execute;
var
TickCount: Integer;
begin
TickCount:=Random(10)+1;
Synchronize(procedure
begin
FLabel.Caption:=IntToStr(TickCount);
end);
(* do it *)
while TickCount>0 do
begin
Synchronize(procedure
begin
FLabel.Caption:=IntToStr(TickCount);
end);
Dec(TickCount);
Sleep(1000);
end;
Synchronize(procedure
begin
FLabel.Tag:=0;
FLabel.Caption:='stoped';
end);
end;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
Randomize;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
lbl: TLabel;
rslt: Boolean;
begin
rslt:=False;
for i:=1 to 5 do
begin
lbl:=TLabel(FindComponent('Label'+IntToStr(i)));
if lbl.Tag=0 then
begin
lbl.Tag:=$7FFFFFFF;
Button1.Tag:=Button1.Tag+1;
Button1.Caption:=IntToStr(Button1.Tag);
with TMyThread.Create(lbl) do OnTerminate:=ThreadTerminate;
rslt:=True;
Break;
end;
end;
if not rslt then ShowMessage('Oops');
end;
procedure TForm1.ThreadTerminate(Sender: TObject);
begin
Button1.Tag:=Button1.Tag-1;
Button1.Caption:=IntToStr(Button1.Tag);
end;
end.
__________________
Пишу программы за еду.
__________________
|