C# winform 显示编辑ip地址,无需重绘textBox或者重写textBox方法,只需要在原生textBox控件对应事件中实现对应的算法即可。
移步升级版: TextBox IP格式化输入
1、textBox keyUp事件
private void textBoxKeyUp(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Back)||(e.KeyCode == Keys.Left)||(e.KeyCode == Keys.Right))
return;
String text = textBoxIP.Text;
string[] subs = text.Split('.');
bool update = false;
int cursor = textBoxIP.SelectionStart;
int index = 0;
foreach (var sub in subs)
{
Debug.WriteLine($"Substring: {sub}");
if(sub != String.Empty)
{
if (Convert.ToUInt16(sub) > 255)
{
subs[index] = "255";
update = true;
}
}
else
{
update = true;
}
index++;
}
if (update)
{
textBoxIP.Text = "";
cursor++;
index = 0;
foreach (var sub in subs)
{
if (sub == String.Empty)
continue;
if(index < 3)
{
textBoxIP.Text += String.Format("{0}.", sub);
}
else if (index == 3)
{
textBoxIP.Text += String.Format("{0}", sub);
}
if(index >= 4)
{
update = true;
}
index++;
}
textBoxIP.SelectionStart = cursor;
textBoxIP.SelectionLength= 0;
}
}
2、textBox click事件
private void textBoxClick(object sender, EventArgs e)
{
String text = textBoxIP.Text;
if (textBoxIP.SelectionStart >= text.Length)
return;
int offset_start = text.LastIndexOf('.', textBoxIP.SelectionStart, textBoxIP.SelectionStart);
Debug.WriteLine("offset_start:{0}", offset_start);
if (offset_start == -1)
{
textBoxIP.SelectionStart = 0;
}
else
{
textBoxIP.SelectionStart = offset_start+1;
}
int offset_end = text.IndexOf('.',textBoxIP.SelectionStart, textBoxIP.Text.Length- textBoxIP.SelectionStart);
Debug.WriteLine("offset_end:{0}", offset_end);
if(offset_end == -1)
{
textBoxIP.SelectionLength = textBoxIP.Text.Length - textBoxIP.SelectionStart;
}
else
{
textBoxIP.SelectionLength = offset_end - textBoxIP.SelectionStart;
}
}
3、实现功能
a)自动补充'.'
b)限制大于255输入
c)点击自动选择