• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Key Event
2
3A key event is triggered when a focusable component, such as **Button**, interacts with a keyboard, remote control, or any other input device with keys. To use a key event for components that are not focusable by default, such as **Text** and **Image**, first set their **focusable** attribute to **true**.
4For details about the process and specific timing of the key event triggering, see [Key Event Data Flow](../../../ui/arkts-common-events-device-input-event.md#key-event-data-flow).
5
6>  **NOTE**
7>
8>  The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
9
10## onKeyEvent
11
12onKeyEvent(event: (event: KeyEvent) => void): T
13
14Triggered when a key event occurs.
15
16**Atomic service API**: This API can be used in atomic services since API version 11.
17
18**System capability**: SystemCapability.ArkUI.ArkUI.Full
19
20**Parameters**
21
22| Name| Type                         | Mandatory| Description              |
23| ------ | ----------------------------- | ---- | ------------------ |
24| event  | [KeyEvent](#keyevent) | Yes  | **KeyEvent** object.|
25
26**Return value**
27
28| Type| Description|
29| -------- | -------- |
30| T | Current component.|
31
32## onKeyEvent<sup>16+</sup>
33onKeyEvent(event: Callback\<KeyEvent, boolean>): T
34
35Triggered when a key operation is performed on the bound component after it obtains focus. If the callback returns **true**, the key event is considered handled.
36
37**Atomic service API**: This API can be used in atomic services since API version 16.
38
39**System capability**: SystemCapability.ArkUI.ArkUI.Full
40
41**Parameters**
42
43| Name| Type                         | Mandatory| Description              |
44| ------ | ----------------------------- | ---- | ------------------ |
45| event  | [Callback](./ts-types.md#callback12)<[KeyEvent](#keyevent), boolean>| Yes  | Callback for handling the key event.|
46
47**Return value**
48
49| Type| Description|
50| -------- | -------- |
51| T | Current component.|
52
53## onKeyPreIme<sup>12+</sup>
54
55onKeyPreIme(event: Callback<KeyEvent, boolean>): T
56
57Triggered before other callbacks when a key operation is performed on the bound component after it obtains focus.
58
59If the return value of this callback is **true**, the key event is considered consumed, and subsequent event callbacks (**keyboardShortcut**, input method events, **onKeyEvent**) will be intercepted and no longer triggered.
60
61**Atomic service API**: This API can be used in atomic services since API version 12.
62
63**System capability**: SystemCapability.ArkUI.ArkUI.Full
64
65**Parameters**
66
67| Name| Type                         | Mandatory| Description              |
68| ------ | ----------------------------- | ---- | ------------------ |
69| event  | [Callback](./ts-types.md#callback12)<[KeyEvent](#keyevent), boolean>| Yes  | Callback for handling the key event.|
70
71**Return value**
72
73| Type| Description|
74| -------- | -------- |
75| T | Current component.|
76
77## onKeyEventDispatch<sup>16+</sup>
78
79onKeyEventDispatch(event: Callback\<KeyEvent, boolean>): T
80
81Triggered when the bound component receives a key event. The key event will not be dispatched to its child components. Constructing a **KeyEvent** object for dispatch is not supported; only existing key events can be dispatched.
82
83If the callback returns **true**, the key event is considered consumed and will not bubble up to the parent component for further handling.
84
85**Atomic service API**: This API can be used in atomic services since API version 16.
86
87**System capability**: SystemCapability.ArkUI.ArkUI.Full
88
89**Parameters**
90
91| Name| Type                         | Mandatory| Description              |
92| ------ | ----------------------------- | ---- | ------------------ |
93| event  | [Callback](./ts-types.md#callback12)<[KeyEvent](#keyevent), boolean>| Yes  | Callback for handling key event dispatch.|
94
95**Return value**
96
97| Type| Description|
98| -------- | -------- |
99| T | Current component.|
100
101
102## KeyEvent
103
104**Atomic service API**: This API can be used in atomic services since API version 11.
105
106**System capability**: SystemCapability.ArkUI.ArkUI.Full
107
108| Name                                   | Type                                      | Description                        |
109| ------------------------------------- | ---------------------------------------- | -------------------------- |
110| type                                  | [KeyType](ts-appendix-enums.md#keytype)  | Key type.                    |
111| [keyCode](../../apis-input-kit/js-apis-keycode.md#keycode) | number                                   | Key code.                    |
112| keyText                               | string                                   | Key value.                    |
113| keySource                             | [KeySource](ts-appendix-enums.md#keysource) | Type of the input device that triggers the key event.            |
114| deviceId                              | number                                   | ID of the input device that triggers the key event.            |
115| metaKey                               | number                                   | State of the metakey when the key is pressed. The value **1** means the pressed state, and **0** means the unpressed state.|
116| timestamp                             | number                                   | Timestamp of the event. It is the interval between the time when the event is triggered and the time when the system starts, in nanoseconds.|
117| stopPropagation                       | () => void                               | Stops the event from bubbling upwards or downwards.                 |
118| intentionCode<sup>10+</sup>           | [IntentionCode](../../apis-input-kit/js-apis-intentioncode.md) | Intention corresponding to the key.      |
119| getModifierKeyState<sup>12+</sup> | (Array&lt;string&gt;) => bool | Obtains the pressed status of modifier keys. For details about the error message, see the following error codes. The following modifier keys are supported: 'Ctrl'\|'Alt'\|'Shift'\|'Fn'. However, the **Fn** key on external keyboards is not supported.<br>**Atomic service API**: This API can be used in atomic services since API version 13.|
120| unicode<sup>14+</sup>                              | number                                   | Unicode value of the key. Non-space basic Latin characters in the 0x0021-0x007E range are supported. Characters with a value of 0 are not supported. In the case of key combination, this API returns the Unicode value of the key corresponding to the key event.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
121
122**Error codes**
123
124For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md).
125
126| ID| Error Message|
127| ------- | -------- |
128| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. |
129
130## Example 1: Triggering the onKeyEvent Callback
131
132This example demonstrates how to set a key event on a button. When the button gains focus, the **onKeyEvent** callback is triggered.
133
134```ts
135// xxx.ets
136@Entry
137@Component
138struct KeyEventExample {
139  @State text: string = ''
140  @State eventType: string = ''
141
142  build() {
143    Column() {
144      Button('KeyEvent')
145        .onKeyEvent((event?: KeyEvent) => {
146          if(event){
147            if (event.type === KeyType.Down) {
148              this.eventType = 'Down'
149            }
150            if (event.type === KeyType.Up) {
151              this.eventType = 'Up'
152            }
153            this.text = 'KeyType:' + this.eventType + '\nkeyCode:' + event.keyCode + '\nkeyText:' + event.keyText + '\nintentionCode:' + event.intentionCode
154          }
155        })
156      Text(this.text).padding(15)
157    }.height(300).width('100%').padding(35)
158  }
159}
160```
161
162 ![keyEvent](figures/keyEvent.gif)
163
164## Example 2: Obtaining Unicode Values
165
166This example demonstrates how to obtain the Unicode value of the pressed key using the key event.
167
168```ts
169// xxx.ets
170@Entry
171@Component
172struct KeyEventExample {
173  @State text: string = ''
174  @State eventType: string = ''
175  @State keyType: string = ''
176
177  build() {
178    Column({ space: 10 }) {
179      Button('KeyEvent')
180        .onKeyEvent((event?: KeyEvent) => {
181          if(event){
182            if (event.type === KeyType.Down) {
183              this.eventType = 'Down'
184            }
185            if (event.type === KeyType.Up) {
186              this.eventType = 'Up'
187            }
188            if (event.unicode == 97) {
189              this.keyType = 'a'
190            } else if (event.unicode == 65) {
191              this.keyType = 'A'
192            } else {
193              this.keyType = ' '
194            }
195            this.text = 'KeyType:' + this.eventType + '\nUnicode:' + event.unicode + '\nkeyCode:' + event.keyCode + '\nkeyType:' + this.keyType
196          }
197        })
198      Text(this.text).padding(15)
199    }.height(300).width('100%').padding(35)
200  }
201}
202```
203
204![keyEvent](figures/keyEvent_unicode.gif)
205