2011-08-30 75 views
1

我的用戶可以在組合框中輸入一些文本,但我希望這個文本自動以大寫字母顯示(就像用戶有大寫鎖定一樣)。任何想法如何做到這一點?c#窗體大寫字母

回答

6

您將需要處理KeyPress事件。

private void ComboBox_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (e.KeyChar >= 'a' && e.KeyChar <= 'z') 
     e.KeyChar -= (char)32; 
} 

32只是小寫字母和大寫字母之間ASCII值的區別。

+0

我覺得KeyChar是隻讀的,對於ComboBox ... –

+0

@Edwin,沒有 - KeyPressEventArgs既有getter和setter。 – Marlon

+0

設置KeyChar從.NET 2.0開始有效 – Patrik

1

您可以註冊到TextChanged事件並將文本轉換爲大寫。

private void combobox_TextChanged(object sender, EventArgs e) 
{ 
    string upper = combobox.Text.ToUpper(); 
    if(upper != combobox.Text) 
     combobox.Text = upper; 
} 
1

另一個例子

private void TextBox_Validated(object sender, EventArgs e) 
    { 
     this.TextBox.Text = this.TextBox.Text.ToUpper(); 
    } 

問候

0

這是我如何處理它,它比簡單地更換整個文本更加平滑變化。

private void ComboBox_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (Char.IsLetter(e.KeyChar)) 
    { 
    int p = this.SelectionStart; 
    this.Text = this.Text.Insert(this.SelectionStart, Char.ToUpper(e.KeyChar).ToString()); 
    this.SelectionStart = p + 1; 
    } 
}