0

I have a simple problem with a code from a C# book. The code is suppose to change background color every time I click the button. The problem is it changes the color to green and instantly goes back to purple again. After clicking again, the situation and colors stay the same. I think there's a problem with Application.DeEvents() because it seems that after one iteration, parameters goes back to default. This is a book's fault obviously but I wanted to make it work, anyway. I found a question about the very same code but it was about for loop and it's not said why code can't work in the first place.

    {
        for (int c = 0; c < 254 && Visible; c++)
        {
            this.BackColor = Color.FromArgb(c, 255 - c, c);
            Application.DoEvents();
            System.Threading.Thread.Sleep(5);
        }
    }
}
3
  • 3
    Why are you looping? Are you trying to do some kind of animation of the colour? Commented Nov 4, 2017 at 18:13
  • Ya, the outcome should be changing the background color of a Form every time I click the button. Commented Nov 4, 2017 at 18:19
  • You are changing the back color for every 5 milliseconds, you will not really noticing the changes in color Commented Nov 4, 2017 at 18:20

1 Answer 1

1

254 iterations last 254 * 5 ms = 1.27 seconds. So, just after clicking you get RGB(0, 255, 0) == green. Then the loop changes the color graduallly to RGB(253, 2, 253)` == purple within 1.27 seconds. It's what your code tells it to do.

Note also that 5 ms is shorter than the monitor refresh rate at 60Hz (~ 16.7 ms).

If you want to change the color gradually manually instead of automatically, remove the loop and store c in a field (outside of the method).

private int c = 0;

private void Button1_Click(object sender, EventArgs e)
{
    this.BackColor = Color.FromArgb(c, 255 - c, c);
    c = (c + 1) % 256; // 256 % 256 == 0. % = modulo operator.
}

Now, the color changes slightly at every click.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok I get it, thanks. I also figured out the loop way, the author says it's an example and I shouldn't use DoEvents() in real example, it's just educational one. But I added another for loop where c goes down and after clicking the button it goes green->purple->green and stops and that's probably what the example is about. Thanks for the help, appreciate it.
Yeah, and because it's just educational one, you can tell students to do things they shouldn't do :-). In a real world example, you should use a timer instead of a loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.