unit SelStart;

interface

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

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    FindDialog1: TFindDialog;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FindDialog1Find(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  FindDialog1.Execute;
end;

// BeginExample: SelStart
// Method: Controls.TWinControl.SetFocus
// Property: StdCtrls.TCustomEdit.SelStart
// Property: StdCtrls.TCustomEdit.SelLength
// Routine: System.Length
// Routine: System.Break

// BeginCode
{
The following OnFind event handler searches a memo component
for the text specified in the FindText property of a find
dialog component. If found, the first occurrence of the text
in Memo1 is selected. The code uses the Pos function to
compare strings, and stores the number of characters to skip
when determining the selection position in the SkipChars
variable. Because there is no handling of case, whole word,
or search direction in this algorithm, it is assumed that
the Options property of FindDialog1 is set to
[frHideMatchCase, frHideWholeWord, frHideUpDown].
} 
procedure TForm1.FindDialog1Find(Sender: TObject);
var
  I, J, PosReturn, SkipChars: Integer;
begin
  for I := 0 to Memo1.Lines.Count do
  begin
    PosReturn := Pos(FindDialog1.FindText,Memo1.Lines[I]);
    if PosReturn <> 0 then {found!}
    begin
      SkipChars := 0;
      for J := 0 to I - 1 do
        SkipChars := SkipChars + Length(Memo1.Lines[J]);
      SkipChars := SkipChars + (I*2);
      SkipChars := SkipChars + PosReturn - 1;
      Memo1.SetFocus;
      Memo1.SelStart := SkipChars;
      Memo1.SelLength := Length(FindDialog1.FindText);
      Break;
    end;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
const Path = 'country.list';
begin
  Memo1.Lines.LoadFromFile(Path);
end;
// EndCode
// EndExample: SelStart
end.
