Einzelnen Beitrag anzeigen

NicoDE
(Gast)

n/a Beiträge
 
#11

Re: Unit in Thread packen?!

  Alt 16. Dez 2005, 13:53
Delphi-Quellcode:
unit Unit1;

interface

uses
  Windows, SysUtils, Classes, Controls, Forms, StdCtrls;

type
  TScanThread = class(TThread)
  private
    FList: TStringList;
  public
    constructor Create(CreateSuspended: Boolean); virtual;
    destructor Destroy(); override;
    procedure Execute(); override;
    property List: TStringList read FList;
  end;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    ScanTerminated: Boolean;
    procedure OnScanTerminated(Sender: TObject);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  ActiveConnections;

{$R *.dfm}

{ TScanThread }

constructor TScanThread.Create(CreateSuspended: Boolean);
begin
  // inherited (angehalten)
  inherited Create(True);
  // private Variablen initialisieren
  FList := TStringList.Create();
  // fortsetzen falls gefordert
  if not CreateSuspended then
    Resume();
end;

destructor TScanThread.Destroy();
begin
  // private Variablen freigeben
  FList.Free();
  // inherited
  inherited Destroy();
end;

procedure TScanThread.Execute();
begin
  // was auch immer...
  ScanNetworkResources(RESOURCETYPE_DISK, RESOURCEDISPLAYTYPE_GENERIC, FList);
end;

{ TForm1 }

procedure TForm1.OnScanTerminated(Sender: TObject);
begin
  // scan beendet
  ScanTerminated := True;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  // Button deaktivieren (Schutz for Doppelklick)
  Button1.Enabled := False;
  try
    // ScanThread erzeugen (angehalten)
    with TScanThread.Create(True) do
    try
      // Beim Beenden nicht freigeben (wir brauchen Zugriff auch die Liste)
      FreeOnTerminate := False;
      // ScanTerminated initialisieren
      ScanTerminated := False;
      // Ereignisroutine setzen
      OnTerminate := OnScanTerminated;
      // nun den Thread arbeiten lassen
      Resume();
      // Warten bis der Thread fertig ist
      while not ScanTerminated do
        // Solange die GUI reagieren lassen...
        Application.ProcessMessages();
      // Ergebnisliste holen
      ListBox1.Items.Text := List.Text;
    finally
      // Thread freigeben
      Free();
    end;
  finally
    // Button reaktivieren
    Button1.Enabled := True;
  end;
end;

end.
  Mit Zitat antworten Zitat