HarmonyOS ArkUI Event Handling: Mouse and Keyboard Events

Mouse Events

The onMouse event handler responds to various user interactions with the mouse interface. This callback function triggers when users perform mouse actions on the UI, enabling developers to capture and respond to mouse clicks, movements, scrolling, hovering, and other mouse-related operations.

The syntax for the onMouse event handler is:

onMouse(event: (event?: MouseEvent) => void)

Implementation Example

// MouseInteractionDemo.ets
@Entry
@Component
struct MouseInteractionDemo {
  @State isHovering: boolean = false;
  @State buttonInfo: string = '';
  @State containerInfo: string = '';

  build() {
    Column() {
      Button(this.isHovering ? 'Active' : 'Inactive')
        .width(180)
        .height(80)
        .backgroundColor(this.isHovering ? Color.Blue : Color.LightGray)
        .onHover((isHover: boolean) => {
          this.isHovering = isHover;
        })
        .onMouse((event: MouseEvent) => {
          this.buttonInfo = 'Button Interaction:\n' +
          'Button: ' + event.button + '\n' +
          'Action: ' + event.action + '\n' +
          'Position: (' + event.x + ',' + event.y + ')\n' +
          'Screen Position: (' + event.screenX + ',' + event.screenY + ')';
        })
      
      Divider()
      Text(this.buttonInfo).fontColor(Color.Blue)
      
      Divider()
      Text(this.containerInfo).fontColor(Color.Red)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
    .borderWidth(2)
    .borderColor(Color.Red)
    .onMouse((event: MouseEvent) => {
      this.containerInfo = 'Container Interaction:\n' +
      'Button: ' + event.button + '\n' +
      'Action: ' + event.action + '\n' +
      'Position: (' + event.x + ',' + event.y + ')\n' +
      'Screen Position: (' + event.screenX + ',' + event.screenY + ')';
    })
  }
}

Event Bubbling

Event bubbling is a propagation mechanism where an event triggered on an element propagates upward through its ancestors in the component hierarchy. When an element triggers an event, the event first executes the handler on the triggering element, then bubbles up to parent elements, executing their handlers until reaching the root component or until propagation is stopped.

This mechanism provides flexibility in event handling. By attaching event handlers to ancestor components, developers can manage events for multiple child components efficiently. For instance, when dealing with multiple buttons in a container, you can attach a single click handler to the parent container instead of individual handlers for each button.

However, event bubbling can sometimes cause issues, especially when elements overlap. In such cases, multiple components may receive the same event, potentially leading to unintended behavior. To prevent this, you can use the event.stopPropagation() method to halt further propagation or check the event's target property to precisely control event handling.

Preventing Event Bubbling

Button(this.isHovering ? 'Active' : 'Inactive')
  .width(180)
  .height(80)
  .backgroundColor(this.isHovering ? Color.Blue : Color.LightGray)
  .onHover((isHover: boolean) => {
    this.isHovering = isHover;
  })
  .onMouse((event: MouseEvent) => {
    event.stopPropagation(); // Prevent event from bubbling to parent components
    this.buttonInfo = 'Button Interaction:\n' +
    'Button: ' + event.button + '\n' +
    'Action: ' + event.action + '\n' +
    'Position: (' + event.x + ',' + event.y + ')\n' +
    'Screen Position: (' + event.screenX + ',' + event.screenY + ')';
  })

Hover Effects

The hoverEffect property defines visual feedback when users hover their mouse over a component. This enhances user experience by providing visual responses to mouse interactions.

The syntax for hoverEffect is:

hoverEffect(value: HoverEffect)

HoverEffect Options

HoverEffect Enum Value Description
Auto Default hover effect provided by the component, as defined by each component type.
Scale Animation effect where the component scales from 100% to 105% on hover and returns to 100% when the mouse leaves.
Highlight Animation effect that adds a 5% opacity white overlay to the component's background on hover, making it appear darker, and reverts to the original style when the mouse leaves.
None Disables hover effects entirely.

Hover Effect Implementation

// HoverEffectDemo.ets
@Entry
@Component
struct HoverEffectDemo {
  build() {
    Column({ space: 12 }) {
      Button('Default Effect')
        .width(160).height(60)
      
      Button('Scale Effect')
        .width(160).height(60)
        .hoverEffect(HoverEffect.Scale)
      
      Button('Highlight Effect')
        .width(160).height(60)
        .hoverEffect(HoverEffect.Highlight)
      
      Button('No Effect')
        .width(160).height(60)
        .hoverEffect(HoverEffect.None)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
    .justifyContent(FlexAlign.Center)
  }
}

Keyboard Events

onKeyEvent

The onKeyEvent handler processes keyboard input events. When a user presses or releases a key, the system generates a keyboard event that can be handled through the onKeyEvent function. This allows developers to respond to specific key presses, such as moving game characters, opening menus, or triggering actions.

The syntax for onKeyEvent is:

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

Keyboard Event Implementation

// KeyboardInteractionDemo.ets
@Entry
@Component
struct KeyboardInteractionDemo {
  @State buttonAction: string = '';
  @State keyType: string = '';
  @State containerAction: string = '';
  @State containerKeyType: string = '';

  build() {
    Column() {
      Button('Keyboard Input')
        .width(120).height(60)
        .onKeyEvent((event: KeyEvent) => {
          if (event.type === KeyType.Down) {
            this.keyType = 'Pressed';
          }
          if (event.type === KeyType.Up) {
            this.keyType = 'Released';
          }
          this.buttonAction = 'Button Status:\n' +
          'Action Type: ' + this.keyType + '\n' +
          'Key Code: ' + event.keyCode + '\n' +
          'Key Label: ' + event.keyText;
        })

      Divider()
      Text(this.buttonAction).fontColor(Color.Blue)

      Divider()
      Text(this.containerAction).fontColor(Color.Red)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
    .onKeyEvent((event: KeyEvent) => {
      if (event.type === KeyType.Down) {
        this.containerKeyType = 'Pressed';
      }
      if (event.type === KeyType.Up) {
        this.containerKeyType = 'Released';
      }
      this.containerAction = 'Container Status:\n' +
      'Action Type: ' + this.containerKeyType + '\n' +
      'Key Code: ' + event.keyCode + '\n' +
      'Key Label: ' + event.keyText;
    })
  }
}

Tags: HarmonyOS ArkUI MouseEvent KeyEvent hoverEffect

Posted on Tue, 19 May 2026 06:32:44 +0000 by bdamod1