鼠标坐标在Firemonkey TMemo组件中的插入位置

时间:2013-08-14 06:22:05

标签: delphi mouse coordinates firemonkey tmemo

在Firemonkeys上处理鼠标/拖放事件TMemo Component提供Mousecursor坐标。有没有办法从鼠标坐标中计算出CaretPosition?

我想将文本拖到TMemo中,此文本应插入当前的MouseCoordinates。

2 个答案:

答案 0 :(得分:5)

尝试拨打GetPointPosition

不幸的是,这似乎已经从XE3中的TMemo中删除了。作为一种快速而肮脏的解决方法,您可以尝试这样做:

function GetPointPosition(Memo: TMemo; Pt: TPointF; RoundToWord: Boolean = False): TCaretPosition;
var
  I, LPos: Integer;
  Rgn: TRegion;
begin
  Result.Line := -1;
  Result.Pos := -1;
  for I := 0 to Memo.Lines.Count - 1 do
  begin
    if Memo.Lines.Objects[I] is TTextLayout then
    begin
      LPos := TTextLayout(Memo.Lines.Objects[I]).PositionAtPoint(Pt, RoundToWord);
      if LPos >= 0 then
      begin
        if LPos > 0 then
        begin
          Rgn := TTextLayout(Memo.Lines.Objects[I]).RegionForRange(TTextRange.Create(LPos, 1), RoundToWord);
          if (Length(Rgn) > 0) and (Rgn[0].Top > Pt.Y) then
            Dec(LPos);
        end;
        Result.Line := I;
        Result.Pos := LPos;
        Break;
      end;
    end;
  end;
end;

答案 1 :(得分:0)

使用RTTI在XE10中适用的解决方案:

procedure TMyForm.MemoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
var Obj: IControl;   
    af: TPointf;
    cp: TCaretPosition;
    aName: string;
    LVar: TStyledMemo;
    LClass: TRttiInstanceType;
    aLines: TObject;
    aMethod: TRttiMethod;
    aValue: TValue;
    pointValue, boolValue: TValue;
begin
   af := TPointF.Create(Panel1.Position.X + X, panel4.Height + Y);
   Obj := ObjectAtPoint(ClientToScreen(af));

   if Assigned(Obj) then
   begin
       LVar := TStyledMemo(Obj);
       LClass := LContext.GetType(TStyledMemo) as TRttiInstanceType;
       aLines := LClass.GetField('FLineObjects').GetValue(LVar).AsObject;

       af := TPointF.Create(X,Y);
       pointValue := TValue.From<TPointF>(af);  
       boolValue := TValue.From<Boolean>(false);

       LClass := LContext.GetType(aLines.ClassType) as TRttiInstanceType;
       aMethod := LClass.GetMethod('GetPointPosition');
       aValue := aMethod.Invoke(aLines, [pointValue, boolValue]);

       cp := aValue.AsType<TCaretPosition>;
   end;
end;