2006. augusztus 19., szombat

How to get a range of text from a TRichEdit without setting a selection


Problem/Question/Abstract:

How to get a range of text from a TRichEdit without setting a selection

Answer:

Sometimes while using RichEdit you need to get just a part of the text from that control, without setting a selection and using the SelText property. The code below shows the way to do that :

{overrides wrong TTextRange definition in RichEdit.pas}
TTextRange = record
  chrg: TCharRange;
  lpstrText: PAnsiChar;
end;

function REGetTextRange(RichEdit: TRichEdit; BeginPos, MaxLength: Integer): string;
{RichEdit: RichEdit control
BeginPos: absolute  index of first char
MaxLength: maximum chars to retrieve}
var
  TextRange: TTextRange;
begin
  if MaxLength > 0 then
  begin
    SetLength(Result, MaxLength);
    with TextRange do
    begin
      chrg.cpMin := BeginPos;
      chrg.cpMax := BeginPos + MaxLength;
      lpstrText := PChar(Result);
    end;
    SetLength(Result, SendMessage(RichEdit.Handle, EM_GETTEXTRANGE, 0,
      longint(@TextRange)));
  end
  else
    Result := '';
end;

This function can be used to extract a word under the current mouse pointer position:

function RECharIndexByPos(RichEdit: TRichEdit; X, Y: Integer): Integer;
{ function returns absolute character position for given cursor coordinates}
var
  P: TPoint;
begin
  P := Point(X, Y);
  Result := SendMessage(RichEdit.Handle, EM_CHARFROMPOS, 0, longint(@P));
end;

function REExtractWordFromPos(RichEdit: TRichEdit; X, Y: Integer): string;
{ X, Y: point coordinates in rich edit control }
{returns word under current cursor position}
var
  BegPos, EndPos: Integer;
begin
  BegPos := RECharIndexByPos(RichEdit, X, Y);
  if (BegPos < 0) or
    (SendMessage(RichEdit.Handle, EM_FINDWORDBREAK,
    WB_CLASSIFY, BegPos) and (WBF_BREAKLINE or WBF_ISWHITE) < > 0) then
  begin
    result := '';
    exit;
  end;
  if SendMessage(RichEdit.Handle, EM_FINDWORDBREAK,
    WB_CLASSIFY, BegPos - 1) and (WBF_BREAKLINE or WBF_ISWHITE) = 0 then
    BegPos := SendMessage(RichEdit.Handle, EM_FINDWORDBREAK,
      WB_MOVEWORDLEFT, BegPos);
  EndPos := SendMessage(RichEdit.Handle, EM_FINDWORDBREAK,
    WB_MOVEWORDRIGHT, BegPos);
  Result := TrimRight(REGetTextRange(RichEdit, BegPos, EndPos - BegPos));
end;

Nincsenek megjegyzések:

Megjegyzés küldése