سؤال

I have a winform application that has a set of RichTextBoxes. I want to change the text color into Red when the text box contents change

and I have a button, when this button is clicked, the text color is reset to its default color.

The problem is, when I use the event handler (TextChanged) to detect if change in Contents has occured, it is also triggered when the color is reset.

to be more clear I will give an example:

1- the contents of the text box change 2- the event handler is triggered and text color is changed to Red. 3- the button is clicked, then the text is black again 4- when the text color changes, the event handler is triggered again and color is changed to Red.

so, The color seems to be always Red even if the button is clicked.

how Can I handle this problem? I need to detect only the change in contents, not in color

here is a piece from the code:

private void AHReg_TextChanged(object sender, EventArgs e)
{
    AHReg.ForeColor = Color.Red;
}

private void RunButton_Click(object sender, EventArgs e)
{
    resetControlColor(); //this function sets the text color to Black
}
هل كانت مفيدة؟

المحلول

There's a few ways to skin this cat. You can track the actual text and look for mismatches, or handle the ForeColorChanged event, but the simplest way I think in your case is to just "turn off" the event subscription when you do your reset.

For example, in your RunButton_Click method:

private void RunButton_Click(object sender, EventArgs e)
{
    AHReg.TextChanged -= AHReg_TextChanged;
    resetControlColor(); //this function sets the text color to Black
    AHReg.TextChanged += AHReg_TextChanged;
}

If you need that event to be active in your resetControlColor() function then you'll need to come at this at a different angle, but that's the simplest away to approach it.

نصائح أخرى

you can add a boolean variable called NeedToBeChangedin your class.

private bool NeedToBeChanged = true;

private void RunButton_Click(object sender, EventArgs e)
    {
        NeedToBeChanged =false;
        resetControlColor(); //this function sets the text color to Black
        NeedToBeChanged =true;
    }
private void AHReg_TextChanged(object sender, EventArgs e)
    {
            if(NeedToBeChanged)
            AHReg.ForeColor = Color.Red;
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top