2008-11-17 58 views
3

阻止在TextBox中使用某些输入键而无法阻止特殊击键(如Ctrl-V/Ctrl-C)的最佳方式是什么?在WinForm中的输入处理

例如,只允许用户输入字符或数字的一个子集,例如A或B或C,而没有其他东西。

回答

2

我会使用keydown事件,并使用e.cancel停止密钥,如果密钥不允许。如果我想在多个地方做,那么我会做一个继承文本框的用户控件,然后添加属性AllowedChars或DisallowedChars来为我处理它。我有几个变体,我经常使用它,有的允许金钱格式化和输入,有的用于时间编辑等等。

将它作为用户控件的好处是,您可以将其添加到自己的杀手文本框中。 ;)

0

您可以使用文本框的TextChanged事件。

private void txtInput_TextChanged(object sender, EventArgs e) 
    { 
     if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B") 
     { 
      //invalid entry logic here 
     } 
    } 
3

我用的是WinForms的Masked Textbox控件。关于它的更多解释here。实质上,它禁止与该字段的标准不匹配的输入。如果您不希望人们输入除数字之外的任何内容,则不会允许他们键入除数字之外的任何内容。

3

这是我通常如何处理。

Regex regex = new Regex("[0-9]|\b");    
e.Handled = !(regex.IsMatch(e.KeyChar.ToString())); 

这将只允许数字字符和退格。问题是在这种情况下你不会被允许使用控制键。如果你想保持这个功能,我会创建自己的文本框类。

+0

埃德:我已经这样做了正则表达式,并且需要扩展文本框以允许Ctrl键。我在KeyPress事件中处理Backspace和Delete作为特殊情况,KeyPress事件是正确的地方做键检查/块 – benPearce 2008-11-17 02:06:48

1

我发现唯一的工作解决方案是结束对Ctrl-V,Ctrl-C,Delete或Backspace的ProcessCmdKey中的按键进行预检查,并且如果它不是这些键中的一个,则进行进一步的验证在KeyPress事件中使用正则表达式。

这可能不是最好的方式,但它在我的情况下工作。

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{ 
    // check the key to see if it should be handled in the OnKeyPress method 
    // the reasons for doing this check here is: 
    // 1. The KeyDown event sees certain keypresses differently, e.g NumKeypad 1 is seen as a lowercase A 
    // 2. The KeyPress event cannot see Modifer keys so cannot see Ctrl-C,Ctrl-V etc. 
    // The functionality of the ProcessCmdKey has not changed, it is simply doing a precheck before the 
    // KeyPress event runs 
    switch (keyData) 
    { 
     case Keys.V | Keys.Control : 
     case Keys.C | Keys.Control : 
     case Keys.X | Keys.Control : 
     case Keys.Back : 
     case Keys.Delete : 
      this._handleKey = true; 
      break; 
     default: 
      this._handleKey = false; 
      break; 
    } 
    return base.ProcessCmdKey(ref msg, keyData); 
} 


protected override void OnKeyPress(KeyPressEventArgs e) 
{ 
    if (String.IsNullOrEmpty(this._ValidCharExpression)) 
    { 
     this._handleKey = true; 
    } 
    else if (!this._handleKey) 
    { 
     // this is the final check to see if the key should be handled 
     // checks the key code against a validation expression and handles the key if it matches 
     // the expression should be in the form of a Regular Expression character class 
     // e.g. [0-9\.\-] would allow decimal numbers and negative, this does not enforce order, just a set of valid characters 
     // [A-Za-z0-9\-_\@\.] would be all the valid characters for an email 
     this._handleKey = Regex.Match(e.KeyChar.ToString(), this._ValidCharExpression).Success; 
    } 
    if (this._handleKey) 
    { 
     base.OnKeyPress(e); 
     this._handleKey = false; 
    } 
    else 
    { 
     e.Handled = true; 
    } 

}