JQSOFT

IPTextBox

Mar 24th, 2020
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.07 KB | None | 0 0
  1. //https://stackoverflow.com/a/60781845/10216583
  2.  
  3. using System;
  4. using System.Linq;
  5. using System.Windows.Forms;
  6. using System.ComponentModel;
  7.  
  8. namespace JQSOFT
  9. {
  10.     [DesignerCategory("Code")]
  11.     class IPTextBox : TextBox
  12.     {
  13.         #region Constructors
  14.  
  15.         public IPTextBox() : base() { }
  16.  
  17.         #endregion
  18.  
  19.         #region Public Properties
  20.  
  21.         [Browsable(false)]
  22.         public bool IsValidIP { get { return IsValidInput(true); } }
  23.  
  24.         #endregion
  25.  
  26.         #region Private Methods
  27.  
  28.         private bool IsValidIP4Part(string input)
  29.         {
  30.             int y;
  31.             return input.Length > 1 && input.StartsWith("0") ? false
  32.                 : int.TryParse(input, out y) && y < 256;
  33.         }
  34.  
  35.         private bool IsValidInput(bool full = false)
  36.         {
  37.             int y;
  38.             var split = Text.Split('.');
  39.             var parts = split.Where(x => int.TryParse(x, out y));
  40.  
  41.             return !Text.StartsWith(".") &&
  42.                 !Text.EndsWith("..") &&
  43.                 split.Length < 5 &&
  44.                 parts.All(x => IsValidIP4Part(x));
  45.         }
  46.  
  47.         #endregion
  48.  
  49.         #region Base
  50.  
  51.         protected override void OnTextChanged(EventArgs e)
  52.         {
  53.             base.OnTextChanged(e);
  54.  
  55.             if (!IsValidInput())
  56.             {
  57.                 SendKeys.SendWait("{BS}");
  58.                 OnInvalidInput();
  59.             }            
  60.         }
  61.  
  62.         protected override void OnKeyPress(KeyPressEventArgs e)
  63.         {
  64.             base.OnKeyPress(e);
  65.  
  66.             if (!char.IsControl(e.KeyChar) &&
  67.                 !char.IsDigit(e.KeyChar) &&
  68.                 e.KeyChar != '.')
  69.             {
  70.                 e.Handled = true;
  71.                 OnInvalidInput();
  72.             }                
  73.         }
  74.  
  75.         #endregion
  76.  
  77.         #region Custom Events
  78.  
  79.         public event EventHandler InvalidInput;
  80.  
  81.         protected virtual void OnInvalidInput()
  82.         {
  83.             var h = InvalidInput;
  84.             h?.Invoke(this, EventArgs.Empty);
  85.         }
  86.  
  87.         #endregion
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment