compose get mouse position on screen
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerMoveFilter
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.application
fun main() = application {
Window(
onCloseRequest = ::exitApplication,
title = "Mouse Position on Screen",
position = WindowPosition(100, 100)
) {
var mouseX by remember { mutableStateOf(0) }
var mouseY by remember { mutableStateOf(0) }
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
.pointerMoveFilter(onMove = {
mouseX = it.x.toInt()
mouseY = it.y.toInt()
false
})
) {
Box(
modifier = Modifier
.offset(x = mouseX.toFloat(), y = mouseY.toFloat())
.size(20.dp)
.background(Color.Red)
)
}
}
}
This code creates a Kotlin Compose application that displays a window. It tracks the mouse position within the window and displays a red square at the current mouse coordinates. The pointerMoveFilter
function is used to detect the mouse movement, updating the mouseX
and mouseY
variables accordingly. These variables represent the X and Y coordinates of the mouse pointer within the window. The position of the red square is updated based on these coordinates using the offset
modifier.