频道分类

Delphi RichEdit根据鼠标位置定位光标的方法

作者:admin 来源: 日期:2020/11/23 18:54:37 人气: 标签:

 

当RichEdit为可用状态时,是不用代码控制此操作的,TRichEdit本身就可以定位光标。但是当RichEdit开始不可用时,则此方法就可能用到了。本例中RichEdit1开始时是不可用的,当在ApplicationEvents1中接收到RichEdit1被双击时则设置RichEdit1的Enable := true;并且定位光标。

unit Unit1;

 

interface

 

uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls, ComCtrls, RichEdit, AppEvnts;

 

type

  TForm1 = class(TForm)

    RichEdit1: TRichEdit;

    ApplicationEvents1: TApplicationEvents;

    procedure EnableRichEdit;

    procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

 

var

  Form1: TForm1;

  FLastMousePos: TPoint;

 

implementation

 

{$R *.dfm}

 

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;

  var Handled: Boolean);

var

  mPos: TPoint;

begin

  if msg.message = WM_LBUTTONDBLCLK then begin

    if msg.hwnd = RichEdit1.Parent.Handle then begin

      GetCursorPos(FLastMousePos);

      EnableRichEdit;

    end;

  end ;

end;

 

procedure TForm1.EnableRichEdit;

var

  cPos: TPoint;

  retCode: integer;

  mR, mC: Word;

begin

  RichEdit1.Enabled := True;

  RichEdit1.SetFocus ;

  RichEdit1.SelStart := 0;

 

  if (FLastMousePos.X = 0) and (FLastMousePos.Y = 0) then

    GetCursorPos(FLastMousePos);

  FLastMousePos := RichEdit1.ScreenToClient(FLastMousePos);

  retCode := SendMessage(RichEdit1.Handle, EM_CHARFROMPOS, 0, LPARAM(@FLastMousePos));

  mR := HiWord(retCode);

  mC := Loword(retCode);

  cPos.X := mC ;

  cPos.Y := mR ;

  RichEdit1.CaretPos := cPos;

 

  FLastMousePos.X := 0;

  FLastMousePos.Y := 0;

end;

 

end.