winform textBox IP格式化输入,效果如下:
代码如下:
namespace WinFormsAppTest
{public partial class Form1 : Form{public Form1(){InitializeComponent();textBoxIP.Text = String.Format("{0,3}.{1,3}.{2,3}.{3,3}", 0, 0, 0, 0);textBoxIP.SelectionStart = textBoxIP.Text.Length;textBoxIP.SelectionLength = 0;}private int getCursorIndex(TextBox tb){String text = tb.Text;String[] subs = text.Split('.');int cursor = tb.SelectionStart;Debug.Print($"cursor={cursor}");int cur_index = 0;int index = 0;int of = 0;foreach (var item in subs){of = text.IndexOf('.', of + 1);Debug.Print($"of={of}");if ((of >= cursor) || (of == -1)){cur_index = index;break;}index++;}Debug.Print($"cur_index={cur_index}");return cur_index;}private void setCursorIndex(TextBox tb, int index){String text = tb.Text;String[] subs = text.Split('.');int set_pos = 0;int j = 0;int of = 0;foreach (var item in subs){of = text.IndexOf('.', of + 1);if (of == -1){of = text.Length;}if (j == index){set_pos = of;break;}j++;}Debug.Print($"set_pos={set_pos}");textBoxIP.SelectionStart = set_pos;textBoxIP.SelectionLength = 0;}private void selectIndex(TextBox tb, int index){String text = tb.Text;String[] subs = text.Split('.');int start = 0,end=0;int j = 0;int of = 0;foreach (var item in subs){of = text.IndexOf('.', of + 1);if (of == -1){of = text.Length;}if (j == index){end = of;break;}j++;}start = end -3;Debug.Print($"start={start}");textBoxIP.SelectionStart = start;textBoxIP.SelectionLength = 3;}private void onClick(object sender, EventArgs e){int cur_index = getCursorIndex(textBoxIP);Debug.Print($"cur_index={cur_index}");selectIndex(textBoxIP, cur_index);}private void onTextChanged(object sender, EventArgs e){String text = textBoxIP.Text;string[] subs = text.Split('.');int cur_index = getCursorIndex(textBoxIP);Debug.Print($"cur_index={cur_index}");int index = 0;int of = 0;index = 0;foreach (var item in subs){String temp = item.Replace(" ", "");if(temp.Length != 1){temp = temp.TrimStart('0');}if (temp.Length != 0){int val = Convert.ToUInt16(temp);Debug.Print($"val={val}");if (val > 255){temp = "255";}}subs[index] = temp;index++;}{text = textBoxIP.Text = String.Format("{0,3}.{1,3}.{2,3}.{3,3}", subs[0].Replace(" ", ""), subs[1].Replace(" ", ""), subs[2].Replace(" ", ""), subs[3].Replace(" ", ""));subs = text.Split('.');setCursorIndex(textBoxIP, cur_index);if ((subs[cur_index].Trim().Length==3) && (cur_index < 3)){selectIndex(textBoxIP, cur_index+1);}}}private void onKeyPress(object sender, KeyPressEventArgs e){if (e.KeyChar != '\b' && !Char.IsDigit(e.KeyChar)){e.Handled = true;}}}
}