注明:如果同样的代码,写在主进程中就完全可以,但写在线程中就不起作用。
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure qaw.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; }注意和VCL的同步
unit Unit1;
interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Panel1: TPanel; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; twudi=class(TThread) private Fpanel : TPanel; fs : string; procedure SetPC; protected procedure Execute; override; public constructor Create(pn : TPanel); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin twudi.Create(Panel1); end; { twudi } constructor twudi.Create(pn: TPanel); begin Fpanel := pn; // FreeOnTerminate := true; inherited Create(false); end; procedure twudi.Execute; var i : integer; begin Fpanel.Align := alLeft; for i := 0 to 10000 do begin fs := IntToStr(i); Synchronize(SetPC); end; end; procedure twudi.SetPC; begin Fpanel.Caption := fs; end; end.在同步的时候,建议不要用Synchronize, 因为Synchronize回暂停现在的线程。建议用消息传递同步信息。
一个用消息的例子:
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Panel1: TPanel; Edit1: TEdit; procedure Button1Click(Sender: TObject); private public { Public declarations } end; twudi=class(TThread) private Fedit : TEdit; protected procedure Execute; override; public constructor Create(ed : TEdit); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin twudi.Create(Edit1); end; { twudi } constructor twudi.Create(ed: TEdit); begin Fedit := ed; inherited create(False); end; procedure twudi.Execute; var i : integer; begin FreeOnTerminate := true; for i := 0 to 10000 do SendMessage(Fedit.Handle,WM_SETTEXT,0,integer(pchar(inttostr(i)))); end; end.