4

在不阻止特殊击键(例如Ctrl- V/ Ctrl- )的情况下阻止某些输入键在 TextBox 中使用的最佳方法是什么C

例如,只允许用户输入字符或数字的子集,例如 A 或 B 或 C,仅此而已。

4

5 回答 5

3

我将Masked Textbox控件用于 winforms。这里有一个更长的解释。本质上,它不允许与字段条件不匹配的输入。如果您不希望人们输入除数字之外的任何内容,那么它根本不允许他们输入除数字之外的任何内容。

于 2008-11-17T00:46:44.813 回答
3

如果不允许使用该键,我将使用 keydown-event 并使用 e.cancel 来停止该键。如果我想在多个地方执行此操作,那么我将创建一个继承文本框的用户控件,然后添加一个属性 AllowedChars 或 DisallowedChars 为我处理它。我有几个变种,我不时使用,一些允许货币格式化和输入,一些用于时间编辑等等。

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

于 2008-11-17T01:27:53.250 回答
3

这就是我通常的处理方式。

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

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

于 2008-11-17T02:03:50.913 回答
1

Ctrl我发现唯一可行的解​​决方案是在 ProcessCmdKey 中对- VCtrl- 、 Delete 或 Backspace中的按键进行预检查,C如果它不是 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;
    }
    
}
于 2008-12-16T03:20:56.100 回答
0

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

    private void txtInput_TextChanged(object sender, EventArgs e)
    {
        if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B")
        {
            //invalid entry logic here
        }
    }
于 2008-11-17T00:19:04.400 回答