openharmony 鸿蒙 js-apis-selectionInput-selectionManager

2026-08-25 浏览 (1)

@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模型下使用。

参数:

参数名类型必填说明
typestring设置监听类型,固定取值为'selectionCompleted'。
callbackCallback<SelectionInfo>回调函数,返回当前划词信息。

错误码:

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

错误码ID错误信息
33600003The 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模型下使用。

参数:

参数名类型必填说明
typestring设置监听类型,固定取值为'selectionCompleted'。
callbackCallback<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错误信息
33600001Selection service exception.
33600004The interface is called too frequently.
33600005The interface is called at the wrong time.
33600006The current application is prohibited from accessing content.
33600007The length of selected content is out of range.
33600008Getting 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异步回调。

单个划词应用仅允许创建一个主面板类型和一个菜单面板类型的窗口。

系统能力: SystemCapability.SelectionInput.Selection

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

参数:

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

返回值:

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

错误码:

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

错误码ID错误信息
33600001Selection service exception.
33600003The 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模型下使用。

参数:

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

返回值:

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

错误码:

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

错误码ID错误信息
33600001Selection 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模型下使用。

名称类型只读可选说明
selectionTypeSelectionType触发划词类型。
startDisplayXnumber划词起始位置的屏幕x轴坐标,单位为px。
startDisplayYnumber划词起始位置的屏幕y轴坐标,单位为px。
endDisplayXnumber划词结束位置的屏幕x轴坐标,单位为px。
endDisplayYnumber划词结束位置的屏幕y轴坐标,单位为px。
startWindowXnumber划词起始位置的窗口x轴坐标,单位为px。
startWindowYnumber划词起始位置的窗口y轴坐标,单位为px。
endWindowXnumber划词结束位置的窗口x轴坐标,单位为px。
endWindowYnumber划词结束位置的窗口y轴坐标,单位为px。
displayIDnumber被划词应用窗口的屏幕ID。
windowIDnumber被划词应用的窗口ID。
bundleNamestring被划词应用的bundleName。

Panel

划词面板。

系统能力: SystemCapability.SelectionInput.Selection

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

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

setUiContent

setUiContent(path: string): Promise<void>

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

系统能力: SystemCapability.SelectionInput.Selection

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

参数:

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

返回值:

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

错误码:

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

错误码ID错误信息
33600001Selection service exception.
33600002This 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错误信息
33600001Selection service exception.
33600002This 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错误信息
33600001Selection service exception.
33600002This 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错误信息
33600001Selection service exception.
33600002This 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

参数:

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

返回值:

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

错误码:

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

错误码ID错误信息
33600001Selection service exception.
33600002This 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模型下使用。

参数:

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

返回值:

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

错误码:

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

错误码ID错误信息
33600001Selection service exception.
33600002This 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模型下使用。

参数:

参数名类型必填说明
typestring设置监听类型,固定取值为'destroyed'。
callbackCallback<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模型下使用。

参数:

参数名类型必填说明
typestring设置监听类型,固定取值为'destroyed'。
callbackCallback<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模型下使用。

参数:

参数名类型必填说明
typestring设置监听类型,固定取值为'hidden'。
callbackCallback<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模型下使用。

参数:

参数名类型必填说明
typestring设置监听类型,固定取值为'hidden'。
callbackCallback<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_MOVE1滑动选词类型。
DOUBLE_CLICK2双击选词类型。
TRIPLE_CLICK3三击选词类型。

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 errorcode-zlib

openharmony 鸿蒙 capi-oh-scan-scan-picturescanprogress

openharmony 鸿蒙 js-apis-screen-lock

openharmony 鸿蒙 capi-os-account-common-h

openharmony 鸿蒙 js-apis-screen-lock-sys

openharmony 鸿蒙 capi-oh-print-print-propertylist

openharmony 鸿蒙 capi-oh-scan

openharmony 鸿蒙 js-apis-system-device

openharmony 鸿蒙 errorcode-intelligentVoice

openharmony 鸿蒙 js-apis-request-sys

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/Bfjkc9hU