2013-07-16 37 views
0

我使用C#.net 4.0 VS 2010我怎麼能分出用戶觸發,並計劃在C#觸發textbox1_TextChange事件

我試圖讓模仿Facebook的行爲的文本框,特別是有「 +輸入消息「,並顯示爲灰色。我也換了tabindex,所以默認情況下文本框沒有被選中(破壞幻覺)。

假設當用戶點擊文本框時,textbox.text消失,然後Forecolor返回黑色。

會發生什麼事情,它檢測到我放在Form_Load上的程序更改,並在顯示之前運行Event。

我如何分開用戶觸發和程序觸發textbox1_TextChange事件。

這裏是我的代碼:

public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    {   
     //facebook illusion 
     this.textBox1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC"); 
     this.textBox1.Text = "+Enter Message"; 

    } 

    //when the user clicks on the textbox 
    private void textBox1_TextChanged(object sender, EventArgs e) 
    {   
     if (this.textBox1.Text.Trim() == "+Enter Message") 
     { 
      this.textBox1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#000000"); 
      this.textBox1.Text = ""; 
     } 
    } 

僅供參考這是最後的工作代碼-------------

private void Form1_Load(object sender, EventArgs e) 
    {   
     //facebook illusion 
     this.textBox1.TextChanged -= new System.EventHandler(this.textBox1_TextChanged); 
     this.textBox1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC"); 
     this.textBox1.Text = "+Enter Message"; 
     this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); 
     this.textBox1.Click += new System.EventHandler(this.textBox1_Click); 
    } 

    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     if (this.textBox1.Text.Trim() == "+Enter Message") 
     { 
      this.textBox1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#000000"); 
      this.textBox1.Text = ""; 
     } 
    } 

    private void textBox1_Click(object sender, EventArgs e) 
    { 
     if (this.textBox1.Text.Trim() == "+Enter Message") 
     { 
      this.textBox1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#000000"); 
      this.textBox1.Text = ""; 
     } 
    } 

回答

1

您可以通過刪除手柄第一

this.textBox1.TextChanged -= new System.EventHandler(this.textBox1_TextChanged); 

然後重新添加或只需添加文本在事件發生後抑制的事件有笨鐘的Form_Load改變

this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); 
1

您可以訂閱的TextChanged例如:

private void Form1_Load(object sender, EventArgs e) 
{   
    //facebook illusion 
    this.textBox1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC"); 
    this.textBox1.Text = "+Enter Message"; 
    this.textBox1.TextChanged += textBox1_TextChanged; 
} 

private void textBox1_TextChanged(object sender, EventArgs e) 
{  
    this.textBox1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#000000"); 
    this.textBox1.Text = "";   
} 

並將其從設計器中刪除。或者,您可以直接在設計器中設置ForeColorText「+ Enter消息」,以這種方式在TextChanged事件訂閱之前完成初始化。

+0

它仍然給同樣的問題,先生 –

+0

你試過了哪種情況?使用您的代碼, –

+0

文字仍然消失。 –