Max Smith
Max Smith

Reputation: 405

How to set caret position by right mouse button click for TRichEdit?

When I right-click a word in a RichEdit control, I want the cursor to be positioned inside that word the way it happens with left mouse button click.

Is it possible to achieve?

Upvotes: 1

Views: 1277

Answers (2)

Max Smith
Max Smith

Reputation: 405

I found another solution here on Stackoverflow. The following is a slightly modified code from https://stackoverflow.com/a/6197549/3986609 by RRUZ.

procedure TForm1.RichEdit1MouseDown(Sender: TObject; Button: TMouseButton;   Shift: TShiftState; X, Y: Integer);
var
    APoint  : TPoint;
    Index   : Integer;
begin
    if Button = mbRight then
    begin
        APoint := Point(X, Y);
        Index :=  SendMessage(TRichEdit(Sender).Handle,EM_CHARFROMPOS, 0, Integer(@APoint));
        if Index<0 then Exit;
        TRichEdit(Sender).SelStart:=Index;
    end;
end;

Upvotes: 1

Gavin Gross
Gavin Gross

Reputation: 16

Just use the ContextPopup event and simulate a left mouse click

type    
    TForm1 = class(TForm)
    edtRich: TRichEdit;
    procedure edtRichContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
  end;

implementation

procedure TForm1.edtRichContextPopup(Sender: TObject; MousePos: TPoint; 
    var Handled: Boolean);
begin
  mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTDOWN,
              MousePos.x, MousePos.y, 0, 0);
  mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTUP,
              MousePos.x, MousePos.y, 0, 0);
end;

Upvotes: 0

Related Questions