1

有没有办法在string grid使用查找对话框中进行文本搜索?我需要找到一个文本并像通常在找到文本时一样突出显示它的背景。

谢谢!

4

1 回答 1

8

像这样:

procedure TForm1.FormClick(Sender: TObject);
begin
  FindDialog1.Execute(Handle)
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FindDialog1.Options := [frDown, frHideWholeWord, frHideUpDown];
end;

procedure TForm1.FindDialog1Find(Sender: TObject);
var
  CurX, CurY, GridWidth, GridHeight: integer;
  X, Y: integer;
  TargetText: string;
  CellText: string;
  i: integer;
  GridRect: TGridRect;
begin
  CurX := StringGrid1.Selection.Left + 1;
  CurY := StringGrid1.Selection.Top;
  GridWidth := StringGrid1.ColCount;
  GridHeight := StringGrid1.RowCount;
  Y := CurY;
  X := CurX;
  if frMatchCase in FindDialog1.Options then
    TargetText := FindDialog1.FindText
  else
    TargetText := AnsiLowerCase(FindDialog1.FindText);
  while Y < GridHeight do
  begin
    while X < GridWidth do
    begin
      if frMatchCase in FindDialog1.Options then
        CellText := StringGrid1.Cells[X, Y]
      else
        CellText := AnsiLowerCase(StringGrid1.Cells[X, Y]);
      i := Pos(TargetText, CellText) ;
      if i > 0 then
      begin
        GridRect.Left := X;
        GridRect.Right := X;
        GridRect.Top := Y;
        GridRect.Bottom := Y;
        StringGrid1.Selection := GridRect;
        Exit;
      end;
      inc(X);
    end;
    inc(Y);
    X := StringGrid1.FixedCols;
  end;
end;

此代码可以轻松扩展以支持向后搜索(“向上”),您可能还希望实现“匹配整个单词”功能。

也许您只想选择匹配的文本,而不是整个单元格?然后做

  if i > 0 then
  begin
    GridRect.Left := X;
    GridRect.Right := X;
    GridRect.Top := Y;
    GridRect.Bottom := Y;
    StringGrid1.Selection := GridRect;
    GetParentForm(StringGrid1).SetFocus;
    StringGrid1.SetFocus;
    StringGrid1.EditorMode := true;
    TCustomEdit(StringGrid1.Components[0]).SelStart := i - 1;
    TCustomEdit(StringGrid1.Components[0]).SelLength := length(TargetText);
    Exit;
  end;

反而。但这会从查找对话框中窃取焦点,因此用户将无法按 Return 键选择下一个匹配项,这可能很烦人。

于 2011-08-10T10:31:49.277 回答