IP-Address TextBox

http://www.codeproject.com/Articles/4693/IP-Address-TextBox

可以下载试用效果。个人感觉功能很强大,但输入时让人不太舒服。可以参考。

ntroduction

Problem was, I didn‘t find a solution to edit an IP address like in Windows network environment, for C#. Although there are some controls for masked edit fields, I wanted to write my own, and if so I wanted it to behave like the controls from MFC library or Windows network environment and maybe a little more.

Problems to solve

The heaviest problem at writing the control was to catch the inputs of backspace and delete keys, to delete characters from the input field. I tried a lot with overridden event handlers, OnKeyDown and OnKeyUp but it didn‘t work like it should.

Then I remembered that another developer had overridden the PreProsessMessage method to catch keyboard inputs and handle it in own ways. So I implemented an override for PreProcessMessage to handle all the backspaces and delete key presses and used OnKeyUpOnKeyPress and OnKeyDown to handle the inputs of dots and slashes and set the input cursor to the right position.

OnKeyDown event



/// <summary>
/// Override standard KeyDownEventHandler
/// Catches Inputs of "." and "/" to jump to next positions
/// </summary>
/// <param name="e">KeyEventArgument</param>

protected override void OnKeyDown(KeyEventArgs e)
{
   //Zeichen an die richtige stelle schreiben
   int iPos = this.SelectionStart;
   char[] cText = this.Text.ToCharArray();
   if(e.Modifiers == Keys.None)
   {
       if((char.IsLetterOrDigit(Convert.ToChar(e.KeyValue)) ||
          e.KeyCode == Keys.NumPad0)//Numpad0=96 --> `
          && iPos < this.TextLength)
       {
           if(cText[iPos] == ‘.‘ || cText[iPos] == ‘:‘
                            || cText[iPos] == ‘/‘)
               iPos+=1;
           this.SelectionStart = iPos;
           if(this.OverWriteMode)
           {
               if(cText[iPos] != ‘ ‘)
               this.SelectionLength = 1;
           }
           else
           {
                if(iPos < this.TextLength)
                   if(cText[iPos] == ‘ ‘)
                       this.SelectionLength = 1;
           }
       }
   }
   base.OnKeyDown (e);
}

 

OnKeyUp event

/// <summary>
/// Override standard KeyUpEventHandler
/// Catches Inputs of "." and "/" to jump to next positions
/// </summary>
/// <param name="e">KeyEventArgument</param>

protected override void OnKeyUp(KeyEventArgs e)
{
     //Zeichen an die richtige stelle schreiben
     int iPos = this.SelectionStart;
     char[] cText = this.Text.ToCharArray();

     //Cursor hintern Punkt setzen
     if((char.IsLetterOrDigit(Convert.ToChar(e.KeyValue)) ||
             e.KeyCode == Keys.NumPad0)//Numpad0=96 --> `
               && iPos < this.TextLength)
     {
          if(cText[iPos] == ‘.‘ || cText[iPos] == ‘:‘
                               || cText[iPos] == ‘/‘)
            iPos+=1;
          this.SelectionStart = iPos;
     }
     base.OnKeyUp (e);
}

OnKeyPress event

/// <summary>
/// Override standard KeyPressEventHandler
/// Catches Inputs of "." and "/" to jump to next positions
/// </summary>
/// <param name="e">KeyPressEventArgument</param>

protected override void OnKeyPress(KeyPressEventArgs e)
{
    //Zulassige Zeichen
    if(char.IsControl(e.KeyChar) ||
         m_regexValidNumbers.IsMatch(e.KeyChar.ToString()))
    {
         e.Handled = false;
    }
    else
    {
         switch(e.KeyChar)
         {
              case ‘/‘:
                 this.JumpToSlash();
                  break;
              case ‘.‘:
                  this.JumpToNextDot();
                  break;
              default:
                  break;
         }
         e.Handled = true;
    }
    base.OnKeyPress(e);
}

PreProcessMessage

/// <summary>
/// Override standard PreProcessMessage
/// Catches Inputs of BackSpace and Deletes
/// </summary>
/// <param name="msg">PreProcessMessage</param>

public override bool PreProcessMessage(ref Message msg)
{
    if (msg.Msg == WM_KEYDOWN)
    {
        Keys keyData = ((Keys) (int) msg.WParam) |ModifierKeys;
        Keys keyCode = ((Keys) (int) msg.WParam);

        int iPos = this.SelectionStart;
        char[] cText = this.Text.ToCharArray();
        switch(keyCode)
        {
            case Keys.Delete:
                if(iPos < this.TextLength)
                {
                    while(cText[iPos] == ‘.‘ ||
                       cText[iPos] == ‘:‘ ||
                       cText[iPos] == ‘/‘)
                    {
                        if((iPos+=1) >= cText.Length)
                            break;
                    }
                    if(iPos < this.TextLength)
                    {
                        base.Text = this.Text.Substring(0,iPos) +
                                " " + this.Text.Substring(iPos+1);
                        this.SelectionStart = iPos+1;
                    }
                    else
                        this.SelectionStart = this.TextLength-1;
                }
                   return true;
            case Keys.Back:
                if(iPos > 0)
                {
                    while(cText[iPos-1] == ‘.‘ ||
                        cText[iPos-1] == ‘:‘ ||
                        cText[iPos-1] == ‘/‘)
                    {
                        if((iPos-=1)<=0)
                            break;
                    }
                    if(iPos>0)
                    {
                        base.Text = this.Text.Substring(0,iPos-1)
                                    + " " + this.Text.Substring(iPos);
                        this.SelectionStart = iPos-1;
                    }
                    else
                        this.SelectionStart = 0;
                }
                return true;
            default:
                break;
        }
    }
    return base.PreProcessMessage (ref msg);
}

