2010-09-14 42 views

回答

4

我想你應該處理KeyPress事件。檢查按下的按鍵是否爲G,如果是,則拒絕輸入並將A放入文本框中。嘗試這種(字符將被附加到現有文本:

private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) 
    { 
     if (e.KeyChar == 'G') 
     { 
      // Stop the character from being entered into the control 
      e.Handled = true; 
      textBox1.Text += 'A'; 
     } 
    } 
+3

相反'textBox1.Text + = 'A' 的;'我寧願'textBox1.AppendText(? 「A」);' – Oliver 2010-09-14 11:45:16

+0

@Oliver任何具體的原因? – 2010-09-14 14:24:34

+0

性能。只需在您的文本框中放入10,000個字符並讓計時器每100ms添加一個隨機字符,在第一次測試中使用'+ ='方法。 'AppendText()'的解決方案,問題是一個字符串是不可變的,所以整個字符串將從文本框中取出一個單獨的字符並且這個整個字符串將被返回給TextBox,這告訴Box扔掉它的全部內容,並採取新的,這將導致令人討厭的閃爍。 – Oliver 2010-09-15 09:14:57

15
TextBox t = new TextBox(); 
    t.KeyPress += new KeyPressEventHandler(t_KeyPress); 


    void t_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (e.KeyChar == 'G') 
      e.KeyChar = 'A'; 
    } 
+0

這更優雅:) - +1 – 2010-09-14 07:09:23

相關問題