I have a form with a TMemo
control where you can enter text, and another TEdit
control that I want when the user selects text in Memo to be automatically displayed in Edit. Is there a way to do this without using a timer? (Actually, is there a way to capture an event that occurs when text is selected or canceled in the Memo control?)
I know that OnMouseUp
and OnKeyUp
events can be used, but in this way the Edit will only be updated after the user has finished selecting, and not at the time of selection.
CodePudding user response:
Check this answer
TEdit and TMemo (and "all controls that provide a text area") implement the ITextInput interface, which has GetSelection(), GetSelectionBounds(), and GetSelectionRect() methods.
CodePudding user response:
This is my try and it works in most cases. Maybe you can adapt it and tweak it to your likings.
type
TForm1 = class(TForm)
Memo1: TMemo;
Edit1: TEdit;
procedure Memo1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure Memo1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure Memo1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure Memo1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
mouseselectionstarted: boolean;
procedure FillText;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
System.UITypes;
{$R *.dfm}
procedure TForm1.FillText;
begin
Edit1.Text := Memo1.SelText;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
mouseselectionstarted := false;
end;
procedure TForm1.Memo1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (ssShift in Shift) and (Key in [vkLeft, vkUp, vkRight, vkDown]) then
FillText;
end;
procedure TForm1.Memo1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) then
mouseselectionstarted := true;
end;
procedure TForm1.Memo1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if mouseselectionstarted then
FillText;
end;
procedure TForm1.Memo1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mouseselectionstarted := false;
end;