【问题标题】:How do I respond to a specific sequence of key presses?如何响应特定的按键顺序?
【发布时间】:2010-04-28 02:22:06
【问题描述】:

最终结果很简单,当用户按顺序输入字母“n”“o”“t”“e”时,我必须要发生一些事情。 “注意”就是这个词。

我正在为一个朋友做一个小应用程序,可以帮助他做笔记,我希望我的应用程序在他从机器上的任何地方键入“note”时变得可见。

这是我目前所得到的:

if (e.KeyCode == neededLetter as Keys)
            {
                neededLetter = "o";
            }

我用“N”初始化neededLetter 变量,但我被困在那里。有什么帮助吗?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    我发现处理全局键盘挂钩的最简单方法是使用AutoHotKey 编写脚本。您可以将脚本编译到托盘应用程序中,这样用户就无需安装 AutoHotKey。

    这是您要求的粗略示例。我没有测试它,但它应该在输入“note”的任何时候捕获,如果它正在运行则激活记事本,或者如果它没有运行则启动记事本......

    :*:note::
        IfWinExist, ahk_class Notepad
            WinActivate, ahk_class Notepad
        else
            Run, Notepad
    return
    

    【讨论】:

      【解决方案2】:

      首先,要从机器上的任何位置执行此操作,您需要挂钩所有键盘输入或找到其他方法来捕捉输入的字母。我不确定在 C# 中是如何完成的,但它应该可以的。

      对于实际的打字,你会想要这样的东西(这不一定是完美的):

      if (e.KeyCode == neededLetter as Keys)
      {
          if ( neededLetter == "n" )
          {
              neededLetter = "o";
          } else if ( neededLetter == "o" ) {
              neededLetter = "t";
          } else if ( neededLetter == "t" ) {
              neededLetter = "e";
          } else if ( neededLetter == "e" ) {
              // you now have the full sequence typed, show your app
          }
      } else { // not sure if this is valid, but it's the idea
          neededLetter = "n"; // reset the sequence if another letter is typed
      }
      

      【讨论】:

        【解决方案3】:

        您可能还想考虑在“n”之前或“e”之后匹配“非单词字符”(如空格或标点符号)。

        否则,您的应用会识别诸如 nanotechnology 之类的其他词,这可能会让用户感到厌烦。

        【讨论】:

          【解决方案4】:

          试试这样的:

          这些是类级别的声明

          string keySequence = "Note";
          int nextKey = 0;
          

          现在在事件处理程序中:

          if (e.KeyCode != keySequence[nextKey++] as Keys)
          {
              nextKey = 0;
          }
          if(nextKey == keySequence.Length)
          {
              // The sequence successfully matched here, do what you want
          }
          

          【讨论】:

            【解决方案5】:
            1. 寻找N
            2. 是下一个字母 O?如果否,则重置回 N
            3. 是下一个字母 T?如果否,则重置回 N
            4. 是下一个字母 E?如果否,则重置回 N
            5. 显示应用程序。

            【讨论】:

              猜你喜欢
              • 2012-02-01
              • 1970-01-01
              • 1970-01-01
              • 2017-02-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多