700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > winform之ip地址控件textBox

winform之ip地址控件textBox

时间:2018-04-15 18:30:38

相关推荐

winform之ip地址控件textBox

C# winform 显示编辑ip地址,无需重绘textBox或者重写textBox方法,只需要在原生textBox控件对应事件中实现对应的算法即可。

1、textBox keyUp事件

private void textBoxKeyUp(object sender, KeyEventArgs e){if (e.KeyCode == Keys.Back)return;String text = textBoxIP.Text;string[] subs = text.Split('.');bool update = false;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;}if((subs.Length == (index+1)) &&(sub.Length >= 3)){update = true;}index++;}if (update){textBoxIP.Text = "";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 = textBoxIP.Text.Length;//设置光标在末尾 }}

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)点击自动选择

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。