WinForm中的输入处理

4

如何在不阻止特殊按键(如 Ctrl-V/Ctrl-C)的情况下,最好地阻止文本框中使用某些输入键?

例如,只允许用户输入字符或数字子集,如 A 或 B 或 C,而不允许其他任何字符。

5个回答

3
我在winforms中使用了掩码文本框控件。这里有更详细的解释链接。基本上,它禁止输入不符合字段条件的内容。如果您不想让人们输入除数字以外的任何内容,它只会允许他们输入数字。

3
我会使用keydown事件,并使用e.cancel来阻止不允许的按键。如果我想在多个地方实现这个功能,我会创建一个用户控件,继承一个文本框,然后添加一个AllowedChars或DisallowedChars属性,以便为我处理它。我有几个变体,可以用于时间编辑和货币格式化等不同场景。
将其作为用户控件实现的好处是,您可以添加自己的功能,让它成为您自己的文本框。 ;)

3
这通常是我处理这个问题的方式。
Regex regex = new Regex("[0-9]|\b");            
e.Handled = !(regex.IsMatch(e.KeyChar.ToString()));

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


Ed:我已经在使用正则表达式来做这件事了,现在需要扩展文本框以允许使用Ctrl键。我正在处理KeyPress事件中的Backspace和Delete作为特殊情况,那么在KeyPress事件中进行按键检查/阻止是正确的吗? - benPearce

1

我发现唯一有效的解决方案是在 ProcessCmdKey 中对 Ctrl-VCtrl-C、Delete 或 Backspace 的按键进行预检查,如果不是这些按键,则在 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;
    }
    
}

0
你可以使用文本框的TextChanged事件。
    private void txtInput_TextChanged(object sender, EventArgs e)
    {
        if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B")
        {
            //invalid entry logic here
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接