private void OnIpTextChange() { string ip = IpBox.Textbox.Text; int amountOfPeriods = ip.Count(x => x == '.'); if (ip.Any(ch => ch != '.' && !char.IsDigit(ch)) || ip.Split('.').Any(x => x.Length > 3) || amountOfPeriods > 3 || ip.Contains("..") || ip.StartsWith('.')) { RevertTextBox(); return; } void RevertTextBox() { IpBox.Textbox.Text = IpTextBefore; IpBox.Textbox.SelectionStart = CaretPositionBefore; IpBox.Textbox.SelectionLength = 0; } IpTextBefore = ip; GetCaretPos(out Point p); // Returns +9 for each number and +4 for a period. We're finding the amount of periods and adding 6 for each of them, so // that they act like a number, in order to be able to count caret position properly. Yeah, ugly. CaretPositionBefore = (p.X + amountOfPeriods * 6) / 9; bool ipCorrect = IpUtils.IsIpCorrect(ip); AddButton.Cursor = ipCorrect ? AddButtonProps.AllowCursor : AddButtonProps.DisallowCursor; IpBox.BorderColor = string.IsNullOrEmpty(ip) || ipCorrect ? IpBoxProps.NeutralColor : IpBoxProps.IncorrectColor; }