有没有简单的代码可以让我在备忘录中搜索一个简单的字符串,并在找到后将其高亮显示?
这个搜索功能允许文档环绕、大小写敏感搜索和从光标位置开始搜索。
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;
如果设置文本框的HideSelection属性为False,则即使该文本框失去焦点,也会显示选择文本。
使用方法如下:
SearchText(Memo1, Edit1.Text, []);
还可以搜索编辑内容。
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;
如果WordWrap为true,则此功能不会跨行搜索。
TStrings.Text
中搜索而不是 TStrings.Strings
是非常昂贵的,实际上是 2×N。 - Free Consulting