Search code examples
delphicharpositionmessagerichedit

How to get the Character by Point or by index from TRichedit


I have function that returns the index of a character GetCharFromPos(Pt: TPoint): Integer;

now i wanted to get character of that position. like GetCharByIndex(Index: Integer): Char;


Solution

  • The efficient way to do this using pure VCL is to use SelStart, SelLength and SelText.

    function GetCharByIndex(Index: Integer): Char;
    begin    
      RichEdit.SelStart := Index;
      RichEdit.SelLength := 1;
      Result := RichEdit.SelText[1];
    end;
    

    You'll likely want to save away the selection before modifying it, and then restore it once you have read the character.


    This is however a rather messy way to read a character. If you are prepared to use raw Win32 API then you can make use of EM_GETTEXTRANGE.