簡體   English   中英

如何使文本框只接受az而不是其他?

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

我在Windows窗體上有4個文本框。 我想將其更改為僅接受字母a到z的字母,而不是其他內容,即使粘貼內容也是如此。如果用戶粘貼了字母和不需要的字符混合,則只有字母應顯示在文本框中。

我想要的最后一件事是numlock pad。 這些數字與鍵盤頂部的數字行相同,但我也想讓它們阻止它們!

我很確定應該有一些看起來像的語法; var isAlpha = char.IsLetter('text'); 您需要做的就是在文本框中實現語法,如圖所示; var isAlpha = textbox.char.IsLetter('text');

在ASCII表中,az的格式為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派生的自定義控件:

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() (如果通過粘貼,通過鍵入,觸摸屏或其他方式無關緊要)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM