@ohos.window (窗口)

窗口提供管理窗口的一些基础能力,包括对当前窗口的创建、销毁、各属性设置,以及对各窗口间的管理调度。

该模块提供以下窗口相关的常用功能:

  • Window:当前窗口实例,窗口管理器管理的基本单元。
  • WindowStage:窗口管理器。管理各个基本窗口单元。

说明:

本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

import { window } from '@kit.ArkUI';

WindowType7+

窗口类型枚举。

系统能力: SystemCapability.WindowManager.WindowManager.Core

名称 说明
TYPE_APP 0 表示应用子窗口。
模型约束: 此接口仅可在FA模型下使用。
TYPE_SYSTEM_ALERT(deprecated) 1 表示系统告警窗口。
- 说明: 从API version 11开始废弃。
- 从API version 7开始支持。
TYPE_FLOAT9+ 8 表示悬浮窗。
模型约束: 此接口仅可在Stage模型下使用。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
TYPE_DIALOG10+ 16 表示模态窗口。
模型约束: 此接口仅可在Stage模型下使用。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
TYPE_MAIN18+ 32 表示应用主窗口。
此窗口类型不支持在创建窗口时使用,仅可在getWindowProperties接口的返回值中用于读取。

Configuration9+

创建子窗口或系统窗口时的参数。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

名称 类型 必填 说明
name string 窗口名字。
windowType WindowType 窗口类型。
ctx BaseContext 当前应用上下文信息。不设置,则默认为空。
FA模型下不需要使用该参数,即可创建子窗口,使用该参数时会报错。
Stage模型必须使用该参数,用于创建悬浮窗、模态窗或系统窗口。
displayId number 当前物理屏幕id。不设置,则默认为-1,该参数应为整数。
parentId number 父窗口id。不设置,则默认为-1,该参数应为整数。
decorEnabled12+ boolean 是否显示窗口装饰,仅在windowType为TYPE_DIALOG时生效。true表示显示,false表示不显示。此参数默认值为false。
系统能力: SystemCapability.Window.SessionManager
title12+ string decorEnabled属性设置为true时,窗口的标题内容。标题显示区域最右端不超过系统三键区域最左端,超过部分以省略号表示。不设置,则默认为空字符串。
系统能力: SystemCapability.Window.SessionManager

AvoidAreaType7+

窗口内容需要规避区域的类型枚举。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

名称 说明
TYPE_SYSTEM 0 表示系统默认区域。包含状态栏和三键导航栏区域。
TYPE_CUTOUT 1 表示刘海屏区域。
TYPE_SYSTEM_GESTURE9+ 2 表示手势区域。当前,各设备均无此类型避让区域。
TYPE_KEYBOARD9+ 3 表示软键盘区域。
TYPE_NAVIGATION_INDICATOR11+ 4 表示底部导航区域。OpenHarmony各设备不支持此能力。

SystemBarProperties

状态栏、三键导航栏的属性。在设置窗口级状态栏、三键导航栏属性时使用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

名称 类型 必填 说明
statusBarColor string 状态栏背景颜色,为十六进制RGB或ARGB颜色,不区分大小写,例如'#00FF00''#FF00FF00'。默认值:'#66000000'
系统能力: SystemCapability.WindowManager.WindowManager.Core
isStatusBarLightIcon7+ boolean 状态栏图标是否为高亮状态。true表示高亮;false表示不高亮。默认值:false。
系统能力: SystemCapability.WindowManager.WindowManager.Core
statusBarContentColor8+ string 状态栏文字颜色。当设置此属性后,isStatusBarLightIcon属性设置无效。默认值:'#E5FFFFFF'
系统能力: SystemCapability.WindowManager.WindowManager.Core
navigationBarColor string 三键导航栏背景颜色,为十六进制RGB或ARGB颜色,不区分大小写,例如'#00FF00''#FF00FF00'。默认值:'#66000000'
系统能力: SystemCapability.WindowManager.WindowManager.Core
isNavigationBarLightIcon7+ boolean 三键导航栏图标是否为高亮状态。true表示高亮;false表示不高亮。默认值:false。
系统能力: SystemCapability.WindowManager.WindowManager.Core
navigationBarContentColor8+ string 三键导航栏文字颜色。当设置此属性后,isNavigationBarLightIcon属性设置无效。默认值:'#E5FFFFFF'
系统能力: SystemCapability.WindowManager.WindowManager.Core
enableStatusBarAnimation12+ boolean 是否使能状态栏属性变化时动画效果。true表示变化时使能动画效果;false表示没有使能动画效果。默认值:false。
系统能力: SystemCapability.Window.SessionManager
enableNavigationBarAnimation12+ boolean 是否使能三键导航栏属性变化时动画效果。true表示变化时使能动画效果;false表示没有使能动画效果。默认值:false。
系统能力: SystemCapability.Window.SessionManager

StatusBarProperty18+

状态栏的属性。在获取状态栏属性信息时返回。

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

名称 类型 必填 说明
contentColor string 状态栏文字颜色,固定为ARGB格式, 如:#E5FFFFFF
系统能力: SystemCapability.Window.SessionManager

SystemBarStyle12+

状态栏的属性。在设置页面级状态栏属性时使用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

名称 类型 只读 可选 说明
statusBarContentColor string 状态栏文字颜色。默认值:'#E5FFFFFF'

Orientation9+

窗口显示方向类型枚举。

名称 说明
UNSPECIFIED 0 表示未定义方向模式,由系统判定。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.WindowManager.WindowManager.Core
PORTRAIT 1 表示竖屏显示模式。
系统能力: SystemCapability.WindowManager.WindowManager.Core
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
LANDSCAPE 2 表示横屏显示模式。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.WindowManager.WindowManager.Core
PORTRAIT_INVERTED 3 表示反向竖屏显示模式。
系统能力: SystemCapability.WindowManager.WindowManager.Core
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
LANDSCAPE_INVERTED 4 表示反向横屏显示模式。
系统能力: SystemCapability.WindowManager.WindowManager.Core
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
AUTO_ROTATION 5 跟随传感器自动旋转,可以旋转到竖屏、横屏、反向竖屏、反向横屏四个方向。
系统能力: SystemCapability.WindowManager.WindowManager.Core
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
AUTO_ROTATION_PORTRAIT 6 跟随传感器自动竖向旋转,可以旋转到竖屏、反向竖屏,无法旋转到横屏、反向横屏。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.WindowManager.WindowManager.Core
AUTO_ROTATION_LANDSCAPE 7 跟随传感器自动横向旋转,可以旋转到横屏、反向横屏,无法旋转到竖屏、反向竖屏。
系统能力: SystemCapability.WindowManager.WindowManager.Core
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
AUTO_ROTATION_RESTRICTED 8 跟随传感器自动旋转,可以旋转到竖屏、横屏、反向竖屏、反向横屏四个方向,且受控制中心的旋转开关控制。
系统能力: SystemCapability.WindowManager.WindowManager.Core
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
AUTO_ROTATION_PORTRAIT_RESTRICTED 9 跟随传感器自动竖向旋转,可以旋转到竖屏、反向竖屏,无法旋转到横屏、反向横屏,且受控制中心的旋转开关控制。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.WindowManager.WindowManager.Core
AUTO_ROTATION_LANDSCAPE_RESTRICTED 10 跟随传感器自动横向旋转,可以旋转到横屏、反向横屏,无法旋转到竖屏、反向竖屏,且受控制中心的旋转开关控制。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.WindowManager.WindowManager.Core
LOCKED 11 表示锁定模式。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.WindowManager.WindowManager.Core
AUTO_ROTATION_UNSPECIFIED12+ 12 跟随传感器自动旋转,受控制中心的旋转开关控制,且可旋转方向受系统判定(如在某种设备,可以旋转到竖屏、横屏、反向横屏三个方向,无法旋转到反向竖屏)。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.Window.SessionManager
USER_ROTATION_PORTRAIT12+ 13 调用时临时旋转到竖屏,之后跟随传感器自动旋转,受控制中心的旋转开关控制,且可旋转方向受系统判定。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.Window.SessionManager
USER_ROTATION_LANDSCAPE12+ 14 调用时临时旋转到横屏,之后跟随传感器自动旋转,受控制中心的旋转开关控制,且可旋转方向受系统判定。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.Window.SessionManager
USER_ROTATION_PORTRAIT_INVERTED12+ 15 调用时临时旋转到反向竖屏,之后跟随传感器自动旋转,受控制中心的旋转开关控制,且可旋转方向受系统判定。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.Window.SessionManager
USER_ROTATION_LANDSCAPE_INVERTED12+ 16 调用时临时旋转到反向横屏,之后跟随传感器自动旋转,受控制中心的旋转开关控制,且可旋转方向受系统判定。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.Window.SessionManager
FOLLOW_DESKTOP12+ 17 表示跟随桌面的旋转模式。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
系统能力: SystemCapability.Window.SessionManager

Rect7+

窗口矩形区域。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

名称 类型 只读 可选 说明
left number 矩形区域的左边界,单位为px,该参数为整数。
top number 矩形区域的上边界,单位为px,该参数应为整数。
width number 矩形区域的宽度,单位为px,该参数应为整数。
height number 矩形区域的高度,单位为px,该参数应为整数。

AvoidArea7+

窗口内容规避区域。如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。在规避区无法响应用户点击事件。

除此之外还需注意规避区域的如下约束,具体为:

  • 底部手势区域中非底部导航条区域支持点击、长按事件透传,不支持拖入。

  • 左右侧边手势区域支持点击、长按以及上下滑动事件透传,不支持拖入。

  • 底部导航条区域支持长按、点击、拖入事件响应,不支持事件向下透传。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

名称 类型 可读 可写 说明
visible9+ boolean 规避区域是否可见。true表示可见;false表示不可见。
leftRect Rect 屏幕左侧的矩形区。
topRect Rect 屏幕顶部的矩形区。
rightRect Rect 屏幕右侧的矩形区。
bottomRect Rect 屏幕底部的矩形区。

Size7+

窗口大小。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

名称 类型 可读 可写 说明
width number 窗口宽度,单位为px,该参数应为整数。
height number 窗口高度,单位为px,该参数应为整数。

RectChangeReason12+

窗口矩形(窗口位置及窗口大小)变化的原因。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

名称 说明
UNDEFINED 0 默认值。
MAXIMIZE 1 窗口最大化。
RECOVER 2 窗口恢复到上一次的状态。
MOVE 3 窗口拖拽移动。
DRAG 4 窗口拖拽缩放。
DRAG_START 5 窗口开始拖拽缩放。
DRAG_END 6 窗口结束拖拽缩放。

RectChangeOptions12+

窗口矩形(窗口位置及窗口大小)变化返回的值及变化原因。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

名称 类型 可读 可写 说明
rect Rect 窗口矩形变化后的值。
reason RectChangeReason 窗口矩形变化的原因。

AvoidAreaOptions12+

系统规避区变化后返回当前规避区域以及规避区域类型。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

名称 类型 可读 可写 说明
type AvoidAreaType 系统规避区变化后返回的规避区域类型。
area AvoidArea 系统规避区变化后返回的规避区域。

WindowProperties

窗口属性。

系统能力: SystemCapability.WindowManager.WindowManager.Core

名称 类型 只读 可选 说明
windowRect7+ Rect 窗口尺寸,可在页面生命周期onPageShow或应用生命周期onForeground阶段获取。
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
drawableRect11+ Rect 窗口内的可绘制区域尺寸,其中左边界上边界是相对于窗口计算。在Stage模型下,需要在调用loadContent()setUIContent()加载页面内容后使用该接口。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
type7+ WindowType 窗口类型。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
isFullScreen boolean 是否全屏,默认为false。true表示全屏;false表示非全屏。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
isLayoutFullScreen7+ boolean 窗口是否为沉浸式且处于全屏模式(不在悬浮窗、分屏等场景下),默认为false。true表示沉浸式且处于全屏模式;false表示非沉浸式或非全屏模式。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
focusable7+ boolean 窗口是否可聚焦,默认为true。true表示可聚焦;false表示不可聚焦。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
touchable7+ boolean 窗口是否可触摸,默认为true。true表示可触摸;false表示不可触摸。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
brightness number 屏幕亮度。该参数为浮点数,可设置的亮度范围为[0.0, 1.0],其取1.0时表示最大亮度值。如果窗口没有设置亮度值,表示亮度跟随系统,此时获取到的亮度值为-1。
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
dimBehindValue(deprecated) number 靠后窗口的暗度值。该参数为浮点数,取值范围为[0.0, 1.0],其取1.0表示最暗。
- 说明: 从API version 9开始废弃。
- 从API version 7开始支持。当前无可替代接口。
isKeepScreenOn boolean 屏幕是否常亮,默认为false。true表示常亮;false表示不常亮。
原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。
isPrivacyMode7+ boolean 隐私模式,默认为false。true表示模式开启;false表示模式关闭。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
isRoundCorner(deprecated) boolean 窗口是否为圆角。默认为false。true表示圆角;false表示非圆角。
- 说明: 从API version 9开始废弃。
- 从API version 7开始支持。当前无可替代接口。
isTransparent7+ boolean 窗口背景是否透明。默认为false。true表示透明;false表示不透明。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
id9+ number 窗口ID,默认值为0,该参数应为整数。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
displayId12+ number 窗口所在屏幕ID,默认返回主屏幕ID,该参数应为整数。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
name18+ string 窗口名字,默认为空字符串。
原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

DecorButtonStyle14+

系统装饰栏按钮样式。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

名称 类型 可读 可写 说明
colorMode ConfigurationConstant.ColorMode 颜色模式。深色模式下按钮颜色适配为浅色,浅色模式下按钮颜色适配为深色。未设置则默认跟随系统颜色模式。
buttonBackgroundSize number 按钮高亮显示时的大小,取值范围20vp-40vp,默认值28vp。
spacingBetweenButtons number 按钮间距,取值范围12vp-24vp,默认值12vp。
closeButtonRightMargin number 关闭按钮右侧距窗口边距,取值范围8vp-22vp,默认值20vp。

ColorSpace8+

色域模式。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

名称 说明
DEFAULT 0 默认SRGB色域模式。
WIDE_GAMUT 1 广色域模式。

WindowEventType10+

窗口生命周期。

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

名称 说明
WINDOW_SHOWN 1 切到前台。
系统能力: SystemCapability.WindowManager.WindowManager.Core
WINDOW_ACTIVE 2 获焦状态。
系统能力: SystemCapability.WindowManager.WindowManager.Core
WINDOW_INACTIVE 3 失焦状态。
系统能力: SystemCapability.WindowManager.WindowManager.Core
WINDOW_HIDDEN 4 切到后台。
系统能力: SystemCapability.WindowManager.WindowManager.Core
WINDOW_DESTROYED11+ 7 窗口销毁。
系统能力: SystemCapability.Window.SessionManager

WindowLimits11+

窗口尺寸限制参数。可以通过setWindowLimits设置窗口尺寸限制,并且可以通过getWindowLimits获得当前的窗口尺寸限制。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 类型 可读 可写 说明
maxWidth number 窗口的最大宽度。单位为px,该参数为整数。值默认为0,表示该属性不发生变化。下限值为0,上限值为系统限定的最大宽度。
maxHeight number 窗口的最大高度。单位为px,该参数为整数。值默认为0,表示该属性不发生变化。下限值为0,上限值为系统限定的最大高度。
minWidth number 窗口的最小宽度。单位为px,该参数为整数。值默认为0,表示该属性不发生变化。下限值为0,上限值为系统限定的最小宽度。
minHeight number 窗口的最小高度。单位为px,该参数为整数。值默认为0,表示该属性不发生变化。下限值为0,上限值为系统限定的最小高度。

WindowStatusType11+

窗口模式枚举。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 说明
UNDEFINED 0 表示APP未定义窗口模式。
FULL_SCREEN 1 表示APP全屏模式, 在2in1设备中,窗口铺满整个屏幕,且无dock栏和状态栏。
MAXIMIZE 2 表示APP窗口最大化模式,在2in1设备中,窗口铺满整个屏幕,有dock栏和状态栏。
MINIMIZE 3 表示APP窗口最小化模式。
FLOATING 4 表示APP自由悬浮形式窗口模式。
SPLIT_SCREEN 5 表示APP分屏模式。

TitleButtonRect11+

标题栏上的最小化、最大化、关闭按钮矩形区域,该区域位置坐标相对窗口右上角。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 类型 可读 可写 说明
right number 矩形区域的右边界,单位为vp,该参数为整数。
top number 矩形区域的上边界,单位为vp,该参数为整数。
width number 矩形区域的宽度,单位为vp,该参数为整数。
height number 矩形区域的高度,单位为vp,该参数为整数。

MaximizePresentation12+

窗口最大化时的布局枚举。

系统能力: SystemCapability.Window.SessionManager

名称 说明
FOLLOW_APP_IMMERSIVE_SETTING 0 最大化时,跟随应用app当前设置的全屏模式。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
EXIT_IMMERSIVE 1 最大化时,如果当前窗口设置了全屏模式会退出全屏模式。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
ENTER_IMMERSIVE 2 最大化时,进入全屏模式,鼠标Hover在热区上显示窗口标题栏和dock栏。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
ENTER_IMMERSIVE_DISABLE_TITLE_AND_DOCK_HOVER14+ 3 最大化时,进入全屏模式,鼠标Hover在热区上不显示窗口标题栏和dock栏。
原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

MoveConfiguration15+

窗口移动选项。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 类型 必填 说明
displayId number 目标屏幕ID,该参数应为整数,输入非整数时将向下取整。填入该参数时,将移动到相对于目标屏幕左上角的指定位置。此参数不填或传入目标屏幕ID不存在时,将移动到相对于当前屏幕左上角的指定位置。

WindowDensityInfo15+

窗口所在显示设备和窗口自定义的显示密度信息,是与像素单位无关的缩放系数,即显示大小缩放系数。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 类型 可读 可写 说明
systemDensity number 窗口所在屏幕的系统显示大小缩放系数,跟随用户设置变化,该参数变化范围为0.5-4.0。
defaultDensity number 窗口所在屏幕的系统默认显示大小缩放系数,跟随窗口所在屏幕变化,该参数变化范围为0.5-4.0。
customDensity number 窗口自定义设置的显示大小缩放系数,该参数取值范围为0.5-4.0。未设置该参数时,将跟随系统显示大小缩放系数变化。

WindowLayoutInfo15+

窗口布局信息。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 类型 必填 说明
windowRect15+ Rect 窗口尺寸,窗口在屏幕上的实际位置和大小。

KeyboardInfo18+

软键盘窗口信息。

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 类型 必填 说明
beginRect Rect 动画开始前软键盘的位置和大小。
endRect Rect 动画结束后软键盘的位置和大小。

WindowInfo18+

当前窗口的详细信息。

系统能力: SystemCapability.Window.SessionManager

名称 类型 只读 可选 说明
rect Rect 窗口尺寸。
bundleName string 应用Bundle的名称。
abilityName string Ability的名称。
windowId number 窗口ID。
windowStatusType WindowStatusType 窗口模式枚举。
isFocused boolean 窗口是否获焦。true表示窗口获焦;false表示窗口未获焦。

Callback15+

(data: T)15+

(data: T): V

通用回调函数。

开发者在使用时,可自定义data的参数类型,回调函数返回对应类型的信息。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
data T 回调函数调用时需要传入T类型的参数。

返回值:

类型 说明
V 回调函数需要返回V类型的返回值。

RotationChangeType19+

窗口旋转事件类型。

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 说明
WINDOW_WILL_ROTATE 0 窗口即将旋转。
WINDOW_DID_ROTATE 1 窗口旋转结束。

RectType19+

窗口矩形区域坐标系类型。

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 说明
RELATIVE_TO_SCREEN 0 窗口矩形区域相对于屏幕坐标系。
RELATIVE_TO_PARENT_WINDOW 1 窗口矩形区域相对于父窗口坐标系。

RotationChangeInfo19+

窗口旋转变化时的窗口信息。

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 类型 只读 可选 说明
type RotationChangeType 窗口旋转事件类型。
orientation number 窗口显示方向。
- 0表示竖屏。
- 1表示反向横屏。
- 2表示反向竖屏。
- 3表示横屏。
开发者在使用时,需要注意该方向与display对象的属性orientation含义不一致。
displayId number 窗口所在屏幕Id。
displayRect Rect 窗口所在屏幕旋转后的矩形区域大小。

RotationChangeResult19+

应用在窗口旋转变化时返回的信息,系统会根据此信息改变当前窗口矩形区域大小。当返回主窗口旋转变化的信息时,系统不改变主窗口的大小。 应用窗口与系统窗口大小存在限制,具体限制与相关规则可见resize

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

名称 类型 只读 可选 说明
rectType RectType 窗口矩形区域坐标系类型。
windowRect Rect 相对于屏幕或父窗坐标系的窗口矩形区域信息。

RotationChangeCallback19+

(info: T)19+

(info: T): U;

旋转事件通知通用回调函数。

开发者在使用时,回调函数参数类型为RotationChangeInfo,返回值类型为RotationChangeResult|void。

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
info T 回调函数调用时系统传入RotationChangeInfo类型的参数。

返回值:

类型 说明
U 回调函数需要返回RotationChangeResult|void类型的返回值。

window.createWindow9+

createWindow(config: Configuration, callback: AsyncCallback<Window>): void

创建子窗口或者系统窗口,使用callback异步回调。

需要权限: ohos.permission.SYSTEM_FLOAT_WINDOW(仅当创建窗口类型为window.WindowType.TYPE_FLOAT时需要申请)

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
config Configuration 创建窗口时的参数。
callback AsyncCallback<Window> 回调函数。返回当前创建的窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
201 Permission verification failed. The application does not have the permission required to call the API.
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. createWindow can not work correctly due to limited device capabilities.
1300001 Repeated operation.
1300002 This window state is abnormal.
1300004 Unauthorized operation.
1300006 This window context is abnormal.
1300009 The parent window is invalid.

示例:

import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    let windowClass: window.Window | undefined = undefined;
    let config: window.Configuration = {
      name: "test",
      windowType: window.WindowType.TYPE_DIALOG,
      ctx: this.context
    };
    try {
      window.createWindow(config, (err: BusinessError, data) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to create the window. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        windowClass = data;
        console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data));
        windowClass.resize(500, 1000);
      });
    } catch (exception) {
      console.error(`Failed to create the window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

window.createWindow9+

createWindow(config: Configuration): Promise<Window>

创建子窗口或者系统窗口,使用Promise异步回调。

需要权限: ohos.permission.SYSTEM_FLOAT_WINDOW(仅当创建窗口类型为window.WindowType.TYPE_FLOAT时需要申请)

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
config Configuration 创建窗口时的参数。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前创建的窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
201 Permission verification failed. The application does not have the permission required to call the API.
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. createWindow can not work correctly due to limited device capabilities.
1300001 Repeated operation.
1300002 This window state is abnormal.
1300004 Unauthorized operation.
1300006 This window context is abnormal.
1300009 The parent window is invalid.

示例:

import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    let config: window.Configuration = {
      name: "test",
      windowType: window.WindowType.TYPE_DIALOG,
      ctx: this.context
    };
    try {
      window.createWindow(config).then((value:window.Window) => {
        console.info('Succeeded in creating the window. Data: ' + JSON.stringify(value));
        value.resize(500, 1000);
      }).catch((err:BusinessError)=> {
        console.error(`Failed to create the window. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to create the window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

window.findWindow9+

findWindow(name: string): Window

查找name所对应的窗口。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 窗口名字,即Configuration中的name。

返回值:

类型 说明
Window 当前查找的窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

let windowClass: window.Window | undefined = undefined;
try {
  windowClass = window.findWindow('test');
} catch (exception) {
  console.error(`Failed to find the Window. Cause code: ${exception.code}, message: ${exception.message}`);
}

window.getLastWindow9+

getLastWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void

获取当前应用内最上层的子窗口,若无应用子窗口,则返回应用主窗口,使用callback异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
ctx BaseContext 当前应用上下文信息。
callback AsyncCallback<Window> 回调函数。返回当前应用内最后显示的窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300006 This window context is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    try {
      window.getLastWindow(this.context, (err: BusinessError, data) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to obtain the top window. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        windowClass = data;
        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
      });
    } catch (exception) {
      console.error(`Failed to obtain the top window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

window.getLastWindow9+

getLastWindow(ctx: BaseContext): Promise<Window>

获取当前应用内最上层的子窗口,若无应用子窗口,则返回应用主窗口,使用Promise异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
ctx BaseContext 当前应用上下文信息。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前应用内最后显示的窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300006 This window context is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    try {
      let promise = window.getLastWindow(this.context);
      promise.then((data) => {
        windowClass = data;
        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
      }).catch((err: BusinessError) => {
        console.error(`Failed to obtain the top window. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to obtain the top window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

window.shiftAppWindowFocus11+

shiftAppWindowFocus(sourceWindowId: number, targetWindowId: number): Promise<void>

在同应用内将窗口焦点从源窗口转移到目标窗口,仅支持应用主窗和子窗的焦点转移。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
sourceWindowId number 源窗口id,必须是获焦状态。
targetWindowId number 目标窗口id。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage) {
    // ...
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    let subWindowClass: window.Window | undefined = undefined;
    let windowClassId: number = -1;
    let subWindowClassId: number = -1;

    try {
      // 获取应用主窗及ID
      let promise = windowStage.getMainWindow();
      promise.then((data) => {
        if (data == null) {
          console.error("Failed to obtaining the window. Cause: The data is empty");
          return;
        }
        windowClass = data;
        windowClass.setUIContent("pages/Index");
        windowClassId = windowClass.getWindowProperties().id;
        console.info('Succeeded in obtaining the window')
      }).catch((err: BusinessError) => {
        console.error(`Failed to obtaining the window. Cause code: ${err.code}, message: ${err.message}`);
      });

      // 创建或获取子窗及ID,此时子窗口获焦
      let promiseSub = windowStage.createSubWindow("testSubWindow");
      promiseSub.then((data) => {
        if (data == null) {
          console.error("Failed to obtaining the window. Cause: The data is empty");
          return;
        }
        subWindowClass = data;
        subWindowClassId = subWindowClass.getWindowProperties().id;
        subWindowClass.resize(500, 500);
        subWindowClass.setUIContent("pages/Index2");
        subWindowClass.showWindow();

        // 监听Window状态,确保已经就绪
        subWindowClass.on("windowEvent", (windowEvent) => {
          if (windowEvent == window.WindowEventType.WINDOW_ACTIVE) {
            // 切换焦点
            let promise = window.shiftAppWindowFocus(subWindowClassId, windowClassId);
            promise.then(() => {
              console.info('Succeeded in shifting app window focus');
            }).catch((err: BusinessError) => {
              console.error(`Failed to shift app window focus. Cause code: ${err.code}, message: ${err.message}`);
            });
          }
        });
      });
    } catch (exception) {
      console.error(`Failed to shift app focus. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

window.shiftAppWindowPointerEvent15+

shiftAppWindowPointerEvent(sourceWindowId: number, targetWindowId: number): Promise<void>

在同应用内窗口分合场景下,需要将输入事件从源窗口转移到目标窗口,使用Promise异步回调,针对主窗和子窗生效。

源窗口需要处于鼠标按下状态,否则调用此接口将不生效。输入事件转移后,会向源窗口补发鼠标抬起事件,并且向目标窗口补发鼠标按下事件。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
sourceWindowId number 源窗口id。推荐使用getWindowProperties()方法获取窗口id属性。
targetWindowId number 目标窗口id。推荐使用getWindowProperties()方法获取窗口id属性。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// ets/pages/Index.ets
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
struct Index {
  build() {
    Row() {
      Column() {
        Blank('160')
          .color(Color.Blue)
          .onTouch((event: TouchEvent) => {
            if (event.type === TouchType.Down) {
              try {
                let sourceWindowId = 1;
                let targetWindowId = 2;
                let promise = window.shiftAppWindowPointerEvent(sourceWindowId, targetWindowId);
                promise.then(() => {
                  console.info('Succeeded in shifting app window pointer event');
                }).catch((err: BusinessError) => {
                  console.error(`Failed to shift app window pointer event. Cause code: ${err.code}, message: ${err.message}`);
                });
              } catch (exception) {
                console.error(`Failed to shift app pointer event. Cause code: ${exception.code}, message: ${exception.message}`);
              }
            }
          })
      }.width('100%')
    }.height('100%').width('100%')
  }
}

window.getWindowsByCoordinate14+

getWindowsByCoordinate(displayId: number, windowNumber?: number, x?: number, y?: number): Promise<Array<Window>>

查询本应用指定坐标下的可见窗口数组,按当前窗口层级排列,层级最高的窗口对应数组下标为0,使用Promise异步回调。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
displayId number 查询窗口所在的displayId,该参数应为整数,可以在窗口属性WindowProperties中获取。
windowNumber number 查询的窗口数量,该参数应为大于0整数,未设置或小于等于0返回所有满足条件的窗口。
x number 查询的x坐标,该参数应为非负整数,未设置或小于0返回所有可见窗口。
y number 查询的y坐标,该参数应为非负整数,未设置或小于0返回所有可见窗口。

返回值:

类型 说明
Promise<Array<Window>> Promise对象。返回获取到的窗口对象数组。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300003 This window manager service works abnormally.
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
    
  onWindowStageCreate(windowStage: window.WindowStage): void {
    try {
      let windowClass = windowStage.getMainWindowSync();
      let properties = windowClass.getWindowProperties();
      window.getWindowsByCoordinate(properties.displayId).then((data) => {
        console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
        for (let window of data) {
          // do something with window
        }
      }).catch((err: BusinessError) => {
        console.error(`Failed to get window from point. Cause code: ${err.code}, message: ${err.message}`);
      });
      window.getWindowsByCoordinate(properties.displayId, 2, 500, 500).then((data) => {
        console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
        for (let window of data) {
          // do something with window
        }
      }).catch((err: BusinessError) => {
        console.error(`Failed to get window from point. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to get window from point. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

window.getAllWindowLayoutInfo15+

getAllWindowLayoutInfo(displayId: number): Promise<Array<WindowLayoutInfo>>

获取指定屏幕上可见的窗口布局信息数组,按当前窗口层级排列,层级最高的对应数组index为0,使用Promise异步回调。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
displayId number 需要获取窗口布局信息的displayId,该参数应为整数,且为当前实际存在屏幕的displayId,可以通过窗口属性WindowProperties获取。

返回值:

类型 说明
Promise<Array<WindowLayoutInfo>> Promise对象。返回获取到的窗口布局信息对象数组。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. function getAllWindowLayoutInfo can not work correctly due to limited device capabilities.
1300003 This window manager service works abnormally.
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  let displayId = 0;
  let promise = window.getAllWindowLayoutInfo(displayId);
  promise.then((data) => {
    console.info('Succeeded in obtaining all window layout info. Data: ' + JSON.stringify(data));
  }).catch((err: BusinessError) => {
    console.error(`Failed to obtain all window layout info. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to obtain all window layout info. Cause code: ${exception.code}, message: ${exception.message}`);
}

window.create(deprecated)

create(id: string, type: WindowType, callback: AsyncCallback<Window>): void

创建子窗口,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用createWindow()

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
id string 窗口名字,即Configuration中的name。
type WindowType 窗口类型。
callback AsyncCallback<Window> 回调函数。返回当前创建的子窗口对象。

示例:

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

let windowClass: window.Window | undefined = undefined;
window.create('test', window.WindowType.TYPE_APP, (err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to create the subWindow. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  windowClass = data;
  console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data));
});

window.create(deprecated)

create(id: string, type: WindowType): Promise<Window>

创建子窗口,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用createWindow()

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
id string 窗口名字,即Configuration中的name。
type WindowType 窗口类型。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前创建的子窗口对象。

示例:

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

let windowClass: window.Window | undefined = undefined;
let promise = window.create('test', window.WindowType.TYPE_APP);
promise.then((data) => {
  windowClass = data;
  console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error(`Failed to create the subWindow. Cause code: ${err.code}, message: ${err.message}`);
});

window.create(deprecated)

create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback<Window>): void

创建系统窗口,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用createWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
ctx BaseContext 当前应用上下文信息。
id string 窗口名字,即Configuration中的name。
type WindowType 窗口类型。
callback AsyncCallback<Window> 回调函数。返回当前创建的子窗口对象。

示例:

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

let windowClass: window.Window | undefined = undefined;
window.create('test', window.WindowType.TYPE_SYSTEM_ALERT, (err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to create the window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  windowClass = data;
  console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data));
  windowClass.resetSize(500, 1000);
});

window.create(deprecated)

create(ctx: BaseContext, id: string, type: WindowType): Promise<Window>

创建系统窗口,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用createWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
ctx BaseContext 当前应用上下文信息。
id string 窗口名字,即Configuration中的name。
type WindowType 窗口类型。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前创建的子窗口对象。

示例:

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

let windowClass: window.Window | undefined = undefined;
let promise = window.create('test', window.WindowType.TYPE_SYSTEM_ALERT);
promise.then((data) => {
  windowClass = data;
  console.info('Succeeded in creating the window. Data:' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error(`Failed to create the Window. Cause code: ${err.code}, message: ${err.message}`);
});

window.find(deprecated)

find(id: string, callback: AsyncCallback<Window>): void

查找id所对应的窗口,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用findWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
id string 窗口名字,即Configuration中的name。
callback AsyncCallback<Window> 回调函数。返回当前查找到的窗口对象。

示例:

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

let windowClass: window.Window | undefined = undefined;
window.find('test', (err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to find the Window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  windowClass = data;
  console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data));
});

window.find(deprecated)

find(id: string): Promise<Window>

查找id所对应的窗口,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用findWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
id string 窗口名字,即Configuration中的name。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前查找的窗口对象。

示例:

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

let windowClass: window.Window | undefined = undefined;
let promise = window.find('test');
promise.then((data) => {
  windowClass = data;
  console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error(`Failed to find the Window. Cause code: ${err.code}, message: ${err.message}`);
});

window.getTopWindow(deprecated)

getTopWindow(callback: AsyncCallback<Window>): void

获取当前应用内最后显示的窗口,使用callback异步回调。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用getLastWindow()

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<Window> 回调函数。返回当前应用内最后显示的窗口对象。

示例:

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

let windowClass: window.Window | undefined = undefined;
window.getTopWindow((err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to obtain the top window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  windowClass = data;
  console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
});

window.getTopWindow(deprecated)

getTopWindow(): Promise<Window>

获取当前应用内最后显示的窗口,使用Promise异步回调。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用getLastWindow()

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

类型 说明
Promise<Window> Promise对象。返回当前应用内最后显示的窗口对象。

示例:

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

let windowClass: window.Window | undefined = undefined;
let promise = window.getTopWindow();
promise.then((data)=> {
    windowClass = data;
    console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
}).catch((err: BusinessError)=>{
    console.error(`Failed to obtain the top window. Cause code: ${err.code}, message: ${err.message}`);
});

window.getTopWindow(deprecated)

getTopWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void

获取当前应用内最后显示的窗口,使用callback异步回调。

说明:

从API version 8开始支持,从API version 9开始废弃,推荐使用getLastWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
ctx BaseContext 当前应用上下文信息。
callback AsyncCallback<Window> 回调函数。返回当前应用内最后显示的窗口对象。

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage:window.WindowStage){
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    try {
      window.getTopWindow(this.context, (err: BusinessError, data) => {
        const errCode: number = err.code;
        if(errCode){
          console.error(`Failed to obtain the top window. Cause code: ${err.code}, message: ${err.message}`);
          return ;
        }
        windowClass = data;
        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
      });
    } catch(error){
      console.error(`Failed to obtain the top window. Cause code: ${error.code}, message: ${error.message}`);
    }
  }
}

window.getTopWindow(deprecated)

getTopWindow(ctx: BaseContext): Promise<Window>

获取当前应用内最后显示的窗口,使用Promise异步回调。

说明:

从API version 8开始支持,从API version 9开始废弃,推荐使用getLastWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
ctx BaseContext 当前应用上下文信息。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前应用内最后显示的窗口对象。

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage:window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    let promise = window.getTopWindow(this.context);
    promise.then((data) => {
      windowClass = data;
      console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
    }).catch((error: BusinessError) => {
      console.error(`Failed to obtain the top window. Cause code: ${error.code}, message: ${error.message}`);
    });
  }
}

window.getVisibleWindowInfo18+

getVisibleWindowInfo(): Promise<Array<WindowInfo>>

获取当前屏幕的可见主窗口(未退至后台的主窗口)信息。使用Promise异步回调。

系统能力: SystemCapability.Window.SessionManager

需要权限: ohos.permission.VISIBLE_WINDOW_INFO

返回值:

类型 说明
Promise<Array<WindowInfo>> Promise对象,返回当前可见窗口的相关信息。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
201 Permission verification failed. The application does not have the permission required to call the API.
801 Capability not supported. Function getVisibleWindowInfo can not work correctly due to limited device capabilities.
1300003 This window manager service works abnormally.

示例:

import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  let promise = window.getVisibleWindowInfo();
  promise.then((data) => {
    data.forEach(windowInfo=>{
      console.info(`left:${windowInfo.rect.left}`);
      console.info(`top:${windowInfo.rect.top}`);
      console.info(`width:${windowInfo.rect.width}`);
      console.info(`height:${windowInfo.rect.height}`);
      console.info(`windowId:${windowInfo.windowId}`);
      console.info(`windowStatusType:${windowInfo.windowStatusType}`);
      console.info(`abilityName:${windowInfo.abilityName}`);
      console.info(`bundleName:${windowInfo.bundleName}`);
      console.info(`isFocused:${windowInfo.isFocused}`);
    })
  }).catch((err: BusinessError) => {
    console.error('Failed to getWindowInfo. Cause: ' + JSON.stringify(err));
  });
} catch (exception) {
  console.error(`Failed to get visible window info. Cause code: ${exception.code}, message: ${exception.message}`);
}

SpecificSystemBar11+

type SpecificSystemBar = 'status' | 'navigation' | 'navigationIndicator'

当前支持显示或隐藏的系统栏类型。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

类型 说明
'status' 状态栏。
'navigation' 三键导航栏。
'navigationIndicator' 底部导航。OpenHarmony各设备不支持此能力。

Window

当前窗口实例,窗口管理器管理的基本单元。

下列API示例中都需先使用getLastWindow()createWindow()findWindow()中的任一方法获取到Window实例(windowClass),再通过此实例调用对应方法。

showWindow9+

showWindow(callback: AsyncCallback<void>): void

显示当前窗口,使用callback异步回调,仅支持系统窗口与应用子窗口,或将已显示的应用主窗口层级提升至顶部。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

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

windowClass.showWindow((err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to show the window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in showing the window.');
});

showWindow9+

showWindow(): Promise<void>

显示当前窗口,使用Promise异步回调,仅支持系统窗口与应用子窗口,或将已显示的应用主窗口层级提升至顶部。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

返回值:

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

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

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

let promise = windowClass.showWindow();
promise.then(() => {
  console.info('Succeeded in showing the window.');
}).catch((err: BusinessError) => {
  console.error(`Failed to show the window. Cause code: ${err.code}, message: ${err.message}`);
});

destroyWindow9+

destroyWindow(callback: AsyncCallback<void>): void

销毁当前窗口,使用callback异步回调,仅支持系统窗口及应用子窗口。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

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

windowClass.destroyWindow((err) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to destroy the window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in destroying the window.');
});

destroyWindow9+

destroyWindow(): Promise<void>

销毁当前窗口,使用Promise异步回调,仅支持系统窗口及应用子窗口。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

返回值:

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

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

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

let promise = windowClass.destroyWindow();
promise.then(() => {
  console.info('Succeeded in destroying the window.');
}).catch((err: BusinessError) => {
  console.error(`Failed to destroy the window. Cause code: ${err.code}, message: ${err.message}`);
});

moveWindowTo9+

moveWindowTo(x: number, y: number, callback: AsyncCallback<void>): void

移动窗口位置,使用callback异步回调。

全屏模式下,本接口仅在2in1设备上生效。 在2in1设备上窗口相对于屏幕移动,其他设备上窗口相对于父窗口移动。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
x number 窗口在x轴方向移动到的坐标位置,单位为px,值为正表示位置在x轴右侧;值为负表示位置在x轴左侧;值为0表示位置在x轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。
y number 窗口在y轴方向移动到的坐标位置,单位为px,值为正表示位置在y轴下侧;值为负表示位置在y轴上侧;值为0表示位置在y轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

try {
  windowClass.moveWindowTo(300, 300, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to move the window. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in moving the window.');
  });
} catch (exception) {
  console.error(`Failed to move the window. Cause code: ${exception.code}, message: ${exception.message}`);
}

moveWindowTo9+

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

移动窗口位置,使用Promise异步回调。调用成功即返回,该接口返回后无法立即获取最终生效结果,如需立即获取,建议使用接口moveWindowToAsync()

全屏模式下,本接口仅在2in1设备上生效。 使用此接口,在2in1设备上窗口相对于屏幕移动,在其他设备上窗口相对于父窗口移动。若需要在非2in1设备上相对于屏幕进行移动,建议使用接口moveWindowToGlobal()

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
x number 窗口在x轴方向移动到的坐标位置,单位为px,值为正表示位置在x轴右侧;值为负表示位置在x轴左侧;值为0表示位置在x轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。
y number 窗口在y轴方向移动到的坐标位置,单位为px,值为正表示位置在y轴下侧;值为负表示位置在y轴上侧;值为0表示位置在y轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

try {
  let promise = windowClass.moveWindowTo(300, 300);
  promise.then(() => {
    console.info('Succeeded in moving the window.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to move the window. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to move the window. Cause code: ${exception.code}, message: ${exception.message}`);
}

moveWindowToAsync12+

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

移动窗口位置,使用Promise异步回调。调用生效后返回,回调中可使用getWindowProperties()(见示例)立即获取最终生效结果。

仅在自由悬浮窗口模式(即窗口模式为window.WindowStatusType.FLOATING)下生效。 在2in1设备上窗口相对于屏幕移动,其他设备上窗口相对于父窗口移动。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
x number 窗口在x轴方向移动到的坐标位置,单位为px,值为正表示位置在x轴右侧;值为负表示位置在x轴左侧;值为0表示位置在x轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。
y number 窗口在y轴方向移动到的坐标位置,单位为px,值为正表示位置在y轴下侧;值为负表示位置在y轴上侧;值为0表示位置在y轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300010 The operation in the current window status is invalid.

示例:

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

try {
  let promise = windowClass.moveWindowToAsync(300, 300);
  promise.then(() => {
    console.info('Succeeded in moving the window.');
    let rect = windowClass?.getWindowProperties().windowRect;
    console.info(`Get window rect: ${JSON.stringify(rect)}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to move the window. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to move the window. Cause code: ${exception.code}, message: ${exception.message}`);
}

moveWindowToAsync15+

moveWindowToAsync(x: number, y: number, moveConfiguration?: MoveConfiguration): Promise<void>

移动窗口位置,使用Promise异步回调。调用生效后返回,回调中可使用getWindowProperties()(见示例)立即获取最终生效结果。

仅在自由悬浮窗口模式(即窗口模式为window.WindowStatusType.FLOATING)下生效。 在2in1设备上窗口相对于屏幕移动,其他设备上窗口相对于父窗口移动。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
x number 窗口在x轴方向移动的值,值为正表示右移,单位为px,该参数应该为整数,非整数输入将向下取整。
y number 窗口在y轴方向移动的值,值为正表示下移,单位为px,该参数应该为整数,非整数输入将向下取整。
moveConfiguration MoveConfiguration 窗口移动选项,未设置将默认保持为当前屏幕。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300010 The operation in the current window status is invalid.

示例:

import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  let moveConfiguration: window.MoveConfiguration = {
    displayId: 0
  };
  let promise = windowClass.moveWindowToAsync(300, 300, moveConfiguration);
  promise.then(() => {
    console.info('Succeeded in moving the window.');
    let rect = windowClass?.getWindowProperties().windowRect;
    console.info(`Get window rect: ${JSON.stringify(rect)}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to move the window. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to move the window. Cause code: ${exception.code}, message: ${exception.message}`);
}

moveWindowToGlobal13+

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

基于屏幕坐标移动窗口位置,使用Promise异步回调。调用生效后返回,回调中可使用getWindowProperties()(见示例)立即获取最终生效结果。

全屏模式窗口不支持该操作。

在非2in1设备下,子窗会跟随主窗移动。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 13开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
x number 表示以屏幕左上角为起点,窗口在x轴方向移动的值,单位为px。值为正表示右移,值为负表示左移。该参数仅支持整数输入,浮点数输入将向下取整。
y number 表示以屏幕左上角为起点,窗口在y轴方向移动的值,单位为px。值为正表示下移,值为负表示上移。该参数仅支持整数输入,浮点数输入将向下取整。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300010 The operation in the current window status is invalid.

示例:

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

try {
  let promise = windowClass.moveWindowToGlobal(300, 300);
  promise.then(() => {
    console.info('Succeeded in moving the window.');
    let rect = windowClass?.getWindowProperties().windowRect;
    console.info(`Get window rect: ${JSON.stringify(rect)}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to move the window. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to move the window. Cause code: ${exception.code}, message: ${exception.message}`);
}

moveWindowToGlobal15+

moveWindowToGlobal(x: number, y: number, moveConfiguration?: MoveConfiguration): Promise<void>

基于屏幕坐标移动窗口位置,使用Promise异步回调。调用生效后返回,回调中可使用getWindowProperties()(见示例)立即获取最终生效结果。

全屏模式窗口不支持该操作。

在非2in1设备下,子窗会跟随主窗移动。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
x number 表示以目标屏幕左上角为起点,窗口在x轴方向移动的值,单位为px。值为正表示右移,值为负表示左移。该参数应该为整数,非整数输入将向下取整。
y number 表示以目标屏幕左上角为起点,窗口在y轴方向移动的值,单位为px。值为正表示下移,值为负表示上移。该参数应该为整数,非整数输入将向下取整。
moveConfiguration MoveConfiguration 窗口移动选项,未设置将默认保持为当前屏幕。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300010 The operation in the current window status is invalid.

示例:

import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  let moveConfiguration: window.MoveConfiguration = {
    displayId: 0
  };
  let promise = windowClass.moveWindowToGlobal(300, 300, moveConfiguration);
  promise.then(() => {
    console.info('Succeeded in moving the window.');
    let rect = windowClass?.getWindowProperties().windowRect;
    console.info(`Get window rect: ${JSON.stringify(rect)}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to move the window. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to move the window. Cause code: ${exception.code}, message: ${exception.message}`);
}

resize9+

resize(width: number, height: number, callback: AsyncCallback<void>): void

改变当前窗口大小,使用callback异步回调。

应用主窗口与子窗口存在大小限制,默认宽度范围:[320, 1920],默认高度范围:[240, 1920],单位为vp。 应用主窗口与子窗口的最小宽度与最小高度可由产品端进行配置,配置后的最小宽度与最小高度以产品端配置值为准,具体尺寸限制范围可以通过getWindowLimits接口进行查询。

系统窗口存在大小限制,宽度范围:(0, 1920],高度范围:(0, 1920],单位为vp。

设置的宽度与高度受到此约束限制,规则: 若所设置的窗口宽/高尺寸小于窗口最小宽/高限值,则窗口最小宽/高限值生效; 若所设置的窗口宽/高尺寸大于窗口最大宽/高限值,则窗口最大宽/高限值生效。

全屏模式窗口不支持该操作。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
width number 目标窗口的宽度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。
height number 目标窗口的高度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

try {
  windowClass.resize(500, 1000, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to change the window size. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in changing the window size.');
  });
} catch (exception) {
  console.error(`Failed to change the window size. Cause code: ${exception.code}, message: ${exception.message}`);
}

resize9+

resize(width: number, height: number): Promise<void>

改变当前窗口大小,使用Promise异步回调。调用成功即返回,该接口返回后无法立即获取最终生效结果,如需立即获取,建议使用接口resizeAsync()

应用主窗口与子窗口存在大小限制,默认宽度范围:[320, 1920],默认高度范围:[240, 1920],单位为vp。 应用主窗口与子窗口的最小宽度与最小高度可由产品端进行配置,配置后的最小宽度与最小高度以产品端配置值为准,具体尺寸限制范围可以通过getWindowLimits接口进行查询。

系统窗口存在大小限制,宽度范围:(0, 1920],高度范围:(0, 1920],单位为vp。

设置的宽度与高度受到此约束限制,规则: 若所设置的窗口宽/高尺寸小于窗口最小宽/高限值,则窗口最小宽/高限值生效; 若所设置的窗口宽/高尺寸大于窗口最大宽/高限值,则窗口最大宽/高限值生效。

全屏模式窗口不支持该操作。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
width number 目标窗口的宽度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。
height number 目标窗口的高度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

try {
  let promise = windowClass.resize(500, 1000);
  promise.then(() => {
    console.info('Succeeded in changing the window size.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to change the window size. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to change the window size. Cause code: ${exception.code}, message: ${exception.message}`);
}

resizeAsync12+

resizeAsync(width: number, height: number): Promise<void>

改变当前窗口大小,使用Promise异步回调。调用生效后返回,回调中可使用getWindowProperties()(见示例)立即获取最终生效结果。

应用主窗口与子窗口存在大小限制,默认宽度范围:[320, 1920],默认高度范围:[240, 1920],单位为vp。 应用主窗口与子窗口的最小宽度与最小高度可由产品端进行配置,配置后的最小宽度与最小高度以产品端配置值为准,具体尺寸限制范围可以通过getWindowLimits接口进行查询。

系统窗口存在大小限制,宽度范围:(0, 1920],高度范围:(0, 1920],单位为vp。

设置的宽度与高度受到此约束限制,规则: 若所设置的窗口宽/高尺寸小于窗口最小宽/高限值,则窗口最小宽/高限值生效; 若所设置的窗口宽/高尺寸大于窗口最大宽/高限值,则窗口最大宽/高限值生效。

全屏模式窗口不支持该操作。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
width number 目标窗口的宽度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。
height number 目标窗口的高度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300010 The operation in the current window status is invalid.

示例:

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

try {
  let promise = windowClass.resizeAsync(500, 1000);
  promise.then(() => {
    console.info('Succeeded in changing the window size.');
    let rect = windowClass?.getWindowProperties().windowRect;
    console.info(`Get window rect: ${JSON.stringify(rect)}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to change the window size. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to change the window size. Cause code: ${exception.code}, message: ${exception.message}`);
}

getWindowProperties9+

getWindowProperties(): WindowProperties

获取当前窗口的属性,返回WindowProperties。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
WindowProperties 当前窗口属性。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

try {
  let properties = windowClass.getWindowProperties();
} catch (exception) {
  console.error(`Failed to obtain the window properties. Cause code: ${exception.code}, message: ${exception.message}`);
}

getWindowDensityInfo15+

getWindowDensityInfo(): WindowDensityInfo

获取当前窗口所在屏幕的系统显示大小缩放系数、系统默认显示大小缩放系数和自定义显示大小缩放系数信息。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
WindowDensityInfo 当前窗口的显示大小缩放系数信息。当返回值为[-1, -1, -1]时,表示当前设备不支持使用该接口。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

try {
  let densityInfo = windowClass.getWindowDensityInfo();
} catch (exception) {
  console.error(`Failed to obtain the window densityInfo. Cause code: ${exception.code}, message: ${exception.message}`);
}

getGlobalRect13+

getGlobalRect(): Rect

获取窗口在屏幕上的真实显示区域,同步接口。

在某些设备上,窗口显示时可能经过了缩放,此接口可以获取缩放后窗口在屏幕上的真实位置和大小。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 13开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
Rect 四元组分别表示距离屏幕左上角的x坐标、距离屏幕左上角的y坐标、缩放后的窗口宽度和缩放后的窗口高度。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

try {
  let rect = windowClass.getGlobalRect();
  console.info(`Succeeded in getting window rect: ` + JSON.stringify(rect));
} catch (exception) {
  console.error(`Failed to get window rect. Cause code: ${exception.code}, message: ${exception.message}`);
}

getWindowAvoidArea9+

getWindowAvoidArea(type: AvoidAreaType): AvoidArea

获取当前应用窗口避让区。避让区指系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。

该接口一般适用于三种场景:1、在onWindowStageCreate方法中,获取应用启动时的初始布局避让区域时可调用该接口;2、当应用内子窗需要临时显示,对显示内容做布局避让时可调用该接口;3、创建悬浮窗、模态窗或WindowType窗口类型为系统窗口时,调用setSystemAvoidAreaEnabled方法使能后,该接口对此类窗口亦生效。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type AvoidAreaType 表示规避区类型。

返回值:

类型 说明
AvoidArea 窗口内容规避区域。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.

示例:

let type = window.AvoidAreaType.TYPE_SYSTEM;
try {
  let avoidArea = windowClass.getWindowAvoidArea(type);
} catch (exception) {
  console.error(`Failed to obtain the area. Cause code: ${exception.code}, message: ${exception.message}`);
}

setSystemAvoidAreaEnabled18+

setSystemAvoidAreaEnabled(enabled: boolean): Promise<void>

创建悬浮窗、模态窗或WindowType窗口类型为系统窗口时,可以调用该接口使能窗口获取避让区

该接口一般适用于此场景:应用于创建上述类型窗口并希望获取避让区信息时,需要在创建窗口后调用该接口设置使能该窗口,再调用getWindowAvoidArea()on('avoidAreaChange')获取或监听避让区。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
enabled boolean 是否可以获取到避让区。
true表示可以获取避让区;false表示不可以获取避让区。默认值是false。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

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

let windowClass: window.Window | undefined = undefined;
let config: window.Configuration = {
  name: "test",
  windowType: window.WindowType.TYPE_DIALOG,
  decorEnabled: true,
  ctx: this.context
};
try {
  window.createWindow(config, (err: BusinessError, data) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to create the system window. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    windowClass = data;
    windowClass.setUIContent("pages/Test");
    let enabled = true;
    let promise = windowClass.setSystemAvoidAreaEnabled(enabled);
    promise.then(() => {
      let type = window.AvoidAreaType.TYPE_SYSTEM;
      let avoidArea = windowClass?.getWindowAvoidArea(type);
    }).catch((err: BusinessError) => {
      console.error(`Failed to obtain the system window avoid area. Cause code: ${err.code}, message: ${err.message}`);
    });
  });
} catch (exception) {
  console.error(`Failed to create the system window. Cause code: ${exception.code}, message: ${exception.message}`);
}

isSystemAvoidAreaEnabled18+

isSystemAvoidAreaEnabled(): boolean

获取悬浮窗、模态窗或WindowType为系统类型的窗口是否可以获取窗口内容的避让区

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
boolean 是否可以获取窗口内容的避让区。
true表示可以获取避让区;false表示不可以获取避让区。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

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

let windowClass: window.Window | undefined = undefined;
let config: window.Configuration = {
  name: "test",
  windowType: window.WindowType.TYPE_DIALOG,
  decorEnabled: true,
  ctx: this.context
};
try {
  window.createWindow(config, (err: BusinessError, data) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to create the system window. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    windowClass = data;
    windowClass.setUIContent("pages/Test");
    let enabled = true;
    let promise = windowClass.setSystemAvoidAreaEnabled(enabled);
    promise.then(() => {
      let enable = windowClass?.isSystemAvoidAreaEnabled();
    }).catch((err: BusinessError) => {
      console.error(`Failed to obtain whether the system window can get avoid area. Cause code: ${err.code}, message: ${err.message}`);
    });
  });
} catch (exception) {
  console.error(`Failed to create the system window. Cause code: ${exception.code}, message: ${exception.message}`);
}

setTitleAndDockHoverShown14+

setTitleAndDockHoverShown(isTitleHoverShown?: boolean, isDockHoverShown?: boolean): Promise<void>

设置主窗口进入全屏模式时鼠标Hover到热区上是否显示窗口标题栏和dock栏,使用Promise异步回调,仅2in1设备可用。

系统能力:SystemCapability.Window.SessionManager

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
isTitleHoverShown boolean 是否显示窗口标题栏。
true表示显示窗口标题栏;false表示不显示窗口标题栏。默认值是true。
isDockHoverShown boolean 是否显示dock栏。
true表示显示dock栏;false表示不显示dock栏。默认值是true。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    // 加载主窗口对应的页面。
    windowStage.loadContent('pages/Index', (err) => {
      let mainWindow: window.Window | undefined = undefined;
      // 获取应用主窗口。
      windowStage.getMainWindow().then(
        data => {
          mainWindow = data;
          console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
          // 调用maximize接口,设置窗口进入全屏模式。
          mainWindow.maximize(window.MaximizePresentation.ENTER_IMMERSIVE);
          // 调用setTitleAndDockHoverShown接口,隐藏标题栏和dock栏。
          mainWindow.setTitleAndDockHoverShown(false, false);
        }
      ).catch((err: BusinessError) => {
          if(err.code){
            console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
          }
      });
    });
  }
}

setWindowLayoutFullScreen9+

setWindowLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void>

设置主窗口或子窗口的布局是否为沉浸式布局,使用Promise异步回调。系统窗口调用不生效。从API version 14开始,该接口在2in1设备上调用不生效。 沉浸式布局生效时,布局不避让状态栏与三键导航栏,组件可能产生与其重叠的情况。 非沉浸式布局生效时,布局避让状态栏与三键导航栏,组件不会与其重叠。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
isLayoutFullScreen boolean 窗口的布局是否为沉浸式布局(该沉浸式布局状态栏、三键导航栏仍然显示)。true表示沉浸式布局;false表示非沉浸式布局。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let isLayoutFullScreen = true;
      try {
        let promise = windowClass.setWindowLayoutFullScreen(isLayoutFullScreen);
        promise.then(() => {
          console.info('Succeeded in setting the window layout to full-screen mode.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set the window layout to full-screen mode. Cause code: ${err.code}, message: ${err.message}`);
        });
      } catch (exception) {
        console.error(`Failed to set the window layout to full-screen mode. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setImmersiveModeEnabledState12+

setImmersiveModeEnabledState(enabled: boolean): void

设置当前窗口是否开启沉浸式布局,该调用不会改变窗口模式和窗口大小。仅主窗口和子窗口可调用。从API version 14开始,该接口在2in1设备上调用不生效。

系统能力:SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
enabled boolean 是否开启沉浸式布局。
true表示开启,false表示关闭。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

try {
  let enabled = false;
  windowClass.setImmersiveModeEnabledState(enabled);
} catch (exception) {
  console.error(`Failed to set the window immersive mode enabled status. Cause code: ${exception.code}, message: ${exception.message}`);
}

getImmersiveModeEnabledState12+

getImmersiveModeEnabledState(): boolean

查询当前窗口是否开启沉浸式布局。

返回值与setImmersiveModeEnabledState()以及setWindowLayoutFullScreen()设置结果一致,若未调用上述两个接口则默认返回false。

系统能力:SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
boolean 是否设置开启沉浸式布局。
true表示开启沉浸式布局,false表示关闭沉浸式布局。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

try {
  let isEnabled = windowClass.getImmersiveModeEnabledState();
} catch (exception) {
  console.error(`Failed to get the window immersive mode enabled status. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowDelayRaiseOnDrag19+

setWindowDelayRaiseOnDrag(isEnabled: boolean): void

设置窗口是否使能延迟抬升,仅主窗和子窗可设置。
不调用此接口或传入false,主窗和子窗在鼠标左键按下时,默认立即抬升。
调用此接口使能延迟抬升后,在跨窗拖拽场景,可拖拽组件所在窗口在鼠标左键按下时不会立即抬升,直到鼠标左键抬起。

此接口仅可在2in1设备下使用。

系统能力:SystemCapability.Window.SessionManager

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
isEnabled boolean 是否使能延迟抬升。
true表示使能窗口延迟抬升;false表示不使能窗口延迟抬升。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported.function setWindowDelayRaiseOnDrag can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.

示例:

try {
  windowClass.setWindowDelayRaiseOnDrag(true);
} catch (exception) {
  console.error(`Failed to set window delay raise. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowSystemBarEnable9+

setWindowSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void>

设置主窗口状态栏、三键导航栏的可见模式,状态栏通过status控制、三键导航栏通过navigation控制,使用Promise异步回调。
从API version 12开始,该接口在2in1设备上调用不生效。

调用生效后返回并不表示状态栏和三键导航栏的显示或隐藏已完成。子窗口调用后不生效。非全屏模式(悬浮窗、分屏等场景)下配置不生效。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
names Array<'status'|'navigation'> 设置窗口全屏模式时状态栏、三键导航栏是否显示。
例如,需全部显示,该参数设置为['status', 'navigation'];设置为[],则不显示。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// 此处以状态栏等均不显示为例
// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let names: Array<'status' | 'navigation'> = [];
      try {
        let promise = windowClass.setWindowSystemBarEnable(names);
        promise.then(() => {
          console.info('Succeeded in setting the system bar to be invisible.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set the system bar to be invisible. Cause code: ${err.code}, message: ${err.message}`);
        });
      } catch (exception) {
        console.error(`Failed to set the system bar to be invisible. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setSpecificSystemBarEnabled11+

setSpecificSystemBarEnabled(name: SpecificSystemBar, enable: boolean, enableAnimation?: boolean): Promise<void>

设置主窗口状态栏、三键导航栏的显示和隐藏,使用Promise异步回调。
从API version 12开始,该接口在2in1设备上调用不生效。

调用生效后返回并不表示状态栏和三键导航栏的显示或隐藏已完成。子窗口调用后不生效。非全屏模式(悬浮窗、分屏等场景)下配置不生效。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name SpecificSystemBar 设置窗口全屏模式时,显示或隐藏的系统栏类型。
enable boolean 设置窗口全屏模式时状态栏或三键导航栏是否显示,true表示显示, false表示隐藏。
enableAnimation12+ boolean 设置状态栏或三键导航栏显示状态变化时是否使用动画,true表示使用, false表示不使用,默认值为false。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// 此处以隐藏状态栏为例
// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      try {
        let promise = windowClass.setSpecificSystemBarEnabled('status', false);
        promise.then(() => {
          console.info('Succeeded in setting the system bar to be invisible.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set the system bar to be invisible. Cause code: ${err.code}, message: ${err.message}`);
        });
      } catch (exception) {
        console.error(`Failed to set the system bar to be invisible. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setWindowSystemBarProperties9+

setWindowSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<void>

设置主窗口三键导航栏、状态栏的属性,使用Promise异步回调,该接口在2in1设备上调用不生效。

子窗口调用后不生效。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
systemBarProperties SystemBarProperties 三键导航栏、状态栏的属性。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let SystemBarProperties: window.SystemBarProperties = {
        statusBarColor: '#ff00ff',
        navigationBarColor: '#00ff00',
        //以下两个属性从API Version8开始支持
        statusBarContentColor: '#ffffff',
        navigationBarContentColor: '#00ffff'
      };
      try {
        let promise = windowClass.setWindowSystemBarProperties(SystemBarProperties);
        promise.then(() => {
          console.info('Succeeded in setting the system bar properties.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set the system bar properties. Cause code: ${err.code}, message: ${err.message}`);
        });
      } catch (exception) {
        console.error(`Failed to set the system bar properties. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

getWindowSystemBarProperties12+

getWindowSystemBarProperties(): SystemBarProperties

主窗口获取三键导航栏、状态栏的属性。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
SystemBarProperties 当前三键导航栏、状态栏属性。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      try {
        let systemBarProperty = windowClass.getWindowSystemBarProperties();
        console.info('Success in obtaining system bar properties. Property: ' + JSON.stringify(systemBarProperty));
      } catch (err) {
        console.error(`Failed to get system bar properties. Code: ${err.code}, message: ${err.message}`);
      }
    });
  }
};

setStatusBarColor18+

setStatusBarColor(color: ColorMetrics): Promise<void>

设置主窗口状态栏的文字颜色,使用Promise异步回调。该接口在2in1设备上调用不生效。

子窗口不支持设置状态栏文字颜色,调用无效果。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
color ColorMetrics 要设置的状态栏颜色值。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported on this device.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { ColorMetrics, window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      try {
        let promise = windowClass.setStatusBarColor(ColorMetrics.numeric(0x112233));
        promise.then(() => {
          console.info('Succeeded in setting the status bar color.');
        }).catch((err: BusinessError) => {
          console.error(`Set the status bar color failed. Cause code: ${err.code}, message: ${err.message}`);
        });
      } catch (exception) {
        console.error(`Failed to set the status bar color. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

getStatusBarProperty18+

getStatusBarProperty(): StatusBarProperty

获取主窗口状态栏的属性,如状态栏文字颜色。

子窗口不支持查询,调用会返回错误码1300002。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
StatusBarProperty 当前状态栏属性,如状态栏颜色。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported on this device.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage) {
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      try {
        let statusBarProperty = windowClass.getStatusBarProperty();
        console.info('Succeeded in obtaining system bar properties. Property: ' + JSON.stringify(statusBarProperty));
      } catch (err) {
        console.error(`Failed to get system bar properties. Code: ${err.code}, message: ${err.message}`);
      }
    });
  }
};

setPreferredOrientation9+

setPreferredOrientation(orientation: Orientation, callback: AsyncCallback<void>): void

设置主窗口的显示方向属性,使用callback异步回调。仅在支持跟随sensor旋转的设备上生效,2in1设备上调用不生效,子窗口调用后不生效。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
orientation Orientation 窗口显示方向的属性。
callback AsyncCallback<void> 回调函数。该回调函数返回调用结果是否成功,非应用旋转动效结束。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let orientation = window.Orientation.AUTO_ROTATION;
      try {
        windowClass.setPreferredOrientation(orientation, (err: BusinessError) => {
          const errCode: number = err.code;
          if (errCode) {
            console.error(`Failed to set window orientation. Cause code: ${err.code}, message: ${err.message}`);
            return;
          }
          console.info('Succeeded in setting window orientation.');
        });
      } catch (exception) {
        console.error(`Failed to set window orientation. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setPreferredOrientation9+

setPreferredOrientation(orientation: Orientation): Promise<void>

设置主窗口的显示方向属性,使用Promise异步回调。仅在支持跟随sensor旋转的设备上生效,2in1设备上调用不生效,子窗口调用后不生效。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
orientation Orientation 窗口显示方向的属性。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let orientation = window.Orientation.AUTO_ROTATION;
      try {
        let promise = windowClass.setPreferredOrientation(orientation);
        promise.then(() => {
          console.info('Succeeded in setting the window orientation.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set the window orientation. Cause code: ${err.code}, message: ${err.message}`);
        });
      } catch (exception) {
        console.error(`Failed to set window orientation. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

getPreferredOrientation12+

getPreferredOrientation(): Orientation

主窗口调用,获取窗口的显示方向属性。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
Orientation 窗口显示方向的属性。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      try {
        let orientation = windowClass.getPreferredOrientation();
      } catch (exception) {
        console.error(`Failed to get window orientation. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
};

getUIContext10+

getUIContext(): UIContext

获取UIContext实例。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
UIContext 返回UIContext实例对象。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window, UIContext } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage) {
    // 为主窗口加载对应的目标页面。
    windowStage.loadContent("pages/page2", (err: BusinessError) => {
      let errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      console.info('Succeeded in loading the content.');
      // 获取应用主窗口。
      let windowClass: window.Window | undefined = undefined;
      windowStage.getMainWindow((err: BusinessError, data) => {
        let errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        windowClass = data;
        console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
        // 获取UIContext实例。
        let uiContext: UIContext | null = null;
        uiContext = windowClass.getUIContext();
      });
    });
  }
};

setUIContent9+

setUIContent(path: string, callback: AsyncCallback<void>): void

根据当前工程中指定的某个页面路径为窗口加载具体页面内容,使用callback异步回调。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,Stage模型下该路径需添加到工程的main_pages.json文件中,FA模型下该路径需添加到工程的config.json文件中。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

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

try {
  windowClass.setUIContent('pages/page2/page3', (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in loading the content.');
  });
} catch (exception) {
  console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
}

setUIContent9+

setUIContent(path: string): Promise<void>

根据当前工程中指定的某个页面路径为窗口加载具体页面内容,使用Promise异步回调。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,Stage模型下该路径需添加到工程的main_pages.json文件中,FA模型下该路径需添加到工程的config.json文件中。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

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

try {
  let promise = windowClass.setUIContent('pages/page2/page3');
  promise.then(() => {
    console.info('Succeeded in loading the content.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
}

loadContent9+

loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void>): void

根据当前工程中指定的页面路径为窗口加载具体页面内容,通过LocalStorage传递状态属性给加载的页面,使用callback异步回调。建议在UIAbility启动过程中使用该接口,重复调用将先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,该路径需添加到工程的main_pages.json文件中。
storage LocalStorage 页面级UI状态存储单元,这里用于为加载到窗口的页面内容传递状态属性。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

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

let storage: LocalStorage = new LocalStorage();
storage.setOrCreate('storageSimpleProp', 121);
windowClass.loadContent('pages/page2', storage, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in loading the content.');
});

loadContent9+

loadContent(path: string, storage: LocalStorage): Promise<void>

根据当前工程中指定的页面路径为窗口加载具体页面内容,通过LocalStorage传递状态属性给加载的页面,使用Promise异步回调。建议在UIAbility启动过程中使用该接口,重复调用将先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,该路径需添加到工程的main_pages.json文件中。
storage LocalStorage 页面级UI状态存储单元,这里用于为加载到窗口的页面内容传递状态属性。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

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

let storage: LocalStorage = new LocalStorage();
storage.setOrCreate('storageSimpleProp', 121);
let promise = windowClass.loadContent('pages/page2', storage);
promise.then(() => {
  console.info('Succeeded in loading the content.');
}).catch((err: BusinessError) => {
  console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
});

loadContentByName11+

loadContentByName(name: string, storage: LocalStorage, callback: AsyncCallback<void>): void

根据指定路由页面名称为当前窗口加载命名路由页面,通过LocalStorage传递状态属性至加载页面,使用callback异步回调。建议在UIAbility启动过程中使用该接口,重复调用该接口将先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 命名路由页面的名称。
storage LocalStorage 页面级UI状态存储单元,这里用于为加载到窗口的页面内容传递状态属性。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
import * as Index from '../pages/Index'; // 导入命名路由页面

console.info('onWindowStageCreate');
let storage: LocalStorage = new LocalStorage();
storage.setOrCreate('storageSimpleProp', 121);
try {
  (windowClass as window.Window).loadContentByName(Index.entryName, storage, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in loading the content.');
  });
} catch (exception) {
  console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
}
// ets/pages/Index.ets
export const entryName : string = 'Index';
@Entry({routeName: entryName, useSharedStorage: true})
@Component
export struct Index {
  @State message: string = 'Hello World'
  @LocalStorageLink('storageSimpleProp') storageSimpleProp: number = 1;
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

loadContentByName11+

loadContentByName(name: string, callback: AsyncCallback<void>): void

根据指定路由页面名称为当前窗口加载命名路由页面,使用callback异步回调。建议在UIAbility启动过程中使用该接口,重复调用该接口将先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 命名路由页面的名称。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
import * as Index from '../pages/Index'; // 导入命名路由页面

try {
  (windowClass as window.Window).loadContentByName(Index.entryName, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in loading the content.');
  });
} catch (exception) {
  console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
}
// ets/pages/Index.ets
export const entryName : string = 'Index';
@Entry({routeName: entryName})
@Component
export struct Index {
  @State message: string = 'Hello World'
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

loadContentByName11+

loadContentByName(name: string, storage?: LocalStorage): Promise<void>

根据指定路由页面名称为当前窗口加载命名路由页面,通过LocalStorage传递状态属性至加载页面,使用Promise异步回调。建议在UIAbility启动过程中使用该接口,重复调用该接口将先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 命名路由页面的名称。
storage LocalStorage 页面级UI状态存储单元,这里用于为加载到窗口的页面内容传递状态属性。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
import * as Index from '../pages/Index'; // 导入命名路由页面

let storage: LocalStorage = new LocalStorage();
storage.setOrCreate('storageSimpleProp', 121);
try {
  let promise = (windowClass as window.Window).loadContentByName(Index.entryName, storage);
  promise.then(() => {
    console.info('Succeeded in loading the content.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
}
// ets/pages/Index.ets
export const entryName : string = 'Index';
@Entry({routeName: entryName, useSharedStorage: true})
@Component
export struct Index {
  @State message: string = 'Hello World'
  @LocalStorageLink('storageSimpleProp') storageSimpleProp: number = 1;
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

isWindowShowing9+

isWindowShowing(): boolean

判断当前窗口是否已显示。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
boolean 当前窗口是否已显示。true表示当前窗口已显示,false则表示当前窗口未显示。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

try {
  let data = windowClass.isWindowShowing();
  console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data));
} catch (exception) {
  console.error(`Failed to check whether the window is showing. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('windowSizeChange')7+

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

开启窗口尺寸变化的监听。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowSizeChange',即窗口尺寸变化事件。
callback Callback<Size> 回调函数。返回当前的窗口尺寸。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

try {
  windowClass.on('windowSizeChange', (data) => {
    console.info(`Succeeded in enabling the listener for window size changes. Data: ${JSON.stringify(data)}`);
  });
} catch (exception) {
  console.error(`Failed to enable the listener for window size changes. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('windowSizeChange')7+

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

关闭窗口尺寸变化的监听。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowSizeChange',即窗口尺寸变化事件。
callback Callback<Size> 回调函数。返回当前的窗口尺寸。如果传入参数,则关闭该监听。如果未传入参数,则关闭窗口尺寸变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.

示例:

const callback = (size: window.Size) => {
  // ...
}
try {
  // 通过on接口开启监听
  windowClass.on('windowSizeChange', callback);
  // 关闭指定callback的监听
  windowClass.off('windowSizeChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('windowSizeChange');
} catch (exception) {
  console.error(`Failed to disable the listener for window size changes. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('avoidAreaChange')9+

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

开启当前应用窗口系统规避区变化的监听。

常见的触发避让区回调的场景如下:应用窗口在全屏模式、悬浮模式、分屏模式之间的切换;应用窗口旋转;多折叠设备在屏幕折叠态和展开态之间的切换;应用窗口在多设备之间的流转。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'avoidAreaChange',即系统规避区变化事件。
callback Callback<AvoidAreaOptions> 回调函数。返回当前规避区以及规避区类型。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

try {
  windowClass.on('avoidAreaChange', (data) => {
    console.info('Succeeded in enabling the listener for system avoid area changes. type:' +
    JSON.stringify(data.type) + ', area: ' + JSON.stringify(data.area));
  });
} catch (exception) {
  console.error(`Failed to enable the listener for system avoid area changes. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('avoidAreaChange')9+

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

关闭当前窗口系统规避区变化的监听。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'avoidAreaChange',即系统规避区变化事件。
callback Callback<AvoidAreaOptions> 回调函数。返回当前规避区以及规避区类型。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有系统规避区变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Incorrect parameter types; 2. Parameter verification failed.

示例:

interface Param {
  type: window.AvoidAreaType,
  area: window.AvoidArea
}
const callback = (data: Param) => {
  // ...
}
try {
  windowClass.on('avoidAreaChange', callback);

  windowClass.off('avoidAreaChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('avoidAreaChange');
} catch (exception) {
  console.error(`Failed to enable or disable the listener for system avoid area changes. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('keyboardHeightChange')7+

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

开启固定态软键盘高度变化的监听,当软键盘由本窗口唤出并存在重叠区域时通知键盘高度变化。从API version 10开始,改变软键盘为固定态或者悬浮态方法详细介绍请参见输入法服务

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'keyboardHeightChange',即键盘高度变化事件。
callback Callback<number> 回调函数。返回当前的键盘高度,返回值为整数,单位为px。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

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

try {
  windowClass.on('keyboardHeightChange', (data) => {
    console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data));
  });
} catch (exception) {
  console.error(`Failed to enable the listener for keyboard height changes. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('keyboardHeightChange')7+

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

关闭固定态软键盘高度变化的监听。从API version 10开始,改变软键盘为固定态或者悬浮态方法详细介绍请参见输入法服务

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'keyboardHeightChange',即键盘高度变化事件。
callback Callback<number> 回调函数。返回当前的键盘高度,返回值为整数,单位为px。若传入参数,则关闭该监听。如果未传入参数,则关闭所有固定态软键盘高度变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.

示例:

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

const callback = (height: number) => {
  // ...
}
try {
  windowClass.on('keyboardHeightChange', callback);

  windowClass.off('keyboardHeightChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('keyboardHeightChange');
} catch (exception) {
  console.error(`Failed to disable the listener for keyboard height changes. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('keyboardDidShow')18+

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

开启固定态软键盘显示动画完成的监听。此监听在固定态软键盘显示动画完成或软键盘由悬浮态切换至固定态时触发。

改变软键盘为固定态或者悬浮态方法详细介绍请参见输入法服务

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'keyboardDidShow',即固定态软键盘显示动画完成事件。
callback Callback<KeyboardInfo> 回调函数。返回软键盘窗口信息。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Function keyboardDidShow can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.

示例:

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

try {
  windowClass.on('keyboardDidShow', (keyboardInfo) => {
    console.info('keyboard show animation completion. keyboardInfo: ' + JSON.stringify(keyboardInfo));
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('keyboardDidShow')18+

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

关闭固定态软键盘显示动画完成的监听。改变输入法窗口为固定态或者悬浮态方法详细介绍请参见输入法服务

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'keyboardDidShow',即固定态软键盘显示动画完成事件。
callback Callback<KeyboardInfo> 回调函数。返回软键盘窗口信息。若传入参数,则关闭该监听。如果未传入参数,则关闭所有固定态软键盘显示动画完成的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Function keyboardDidShow can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.

示例:

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

const callback = (keyboardInfo: window.KeyboardInfo) => {
  // ...
}
try {
  windowClass.on('keyboardDidShow', callback);
  windowClass.off('keyboardDidShow', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('keyboardDidShow');
} catch (exception) {
  console.error(`Failed to register or unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('keyboardDidHide')18+

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

开启固定态软键盘隐藏动画完成的监听。此监听在固定态软键盘隐藏动画完成或软键盘由固定态切换至悬浮态时触发。

改变软键盘为固定态或者悬浮态方法详细介绍请参见输入法服务

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'keyboardDidHide',即固定态软键盘隐藏动画完成事件。
callback Callback<KeyboardInfo> 回调函数。返回软键盘窗口信息。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Function keyboardDidHide can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.

示例:

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

try {
  windowClass.on('keyboardDidHide', (keyboardInfo) => {
    console.info('keyboard hide animation completion. keyboardInfo: ' + JSON.stringify(keyboardInfo));
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('keyboardDidHide')18+

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

关闭固定态软键盘隐藏动画完成的监听。改变输入法窗口为固定态切换至悬浮态方法详细介绍请参见输入法服务

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'keyboardDidHide',即固定态软键盘隐藏动画完成事件。
callback Callback<KeyboardInfo> 回调函数。返回软键盘窗口信息。若传入参数,则关闭该监听。如果未传入参数,则关闭所有固定态软键盘隐藏动画完成的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Function keyboardDidHide can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.

示例:

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

const callback = (keyboardInfo: window.KeyboardInfo) => {
  // ...
}
try {
  windowClass.on('keyboardDidHide', callback);
  windowClass.off('keyboardDidHide', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('keyboardDidHide');
} catch (exception) {
  console.error(`Failed to register or unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('touchOutside')11+

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

开启本窗口区域范围外的点击事件的监听。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'touchOutside',即本窗口范围外的点击事件。
callback Callback<void> 回调函数。当点击事件发生在本窗口范围之外的回调。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

try {
  windowClass.on('touchOutside', () => {
    console.info('touch outside');
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('touchOutside')11+

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

关闭本窗口区域范围外的点击事件的监听。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'touchOutside',即本窗口范围外的点击事件。
callback Callback<void> 回调函数。当点击事件发生在本窗口范围之外的回调。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有本窗口区域范围外的点击事件的监听。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.

示例:

const callback = () => {
  // ...
}
try {
  windowClass.on('touchOutside', callback);
  windowClass.off('touchOutside', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('touchOutside');
} catch (exception) {
  console.error(`Failed to register or unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('screenshot')9+

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

开启截屏事件的监听。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'screenshot',即截屏事件,对控制中心截屏、hdc命令截屏、整屏截屏接口生效。
callback Callback<void> 回调函数。发生截屏事件时的回调。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

try {
  windowClass.on('screenshot', () => {
    console.info('screenshot happened');
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('screenshot')9+

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

关闭截屏事件的监听。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'screenshot',即截屏事件。
callback Callback<void> 回调函数。发生截屏事件时的回调。若传入参数,则关闭该监听。若未传入参数,则关闭所有截屏事件的监听。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.

示例:

let callback = () => {
  console.info('screenshot happened');
};
try {
  windowClass.on('screenshot', callback);
  windowClass.off('screenshot', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('screenshot');
} catch (exception) {
  console.error(`Failed to register or unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('dialogTargetTouch')10+

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

开启模态窗口所遮盖窗口的点击或触摸事件的监听,除模态窗口以外其他窗口调用此接口不生效。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'dialogTargetTouch',即模态窗口所遮盖窗口的点击或触摸事件。
callback Callback<void> 回调函数。当点击或触摸事件发生在模态窗口所遮盖窗口的回调。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

try {
  windowClass.on('dialogTargetTouch', () => {
    console.info('touch dialog target');
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('dialogTargetTouch')10+

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

关闭模态窗口目标窗口的点击事件的监听。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'dialogTargetTouch',即模态窗口目标窗口的点击事件。
callback Callback<void> 回调函数。当点击事件发生在模态窗口目标窗口的回调。若传入参数,则关闭该监听。若未传入参数,则关闭所有模态窗口目标窗口的点击事件的监听。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.

示例:

const callback = () => {
  // ...
}
try {
  windowClass.on('dialogTargetTouch', callback);
  windowClass.off('dialogTargetTouch', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('dialogTargetTouch');
} catch (exception) {
  console.error(`Failed to register or unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('windowEvent')10+

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

开启窗口生命周期变化的监听。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowEvent',即窗口生命周期变化事件。
callback Callback<WindowEventType> 回调函数。返回当前的窗口生命周期状态。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.

示例:

try {
  windowClass.on('windowEvent', (data) => {
    console.info('Window event happened. Event:' + JSON.stringify(data));
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('windowEvent')10+

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

关闭窗口生命周期变化的监听。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowEvent',即窗口生命周期变化事件。
callback Callback<WindowEventType> 回调函数。返回当前的窗口生命周期状态。若传入参数,则关闭该监听。若未传入参数,则关闭所有窗口生命周期变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.

示例:

const callback = (windowEventType: window.WindowEventType) => {
  // ...
}
try {
  // 通过on接口开启监听
  windowClass.on('windowEvent', callback);
  // 关闭指定callback的监听
  windowClass.off('windowEvent', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('windowEvent');
} catch (exception) {
  console.error(`Failed to unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('displayIdChange')14+

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

开启本窗口所处屏幕变化事件的监听。比如,当前窗口移动到其他屏幕时,可以从此接口监听到这个行为。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'displayIdChange',即本窗口所处屏幕变化的事件。
callback Callback<number> 回调函数。当本窗口所处屏幕发生变化后的回调。回调函数返回number类型参数,表示窗口所处屏幕的displayId。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

try {
  windowClass.on('displayIdChange', (data) => {
    console.info('Window displayId changed, displayId=' + JSON.stringify(data));
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('displayIdChange')14+

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

关闭本窗口所处屏幕变化事件的监听。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'displayIdChange',即本窗口所处屏幕变化的事件。
callback Callback<number> 回调函数。当本窗口所处屏幕发生变化时的回调。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有本窗口所处屏幕变化事件的回调。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

const callback = (displayId: number) => {
  // ...
}
try {
  // 通过on接口开启监听
  windowClass.on('displayIdChange', callback);
  // 关闭指定callback的监听
  windowClass.off('displayIdChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('displayIdChange');
} catch (exception) {
  console.error(`Failed to unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('windowVisibilityChange')11+

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

开启本窗口可见状态变化事件的监听。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowVisibilityChange',即本窗口可见状态变化的事件。
callback Callback<boolean> 回调函数。当本窗口可见状态发生变化后的回调。回调函数返回boolean类型参数,当返回参数为true时表示窗口可见,否则表示窗口不可见。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

try {
  windowClass.on('windowVisibilityChange', (boolean) => {
    console.info('Window visibility changed, isVisible=' + boolean);
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('windowVisibilityChange')11+

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

关闭本窗口可见状态变化事件的监听。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowVisibilityChange',即本窗口可见状态变化的事件。
callback Callback<boolean> 回调函数。当本窗口可见状态发生变化时的回调。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有本窗口可见状态变化事件的回调。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

const callback = (bool: boolean) => {
  // ...
}
try {
  // 通过on接口开启监听
  windowClass.on('windowVisibilityChange', callback);
  // 关闭指定callback的监听
  windowClass.off('windowVisibilityChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('windowVisibilityChange');
} catch (exception) {
  console.error(`Failed to unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('systemDensityChange')15+

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

开启本窗口所处屏幕的系统显示大小缩放系数变化事件的监听。比如,当调整窗口所处屏幕的显示大小缩放系数时,可以从此接口监听到这个行为。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'systemDensityChange',即本窗口所处屏幕的系统显示大小缩放系数变化的事件。
callback Callback<number> 回调函数。当本窗口所处屏幕的系统显示大小缩放系数发生变化后的回调。回调函数返回number类型参数,表示当前窗口所处屏幕的系统显示大小缩放系数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

const callback = (density: number) => {
  console.info('System density changed, density=' + JSON.stringify(density));
}
try {
  windowClass.on('systemDensityChange', callback);
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('systemDensityChange')15+

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

关闭本窗口所处屏幕的系统显示大小缩放系数变化事件的监听。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'systemDensityChange',即本窗口所处屏幕的系统显示大小缩放系数变化的事件。
callback Callback<number> 回调函数。当本窗口所处屏幕的系统显示大小缩放系数发生变化后的回调。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有本窗口所处屏幕的系统显示大小缩放系数变化事件的回调。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

const callback = (density: number) => {
  // ...
}
try {
  // 通过on接口开启监听
  windowClass.on('systemDensityChange', callback);
  // 关闭指定callback的监听
  windowClass.off('systemDensityChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('systemDensityChange');
} catch (exception) {
  console.error(`Failed to unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('noInteractionDetected')12+

on(type: 'noInteractionDetected', timeout: number, callback: Callback<void>): void

开启本窗口在指定超时时间内无交互事件的监听,交互事件支持物理键盘输入事件和屏幕触控点击事件,不支持软键盘输入事件。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'noInteractionDetected',即本窗口在指定超时时间内无交互的事件。
timeout number 指定本窗口在多长时间内无交互即回调,单位为秒(s)。该参数仅支持整数输入,负数和小数为非法参数。
callback Callback<void> 回调函数。当本窗口在指定超时时间内无交互事件时的回调。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

try {
  windowClass.on('noInteractionDetected', 60, () => {
    console.info('no interaction in 60s');
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('noInteractionDetected')12+

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

关闭本窗口在指定超时时间内无交互事件的监听,交互事件支持物理键盘输入事件和屏幕触控点击事件,不支持软键盘输入事件。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'noInteractionDetected',即本窗口在指定超时时间内无交互的事件。
callback Callback<void> 回调函数,当本窗口在指定超时时间内无交互事件时的回调。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有本窗口在指定超时时间内无交互事件的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

const callback = () => {
  // ...
}
try {
  windowClass.on('noInteractionDetected', 60, callback);
  windowClass.off('noInteractionDetected', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('noInteractionDetected');
} catch (exception) {
  console.error(`Failed to register or unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('windowStatusChange')11+

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

开启窗口模式变化的监听,当窗口windowStatus发生变化时进行通知(此时窗口属性可能还没有更新)。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowStatusChange',即窗口模式变化事件。
callback Callback<WindowStatusType> 回调函数。返回当前的窗口模式。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.

示例:

try {
    windowClass.on('windowStatusChange', (WindowStatusType) => {
        console.info('Succeeded in enabling the listener for window status changes. Data: ' + JSON.stringify(WindowStatusType));
    });
} catch (exception) {
    console.error(`Failed to unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('windowStatusChange')11+

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

关闭窗口模式变化的监听。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowStatusChange',即窗口模式变化事件。
callback Callback<WindowStatusType> 回调函数。返回当前的窗口模式。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有窗口模式变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.

示例:

const callback = (windowStatusType: window.WindowStatusType) => {
    // ...
}
try {
    windowClass.on('windowStatusChange', callback);
    windowClass.off('windowStatusChange', callback);
    // 如果通过on开启多个callback进行监听,同时关闭所有监听:
    windowClass.off('windowStatusChange');
} catch (exception) {
    console.error(`Failed to unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowGrayScale12+

setWindowGrayScale(grayScale: number): Promise<void>

设置窗口灰阶,使用Promise异步回调。该接口需要在调用loadContent()setUIContent()使窗口加载页面内容后调用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
grayScale number 窗口灰阶。该参数为浮点数,取值范围为[0.0, 1.0]。0.0表示窗口图像无变化,1.0表示窗口图像完全转为灰度图像,0.0至1.0之间时效果呈线性变化。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

windowClass?.setUIContent('pages/Index', (error: BusinessError) => {
  if (error.code) {
    console.error(`Failed to set the content. Cause code: ${error.code}`);
    return;
  }
  console.info('Succeeded in setting the content.');
  let grayScale: number = 0.5;
  try {
    if (canIUse("SystemCapability.Window.SessionManager")) {
      let promise = windowClass?.setWindowGrayScale(grayScale);
      promise?.then(() => {
        console.info('Succeeded in setting the grayScale.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set the grayScale. Cause code: ${err.code}, message: ${err.message}`);
      });
    }
  } catch (exception) {
    console.error(`Failed to set the grayScale. Cause code: ${exception.code}, message: ${exception.message}`);
  }
});

on('windowTitleButtonRectChange')11+

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

开启窗口标题栏上的最小化、最大化、关闭按钮矩形区域变化的监听,对存在标题栏和三键区的窗口形态生效。如果使用Stage模型,该接口需要在loadContent()setUIContent()调用生效后使用。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowTitleButtonRectChange',即标题栏上的最小化、最大化、关闭按钮矩形区域变化事件。
callback Callback<TitleButtonRect> 回调函数。返回当前标题栏上的最小化、最大化、关闭按钮矩形区域。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

windowClass.setUIContent('pages/WindowPage').then(() => {
  try {
    windowClass?.on('windowTitleButtonRectChange', (titleButtonRect) => {
      console.info('Succeeded in enabling the listener for window title buttons area changes. Data: ' + JSON.stringify(titleButtonRect));
    });
  } catch (exception) {
    console.error(`Failed to enable the listener for window title buttons area changes. Cause code: ${exception.code}, message: ${exception.message}`);
  }
})

off('windowTitleButtonRectChange')11+

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

关闭窗口标题栏上的最小化、最大化、关闭按钮矩形区域变化的监听,对存在标题栏和三键区的窗口形态生效。如果使用Stage模型,该接口需要在loadContent()setUIContent()调用生效后使用。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowTitleButtonRectChange',即标题栏上的最小化、最大化、关闭按钮矩形区域变化事件。
callback Callback<TitleButtonRect> 回调函数。返回当前标题栏上的最小化、最大化、关闭按钮矩形区域。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有标题栏上的最小化、最大化、关闭按钮矩形区域变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

windowClass.setUIContent('pages/WindowPage').then(() => {
	const callback = (titleButtonRect: window.TitleButtonRect) => {
		// ...
	}
  try {
    // 通过on接口开启监听
    windowClass?.on('windowTitleButtonRectChange', callback);
    // 关闭指定callback的监听
    windowClass?.off('windowTitleButtonRectChange', callback);
    // 如果通过on开启多个callback进行监听,同时关闭所有监听:
    windowClass?.off('windowTitleButtonRectChange');
  } catch (exception) {
    console.error(`Failed to disable the listener for window title buttons area changes. Cause code: ${exception.code}, message: ${exception.message}`);
  }
})

on('windowRectChange')12+

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

开启窗口矩形(窗口位置及窗口大小)变化的监听。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowRectChange',即窗口矩形变化事件。
callback Callback<RectChangeOptions> 回调函数。返回当前窗口矩形变化值及变化原因。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

try {
  windowClass.on('windowRectChange', (data: window.RectChangeOptions) => {
      console.info(`Succeeded window rect changes. Data: ${JSON.stringify(data)}`);
  });
} catch (exception) {
  console.error(`Failed to disable the listener for window rect changes. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('windowRectChange')12+

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

关闭窗口矩形(窗口位置及窗口大小)变化的监听。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowRectChange',即窗口矩形变化事件。
callback Callback<RectChangeOptions> 回调函数。返回当前的窗口矩形及变化原因。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有窗口矩形变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

const callback = (rectChangeOptions: window.RectChangeOptions) => {
  // ...
}

try {
  windowClass.on('windowRectChange', callback);
  windowClass.off('windowRectChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('windowRectChange');
} catch (exception) {
  console.error(`Failed to disable the listener for window rect changes. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('subWindowClose')12+

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

开启子窗口关闭事件的监听。此监听仅在点击系统提供的右上角关闭按钮关闭子窗时触发,其余关闭方式不触发回调。

当重复注册窗口关闭事件的监听时,最后一次注册成功的监听事件生效。

该接口触发的窗口关闭事件监听回调函数是同步执行,子窗口的异步关闭事件监听参考on('windowWillClose')方法。

如果存在on('windowWillClose')监听事件,只响应on('windowWillClose')接口。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'subWindowClose',即子窗口关闭事件。
callback Callback<void> 回调函数。当点击子窗口右上角关闭按钮事件发生时的回调。该回调函数不返回任何参数。回调函数内部逻辑的返回值决定当前子窗是否继续关闭,如果返回boolean类型的true表示不关闭子窗,返回false或者其他非boolean类型表示关闭子窗。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

const callback = () => {
  // ...
  return true;
}
try {
  windowClass.on('subWindowClose', callback);
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('subWindowClose')12+

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

关闭子窗口关闭事件的监听。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'subWindowClose',即子窗口关闭事件。
callback Callback<void> 回调函数。当点击子窗口右上角关闭按钮事件发生时的回调。该回调函数不返回任何参数。回调函数内部逻辑的返回值决定当前子窗是否继续关闭,如果返回boolean类型的true表示不关闭子窗,返回false或者其他非boolean类型表示关闭子窗。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有子窗口关闭的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

const callback = () => {
  // ...
  return true;
}
try {
  windowClass.on('subWindowClose', callback);
  windowClass.off('subWindowClose', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('subWindowClose');
} catch (exception) {
  console.error(`Failed to register or unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('windowWillClose')15+

on(type: 'windowWillClose', callback: Callback<void, Promise<boolean>>): void

开启主窗口或子窗口关闭事件的监听。此监听仅能通过系统提供的窗口标题栏关闭按键触发,其余关闭窗口的方式不触发回调。

该接口触发的回调函数是异步执行。子窗口的同步关闭事件监听参考on('subWindowClose')方法。主窗口的同步关闭事件监听参考on('windowStageClose')方法。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowWillClose',即窗口关闭事件。
callback Callback<void, Promise<boolean>> 回调函数。当点击窗口系统提供的右上角关闭按钮事件发生时的回调。该回调函数不返回任何参数。回调函数内部逻辑需要有Promise<boolean>类型的返回值。在返回的Promise函数里,执行resolve(true) 方法表示不关闭当前窗口,执行resolve(false) 方法或者reject方法均表示关闭当前窗口。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    const callback = () => {
      // ...
      return new Promise<boolean>((resolve, reject) => {
        // 是否关闭该窗口
        let result: boolean = true;
        resolve(result);
      });
    }
    try {
      let windowClass = windowStage.getMainWindowSync();
      windowClass.on('windowWillClose', callback);
    } catch (exception) {
      console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

off('windowWillClose')15+

off(type: 'windowWillClose', callback?: Callback<void, Promise<boolean>>): void

关闭主窗口或子窗口关闭事件的监听。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowWillClose',即窗口关闭事件。
callback Callback<void, Promise<boolean>> 回调函数。当点击窗口系统提供的右上角关闭按钮事件发生时的回调。该回调函数不返回任何参数。回调函数内部逻辑需要有Promise<boolean>类型的返回值。在返回的Promise函数里,执行resolve(true) 方法表示不关闭当前窗口,执行resolve(false) 方法或者reject方法均表示关闭当前窗口。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    try {
      const callback = () => {
        // ...
        return new Promise<boolean>((resolve, reject) => {
          // 是否关闭该窗口
          let result: boolean = true;
          resolve(result);
        });
      }
      let windowClass = windowStage.getMainWindowSync();
      windowClass.on('windowWillClose', callback);
      windowClass.off('windowWillClose', callback);
      // 如果通过on开启多个callback进行监听,同时关闭所有监听:
      windowClass.off('windowWillClose');
    } catch (exception) {
      console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

on('windowHighlightChange')15+

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

开启窗口激活态变化事件的监听。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowHighlightChange',即窗口激活态变化事件。
callback Callback<boolean> 回调函数。当本窗口的激活态发生变化时的回调。回调函数返回boolean类型参数。当返回参数为true表示激活态;false表示非激活态。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

try {
  windowClass.on('windowHighlightChange', (data: boolean) => {
    console.info(`Window highlight Change: ${data}`);
  });
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('windowHighlightChange')15+

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

关闭窗口激活态变化事件的监听。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'windowHighlightChange',即窗口激活态变化事件。
callback Callback<boolean> 回调函数。当本窗口的激活态发生变化时的回调。若传入参数,则关闭该监听。若未传入参数,则关闭所有窗口激活态变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

const callback = (data: boolean) => {
  // ...
}
try {
  // 通过on接口开启监听
  windowClass.on('windowHighlightChange', callback);
  // 关闭指定callback的监听
  windowClass.off('windowHighlightChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听:
  windowClass.off('windowHighlightChange');
} catch (exception) {
  console.error(`Failed to unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

on('rotationChange')19+

on(type: 'rotationChange', callback: RotationChangeCallback<RotationChangeInfo, RotationChangeResult | void>): void

开启窗口旋转变化的监听。RotationChangeInfo中窗口旋转事件类型为窗口即将旋转时,必须返回RotationChangeResult。窗口旋转事件类型为窗口旋转结束时返回RotationChangeResult不生效。

同一个窗口多次注册同类型回调函数,只生效最新注册的同类型回调函数返回值。系统提供了超时保护机制,若20ms内窗口未返回RotationChangeResult,系统不处理该返回值。

此接口在2in1设备上调用不生效。

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'rotationChange',即窗口旋转变化事件。
callback RotationChangeCallback<RotationChangeInfo, RotationChangeResult | void> 回调函数。返回窗口旋转信息RotationChangeInfo,应用返回当前窗口变化结果RotationChangeResult

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

function calculateRect(info: window.RotationChangeInfo): window.Rect {
    // calculate result with info
    let rect : window.Rect = {
      left: 0,
      top: 0,
      width: 500,
      height: 600,
    }
    return rect;
}

const callback = (info: window.RotationChangeInfo): window.RotationChangeResult | void => {
  let result: window.RotationChangeResult = {
    rectType: window.RectType.RELATIVE_TO_SCREEN,
    windowRect: {
      left: 0,
      top: 0,
      width: 0,
      height: 0,
    }
  };
  if (info.type === window.RotationChangeType.WINDOW_WILL_ROTATE) {
      result.rectType = window.RectType.RELATIVE_TO_SCREEN;
      result.windowRect = calculateRect(info);
      return result;
  } else {
      // do something after rotate
      return;
  }
}

try {
  windowClass.on('rotationChange', callback);
} catch (exception) {
  console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

off('rotationChange')19+

off(type: 'rotationChange', callback?: RotationChangeCallback<RotationChangeInfo, RotationChangeResult | void>): void

关闭窗口旋转变化的监听。

此接口在2in1设备上调用不生效。

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'rotationChange',即窗口旋转变化事件。
callback RotationChangeCallback<RotationChangeInfo, RotationChangeResult | void> 回调函数。如果传入参数,则关闭该监听。如果未传入参数,则关闭该窗口的所有监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

const callback = (info: window.RotationChangeInfo): window.RotationChangeResult | void => {
  // ...
  return;
}
try {
  windowClass.off('rotationChange', callback);
  // 如果通过on开启多个callback进行监听,同时关闭所有监听。
  windowClass.off('rotationChange');
} catch (exception) {
  console.error(`Failed to unregister callback. Cause code: ${exception.code}, message: ${exception.message}`);
}

isWindowSupportWideGamut9+

isWindowSupportWideGamut(callback: AsyncCallback<boolean>): void

判断当前窗口是否支持广色域模式,使用callback异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<boolean> 回调函数。返回true表示当前窗口支持广色域模式,返回false表示当前窗口不支持广色域模式。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

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

windowClass.isWindowSupportWideGamut((err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to check whether the window support WideGamut. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info(`Succeeded in checking whether the window support WideGamut Data: ${data}`);
});

isWindowSupportWideGamut9+

isWindowSupportWideGamut(): Promise<boolean>

判断当前窗口是否支持广色域模式,使用Promise异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

类型 说明
Promise<boolean> Promise对象。返回true表示当前窗口支持广色域模式,返回false表示当前窗口不支持广色域模式。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

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

let promise = windowClass.isWindowSupportWideGamut();
promise.then((data) => {
  console.info(`Succeeded in checking whether the window support WideGamut. Data: ${data}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to check whether the window support WideGamut. Cause code: ${err.code}, message: ${err.message}`);
});

setWindowColorSpace9+

setWindowColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void

设置当前窗口为广色域模式或默认色域模式,使用callback异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
colorSpace ColorSpace 设置色域模式。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.

示例:

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

try {
  windowClass.setWindowColorSpace(window.ColorSpace.WIDE_GAMUT, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to set window colorspace. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in setting window colorspace.');
  });
} catch (exception) {
  console.error(`Failed to set window colorspace. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowColorSpace9+

setWindowColorSpace(colorSpace:ColorSpace): Promise<void>

设置当前窗口为广色域模式或默认色域模式,使用Promise异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
colorSpace ColorSpace 设置色域模式。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.

示例:

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

try {
  let promise = windowClass.setWindowColorSpace(window.ColorSpace.WIDE_GAMUT);
  promise.then(() => {
    console.info('Succeeded in setting window colorspace.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set window colorspace. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set window colorspace. Cause code: ${exception.code}, message: ${exception.message}`);
}

getWindowColorSpace9+

getWindowColorSpace(): ColorSpace

获取当前窗口色域模式。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

类型 说明
ColorSpace 当前色域模式。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

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

try {
  let colorSpace = windowClass.getWindowColorSpace();
  console.info(`Succeeded in getting the window color space. ColorSpace: ${colorSpace}`);
} catch (exception) {
  console.error(`Failed to set the window to be focusable. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowBackgroundColor9+

setWindowBackgroundColor(color: string | ColorMetrics): void

设置窗口的背景色。Stage模型下,该接口需要在loadContent()setUIContent()调用生效后使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
color string | ColorMetrics18+ 需要设置的背景色,为十六进制RGB或ARGB颜色,不区分大小写,例如'#00FF00''#FF00FF00'
从API version 18开始,此参数支持ColorMetrics类型。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
import { ColorMetrics } from '@kit.ArkUI';

let storage: LocalStorage = new LocalStorage();
storage.setOrCreate('storageSimpleProp', 121);
windowClass.loadContent("pages/page2", storage, (err: BusinessError) => {
  let errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in loading the content.');
  let color1: string = '#00ff33';
  let color2: ColorMetrics = ColorMetrics.numeric(0xff112233);
  try {
    windowClass?.setWindowBackgroundColor(color1);
    windowClass?.setWindowBackgroundColor(color2);
  } catch (exception) {
    console.error(`Failed to set the background color. Cause code: ${exception.code}, message: ${exception.message}`);
  };
});

setWindowBrightness9+

setWindowBrightness(brightness: number, callback: AsyncCallback<void>): void

允许应用主窗口设置屏幕亮度值,使用callback异步回调。

非2in1设备,窗口设置屏幕亮度生效时,控制中心不可以调整系统屏幕亮度,窗口恢复默认系统亮度之后,控制中心可以调整系统屏幕亮度; 2in1设备,窗口设置屏幕亮度和控制中心调整屏幕亮度的优先级相同,窗口设置屏幕亮度生效后,控制中心也可以调整系统屏幕亮度。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
brightness number 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let brightness: number = 1.0;
      try {
        windowClass.setWindowBrightness(brightness, (err: BusinessError) => {
          const errCode: number = err.code;
          if (errCode) {
            console.error(`Failed to set the brightness. Cause code: ${err.code}, message: ${err.message}`);
            return;
          }
          console.info('Succeeded in setting the brightness.');
        });
      } catch (exception) {
        console.error(`Failed to set the brightness. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setWindowBrightness9+

setWindowBrightness(brightness: number): Promise<void>

允许应用主窗口设置屏幕亮度值,使用Promise异步回调。

非2in1设备,窗口设置屏幕亮度生效时,控制中心不可以调整系统屏幕亮度,窗口恢复默认系统亮度之后,控制中心可以调整系统屏幕亮度; 2in1设备,窗口设置屏幕亮度和控制中心调整屏幕亮度的优先级相同,窗口设置屏幕亮度生效后,控制中心也可以调整系统屏幕亮度。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
brightness number 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let brightness: number = 1.0;
      try {
        let promise = windowClass.setWindowBrightness(brightness);
        promise.then(() => {
          console.info('Succeeded in setting the brightness.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set the brightness. Cause code: ${err.code}, message: ${err.message}`);
        });
      } catch (exception) {
        console.error(`Failed to set the brightness. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setWindowFocusable9+

setWindowFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void

设置窗口是否具有获得焦点的能力,使用callback异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isFocusable boolean 窗口是否可获焦。true表示支持;false表示不支持。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

let isFocusable: boolean = true;
try {
  windowClass.setWindowFocusable(isFocusable, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to set the window to be focusable. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in setting the window to be focusable.');
  });
} catch (exception) {
  console.error(`Failed to set the window to be focusable. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowFocusable9+

setWindowFocusable(isFocusable: boolean): Promise<void>

设置窗口是否具有获得焦点的能力,使用Promise异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isFocusable boolean 窗口是否可获焦。true表示支持;false表示不支持。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

let isFocusable: boolean = true;
try {
  let promise = windowClass.setWindowFocusable(isFocusable);
  promise.then(() => {
    console.info('Succeeded in setting the window to be focusable.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the window to be focusable. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the window to be focusable. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowKeepScreenOn9+

setWindowKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void

设置屏幕是否为常亮状态,使用callback异步回调。

规范使用该接口:仅在必要场景(导航、视频播放、绘画、游戏等场景)下,设置该属性为true;退出上述场景后,应当重置该属性为false;其他场景(无屏幕互动、音频播放等)下,不使用该接口;系统检测到非规范使用该接口时,可能会恢复自动灭屏功能。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
isKeepScreenOn boolean 设置屏幕是否为常亮状态。true表示常亮;false表示不常亮。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

let isKeepScreenOn: boolean = true;
try {
  windowClass.setWindowKeepScreenOn(isKeepScreenOn, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to set the screen to be always on. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in setting the screen to be always on.');
  });
} catch (exception) {
  console.error(`Failed to set the screen to be always on. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowKeepScreenOn9+

setWindowKeepScreenOn(isKeepScreenOn: boolean): Promise<void>

设置屏幕是否为常亮状态,使用Promise异步回调。

规范使用该接口:仅在必要场景(导航、视频播放、绘画、游戏等场景)下,设置该属性为true;退出上述场景后,应当重置该属性为false;其他场景(无屏幕互动、音频播放等)下,不使用该接口;系统检测到非规范使用该接口时,可能会恢复自动灭屏功能。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
isKeepScreenOn boolean 设置屏幕是否为常亮状态。true表示常亮;false表示不常亮。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

let isKeepScreenOn: boolean = true;
try {
  let promise = windowClass.setWindowKeepScreenOn(isKeepScreenOn);
  promise.then(() => {
    console.info('Succeeded in setting the screen to be always on.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the screen to be always on. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the screen to be always on. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowPrivacyMode9+

setWindowPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void

设置窗口是否为隐私模式,使用callback异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。此接口可用于禁止截屏/录屏的场景。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

需要权限: ohos.permission.PRIVACY_WINDOW

参数:

参数名 类型 必填 说明
isPrivacyMode boolean 窗口是否为隐私模式。true表示模式开启;false表示模式关闭。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
201 Permission verification failed. The application does not have the permission required to call the API.
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

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

let isPrivacyMode: boolean = true;
try {
  windowClass.setWindowPrivacyMode(isPrivacyMode, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to set the window to privacy mode. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in setting the window to privacy mode.');
  });
} catch (exception) {
  console.error(`Failed to set the window to privacy mode. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowPrivacyMode9+

setWindowPrivacyMode(isPrivacyMode: boolean): Promise<void>

设置窗口是否为隐私模式,使用Promise异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。此接口可用于禁止截屏/录屏的场景。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

需要权限: ohos.permission.PRIVACY_WINDOW

参数:

参数名 类型 必填 说明
isPrivacyMode boolean 窗口是否为隐私模式。true表示模式开启;false表示模式关闭。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
201 Permission verification failed. The application does not have the permission required to call the API.
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

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

let isPrivacyMode: boolean = true;
try {
  let promise = windowClass.setWindowPrivacyMode(isPrivacyMode);
  promise.then(() => {
    console.info('Succeeded in setting the window to privacy mode.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the window to privacy mode. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the window to privacy mode. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowTouchable9+

setWindowTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void

设置窗口是否为可触状态,使用callback异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isTouchable boolean 窗口是否为可触状态。true表示可触;false表示不可触。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

let isTouchable = true;
try {
  windowClass.setWindowTouchable(isTouchable, (err: BusinessError) => {
    const errCode: number = err.code;
    if (errCode) {
      console.error(`Failed to set the window to be touchable. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in setting the window to be touchable.');
  });
} catch (exception) {
  console.error(`Failed to set the window to be touchable. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowTouchable9+

setWindowTouchable(isTouchable: boolean): Promise<void>

设置窗口是否为可触状态,使用Promise异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isTouchable boolean 窗口是否为可触状态。true表示可触;false表示不可触。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

let isTouchable: boolean = true;
try {
  let promise = windowClass.setWindowTouchable(isTouchable);
  promise.then(() => {
    console.info('Succeeded in setting the window to be touchable.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the window to be touchable. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the window to be touchable. Cause code: ${exception.code}, message: ${exception.message}`);
}

snapshot9+

snapshot(callback: AsyncCallback<image.PixelMap>): void

获取窗口截图,使用callback异步回调。若当前窗口设置为隐私模式(可通过setWindowPrivacyMode接口设置),截图结果为白屏。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<image.PixelMap> 回调函数。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';

windowClass.snapshot((err: BusinessError, pixelMap: image.PixelMap) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to snapshot window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
  pixelMap.release(); // PixelMap使用完后及时释放内存
});

snapshot9+

snapshot(): Promise<image.PixelMap>

获取当前窗口截图。若当前窗口设置为隐私模式(可通过setWindowPrivacyMode接口设置),截图结果为白屏。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

类型 说明
Promise<image.PixelMap> Promise对象。返回当前窗口截图。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';

let promise = windowClass.snapshot();
promise.then((pixelMap: image.PixelMap) => {
  console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
  pixelMap.release(); // PixelMap使用完后及时释放内存
}).catch((err: BusinessError) => {
  console.error(`Failed to snapshot window. Cause code: ${err.code}, message: ${err.message}`);
});

snapshotIgnorePrivacy18+

snapshotIgnorePrivacy(): Promise<image.PixelMap>

获取当前窗口截图。即使当前窗口设置为隐私模式(可通过setWindowPrivacyMode接口设置),仍可调用本接口返回当前窗口截图。

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

类型 说明
Promise<image.PixelMap> Promise对象。返回当前窗口截图。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Function snapshotIgnorePrivacy can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';

let promise = windowClass.snapshotIgnorePrivacy();
promise.then((pixelMap: image.PixelMap) => {
  console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
  pixelMap.release(); // PixelMap使用完后及时释放内存
}).catch((err: BusinessError) => {
  console.error(`Failed to snapshot window. Cause code: ${err.code}, message: ${err.message}`);
});

setAspectRatio10+

setAspectRatio(ratio: number): Promise<void>

设置窗口内容布局的比例,使用Promise异步回调。

通过其他接口如resizeresizeAsync设置窗口大小时,不受ratio约束。

仅主窗可设置,且仅在自由悬浮窗口模式(即窗口模式为window.WindowStatusType.FLOATING)下生效,比例参数将持久化保存,关闭应用或重启设备设置的比例仍然生效。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
ratio number 除边框装饰之外的窗口内容布局的宽高比。该参数为浮点数,受窗口最大最小尺寸限制,比例值下限为最小宽度/最大高度,上限为最大宽度/最小高度。窗口最大最小尺寸由WindowLimits和系统限制的交集决定,系统限制优先级高于WindowLimits。ratio的有效范围会随WindowLimits变化而变化。如果先设置了WindowLimits,后设置的ratio与其冲突,会返回错误码;如果先设置了ratio,后设置的WindowLimits与其冲突,窗口的宽高比可能会不跟随设置的宽高比(ratio)。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {

  // ...
  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
    if (!windowClass) {
      console.info('windowClass is null');
    }
    try {
      let ratio = 1.0;
      let promise = windowClass.setAspectRatio(ratio);
      promise.then(() => {
        console.info('Succeeded in setting aspect ratio of window.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set the aspect ratio of window. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to set the aspect ratio of window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

setAspectRatio10+

setAspectRatio(ratio: number, callback: AsyncCallback<void>): void

设置窗口内容布局的比例,使用callback异步回调。

通过其他接口如resizeresizeAsync设置窗口大小时,不受ratio约束。

仅主窗可设置,且仅在自由悬浮窗口模式(即窗口模式为window.WindowStatusType.FLOATING)下生效,比例参数将持久化保存,关闭应用或重启设备设置的比例仍然生效。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
ratio number 除边框装饰之外的窗口内容布局的宽高比。该参数为浮点数,受窗口最大最小尺寸限制,比例值下限为最小宽度/最大高度,上限为最大宽度/最小高度。窗口最大最小尺寸由WindowLimits和系统限制的交集决定,系统限制优先级高于WindowLimits。ratio的有效范围会随WindowLimits变化而变化。如果先设置了WindowLimits,后设置的ratio与其冲突,会返回错误码;如果先设置了ratio,后设置的WindowLimits与其冲突,窗口的宽高比可能会不跟随设置的宽高比(ratio)。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {

  // ...
  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
    if (!windowClass) {
      console.info('Failed to load the content. Cause: windowClass is null');
    }
    try {
      let ratio = 1.0;
      windowClass.setAspectRatio(ratio, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to set the aspect ratio of window. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in setting the aspect ratio of window.');
      });
    } catch (exception) {
      console.error(`Failed to set the aspect ratio of window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

resetAspectRatio10+

resetAspectRatio(): Promise<void>

取消设置窗口内容布局的比例,使用Promise异步回调。

仅主窗可设置,且仅在自由悬浮窗口模式(即窗口模式为window.WindowStatusType.FLOATING)下生效,调用后将清除持久化储存的比例信息。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

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

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {

  // ...
  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
    if (!windowClass) {
      console.info('Failed to load the content. Cause: windowClass is null');
    }
    try {
      let promise = windowClass.resetAspectRatio();
      promise.then(() => {
        console.info('Succeeded in resetting aspect ratio of window.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to reset the aspect ratio of window. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to reset the aspect ratio of window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

resetAspectRatio10+

resetAspectRatio(callback: AsyncCallback<void>): void

取消设置窗口内容布局的比例,使用callback异步回调。

仅主窗可设置,且仅在自由悬浮窗口模式(即窗口模式为window.WindowStatusType.FLOATING)下生效,调用后将清除持久化储存的比例信息。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {

  // ...
  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window = windowStage.getMainWindowSync(); // 获取应用主窗口
    if (!windowClass) {
      console.info('Failed to load the content. Cause: windowClass is null');
    }
    try {
      windowClass.resetAspectRatio((err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to reset the aspect ratio of window. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in resetting aspect ratio of window.');
      });
    } catch (exception) {
      console.error(`Failed to reset the aspect ratio of window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

minimize11+

minimize(callback: AsyncCallback<void>): void

此接口根据调用对象不同,实现不同的功能:

  • 当调用对象为主窗口时,实现最小化功能,可在Dock栏中还原,2in1 设备上可以使用restore()进行还原。

  • 当调用对象为子窗口或悬浮窗时,实现隐藏功能,不可在Dock栏中还原,可以使用showWindow()进行还原。

使用callback异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

windowClass.minimize((err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to minimize the window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in minimizing the window.');
});

minimize11+

minimize(): Promise<void>

此接口根据调用对象不同,实现不同的功能:

  • 当调用对象为主窗口时,实现最小化功能,可在Dock栏中还原,2in1 设备上可以使用restore()进行还原。

  • 当调用对象为子窗口或悬浮窗时,实现隐藏功能,不可在Dock栏中还原,可以使用showWindow()进行还原。

使用Promise异步回调。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

let promise = windowClass.minimize();
promise.then(() => {
  console.info('Succeeded in minimizing the window.');
}).catch((err: BusinessError) => {
  console.error(`Failed to minimize the window. Cause code: ${err.code}, message: ${err.message}`);
});

maximize12+

maximize(presentation?: MaximizePresentation): Promise<void>

实现最大化功能。主窗口可调用此接口实现最大化功能;子窗口需在创建时设置子窗口参数maximizeSupported为true,再调用此接口可实现最大化功能。使用Promise异步回调。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
presentation MaximizePresentation 主窗口或子窗口最大化时的布局枚举。默认值window.MaximizePresentation.ENTER_IMMERSIVE,即默认最大化时进入全屏模式。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let promise = windowClass.maximize();
      // let promise = windowClass.maximize(window.MaximizePresentation.ENTER_IMMERSIVE);
      promise.then(() => {
        console.info('Succeeded in maximizing the window.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to maximize the window. Cause code: ${err.code}, message: ${err.message}`);
      });
    });
  }
};

setResizeByDragEnabled14+

setResizeByDragEnabled(enable: boolean, callback: AsyncCallback<void>): void

禁止/使能通过拖拽方式缩放主窗口或启用装饰的子窗口的功能。使用callback异步回调。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
enable boolean 设置窗口是否使能通过拖拽进行缩放,true表示使能,false表示禁止。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

try {
  let enabled = false;
  windowClass.setResizeByDragEnabled(enabled, (err) => {
    if (err.code) {
      console.error(`Failed to set the function of disabling the resize by drag window. Cause code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in setting the function of disabling the resize by drag window.`);
  });
} catch (exception) {
  console.error(`Failed to set the function of disabling the resize by drag window. Cause code: ${exception.code}, message: ${exception.message}`);
}

setResizeByDragEnabled14+

setResizeByDragEnabled(enable: boolean): Promise<void>

禁止/使能通过拖拽方式缩放主窗口或启用装饰的子窗口的功能。使用Promise异步回调。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
enable boolean 设置窗口是否使能通过拖拽进行缩放,true表示使能,false表示禁止。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

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

try {
  let enabled = false;
  let promise = windowClass.setResizeByDragEnabled(enabled);
  promise.then(() => {
    console.info(`Succeeded in setting the function of disabling the resize by drag window.`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the function of disabling the resize by drag window. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the function of disabling the resize by drag window. Cause code: ${exception.code}, message: ${exception.message}`);
}

recover11+

recover(): Promise<void>

将主窗口从全屏、最大化、分屏模式下还原为浮动窗口,并恢复到进入该模式之前的大小和位置,已经是浮动窗口模式不可再还原。使用Promise异步回调。此接口仅在多窗层叠布局效果下生效。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300001 Repeated operation.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let promise = windowClass.recover();
      promise.then(() => {
        console.info('Succeeded in recovering the window.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to recover the window. Cause code: ${err.code}, message: ${err.message}`);
      });
    });
  }
}

restore14+

restore(): Promise<void>

将主窗口从最小化状态,恢复到前台显示,并恢复到进入该模式之前的大小和位置。使用Promise异步回调。 此接口仅在多窗层叠布局效果下生效,仅在主窗口为最小化状态且UIAbility生命周期为onForeground时生效。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    try {
      let windowClass = windowStage.getMainWindowSync();
      // 调用minimize, 使主窗最小化
      windowClass.minimize();
      //设置延时函数延时5秒钟后对主窗进行恢复。
      setTimeout(()=>{
        //调用restore()函数对主窗进行恢复。
        let promise = windowClass.restore();
        promise.then(() => {
          console.info('Succeeded in restoring the window.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to restore the window. Cause code: ${err.code}, message: ${err.message}`);
        });
      }, 5000);
    } catch (exception) {
      console.error(`Failed to restore the window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

getWindowLimits11+

getWindowLimits(): WindowLimits

获取当前应用窗口的尺寸限制。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

类型 说明
WindowLimits 当前窗口尺寸限制。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

try {
  let windowLimits = windowClass.getWindowLimits();
} catch (exception) {
  console.error(`Failed to obtain the window limits of window. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowLimits11+

setWindowLimits(windowLimits: WindowLimits): Promise<WindowLimits>

设置当前应用窗口的尺寸限制,使用Promise异步回调。 默认存在一个系统尺寸限制,系统尺寸限制由产品配置决定,不可修改。未调用setWindowLimits配置过WindowLimits时,使用getWindowLimits可获取系统限制。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
windowLimits WindowLimits 目标窗口的尺寸限制,单位为px。

返回值:

类型 说明
Promise<WindowLimits> Promise对象。返回设置后的尺寸限制,为入参与系统尺寸限制的交集。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
try {
  let windowLimits: window.WindowLimits = {
    maxWidth: 1500,
    maxHeight: 1000,
    minWidth: 500,
    minHeight: 400
  };
  let promise = windowClass.setWindowLimits(windowLimits);
    promise.then((data) => {
    console.info(`Succeeded in changing the window limits. Cause: ${JSON.stringify(data)}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to change the window limits. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to change the window limits. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowLimits15+

setWindowLimits(windowLimits: WindowLimits, isForcible: boolean): Promise<WindowLimits>

设置当前应用窗口的尺寸限制,使用Promise异步回调。 默认存在一个系统尺寸限制,系统尺寸限制由产品配置决定,不可修改。未调用setWindowLimits配置过WindowLimits时,使用getWindowLimits可获取系统限制。 此接口仅支持2in1设备。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
windowLimits WindowLimits 目标窗口的尺寸限制,单位为px。
isForcible boolean 是否强制设置窗口的尺寸限制。
设置为true,表示窗口宽高最小值以系统限制值和40vp两者中的低数值为准,窗口宽高的最大值仍取决于系统限制。
设置为false,表示窗口宽高的最小值和最大值都取决于系统限制。

返回值:

类型 说明
Promise<WindowLimits> Promise对象。返回设置后的窗口尺寸限制。根据isForcible判断为入参与系统默认窗口尺寸限制的交集。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
try {
  let windowLimits: window.WindowLimits = {
    maxWidth: 1500,
    maxHeight: 1000,
    minWidth: 100,
    minHeight: 100
  };
  let promise = windowClass.setWindowLimits(windowLimits, true);
  promise.then((data) => {
    console.info('Succeeded in changing the window limits. Cause:' + JSON.stringify(data));
  }).catch((err: BusinessError) => {
    console.error(`Failed to change the window limits. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to change the window limits. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowMask12+

setWindowMask(windowMask: Array<Array<number>>): Promise<void>;

设置异形窗口的掩码,使用Promise异步回调。异形窗口为非常规形状的窗口,掩码用于描述异形窗口的形状。此接口仅限子窗和全局悬浮窗可用。 当异形窗口大小发生变化时,实际的显示内容为掩码大小和窗口大小的交集部分。

该接口只在多个线程操作同一个窗口时可能返回错误码1300002。窗口被销毁场景下错误码返回401。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
windowMask Array<Array<number>> 异形窗口的掩码,该参数仅支持宽高为窗口宽高、取值为整数0和整数1的二维数组输入,整数0代表所在像素透明,整数1代表所在像素不透明,宽高不符合的二维数组或二维数组取值不为整数0和整数1的二维数组为非法参数。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
try {
  let windowMask: Array<Array<number>> = [
      [0, 0, 0, 1, 0, 0, 0],
      [0, 0, 1, 1, 1, 0, 0],
      [0, 1, 1, 0, 1, 1, 0],
      [1, 1, 0, 0, 0, 1, 1]
    ];
  let promise = windowClass.setWindowMask(windowMask);
    promise.then(() => {
    console.info('Succeeded in setting the window mask.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the window mask. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the window mask. Cause code: ${exception.code}, message: ${exception.message}`);
}

keepKeyboardOnFocus11+

keepKeyboardOnFocus(keepKeyboardFlag: boolean): void

窗口获焦时保留由其他窗口创建的软键盘,仅支持系统窗口与应用子窗口。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
keepKeyboardFlag boolean 是否保留其他窗口创建的软键盘。true表示保留;false表示不保留。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

try {
  windowClass.keepKeyboardOnFocus(true);
} catch (exception) {
  console.error(`Failed to keep keyboard onFocus. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowDecorVisible11+

setWindowDecorVisible(isVisible: boolean): void

设置窗口标题栏是否可见,对存在标题栏和三键区的窗口形态生效。Stage模型下,该接口需要在loadContent()setUIContent()调用生效后使用。

设置窗口标题栏不可见后,当主窗口进入全屏沉浸状态时,此时鼠标Hover到上方窗口标题栏热区上会显示悬浮标题栏。若想禁用悬浮标题栏显示,请使用setTitleAndDockHoverShown()接口。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
isVisible boolean 设置标题栏是否可见,true为可见,false为隐藏。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

import { BusinessError } from '@kit.BasicServicesKit';
let storage: LocalStorage = new LocalStorage();
storage.setOrCreate('storageSimpleProp', 121);
windowClass.loadContent("pages/page2", storage, (err: BusinessError) => {
  let errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in loading the content.');
  let isVisible = false;
  // 调用setWindowDecorVisible接口
  try {
      windowClass?.setWindowDecorVisible(isVisible);
  } catch (exception) {
      console.error(`Failed to set the visibility of window decor. Cause code: ${exception.code}, message: ${exception.message}`);
  }
});

getWindowDecorVisible18+

getWindowDecorVisible(): boolean

查询窗口标题栏是否可见。如果使用Stage模型,该接口需要在loadContent()setUIContent()调用生效后使用。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

类型 说明
boolean 返回当前窗口标题栏是否可见,true表示可见,false表示不可见。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

let isVisible: boolean | undefined = undefined;
windowClass.setUIContent('pages/WindowPage').then(() => {
  try {
    isVisible = windowClass?.getWindowDecorVisible();
  } catch (exception) {
    console.error(`Failed to get the window decor visibility. Cause code: ${exception.code}, message: ${exception.message}`);
  }
})

setWindowTitle15+

setWindowTitle(titleName: string): Promise<void>

设置窗口标题,存在标题栏的窗口形态生效,若不存在标题栏则返回1300002错误码,使用Promise异步回调。如果使用Stage模型,该接口需要在loadContent()setUIContent()调用生效后使用。

此接口仅支持2in1设备和平板设备。

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
titleName string 窗口标题。标题显示区域最右端不超过系统三键区域最左端,超过部分以省略号表示。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

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

try {
  let title = "title";
  windowClass.setWindowTitle(title).then(() => {
    console.info('Succeeded in setting the window title.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the window title. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the window title. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowTitleMoveEnabled14+

setWindowTitleMoveEnabled(enabled: boolean): void

禁止/使能主窗或子窗标题栏默认移动窗口和双击最大化的功能,当禁用标题栏默认移动窗口和双击最大化的功能时,可使用startMoving()在应用热区中发起拖拽移动,使用maximize()实现最大化功能。如果使用Stage模型,该接口需要在loadContent()setUIContent()调用生效后使用。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
enabled boolean 是否使能标题栏默认移动窗口和双击最大化功能,true表示使能,false表示不使能。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    try {
      windowStage.loadContent("pages/Index").then(() =>{
        let windowClass = windowStage.getMainWindowSync();
        let enabled = false;
        windowClass.setWindowTitleMoveEnabled(enabled);
        console.info(`Succeeded in setting the the window title move enabled: ${enabled}`);
      });
    } catch (exception) {
      console.error(`Failed to set the window title move enabled. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

setSubWindowModal12+

setSubWindowModal(isModal: boolean): Promise<void>

设置子窗的模态属性是否启用,使用Promise异步回调。

子窗口调用该接口时,设置子窗口模态属性是否启用。启用子窗口模态属性后,其父级窗口不能响应用户操作,直到子窗口关闭或者子窗口的模态属性被禁用。

子窗口之外的窗口调用该接口时,会报错。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
isModal boolean 设置子窗口模态属性是否启用,true为启用,false为不启用。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    // 创建子窗
    try {
      let subWindow = windowStage.createSubWindow("testSubWindow");
      subWindow.then((data) => {
        if (data == null) {
          console.error("Failed to create the subWindow. Cause: The data is empty");
          return;
        }
        windowClass = data;
        let promise = windowClass.setSubWindowModal(true);
        promise.then(() => {
          console.info('Succeeded in setting subwindow modal');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set subwindow modal. Cause code: ${err.code}, message: ${err.message}`);
        });
      });
    } catch (exception) {
      console.error(`Failed to create the subWindow. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

setSubWindowModal14+

setSubWindowModal(isModal: boolean, modalityType: ModalityType): Promise<void>

设置子窗的模态类型,使用Promise异步回调。

当子窗口模态类型为模窗口子窗时,其父级窗口不能响应用户操作,直到子窗口关闭或者子窗口的模态类型被禁用。

当子窗口模态类型为模应用子窗时,其父级窗口与该应用其他实例的窗口不能响应用户操作,直到子窗口关闭或者子窗口的模态类型被禁用。

此接口仅支持设置子窗口模态类型,当需要禁用子窗口模态属性时,建议使用setSubWindowModal12+

子窗口之外的窗口调用该接口时,会报错。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
isModal boolean 设置子窗口模态属性是否启用,true为启用,false为不启用。当前仅支持设置为true。
modalityType ModalityType 子窗口模态类型。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    // 创建子窗
    try {
      let subWindow = windowStage.createSubWindow("testSubWindow");
      subWindow.then((data) => {
        if (data == null) {
          console.error("Failed to create the subWindow. Cause: The data is empty");
          return;
        }
        windowClass = data;
        let promise = windowClass.setSubWindowModal(true, window.ModalityType.WINDOW_MODALITY);
        promise.then(() => {
          console.info('Succeeded in setting subwindow modal');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set subwindow modal. Cause code: ${err.code}, message: ${err.message}`);
        });
      });
    } catch (exception) {
      console.error(`Failed to create the subWindow. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

setWindowDecorHeight11+

setWindowDecorHeight(height: number): void

设置窗口的标题栏高度,仅在2in1设备中,对存在标题栏和三键区的窗口形态生效。如果使用Stage模型,该接口需要在loadContent()setUIContent()调用生效后使用。

当主窗口进入全屏沉浸状态时,此时鼠标Hover到窗口标题栏热区时,会显示悬浮标题栏,悬浮标题栏高度固定为37vp。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
height number 设置的窗口标题栏高度,仅支持具有窗口标题栏的窗口。该参数为整数,浮点数输入将向下取整,取值范围为[37,112],范围外为非法参数,单位为vp。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

windowClass.setUIContent('pages/WindowPage').then(() => {
  let height: number = 50;
  try {
    windowClass?.setWindowDecorHeight(height);
    console.info(`Succeeded in setting the height of window decor: ${height}`);
  } catch (exception) {
    console.error(`Failed to set the height of window decor. Cause code: ${exception.code}, message: ${exception.message}`);
  }
})

setDecorButtonStyle14+

setDecorButtonStyle(dectorStyle: DecorButtonStyle): void

设置装饰栏按钮样式,仅对主窗和子窗生效。如果使用Stage模型,该接口需要在loadContent()setUIContent()调用生效后使用。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
dectorStyle DecorButtonStyle 要设置的装饰栏按钮样式。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { ConfigurationConstant } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    try {
      windowStage.loadContent("pages/Index").then(() =>{
        let windowClass = windowStage.getMainWindowSync();
        let colorMode : ConfigurationConstant.ColorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT;
        let style: window.DecorButtonStyle = {
          colorMode: colorMode,
          buttonBackgroundSize: 24,
          spacingBetweenButtons: 12,
          closeButtonRightMargin: 20
        };
        windowClass.setDecorButtonStyle(style);
        console.info('Succeeded in setting the style of button. Data: ' + JSON.stringify(style));
      });
    } catch (exception) {
      console.error(`Failed to set the style of button. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

getDecorButtonStyle14+

getDecorButtonStyle(): DecorButtonStyle

获取装饰栏按钮样式,仅对主窗和子窗生效。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

类型 说明
DecorButtonStyle 返回当前窗口装饰栏上的按钮样式,窗口装饰按钮区域位于窗口的右上角。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

try {
  let decorButtonStyle = windowClass.getDecorButtonStyle();
  console.info('Succeeded in getting the style of button. Data: ' + JSON.stringify(decorButtonStyle));
} catch (exception) {
  console.error(`Failed to get the style of button. Cause code: ${exception.code}, message: ${exception.message}`);
}

getWindowDecorHeight11+

getWindowDecorHeight(): number

获取窗口的标题栏高度,仅在2in1设备中,对存在标题栏和三键区的窗口形态生效。如果使用Stage模型,该接口需要在loadContent()setUIContent()调用生效后使用。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

类型 说明
number 返回的窗口标题栏高度。该参数为整数,取值范围为[37,112],单位为vp。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

windowClass.setUIContent('pages/WindowPage').then(() => {
  try {
    let height = windowClass?.getWindowDecorHeight();
    console.info(`Succeeded in getting the height of window decor: ${height}`);
  } catch (exception) {
    console.error(`Failed to get the height of window decor. Cause code: ${exception.code}, message: ${exception.message}`);
  }
})

getTitleButtonRect11+

getTitleButtonRect(): TitleButtonRect

获取主窗口或启用装饰的子窗口的标题栏上的最小化、最大化、关闭按钮矩形区域。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

类型 说明
TitleButtonRect 标题栏上的最小化、最大化、关闭按钮矩形区域,该区域位置坐标相对窗口右上角。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      try {
        let titleButtonArea = windowClass.getTitleButtonRect();
        console.info('Succeeded in obtaining the area of title buttons. Data: ' + JSON.stringify(titleButtonArea));
      } catch (exception) {
        console.error(`Failed to get the area of title buttons. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

getWindowStatus12+

getWindowStatus(): WindowStatusType

获取当前应用窗口的模式。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

类型 说明
WindowStatusType 当前窗口模式。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

try {
  let windowStatusType = windowClass.getWindowStatus();
} catch (exception) {
  console.error(`Failed to obtain the window status of window. Cause code: ${exception.code}, message: ${exception.message}`);
}

isFocused12+

isFocused(): boolean

判断当前窗口是否已获焦。

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
boolean 当前窗口是否已获焦。true表示当前窗口已获焦,false则表示当前窗口未获焦。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

try {
  let focus = windowClass.isFocused();
  console.info('Succeeded in checking whether the window is focused. Data: ' + JSON.stringify(focus));
} catch (exception) {
  console.error(`Failed to check whether the window is focused. Cause code: ${exception.code}, message: ${exception.message}`);
}

createSubWindowWithOptions12+

createSubWindowWithOptions(name: string, options: SubWindowOptions): Promise<Window>

创建主窗口、子窗口或悬浮窗下的子窗口,使用Promise异步回调。

此接口仅可在2in1设备下使用。

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

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 子窗口的名字。
options SubWindowOptions 子窗口参数。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前Window下创建的子窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

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

try {
  let options : window.SubWindowOptions = {
    title: 'title',
    decorEnabled: true,
    isModal: true
  };
  let promise = windowClass.createSubWindowWithOptions('mySubWindow', options);
  promise.then((data) => {
    console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
  }).catch((err: BusinessError) => {
    console.error(`Failed to create the subwindow. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to create the subwindow. Cause code: ${exception.code}, message: ${exception.message}`);
}

setParentWindow19+

setParentWindow(windowId: number): Promise<void>

更改子窗口的父窗口,该父窗口仅支持主窗口、子窗口或悬浮窗,使用Promise异步回调。

如果该子窗口处于获焦状态,且新的父窗口处于前台,则会抬升父窗口的层级。

如果该子窗口处于获焦状态,且新的父窗口的子窗口存在层级更高的模态子窗口,则焦点会转移给该模态子窗口。

此接口仅可在2in1设备下使用。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
windowId number 父窗口id,该参数应为整数。推荐使用getWindowProperties()方法获取父窗口id属性。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.
1300009 The parent window is invaild.

示例:

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

try {
  let windowClass: window.Window = window.findWindow("subWindow");
  let newParentWindow: window.Window = window.findWindow("newParentWindow");
  let newParentWindowId: number = newParentWindow.getWindowProperties().id;
  let promise = windowClass.setParentWindow(newParentWindowId);
  promise.then(() => {
    console.info('Succeeded in setting the new parent window.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the new parent window. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the new parent window. Cause code: ${exception.code}, message: ${exception.message}`);
}

getParentWindow19+

getParentWindow(): Window

获取子窗口的父窗口。

此接口仅可在2in1设备下使用。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
Window 子窗口的父窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.
1300009 The parent window is invaild.

示例:

try {
  let windowClass: window.Window = window.findWindow("subWindow");
  let parentWindow: window.Window = windowClass.getParentWindow();
  let properties = parentWindow.getWindowProperties();
  console.info(`Succeeded in obtaining parent window properties. Property: ${JSON.stringify(properties)}`);
} catch (exception) {
  console.error(`Failed to get the parent window. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowTitleButtonVisible14+

setWindowTitleButtonVisible(isMaximizeButtonVisible: boolean, isMinimizeButtonVisible: boolean, isCloseButtonVisible?: boolean): void

设置主窗标题栏上的最大化、最小化、关闭按钮是否可见。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
isMaximizeButtonVisible boolean 设置最大化按钮是否可见,true为可见,false为隐藏。如果最大化按钮隐藏,那么在最大化场景下,也隐藏对应的还原按钮。
isMinimizeButtonVisible boolean 设置最小化按钮是否可见,true为可见,false为隐藏。
isCloseButtonVisible boolean 设置关闭按钮是否可见,true为可见,false为隐藏,默认值true。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    // 加载主窗口对应的页面
    windowStage.loadContent('pages/Index', (err) => {
      let mainWindow: window.Window | undefined = undefined;
      // 获取应用主窗口。
      windowStage.getMainWindow().then(
        data => {
          mainWindow = data;
          console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
          // 调用setWindowTitleButtonVisible接口,隐藏主窗标题栏最大化、最小化、关闭按钮。
          mainWindow.setWindowTitleButtonVisible(false, false, false);
        }
      ).catch((err: BusinessError) => {
          if(err.code){
            console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
          }
      });
    });
  }
}

setWindowTopmost14+

setWindowTopmost(isWindowTopmost: boolean): Promise<void>

应用主窗口调用,实现将窗口置于其他应用窗口之上不被遮挡,使用Promise异步回调。

应用可通过自定义快捷键实现主窗口的置顶和取消置顶。

此接口仅可在2in1设备下使用。

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

需要权限: ohos.permission.WINDOW_TOPMOST

参数:

参数名 类型 必填 说明
isWindowTopmost boolean 设置主窗口置顶,true为置顶,false为取消置顶。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
201 Permission verification failed. The application does not have the permission required to call the API.
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// ets/pages/Index.ets
import { window } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

let windowClass: window.Window | undefined;
let keyUpEventAry: string[] = [];

@Entry
@Component
struct Index {
  private context = (this.getUIContext()?.getHostContext() as common.UIAbilityContext);
  private windowStage = this.context.windowStage;

  build() {
    RelativeContainer() {
      Button("窗口置顶")
        .onClick(() => {
          try {
            windowClass = this.windowStage.getMainWindowSync();
            //  true:窗口置顶,false:取消窗口置顶
            let isWindowTopmost: boolean = true;
            let promiseTopmost = windowClass.setWindowTopmost(isWindowTopmost);
            promiseTopmost.then(() => {
              console.info('Succeeded in setting the main window to be topmost.');
            }).catch((err: BusinessError) => {
              console.error(`Failed to set the main window to be topmost. Cause code: ${err.code}, message: ${err.message}`);
            });
          } catch (exception) {
            console.error(`Failed to obtain the top window. Cause code: ${exception.code}, message: ${exception.message}`)
          }
        })
    }
    .height('100%')
    .width('100%')
    .onKeyEvent((event) => {
      if(event) {
        if(event.type === KeyType.Down) {
          keyUpEventAry = [];
        }
        if(event.type === KeyType.Up) {
          keyUpEventAry.push(event.keyText);
          // 自定义快捷键 ctrl+T 执行主窗口置顶、取消置顶的操作
          if(windowClass && keyUpEventAry.includes('KEYCODE_CTRL_LEFT') && keyUpEventAry.includes('KEYCODE_T')) {
            let isWindowTopmost: boolean = false;
            windowClass.setWindowTopmost(isWindowTopmost);
          }
        }
      }
    })
  }
}

raiseToAppTop14+

raiseToAppTop(): Promise<void>

应用子窗口调用,提升应用子窗口到顶层,只在当前应用同一个父窗口下的相同类型子窗范围内生效,对于自定义了zLevel属性的子窗口,只在当前应用同一个父窗口下相同zLevel值的子窗范围内生效。使用Promise异步回调。

使用该接口需要先创建子窗口,并确保该子窗口调用showWindow()并执行完毕。

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.
1300009 The parent window is invalid.

示例:

// EntryAbility.ets
import { window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    // 创建子窗
    try {
      let subWindowPromise = windowStage.createSubWindow("testSubWindow");
      subWindowPromise.then((data) => {
        if (data == null) {
          console.error("Failed to create the subWindow. Cause: The data is empty");
          return;
        }
        let showWindowPromise = data.showWindow();
        showWindowPromise.then(() => {
          let raiseToTopPromise = data.raiseToAppTop();
          raiseToTopPromise.then(() => {
            console.info('Succeeded in raising window to app top.');
          }).catch((err: BusinessError)=>{
            console.error(`Failed to raise window to app top. Cause code: ${err.code}, message: ${err.message}`);
          });
        });
      });
    } catch (exception) {
      console.error(`Failed to create the subWindow. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

setRaiseByClickEnabled14+

setRaiseByClickEnabled(enable: boolean): Promise<void>

禁止/使能子窗点击抬升功能。使用Promise异步回调。

通常来说,点击一个子窗口,会将该子窗口显示抬升到应用内同一个父窗口下同类型子窗口的最上方,如果设置为false,那么点击子窗口的时候,不会将该子窗口进行抬升,而是保持不变。

使用该接口需要先创建子窗口,并确保该子窗口调用showWindow()并执行完毕。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
enable boolean 设置子窗口点击抬升功能是否使能,true表示使能,false表示禁止。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.
1300009 The parent window is invalid.

示例:

// EntryAbility.ets
import { window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    // 创建子窗
    try {
      let subWindowPromise = windowStage.createSubWindow("testSubWindow");
      subWindowPromise.then((data) => {
        if (data == null) {
          console.error("Failed to create the subWindow. Cause: The data is empty");
          return;
        }
        let showWindowPromise = data.showWindow();
        showWindowPromise.then(() => {
          let enabled = false;
          let setRaisePromise = data.setRaiseByClickEnabled(enabled);
          setRaisePromise.then(() => {
            console.info('Succeeded in disabling the raise-by-click function.');
          }).catch((err: BusinessError)=>{
            console.error(`Failed to disable the raise-by-click function. Cause code: ${err.code}, message: ${err.message}`);
          });
        });
      });
    } catch (exception) {
      console.error(`Failed to create the subWindow. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

enableLandscapeMultiWindow12+

enableLandscapeMultiWindow(): Promise<void>

应用部分界面支持横向布局时,在进入该界面时使能,使能后可支持进入横向多窗。不建议竖向布局界面使用。

此接口只对应用主窗口生效,且需要在module.json5配置文件中abilities标签中配置preferMultiWindowOrientation属性为"landscape_auto"。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

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

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let promise = windowClass.enableLandscapeMultiWindow();
      promise.then(() => {
        console.info('Succeeded in making multi-window become landscape.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to make multi-window become landscape. Cause code: ${err.code}, message: ${err.message}`);
      });
    });
  }
}

disableLandscapeMultiWindow12+

disableLandscapeMultiWindow(): Promise<void>

应用部分界面支持横向布局时,在退出该界面时去使能,去使能后不支持进入横向多窗。

此接口只对应用主窗口生效,且需要在module.json5配置文件中abilities标签中配置preferMultiWindowOrientation属性为"landscape_auto"。

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

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

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let promise = windowClass.disableLandscapeMultiWindow();
      promise.then(() => {
        console.info('Succeeded in making multi-window become not landscape.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to make multi-window become not landscape. Cause code: ${err.code}, message: ${err.message}`);
      });
    });
  }
}

setDialogBackGestureEnabled12+

setDialogBackGestureEnabled(enabled: boolean): Promise<void>

设置模态窗口是否响应手势返回事件,非模态窗口调用返回错误码。

系统能力:SystemCapability.Window.SessionManager

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
enabled boolean 是否响应手势返回事件。
true表示响应手势返回事件,触发onBackPress回调;false表示不响应手势返回事件,不触发onBackPress回调。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    let config: window.Configuration = {
      name: "test",
      windowType: window.WindowType.TYPE_DIALOG,
      ctx: this.context
    };
    try {
      window.createWindow(config, (err: BusinessError, data) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to create the window. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        windowClass = data;
        windowClass.setUIContent("pages/Index");
        let enabled = true;
        let promise = windowClass.setDialogBackGestureEnabled(enabled);
        promise.then(() => {
          console.info('Succeeded in setting dialog window to respond back gesture.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set dialog window to respond back gesture. Cause code: ${err.code}, message: ${err.message}`);
        });
      });
    } catch (exception) {
      console.error(`Failed to create the window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}
// ets/pages/Index.ets
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
    }
    .height('100%')
    .width('100%')
  }

  onBackPress(): boolean | void {
    console.info('Succeeded in setting dialog window to respond back gesture.');
    return true;
  }
}

startMoving14+

startMoving(): Promise<void>

开始移动窗口,使用Promise异步回调。

仅在onTouch事件(其中,事件类型必须为TouchType.Down)的回调方法中调用此接口才会有移动效果,成功调用此接口后,窗口将跟随鼠标或触摸点移动。

在点击拖拽场景下,若不期望在按下时触发拖拽事件,则可以在事件类型为TouchType.Move(需要保证当前行为已经触发TouchType.Down事件)时调用此接口,触发移动效果。

此接口仅可在2in1设备下使用。

仅对主窗、子窗、系统窗口生效,其它设备类型和窗口类型调用此接口会报错。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300001 Repeated operation.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// ets/pages/Index.ets
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private isTouchDown: boolean = false;
  build() {
    Row() {
      Column() {
        Blank('160')
          .color(Color.Blue)
          .onTouch((event: TouchEvent) => {
            if (event.type === TouchType.Down) {
              try {
                let windowClass: window.Window = window.findWindow("subWindow");
                windowClass.startMoving().then(() => {
                  console.info('Succeeded in starting moving window.')
                }).catch((err: BusinessError) => {
                  console.error(`Failed to start moving. Cause code: ${err.code}, message: ${err.message}`);
                });
              } catch (exception) {
                console.error(`Failed to start moving window. Cause code: ${exception.code}, message: ${exception.message}`);
              }
            }
          })
        Blank('160')
          .color(Color.Red)
          .onTouch((event: TouchEvent) => {
            if(event.type == TouchType.Down){
              this.isTouchDown = true;
            } else if (event.type === TouchType.Move && this.isTouchDown) {
              try {
                let context = this.getUIContext().getHostContext();
                window.getLastWindow(context).then((data)=>{
                  let windowClass: window.Window = data;
                  windowClass.startMoving().then(() => {
                    console.info('Succeeded in starting moving window.')
                  }).catch((err: BusinessError) => {
                    console.error(`Failed to start moving. Cause code: ${err.code}, message: ${err.message}`);
                  });
                });
              } catch (exception) {
                console.error(`Failed to start moving window. Cause code: ${exception.code}, message: ${exception.message}`);
              }
            } else {
              this.isTouchDown = false;
            }
          })
      }.width('100%')
    }.height('100%').width('100%')
  }
}

startMoving15+

startMoving(offsetX: number, offsetY: number): Promise<void>

指定鼠标在窗口内的位置并移动窗口,使用Promise异步回调。

在同应用内窗口分合后,且鼠标保持按下状态直接移动新窗口,如果此时鼠标快速移动,窗口移动时鼠标可能会在窗口外。可以使用本接口指定窗口移动时鼠标在窗口内的位置,先移动窗口到鼠标位置,再开始移动窗口。

仅在onTouch事件(其中,事件类型必须为TouchType.Down)的回调方法中调用此接口才会有移动效果,成功调用此接口后,窗口将跟随鼠标移动。

在点击拖拽场景下,若不期望在按下时触发拖拽事件,则可以在事件类型为TouchType.Move(需要保证当前行为已经触发TouchType.Down事件)时调用此接口,触发移动效果。

此接口仅可在2in1设备下使用。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
offsetX number 窗口移动时预期鼠标位置相对窗口左上角的x轴偏移量,单位为px,该参数仅支持整数输入,浮点数向下取整。负值为非法参数,大于窗口宽度为非法参数,窗口宽度可以在窗口属性WindowProperties中获取。
offsetY number 窗口移动时预期鼠标位置相对窗口左上角的y轴偏移量,单位为px,该参数仅支持整数输入,浮点数向下取整。负值为非法参数,大于窗口高度为非法参数,窗口高度可以在窗口属性WindowProperties中获取。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300001 Repeated operation.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// ets/pages/Index.ets
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private isTouchDown: boolean = false;
  build() {
    Row() {
      Column() {
        Blank('160')
          .color(Color.Blue)
          .onTouch((event: TouchEvent) => {
            if (event.type === TouchType.Down) {
              try {
                let windowClass: window.Window = window.findWindow("subWindow");
                windowClass.startMoving(100, 50).then(() => {
                  console.info('Succeeded in starting moving window.')
                }).catch((err: BusinessError) => {
                  console.error(`Failed to start moving. Cause code: ${err.code}, message: ${err.message}`);
                });
              } catch (exception) {
                console.error(`Failed to start moving window. Cause code: ${exception.code}, message: ${exception.message}`);
              }
            }
          })
        Blank('160')
          .color(Color.Red)
          .onTouch((event: TouchEvent) => {
            if(event.type == TouchType.Down){
              this.isTouchDown = true;
            } else if (event.type === TouchType.Move && this.isTouchDown) {
              try {
                let context = this.getUIContext().getHostContext();
                window.getLastWindow(context).then((data)=>{
                  let windowClass: window.Window = data;
                  windowClass.startMoving(100, 50).then(() => {
                    console.info('Succeeded in starting moving window.')
                  }).catch((err: BusinessError) => {
                    console.error(`Failed to start moving. Cause code: ${err.code}, message: ${err.message}`);
                  });
                });
              } catch (exception) {
                console.error(`Failed to start moving window. Cause code: ${exception.code}, message: ${exception.message}`);
              }
            } else {
              this.isTouchDown = false;
            }
          })
      }.width('100%')
    }.height('100%').width('100%')
  }
}

stopMoving15+

stopMoving(): Promise<void>

在窗口拖拽移动过程中,通过此接口来停止窗口移动,使用Promise异步回调。

此接口仅可在2in1设备下使用。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {

  onWindowStageCreate(windowStage: window.WindowStage) {
    try {
      let windowClass = windowStage.getMainWindowSync();
      windowClass.on('windowRectChange', (data: window.RectChangeOptions) => {
        if (data.reason === window.RectChangeReason.MOVE) {
          windowClass.stopMoving().then(() => {
            console.info('Succeeded in stopping moving window.')
          }).catch((err: BusinessError) => {
            console.error(`Failed to stop moving. Cause code: ${err.code}, message: ${err.message}`);
          });
        }
      });
    } catch (exception) {
      console.error(`Failed to stop moving window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

setGestureBackEnabled13+

setGestureBackEnabled(enabled: boolean): Promise<void>

设置当前窗口是否禁用返回手势功能,仅主窗全屏模式下生效,2in1设备下不生效。 禁用返回手势功能后,当前应用会禁用手势热区,侧滑返回功能失效;切换到其他应用或者回到桌面后,手势热区恢复,侧滑返回功能正常。 开启返回手势功能后,当前应用会恢复手势热区,侧滑返回功能正常。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 13开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
enabled boolean true时开启返回手势功能,false时禁用返回手势功能。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;

      // 设置当前窗口禁用返回手势功能
      try {
        let gestureBackEnabled: boolean = false;
        let promise = windowClass.setGestureBackEnabled(gestureBackEnabled);
        promise.then(() => {
          console.info(`Succeeded in setting gesture back disabled`);
        }).catch((err: BusinessError) => {
          console.error(`Failed to set gesture back disabled, Cause code: ${err.code}, message: ${err.message}`);
        });
      } catch(exception) {
        console.error(`Failed to set gesture back disabled, Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

isGestureBackEnabled13+

isGestureBackEnabled(): boolean

获取当前窗口是否禁用返回手势功能,仅主窗全屏模式下生效,2in1设备不生效。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 13开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
boolean 是否已经禁用返回手势。true表示未禁用返回手势功能,false表示已禁用返回手势功能。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;

      // 获取当前窗口是否禁用返回手势功能
      try {
        let gestureBackEnabled: boolean = windowClass.isGestureBackEnabled();
        console.info(`Succeeded in obtaining gesture back enabled status: ${gestureBackEnabled}`);
      } catch (exception) {
        console.error(`Failed to get gesture back enabled status. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setWindowShadowRadius17+

setWindowShadowRadius(radius: number): void

设置子窗或悬浮窗窗口边缘阴影的模糊半径,此接口仅支持在2in1设备或平板设备上使用。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 17开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
radius number 表示窗口边缘阴影的模糊半径。该参数为浮点数,单位为px,取值范围为[0.0, +∞),取值为0.0时表示关闭窗口边缘阴影。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

try {
  windowClass.setWindowShadowRadius(4.0);
} catch (exception) {
  console.error(`Failed to set shadow. Cause code: ${exception.code}, message: ${exception.message}`);
}

setWindowCornerRadius17+

setWindowCornerRadius(cornerRadius: number): Promise<void>

设置子窗或悬浮窗的圆角半径值,使用Promise异步回调。

此接口仅可在2in1设备下使用。

圆角半径值过大将会导致三键(最大化、最小化、关闭按钮)位置被裁切,且会导致热区不易识别,请根据窗口大小设置合适的圆角半径值。

在调用此接口之前调用getWindowCornerRadius()接口可以获得窗口默认圆角半径值。

系统能力:SystemCapability.Window.SessionManager

原子化服务API: 从API version 17开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
cornerRadius number 表示窗口圆角的半径值。该参数为浮点数,单位为vp,取值范围为[0.0, +∞),取值为0.0时表示没有窗口圆角。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

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

try{
  let promise = windowClass.setWindowCornerRadius(1.0);
  promise.then(() => {
    console.info('Succeeded in setting window corner radius.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set window corner radius. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set corner radius. Cause code: ${exception.code}, message: ${exception.message}`);
}

getWindowCornerRadius17+

getWindowCornerRadius(): number

获取子窗或悬浮窗的圆角半径值,在未调用setWindowCornerRadius()接口设置窗口圆角半径值之前,调用此接口可获取窗口默认圆角半径值。

此接口仅可在2in1设备下使用。

系统能力:SystemCapability.Window.SessionManager

原子化服务API: 从API version 17开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
number 当前子窗或悬浮窗的圆角半径值,单位为vp。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

try {
  let cornerRadius = windowClass.getWindowCornerRadius();
} catch (exception) {
  console.error(`Failed to get corner radius. Cause code: ${exception.code}, message: ${exception.message}`);
}

setExclusivelyHighlighted15+

setExclusivelyHighlighted(exclusivelyHighlighted: boolean): Promise<void>

设置窗口独占激活态属性。独占激活态表示窗口获焦时,会导致当前父子窗口链中处于激活态的其他窗口失去激活态。使用Promise异步回调。

此接口对主窗、模态窗、dialog窗口不生效。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
exclusivelyHighlighted boolean 窗口是否独占激活态。true表示独占激活态;false表示不独占激活态。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

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

let exclusivelyHighlighted: boolean = true;
try {
  let promise = windowClass.setExclusivelyHighlighted(exclusivelyHighlighted);
  promise.then(() => {
    console.info('Succeeded in setting the window to be exclusively highlight.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the window to be exclusively highlight. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the window to be exclusively highlight. Cause code: ${exception.code}, message: ${exception.message}`);
}

isWindowHighlighted18+

isWindowHighlighted(): boolean

获取当前窗口是否为激活态。为准确获取激活态,需要在WindowEventType生命周期处于WINDOW_ACTIVE之后调用。

可使用on('windowHighlightChange')监听对应状态变更,再执行对应具体业务。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
boolean 当前窗口是否为激活态。true表示当前窗口为激活态,false表示当前窗口非激活态。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

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

try {
  let isHighlighted = windowClass.isWindowHighlighted();
  console.info(`Succeeded in getting the window highlight status: ${isHighlighted}`);
} catch (exception) {
  console.error(`Failed to get the window highlight status.. Cause code: ${exception.code}, message: ${exception.message}`);
}

setFollowParentMultiScreenPolicy17+

setFollowParentMultiScreenPolicy(enabled: boolean): Promise<void>

设置子窗口在其父窗口处于拖拽移动或拖拽缩放过程时,该子窗口是否支持跨多个屏幕同时显示。使用Promise异步回调。

通过监听父窗口大小位置变化,对子窗口调用moveWindowTo()等接口实现子窗口跟随父窗口布局时,此时子窗口默认不支持跨多个屏幕同时显示。

对子窗口调用此接口后可以使能子窗口在跟随父窗口布局过程中跨多个屏幕同时显示。

此接口仅可在2in1设备下使用。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 17开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
enabled boolean 设置子窗口在其父窗口处于拖拽移动或拖拽缩放过程时,该子窗口是否支持跨多个屏幕同时显示。true表示支持;false表示不支持。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported.Function setFollowParentMultiScreenPolicy can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

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

try {
  let windowClass: window.Window = window.findWindow("subWindow");
  let enabled: boolean = true;
  let promise = windowClass?.setFollowParentMultiScreenPolicy(enabled);
  promise.then(() => {
    console.info('Succeeded in setting the sub window supports multi-screen simultaneous display')
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the sub window supports multi-screen simultaneous display. Cause code: ${err.code}, message: ${err.message}`);
  });
} catch (exception) {
  console.error(`Failed to set the sub window supports multi-screen simultaneous display. Cause code: ${exception.code}, message: ${exception.message}`);
}

setFollowParentWindowLayoutEnabled17+

setFollowParentWindowLayoutEnabled(enabled: boolean): Promise<void>

设置子窗或模态窗口(即WindowType为TYPE_DIALOG的窗口)的布局信息(position和size)是否跟随主窗,使用Promise异步回调。

1、只支持主窗的一级子窗或模态窗口使用该接口。

2、当子窗或模态窗口调用该接口后,立即使其布局信息与主窗完全一致并保持,除非传入false再次调用该接口,否则效果将持续。

3、当子窗或模态窗口调用该接口后,再调用moveTo、resize等修改布局信息的接口将不生效。

4、当子窗或模态窗口不再使用该功能后,不保证子窗或模态窗口的布局信息(position和size)为确定的值,需要应用重新进行设置。

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

原子化服务API: 从API version 17开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
enabled boolean 设置是否启用跟随主窗布局。true表示启用,false表示不启用。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage): void {
    windowStage.loadContent('pages/Index', (loadError: BusinessError) => {
      if (loadError.code) {
        console.error(`Failed to load the content. Cause code: ${loadError.code}, message: ${loadError.message}`);
        return;
      }
      console.info("Succeeded in loading the content.");
      windowStage.createSubWindow("subWindow").then((subWindow: window.Window) => {
        if (subWindow === null) {
          console.error("Failed to create the subWindow. Cause: The data is empty");
          return;
        }
        subWindow.setFollowParentWindowLayoutEnabled(true).then(() => {
          console.info("after set follow parent window layout")
        }).catch((error: BusinessError) => {
          console.error(`setFollowParentWindowLayoutEnabled failed. ${error.code} ${error.message}`);
        })
      }).catch((error: BusinessError) => {
        console.error(`createSubWindow failed. ${error.code} ${error.message}`);
      })
    });
  }
}

setWindowSystemBarProperties(deprecated)

setWindowSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback<void>): void

设置主窗口三键导航栏、状态栏的属性,使用callback异步回调,该接口在2in1设备上调用不生效。

子窗口调用后不生效。

说明:

从API version 9开始支持,从API version 12开始废弃,推荐使用Promise方式的setWindowSystemBarProperties

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
systemBarProperties SystemBarProperties 三键导航栏、状态栏的属性。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let SystemBarProperties: window.SystemBarProperties = {
        statusBarColor: '#ff00ff',
        navigationBarColor: '#00ff00',
        //以下两个属性从API Version8开始支持
        statusBarContentColor: '#ffffff',
        navigationBarContentColor: '#00ffff'
      };
      try {
        windowClass.setWindowSystemBarProperties(SystemBarProperties, (err: BusinessError) => {
          const errCode: number = err.code;
          if (errCode) {
            console.error(`Failed to set the system bar properties. Cause code: ${err.code}, message: ${err.message}`);
            return;
          }
          console.info('Succeeded in setting the system bar properties.');
        });
      } catch (exception) {
        console.error(`Failed to set the system bar properties. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setSubWindowZLevel18+

setSubWindowZLevel(zLevel: number): Promise<void>

设置当前子窗口层级级别,设置了模态属性的子窗不支持。使用Promise异步回调。

通过该接口改变子窗口的显示层级时,不会发生焦点切换。推荐使用shiftAppWindowFocus()进行焦点切换。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
zLevel number 子窗口层级级别。默认值为0,取值范围为[-10000, 10000],该参数仅支持整数输入,浮点数输入将向下取整。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Function setSubWindowZLevel can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.
1300004 Unauthorized operation.
1300009 The parent window is invalid.

示例:

// EntryAbility.ets
import { window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    // 创建子窗
    try {
      let subWindowPromise = windowStage.createSubWindow('testSubWindow');
      subWindowPromise.then((subWindow) => {
        if (subWindow == null) {
          console.error('Failed to create the sub window. Cause: The sub window is null');
          return;
        }
        let zLevelPromise = subWindow.setSubWindowZLevel(1);
        zLevelPromise.then(() => {
          console.info('Succeeded in setting sub window zLevel.');
        }).catch((err: BusinessError) => {
          console.error(`Failed to set sub window zLevel. Cause code: ${err.code}, message: ${err.message}`);
        });
      });
    } catch (err) {
      console.error(`Failed to create the sub window. Cause code: ${err.code}, message: ${err.message}`);
    }
  }
}

getSubWindowZLevel18+

getSubWindowZLevel(): number

获取当前子窗口层级级别。不支持主窗、系统窗调用。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
number 当前子窗口层级级别。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Function getSubWindowZLevel can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.
1300004 Unauthorized operation.

示例:

// EntryAbility.ets
import { window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    // 创建子窗
    try {
      let subWindowPromise = windowStage.createSubWindow('testSubWindow');
      subWindowPromise.then((subWindow) => {
        if (subWindow == null) {
          console.error('Failed to create the sub window. Cause: The sub window is null');
          return;
        }
        try {
          let subWindowZLevel = subWindow.getSubWindowZLevel();
          console.info(`Succeeded in getting sub window zLevel: ${subWindowZLevel}`);
        } catch (err) {
          console.error(`Failed to get sub window zLevel. Cause code: ${err.code}, message: ${err.message}`);
        }
      });
    } catch (err) {
      console.error(`Failed to create the sub window. Cause code: ${err.code}, message: ${err.message}`);
    }
  }
}

setWindowSystemBarEnable(deprecated)

setWindowSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallback<void>): void

设置主窗口状态栏、三键导航栏的可见模式,状态栏通过status控制、三键导航栏通过navigation控制,使用callback异步回调。
从API version 12开始,该接口在2in1设备上调用不生效。

调用生效后返回并不表示状态栏和三键导航栏的显示或隐藏已完成。子窗口调用后不生效。非全屏模式(悬浮窗、分屏等场景)下配置不生效。

说明:

从API version 9开始支持,从API version 12开始废弃,推荐使用Promise方式的setWindowSystemBarEnable

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
names Array<'status'|'navigation'> 设置窗口全屏模式时状态栏和三键导航栏是否显示。
例如,需全部显示,该参数设置为['status', 'navigation'];设置为[],则不显示。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// 此处以状态栏等均不显示为例
// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let names: Array<'status' | 'navigation'> = [];
      try {
        windowClass.setWindowSystemBarEnable(names, (err: BusinessError) => {
          const errCode: number = err.code;
          if (errCode) {
            console.error(`Failed to set the system bar to be invisible. Cause code: ${err.code}, message: ${err.message}`);
            return;
          }
          console.info('Succeeded in setting the system bar to be invisible.');
        });
      } catch (exception) {
        console.error(`Failed to set the system bar to be invisible. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

setWindowLayoutFullScreen(deprecated)

setWindowLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void

设置主窗口或子窗口的布局是否为沉浸式布局,使用callback异步回调。系统窗口调用不生效。 沉浸式布局生效时,布局不避让状态栏与三键导航栏,组件可能产生与其重叠的情况。 非沉浸式布局生效时,布局避让状态栏与三键导航栏,组件不会与其重叠。

说明:

从API version 9开始支持,从API version 12开始废弃,推荐使用Promise方式的setWindowLayoutFullScreen

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
isLayoutFullScreen boolean 窗口的布局是否为沉浸式布局(该沉浸式布局状态栏、三键导航栏仍然显示)。true表示沉浸式布局;false表示非沉浸式布局。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let isLayoutFullScreen = true;
      try {
        windowClass.setWindowLayoutFullScreen(isLayoutFullScreen, (err: BusinessError) => {
          const errCode: number = err.code;
          if (errCode) {
            console.error(`Failed to set the window layout to full-screen mode. Cause code: ${err.code}, message: ${err.message}`);
            return;
          }
          console.info('Succeeded in setting the window layout to full-screen mode.');
        });
      } catch (exception) {
        console.error(`Failed to set the window layout to full-screen mode. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
}

show(deprecated)

show(callback: AsyncCallback<void>): void

显示当前窗口,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用showWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<void> 回调函数。

示例:

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

windowClass.show((err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to show the window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in showing the window.');
});

show(deprecated)

show(): Promise<void>

显示当前窗口,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用showWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

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

示例:

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

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

destroy(deprecated)

destroy(callback: AsyncCallback<void>): void

销毁当前窗口,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用destroyWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<void> 回调函数。

示例:

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

windowClass.destroy((err: BusinessError) => {
  const errCode: number = err.code;
  if (err.code) {
    console.error(`Failed to destroy the window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in destroying the window.');
});

destroy(deprecated)

destroy(): Promise<void>

销毁当前窗口,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用destroyWindow()

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

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

示例:

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

let promise = windowClass.destroy();
promise.then(() => {
  console.info('Succeeded in destroying the window.');
}).catch((err: BusinessError) => {
  console.error(`Failed to destroy the window. Cause code: ${err.code}, message: ${err.message}`);
});

moveTo(deprecated)

moveTo(x: number, y: number, callback: AsyncCallback<void>): void

移动窗口位置,使用callback异步回调。

全屏模式窗口不支持该操作。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用moveWindowTo()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
x number 窗口在x轴方向移动到的坐标位置,单位为px,值为正表示位置在x轴右侧;值为负表示位置在x轴左侧;值为0表示位置在x轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。
y number 窗口在y轴方向移动到的坐标位置,单位为px,值为正表示位置在y轴下侧;值为负表示位置在y轴上侧;值为0表示位置在x轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。
callback AsyncCallback<void> 回调函数。

示例:

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

windowClass.moveTo(300, 300, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to move the window. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in moving the window.');
});

moveTo(deprecated)

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

移动窗口位置,使用Promise异步回调。

全屏模式窗口不支持该操作。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用moveWindowTo()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
x number 窗口在x轴方向移动到的坐标位置,单位为px,值为正表示位置在x轴右侧;值为负表示位置在x轴左侧;值为0表示位置在x轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。
y number 窗口在y轴方向移动到的坐标位置,单位为px,值为正表示位置在y轴下侧;值为负表示位置在y轴上侧;值为0表示位置在y轴坐标原点。该参数仅支持整数输入,浮点数输入将向下取整。

返回值:

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

示例:

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

let promise = windowClass.moveTo(300, 300);
promise.then(() => {
  console.info('Succeeded in moving the window.');
}).catch((err: BusinessError) => {
  console.error(`Failed to move the window. Cause code: ${err.code}, message: ${err.message}`);
});

resetSize(deprecated)

resetSize(width: number, height: number, callback: AsyncCallback<void>): void

改变当前窗口大小,使用callback异步回调。

应用主窗口与子窗口存在大小限制,默认宽度范围:[320, 1920],默认高度范围:[240, 1920],单位为vp。 应用主窗口与子窗口的最小宽度与最小高度可由产品端进行配置,配置后的最小宽度与最小高度以产品段配置值为准,具体尺寸限制范围可以通过getWindowLimits接口进行查询。

系统窗口存在大小限制,宽度范围:(0, 1920],高度范围:(0, 1920],单位为vp。

设置的宽度与高度受到此约束限制,规则: 若所设置的窗口宽/高尺寸小于窗口最小宽/高限值,则窗口最小宽/高限值生效; 若所设置的窗口宽/高尺寸大于窗口最大宽/高限值,则窗口最大宽/高限值生效。

全屏模式窗口不支持该操作。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用resize()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
width number 目标窗口的宽度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。
height number 目标窗口的高度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。
callback AsyncCallback<void> 回调函数。

示例:

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

windowClass.resetSize(500, 1000, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to change the window size. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in changing the window size.');
});

resetSize(deprecated)

resetSize(width: number, height: number): Promise<void>

改变当前窗口大小,使用Promise异步回调。

应用主窗口与子窗口存在大小限制,默认宽度范围:[320, 1920],默认高度范围:[240, 1920],单位为vp。 应用主窗口与子窗口的最小宽度与最小高度可由产品端进行配置,配置后的最小宽度与最小高度以产品段配置值为准,具体尺寸限制范围可以通过getWindowLimits接口进行查询。

系统窗口存在大小限制,宽度范围:(0, 1920],高度范围:(0, 1920],单位为vp。

设置的宽度与高度受到此约束限制,规则: 若所设置的窗口宽/高尺寸小于窗口最小宽/高限值,则窗口最小宽/高限值生效; 若所设置的窗口宽/高尺寸大于窗口最大宽/高限值,则窗口最大宽/高限值生效。

全屏模式窗口不支持该操作。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用resize()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
width number 目标窗口的宽度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。
height number 目标窗口的高度,单位为px,该参数仅支持整数输入,浮点数输入将向下取整,负值为非法参数。

返回值:

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

示例:

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

let promise = windowClass.resetSize(500, 1000);
promise.then(() => {
  console.info('Succeeded in changing the window size.');
}).catch((err: BusinessError) => {
  console.error(`Failed to change the window size. Cause code: ${err.code}, message: ${err.message}`);
});

getProperties(deprecated)

getProperties(callback: AsyncCallback<WindowProperties>): void

获取当前窗口的属性,使用callback异步回调,返回WindowProperties。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用getWindowProperties()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<WindowProperties> 回调函数。返回当前窗口属性。

示例:

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

windowClass.getProperties((err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to obtain the window properties. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data));
});

getProperties(deprecated)

getProperties(): Promise<WindowProperties>

获取当前窗口的属性,使用Promise异步回调,返回WindowProperties。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用getWindowProperties()

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

类型 说明
Promise<WindowProperties> Promise对象。返回当前窗口属性。

示例:

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

let promise = windowClass.getProperties();
promise.then((data) => {
  console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error(`Failed to obtain the window properties. Cause code: ${err.code}, message: ${err.message}`);
});

getAvoidArea(deprecated)

getAvoidArea(type: AvoidAreaType, callback: AsyncCallback<AvoidArea>): void

获取当前窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用getWindowAvoidArea()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type AvoidAreaType 表示规避区类型。
callback AsyncCallback<AvoidArea> 回调函数。返回窗口内容规避区域。

示例:

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

let type = window.AvoidAreaType.TYPE_SYSTEM;
windowClass.getAvoidArea(type, (err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to obtain the area. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data));
});

getAvoidArea(deprecated)

getAvoidArea(type: AvoidAreaType): Promise<AvoidArea>

获取当前窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用getWindowAvoidArea()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type AvoidAreaType 表示规避区类型。

返回值:

类型 说明
Promise<AvoidArea> Promise对象。返回窗口内容规避区域。

示例:

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

let type = window.AvoidAreaType.TYPE_SYSTEM;
let promise = windowClass.getAvoidArea(type);
promise.then((data) => {
  console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error(`Failed to obtain the area. Cause code: ${err.code}, message: ${err.message}`);
});

setFullScreen(deprecated)

setFullScreen(isFullScreen: boolean, callback: AsyncCallback<void>): void

设置主窗口或子窗口的布局是否为全屏布局,使用callback异步回调。 全屏布局生效时,布局不避让状态栏与三键导航栏,组件可能产生与其重叠的情况。 非全屏布局生效时,布局避让状态栏与三键导航栏,组件不会与其重叠。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐联合使用setWindowSystemBarEnable()setWindowLayoutFullScreen()实现全屏。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isFullScreen boolean 是否设为全屏布局(该全屏布局影响状态栏、三键导航栏显示)。true表示全屏;false表示非全屏。
callback AsyncCallback<void> 回调函数。

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let isFullScreen: boolean = true;
      windowClass.setFullScreen(isFullScreen, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to enable the full-screen mode. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in enabling the full-screen mode.');
      });
    });
  }
}

setFullScreen(deprecated)

setFullScreen(isFullScreen: boolean): Promise<void>

设置主窗口或子窗口的布局是否为全屏布局,使用Promise异步回调。 全屏布局生效时,布局不避让状态栏与三键导航栏,组件可能产生与其重叠的情况。 非全屏布局生效时,布局避让状态栏与三键导航栏,组件不会与其重叠。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐联合使用setWindowSystemBarEnable()setWindowLayoutFullScreen()实现全屏。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isFullScreen boolean 是否设为全屏布局(该全屏布局影响状态栏、三键导航栏显示)。true表示全屏;false表示非全屏。

返回值:

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

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let isFullScreen: boolean = true;
      let promise = windowClass.setFullScreen(isFullScreen);
      promise.then(() => {
        console.info('Succeeded in enabling the full-screen mode.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to enable the full-screen mode. Cause code: ${err.code}, message: ${err.message}`);
      });
    });
  }
}

setLayoutFullScreen(deprecated)

setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void

设置主窗口或子窗口的布局是否为沉浸式布局,使用callback异步回调。 沉浸式布局生效时,布局不避让状态栏与三键导航栏,组件可能产生与其重叠的情况。 非沉浸式布局生效时,布局避让状态栏与三键导航栏,组件不会与其重叠。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowLayoutFullScreen()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isLayoutFullScreen boolean 窗口的布局是否为沉浸式布局(该沉浸式布局不影响状态栏、三键导航栏显示)。true表示沉浸式布局;false表示非沉浸式布局。
callback AsyncCallback<void> 回调函数。

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let isLayoutFullScreen: boolean = true;
      windowClass.setLayoutFullScreen(isLayoutFullScreen, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to set the window layout to full-screen mode. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in setting the window layout to full-screen mode.');
      });
    });
  }
}

setLayoutFullScreen(deprecated)

setLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void>

设置主窗口或子窗口的布局是否为沉浸式布局,使用Promise异步回调。 沉浸式布局生效时,布局不避让状态栏与三键导航栏,组件可能产生与其重叠的情况。 非沉浸式布局生效时,布局避让状态栏与三键导航栏,组件不会与其重叠。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowLayoutFullScreen()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isLayoutFullScreen boolean 窗口的布局是否为沉浸式布局(该沉浸式布局不影响状态栏、三键导航栏显示)。true表示沉浸式布局;false表示非沉浸式布局。

返回值:

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

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let isLayoutFullScreen: boolean = true;
      let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen);
      promise.then(() => {
        console.info('Succeeded in setting the window layout to full-screen mode.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set the window layout to full-screen mode. Cause code: ${err.code}, message: ${err.message}`);
      });
    });
  }
}

setSystemBarEnable(deprecated)

setSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallback<void>): void

设置主窗口状态栏、三键导航栏的可见模式,状态栏通过status控制、三键导航栏通过navigation控制,使用callback异步回调。
从API version 12开始,该接口在2in1设备上调用不生效。

调用生效后返回并不表示状态栏和三键导航栏的显示或隐藏已完成。子窗口调用后不生效。非全屏模式(悬浮窗、分屏等场景)下配置不生效。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowSystemBarEnable()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
names Array<'status'|'navigation'> 设置窗口全屏模式时状态栏和三键导航栏是否显示。
例如,需全部显示,该参数设置为['status', 'navigation'];设置为[],则不显示。
callback AsyncCallback<void> 回调函数。

示例:

// 此处以状态栏等均不显示为例
// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let names: Array<'status' | 'navigation'> = [];
      windowClass.setSystemBarEnable(names, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to set the system bar to be invisible. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in setting the system bar to be invisible.');
      });
    });
  }
}

setSystemBarEnable(deprecated)

setSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void>

设置主窗口状态栏、三键导航栏的可见模式,状态栏通过status控制、三键导航栏通过navigation控制,使用Promise异步回调。
从API version 12开始,该接口在2in1设备上调用不生效。

调用生效后返回并不表示状态栏和三键导航栏的显示或隐藏已完成。子窗口调用后不生效。非全屏模式(悬浮窗、分屏等场景)下配置不生效。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowSystemBarEnable()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
names Array<'status'|'navigation'> 设置窗口全屏模式时状态栏和三键导航栏是否显示。
例如,需全部显示,该参数设置为['status', 'navigation'];设置为[],则不显示。

返回值:

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

示例:

// 此处以状态栏等均不显示为例
// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let names: Array<'status' | 'navigation'> = [];
      let promise = windowClass.setSystemBarEnable(names);
      promise.then(() => {
        console.info('Succeeded in setting the system bar to be invisible.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set the system bar to be invisible. Cause code: ${err.code}, message: ${err.message}`);
      });
    });
  }
}

setSystemBarProperties(deprecated)

setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback<void>): void

设置主窗口三键导航栏、状态栏的属性,使用callback异步回调,该接口在2in1设备上调用不生效。

子窗口调用后不生效。非全屏模式(悬浮窗、分屏等场景)下配置不生效。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用setWindowSystemBarProperties()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
systemBarProperties SystemBarProperties 三键导航栏、状态栏的属性。
callback AsyncCallback<void> 回调函数。

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let SystemBarProperties: window.SystemBarProperties = {
        statusBarColor: '#ff00ff',
        navigationBarColor: '#00ff00',
        //以下两个属性从API Version8开始支持
        statusBarContentColor: '#ffffff',
        navigationBarContentColor: '#00ffff'
      };
      windowClass.setSystemBarProperties(SystemBarProperties, (err) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to set the system bar properties. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in setting the system bar properties.');
      });
    });
  }
}

setSystemBarProperties(deprecated)

setSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<void>

设置主窗口三键导航栏、状态栏的属性,使用Promise异步回调,该接口在2in1设备上调用不生效。

子窗口调用后不生效。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用setWindowSystemBarProperties()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
systemBarProperties SystemBarProperties 三键导航栏、状态栏的属性。

返回值:

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

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      let SystemBarProperties: window.SystemBarProperties = {
        statusBarColor: '#ff00ff',
        navigationBarColor: '#00ff00',
        //以下两个属性从API Version8开始支持
        statusBarContentColor: '#ffffff',
        navigationBarContentColor: '#00ffff'
      };
      let promise = windowClass.setSystemBarProperties(SystemBarProperties);
      promise.then(() => {
        console.info('Succeeded in setting the system bar properties.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set the system bar properties. Cause code: ${err.code}, message: ${err.message}`);
      });
    });
  }
}

loadContent(deprecated)

loadContent(path: string, callback: AsyncCallback<void>): void

为当前窗口加载具体页面内容,使用callback异步回调。建议在UIAbility启动过程中使用该接口,多次调用该接口会先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setUIContent()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,Stage模型下该路径需添加到工程的main_pages.json文件中,FA模型下该路径需添加到工程的config.json文件中。
callback AsyncCallback<void> 回调函数。

示例:

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

windowClass.loadContent('pages/page2/page3', (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in loading the content.');
});

loadContent(deprecated)

loadContent(path: string): Promise<void>

为当前窗口加载具体页面内容,使用Promise异步回调。建议在UIAbility启动过程中使用该接口,多次调用该接口会先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setUIContent()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,Stage模型下该路径需添加到工程的main_pages.json文件中,FA模型下该路径需添加到工程的config.json文件中。

返回值:

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

示例:

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

let promise = windowClass.loadContent('pages/page2/page3');
promise.then(() => {
  console.info('Succeeded in loading the content.');
}).catch((err: BusinessError) => {
  console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
});

isShowing(deprecated)

isShowing(callback: AsyncCallback<boolean>): void

判断当前窗口是否已显示,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用isWindowShowing()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<boolean> 回调函数。返回true表示当前窗口已显示,返回false表示当前窗口未显示。

示例:

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

windowClass.isShowing((err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to check whether the window is showing. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data));
});

isShowing(deprecated)

isShowing(): Promise<boolean>

判断当前窗口是否已显示,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用isWindowShowing()

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

类型 说明
Promise<boolean> Promise对象。返回true表示当前窗口已显示,返回false表示当前窗口未显示。

示例:

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

let promise = windowClass.isShowing();
promise.then((data) => {
  console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error(`Failed to check whether the window is showing. Cause code: ${err.code}, message: ${err.message}`);
});

on('systemAvoidAreaChange')(deprecated)

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

开启当前窗口系统规避区变化的监听。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用on('avoidAreaChange')

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'systemAvoidAreaChange',即系统规避区变化事件。
callback Callback<AvoidArea> 回调函数。返回当前规避区。

示例:

windowClass.on('systemAvoidAreaChange', (data) => {
  console.info('Succeeded in enabling the listener for system avoid area changes. Data: ' + JSON.stringify(data));
});

off('systemAvoidAreaChange')(deprecated)

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

关闭当前窗口系统规避区变化的监听。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用off('avoidAreaChange')

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
type string 监听事件,固定为'systemAvoidAreaChange',即系统规避区变化事件。
callback Callback<AvoidArea> 回调函数。返回当前规避区。若传入参数,则关闭该监听。若未传入参数,则关闭所有系统规避区变化的监听。

示例:

const callback = (avoidArea: window.AvoidArea) => {
  // ...
}
windowClass.on('systemAvoidAreaChange', callback);
windowClass.off('systemAvoidAreaChange', callback);
// 如果通过on开启多个callback进行监听,同时关闭所有监听:
windowClass.off('systemAvoidAreaChange');

isSupportWideGamut(deprecated)

isSupportWideGamut(callback: AsyncCallback<boolean>): void

判断当前窗口是否支持广色域模式,使用callback异步回调。

说明:

从API version 8开始支持,从API version 9开始废弃,推荐使用isWindowSupportWideGamut()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<boolean> 回调函数。返回true表示当前窗口支持广色域模式,返回false表示当前窗口不支持广色域模式。

示例:

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

windowClass.isSupportWideGamut((err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to check whether the window support WideGamut. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data));
});

isSupportWideGamut(deprecated)

isSupportWideGamut(): Promise<boolean>

判断当前窗口是否支持广色域模式,使用Promise异步回调。

说明:

从API version 8开始支持,从API version 9开始废弃,推荐使用isWindowSupportWideGamut()

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

类型 说明
Promise<boolean> Promise对象。返回true表示当前窗口支持广色域模式,返回false表示当前窗口不支持广色域模式。

示例:

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

let promise = windowClass.isSupportWideGamut();
promise.then((data) => {
  console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error(`Failed to check whether the window support WideGamut. Cause code: ${err.code}, message: ${err.message}`);
});

setColorSpace(deprecated)

setColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void

设置当前窗口为广色域模式或默认色域模式,使用callback异步回调。

说明:

从API version 8开始支持,从API version 9开始废弃,推荐使用setWindowColorSpace()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
colorSpace ColorSpace 设置色域模式。
callback AsyncCallback<void> 回调函数。

示例:

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

windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set window colorspace. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting window colorspace.');
});

setColorSpace(deprecated)

setColorSpace(colorSpace:ColorSpace): Promise<void>

设置当前窗口为广色域模式或默认色域模式,使用Promise异步回调。

说明:

从API version 8开始支持,从API version 9开始废弃,推荐使用setWindowColorSpace()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
colorSpace ColorSpace 设置色域模式。

返回值:

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

示例:

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

let promise = windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT);
promise.then(() => {
  console.info('Succeeded in setting window colorspace.');
}).catch((err: BusinessError) => {
  console.error(`Failed to set window colorspace. Cause code: ${err.code}, message: ${err.message}`);
});

getColorSpace(deprecated)

getColorSpace(callback: AsyncCallback<ColorSpace>): void

获取当前窗口色域模式,使用callback异步回调。

说明:

从API version 8开始支持,从API version 9开始废弃,推荐使用getWindowColorSpace()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
callback AsyncCallback<ColorSpace> 回调函数。当获取成功,err为undefined,data为当前色域模式。

示例:

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

windowClass.getColorSpace((err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to get window colorspace. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data));
});

getColorSpace(deprecated)

getColorSpace(): Promise<ColorSpace>

获取当前窗口色域模式,使用Promise异步回调。

说明:

从API version 8开始支持,从API version 9开始废弃,推荐使用getWindowColorSpace()

系统能力: SystemCapability.WindowManager.WindowManager.Core

返回值:

类型 说明
Promise<ColorSpace> Promise对象。返回当前色域模式。

示例:

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

let promise = windowClass.getColorSpace();
promise.then((data) => {
  console.info('Succeeded in getting window color space. Cause:' + JSON.stringify(data));
}).catch((err: BusinessError) => {
  console.error(`Failed to get window colorspace. Cause code: ${err.code}, message: ${err.message}`);
});

setBackgroundColor(deprecated)

setBackgroundColor(color: string, callback: AsyncCallback<void>): void

设置窗口的背景色,使用callback异步回调。Stage模型下,该接口需要在loadContent()setUIContent()调用生效后使用。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用setWindowBackgroundColor()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
color string 需要设置的背景色,为十六进制RGB或ARGB颜色,不区分大小写,例如'#00FF00''#FF00FF00'
callback AsyncCallback<void> 回调函数。

示例:

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

let color: string = '#00ff33';
windowClass.setBackgroundColor(color, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set the background color. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting the background color.');
});

setBackgroundColor(deprecated)

setBackgroundColor(color: string): Promise<void>

设置窗口的背景色,使用Promise异步回调。Stage模型下,该接口需要在loadContent()setUIContent()调用生效后使用。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用setWindowBackgroundColor()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
color string 需要设置的背景色,为十六进制RGB或ARGB颜色,不区分大小写,例如'#00FF00''#FF00FF00'

返回值:

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

示例:

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

let color: string = '#00ff33';
let promise = windowClass.setBackgroundColor(color);
promise.then(() => {
  console.info('Succeeded in setting the background color.');
}).catch((err: BusinessError) => {
  console.error(`Failed to set the background color. Cause code: ${err.code}, message: ${err.message}`);
});

setBrightness(deprecated)

setBrightness(brightness: number, callback: AsyncCallback<void>): void

允许应用窗口设置屏幕亮度值,使用callback异步回调。

当前屏幕亮度规格:窗口设置屏幕亮度生效时,控制中心不可以调整系统屏幕亮度,窗口恢复默认系统亮度之后,控制中心可以调整系统屏幕亮度。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用setWindowBrightness()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
brightness number 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。
callback AsyncCallback<void> 回调函数。

示例:

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

let brightness: number = 1;
windowClass.setBrightness(brightness, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set the brightness. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting the brightness.');
});

setBrightness(deprecated)

setBrightness(brightness: number): Promise<void>

允许应用窗口设置屏幕亮度值,使用Promise异步回调。

当前屏幕亮度规格:窗口设置屏幕亮度生效时,控制中心不可以调整系统屏幕亮度,窗口恢复默认系统亮度之后,控制中心可以调整系统屏幕亮度。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用setWindowBrightness()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
brightness number 屏幕亮度值。该参数为浮点数,取值范围为[0.0, 1.0]或-1.0。1.0表示最亮,-1.0表示默认亮度。

返回值:

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

示例:

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

let brightness: number = 1;
let promise = windowClass.setBrightness(brightness);
promise.then(() => {
  console.info('Succeeded in setting the brightness.');
}).catch((err: BusinessError) => {
  console.error(`Failed to set the brightness. Cause code: ${err.code}, message: ${err.message}`);
});

setDimBehind(deprecated)

setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void

窗口叠加时,设备有子窗口的情况下设置靠后的窗口的暗度值,使用callback异步回调。

说明:

该接口不支持使用。从API version 7开始支持,从API version 9开始废弃。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
dimBehindValue number 表示靠后的窗口的暗度值,取值范围为[0.0, 1.0],取1.0时表示最暗。
callback AsyncCallback<void> 回调函数。

示例:

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

windowClass.setDimBehind(0.5, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set the dimness. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting the dimness.');
});

setDimBehind(deprecated)

setDimBehind(dimBehindValue: number): Promise<void>

窗口叠加时,设备有子窗口的情况下设置靠后的窗口的暗度值,使用Promise异步回调。

说明:

该接口不支持使用。从API version 7开始支持,从API version 9开始废弃。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
dimBehindValue number 表示靠后的窗口的暗度值,取值范围为0-1,1表示最暗。

返回值:

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

示例:

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

let promise = windowClass.setDimBehind(0.5);
promise.then(() => {
  console.info('Succeeded in setting the dimness.');
}).catch((err: BusinessError) => {
  console.error(`Failed to set the dimness. Cause code: ${err.code}, message: ${err.message}`);
});

setFocusable(deprecated)

setFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void

设置使用点击或其他方式使该窗口获焦的场景时,该窗口是否支持窗口焦点从操作前的获焦窗口切换到该窗口,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowFocusable()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isFocusable boolean 点击时是否支持切换焦点窗口。true表示支持;false表示不支持。
callback AsyncCallback<void> 回调函数。

示例:

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

let isFocusable: boolean = true;
windowClass.setFocusable(isFocusable, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set the window to be focusable. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting the window to be focusable.');
});

setFocusable(deprecated)

setFocusable(isFocusable: boolean): Promise<void>

设置使用点击或其他方式使该窗口获焦的场景时,该窗口是否支持窗口焦点从点击前的获焦窗口切换到该窗口,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowFocusable()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isFocusable boolean 点击时是否支持切换焦点窗口。true表示支持;false表示不支持。

返回值:

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

示例:

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

let isFocusable: boolean = true;
let promise = windowClass.setFocusable(isFocusable);
promise.then(() => {
  console.info('Succeeded in setting the window to be focusable.');
}).catch((err: BusinessError) => {
  console.error(`Failed to set the window to be focusable. Cause code: ${err.code}, message: ${err.message}`);
});

setKeepScreenOn(deprecated)

setKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void

设置屏幕是否为常亮状态,使用callback异步回调。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用setWindowKeepScreenOn()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isKeepScreenOn boolean 设置屏幕是否为常亮状态。true表示常亮;false表示不常亮。
callback AsyncCallback<void> 回调函数。

示例:

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

let isKeepScreenOn: boolean = true;
windowClass.setKeepScreenOn(isKeepScreenOn, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set the screen to be always on. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting the screen to be always on.');
});

setKeepScreenOn(deprecated)

setKeepScreenOn(isKeepScreenOn: boolean): Promise<void>

设置屏幕是否为常亮状态,使用Promise异步回调。

说明:

从API version 6开始支持,从API version 9开始废弃,推荐使用setWindowKeepScreenOn()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isKeepScreenOn boolean 设置屏幕是否为常亮状态。true表示常亮;false表示不常亮。

返回值:

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

示例:

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

let isKeepScreenOn: boolean = true;
let promise = windowClass.setKeepScreenOn(isKeepScreenOn);
promise.then(() => {
  console.info('Succeeded in setting the screen to be always on.');
}).catch((err: BusinessError) => {
  console.info(`Failed to set the screen to be always on. Cause code: ${err.code}, message: ${err.message}`);
});

setOutsideTouchable(deprecated)

setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): void

设置是否允许可点击子窗口之外的区域,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃。

从API version 9开始,系统默认允许点击子窗口之外的区域,此接口不再支持使用,也不再提供替代接口。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
touchable boolean 设置是否可点击。true表示可点击;false表示不可点击。
callback AsyncCallback<void> 回调函数。

示例:

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

windowClass.setOutsideTouchable(true, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set the area to be touchable. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting the area to be touchable.');
});

setOutsideTouchable(deprecated)

setOutsideTouchable(touchable: boolean): Promise<void>

设置是否允许可点击子窗口之外的区域,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃。

从API version 9开始,系统默认允许点击子窗口之外的区域,此接口不再支持使用,也不再提供替代接口。

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
touchable boolean 设置是否可点击。true表示可点击;false表示不可点击。

返回值:

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

示例:

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

let promise = windowClass.setOutsideTouchable(true);
promise.then(() => {
  console.info('Succeeded in setting the area to be touchable.');
}).catch((err: BusinessError) => {
  console.error(`Failed to set the area to be touchable. Cause code: ${err.code}, message: ${err.message}`);
});

setPrivacyMode(deprecated)

setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void

设置窗口是否为隐私模式,使用callback异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。此接口可用于禁止截屏/录屏的场景。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowPrivacyMode()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isPrivacyMode boolean 窗口是否为隐私模式。true表示模式开启;false表示模式关闭。
callback AsyncCallback<void> 回调函数。

示例:

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

let isPrivacyMode: boolean = true;
windowClass.setPrivacyMode(isPrivacyMode, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set the window to privacy mode. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting the window to privacy mode.');
});

setPrivacyMode(deprecated)

setPrivacyMode(isPrivacyMode: boolean): Promise<void>

设置窗口是否为隐私模式,使用Promise异步回调。设置为隐私模式的窗口,窗口内容将无法被截屏或录屏。此接口可用于禁止截屏/录屏的场景。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowPrivacyMode()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isPrivacyMode boolean 窗口是否为隐私模式。true表示模式开启;false表示模式关闭。

返回值:

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

示例:

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

let isPrivacyMode: boolean = true;
let promise = windowClass.setPrivacyMode(isPrivacyMode);
promise.then(() => {
  console.info('Succeeded in setting the window to privacy mode.');
}).catch((err: BusinessError) => {
  console.error(`Failed to set the window to privacy mode. Cause code: ${err.code}, message: ${err.message}`);
});

setTouchable(deprecated)

setTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void

设置窗口是否为可触状态,使用callback异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowTouchable()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isTouchable boolean 窗口是否为可触状态。true表示可触;false表示不可触。
callback AsyncCallback<void> 回调函数。

示例:

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

let isTouchable = true;
windowClass.setTouchable(isTouchable, (err: BusinessError) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error(`Failed to set the window to be touchable. Cause code: ${err.code}, message: ${err.message}`);
    return;
  }
  console.info('Succeeded in setting the window to be touchable.');
});

setTouchable(deprecated)

setTouchable(isTouchable: boolean): Promise<void>

设置窗口是否为可触状态,使用Promise异步回调。

说明:

从API version 7开始支持,从API version 9开始废弃,推荐使用setWindowTouchable()

系统能力: SystemCapability.WindowManager.WindowManager.Core

参数:

参数名 类型 必填 说明
isTouchable boolean 窗口是否为可触状态。true表示可触;false表示不可触。

返回值:

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

示例:

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

let isTouchable = true;
let promise = windowClass.setTouchable(isTouchable);
promise.then(() => {
  console.info('Succeeded in setting the window to be touchable.');
}).catch((err: BusinessError) => {
  console.error(`Failed to set the window to be touchable. Cause code: ${err.code}, message: ${err.message}`);
});

WindowStageEventType9+

WindowStage生命周期。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

名称 说明
SHOWN 1 切到前台,例如点击应用图标启动,无论是首次启动还是从后台启动均会触发。
ACTIVE 2 获焦状态,例如应用窗口处理点击事件后的状态、应用启动后的状态。
INACTIVE 3 失焦状态,例如打开新应用或点击其他窗口后,原获焦窗口的状态。
HIDDEN 4 切到后台,例如应用上滑退出、应用窗口关闭。
RESUMED11+ 5 前台可交互状态,例如应用打开后,可以与用户交互的状态。
PAUSED11+ 6 前台不可交互状态,例如从屏幕底部上划,应用进入到多任务界面后的状态。

ModalityType14+

子窗口模态类型枚举。

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

名称 说明
WINDOW_MODALITY 0 模态子窗类型为模窗口子窗,当仅需要其父级窗口不响应用户操作时,可选此参数。
APPLICATION_MODALITY 1 模态子窗类型为模应用子窗,除其父级窗口外还需要该应用其他实例的窗口不响应用户操作时,可选此参数。
此接口仅支持在2in1设备下使用。

SubWindowOptions11+

子窗口创建参数。

系统能力: SystemCapability.Window.SessionManager

名称 类型 只读 可选 说明
title11+ string 子窗口标题。标题显示区域最右端不超过系统三键区域最左端,超过部分以省略号表示。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
decorEnabled11+ boolean 子窗口是否显示装饰。true表示子窗口显示装饰,false表示子窗口不显示装饰。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
isModal12+ boolean 子窗口是否启用模态属性。true表示子窗口启用模态属性,false表示子窗口禁用模态属性。不设置,则默认为false。
原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。
modalityType14+ ModalityType 子窗口模态类型,仅当子窗口启用模态属性时生效。WINDOW_MODALITY表示子窗口模态类型为模窗口子窗,APPLICATION_MODALITY表示子窗口模态类型为模应用子窗。不设置,则默认为WINDOW_MODALITY。
原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。
windowRect18+ Rect 子窗口矩形区域,其中子窗存在大小限制,具体参考resize()方法。不设置,此窗口在显示时默认为全屏大小。
原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。
zLevel18+ number 子窗口层级级别,仅当子窗口未启用模态属性,即未设置isModal时生效。该参数是整数,取值范围为[-10000, 10000],浮点数输入将向下取整。不设置,则默认为0。
原子化服务API: 从API version 18开始,该接口支持在原子化服务中使用。
maximizeSupported19+ boolean 子窗口是否支持最大化特性。此接口仅可在2in1设备下使用。true表示子窗口支持最大化,false表示子窗口不支持最大化。不设置,则默认为false。
原子化服务API: 从API version 19开始,该接口支持在原子化服务中使用。

WindowStage9+

窗口管理器。管理各个基本窗口单元,即Window实例。

下列API示例中都需在onWindowStageCreate()函数中使用WindowStage的实例调用对应方法。

getMainWindow9+

getMainWindow(callback: AsyncCallback<Window>): void

获取该WindowStage实例下的主窗口,使用callback异步回调。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
callback AsyncCallback<Window> 回调函数。返回当前WindowStage下的主窗口对象。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
    });
  }
};

getMainWindow9+

getMainWindow(): Promise<Window>

获取该WindowStage实例下的主窗口,使用Promise异步回调。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前WindowStage下的主窗口对象。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    let promise = windowStage.getMainWindow();
    promise.then((data) => {
      windowClass = data;
      console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
    }).catch((err: BusinessError) => {
      console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
    });
  }
};

getMainWindowSync9+

getMainWindowSync(): Window

获取该WindowStage实例下的主窗口。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
Window 返回当前WindowStage下的主窗口对象。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    try {
      let windowClass = windowStage.getMainWindowSync();
    } catch (exception) {
      console.error(`Failed to obtain the main window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

createSubWindow9+

createSubWindow(name: string, callback: AsyncCallback<Window>): void

创建该WindowStage实例下的子窗口,使用callback异步回调。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 子窗口的名字。
callback AsyncCallback<Window> 回调函数。返回当前WindowStage下的子窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: Incorrect parameter types.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    try {
      windowStage.createSubWindow('mySubWindow', (err: BusinessError, data) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to create the subwindow. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        windowClass = data;
        console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
        if (!windowClass) {
          console.info('Failed to load the content. Cause: windowClass is null');
        }
        else {
          (windowClass as window.Window).resize(500, 1000);
        }
      });
    } catch (exception) {
      console.error(`Failed to create the subwindow. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

createSubWindow9+

createSubWindow(name: string): Promise<Window>

创建该WindowStage实例下的子窗口,使用Promise异步回调。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 子窗口的名字。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前WindowStage下的子窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: Incorrect parameter types.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    try {
      let promise = windowStage.createSubWindow('mySubWindow');
      promise.then((data) => {
        windowClass = data;
        console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
      }).catch((err: BusinessError) => {
        console.error(`Failed to create the subwindow. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to create the subwindow. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

createSubWindowWithOptions11+

createSubWindowWithOptions(name: string, options: SubWindowOptions): Promise<Window>

创建该WindowStage实例下的子窗口,使用Promise异步回调。

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

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
name string 子窗口的名字。
options SubWindowOptions 子窗口参数。

返回值:

类型 说明
Promise<Window> Promise对象。返回当前WindowStage下创建的子窗口对象。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window | undefined = undefined;
    try {
      let options : window.SubWindowOptions = {
        title: 'title',
        decorEnabled: true
      };
      let promise = windowStage.createSubWindowWithOptions('mySubWindow', options);
      promise.then((data) => {
        windowClass = data;
        console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
      }).catch((err: BusinessError) => {
        console.error(`Failed to create the subwindow. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to create the subwindow. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

getSubWindow9+

getSubWindow(callback: AsyncCallback<Array<Window>>): void

获取该WindowStage实例下的所有子窗口,使用callback异步回调。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
callback AsyncCallback<Array<Window>> 回调函数。返回当前WindowStage下的所有子窗口对象。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window[] = [];
    windowStage.getSubWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error(`Failed to obtain the subwindow. Cause code: ${err.code}, message: ${err.message}`);
        return;
      }
      windowClass = data;
      console.info('Succeeded in obtaining the subwindow. Data: ' + JSON.stringify(data));
    });
  }
};

getSubWindow9+

getSubWindow(): Promise<Array<Window>>

获取该WindowStage实例下的所有子窗口,使用Promise异步回调。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

返回值:

类型 说明
Promise<Array<Window>> Promise对象。返回当前WindowStage下的所有子窗口对象。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    let windowClass: window.Window[] = [];
    let promise = windowStage.getSubWindow();
    promise.then((data) => {
      windowClass = data;
      console.info('Succeeded in obtaining the subwindow. Data: ' + JSON.stringify(data));
    }).catch((err: BusinessError) => {
      console.error(`Failed to obtain the subwindow. Cause code: ${err.code}, message: ${err.message}`);
    });
  }
};

loadContent9+

loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void>): void

根据当前工程中指定的页面路径为WindowStage的主窗口加载具体页面内容,通过LocalStorage传递状态属性给加载的页面,使用callback异步回调。建议在UIAbility启动过程中调用该接口,重复调用将首先销毁旧的页面内容(即UIContent)再加载新页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,该路径需添加到工程的main_pages.json文件中。
storage LocalStorage 页面级UI状态存储单元,这里用于为加载到窗口的页面内容传递状态属性。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  storage: LocalStorage = new LocalStorage();

  onWindowStageCreate(windowStage: window.WindowStage) {
    this.storage.setOrCreate('storageSimpleProp', 121);
    console.info('onWindowStageCreate');
    try {
      windowStage.loadContent('pages/page2', this.storage, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in loading the content.');
      });
    } catch (exception) {
      console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

loadContent9+

loadContent(path: string, storage?: LocalStorage): Promise<void>

根据当前工程中指定的页面路径为WindowStage的主窗口加载具体页面内容,通过LocalStorage传递状态属性给加载的页面,使用Promise异步回调。建议在UIAbility启动过程中调用该接口,重复调用将首先销毁旧的页面内容(即UIContent)再加载新页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,该路径需添加到工程的main_pages.json文件中。
storage LocalStorage 页面级UI状态存储单元,这里用于为加载到窗口的页面内容传递状态属性。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  storage: LocalStorage = new LocalStorage();

  onWindowStageCreate(windowStage: window.WindowStage) {
    this.storage.setOrCreate('storageSimpleProp', 121);
    console.info('onWindowStageCreate');
    try {
      let promise = windowStage.loadContent('pages/page2', this.storage);
      promise.then(() => {
        console.info('Succeeded in loading the content.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
    }
    ;
  }
};

loadContent9+

loadContent(path: string, callback: AsyncCallback<void>): void

根据当前工程中指定的页面路径为WindowStage的主窗口加载具体页面内容,使用callback异步回调。建议在UIAbility启动过程中调用该接口,重复调用将首先销毁旧的页面内容(即UIContent)再加载新页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
path string 要加载到窗口中的页面内容的路径,该路径需添加到工程的main_pages.json文件中。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    try {
      windowStage.loadContent('pages/page2', (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in loading the content.');
      });
    } catch (exception) {
      console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

loadContentByName11+

loadContentByName(name: string, storage: LocalStorage, callback: AsyncCallback<void>): void

根据指定路由页面名称为当前WindowStage加载命名路由页面,通过LocalStorage传递状态属性至加载页面,使用callback异步回调。建议在UIAbility启动过程中使用该接口,重复调用该接口将先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 命名路由页面的名称。
storage LocalStorage 页面级UI状态存储单元,这里用于为加载到窗口的页面内容传递状态属性。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import * as Index from '../pages/Index'; // 导入命名路由页面

export default class EntryAbility extends UIAbility {
  // ...

  storage: LocalStorage = new LocalStorage();

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    this.storage.setOrCreate('storageSimpleProp', 121);
    try {
      windowStage.loadContentByName(Index.entryName, this.storage, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in loading the content.');
      });
    } catch (exception) {
      console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};
// ets/pages/Index.ets
export const entryName : string = 'Index';
@Entry({routeName: entryName, useSharedStorage: true})
@Component
export struct Index {
  @State message: string = 'Hello World'
  @LocalStorageLink('storageSimpleProp') storageSimpleProp: number = 1;
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

loadContentByName11+

loadContentByName(name: string, callback: AsyncCallback<void>): void

根据指定路由页面名称为当前WindowStage加载命名路由页面,使用callback异步回调。建议在UIAbility启动过程中使用该接口,重复调用该接口将先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 命名路由页面的名称。
callback AsyncCallback<void> 回调函数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import * as Index from '../pages/Index'; // 导入命名路由页面

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    try {
      windowStage.loadContentByName(Index.entryName, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('Succeeded in loading the content.');
      });
    } catch (exception) {
      console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};
// ets/pages/Index.ets
export const entryName : string = 'Index';
@Entry({routeName: entryName})
@Component
export struct Index {
  @State message: string = 'Hello World'
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

loadContentByName11+

loadContentByName(name: string, storage?: LocalStorage): Promise<void>;

根据指定路由页面名称为当前WindowStage加载命名路由页面,通过LocalStorage传递状态属性至加载页面,使用promise异步回调。建议在UIAbility启动过程中使用该接口,重复调用该接口将先销毁旧的页面内容(即UIContent)再加载新的页面内容,请谨慎使用。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
name string 命名路由页面的名称。
storage LocalStorage 页面级UI状态存储单元,这里用于为加载到窗口的页面内容传递状态属性。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import * as Index from '../pages/Index'; // 导入命名路由页面

export default class EntryAbility extends UIAbility {
  // ...

  storage: LocalStorage = new LocalStorage();

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    this.storage.setOrCreate('storageSimpleProp', 121);
    try {
      let promise = windowStage.loadContentByName(Index.entryName, this.storage);
      promise.then(() => {
        console.info('Succeeded in loading the content.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};
// ets/pages/Index.ets
export const entryName : string = 'Index';
@Entry({routeName: entryName, useSharedStorage: true})
@Component
export struct Index {
  @State message: string = 'Hello World'
  @LocalStorageLink('storageSimpleProp') storageSimpleProp: number = 1;
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

on('windowStageEvent')9+

on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void

开启WindowStage生命周期变化的监听。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
eventType string 监听事件,固定为'windowStageEvent',即WindowStage生命周期变化事件。
callback Callback<WindowStageEventType> 回调函数。返回当前的WindowStage生命周期状态。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
1300002 This window state is abnormal.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    try {
      windowStage.on('windowStageEvent', (data) => {
        console.info('Succeeded in enabling the listener for window stage event changes. Data: ' +
        JSON.stringify(data));
      });
    } catch (exception) {
      console.error(`Failed to enable the listener for window stage event changes. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

off('windowStageEvent')9+

off(eventType: 'windowStageEvent', callback?: Callback<WindowStageEventType>): void

关闭WindowStage生命周期变化的监听。

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

系统能力: SystemCapability.WindowManager.WindowManager.Core

原子化服务API: 从API version 11开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
eventType string 监听事件,固定为'windowStageEvent',即WindowStage生命周期变化事件。
callback Callback<WindowStageEventType> 回调函数。返回当前的WindowStage生命周期状态。若传入参数,则关闭该监听。若未传入参数,则关闭所有WindowStage生命周期变化的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Incorrect parameter types; 2. Parameter verification failed.
1300002 This window state is abnormal.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    const callback = (windowStageEventType: window.WindowStageEventType) => {
      // ...
    }
    try {
      windowStage.on('windowStageEvent', callback);
    } catch (exception) {
      console.error(`Failed to enable the listener for window stage event changes. Cause code: ${exception.code}, message: ${exception.message}`);
    }
    try {
      windowStage.off('windowStageEvent', callback);
      // 如果通过on开启多个callback进行监听,同时关闭所有监听:
      windowStage.off('windowStageEvent');
    } catch (exception) {
      console.error(`Failed to disable the listener for window stage event changes. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

on('windowStageClose')14+

on(eventType: 'windowStageClose', callback: Callback<void>): void

开启点击主窗三键区的关闭按钮监听事件。点击主窗口的三键区域的关闭键时触发该回调函数,将不执行注册的UIAbility.onPrepareToTerminate生命周期回调函数。

当重复注册窗口关闭事件的监听时,最后一次注册成功的监听事件生效。

触发的回调函数是同步执行,主窗口的异步关闭事件监听参考on('windowWillClose')方法。

如果存在on('windowWillClose')监听事件,只响应on('windowWillClose')接口。

此接口仅可在2in1设备下使用。

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

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
eventType string 监听事件,固定为'windowStageClose',即开启主窗三键区的关闭按钮监听。
callback Callback<void> 回调函数。当点击主窗口右上角关闭按钮事件发生时的回调。该回调函数不返回任何参数。回调函数内部逻辑需要有boolean类型的返回值,该返回值决定当前主窗是否继续关闭,true表示不关闭,false表示关闭。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    try {
      windowStage.on('windowStageClose', () => {
        console.info('Succeeded in enabling the listener for window stage close event.');
        return false;
      });
    } catch (exception) {
      console.error(`Failed to enable the listener for window stage close event. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

off('windowStageClose')14+

off(eventType: 'windowStageClose', callback?: Callback<void>): void

关闭主窗口关闭事件的监听。

此接口仅可在2in1设备下使用。

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

系统能力: SystemCapability.Window.SessionManager

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

参数:

参数名 类型 必填 说明
eventType string 监听事件,固定为'windowStageClose',即关闭主窗口关闭事件的监听。
callback Callback<void> 回调函数。当点击主窗口右上角关闭按钮事件发生时的回调。该回调函数不返回任何参数。回调函数内部逻辑需要有boolean类型的返回值,该返回值决定当前主窗是否继续关闭,true表示不关闭,false表示关闭。如果传入参数,则关闭该监听。如果未传入参数,则关闭所有主窗口关闭的监听。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    const callback = () => {
      // ...
      return false;
    }
    try {
      windowStage.on('windowStageClose', callback);
      windowStage.off('windowStageClose', callback);
      windowStage.off('windowStageClose');
    } catch (exception) {
      console.error(`Failed to disable the listener for window stage close changes. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

setDefaultDensityEnabled12+

setDefaultDensityEnabled(enabled: boolean): void

设置应用是否使用系统默认Density,调用此接口前,需先调用WindowStage.loadContent()初始化布局,确保接口调用时序正确。

不调用此接口进行设置,则表示不使用系统默认Density。

不使用系统默认Density时,若调用过setCustomDensity(),则窗口会跟随用户自定义的显示大小变化重新布局,否则跟随系统显示大小变化重新布局。

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

原子化服务API: 从API version 12开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
enabled boolean 是否设置应用使用系统默认Density。true表示使用系统默认Density,窗口不跟随系统显示大小变化重新布局;false表示不使用系统默认Density,窗口跟随系统显示大小变化重新布局。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit'

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
      windowStage.loadContent("pages/page2", (err: BusinessError) => {
        let errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        console.info('onWindowStageCreate');
      try {
        windowStage.setDefaultDensityEnabled(true);
        console.info('Succeeded in loading the content.');
      } catch (exception) {
        console.error(`Failed to set default density enabled. Cause code: ${exception.code}, message: ${exception.message}`);
      }
    });
  }
};

setCustomDensity15+

setCustomDensity(density: number): void

支持应用主窗口自定义其显示大小缩放系数,子窗会跟随主窗生效。当存在同时使用该接口和setDefaultDensityEnabled(true)时,以最后调用的设置效果为准。

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

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
density number 自定义显示大小缩放系数。该参数为浮点数,取值范围为[0.5, 4.0]或-1.0。4.0表示窗口可显示的最大显示大小缩放系数,-1.0表示窗口使用系统显示大小缩放系数。

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300005 This window stage is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    try {
      windowStage.setCustomDensity(-1.0);
    } catch (exception) {
      console.error(`Failed to set custom density. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
};

setWindowModal14+

setWindowModal(isModal: boolean): Promise<void>

设置主窗的模态属性是否启用,使用Promise异步回调。

主窗口调用该接口时,设置主窗口模态属性是否启用。启用主窗口模态属性后,其相同应用进程下的其他主窗口以及其他主窗口的子窗口不能响应用户操作,直到该主窗口关闭或者主窗口的模态属性被禁用。

此接口仅可在2in1设备下使用。

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

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
isModal boolean 设置主窗口模态属性是否启用,true为启用,false为不启用。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    try {
      let promise = windowStage.setWindowModal(true);
      promise.then(() => {
        console.info('Succeeded in setting window modal');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set window modal. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to set window modal. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

removeStartingWindow14+

removeStartingWindow(): Promise<void>

支持应用控制启动页消失时机。

此接口只对应用主窗口生效,且需要在module.json5配置文件abilities标签中的metadata标签下配置"enable.remove.starting.window"为"true"才会生效。

在标签配置为"true"的情况下,系统提供了启动页超时保护机制,若5s内未调用此接口,系统将自动移除启动页。

若标签配置为"false"或未配置标签,则此接口不生效,启动页将会在应用首帧渲染完成后自动移除。

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

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...

  onWindowStageCreate(windowStage: window.WindowStage) {
    console.info('onWindowStageCreate');
    windowStage.removeStartingWindow().then(() => {
      console.info('Succeeded in removing starting window.');
    }).catch((err: BusinessError) => {
        console.error(`Failed to remove starting window. Cause code: ${err.code}, message: ${err.message}`);
    });
  }
};

setWindowRectAutoSave14+

setWindowRectAutoSave(enabled: boolean): Promise<void>

设置是否启用最后关闭的主窗尺寸的记忆功能,使用Promise异步回调,仅对2in1设备生效。

启用记忆功能后,在同一个UIAbility下,记忆最后关闭的主窗口的尺寸;此主窗口再次启动时,以记忆的尺寸按照规则进行打开。

层叠规则: 1、当前实例是自由窗口时,打开下一实例窗口层叠时,大小要跟随。2、当前实例是最大化或全屏窗口时,打开下一个实例窗口层叠时,保持最大化。

记忆规则:

上一次窗口状态 记忆规则
自由窗口 保留自由窗口的大小/位置,超出工作区回弹
二分屏窗口 保留二分屏之前自由窗口的大小/位置
最大化窗口 保留最大化
沉浸式窗口 保留沉浸式之前自由窗口的大小/位置
最小化窗口 保留最小化之前自由窗口的大小/位置

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

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
enabled boolean 设置是否启用主窗尺寸的记忆功能,true为启用,false为不启用。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    try {
      let promise = windowStage.setWindowRectAutoSave(true);
      promise.then(() => {
        console.info('Succeeded in setting window rect auto-save');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set window rect auto-save. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to set window rect auto-save. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

setWindowRectAutoSave17+

setWindowRectAutoSave(enabled: boolean, isSaveBySpecifiedFlag: boolean): Promise<void>

设置是否启用主窗的尺寸记忆功能,使用Promise异步回调,仅对2in1设备生效。

在同一个UIAbility下,可记忆最后关闭的主窗口尺寸,也可针对每个主窗口尺寸单独进行记忆。只有在UIAbility启动模式为specified,且isSaveBySpecifiedFlag设置为true时,才能针对每个主窗口尺寸进行单独记忆。

启用记忆功能后,记忆主窗口关闭时的尺寸;对应主窗口再次启动时,以记忆的尺寸按照规则进行打开。

记忆规则:

上一次窗口状态 记忆规则
自由窗口 保留自由窗口的大小/位置,超出工作区回弹。
二分屏窗口 保留二分屏之前自由窗口的大小/位置。
最大化窗口 保留最大化。
沉浸式窗口 保留沉浸式之前自由窗口的大小/位置。
最小化窗口 保留最小化之前自由窗口的大小/位置。

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

原子化服务API: 从API version 17开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
enabled boolean 设置是否启用主窗的尺寸记忆功能,true为启用,false为不启用。
isSaveBySpecifiedFlag boolean 设置specified模式下是否启用对窗口进行单独记忆,true为启用,false为不启用。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Function setWindowRectAutoSave can not work correctly due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    try {
      let promise = windowStage.setWindowRectAutoSave(true, true);
      promise.then(() => {
        console.info('Succeeded in setting window rect auto-save');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set window rect auto-save. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to set window rect auto-save. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

isWindowRectAutoSave14+

isWindowRectAutoSave(): Promise<boolean>

判断当前主窗口是否已经启用尺寸记忆,使用Promise异步回调,仅对2in1设备生效。

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

原子化服务API: 从API version 14开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

返回值:

类型 说明
Promise<boolean> Promise对象。返回true表示当前窗口启用尺寸记忆,返回false表示当前窗口禁用尺寸记忆。

错误码:

以下错误码的详细介绍请参见窗口错误码

错误码ID 错误信息
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.

示例:

// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    try {
      let promise = windowStage.isWindowRectAutoSave();
      promise.then((data) => {
        console.info(`Succeeded in checking whether the window support the rect auto-save. Data: ${data}`);
      }).catch((err: BusinessError) => {
        console.error(`Failed to check whether the window support the rect auto-save. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to check whether the window support the rect auto-save. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}

setSupportedWindowModes15+

setSupportedWindowModes(supportedWindowModes: Array<bundleManager.SupportWindowMode>): Promise<void>

设置主窗的窗口支持模式,使用Promise异步回调。

此接口仅可在2in1设备下使用。

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

原子化服务API: 从API version 15开始,该接口支持在原子化服务中使用。

系统能力: SystemCapability.Window.SessionManager

参数:

参数名 类型 必填 说明
supportedWindowModes Array<bundleManager.SupportWindowMode> 设置主窗的窗口支持模式。
- FULL_SCREEN:支持全屏模式。
- FLOATING:支持悬浮窗模式。
- SPLIT:支持分屏模式。需要配合FULL_SCREEN或FLOATING一起使用,不支持仅配置SPLIT。
注:数组中SupportWindowMode字段取值不应该与该UIAbility对应的module.json5配置文件abilities标签的supportWindowMode字段取值或者StartOptions属性的supportWindowModes字段取值冲突。当取值冲突时,最终以该参数设置的窗口支持模式为准。

返回值:

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

错误码:

以下错误码的详细介绍请参见通用错误码窗口错误码

错误码ID 错误信息
401 Parameter error. Possible cause: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported. Failed to call the API due to limited device capabilities.
1300002 This window state is abnormal.
1300003 This window manager service works abnormally.

示例:

// EntryAbility.ets
import { UIAbility, bundleManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export default class EntryAbility extends UIAbility {
  // ...
  onWindowStageCreate(windowStage: window.WindowStage): void {
    console.info('onWindowStageCreate');
    try {
      let promise = windowStage.setSupportedWindowModes([
        bundleManager.SupportWindowMode.FULL_SCREEN,
        bundleManager.SupportWindowMode.SPLIT,
        bundleManager.SupportWindowMode.FLOATING
      ]);
      promise.then(() => {
        console.info('Succeeded in setting window support modes');
      }).catch((err: BusinessError) => {
        console.error(`Failed to set window support modes. Cause code: ${err.code}, message: ${err.message}`);
      });
    } catch (exception) {
      console.error(`Failed to set window support modes. Cause code: ${exception.code}, message: ${exception.message}`);
    }
  }
}