搜索并选择找到的文本内容
下面的代码搜索并选定找到的文本内容:
procedure SearchText(wnd: HWND; Text: pchar; Down, Sense, Whole: Bool);
var
REdit : HWND;
Flags : integer;
FindRec : TFindText;
FindPos : integer;
ErrMsg : array[0..4096]of Char;
begin
REdit := GetDlgItem(wnd,IDC_EDIT);
if(REdit <> 0) then begin
SendMessage(REdit,EM_EXGETSEL,0,LPARAM(@FindRec.chrg));
if(not Down) then FindRec.chrg.cpMin := FindRec.chrg.cpMax - 1
else FindRec.chrg.cpMin := FindRec.chrg.cpMax;
FindRec.chrg.cpMax := -1;
FindRec.lpstrText := Text;
Flags := 0;
if(Down) then Flags := FR_DOWN;
if(Sense) then Flags := Flags or FR_MATCHCASE;
if(Whole) then Flags := Flags or FR_WHOLEWORD;
FindPos := SendMessage(REdit,EM_FINDTEXT,
Flags,LPARAM(@FindRec));
if(FindPos > 0) then begin
FindRec.chrg.cpMin := FindPos;
FindRec.chrg.cpMax := FindPos + lstrLen(Text);
SendMessage(REdit,EM_EXSETSEL,0,LPARAM(@FindRec.chrg));
end else begin
lstrcpy(ErrMsg,pchar('"' + Text + '"'));
lstrcat(ErrMsg,CANNOT_FINDTEXT);
MessageBox(wnd,ErrMsg,APPNAME,MB_ICONINFORMATION);
end;
end;
end;
function SearchAndReplaceText(wnd: HWND; const OldText, NewText: WideString;
Down, Sense, Whole: Bool): Integer;
const
FR_DOWN = 1;
var
Flags : integer;
FindRec : TFindTextExW;
FindPos : integer;
Ranged : Boolean;
begin
Result := 0;
Ranged := False;
if wnd = 0 then Exit;
FillChar(FindRec, SizeOf(FindRec), 0);
SendMessage(wnd, EM_EXGETSEL, 0, LPARAM(@FindRec.chrg));
Ranged := FindRec.chrg.cpMin <> FindRec.chrg.cpMax;
if not Ranged then
begin
if down then
FindRec.chrg.cpMin := FindRec.chrg.cpMax + 1;
FindRec.chrg.cpMax := -1;
end
else if not Down then
begin
FindPos := FindRec.chrg.cpMax;
FindRec.chrg.cpMax := FindRec.chrg.cpMin;
FindRec.chrg.cpMin := FindPos;
end;
FindRec.lpstrText := PWideChar(OldText);
Flags := 0;
if Down then Flags := FR_DOWN;
if Sense then Flags := Flags or FT_MATCHCASE;
if Whole then Flags := Flags or FT_WHOLEWORD;
FindPos := SendMessageW(wnd, EM_FINDTEXTEXW, Flags, LPARAM(@FindRec));
while (FindPos > 0) do
begin
Inc(Result);
if Ranged then
if Down then
Inc(FindRec.chrg.cpMax, Length(NewText) - Length(OldText))
else
Inc(FindRec.chrg.cpMin, Length(NewText) - Length(OldText));
SendMessage(wnd, EM_EXSETSEL, 0, LPARAM(@FindRec.chrgText));
SendMessageW(wnd, EM_REPLACESEL, Ord(True), LPARAM(PWideChar(NewText)));
FindPos := SendMessageW(wnd, EM_FINDTEXTEXW, Flags, LPARAM(@FindRec));
end;
if Ranged then
SendMessage(wnd, EM_EXSETSEL, 0, LPARAM(@FindRec.chrg));
end;