Search code examples
c#winformstextboxmasking

How to make a textbox only accep a-z and nothing else?


I have 4 text boxes at a Windows form. I would like to change it to only accept letters the letters a to z and nothing else, even when content is pasted in. If the user pastes in a mix of letters and unwanted characters, only the letters should show up in the textbox.

The last thing that I would like to have is the numlock pad. Those numbers are the same as the number row at a top of a keyboard, but I want to them to block them too!


Solution

  • I'd suppose to introduce a custom control derived from TextBox, by analogy with this post:

    public class LettersTextBox : TextBox
    {
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
    
            string c = e.KeyChar.ToString();
    
            if (e.KeyChar >= 'a' && e.KeyChar <= 'z' || char.IsControl(e.KeyChar))
                return;
    
            e.Handled = true;
        }
    
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            const int WM_PASTE = 0x0302;
            if (m.Msg == WM_PASTE)
            {
                string text = Clipboard.GetText();
                if (string.IsNullOrEmpty(text))
                    return;
    
                if (text.Any(c => c < 'a' || c > 'z'))
                {
                    if (text.Any(c => c >= 'a' || c <= 'z'))
                        SelectedText = new string(text.Where(c => c >= 'a' && c <= 'z').ToArray());
                    return;
                }
            }
            base.WndProc(ref m);
        }
    }