Consuming keyboard events in custom editors

I am writing a custom editor. When this editor is in a specific state, I want it to get hold of keyboard input. There is GUIUtility.hotControl for mouse events, but what about keyboard events?

Example:

public void OnSceneGUI () {
    if (isMySpecialContextActive) {
        Event e = Event.current;
        if (e.isKey && e.keyCode == KeyCode.F) {
            DoSomethingWonderfulButPleaseDontFitSelectionToView();
        }
    }
}

I have tried e.Use() obviously, but that appears to be entirely non-functional here. I also tried GUIUtility.keyboardControl in the same way one would use hotControl. I really need to suppress default behavior entirely, even for bare keystrokes without Ctrl and Shift held down.

1 Answer

1

This is rather old by stumbled across this when googling and found the answer here Get KeyCode events in editor without object selected - Questions & Answers - Unity Discussions

So in case this is still useful to Zyl or other users, you would have to do:

public void OnSceneGUI () {
     if (isMySpecialContextActive) {
        int controlID = GUIUtility.GetControlID(FocusType.Passive);
        Event e = Event.current;
        if (Event.current.GetTypeForControl(controlID) == EventType.keyDown) {
            if(Event.current.keyCode == KeyCode.F) {
                DoWhatYouWantItWontFitSelectionToView();
            }
        }
     }
}

Disclaimer: At least it worked in my case, trying the exact same thing. To my shame, I do not understand WHY it works due to not understanding the Control-ID-thingy… but I’ll work on that. :wink: