【问题标题】:How To Detect Keyboard Shortcuts like CTRL+S in Scala如何在 Scala 中检测 CTRL+S 等键盘快捷键
【发布时间】:2014-04-16 11:05:36
【问题描述】:

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

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

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

这是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")
    }
  }
}

【问题讨论】:

    标签: scala scala-swing


    【解决方案1】:

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

    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")
    

    【讨论】:

    • 谢谢。但是,是的,我也认为这更难理解......我认为/认为必须有一个更好、更具可扩展性的解决方案(对于带有 X 按键的快捷方式)......
    猜你喜欢
    • 2021-04-11
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2010-09-15
    相关资源
    最近更新 更多