DEV Community

Cover image for Customizing menu shortcuts in Compose for Desktop

Customizing menu shortcuts in Compose for Desktop

tkuenneth profile image Thomas Kuenneth ・2 min read

It is very easy to setup a MenuBar in Compose for Desktop. But as you will see shortly, some MenuItems may need help from old classes. Take a look at the following code snippet. This function configures a menubar with one (if running on macOS) or two Menus.

private fun configureMenuBar() {
  val menuBar = MenuBar()
  if (!System.getProperty("", "").contains("mac os x", true)) {
    menuBar.add(Menu("File", MenuItem(
        name = "Quit",
        onClick = {
        shortcut = KeyStroke(Key.F4)
  menuBar.add(Menu("Appearance", MenuItem(
      name = "Toggle Colors",
      onClick = {
        isInDarkMode = !isInDarkMode
      shortcut = KeyStroke(Key.T)
Enter fullscreen mode Exit fullscreen mode

On macOS the app gets a Quit menu item for free. On other platforms, we need to provide it on our own.

A menu

Have you noticed the shortcut? It's Ctrl+F4, which is not quite correct as on Windows applications are closed using Alt+F4. That happens because I wrote shortcut = KeyStroke(Key.F4). The source code for KeyStroke() (the file MenuItem.kt belongs to package androidx.compose.ui.window) currently looks like this:

fun KeyStroke(key: Key): KeyStroke {
    return KeyStroke.getKeyStroke(
Enter fullscreen mode Exit fullscreen mode

The implementation of getMenuShortcutKeyMaskEx() in is as follows:

public int getMenuShortcutKeyMaskEx() throws HeadlessException {
  return InputEvent.CTRL_DOWN_MASK;
Enter fullscreen mode Exit fullscreen mode

So, how to get Alt instead? We just need to invoke KeyStroke.getKeyStroke() on our own:

shortcut = KeyStroke.getKeyStroke(
               KeyEvent.VK_F4, ActionEvent.ALT_MASK)
Enter fullscreen mode Exit fullscreen mode

Menu item with Alt+F4

As most menu item shortcuts should correspond to Ctrl using KeyStroke() is fine most of the time. But if you need another modifier key, you now know how to get it.

Discussion (0)

Editor guide