【问题标题】:How to scroll to the 'found' word that the user has entered in the finddialog box如何滚动到用户在查找对话框中输入的“找到”单词
【发布时间】:2016-04-04 00:36:15
【问题描述】:

我对一个包含查找对话框的 delphi 表单进行了丰富的编辑。用户输入要找到的单词,程序正确地突出显示“找到”的单词——这很好用。然而,我想要的是让程序滚动,以便找到的单词的第一次出现出现在 Richedit 框中的第一行。如果用户然后单击“下一步”(查找对话框),则滚动继续,以便单词的下一个出现出现在第一行,依此类推。有谁能帮帮我吗?

procedure tform3.FindDialog1Find(Sender: TObject);
var
  sText: string;
  StartFrom, FoundPos: integer;
begin
  { If saved position is 0, this must be a "Find First" operation. }
  if PreviousFoundPos = 0 then
    { Reset the frFindNext flag of the FindDialog }
    findDialog1.Options := findDialog1.Options - [frFindNext];

  if not (frFindNext in FindDialog1.Options) then begin // is it a Find "First" ?
    sText := Richedit1.Text;
    StartFrom := 1;
  end
  else begin // it's a Find "Next"
    { Calculate from where to start searching:
      start AFTER the end of the last found position. }
    StartFrom := PreviousFoundPos + Length(FindDialog1.Findtext);
    { Get text from the RichEdit, starting from StartFrom }
    sText := Copy(Richedit1.Text, StartFrom, Length(Richedit1.Text) - StartFrom + 1);
  end;

  if frMatchCase in FindDialog1.Options then   // case-sensitive search?
    { Search position of FindText in sText.
      Note that function Pos() is case-sensitive. }
    FoundPos := Pos(FindDialog1.FindText, sText)
  else
    { Search position of FindText, converted to uppercase,
      in sText, also converted to uppercase        }
    FoundPos := Pos(UpperCase(FindDialog1.FindText), UpperCase(sText));

  if FoundPos > 0 then begin
    { If found, calculate position of FindText in the RichEdit }
    PreviousFoundPos := FoundPos + StartFrom - 1;
    { Highlight the text that was found }
    RichEdit1.SelStart := PreviousFoundPos - 1;
    RichEdit1.SelLength := Length(FindDialog1.FindText);
    RichEdit1.SetFocus;
  end
  else
    ShowMessage('Could not find "' + FindDialog1.FindText + '"');
end;

【问题讨论】:

  • 谢谢 NineBerry。这完美地工作。天知道我要花多长时间才能弄清楚(如果有的话!)。
  • 问题与对话框无关,只是滚动控件。 FWIW,您在文本中搜索的代码效率不高。你应该得到控制来完成这项工作。
  • 另外,如果您觉得问题已经得到解答,您应该接受最佳答案:meta.stackexchange.com/questions/5234/…

标签: delphi trichedit


【解决方案1】:

您可以使用以下代码滚动到 TRichEdit 控件中的光标位置:

RichEdit1.SelStart := PreviousFoundPos - 1;
RichEdit1.SelLength := Length(FindDialog1.FindText);
RichEdit1.SetFocus;   

// Now scroll to the current cursor position 
RichEdit1.Perform(EM_SCROLLCARET, 0, 0);

这会将 Windows 消息 EM_SCROLLCARET 发送到控件,这将使控件滚动到当前光标位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 2022-01-10
    • 1970-01-01
    • 2017-10-13
    相关资源
    最近更新 更多