有關TextBox中輸入字元控制的一種解決辦法

來源:互聯網
上載者:User
解決|控制 我們知道,在C#中,TextBox控制項對輸入字元的控制有keypress、keyup、和keydown事件來使用,但大家也看到了,這幾個事件對輸入字元的控制都有一定的缺陷,如果,你使用中文IME,那麼很多原來你不希望輸入的字元也可以輸入進去。這幾天做程式的時候,就碰到了這個問題,我的解決思路很簡單,既然這三個事件不再起作用,那麼我就使用了TextBox控制項中時刻能發生的TextChanged事件,以期望在這個事件中作些東西,以達到控制字元的目的。廢話就不多說了,我將控制輸入字元為數位代碼粘貼出來,希望大家多指正,如果能對你有益的話,我就更happy了。


private System.Windows.Forms.TextBox textBox1;
private string text;
public Form1()
{
text = textBox1.Text;
}
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
int len = text.Length;
if(len < textBox1.Text.Length)
{
int index = textBox1.Text.IndexOf(text);
char c = (textBox1.Text.Remove(index,text.Length))[0];
if(c.CompareTo('0') < 0||c.CompareTo('9') >0)
{
textBox1.Text = text;
textBox1.SelectionStart = text.Length;
}
}
text = textBox1.Text;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.