【问题标题】:Determine if text has been selected that may be cut or copied to clipboard确定是否选择了可以剪切或复制到剪贴板的文本
【发布时间】:2017-10-05 01:46:31
【问题描述】:

我的应用有用于剪切、复制和粘贴的菜单项。我知道如何执行这些操作,但不知道如何确定是否已选择某些内容。我需要知道这一点才能启用或禁用剪切和复制菜单项(我会在 TAction.OnUpdate 事件中执行此操作)。

例如,要从当前获得焦点的控件中复制选定的文本,我使用这个:

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

但是,我如何确定当前焦点控件中是否选择了任何文本?

我可以遍历我的所有控件并使用如下条件:

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

但这似乎并不优雅。有没有更好的办法?

编辑:

根据 Remy 的回答,我编写了以下代码,它似乎可以工作:

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 是我的TAction 用于剪切操作,EditCut1Update 是它的OnUpdate 事件处理程序。

编辑 2: 在 Remy 对我的第一次编辑发表评论之后,我现在正在使用:

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;

【问题讨论】:

    标签: delphi firemonkey


    【解决方案1】:

    TEditTMemo(以及“提供文本区域的所有控件”)实现了ITextInput 接口,该接口具有GetSelection()GetSelectionBounds()GetSelectionRect() 方法。

    【讨论】:

    • 在您的回答的指导下,我采用了问题编辑中显示的代码,它似乎有效。
    • @Duns: 你的第二个if 可以被删除:EditCut1.Enabled := Length(Textinput.GetSelection) &gt; 0; 这也可以工作,而不必为临时string分配内存:EditCut1.Enabled := not Textinput.GetSelectionBounds.IsEmpty;EditCut1.Enabled := not Textinput.GetSelectionRect.IsEmpty;跨度>
    • 看来我的第二个 if 确实可以被淘汰。我的 if else 可以改写为EditCut1.Enabled := Length(Textinput.GetSelection) &gt; 0;EditCut1.Enabled := not Textinput.GetSelectionRect.IsEmpty; 也可以。奇怪的是,EditCut1.Enabled := not Textinput.GetSelectionBounds.IsEmpty; 似乎不起作用,因为它似乎永远不会返回 true。
    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多