【问题标题】:Delphi - Get the whole word where the caret is in a memoDelphi - 获取备忘录中插入符号的整个单词
【发布时间】:2011-06-14 05:25:03
【问题描述】:

如果插入符号直接相邻或在备忘录中的单词中,我需要能够选择 TMemo 的整个单词。

考虑以下内容(其中 | 是插入符号)

Here is some text| = 选择text

Here is so|me text = 选择some

|Here is some text = 选择Here

Here is some text | = 选择''

【问题讨论】:

    标签: delphi selection memo


    【解决方案1】:

    用 cmets 检查此代码以解释其工作原理。

    function SelectWordUnderCaret(AMemo:TMemo):string;
    var
       Line    : Integer;
       Column  : Integer;
       LineText: string;
       InitPos : Integer;
       EndPos  : Integer;
    begin
       //Get the caret position
       Line   := AMemo.Perform(EM_LINEFROMCHAR,AMemo.SelStart, 0) ;
       Column := AMemo.SelStart - AMemo.Perform(EM_LINEINDEX, Line, 0) ;
       //Validate the line number
       if AMemo.Lines.Count-1 < Line then Exit;
    
       //Get the text of the line
       LineText := AMemo.Lines[Line];
    
       Inc(Column);
       InitPos := Column;
       //search the initial position using the space symbol as separator
       while (InitPos > 0) and (LineText[InitPos] <> ' ') do Dec(InitPos);
       Inc(Column);
    
       EndPos := Column;
       //search the final position using the space symbol as separator
       while (EndPos <= Length(LineText)) and (LineText[EndPos] <> ' ') do Inc(EndPos);
    
       //Get the text
       Result := Trim(Copy(LineText, InitPos, EndPos - InitPos));
    
       //Finally select the text in the Memo
       AMemo.SelStart  := AMemo.Perform(EM_LINEINDEX, Line, 0)+InitPos;
       AMemo.SelLength := Length(Result);
    end;
    

    你可以这样使用

    procedure TForm1.Button1Click(Sender: TObject);
    begin
         Caption := SelectWordUnderCaret(Memo1) ;
    end;
    

    【讨论】:

    • 要获得插入符号的位置,您可以使用 AMemo.CaretPos
    • +1。这个算法非常适合实际使用,也就是说,如果你真的想将它用于 TMemo:它只读取所需的文本行,而不是像我的那样读取整个备忘录。它可能启用了 unicode,因为它测试空格,这是 OP 需要考虑的事情(什么构成单词?)。
    • 太棒了,谢谢 RRUZ。我有一个与 Cosmins 类似的,但它看起来更有效。
    • RangeCheck 有空行时出错。您需要更改此行: while (InitPos > 0) and (InitPos ' ')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多