dmitrybv 3 Posted November 6 Hello. The following code throws an 'Invalid class typecast' exception. procedure TForm1.Button1Click(Sender: TObject); var RttiContext: TRttiContext; LType: TRttiType; ACaretPositionProp: TRttiProperty; Val: TValue; begin RttiContext := TRttiContext.Create; LType := RttiContext.GetType(TMemo); ACaretPositionProp := LType.GetProperty('CaretPosition'); Val := ACaretPositionProp.GetValue(Memo1); end; Although it shouldn't. Place a TMemo and a TButton on a Form and write the Button.OnClick event as described above. Embarcadero® RAD Studio 12 Version 29.0.53571.9782 Delphi 12 Update 2. Share this post Link to post
Rollo62 534 Posted November 7 (edited) Try this, untested uses System.Rtti, System.SysUtils, Vcl.StdCtrls; procedure TForm1.Button1Click(Sender: TObject); var RttiContext: TRttiContext; LType: TRttiType; ACaretPositionProp: TRttiProperty; Val: TValue; CaretPos: TPoint; begin RttiContext := TRttiContext.Create; try LType := RttiContext.GetType(TMemo.ClassType); ACaretPositionProp := LType.GetProperty('CaretPosition'); if Assigned(ACaretPositionProp) then begin Val := ACaretPositionProp.GetValue(Memo1); if Val.IsType<TPoint> then // Check if the value is of type TPoint (which is compatible with TCaretPosition) begin CaretPos := Val.AsType<TPoint>; ShowMessage(Format('Caret Position: X=%d, Y=%d', [CaretPos.X, CaretPos.Y])); end else ShowMessage('CaretPosition property is not of type TPoint.'); end else ShowMessage('CaretPosition property not found.'); finally RttiContext.Free; end; end; Edited November 7 by Rollo62 Share this post Link to post
dmitrybv 3 Posted November 7 8 hours ago, Rollo62 said: Try this, untested uses System.Rtti, System.SysUtils, Vcl.StdCtrls; procedure TForm1.Button1Click(Sender: TObject); var RttiContext: TRttiContext; LType: TRttiType; ACaretPositionProp: TRttiProperty; Val: TValue; CaretPos: TPoint; begin RttiContext := TRttiContext.Create; try LType := RttiContext.GetType(TMemo.ClassType); ACaretPositionProp := LType.GetProperty('CaretPosition'); if Assigned(ACaretPositionProp) then begin Val := ACaretPositionProp.GetValue(Memo1); if Val.IsType<TPoint> then // Check if the value is of type TPoint (which is compatible with TCaretPosition) begin CaretPos := Val.AsType<TPoint>; ShowMessage(Format('Caret Position: X=%d, Y=%d', [CaretPos.X, CaretPos.Y])); end else ShowMessage('CaretPosition property is not of type TPoint.'); end else ShowMessage('CaretPosition property not found.'); finally RttiContext.Free; end; end; Exception: Project TestDemo.exe raised exception class EInvalidCast with message 'Invalid class typecast'. On the line: Val := ACaretPositionProp.GetValue(Memo1); Share this post Link to post