线程的变量问题,请教大侠! VCL组件开发及应用http://www.delphi2007.net/DelphiVCL/html/delphi_20061222154739181.html
主进程中有一个panel对象,创建一个进程thread.create(panel),传入panel对象,然后在进程thread中修改panel的一些属性,但是窗体上panel并没有发生相应的改变,不知道是什么原因,请高手指点!
谢谢!
注明:如果同样的代码,写在主进程中就完全可以,但写在线程中就不起作用。
{ 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.