How to dispatch an KeyboardEvent with specific KeyCode

老子叫甜甜 提交于 2020-02-04 07:28:27

问题


I try to dispatch an keyboard event for the esc key (for testing) this is what i got so far:

  KeyboardEvent keyEvent = new KeyboardEvent('keypress');

  window.onKeyPress.listen((KeyboardEvent event){
    KeyEvent keyEvent = new KeyEvent.wrap(event);
    if(keyEvent.keyCode == KeyCode.ESC){
      //do stuff
    }
  });

  window.dispatchEvent(keyEvent);

This works as expected. The onKeyPress listener triggers.

But i didn't find out how to set a KeyCode for my KeyBoardEvent?


回答1:


Can't use dispatchEvent. Try:

import 'dart:async';
import 'dart:html';

void main() {
  Stream stream = KeyEvent.keyPressEvent.forTarget(document.body);
  stream.listen((KeyEvent keyEvent){
    if(keyEvent.keyCode == KeyCode.ESC) {
        // do stuff
    }
  });
  stream.add(new KeyEvent('keypress', keyCode: KeyCode.ESC));
}

as described in https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:html.KeyEvent



来源:https://stackoverflow.com/questions/31058952/how-to-dispatch-an-keyboardevent-with-specific-keycode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!