仅允许文本框中的特定字符

时间:2012-09-26 17:20:10

标签: c# winforms textbox

如何只允许Visual C#文本框中的某些字符?用户应该能够将以下字符输入文本框,其他所有内容都应该被阻止:0-9,+, - ,/,*,(,)。

我已经使用谷歌来查找这个问题,但我得到的唯一解决方案是只允许字母字符,只允许数字或禁止某些字符。我想要的不是禁止某些字符,我想在默认情况下禁止所有内容,除了我在代码中添加的字符。

6 个答案:

答案 0 :(得分:25)

正如评论中提到的(以及我输入的另一个答案),您需要注册一个事件处理程序来捕获文本框上的keydown或keypress事件。这是因为TextChanged仅在TextBox失去焦点时触发

以下正则表达式可让您匹配想要允许的字符

Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);

,这反过来并捕获不允许的字符

Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);

我不认为会有一场比赛,因为有人可以将文字粘贴到文本框中。在这种情况下catch textchanged

textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
    Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
    MatchCollection matches = regex.Matches(textBox1.Text);
    if (matches.Count > 0) {
       //tell the user
    }
}

并验证单键按下

textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for a naughty character in the KeyDown event.
    if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
    {
        // Stop the character from being entered into the control since it is illegal.
        e.Handled = true;
    }
}

答案 1 :(得分:10)

您需要在文本框中订阅KeyDown事件。然后是这样的事情:

private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if (!char.IsControl(e.KeyChar) 
       && !char.IsDigit(e.KeyChar) 
       && e.KeyChar != '.' && e.KeyChar != '+' && e.KeyChar != '-'
       && e.KeyChar != '(' && e.KeyChar != ')' && e.KeyChar != '*' 
       && e.KeyChar != '/')
    {
        e.Handled = true;
        return;
    }
    e.Handled=false;
    return;
}

要知道的重要一点是,如果您将Handled属性更改为true,则不会处理击键。将其设置为false将会。

答案 2 :(得分:1)

您可以使用KeyDown eventKeyPress eventKeyUp event。我会首先尝试我认为的KeyDown事件。

您可以设置事件参数的Handled属性以停止处理事件。

答案 3 :(得分:0)

对于您的验证事件IMO,最简单的方法是使用字符数组来验证文本框字符。真实 - 迭代和验证不是特别有效,但它很简单。

或者,对输入字符串使用白名单字符的正则表达式。您的活动在MSDN上可用:http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx

答案 4 :(得分:0)

拦截KeyPressed事件在我看来是一个很好的解决方案。如果使用RegExp,请注意触发代码字符(e.KeyChar低于32)。

但是,只要用户从剪贴板粘贴文本,这样仍然可以将字符注入范围之外。不幸的是我没有找到正确的剪贴板事件来解决这个问题。

因此,防水解决方案是截取TextBox.TextChanged。有时原始的超出范围的字符可以在短时间内看到。我建议实施两者。

using System.Text.RegularExpressions;

private void Form1_Shown(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}


string pattern = @"[^0-9^+^\-^/^*^(^)]";

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}

private bool filterTextBoxContent(TextBox textBox)
{
    string text = textBox.Text;

    MatchCollection matches = Regex.Matches(text, pattern);
    bool matched = false;

    int selectionStart = textBox.SelectionStart;
    int selectionLength = textBox.SelectionLength;

    int leftShift = 0;
    foreach (Match match in matches)
    {
        if (match.Success && match.Captures.Count > 0)
        {
            matched = true;
            Capture capture = match.Captures[0];

            int captureLength = capture.Length;
            int captureStart = capture.Index - leftShift;
            int captureEnd = captureStart + captureLength;

            int selectionEnd = selectionStart + selectionLength;

            text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);

            textBox.Text = text;

            int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
            int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);

            if (boundSelectionStart == -1)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionLength -= selectionEnd - captureStart;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionLength -= captureLength;
                }
            }
            else if (boundSelectionStart == 0)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionStart = captureStart;
                    selectionLength = 0;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionStart = captureStart;
                    selectionLength -= captureEnd - selectionStart;
                }
            }
            else if (boundSelectionStart == 1)
            {
                selectionStart -= captureLength;
            }

            leftShift++;
        }
    }

    textBox.SelectionStart = selectionStart;
    textBox.SelectionLength = selectionLength;

    return matched;
}

答案 5 :(得分:-1)

    private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar))
        {
            e.Handled = true;
        }
    }
相关问题