Customizing menu shortcuts in Compose for Desktop

Thomas Künneth - Dec 21 '20 - - Dev Community

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("os.name", "").contains("mac os x", true)) {
    menuBar.add(Menu("File", MenuItem(
        name = "Quit",
        onClick = {
          AppManager.exit()
        },
        shortcut = KeyStroke(Key.F4)
    )))
  }
  menuBar.add(Menu("Appearance", MenuItem(
      name = "Toggle Colors",
      onClick = {
        isInDarkMode = !isInDarkMode
      },
      shortcut = KeyStroke(Key.T)
  )))
  AppManager.setMenu(menuBar)
}
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(
        key.keyCode,
        Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()
    )
}
Enter fullscreen mode Exit fullscreen mode

The implementation of getMenuShortcutKeyMaskEx() in Toolkit.java is as follows:

public int getMenuShortcutKeyMaskEx() throws HeadlessException {
  GraphicsEnvironment.checkHeadless();
  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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player