The question is simple: how to do it?
I’ve a couple of MaskedTextboxes which are filled by some indirect user actions (so not by typing in values directly). The text within the textboxes is colored red when the input is being rejected by the mask. Fine so far.
However, I don’t want the end-user to be able to edit the boxes directly. So, I added the following code:
private void HandleMaskedTextBoxKeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void HandleMaskedTextBoxKeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
e.SuppressKeyPress = true;
}
And while most characters are handled, the backspace and delete keys aren’t: text disappears when pressing those keys. How can those keys be handled, too?
(Another option would be to set the readonly property of the boxes to true, but then the text doesn’t get colored red anymore when input is rejected. I tried to force the red color in the MaskInputRejected event, but this didn’t work out, either.)
I think it’s a good idea to set the
MaskedTextBox‘sReadOnlyproperty totrue. But instead of handling theMaskInputRejectedevent, you should use theTypeValidationCompletedevent like this:Since I guess you’re modifying the value of the
MaskedTextBoxby code, you’ll have to also handle theTextChangedevent to trigger a validation like this:Finally (and this is key), since the
MaskedTextBoxwill be read only, you’ll want to set theBackColorandForeColorproperties back toColor.WhiteandColor.Blackrespectively, but you’ll have to do it in code, in the constructor of the form for instance…If you have a lot of them, I suggest you create a new control that inherits from
MasketTextBoxand override those values.