简体   繁体   中英

private method issue c# (change color from tool strip menu item)

I have a logic issue on a tic tac toe game. I want to add a new feature. When I click on "Yellow Color" in the menu, I want my red cross to become yellow when the cursor enters the button.

I can't see the variable "b" from the following method, so I was wondering how should I do that.

private void yellowColorToolStripMenuItem_Click(object sender, EventArgs e)
{
    b.ForeColor= System.Drawing.Color.Yellow;
} //syntax error

private void button_enter(object sender, EventArgs e)
{
    Button b = (Button)sender;
    if (b.Enabled)
    {
        if (turn)
        {
            b.ForeColor = System.Drawing.Color.Red;
            b.Text = "X";
        }
        else
        {
            b.ForeColor = System.Drawing.Color.Blue;
            b.Text = "O";
        }
    }
}

I couldn't find anything on the net

You've declared a local variable in the button_enter method. That variable is only available within the method. If you want that variable to be part of the start of the instance, you need to make it an instance variable, declared outside any method.

However, it sounds like the real state that you want isn't another button reference - it's "the colour to set the foreground to when the cursor enters the button". So you might have:

private Color entryColor;

private void yellowColorToolStripMenuItem_Click(object sender, EventArgs e)
{
    entryColor = Color.Yellow;
}

private void button_enter(object sender, EventArgs e)
{
    Button b = (Button) sender;
    if (b.Enabled)
    {
        if (turn)
        {
            b.ForeColor = entryColor;
            b.Text = "X";
        }
        else
        {
            b.ForeColor = Color.Blue;
            b.Text = "O";
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM