如何在C#中的textbox1_TextChange事件中分离用户触发和程序触发

时间:2013-07-16 06:30:25

标签: c#

我正在使用C#.net 4.0 VS 2010。

我正在尝试创建一个模拟Facebook行为的文本框,特别是文本框中有“+ Enter Message”并且颜色为灰色。我还交换了tabindex,因此默认情况下没有选中文本框(破坏幻觉)。

据说当用户点击文本框时,textbox.text消失,然后Forecolor重新变为黑色。

发生的事情是,它检测到我在Form_Load上的程序更改并在事件显示之前运行事件。

如何在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 = "";
        }
    }

2 个答案:

答案 0 :(得分: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事件订阅之前完成初始化。

答案 1 :(得分:1)

您可以先删除句柄来压制事件

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

然后再添加它,或者只是在form_load

中更改文本后添加事件
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);