用线程下载,线程代码如下:
unit ThrDown;
interface
uses
Classes,StdCtrls,Windows,Dialogs,SysUtils,wininet,UrlMon;
var
CS:TRTLCriticalSection; //定义全局临界区
type
T1 = class(TThread)
private
TmpS1,TmpS2: string;
protected
procedure Execute; override;
public
constructor Create(S1,S2: string);
end;
implementation
uses Unit1;
{ T1 }
constructor T1.Create(S1,S2: string);
begin
TmpS1 :=S1;
TmpS2 :=S2;
FreeOnTerminate := True; // 自动删除
InitializeCriticalSection(CS); //初始化临界区
inherited Create(False); // 直接运行
end;
function DownloadFile(Source, Dest: string): Boolean;
begin
try
Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;
except
Result := False;
end;
end;
procedure T1.Execute;
begin
EnterCriticalSection(cs); //进入临界区
DownloadFile(TmpS1,TmpS2);
LeaveCriticalSection(CS); //退出临界区
end;
end.
不过最好引用这下载之前定时检查网络通断情况,不然网络意外会很久没有回应的;我是靠检查百度网站来判断网络的:
uses wininet, ThrDown;
function IsInternet: Boolean;
begin
if InternetCheckConnection('http://www.baidu.com/',1,0) then
Result := True
else
Result := False;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
fl,ts: string;
begin
if IsInternet() then
begin
for i := 0 to 20 do
begin
fl:=trim(inttostr(i))+'.txt';
ts1:=.....;
Thread1 := T1.Create(ts1,fl);
Thread1.OnTerminate := ThreadExit;
end;
end;
end;