Another problem was the input of numbers via the numpad. Especially the 0 key was not recognized, because it‘s char value is neither a letter nor a digit, so I had to ask for Keys.NumPad0 hard coded.

Hide   Copy Code

if((char.IsLetterOrDigit(Convert.ToChar(e.KeyValue)) ||
    e.KeyCode == Keys.NumPad0)//Numpad0=96 --> `
    iPos < this.TextLength)
{[...]}

At least...

...I have a control that looks like a TextBox with dots, where I can input numbers, type dots to jump to next IP parts, and get its contents via the Text property.

Using the code

Include the IPAddressTextBox.cs in your project. Set a TextBox in your form or user control and clear its contents. Change the type of this TextBox from System.Windows.Forms.TextBox to rj2_cs.IPAddressTextBox in code editor. Then you can change the properties of the IP textbox like you want.

时间: 2024-10-04 23:26:36

IP-Address TextBox的相关文章

在windows下运行docker的问题【Error getting IP address: ***】

环境配置系统:windows 10docker:Docker Toolbox https://www.docker.com/products/docker-toolbox 问题描述windows下安装完Docker Toolbox后运行Docker Quickstart Terminal可能会看到如下错误 Creating Machine default... Running pre-create checks... Creating machine... Error creating mach

Java Regex match IP address

Reference: [1] https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/ import java.util.regex.Matcher; import java.util.regex.Pattern; public class IPAddressValidator{ private Pattern pattern; private Matcher ma

router 分配ip address(dhcp)和dhcp中继

路由器的主要功能是网络寻址,有时候也需要用来分配ip地址.但用路由器分配地址又会加大路由器的负载,所以,有的时候我们可以把分配地址的工作交给一台PC. 1.使用router分配ip address: Router>en Router#conf t Enter configuration commands, one per line.  End with CNTL/Z. Router(config)#int vlan 1 Router(config-if)#ip dhcp pool vlan1  

poj2105 IP Address(简单题)

题目链接:http://poj.org/problem?id=2105 Description Suppose you are reading byte streams from any device, representing IP addresses. Your task is to convert a 32 characters long sequence of '1s' and '0s' (bits) to a dotted decimal format. A dotted decima

Debian static ip address

1 // /etc/network/interfaces 2 auto eth0 3 iface eth0 inet static 4 address <Your ip address> 5 netmask <Your netmask> 6 gateway <Your gateway address> 7 broadcast <Your broadcast address> 8 9 // /etc/resolv.conf 10 nameserver <

If application data needs to be sent to IP address xx.xx.xx.xx, how does it work in underneath network?

This is to illustrate the communication between two separate machines which don't have a direct physical connection. Application data is generated and passed to layer 3 (network layer) which wrapps up the data with the destination IP address. Then ha

Bringing up interface eth0: Determining if ip address 10.109.67.81 is already in use for device eth0...

重启网卡出现提示: Bringing up interface eth0:  Determining if ip address 10.109.67.81 is already in use for device eth0...                                                            [  OK  ] Bringing up interface eth1:  Determining if ip address 10.109.67.83

oracle 11g RAC安装节点二执行结果错误CRS-5005: IP Address: 192.168.1.24 is already in use in the network

[[email protected] ~]# /u01/app/oraInventory/orainstRoot.sh Changing permissions of /u01/app/oraInventory. Adding read,write permissions for group. Removing read,write,execute permissions for world. Changing groupname of /u01/app/oraInventory to oins

Linux下network提示Determining if ip address

[[email protected] NetworkManager]# service network restart正在关闭接口 eth0: [确定]关闭环回接口: [确定]弹出环回接口: [确定]弹出界面 eth0: Determining if ip address 192.168.8.102 is already in use for device eth0... vi /etc/sysconfig/network-scripts/ifcfg-eth0 添加   ARPCHECK=no

Linux Force DHCP Client (dhclient) to Renew IP Address

http://www.cyberciti.biz/faq/howto-linux-renew-dhcp-client-ip-address/‘m using Ubuntu Linux. How to force Linux to reacquire a new IP address from the DHCP server? What is the command in Linux equivalent to Windows’ “ipconfig /renew” command? You nee