0
votes

I've recently started to learn c#, and I started off by making a simple tic-tac-toe game, using labels and forms.

When I click on a label I want it to change background color and Foreground color.

Here is my code;

        public void LabelClick(Label lbl, int i)
    {
        if (strCurrPlayer == strPlayer1)
        {
            liP1Squares.Add(i);
            lbl.BackColor = System.Drawing.Color.Black;
            lbl.ForeColor = System.Drawing.Color.White;
            lbl.Text = "X";
        }
        else
        {
            //Player2
            liP2Squares.Add(i);
            lbl.BackColor = System.Drawing.Color.White;
            lbl.ForeColor = System.Drawing.Color.Black;
            lbl.Text = "O";
        }
        lbl.Enabled = false;
        SwapPlayer();
    }

However, when it's called, it sets the background color correctly, but the foregorund, i.e. text, changes from the red, (default) to black for player 1 instead of White, and Light Grey for player 2, instead of Black.

I was wondering if there are any fields within Label or Forms that change text color by default when the background color is changed. If not, what else could be making this change?

Any help would be appreciated.

2
Have you tried NOT to disable the field, i.e. leave out lbl.Enabled = false?bash.d
That works, but I would quite like the labels to be disabled once they've been click. Is there any other functionality that would achieve the same thing? lbl.Clickable = false for example?Alex
Please read my answer for a suggestion (which is very usable and common, too).bash.d

2 Answers

1
votes

After you set your items on the label, you are disabling it by

lbl.Enabled = false;

This then causes the label to use the disabled-theme from Windows.

In order to change this behavior, you should turn to using events instead of direct methods.

Every label offers a Click-event that you can use to call a method once the label was clicked.
You can then remove the event-handler from Label.Click and you don't need to disable it.

See MSDN to learn about Control.Click-EventHandler

1
votes

remove lbl.Enabled = false; to see the changes

after you dissable control it will set the label background color to SystemColors.Control and foreground color to SystemColors.GrayText