[英]How to allow, and limit to one “.” (period) character in a TextBox? (C# winforms)
[英]How to limit number of specific character of a textbox c# form application
我想知道如何限制 c# 表单应用程序中文本框的特定字符的数量。 例如,我想限制用户只能输入-
(减号)一次,然后如果他再次尝试输入,我希望程序再次限制输入。
示例: -123
或123-
或123-123
(只有一个-
)。
如果用户删除-
那么应该有权限输入一个-
再次,当然没有更多!
我想阻止用户输入----1234
或1234--
,或123-4--21
或者你想的更多!!
这是我正在尝试的:
private void txtStopAfterXTimes_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract)
{
if (txtStopAfterXTimes.Text.Count((char)'-', 1))
{
e.SuppressKeyPress = true;
}
else if (txtStopAfterXTimes.Text.Count((char)'-', 0))
{
e.SuppressKeyPress = false;
}
}
}
我知道这是错误的,但请帮忙! 谢谢你...
您可以通过两种方式更改txtStopAfterXTimes
的Text
:按一个键 ( -
) 或粘贴一个值。 这就是为什么我们必须处理2 个事件: KeyPress
用于-
按键和TextChanged
用于文本粘贴:
代码: (WinForms)
private void txtStopAfterXTimes_TextChanged(object sender, EventArgs e) {
// When pasting a text into txtStopAfterXTimes...
TextBox box = sender as TextBox;
StringBuilder sb = new StringBuilder(box.Text.Length);
bool containsMinus = false;
// We remove all '-' but the very first one
foreach (char ch in box.Text) {
if (ch == '-') {
if (containsMinus)
continue;
containsMinus = true;
}
sb.Append(ch);
}
box.Text = sb.ToString();
}
private void txtStopAfterXTimes_KeyPress(object sender, KeyPressEventArgs e) {
TextBox box = sender as TextBox;
// we allow all characters ...
e.Handled = e.KeyChar == '-' && // except '-'
box.Text.Contains('-') && // when we have '-' within Text
!box.SelectedText.Contains('-'); // and we are not going to remove it
}
我会避免使用TextChanged
因为它会在文本更改后引发,并且可能会有点晚。
这是我将使用的解决方案,因为您还需要关心粘贴。
keyPress
我检查字符是否不是第一个“-”,然后我会忽略它,否则我会接受它。WndProc
我通过删除所有出现的“-”但第一个来捕获WM_PASTE
并清理剪贴板文本。 如果输入不可接受,您也可以轻松决定停止粘贴。这是实现:
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class MyTextBox : TextBox
{
private const int WM_PASTE = 0x0302;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool MessageBeep(int type);
protected override void WndProc(ref Message m)
{
if (m.Msg != WM_PASTE) { base.WndProc(ref m); }
else {
//You can sanitize the input or even stop pasting the input
var text = SanitizeText(Clipboard.GetText());
SelectedText = text;
}
}
protected virtual string SanitizeText(string value)
{
if (Text.IndexOf('-') >= 0) { return value.Replace("-", ""); }
else {
var str = value.Substring(0, value.IndexOf("-") + 1);
return str + value.Substring(str.Length).Replace("-", "");
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '-' && this.Text.IndexOf('-') >= 0) {
e.Handled = true;
MessageBeep(0);
}
else {
base.OnKeyPress(e);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.