Why not simply use the (Textbox.Text.Length - Textbox.SelectionLength) calculation to determine if a Keypress is to be allowed or not ?
For instance, --- const int maxLen = 6; int textLen = Textbox1.Text.Length; int selLen = Textbox1.SelectionLength; if (textLen - selLen + 1 > maxLen) // Suppress KeyPress. --- You may have to refine that logic since I haven't tested it. You shouldn't have to tell the difference between a keystroke that replaces a selection and one that doesn't. On Sep 26, 5:50 pm, Tom <[email protected]> wrote: > I am using the KeyDown event to edit a text box as the user types. If > the user types a key I don't like I use the > KeyEventArgs.SuppressKeyPress property to suppress that key stroke. > > One of the edits is that the maximum length of input is 6 characters. > I can have code that says if the TextBox.Text.Length property is 6 > then suppress further keystrokes. The problem with that is what if > the user typed "1234546", then uses the mouse to highlight the "3" and > wants to change it to "9"? I wouldn't want to suppress that key > stroke because it doesn't cause the length to exceed 6 positions. I > know I have the MaskedTextBox available, but I don't want to use it. > > In summary, how do I tell the difference between a keystroke at the > end of the string versus a keystroke that replaces a character in the > string? > > Thank you
