unit PalPrimeForm;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

const
  WM_DATA_IN_BUF = WM_APP + 1000;
  MaxMemoLines = 20;

type
  TPalFrm = class(TForm)
    ResultsMemo: TMemo;
    StartButton: TButton;
    StopButton: TButton;
    procedure StartButtonClick(Sender: TObject);
    procedure StopButtonClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    FStringSectInit: boolean;
    FStringBuf: TStringList;
    StringSection: TRTLCriticalSection;
    procedure UpdateButtons;
    procedure HandleNewData(var Message: TMessage); message WM_DATA_IN_BUF;
  public
    { Public declarations }
  end;

var
  PalFrm: TPalFrm;

implementation

uses PrimeThreads;

{$R *.DFM}

procedure TPalFrm.UpdateButtons;
begin
  StopButton.Enabled := FStringSectInit;
  StartButton.Enabled := not FStringSectInit;
end;

procedure TPalFrm.StartButtonClick(Sender: TObject);
begin
  if not FStringSectInit then
  begin
    InitializeCriticalSection(StringSection);
    FStringBuf := TStringList.Create;
    FStringSectInit := true;
    StartThreads(Self, @StringSection, WM_DATA_IN_BUF, FStringBuf);
  end;
  UpdateButtons;
end;

procedure TPalFrm.StopButtonClick(Sender: TObject);
begin
  if FStringSectInit then
  begin
    ResultsMemo.Lines.Add('Please wait...');
    StopThreads;
    ResultsMemo.Lines.Add('Done!');
    FStringBuf.Free;
    FStringBuf := nil;
    DeleteCriticalSection(StringSection);
    FStringSectInit := false;
  end;
  UpdateButtons;
end;

procedure TPalFrm.HandleNewData(var Message: TMessage);
begin
  if FStringSectInit then
  begin
    EnterCriticalSection(StringSection);
    ResultsMemo.Lines.Add(FStringBuf.Strings[0]);
    FStringBuf.Delete(0);
    LeaveCriticalSection(StringSection);
    if ResultsMemo.Lines.Count > MaxMemoLines then
      ResultsMemo.Lines.Delete(0);
  end;
end;

procedure TPalFrm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  StopButtonClick(Self);
end;

end.