Is there a way to know if a key pressed (onKeyEven...
# compose
a
Is there a way to know if a key pressed (onKeyEvent) will output a character or not when pressed? ie 'A' will print A, but meta,esc, cmd keys don't output any characters
Made it work with:
Copy code
fun isCharacterKey(event: KeyEvent): Boolean {
    val char = event.key.toString().replace("Key: ", "")
    return char.length == 1 && event.key !in listOf(
        Key.MetaLeft, Key.MetaRight,
        Key.Escape, Key.Delete, Key.Backspace,
        Key.Tab, Key.AltLeft, Key.AltRight
    )
}
👍 2
✔️ 1
PS: The above tells you whether a "key" will print a character, but it will not tell you which character will be printed (ie upper or lower case). I found that you can get the actual
keyChar
(instead of the replace trick i do above) by using the actual platform. On desktop you get it by
awtEventOrNull!!.keyChar
. haven't checked for others PS2: Desktop also has a
KeyEvent.isTypedEvent
which i think does exactly what i want, but need this on web too
This seems to be working reliably on both desktop and web:
Copy code
expect val KeyEvent.isTypedEvent: Boolean

expect val KeyEvent.typedChar: String

// Desktop
actual val KeyEvent.isTypedEvent: Boolean
    get() {
        return this.isTypedEvent
    }

actual val KeyEvent.typedChar: String
    get() = awtEventOrNull!!.keyChar.toString()

// Web
actual val KeyEvent.isTypedEvent: Boolean
    get() {
        return this.typedChar.length == 1
    }

actual val KeyEvent.typedChar: String
    get() {
        return domEventOrNull!!.key
    }
PS3:
awsEventOrNull.isTypedEvent
will only return true if the character is combined with the appropriate key type (key down, etc). so the above won't work on Desktop unless you use it on a TextField. Just a headsup for whoever reads this in the future
t
I use a compose key so the notion of a key necessarily outputting a character is iffy on my setup too, sometimes it just contributes to the current sequence
I'm guessing typedChar does the right thing in this situation although the actual number of chars typed isn't always 1 either
e.g. [compose] [compose] [a] [l] [e] [p] [0] would type ℵ₀ which is probably two
[compose] [t] [f] types (ノಥ益ಥ)ノ彡┻━┻ which is 11 or so
so I guess at the very least the correct check would be
typedChar.length > 0
?