【问题标题】:Checking TextCompositionEventArgs.ControlText by Unicode encoding通过 Unicode 编码检查 TextCompositionEventArgs.ControlText
【发布时间】:2019-04-04 00:51:11
【问题描述】:

我正在查看一本书中的 WPF 示例,其中OnPreviewTextInput 在派生自Window 的类中被覆盖。覆盖检查TextCompositionEventArgs.ControlText 字符串与Unicode 文字字符'\u000F'。这对应于用户按 Ctrl+O。

角色'\u000F' 对我来说就像一个“魔法”文字。如果我想检查其他代码,我怎么知道要检查什么?有没有更便于阅读的方式来做到这一点?

protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
    // Ctrl+O
    if (e.ControlText.Length > 0 && e.ControlText[0] == '\u000F')
    {
        // do stuff
    }
}

【问题讨论】:

    标签: c# unicode control-characters


    【解决方案1】:

    正如你所推测的,它是一个“魔法”字面。但魔术背后有一些逻辑和历史。它对应于一个名为Control characters 的旧概念(长读,仅当您感兴趣时)。

    有关0x0FCtrl-Osee this table 的对应关系的快速参考。用caret notation 关注第一列;您会看到字符 1-26 (0x01-0x1A) 将 Ctrl-A 映射到 Ctrl-Z。 Char 15(或0x0F)是你的Ctrl-O

    这些旧的 ASCII 控制代码被带到了 Unicode 中,保留了它们的映射。因此你的'\u0000F'

    如果您在互联网上的时间足够长,您会看到一些愚蠢的^H^H^H^令人敬畏的笑话,这些笑话依赖于 ^H 映射到 Backspace 控制字符的神秘知识。您实际上可以尝试其中一些。启动记事本,您会看到Ctrl-ICtrl-M 对应地映射到Tab 和Enter。

    【讨论】:

      【解决方案2】:

      使用Keyboard.IsKeyDown 方法应该使代码更具可读性:

      protected override void OnPreviewTextInput(TextCompositionEventArgs e)
      {
          // Ctrl+O
          if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
              && Keyboard.IsKeyDown(Key.O))
          {
              //...
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-01
        • 1970-01-01
        相关资源
        最近更新 更多