我想创建某种类型的许可证验证文本框,自动将用户输入拆分为由连字符分隔的块。我的执照是25个字符长,而且分开,例如:解析用户输入作为用户键入WinForms文本框控件
XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
我想出了下面的代码来分析用户的输入,而他是打字或通过复制/粘贴通过处理TextChanged
事件TextBox控件像这样的:
public static string InsertStringAtInterval(string source, string insert, int interval)
{
StringBuilder result = new StringBuilder();
int currentPosition = 0;
while (currentPosition + interval < source.Length)
{
result.Append(source.Substring(currentPosition, interval)).Append(insert);
currentPosition += interval;
}
if (currentPosition < source.Length)
{
result.Append(source.Substring(currentPosition));
}
return result.ToString();
}
private bool bHandlingChangeEvent = false;
private void txtLicense_TextChanged(object sender, EventArgs e)
{
if (bHandlingChangeEvent == true)
return;
bHandlingChangeEvent = true;
string text = txtLicense.Text.Replace("-", "").Replace(" ","");
int nPos = txtLicense.SelectionStart;
if((text.Length==5||text.Length==10||text.Length==15||text.Length==20) && txtLicense.Text[txtLicense.Text.Length-1]!='-')
{
txtLicense.Text += "-";
txtLicense.SelectionStart = nPos + 1;
}
if(text.Length>=25)
{
string tmp = text.Substring(0, 25);
tmp = InsertStringAtInterval(tmp, "-", 5);
txtLicense.Text = tmp;
txtLicense.SelectionStart = nPos;
}
bHandlingChangeEvent = false;
}
虽然这是正常使用时,我的用户类型和箱内膏。我唯一的问题是,当用户试图通过按退格键或删除键从输入的键中删除字符时。
由于强制连字符插入@位置5,10,15,20,一旦用户在退格按下这些标记之一时,按上述逻辑强制连字符添加到字符串,并且用户不能超出该范围。
我试着摆弄KeyDown事件,但不能拿出任何有用的东西。有人可以帮忙吗?
我也尝试过使用MaskedTextbox,但那件事很丑陋,因为我不想让遮罩/连字符在焦点上可见,我当然不想用空格替换提示,因为它会给一些混淆当在盒子内部点击时,由于当其“假定”为空时,光标不会始终位于盒子的开始处。
会[MaskedTextBox](http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx)有帮助吗? – publicgk 2013-03-06 15:23:39
我刚刚编辑了我关于那个问题,因为我以为有人会提到它..检查我的问题的结束 – 2013-03-06 15:24:13
@DJKRAZE不知道你在瞄准什么..你能在代码中解释也许 – 2013-03-06 17:32:43