---
title: "onKeyEvent"
description: "Adding this [modifier][Modifier] to the [modifier][Modifier] parameter of a component will allow
it to intercept hardware key events when it (or one of its children) is focused."
type: "modifier"
---

<div class='type'>Compose Modifier</div>

<a id='references'></a>
<div class='sourceset sourceset-common'>Common</div>


```kotlin
fun Modifier.onKeyEvent(onKeyEvent: (KeyEvent) -> Boolean): Modifier
```


Adding this `modifier` to the `modifier` parameter of a component will allow
it to intercept hardware key events when it (or one of its children) is focused.

#### Parameters

| | |
| --- | --- |
| onKeyEvent | This callback is invoked when the user interacts with the hardware keyboard. While implementing this callback, return true to stop propagation of this event. If you return false, the key event will be sent to this `onKeyEvent`'s parent. |




## Code Examples
### KeyEventSample
```kotlin
@Suppress("UNUSED_ANONYMOUS_PARAMETER")
@Composable
fun KeyEventSample() {
    // When the inner Box is focused, and the user presses a key, the key goes down the hierarchy
    // and then back up to the parent. At any stage you can stop the propagation by returning
    // true to indicate that you consumed the event.
    Box(Modifier.onPreviewKeyEvent { keyEvent1 -> false }.onKeyEvent { keyEvent4 -> false }) {
        Box(
            Modifier.onPreviewKeyEvent { keyEvent2 -> false }
                .onKeyEvent { keyEvent3 -> false }
                .focusable()
        )
    }
}
```

