Author: Jonas Bilinkevicius
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 :
1
2 {overrides wrong TTextRange definition in RichEdit.pas}
3 TTextRange = record
4 chrg: TCharRange;
5 lpstrText: PAnsiChar;
6 end;
7
8 function REGetTextRange(RichEdit: TRichEdit; BeginPos, MaxLength: Integer): string;
9 {RichEdit: RichEdit control
10 BeginPos: absolute index of first char
11 MaxLength: maximum chars to retrieve}
12 var
13 TextRange: TTextRange;
14 begin
15 if MaxLength > 0 then
16 begin
17 SetLength(Result, MaxLength);
18 with TextRange do
19 begin
20 chrg.cpMin := BeginPos;
21 chrg.cpMax := BeginPos + MaxLength;
22 lpstrText := PChar(Result);
23 end;
24 SetLength(Result, SendMessage(RichEdit.Handle, EM_GETTEXTRANGE, 0,
25 longint(@TextRange)));
26 end
27 else
28 Result := '';
29 end;
This function can be used to extract a word under the current mouse pointer
position:
30
31 function RECharIndexByPos(RichEdit: TRichEdit; X, Y: Integer): Integer;
32 { function returns absolute character position for given cursor coordinates}
33 var
34 P: TPoint;
35 begin
36 P := Point(X, Y);
37 Result := SendMessage(RichEdit.Handle, EM_CHARFROMPOS, 0, longint(@P));
38 end;
39
40 function REExtractWordFromPos(RichEdit: TRichEdit; X, Y: Integer): string;
41 { X, Y: point coordinates in rich edit control }
42 {returns word under current cursor position}
43 var
44 BegPos, EndPos: Integer;
45 begin
46 BegPos := RECharIndexByPos(RichEdit, X, Y);
47 if (BegPos < 0) or
48 (SendMessage(RichEdit.Handle, EM_FINDWORDBREAK,
49 WB_CLASSIFY, BegPos) and (WBF_BREAKLINE or WBF_ISWHITE) < > 0) then
50 begin
51 result := '';
52 exit;
53 end;
54 if SendMessage(RichEdit.Handle, EM_FINDWORDBREAK,
55 WB_CLASSIFY, BegPos - 1) and (WBF_BREAKLINE or WBF_ISWHITE) = 0 then
56 BegPos := SendMessage(RichEdit.Handle, EM_FINDWORDBREAK,
57 WB_MOVEWORDLEFT, BegPos);
58 EndPos := SendMessage(RichEdit.Handle, EM_FINDWORDBREAK,
59 WB_MOVEWORDRIGHT, BegPos);
60 Result := TrimRight(REGetTextRange(RichEdit, BegPos, EndPos - BegPos));
61 end;
|