Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //https://stackoverflow.com/a/60781845/10216583
- using System;
- using System.Linq;
- using System.Windows.Forms;
- using System.ComponentModel;
- namespace JQSOFT
- {
- [DesignerCategory("Code")]
- class IPTextBox : TextBox
- {
- #region Constructors
- public IPTextBox() : base() { }
- #endregion
- #region Public Properties
- [Browsable(false)]
- public bool IsValidIP { get { return IsValidInput(true); } }
- #endregion
- #region Private Methods
- private bool IsValidIP4Part(string input)
- {
- int y;
- return input.Length > 1 && input.StartsWith("0") ? false
- : int.TryParse(input, out y) && y < 256;
- }
- private bool IsValidInput(bool full = false)
- {
- int y;
- var split = Text.Split('.');
- var parts = split.Where(x => int.TryParse(x, out y));
- return !Text.StartsWith(".") &&
- !Text.EndsWith("..") &&
- split.Length < 5 &&
- parts.All(x => IsValidIP4Part(x));
- }
- #endregion
- #region Base
- protected override void OnTextChanged(EventArgs e)
- {
- base.OnTextChanged(e);
- if (!IsValidInput())
- {
- SendKeys.SendWait("{BS}");
- OnInvalidInput();
- }
- }
- protected override void OnKeyPress(KeyPressEventArgs e)
- {
- base.OnKeyPress(e);
- if (!char.IsControl(e.KeyChar) &&
- !char.IsDigit(e.KeyChar) &&
- e.KeyChar != '.')
- {
- e.Handled = true;
- OnInvalidInput();
- }
- }
- #endregion
- #region Custom Events
- public event EventHandler InvalidInput;
- protected virtual void OnInvalidInput()
- {
- var h = InvalidInput;
- h?.Invoke(this, EventArgs.Empty);
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment