• 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>15+</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 15.
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>15+</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 15.
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 Meta key (the key located next to the **Ctrl** key at the lower left corner of the keyboard, or the key marked with a window logo) when the key event occurs. The value **1** indicates that the Meta key is pressed, and **0** indicates that it is not pressed.|
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
131
132### Example 1: Triggering the onKeyEvent Callback
133
134This example demonstrates how to set a key event on a button. When the button gains focus, the **onKeyEvent** callback is triggered.
135
136```ts
137// xxx.ets
138@Entry
139@Component
140struct KeyEventExample {
141  @State text: string = ''
142  @State eventType: string = ''
143
144  build() {
145    Column() {
146      Button('KeyEvent')
147        .onKeyEvent((event?: KeyEvent) => {
148          if(event){
149            if (event.type === KeyType.Down) {
150              this.eventType = 'Down'
151            }
152            if (event.type === KeyType.Up) {
153              this.eventType = 'Up'
154            }
155            this.text = 'KeyType:' + this.eventType + '\nkeyCode:' + event.keyCode + '\nkeyText:' + event.keyText + '\nintentionCode:' + event.intentionCode
156          }
157        })
158      Text(this.text).padding(15)
159    }.height(300).width('100%').padding(35)
160  }
161}
162```
163
164 ![keyEvent](figures/keyEvent.gif)
165
166### Example 2: Obtaining Unicode Values
167
168This example demonstrates how to obtain the Unicode value of the pressed key using the key event.
169
170```ts
171// xxx.ets
172@Entry
173@Component
174struct KeyEventExample {
175  @State text: string = ''
176  @State eventType: string = ''
177  @State keyType: string = ''
178
179  build() {
180    Column({ space: 10 }) {
181      Button('KeyEvent')
182        .onKeyEvent((event?: KeyEvent) => {
183          if(event){
184            if (event.type === KeyType.Down) {
185              this.eventType = 'Down'
186            }
187            if (event.type === KeyType.Up) {
188              this.eventType = 'Up'
189            }
190            if (event.unicode == 97) {
191              this.keyType = 'a'
192            } else if (event.unicode == 65) {
193              this.keyType = 'A'
194            } else {
195              this.keyType = ' '
196            }
197            this.text = 'KeyType:' + this.eventType + '\nUnicode:' + event.unicode + '\nkeyCode:' + event.keyCode + '\nkeyType:' + this.keyType
198          }
199        })
200      Text(this.text).padding(15)
201    }.height(300).width('100%').padding(35)
202  }
203}
204```
205
206![keyEvent](figures/keyEvent_unicode.gif)
207
208### Example 3: Triggering the onKeyPreIme Callback
209
210This example demonstrates how to use the **onKeyPreIme** callback to intercept and disable the left arrow key in a text field.
211
212```ts
213import { KeyCode } from '@kit.InputKit';
214
215@Entry
216@Component
217struct PreImeEventExample {
218  @State buttonText: string = '';
219  @State buttonType: string = '';
220  @State columnText: string = '';
221  @State columnType: string = '';
222
223  build() {
224    Column() {
225      Search({
226        placeholder: "Search..."
227      })
228        .width("80%")
229        .height("40vp")
230        .border({ radius:"20vp" })
231        .onKeyPreIme((event:KeyEvent) => {
232          // Prevent the left arrow key from working.
233          if (event.keyCode == KeyCode.KEYCODE_DPAD_LEFT) {
234            return true;
235          }
236          return false;
237        })
238    }
239  }
240}
241```
242