if (! CheckKeyPress(e.KeyChar) ) { SystemSounds.Beep.Play(); e.Handled = true; return; }and added the following method:
protected bool CheckKeyPress(char TheKey) { string LeftText = this.Text.Substring(0, this.SelectionStart); string RightText = this.Text.Substring(this.SelectionStart + this.SelectionLength); string TestText; //----- Check for control keys if ( char.IsControl(TheKey) ) { //----- Pass through controls other than ctrl-v (Paste) if (TheKey != '\u0016') return true; //----- Handle Paste ctrl-v (Paste) IDataObject ClipData = Clipboard.GetDataObject(); if ((ClipData == null) || (! ClipData.GetDataPresent(DataFormats.Text)) ) { //----- Nothing to paste, but something might get deleted TestText = LeftText + RightText; } else { string InsText = (string)ClipData.GetData(DataFormats.StringFormat); //----- Check for illegitimate characters in clipboard text foreach ( char ch in InsText.ToCharArray() ) if ( Array.IndexOf(this.AllowedChars, ch) < 0 ) return false; //----- Check pasted text TestText = LeftText + InsText + RightText; } } else { //-----Discard any undesirable characters if (Array.IndexOf(this.AllowedChars, TheKey) < 0) return false; //----- Prevent duplicates of decimal point and minus sign if ((TheKey == '.' || TheKey == '-') && (LeftText.IndexOf(TheKey) >= 0 || RightText.IndexOf(TheKey) >= 0)) return false; TestText = LeftText + TheKey + RightText; } if (this.m_DecimalPlaces == 0) return true; //----- Check for too many digits on the right side of decimal point int I = TestText.IndexOf("."); if (I < 0) I = TestText.Length - 1; if (TestText.Length - I - 1 > this.m_DecimalPlaces) return false; else return true; }It checks the number of digits after the decimal. I didn't think it necessary to check the count of digits left of the decimal point, as that should be caught by the maximum value, but it would obviously be easy to add. It passes control keys through so cut, copy, paste, undo and backspace work. And just for grins I added a beep when it discards an entry.