Search code examples
delphifiremonkey

Determine if text has been selected that may be cut or copied to clipboard


My app has menu items for cut, copy and paste. I know how to execute these actions but not how to determine if something has been selected. I need to know this to enable or disable the cut and copy menu items (which I would do in TAction.OnUpdate events).

For example, to copy selected text from the currently focused control, I use this:

if Assigned(Focused) and TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc) then
  if Supports(Focused.GetObject, ITextActions, TextAction) then
    TextAction.CopyToClipboard;

But, how do I determine if any selection of text has been made in the currently focused control?

I could iterate through all my controls and use conditions like this:

if ((Focused.GetObject is TMemo) and (TMemo(Focused.GetObject).SelLength > 0) then 
  <Enable the Cut and Copy menu items>

but this does not seem elegant. Is there a better way?

EDIT:

Based on Remy's answer, I programmed the following and it seems to work:

procedure TMyMainForm.EditCut1Update(Sender: TObject);
var
  Textinput: ITextinput;
begin
  if Assigned(Focused) and Supports(Focused.GetObject, ITextinput, Textinput) then
    if Length(Textinput.GetSelection) > 0 then
      EditCut1.Enabled := True
    else
      EditCut1.Enabled := False;
end;

EditCut1 is my TAction for cut operations, and EditCut1Update is its OnUpdate event handler.

EDIT 2: Following Remy's comment on my first edit, I am now using:

procedure TMyMainForm.EditCut1Update(Sender: TObject);
var
  TextInput: ITextInput;
begin
  if Assigned(Focused) and Supports(Focused.GetObject, ITextInput, TextInput)
    then
  EditCut1.Enabled := not TextInput.GetSelectionRect.IsEmpty;
end;

Solution

  • TEdit and TMemo (and "all controls that provide a text area") implement the ITextInput interface, which has GetSelection(), GetSelectionBounds(), and GetSelectionRect() methods.