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



我正在创建一个新应用程序,我需要在运行时使用代码编辑文本框。但是,有一个 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 */
}

根据@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;
}
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 */
    }
}

最新更新