如何使用特定的KeyCode调度KeyboardEvent

时间:2015-06-25 19:18:04

标签: events keyboard dart

我尝试为esc键发送键盘事件(用于测试) 这是我到目前为止所得到的:

  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);

这可以按预期工作。 onKeyPress监听器触发。

但我没有找到如何为我的KeyBoardEvent设置KeyCode?

1 个答案:

答案 0 :(得分:1)

无法使用dispatchEvent。尝试:

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));
}

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

中所述