代码之家  ›  专栏  ›  技术社区  ›  benPearce

锁定文本框中的有效字符

  •  1
  • benPearce  · 技术社区  · 17 年前

    我需要能够锁定文本框中的有效字符,我目前有一个正则表达式,我可以检查每个字符,如

    [A-Za-z]

    将锁定为字母字符。

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
      if (e.KeyChar == (char)Keys.Back)
      {
        base.OnKeyPress(e);
        return;
      }
      if (String.IsNullOrEmpty(this._ValidCharExpression))
      {
        base.OnKeyPress(e);
      }
      else
      {
        bool isValidChar = Regex.Match(e.KeyChar.ToString(),this._ValidCharExpression).Success;
        if (isValidChar)
        {
          base.OnKeyPress(e);
        }
        else
        {
          e.Handled = true;
        }
      }
    }
    

    我已经将regex代码放在OnKeyPress代码中,但是我不想允许所有特殊的键,比如Ctrl-V、Ctrl-C和Backspace。

    正如您所看到的,我正在处理退格键。但是,例如,Ctrl-V无法看到V键,因为它对Ctrl键运行一次,但看不到任何修改器键。

    处理这种情况的最佳方法是什么?

    5 回复  |  直到 17 年前
        1
  •  4
  •   Tomalak    17 年前

    MaskedTextBox 也许对你合适。

    你也可以看看 FilterTextBox 在CodeProjct。您可以使用它(或描述的方法)来做您想要做的事情。基本思想是在更改变得可见之前取消更改(通过OnTextChanging事件)。

        2
  •  2
  •   Jimmy    17 年前

    如果将验证放在ContextChanged而不是OnKeyPress中,但每次通过验证时都将值保存到一个变量中,该怎么办?然后,如果用户粘贴或键入不正确的字符串,您可以进行还原,并给出一些其他UI提示,指出某些内容无效(例如,设置标签的文本)。

        3
  •  1
  •   user18443 user18443    17 年前

    为什么不在ContextChanged事件中检查有效字符

    然后处理Ctrl+C,Ctrl+V中的on键向下

    您还可以使用e.ModifierKeys==Keys.Control来测试控制键

    http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.aspx

        4
  •  0
  •   Rune Grimstad    17 年前

        5
  •  0
  •   benPearce    17 年前

    我提出的解决方案是检查OnKeyDown事件中的键,然后设置一个标志是否应该处理按键,这就是检查OnKeyPress事件。

    protected override void OnKeyDown(KeyEventArgs e)
     {
        Keys keyCode = (Keys)e.KeyValue;
        base.OnKeyDown(e);
        if ((e.Modifiers == Keys.Control) ||
           (e.Modifiers == Keys.Control) ||
           (keyCode == Keys.Back) ||
           (keyCode == Keys.Delete))
        {
          this._handleKey = true;
        }
        else
        {
          // check if the key is valid and set the flag
          this._handleKey = Regex.Match(key.ToString(), this._ValidCharExpression).Success;
        }
      }
    
    
    
    
    protected override void OnKeyPress(KeyPressEventArgs e)
      {
        if (this._handleKey)
        {
          base.OnKeyPress(e);
          this._handleKey = false;
        }
        else
        {
          e.Handled = true;
        }
      }
    
    推荐文章