历经千辛万苦阿(凌晨哦),下面的代码演示怎么从线程里面发消息到主窗口,其实只是一个地址而已,问题都不大,几个大项目都这样处理的。可以解决。至于怎么连接Socket都放可以在线程里面处理了,希望对你有帮助
Unit2.pas
unit Unit2;
interface
uses
Classes, Messages, windows;
const
WM_Info = WM_USER + 100;
type
TInfo = record
nPos, nTotal: Integer;
end;
TMyThread = class(TThread)
private
{ Private declarations }
FMainHandle : THandle;
nPos : Integer;
nTotal : Integer;
protected
procedure Execute;
override;
public
constructor Create(CreateSuspended: Boolean;
_MainHandle : THandle;
_Total: Integer);reintroduce;
end;
implementation
{ TMyThread }
constructor TMyThread.Create(CreateSuspended: Boolean;
_MainHandle: THandle;
_Total: Integer);
begin
Inherited Create(CreateSuspended);
FMainHandle := _MainHandle;
nPos := 0;
nTotal := _Total;
end;
procedure TMyThread.Execute;
var
p : TInfo;
begin
while not Terminateddo
begin
if nPos < nTotal then
begin
p.nPos := nPos;
p.nTotal := nTotal;
Inc(nPos);
if FMainHandle <> 0 then
SendMessage(FMainHandle, WM_Info, 0, Integer(@P));// 向主窗口发送消息
end;
end;
end;
end.
unit1.pas
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, unit2, StdCtrls, ComCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ProgressBar1: TProgressBar;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
Thread : TMyThread;
public
{ Public declarations }
procedure Info(var msg : TMessage);
message WM_Info;
constructor Create(AOwner : TComponent);override;
destructor Destroy;
override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
constructor TForm1.Create(AOwner: TComponent);
begin
inherited;
Thread := TMyThread.Create(True, Self.Handle, 100000);
end;
destructor TForm1.Destroy;
begin
Thread.Terminate;
inherited;
end;
procedure TForm1.Info(var msg: TMessage);
var
P : TInfo;
begin
if msg.Msg = WM_Info then
begin
// 先判断消息类型
p := TInfo(Pointer(msg.LParam)^);// 取出对应地址里面的东西
ProgressBar1.Max := p.nTotal;// 更新界面
ProgressBar1.Min := 0;
ProgressBar1.Position := p.nPos;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Thread.Suspended then
Thread.Resume
else
Thread.Suspend;
end;
end.