C# 只允许文本框中的特定字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12607087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Only allow specific characters in textbox
提问by Annoying Bot
How can I only allow certain characters in a Visual C# textbox? Users should be able to input the following characters into a text box, and everything else should be blocked: 0-9, +, -, /, *, (, ).
如何在 Visual C# 文本框中只允许某些字符?用户应该能够在文本框中输入以下字符,其他所有字符都应该被屏蔽:0-9、+、-、/、*、(、)。
I've used Google to look up this problem, but the only solutions I'm getting are allowing only alphabetic characters, only numerical or disallowing certain characters. What I want is not disallowing certain characters, I want to disallow everything by default except the characters that I put in the code.
我已经使用谷歌来查找这个问题,但我得到的唯一解决方案是只允许字母字符、数字字符或不允许某些字符。我想要的不是禁止某些字符,我想默认情况下禁止除我放入代码中的字符之外的所有内容。
采纳答案by Paul D'Ambra
As mentioned in a comment (and another answer as I typed) you need to register an event handler to catch the keydown or keypress event on a text box. This is because TextChanged is only fired when the TextBox loses focus
正如评论中提到的(以及我输入的另一个答案),您需要注册一个事件处理程序来捕获文本框上的 keydown 或 keypress 事件。这是因为只有当 TextBox 失去焦点时才会触发 TextChanged
The below regex lets you match those characters you want to allow
下面的正则表达式可以让你匹配那些你想要允许的字符
Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);
and this does the opposite and catches characters that aren't allowed
这做相反的事情并捕获不允许的字符
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);
I'm not assuming there'll be a single match as someone could paste text into the textbox. in which case catch textchanged
我不假设会有一个匹配项,因为有人可以将文本粘贴到文本框中。在这种情况下,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
}
}
and to validate single key presses
并验证单个按键
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;
}
}
回答by Maarten
You can probably use the KeyDown event, KeyPress eventor KeyUp event. I would first try the KeyDown event I think.
您可能可以使用KeyDown 事件、KeyPress 事件或KeyUp 事件。我会首先尝试我认为的 KeyDown 事件。
You can set the Handled property of the event args to stop handling the event.
您可以设置事件参数的 Handled 属性以停止处理事件。
回答by iivel
For your validation event IMO the easiest method would be to use a character array to validate textbox characters against. True - iterating and validating isn't particularly efficient, but it is straightforward.
对于您的验证事件 IMO,最简单的方法是使用字符数组来验证文本框字符。是的 - 迭代和验证并不是特别有效,但它很简单。
Alternately, use a regular expression of your whitelist characters against the input string. Your events are availalbe at MSDN here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx
或者,对输入字符串使用白名单字符的正则表达式。您的活动可在 MSDN 此处获得:http: //msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx
回答by Icemanind
You need to subscribe to the KeyDownevent on the text box. Then something like this:
您需要订阅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;
}
The important thing to know is that if you changed the Handledproperty to true, it will not process the keystroke. Setting it to falsewill.
要知道的重要一点是,如果您将Handled属性更改为true,它将不会处理击键。将其设置为falsewill。
回答by ranazeshankhan
private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
回答by Martin Wantke
Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.
拦截 KeyPressed 事件在我看来是一个很好的可靠解决方案。如果使用 RegExp,请注意触发代码字符(e.KeyChar 小于 32)。
But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.
但是这种方式仍然可以在用户从剪贴板粘贴文本时注入超出范围的字符。不幸的是,我没有找到正确的剪贴板事件来解决这个问题。
So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.
所以一个防水的解决方案是拦截TextBox.TextChanged。这里有时会在短时间内看到原始的超出范围的字符。我建议两者都实施。
using System.Text.RegularExpressions;
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;
}

