C# 获得按钮的焦点/使其处于活动状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13035608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Getting the focus on a button / making it active
提问by vlovystack
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)
我正在用 C# 制作一个蛇游戏,我有一个暂停和播放按钮。问题是:这些按钮位于完全相同的位置,所以我点击暂停后无法点击开始(因为它仍然处于活动状态)
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 :/
.Focus 不起作用并出现错误:/
ERROR = Error 1 Cannot assign to 'Focus' because it is a 'method group' C:\Users\Mave\Desktop\SnakeGame\Form1.cs 271 7 SnakeGame
错误 = 错误 1 无法分配给“焦点”,因为它是一个“方法组” C:\Users\Mave\Desktop\SnakeGame\Form1.cs 271 7 SnakeGame
采纳答案by Reed Copsey
Control.Focusis a method, not a property. This should be:
Control.Focus是一种方法,而不是属性。这应该是:
private void picStart_Click(object sender, EventArgs e)
{
timer1.Start();
picBreak.Visible = true;
picStart.Visible = false;
picBreak.Focus(); // Focus picBreak here?
}
回答by Miguel Angelo
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 Focusis a method, and you are trying to use it as a property.
在您的代码中,您试图将焦点放在您在上一行中设置为不可见的控件上……此外,编译器告诉您这Focus是一种方法,而您正试图将其用作属性。
I'd do this in a different way:
我会以不同的方式做到这一点:
Just one button called btnStartPauseResume... and in the click event:
只有一个按钮叫做btnStartPauseResume... 并且在点击事件中:
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
}
}

