1. Computing & Technology

Discuss in my forum

What's the word under the mouse cursor in a TRichEdit?

By , About.com Guide

Here's a code to find the word under the mouse cursor in a RichEdit.

The WordInRE string variable holds the word.

Note: you'll need a TRichEdit (name: RichEdit1) on a form (name: Form1), and the code below in the OnMouseMove event handler procedure for RichEdit1.

~~~~~~~~~~~~~~~~~~~~~~~~~
uses
  RichEdit;

var
  WordInRE : string;

procedure TForm1.RichEdit1MouseMove
  (Sender: TObject; Shift: TShiftState; X, Y: Integer) ;
var
   ci, //Character Index
   lix, //Line Index
   co, //Character Offset
   k, j: Integer;
   Pt: TPoint;
   s: string;
begin
   with TRichEdit(Sender) do
   begin
     Pt := Point(X, Y) ;
     ci := Perform(Messages.EM_CHARFROMPOS, 0, Integer(@Pt)) ;
     if ci < 0 then Exit;
     lix := Perform(EM_EXLINEFROMCHAR, 0, ci) ;
     co := ci - Perform(EM_LINEINDEX, lix, 0) ;
     if -1 + Lines.Count < lix then Exit;
     s := Lines[lix];
     Inc(co) ;
k := co;
     while (k > 0) and (s[k] <> ' ') do k:=k-1;
     Inc(co) ;
j := co;
     while (j <= Length(s)) and (s[j] <> ' ') do Inc(j) ;
     WordInRE := Copy(s, k, j - k) ;
   end;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Get the RTF formatting from a RichEdit
« Select ListBox items as mouse hovers over them

©2012 About.com. All rights reserved.

A part of The New York Times Company.