Find text in a Delphi TMemo

Posted by Andri Mar on June 05, 2001

I've made a onFind code for a TMemo and it doesn't work and I don't know why. Here is the code:

procedure TForm1.FindDialog1Find(Sender: TObject);
var
 Buff, P, FT : PChar;
 BuffLen : Word;
begin
 with Sender as TFindDialog do
  begin
   GetMem(FT, Length(FindText) + 1);
   StrPCopy(FT, FindText);
   BuffLen := Memo1.GetTextLen + 1;
   GetMem(Buff, BuffLen);
   P := Buff + Memo1.SelStart + Memo1.SelLength;
   P := StrPos(P, FT);
   if P = NIL then MessageBeep(0)
   else
    begin
     Memo1.SelStart := P - Buff;
     Memo1.SelLength := Length(FindText);
    end;
    FreeMem(FT, Length(FindText) + 1);
    FreeMem(Buff, BuffLen);
  end;
end;

Anyone got a clu?
Andri Mar Jónsson

Re: webmaster Guido on June 10, 2001

There is a line missing from your code. Try it like this :)

GetMem(Buff, BuffLen);
Memo1.GetTextBuf(Buff, BuffLen); // add this line

The code above is typical for Delphi 1, using PChars and buffers. Starting from Delphi 2, strings are not limited anymore to 256 characters, and you can use the Memo.Text property. This gives:

procedure TForm1.FindDialog1Find(Sender: TObject);
var
  TextToFind, Txt: string;
  StartPos, TxtLen, FoundPos: Integer;
begin
  TextToFind := (Sender as TFindDialog).FindText;
  StartPos := Memo1.SelStart + Memo1.SelLength + 1;
  TxtLen := Length(Memo1.Text) - StartPos + 1;
  Txt := Copy(Memo1.Text, StartPos, TxtLen);
  FoundPos := Pos(TextToFind, Txt);
  if FoundPos = 0 then ShowMessage('Not found')
  else begin
    Memo1.HideSelection := False; // allways show selection
    Memo1.SelStart := StartPos + FoundPos - 2;
    Memo1.SelLength := Length(TextToFind);
  end;
end;