【问题标题】:How to detect multiple keys entered in c# keydown event of textbox?如何检测在文本框的 c# keydown 事件中输入的多个键?
【发布时间】:2011-10-31 07:00:05
【问题描述】:

我想在 silverlight 中设计一个数字文本框。

我已经添加了 TextBox 的 keydown 事件 来处理按键。

内部事件我验证在文本框中输入的密钥。

事件如下

  private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (!this.Validate(sender,e))
            e.Handled = true;
    }

函数验证如下

  private bool Validate(object sender, KeyEventArgs e)
    {

        if (e.Key == Key.Enter) //accept enter and tab
        {
            return true;
        }
        if (e.Key == Key.Tab)
        {
            return true;
        }

        if (e.Key < Key.D0 || e.Key > Key.D9) //accept number on alphnumeric key
            if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9) //accept number fomr NumPad
                if (e.Key != Key.Back) //accept backspace
                    return false;

        return true;
    }

我无法检测到移位和 Key.D0 到 Key.D1 即

SHIFT + 1 返回 "!"

SHIFT + 3 与任何其他特殊键一样返回“#”。

我不希望用户在文本框中输入特殊字符。

如何处理这个按键事件??

【问题讨论】:

    标签: c# silverlight keyboard


    【解决方案1】:

    在 Silverlight 中,我认为在 KeyEventArgs 类中没有任何 Modifiers,而是在 Keyboard 中:

        public void KeyDown(KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.D0)
            {
                ControlZero();
            }
        }
    

    【讨论】:

    • 这是正确答案。 KeyEventArgs 不包含修饰符。
    【解决方案2】:

    e 应该有一个属性,它会告诉你是否按下了 Shift、Control 或 Alt。 e.Modifiers 还可以为您提供有关已按下哪些附加修饰键的其他信息。

    要取消字符,您可以将e.Handled 设置为True,这将导致控件忽略按键。

    【讨论】:

      【解决方案3】:
      textBox2.Text = string.Empty;
      textBox2.Text = e.Modifiers.ToString() + " + " + e.KeyCode.ToString();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-13
        • 2010-11-23
        • 1970-01-01
        • 1970-01-01
        • 2012-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多