检查C#中的TextChanged事件是否由代码或用户触发

时间:2019-06-19 16:58:15

标签: c# winforms

我正在创建一个新的应用程序,并且需要在运行时使用代码编辑TextBox。但是,有一个TextChanged事件处理程序,当代码编辑该框时会触发该事件处理程序。如何检测该框是由用户编辑还是由代码编辑?

private void TextBox_TextChanged(object sender, EventArgs e)
{
    /* some code here that must be run if the user edits the box, but not if the code edits the box */
}

private void Button_Click(object sender, EventArgs e)
{
    textBox.Text = "hello world";
    /* the TextBox_TextChanged function is fired */
}

2 个答案:

答案 0 :(得分:0)

在@elgonzo的评论之后,您基本上必须这样做:

bool byCode;    

private void TextBox_TextChanged(object sender, EventArgs e)
{
    if(byCode == true)
    {
         //textbox was changed by the code...
    }
    else
    {
         //textbox was changed by the user...
    }
}

private void Button_Click(object sender, EventArgs e)
{
    byCode = true; 
    textBox.Text = "hello world";
    byCode = false;
}

答案 1 :(得分:0)

bool automationLatch;
private void Button_Click(object sender, EventArgs e)
{
    automationLatch = true;
    textBox.Text = "hello world";
    automationLatch = false;
    /* the TextBox_TextChanged function is fired */
}
private void TextBox_TextChanged(object sender, EventArgs e)
{
    if(!automationLatch){
    /* some code here that must be run if the user edits the box, but not if the code edits the box */
    }
}