harmony 鸿蒙Key Event

  • 2025-06-12
  • 浏览 (4)

Key Event

A 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. For details about the process and specific timing of the key event triggering, see Key Event Data Flow.

NOTE

The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.

onKeyEvent

onKeyEvent(event: (event: KeyEvent) => void): T

Triggered when a key event occurs.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
event KeyEvent Yes KeyEvent object.

Return value

Type Description
T Current component.

onKeyEvent15+

onKeyEvent(event: Callback<KeyEvent, boolean>): T

Triggered 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.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
event Callback<KeyEvent, boolean> Yes Callback for handling the key event.

Return value

Type Description
T Current component.

onKeyPreIme12+

onKeyPreIme(event: Callback): T

Triggered before other callbacks when a key operation is performed on the bound component after it obtains focus.

If 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.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
event Callback<KeyEvent, boolean> Yes Callback for handling the key event.

Return value

Type Description
T Current component.

onKeyEventDispatch15+

onKeyEventDispatch(event: Callback<KeyEvent, boolean>): T

Triggered 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.

If the callback returns true, the key event is considered consumed and will not bubble up to the parent component for further handling.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
event Callback<KeyEvent, boolean> Yes Callback for handling key event dispatch.

Return value

Type Description
T Current component.

KeyEvent

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Description
type KeyType Key type.
keyCode number Key code.
keyText string Key value.
keySource KeySource Type of the input device that triggers the key event.
deviceId number ID of the input device that triggers the key event.
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.
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.
stopPropagation () => void Stops the event from bubbling upwards or downwards.
intentionCode10+ IntentionCode Intention corresponding to the key.
getModifierKeyState12+ (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.
Atomic service API: This API can be used in atomic services since API version 13.
unicode14+ 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.
Atomic service API: This API can be used in atomic services since API version 14.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed.

Example

Example 1: Triggering the onKeyEvent Callback

This example demonstrates how to set a key event on a button. When the button gains focus, the onKeyEvent callback is triggered.

// xxx.ets
@Entry
@Component
struct KeyEventExample {
  @State text: string = ''
  @State eventType: string = ''

  build() {
    Column() {
      Button('KeyEvent')
        .onKeyEvent((event?: KeyEvent) => {
          if(event){
            if (event.type === KeyType.Down) {
              this.eventType = 'Down'
            }
            if (event.type === KeyType.Up) {
              this.eventType = 'Up'
            }
            this.text = 'KeyType:' + this.eventType + '\nkeyCode:' + event.keyCode + '\nkeyText:' + event.keyText + '\nintentionCode:' + event.intentionCode
          }
        })
      Text(this.text).padding(15)
    }.height(300).width('100%').padding(35)
  }
}

keyEvent

Example 2: Obtaining Unicode Values

This example demonstrates how to obtain the Unicode value of the pressed key using the key event.

// xxx.ets
@Entry
@Component
struct KeyEventExample {
  @State text: string = ''
  @State eventType: string = ''
  @State keyType: string = ''

  build() {
    Column({ space: 10 }) {
      Button('KeyEvent')
        .onKeyEvent((event?: KeyEvent) => {
          if(event){
            if (event.type === KeyType.Down) {
              this.eventType = 'Down'
            }
            if (event.type === KeyType.Up) {
              this.eventType = 'Up'
            }
            if (event.unicode == 97) {
              this.keyType = 'a'
            } else if (event.unicode == 65) {
              this.keyType = 'A'
            } else {
              this.keyType = ' '
            }
            this.text = 'KeyType:' + this.eventType + '\nUnicode:' + event.unicode + '\nkeyCode:' + event.keyCode + '\nkeyType:' + this.keyType
          }
        })
      Text(this.text).padding(15)
    }.height(300).width('100%').padding(35)
  }
}

keyEvent

Example 3: Triggering the onKeyPreIme Callback

This example demonstrates how to use the onKeyPreIme callback to intercept and disable the left arrow key in a text field.

import { KeyCode } from '@kit.InputKit';

@Entry
@Component
struct PreImeEventExample {
  @State buttonText: string = '';
  @State buttonType: string = '';
  @State columnText: string = '';
  @State columnType: string = '';

  build() {
    Column() {
      Search({
        placeholder: "Search..."
      })
        .width("80%")
        .height("40vp")
        .border({ radius:"20vp" })
        .onKeyPreIme((event:KeyEvent) => {
          // Prevent the left arrow key from working.
          if (event.keyCode == KeyCode.KEYCODE_DPAD_LEFT) {
            return true;
          }
          return false;
        })
    }
  }
}

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArcButton

harmony 鸿蒙ArcSlider

harmony 鸿蒙Chip

harmony 鸿蒙ChipGroup

harmony 鸿蒙ComposeListItem

harmony 鸿蒙ComposeTitleBar

harmony 鸿蒙advanced.Counter

harmony 鸿蒙Dialog Box (Dialog)

harmony 鸿蒙DialogV2

harmony 鸿蒙DownloadFileButton

0  赞