Search code examples
javajavascriptgwtjakarta-eejsni

Capture ctr-z(undo) and ctr-y(redo) within GWT application


I have been writing a web application baased on GWT 2.3 and along with it I have written my own undo and redo functions. When the user presses ctr-z or ctr-y the undoes or redoes the last changes. Is their a way to effectively detect the ctr-z and ctr-y keypress events that occur anywhere on the page and cause them to run my own functions.


Solution

  • Add a NativePreviewHandler:

    Event.addNativePreviewHandler(new NativePreviewHandler() {
      @Override
      public void onPreviewNativeEvent(NativePreviewEvent event) {
        if (event.getTypeInt() == Event.ONKEYDOWN) {
          NativeEvent ne = event.getNativeEvent();
    
          if (ne.getCtrlKey() && ne.getKeyCode() == 'Z') {
            event.cancel();
            // Handle undo
          } else if (ne.getCtrlKey() && ne.getKeyCode() == 'Y') {
            event.cancel();
            // Handle redo
          }
        }
      }
    });