#鸿蒙通关秘籍#如何使用onMouse回调捕获和处理鼠标事件数据?

HarmonyOS
2024-12-04 15:12:27
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
云海谜ETL

在组件上绑定onMouse回调可以捕获鼠标事件,并处理事件数据。相关属性如:event对象可以提供鼠标按键、位置、以及行为等信息:

@Entry
@Component
struct MouseExample {
  @State buttonText: string = '';
  @State columnText: string = '';
  @State hoverText: string = 'Not Hover';
  @State Color: Color = Color.Gray;

  build() {
    Column() {
      Button(this.hoverText)
        .width(200)
        .height(100)
        .backgroundColor(this.Color)
        .onHover((isHover?: boolean) => {
          if (isHover) {
            this.hoverText = 'Hovered!';
            this.Color = Color.Green;
          } else {
            this.hoverText = 'Not Hover';
            this.Color = Color.Gray;
          }
        })
        .onMouse((event?: MouseEvent) => {
          if (event) {
            this.buttonText = 'Button onMouse:\n' +
                              'button = ' + event.button + '\n' +
                              'action = ' + event.action + '\n' +
                              'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
                              'windowXY=(' + event.windowX + ',' + event.windowY + ')';
          }
        });
      Divider();
      Text(this.buttonText).fontColor(Color.Green);
      Divider();
      Text(this.columnText).fontColor(Color.Red);
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
    .borderWidth(2)
    .borderColor(Color.Red)
    .onMouse((event?: MouseEvent) => {
      if (event) {
        this.columnText = 'Column onMouse:\n' +
                          'button = ' + event.button + '\n' +
                          'action = ' + event.action + '\n' +
                          'x,y = (' + event.x + ',' + event.y + ')' + '\n' +
                          'windowXY=(' + event.windowX + ',' + event.windowY + ')';
      }
    });
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
分享
微博
QQ
微信
回复
2024-12-04 16:53:47
相关问题
HarmonyOS 事件
1025浏览 • 1回复 待解决