如何让文本框只接受 a-z 而没有其他内容?

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

我在 Windows 表单中有 4 个文本框。我想将其更改为仅接受字母 a 到 z,不接受其他字母,即使粘贴内容时也是如此。如果用户混合粘贴字母和不需要的字符,则只有字母应显示在文本框中。

我最不想拥有的是数字锁定键盘。这些数字与键盘顶部的数字行相同,但我希望它们也能屏蔽它们!

我很确定应该有一些看起来像这样的语法; var isAlpha = char.IsLetter('text'); 您需要做的就是为您的文本框实现语法,如图所示; var isAlpha = textbox.char.IsLetter('text');

在 ASCII table 中 a-z 是 97 到 122 的形式:

string str = "a string with some CAP letters and 123numbers";
void Start(){
    string result = KeepaToz(str);
    Debug.Log(result); // print "astringwithsomelettersandnumbers"
}
string KeepaToz(string input){
   StringBuilder sb = new StringBuilder();
   foreach(char c in str){
       if(c >= 97 && c<= 122){ sb.Append(c); }
   }
   return sb.ToString();
}

我想引入一个派生自 TextBox 的自定义控件,类比 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);
    }
}

使用TextChanged事件。类似于:

// Set which characters you allow here
private bool IsCharAllowed(char c)
{
    return (c >= 'a' && c <= 'z')
}    

private bool _parsingText = false;
private void textBox1_TextChanged(object sender, EventArgs e)
{
    // if we changed the text from within this event, don't do anything
    if(_parsingText) return;

    var textBox = sender as TextBox;
    if(textBox == null) return;

    // if the string contains any not allowed characters
    if(textBox.Text.Any(x => !IsCharAllowed(x))
    {        
      // make sure we don't reenter this when changing the textbox's text
      _parsingText = true;
      // create a new string with only the allowed chars
      textBox.Text = new string(textBox.Text.Where(IsCharAllowed).ToArray());         
      _parsingText = false;
    }
}

您可以将此方法分配给每个文本框 TextChanged 事件,它们将只允许它们输入 IsCharAllowed() 中的内容(无论是通过粘贴、键入、触摸屏或其他)