Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Lazarus Pascal - A quick and easy way to add a search function to a TMemo

1 Posts
1 Users
0 Reactions
1,929 Views
 Hans
(@hans)
Famed Member Admin
Joined: 11 years ago
Posts: 2796
Topic starter  

I just wanted a quick and easy search function for a TMemo (Memo1) - with the option to jump from one result to another and highlighting the [active] result.
This is based on this example in the Lazarus Wiki - just posting it here with minor modifications and for my own reference.

So for this I added a TEdit (Edit1, enter search criteria) and a TButton (Button1) to my form.

...
Uses ... , StrUtils, LazUTF8;

...
function TForm1.FindInMemo(AString: String; StartPos: Integer): Integer;
begin
  Result := PosEx(AString, Memo1.Text, StartPos);

  if Result > 0 then
    begin
      Memo1.SelStart  := UTF8Length(PChar(Memo1.Text), Result - 1);
      Memo1.SelLength := Length(AString);
      Memo1.SetFocus;
    end;
end;

procedure TForm1.Button1Click(Sender: TObject);
const
  SearchStart : Integer = 0;
  SearchStr   : string = '';
begin
  if SearchStr <> Edit1.Text then
    begin
      SearchStart := 0;
      SearchStr := Edit1.Text;
    end;

  SearchStart := FindInMemo(SearchStr, SearchStart + 1);

  if SearchStart = 0 then beep;
end;                                 

 

Obviously the onClick event of the button needs to be tied to the Button1Click() procedure.

Next thing I did was create a popup menu for the TMemo so I could tie a key combination to finding the next result (Mac: Command+G, Windows/Linux: F3).


   
ReplyQuote
Share: