winform之ip地址控件textBox

本文介绍如何在C# WinForm应用中创建一个编辑IP地址的textBox控件,无需重绘或自定义控件。主要功能包括自动补全'.',限制输入数值不超过255,以及点击自动选择IP段。通过处理textBox的KeyUp和Click事件,实现了这些功能。
摘要由CSDN通过智能技术生成

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值