Ziz*_*o47 6 c# loops boolean button wait
我想让程序在继续之前等待按下按钮,我尝试创建一个while循环并让它循环直到单击按钮并将bool设置为true以使while循环结束,这使它崩溃
while (!Redpress)
{
//I'd like the wait here
}
Redpress = false;
Run Code Online (Sandbox Code Playgroud)
只要程序在将"Redpress"设置为false之前等待按下按钮就没有关系到那里也没关系...任何想法?
使用事件 - 这是他们的设计目标.
在Button_Click事件处理程序中调用代码时,您不需要为此使用布尔变量:
private void Button_Click(object sender, EventArgs e)
{
// The code you need to execute when the button is pressed
}
Run Code Online (Sandbox Code Playgroud)
正如@trickdev所指出的,您需要订阅此事件,但如果您在Visual Studio中使用"事件"窗口,它将为您添加必要的代码 - 包括空处理程序.
通过事件驱动程序,您总是在等待下一个"事情"发生.因此,在您的情况下(如果我已正确理解您的应用程序),当您启动程序时,它应该只是告诉第一个按钮闪烁"N"次.如果将其写为事件,则代码完成后应用程序将返回等待状态.
然后在按钮单击事件处理程序中 - 您可以将所有按钮订阅到同一事件 - 您可以检查是否按下了正确的按钮,然后告诉下一个按钮闪烁.如果按下了错误的按钮,则显示合适的消息.
所以在伪代码中你有:
public class Form
{
Initialise()
{
this.Loaded += FormLoaded;
}
private void FormLoaded(object sender, EventArgs e)
{
// pick a button
pickedButton.Flash();
}
private void Button_Click(object sender, EventArgs e)
{
if (sender == pickedButton)
{
pickedButton = pickButton();
}
else
{
message = "Sorry wrong button, try again";
}
pickedButton.Flash();
}
}
public class Button
{
public void Flash()
{
// loop N times turning button on/off
}
}
Run Code Online (Sandbox Code Playgroud)