Search thru a memo in Delphi?

冷暖自知 提交于 2020-01-13 09:35:10

问题


Can anybody give me some simple code that would give me the ability to search a simple string in a memo and have it highlighted in the memo after being found?


回答1:


This search allows for document wrap, case (in)sensitive search and searching from cursor position.

type
  TSearchOption = (soIgnoreCase, soFromStart, soWrap);
  TSearchOptions = set of TSearchOption;


function SearchText(
    Control: TCustomEdit; 
    Search: string; 
    SearchOptions: TSearchOptions): Boolean;
var
  Text: string;
  Index: Integer;
begin
  if soIgnoreCase in SearchOptions then
  begin
    Search := UpperCase(Search);
    Text := UpperCase(Control.Text);
  end
  else
    Text := Control.Text;

  Index := 0;
  if not (soFromStart in SearchOptions) then
    Index := PosEx(Search, Text, 
         Control.SelStart + Control.SelLength + 1);

  if (Index = 0) and 
      ((soFromStart in SearchOptions) or 
       (soWrap in SearchOptions)) then
    Index := PosEx(Search, Text, 1);

  Result := Index > 0;
  if Result then
  begin
    Control.SelStart := Index - 1;
    Control.SelLength := Length(Search);
  end;
end;

You can set HideSelection = False on the memo to show the selection even if the memo isn't focussed.

Use like this:

  SearchText(Memo1, Edit1.Text, []);

Allows searching edits as well.




回答2:


  function TForm1.FindText( const aPatternToFind: String):Boolean;
  var
    p: Integer;
  begin
    p := pos(aPatternToFind, Memo1.Text);
    Result :=  (p > 0);
    if Result then
      begin
        Memo1.SelStart := p;
        Memo1.SelLength := Length(aPatternToFind);
        Memo1.SetFocus; // necessary so highlight is visible
      end;
  end;

This does NOT search across lines if WordWrap is true.



来源:https://stackoverflow.com/questions/4232709/search-thru-a-memo-in-delphi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!