Bonnie,
Thanks for the inspiration. It was what I needed to get started. I replaced the code in your KeyPressHandler with this:
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;
if ( char.IsControl(TheKey) )
{
if (TheKey != '\u0016')
return true;
IDataObject ClipData = Clipboard.GetDataObject();
if ((ClipData == null) || (! ClipData.GetDataPresent(DataFormats.Text)) )
{
TestText = LeftText + RightText;
}
else
{
string InsText = (string)ClipData.GetData(DataFormats.StringFormat);
foreach ( char ch in InsText.ToCharArray() )
if ( Array.IndexOf(this.AllowedChars, ch) < 0 )
return false;
TestText = LeftText + InsText + RightText;
}
}
else
{
if (Array.IndexOf(this.AllowedChars, TheKey) < 0)
return false;
if ((TheKey == '.' || TheKey == '-')
&& (LeftText.IndexOf(TheKey) >= 0 || RightText.IndexOf(TheKey) >= 0))
return false;
TestText = LeftText + TheKey + RightText;
}
if (this.m_DecimalPlaces == 0)
return true;
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.
I know some purists don't like more than one
return in a method, but I sometimes find the code easier to read with multiple returns.
The only thing that I am aware it doesn't do is validate insertions via
Shift-Ins. To do that I have to handle the
KeyDown event or override the
ProcessCmdKey method and that was a little more complicated than I had time or energy for today.
If you use the code and find any issues, please let me know. I haven't tested it for every combination of settings yet, but my brain needs a rest. I learned a lot today about keyboard input vis-a-vis the .Net framework and about control events, and I grew my C# muscles a bit and explored several blind alleys.
Thanks again,
...Jim