@ohos.selectionInput.selectionManager (划词管理)

本模块提供划词管理能力,包括创建窗口、显示窗口、移动窗口、隐藏窗口、销毁窗口、监听鼠标划词事件、获取选中文本等。

说明:

  • 本模块首批接口从API version 24开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
  • 本模块仅支持PC/2in1设备。
  • 仅支持集成了划词扩展的应用调用。

导入模块

import { selectionManager } from '@kit.BasicServicesKit';

selectionManager

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

selectionManager.on('selectionCompleted')

on(type: 'selectionCompleted', callback: Callback<SelectionInfo>): void

订阅划词完成事件。使用callback异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
type string 设置监听类型,固定取值为'selectionCompleted'。
callback Callback<SelectionInfo> 回调函数,返回当前划词信息。该回调仅在用户通过鼠标或触控板选中文本(鼠标左键双击/三击/按下滑动)后按下Ctrl键时触发。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600003 The application calling the API does not match the application selected in the system settings.

示例:

import { selectionManager } from '@kit.BasicServicesKit';

try {
  selectionManager.on('selectionCompleted', (info: selectionManager.SelectionInfo) => {
    console.info(`Enter the callback function.`);
  });
} catch (err) {
  console.error(`Failed to register selectionCompleted callback: ${err.code}, error message: ${err.message}`);
}

selectionManager.off('selectionCompleted')

off(type: 'selectionCompleted', callback?: Callback<SelectionInfo>): void

取消订阅划词完成事件。使用callback异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
type string 设置监听类型,固定取值为'selectionCompleted'。
callback Callback<SelectionInfo> 回调函数,返回SelectionInfo。参数不填写时,取消订阅type对应的所有回调事件。

示例:

import { selectionManager } from '@kit.BasicServicesKit';

let selectionChangeCallback = (info: selectionManager.SelectionInfo) => {
  console.info(`Enter the callback function.`);
};

selectionManager.on('selectionCompleted', selectionChangeCallback);
try {
  selectionManager.off('selectionCompleted', selectionChangeCallback);
} catch (err) {
  console.error(`Failed to unregister selectionCompleted: ${err.code}, error message: ${err.message}`);
}

getSelectionContent()

getSelectionContent(): Promise<string>

获取选中文本的内容。使用Promise异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

返回值:

类型 说明
Promise<string> Promise对象,返回当前选中文本的内容。

错误码:

以下错误码的详细介绍请参见通用错误码划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.
33600004 The interface is called too frequently.
33600005 The interface is called at the wrong time.
33600006 The current application is prohibited from accessing content.
33600007 The length of selected content is out of range.
33600008 Getting the selected content times out.

示例:

import { selectionManager } from '@kit.BasicServicesKit';

selectionManager.on('selectionCompleted', async (info: selectionManager.SelectionInfo) => {
  try {
    let content = await selectionManager.getSelectionContent();
  } catch (err) {
    console.error(`Failed to get selection content: ${err.code}, error message: ${err.message}`);
  }
});

createPanel

createPanel(ctx: Context, info: PanelInfo): Promise<Panel>

创建划词面板。使用Promise异步回调。

单个划词应用仅允许创建一个MENU_PANEL和一个MAIN_PANEL

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
ctx Context 当前划词面板依赖的上下文信息。
info PanelInfo 划词面板信息。

返回值:

类型 说明
Promise<Panel> Promise对象,返回当前创建的划词面板对象。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.
33600003 The application calling the API does not match the application selected in the system settings.

示例:

import { selectionManager, SelectionExtensionAbility, PanelInfo, PanelType, BusinessError } from '@kit.BasicServicesKit';
import { rpc } from '@kit.IPCKit';
import { Want } from '@kit.AbilityKit';

class SelectionAbilityStub extends rpc.RemoteObject {
  constructor(des: string) {
    super(des);
  }
  onRemoteMessageRequest(
    code: number,
    data: rpc.MessageSequence,
    reply: rpc.MessageSequence,
    options: rpc.MessageOption
  ): boolean | Promise<boolean> {
    return true;
  }
}

class ServiceExtAbility extends SelectionExtensionAbility {
  onConnect(want: Want): rpc.RemoteObject {
    let panelInfo: PanelInfo = {
      panelType: PanelType.MENU_PANEL,
      x: 0,
      y: 0,
      width: 500,
      height: 200
    }
    let selectionPanel: selectionManager.Panel | undefined = undefined;
    selectionManager.createPanel(this.context, panelInfo)
      .then((panel: selectionManager.Panel) => {
        selectionPanel = panel;
        console.info('Succeed in creating panel.');
      }).catch((err: BusinessError) => {
      console.error(`Failed to create panel: ${err.code}, error message: ${err.message}`);
    });
    return new SelectionAbilityStub('remote');
  }
}
export default ServiceExtAbility;

destroyPanel

destroyPanel(panel: Panel): Promise<void>

销毁划词面板。使用Promise异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
panel Panel 要销毁的面板对象。

返回值:

类型 说明
Promise<void> Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.

示例:

import { selectionManager, SelectionExtensionAbility, PanelInfo, PanelType, BusinessError } from '@kit.BasicServicesKit';
import { rpc } from '@kit.IPCKit';
import { Want } from '@kit.AbilityKit';

class SelectionAbilityStub extends rpc.RemoteObject {
  constructor(des: string) {
    super(des);
  }
  onRemoteMessageRequest(
    code: number,
    data: rpc.MessageSequence,
    reply: rpc.MessageSequence,
    options: rpc.MessageOption
  ): boolean | Promise<boolean> {
    return true;
  }
}

class ServiceExtAbility extends SelectionExtensionAbility {
  onConnect(want: Want): rpc.RemoteObject {
    let panelInfo: PanelInfo = {
      panelType: PanelType.MENU_PANEL,
      x: 0,
      y: 0,
      width: 500,
      height: 200
    }
    let selectionPanel: selectionManager.Panel | undefined = undefined;

    selectionManager.createPanel(this.context, panelInfo)
      .then((panel: selectionManager.Panel) => {
        console.info('Succeed in creating panel.');
        selectionPanel = panel;
        try {
          if (selectionPanel) {
            selectionManager.destroyPanel(selectionPanel).then(() => {
              console.info('Succeed in destroying panel.');
            }).catch((err: BusinessError) => {
              console.error(`Failed to destroy panel: ${err.code}, error message: ${err.message}`);
            });
          }
        } catch (err) {
          console.error(`Failed to destroy panel: ${err.code}, error message: ${err.message}`);
        }
      }).catch((err: BusinessError) => {
      console.error(`Failed to create panel: ${err.code}, error message: ${err.message}`);
    });
    return new SelectionAbilityStub('remote');
  }
}
export default ServiceExtAbility;

SelectionInfo

划词事件信息。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

名称 类型 只读 可选 说明
selectionType SelectionType 触发划词类型。
startDisplayX number 划词起始位置的屏幕x轴坐标,单位为px。
startDisplayY number 划词起始位置的屏幕y轴坐标,单位为px。
endDisplayX number 划词结束位置的屏幕x轴坐标,单位为px。
endDisplayY number 划词结束位置的屏幕y轴坐标,单位为px。
startWindowX number 划词起始位置的窗口x轴坐标,单位为px。
startWindowY number 划词起始位置的窗口y轴坐标,单位为px。
endWindowX number 划词结束位置的窗口x轴坐标,单位为px。
endWindowY number 划词结束位置的窗口y轴坐标,单位为px。
displayID number 被划词应用窗口的屏幕ID。
windowID number 被划词应用的窗口ID。
bundleName string 被划词应用的bundleName。

Panel

划词面板。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

下列API均需使用createPanel获取到Panel实例后,通过实例调用。

setUiContent

setUiContent(path: string): Promise<void>

为当前的划词面板加载具体页面内容。使用Promise异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
path string 要加载到面板中的页面内容的路径,Stage模型下该路径需添加到工程的resources/base/profile/main_pages.json文件中,不支持FA模型。

返回值:

类型 说明
Promise<void> Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.
33600002 This selection window has been destroyed.

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.setUiContent('pages/Index').then(() => {
    console.info('Succeeded in setting the content.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to setUiContent: ${err.code}, error message: ${err.message}`);
  });
} catch (err) {
  console.error(`Failed to setUiContent: ${err.code}, error message: ${err.message}`);
}

show

show(): Promise<void>

显示划词面板。使用Promise异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

返回值:

类型 说明
Promise<void> Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.
33600002 This selection window has been destroyed.

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

selectionPanel.show().then(() => {
  console.info('Succeeded in showing the panel.');
}).catch((err: BusinessError) => {
  console.error(`Failed to show panel: ${err.code}, error message: ${err.message}`);
});

hide

hide(): Promise<void>

隐藏当前划词面板。使用Promise异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

返回值:

类型 说明
Promise<void> Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.
33600002 This selection window has been destroyed.

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

selectionPanel.hide().then(() => {
  console.info('Succeeded in hiding the panel.');
}).catch((err: BusinessError) => {
  console.error(`Failed to hide panel: ${err.code}, error message: ${err.message}`);
});

startMoving

startMoving(): Promise<void>

使当前划词面板可以随鼠标拖动位置。使用Promise异步回调。该接口需要写在onTouch的回调函数中,并且事件类型为TouchType.Down。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

返回值:

类型 说明
Promise<void> Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.
33600002 This selection window has been destroyed.

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

RelativeContainer() {
  /* 
   * 页面布局内容,需要开发者根据实际补充
   */
}
.onTouch((event: TouchEvent) => {
  if (event.type === TouchType.Down) {
    if (selectionPanel !== undefined) {
      selectionPanel.startMoving().then(() => {   // selectionPanel为createPanel创建出的panel实例
        console.info('Succeeded in startMoving the panel.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to startMoving panel: ${err.code}, error message: ${err.message}`);
      });
    }
  }
})

moveTo(deprecated)

moveTo(x: number, y: number): Promise<void>

移动划词面板至屏幕指定位置。使用Promise异步回调。

说明:

从API version 20开始支持,从API version 24开始废弃。建议使用moveToGlobalDisplay替代。

系统接口: 此接口为系统接口。

系统能力: SystemCapability.SelectionInput.Selection

参数:

参数名 类型 必填 说明
x number x轴方向移动的值,单位为px。
y number y轴方向移动的值,单位为px。

返回值:

类型 说明
Promise<void> Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.
33600002 This selection window has been destroyed.

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.moveTo(200, 200).then(() => {
    console.info('Succeeded in moving the panel.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to move panel: ${err.code}, error message: ${err.message}`);
  });
} catch (err) {
  console.error(`Failed to move panel: ${err.code}, error message: ${err.message}`);
}

moveToGlobalDisplay

moveToGlobalDisplay(x: number, y: number): Promise<void>

移动划词面板至屏幕指定位置。使用Promise异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
x number x轴方向移动的值,单位为px。
y number y轴方向移动的值,单位为px。

返回值:

类型 说明
Promise<void> Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见划词服务错误码

错误码ID 错误信息
33600001 Selection service exception.
33600002 This selection window has been destroyed.

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.moveToGlobalDisplay(200, 200).then(() => {
    console.info('Succeeded in moving the panel.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to move panel: ${err.code}, error message: ${err.message}`);
  });
} catch (err) {
  console.error(`Failed to move panel: ${err.code}, error message: ${err.message}`);
}

on('destroyed')

on(type: 'destroyed', callback: Callback<void>): void

订阅划词窗口销毁事件。使用callback异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
type string 设置监听类型,固定取值为'destroyed'。
callback Callback<void> 回调函数,返回值为空。

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.on('destroyed', () => {
    console.info('Panel has been destroyed.');
  });
} catch (err) {
  console.error(`Failed to register destroyed callback: ${err.code}, error message: ${err.message}`);
}

off('destroyed')

off(type: 'destroyed', callback?: Callback<void>): void

取消订阅划词窗口销毁事件。使用callback异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
type string 设置监听类型,固定取值为'destroyed'。
callback Callback<void> 回调函数,返回值为空。参数不填写时,取消订阅type对应的所有回调事件。

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.off('destroyed');
} catch (err) {
  console.error(`Failed to unregister destroyed: ${err.code}, error message: ${err.message}`);
}

on('hidden')

on(type: 'hidden', callback: Callback<void>): void

订阅划词窗口隐藏事件。使用callback异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
type string 设置监听类型,固定取值为'hidden'。
callback Callback<void> 回调函数,返回值为空。

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.on('hidden', () => {
    console.info('Panel has been hidden.');
  });
} catch (err) {
  console.error(`Failed to register hidden callback: ${err.code}, error message: ${err.message}`);
}

off('hidden')

off(type: 'hidden', callback?: Callback<void>): void

取消订阅划词窗口隐藏事件。使用callback异步回调。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

参数:

参数名 类型 必填 说明
type string 设置监听类型,固定取值为'hidden'。
callback Callback<void> 回调函数,返回值为空。参数不填写时,取消订阅type对应的所有回调事件。

示例:

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.off('hidden');
} catch (err) {
  console.error(`Failed to unregister hidden: ${err.code}, error message: ${err.message}`);
}

SelectionType

定义触发划词的类型枚举。

系统能力: SystemCapability.SelectionInput.Selection

模型约束: 此接口仅可在Stage模型下使用。

名称 说明
MOUSE_MOVE 1 滑动选词类型。
DOUBLE_CLICK 2 双击选词类型。
TRIPLE_CLICK 3 三击选词类型。