Home > front end >  Disable some letter keys in MaskedTextBox
Disable some letter keys in MaskedTextBox

Time:05-24

I want a MaskedTextBox that is made for hex color codes, such as "#73E57E" for example. This means that only 0-9 and A-F shall be allowed. My mask is ">AAAAAA". What I can't figure out is how do disable some letters. So that when I hit the "G" key, nothing shall happen. Exectly as if I hit the " " key for example.

This is what I have tested so far:

        private void mskBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.G)
            {
                e.Handled = true;
            }
        }
        private void mskBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.H)
            {
                e.Handled = true;
            }
        }

CodePudding user response:

Close! Try suppressing the KeyPress also. Here's one approach:

private void mskbox_OnKeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyData)
    {
        case Keys.D0:
        case Keys.D1:
        case Keys.D2:
        case Keys.D3:
        case Keys.D4:
        case Keys.D5:
        case Keys.D6:
        case Keys.D7:
        case Keys.D8:
        case Keys.D9:
        case Keys.A:
        case Keys.B:
        case Keys.C:
        case Keys.D:
        case Keys.E:
        case Keys.F:
        case Keys.Shift | Keys.A:
        case Keys.Shift | Keys.B:
        case Keys.Shift | Keys.C:
        case Keys.Shift | Keys.D:
        case Keys.Shift | Keys.E:
        case Keys.Shift | Keys.F:
                break;
        default:
            e.Handled = true;
            e.SuppressKeyPress = true;
            break;
    }
}
  • Related