简体   繁体   中英

C# Getting the focus on a button / making it active

I'm making a snake game in C# and I have a pause and play button. Problem is: these buttons are in the exact same position, so I can't click start after I have clicked pause (because it's still active)

private void picBreak_Click(object sender, EventArgs e)
{
  timer1.Stop();
  picBreak.Visible = false;
  picStart.Visible = true;
}

private void picStart_Click(object sender, EventArgs e)
{
  timer1.Start();
  picBreak.Visible = true;
  picStart.Visible = false;
  picStart.Focus = true;
}

The .Focus does not work and gives an error :/

ERROR = Error 1 Cannot assign to 'Focus' because it is a 'method group' C:\\Users\\Mave\\Desktop\\SnakeGame\\Form1.cs 271 7 SnakeGame

Control.Focus is a method, not a property. This should be:

private void picStart_Click(object sender, EventArgs e)
{
  timer1.Start();
  picBreak.Visible = true;
  picStart.Visible = false;
  picBreak.Focus(); // Focus picBreak here?
}

In your code, you are trying to give focus to a control that you made invisible in the previous line... also, the compiler is telling you that Focus is a method, and you are trying to use it as a property.

I'd do this in a different way:

Just one button called btnStartPauseResume ... and in the click event:

private void btnStartPauseResume_Click(object sender, EventArgs e)
{
    if (btnStartPause.Text == "start")
    {
       btnStartPause.Text == "pause";

       // code to start the game
    }
    else if (btnStartPause.Text == "pause")
    {
       btnStartPause.Text == "resume";

       // code to pause the game
    }
    else if (btnStartPause.Text == "resume")
    {
       btnStartPause.Text == "pause";

       // code to resume the game
    }
}

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