3

我想在 Scala 中检测像 CTRL+S 这样的键盘快捷键。如果只按下一个键很容易,但如果按下两个或多个键似乎很难。有没有比以下更好的解决方案?

reactions += {
  case c @ KeyReleased(_, Key.S, _, _) =>
    if (c.peer.isControlDown())
      // CTRL+S pressed
}

KeyPressed感觉在语义上有点不正确,因为它检查是否在释放 S 按钮后按下了 CTRL 按钮(我认为使用or并没有更好KeyTyped)。

这是一个SSCE

import scala.swing._
import scala.swing.event._

object SSCCE extends SimpleSwingApplication {
  def top = new MainFrame {
    val textArea = new TextArea(3, 30)
    contents = new FlowPanel {
      contents += textArea
    }
    listenTo(textArea.keys)
    reactions += {
      case c @ KeyReleased(_, Key.S, _, _) =>
        if (c.peer.isControlDown())
          Dialog.showMessage(null, "Message", "CTRL+S pressed")
    }
  }
}
4

1 回答 1

2

您可以通过测试修饰符来检查模式匹配:

case c @ KeyReleased(_, Key.S, mods, _) if (1 == (1 & mods>>7)) =>
  Dialog.showMessage(null, "Message", "CTRL+S pressed")

按下 Ctrl 时,设置索引 7 处的位。

但是,我认为您的原始代码更容易理解。

当然,添加辅助函数会有所帮助:

def ctrlDown(mods:Int) = (1 == (1 & mods>>7))
...

case c @ KeyReleased(_, Key.S, mods, _) if ctrlDown(mods) =>
  Dialog.showMessage(null, "Message", "CTRL+S pressed")
于 2014-04-16T11:24:12.087 回答